diff --git a/apps/sim/blocks/blocks/affinity.test.ts b/apps/sim/blocks/blocks/affinity.test.ts new file mode 100644 index 00000000000..51992e239ad --- /dev/null +++ b/apps/sim/blocks/blocks/affinity.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from 'vitest' +import { AffinityBlock } from '@/blocks/blocks/affinity' + +/** Runs the mapper the way an Agent tool call does: its result is spread over the merged args. */ +function toolCall(args: Record, operation: string) { + const mapParams = AffinityBlock.tools.config?.params + if (!mapParams) throw new Error('Affinity block has no params mapper') + return { ...args, ...mapParams(args, { operation }) } +} + +describe('AffinityBlock agent tool calls', () => { + it('maps block-field keys and keeps model args instead of dropping them', () => { + const result = toolCall( + { apiKey: 'key', noteEntityType: 'company', entityId: '42', limit: '10' }, + 'list_entity_notes' + ) + expect(result).toMatchObject({ entityType: 'company', entityId: '42', limit: 10 }) + expect(result.noteEntityType).toBeUndefined() + + expect( + toolCall({ apiKey: 'key', name: 'Deals', type: 'company', isPublic: true }, 'create_list') + ).toMatchObject({ name: 'Deals', type: 'company', isPublic: true }) + }) +}) diff --git a/apps/sim/blocks/blocks/affinity.ts b/apps/sim/blocks/blocks/affinity.ts index 6bc3c72ed38..8c6a160be84 100644 --- a/apps/sim/blocks/blocks/affinity.ts +++ b/apps/sim/blocks/blocks/affinity.ts @@ -2,8 +2,11 @@ import { AffinityIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' import { + isToolCall, + mapperOperation, parseOptionalBooleanInput, parseOptionalNumberInput, + toolCallArg, withSavedCredential, } from '@/blocks/utils' @@ -1337,9 +1340,13 @@ export const AffinityBlock: BlockConfig = { * omitting a key leaves the previous operation's value on the wire — an * advanced field is serialized on non-emptiness alone, even while the UI * hides it. `undefined` is what actually drops one. + * + * On a tool call the model's args arrive under the tool's own param names, + * so a tool param the selected operation does not fill from a block field + * keeps the model's value instead of being dropped. */ - params: (params) => { - const operation = String(params.operation ?? '') + params: (params, context) => { + const operation = mapperOperation(params, context) const isIn = (group: readonly string[]) => group.includes(operation) const isKeywordSearch = isIn(KEYWORD_SEARCH_OPERATIONS) @@ -1380,7 +1387,7 @@ export const AffinityBlock: BlockConfig = { else if (isKeywordSearch) ids = params.searchIds else if (isFieldValueSelection) ids = params.valueFieldIds - return { + const toolParams: Record = { apiKey: params.apiKey, entityType, type, @@ -1429,16 +1436,24 @@ export const AffinityBlock: BlockConfig = { isPublic: isCreateList ? parseOptionalBooleanInput(params.isPublic) : undefined, text: isDropdownWrite ? params.optionText : undefined, rank: isDropdownWrite - ? parseOptionalNumberInput(params.optionRank, 'Option Rank', { integer: true, min: 0 }) + ? parseOptionalNumberInput( + params.optionRank ?? toolCallArg(context, params.rank), + 'Option Rank', + { integer: true, min: 0 } + ) : undefined, color: isDropdownWrite ? params.optionColor : undefined, statusCategory: isDropdownWrite ? params.optionStatusCategory : undefined, winRate: isDropdownWrite - ? parseOptionalNumberInput(params.optionWinRate, 'Win Rate', { - integer: true, - min: 0, - max: 100, - }) + ? parseOptionalNumberInput( + params.optionWinRate ?? toolCallArg(context, params.winRate), + 'Win Rate', + { + integer: true, + min: 0, + max: 100, + } + ) : undefined, value: isIn(FIELD_VALUE_WRITE_OPERATIONS) ? params.fieldValue : undefined, updates: isIn(FIELD_BATCH_WRITE_OPERATIONS) ? params.fieldUpdates : undefined, @@ -1470,6 +1485,16 @@ export const AffinityBlock: BlockConfig = { totalCount: isIn(TOTAL_COUNT_OPERATIONS) ? parseOptionalBooleanInput(params.totalCount) : undefined, + } + + if (isToolCall(context)) { + for (const [key, value] of Object.entries(toolParams)) { + if (value === undefined) toolParams[key] = params[key] + } + } + + return { + ...toolParams, fieldEntityType: undefined, noteEntityType: undefined, mergeEntityType: undefined, diff --git a/apps/sim/blocks/blocks/agentmail.test.ts b/apps/sim/blocks/blocks/agentmail.test.ts new file mode 100644 index 00000000000..5959ce72671 --- /dev/null +++ b/apps/sim/blocks/blocks/agentmail.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from 'vitest' +import { AgentMailBlock } from '@/blocks/blocks/agentmail' + +/** Runs the mapper the way an Agent tool call does: its result is spread over the merged args. */ +function toolCall(args: Record, operation: string) { + const mapParams = AgentMailBlock.tools.config?.params + if (!mapParams) throw new Error('AgentMail block has no params mapper') + return { ...args, ...mapParams(args, { operation }) } +} + +describe('AgentMailBlock agent tool calls', () => { + it('maps the block-field reply message key and keeps the model recipients and flags', () => { + expect( + toolCall( + { inboxId: 'inbox', replyMessageId: 'msg-1', to: 'a@example.com', replyAll: true }, + 'reply_message' + ) + ).toMatchObject({ messageId: 'msg-1', to: 'a@example.com', replyAll: true }) + }) + + it('keeps a boolean permanent flag from the model', () => { + expect( + toolCall({ inboxId: 'inbox', threadId: 't-1', permanent: true }, 'delete_thread') + ).toMatchObject({ permanent: true }) + }) + + it('treats a stored "false" permanent dropdown as a trash move, not a permanent delete', () => { + expect( + toolCall({ inboxId: 'inbox', threadId: 't-1', permanent: 'false' }, 'delete_thread') + ).toMatchObject({ permanent: false }) + }) + + it('treats a stored "false" reply-all dropdown as a reply to the sender only', () => { + expect( + toolCall({ inboxId: 'inbox', replyMessageId: 'msg-1', replyAll: 'false' }, 'reply_message') + ).toMatchObject({ replyAll: false }) + }) +}) diff --git a/apps/sim/blocks/blocks/agentmail.ts b/apps/sim/blocks/blocks/agentmail.ts index db6048ac1d3..d2f79653304 100644 --- a/apps/sim/blocks/blocks/agentmail.ts +++ b/apps/sim/blocks/blocks/agentmail.ts @@ -1,7 +1,7 @@ import { AgentMailIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' export const AgentMailBlock: BlockConfig = { type: 'agentmail', @@ -567,9 +567,9 @@ export const AgentMailBlock: BlockConfig = { ], config: { tool: (params) => `agentmail_${params.operation || 'send_message'}`, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { - operation, inboxIdParam, permanent, replyMessageId, @@ -590,11 +590,11 @@ export const AgentMailBlock: BlockConfig = { } if (operation === 'delete_thread' && permanent !== undefined) { - rest.permanent = permanent === 'true' + rest.permanent = permanent === true || permanent === 'true' } if (operation === 'reply_message' && replyAll !== undefined) { - rest.replyAll = replyAll === 'true' + rest.replyAll = replyAll === true || replyAll === 'true' } if (operation === 'reply_message' && replyMessageId) { @@ -604,7 +604,7 @@ export const AgentMailBlock: BlockConfig = { if (operation === 'reply_message' && replyTo) { rest.to = replyTo } else if (operation === 'reply_message') { - rest.to = undefined + rest.to = toolCallArg(context, rest.to) } if (operation === 'forward_message' && forwardMessageId) { diff --git a/apps/sim/blocks/blocks/agentphone.test.ts b/apps/sim/blocks/blocks/agentphone.test.ts new file mode 100644 index 00000000000..987946d1a89 --- /dev/null +++ b/apps/sim/blocks/blocks/agentphone.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from 'vitest' +import { AgentPhoneBlock } from '@/blocks/blocks/agentphone' + +/** Runs the mapper the way an Agent tool call does: its result is spread over the merged args. */ +function toolCall(args: Record, operation: string) { + const mapParams = AgentPhoneBlock.tools.config?.params + if (!mapParams) throw new Error('AgentPhone block has no params mapper') + return { ...args, ...mapParams(args, { operation }) } +} + +describe('AgentPhoneBlock agent tool calls', () => { + it('maps block-field filters and coerces limits for an operation passed only in context', () => { + expect( + toolCall({ apiKey: 'key', callsStatus: 'completed', limit: '25' }, 'list_calls') + ).toMatchObject({ status: 'completed', limit: 25 }) + }) +}) diff --git a/apps/sim/blocks/blocks/agentphone.ts b/apps/sim/blocks/blocks/agentphone.ts index 2212123f5dc..0159154666d 100644 --- a/apps/sim/blocks/blocks/agentphone.ts +++ b/apps/sim/blocks/blocks/agentphone.ts @@ -2,7 +2,7 @@ import { toError } from '@sim/utils/errors' import { AgentPhoneIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, withSavedCredential } from '@/blocks/utils' const CONVERSATION_OPS = [ 'get_conversation', @@ -588,9 +588,9 @@ export const AgentPhoneBlock: BlockConfig = { ], config: { tool: (params) => `agentphone_${params.operation || 'create_number'}`, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { - operation, attachAgentId, callAgentId, toNumberCall, @@ -633,7 +633,7 @@ export const AgentPhoneBlock: BlockConfig = { if (messageBody !== undefined) rest.body = messageBody } - if (['create_contact', 'update_contact'].includes(operation as string)) { + if (['create_contact', 'update_contact'].includes(operation)) { if (contactPhoneNumber) rest.phoneNumber = contactPhoneNumber if (contactName) rest.name = contactName if (contactEmail) rest.email = contactEmail diff --git a/apps/sim/blocks/blocks/algolia.test.ts b/apps/sim/blocks/blocks/algolia.test.ts new file mode 100644 index 00000000000..c5c3c4e9d44 --- /dev/null +++ b/apps/sim/blocks/blocks/algolia.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from 'vitest' +import { AlgoliaBlock } from '@/blocks/blocks/algolia' + +/** Runs the mapper the way an Agent tool call does: its result is spread over the merged args. */ +function toolCall(args: Record, operation: string) { + const mapParams = AlgoliaBlock.tools.config?.params + if (!mapParams) throw new Error('Algolia block has no params mapper') + return { ...args, ...mapParams(args, { operation }) } +} + +describe('AlgoliaBlock agent tool calls', () => { + it('maps the block-field requests key on a tool call', () => { + expect( + toolCall({ indexName: 'products', getRecordsRequests: '[{"objectID":"1"}]' }, 'get_records') + ).toMatchObject({ requests: '[{"objectID":"1"}]' }) + }) + + it('keeps the model filters, requests, and copy-or-move operation', () => { + expect(toolCall({ indexName: 'p', filters: 'brand:x' }, 'delete_by_filter')).toMatchObject({ + filters: 'brand:x', + }) + expect( + toolCall({ indexName: 'p', requests: [{ objectID: '1' }] }, 'get_records') + ).toMatchObject({ requests: [{ objectID: '1' }] }) + expect( + toolCall({ indexName: 'p', destination: 'q', operation: 'move' }, 'copy_move_index') + ).toMatchObject({ operation: 'move' }) + }) +}) diff --git a/apps/sim/blocks/blocks/algolia.ts b/apps/sim/blocks/blocks/algolia.ts index fbcbe319e9e..077b1164aa5 100644 --- a/apps/sim/blocks/blocks/algolia.ts +++ b/apps/sim/blocks/blocks/algolia.ts @@ -1,7 +1,7 @@ import { AlgoliaIcon } from '@/components/icons' -import type { BlockConfig, BlockMeta } from '@/blocks/types' +import type { BlockConfig, BlockMeta, BlockToolParamsContext } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { isToolCall, mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' export const AlgoliaBlock: BlockConfig = { type: 'algolia', @@ -593,11 +593,11 @@ Return ONLY the JSON array.`, ], config: { tool: (params: Record) => `algolia_${params.operation}`, - params: (params: Record) => { - const { operation, ...rest } = params + params: (params: Record, context?: BlockToolParamsContext) => { + const operation = mapperOperation(params, context) const result: Record = {} - for (const [key, value] of Object.entries(rest)) { + for (const [key, value] of Object.entries(params)) { if (value === undefined || value === null || value === '') continue result[key] = value } @@ -618,15 +618,18 @@ Return ONLY the JSON array.`, result.getRankingInfo = toBool(result.getRankingInfo, false) } if (operation === 'copy_move_index') { - result.operation = result.copyMoveOperation + // A tool call carries the tool's own copy-or-move `operation` as a model arg. + if (!isToolCall(context) || result.copyMoveOperation !== undefined) { + result.operation = result.copyMoveOperation + } result.copyMoveOperation = undefined } if (operation === 'delete_by_filter') { - result.filters = result.deleteFilters + result.filters = result.deleteFilters ?? toolCallArg(context, result.filters) result.deleteFilters = undefined } if (operation === 'get_records') { - result.requests = result.getRecordsRequests + result.requests = result.getRecordsRequests ?? toolCallArg(context, result.requests) result.getRecordsRequests = undefined } diff --git a/apps/sim/blocks/blocks/amplitude.test.ts b/apps/sim/blocks/blocks/amplitude.test.ts new file mode 100644 index 00000000000..3c4cbc212b2 --- /dev/null +++ b/apps/sim/blocks/blocks/amplitude.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest' +import { AmplitudeBlock } from '@/blocks/blocks/amplitude' + +/** Runs the mapper the way an Agent tool call does: its result is spread over the merged args. */ +function toolCall(args: Record, operation: string) { + const mapParams = AmplitudeBlock.tools.config?.params + if (!mapParams) throw new Error('Amplitude block has no params mapper') + return { ...args, ...mapParams(args, { operation }) } +} + +describe('AmplitudeBlock agent tool calls', () => { + it('maps the block-field event key for an operation passed only in context', () => { + expect( + toolCall( + { apiKey: 'k', secretKey: 's', segmentationEventType: 'signup', start: '20260101' }, + 'event_segmentation' + ) + ).toMatchObject({ eventType: 'signup', start: '20260101' }) + }) +}) diff --git a/apps/sim/blocks/blocks/amplitude.ts b/apps/sim/blocks/blocks/amplitude.ts index 22ff60e1c80..f2975f113e0 100644 --- a/apps/sim/blocks/blocks/amplitude.ts +++ b/apps/sim/blocks/blocks/amplitude.ts @@ -1,6 +1,6 @@ import { AmplitudeIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, withSavedCredential } from '@/blocks/utils' /* * Amplitude identifies a person by user id or device id — either one alone is @@ -1012,10 +1012,10 @@ export const AmplitudeBlock: BlockConfig = { ], config: { tool: (params) => `amplitude_${params.operation}`, - params: (params) => { + params: (params, context) => { const result: Record = {} - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'send_event': if (params.sendEventUserProperties) result.userProperties = params.sendEventUserProperties diff --git a/apps/sim/blocks/blocks/apollo.test.ts b/apps/sim/blocks/blocks/apollo.test.ts new file mode 100644 index 00000000000..3af28753040 --- /dev/null +++ b/apps/sim/blocks/blocks/apollo.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from 'vitest' +import { ApolloBlock } from '@/blocks/blocks/apollo' +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 => ApolloBlock.tools.config?.params?.(inputs, context) ?? {} + +/** + * On an agent call the stored row params merge with the model args (keyed by the tool's param + * names), the operation reaches the mapper only on `context`, and the handler forwards + * `{ ...merged, ...mapped }`. + */ +describe('ApolloBlock agent tool calls', () => { + const agentCall = ( + operation: string, + merged: Record + ): Record => { + return { ...merged, ...buildParams(merged, { operation }) } + } + + it('forwards the row acting user and label names to sequence_add_contacts', () => { + const mapped = agentCall('sequence_add', { + apiKey: 'key', + sequence_id: 'seq_1', + contact_ids: ['c_1'], + send_email_from_email_account_id: 'ea_1', + sequence_user_id: 'user_1', + sequence_add_label_names: '["outbound"]', + }) + expect(mapped).toMatchObject({ user_id: 'user_1', label_names: ['outbound'] }) + expect(mapped.sequence_user_id).toBeUndefined() + expect(mapped.sequence_add_label_names).toBeUndefined() + }) + + it('sends the row initial status over a stale task status carried from another operation', () => { + const mapped = agentCall('sequence_add', { + apiKey: 'key', + sequence_id: 'seq_1', + contact_ids: ['c_1'], + send_email_from_email_account_id: 'ea_1', + sequence_status: 'paused', + status: 'scheduled', + }) + expect(mapped.status).toBe('paused') + }) + + it('keeps the row initial status on the canvas', () => { + const mapped = buildParams({ + operation: 'sequence_add', + apiKey: 'key', + sequence_status: 'paused', + status: 'active', + }) + expect(mapped.status).toBe('paused') + }) +}) diff --git a/apps/sim/blocks/blocks/apollo.ts b/apps/sim/blocks/blocks/apollo.ts index aba5a2b5a8a..7a851822308 100644 --- a/apps/sim/blocks/blocks/apollo.ts +++ b/apps/sim/blocks/blocks/apollo.ts @@ -3,7 +3,7 @@ import { getErrorMessage } from '@sim/utils/errors' import { ApolloIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, withSavedCredential } from '@/blocks/utils' /** Identifies a person by email when available, otherwise by given name. */ const PERSON_IDENTITY_FIELD = ['email', 'first_name'] as const @@ -1112,7 +1112,8 @@ Return ONLY the timestamp string in ISO 8601 format - no explanations, no quotes throw new Error(`Invalid Apollo operation: ${params.operation}`) } }, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { apiKey, ...rest } = params const parsedParams: Record = { apiKey, ...rest } @@ -1190,7 +1191,7 @@ Return ONLY the timestamp string in ISO 8601 format - no explanations, no quotes } } - if (params.operation === 'organization_bulk_enrich') { + if (operation === 'organization_bulk_enrich') { // Back-compat: workflows saved before the `organizations` → `domains` rename stored an // array of { name, domain? } objects (or plain strings) under `organizations`. Derive // `domains` from it so those workflows keep running without manual migration. @@ -1213,7 +1214,7 @@ Return ONLY the timestamp string in ISO 8601 format - no explanations, no quotes parsedParams.organizations = undefined } - if (params.operation === 'contact_bulk_update') { + if (operation === 'contact_bulk_update') { const { ids, attributes } = splitBulkUpdateInput(parsedParams.contacts) if (attributes) { if (parsedParams.contact_attributes === undefined) { @@ -1225,7 +1226,7 @@ Return ONLY the timestamp string in ISO 8601 format - no explanations, no quotes parsedParams.contacts = undefined } - if (params.operation === 'account_bulk_update') { + if (operation === 'account_bulk_update') { const { ids, attributes } = splitBulkUpdateInput(parsedParams.accounts) if (attributes) { if (parsedParams.account_attributes === undefined) { @@ -1249,23 +1250,23 @@ Return ONLY the timestamp string in ISO 8601 format - no explanations, no quotes parsedParams.account_bulk_update_account_stage_id = undefined } - if (params.operation === 'contact_create') { + if (operation === 'contact_create') { if (rest.contact_run_dedupe !== undefined) { parsedParams.run_dedupe = rest.contact_run_dedupe } parsedParams.contact_run_dedupe = undefined } - if (params.operation === 'account_create' || params.operation === 'account_update') { + if (operation === 'account_create' || operation === 'account_update') { if (rest.account_name) parsedParams.name = rest.account_name parsedParams.account_name = undefined } - if (params.operation === 'account_update') { + if (operation === 'account_update') { parsedParams.account_id = rest.account_id } - if (params.operation === 'sequence_add') { + if (operation === 'sequence_add') { if (parsedParams.sequence_add_label_names !== undefined) { parsedParams.label_names = parsedParams.sequence_add_label_names } @@ -1280,17 +1281,14 @@ Return ONLY the timestamp string in ISO 8601 format - no explanations, no quotes parsedParams.sequence_status = undefined } - if (params.operation === 'task_create') { + if (operation === 'task_create') { if (rest.task_notes !== undefined) { parsedParams.note = rest.task_notes } parsedParams.task_notes = undefined } - if ( - params.operation === 'opportunity_create' || - params.operation === 'opportunity_update' - ) { + if (operation === 'opportunity_create' || operation === 'opportunity_update') { if (rest.opportunity_name) parsedParams.name = rest.opportunity_name parsedParams.opportunity_name = undefined } diff --git a/apps/sim/blocks/blocks/ashby.test.ts b/apps/sim/blocks/blocks/ashby.test.ts index 4678e846694..f4211b5dc1b 100644 --- a/apps/sim/blocks/blocks/ashby.test.ts +++ b/apps/sim/blocks/blocks/ashby.test.ts @@ -1,6 +1,9 @@ import { describe, expect, it } from 'vitest' import { AshbyBlock } from './ashby' +const blockParams = AshbyBlock.tools.config?.params +if (!blockParams) throw new Error('AshbyBlock has no params mapper') + describe('AshbyBlock', () => { const buildParams = (operation: string, extra: Record) => ({ operation, @@ -9,7 +12,7 @@ describe('AshbyBlock', () => { describe('alternateEmailAddresses parsing (create_candidate)', () => { it('parses a comma-separated string into an array', () => { - const result = AshbyBlock.tools.config.params!( + const result = blockParams( buildParams('create_candidate', { alternateEmailAddresses: 'a@x.com, b@x.com', }) @@ -20,9 +23,7 @@ describe('AshbyBlock', () => { describe('socialLinks parsing (update_candidate)', () => { it('preserves an empty JSON array so users can clear all social links', () => { - const result = AshbyBlock.tools.config.params!( - buildParams('update_candidate', { socialLinks: '[]' }) - ) + const result = blockParams(buildParams('update_candidate', { socialLinks: '[]' })) expect(result.socialLinks).toEqual([]) }) @@ -30,24 +31,20 @@ describe('AshbyBlock', () => { // A silent [] here would let the Ashby update proceed without applying // the requested links and with no error shown to the workflow author. expect(() => - AshbyBlock.tools.config.params!( - buildParams('update_candidate', { socialLinks: 'not json' }) - ) + blockParams(buildParams('update_candidate', { socialLinks: 'not json' })) ).toThrow(/Invalid JSON in Ashby social links/) }) it('throws when the parsed JSON is not an array', () => { expect(() => - AshbyBlock.tools.config.params!( - buildParams('update_candidate', { socialLinks: '{"type":"Twitter"}' }) - ) + blockParams(buildParams('update_candidate', { socialLinks: '{"type":"Twitter"}' })) ).toThrow(/expected a JSON array/) }) }) describe('nullable candidate updates', () => { it('preserves nulls from dynamic references for aliased update fields', () => { - const result = AshbyBlock.tools.config.params!( + const result = blockParams( buildParams('update_candidate', { updateName: null, candidateLocation: null, @@ -63,17 +60,14 @@ describe('AshbyBlock', () => { describe('archiveEmail parsing (change_application_stage)', () => { it('rejects non-object archive email input', () => { expect(() => - AshbyBlock.tools.config.params!( - buildParams('change_application_stage', { archiveEmail: 'true' }) - ) + blockParams(buildParams('change_application_stage', { archiveEmail: 'true' })) ).toThrow(/expected a JSON object/) }) }) describe('fieldValue parsing (set_custom_field_value)', () => { const parse = (fieldValue: unknown) => - AshbyBlock.tools.config.params!(buildParams('set_custom_field_value', { fieldValue })) - .fieldValue + blockParams(buildParams('set_custom_field_value', { fieldValue })).fieldValue it('decodes null so the annotation can be cleared', () => { // Ashby clears a custom field when it receives an explicit null, which is @@ -106,17 +100,13 @@ describe('AshbyBlock', () => { describe('fieldValues parsing (set_custom_field_values)', () => { it('throws instead of silently dropping the writes when the JSON is malformed', () => { expect(() => - AshbyBlock.tools.config.params!( - buildParams('set_custom_field_values', { fieldValues: 'not json' }) - ) + blockParams(buildParams('set_custom_field_values', { fieldValues: 'not json' })) ).toThrow(/Invalid JSON in Ashby custom field values/) }) it('throws when the parsed JSON is not an array', () => { expect(() => - AshbyBlock.tools.config.params!( - buildParams('set_custom_field_values', { fieldValues: '{"fieldId":"abc"}' }) - ) + blockParams(buildParams('set_custom_field_values', { fieldValues: '{"fieldId":"abc"}' })) ).toThrow(/expected a JSON array/) }) }) @@ -126,7 +116,7 @@ describe('AshbyBlock', () => { // The Source ID field is hidden once the clear switch is on, but a value // typed beforehand is still stored. Sending both would trip the tool's // exclusivity guard and surface as an error the user cannot see the cause of. - const result = AshbyBlock.tools.config.params!( + const result = blockParams( buildParams('change_application_source', { changeSourceId: 'src-left-over', unsetSource: 'true', @@ -146,7 +136,7 @@ describe('AshbyBlock', () => { // result, not just the mapping, since that gap is where the bug lived. const merge = (inputs: Record) => ({ ...inputs, - ...AshbyBlock.tools.config.params!(inputs), + ...blockParams(inputs), }) const cleared = merge( @@ -179,4 +169,33 @@ describe('AshbyBlock', () => { expect(explicit.sourceId).toBe('src-intended') }) }) + describe('agent tool calls (operation only in context)', () => { + const toolCall = (operation: string, args: Record) => ({ + ...args, + ...blockParams(args, { operation }), + }) + + it('maps block-only fields saved on the tool row to the tool params', () => { + const result = toolCall('create_application', { + appCandidateId: 'cand-1', + appCreatedAt: '2026-01-01T00:00:00Z', + jobId: 'job-1', + }) + expect(result.candidateId).toBe('cand-1') + expect(result.createdAt).toBe('2026-01-01T00:00:00Z') + }) + + it('keeps model args keyed by the tool param names', () => { + const values = [{ fieldId: 'f-1', fieldValue: 'High' }] + expect( + toolCall('set_custom_field_values', { objectType: 'Candidate', objectId: 'c-1', values }) + .values + ).toEqual(values) + expect( + toolCall('change_application_source', { applicationId: 'app-1', sourceId: 'src-1' }) + .sourceId + ).toBe('src-1') + expect(toolCall('search_candidates', { name: 'Ada', limit: 5 }).limit).toBe(5) + }) + }) }) diff --git a/apps/sim/blocks/blocks/ashby.ts b/apps/sim/blocks/blocks/ashby.ts index 7c3d6af7950..b04c6993f08 100644 --- a/apps/sim/blocks/blocks/ashby.ts +++ b/apps/sim/blocks/blocks/ashby.ts @@ -1,7 +1,12 @@ import { getErrorMessage } from '@sim/utils/errors' import { AshbyIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' -import { normalizeFileInput, withSavedCredential } from '@/blocks/utils' +import { + mapperOperation, + normalizeFileInput, + toolCallArg, + withSavedCredential, +} from '@/blocks/utils' import { getTrigger } from '@/triggers' function parseStringListInput(value: unknown): string[] { @@ -1420,7 +1425,8 @@ Output only the JSON array.`, ], config: { tool: (params) => `ashby_${params.operation}`, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const result: Record = {} if (params.perPage) result.perPage = Number(params.perPage) if (params.searchName) result.name = params.searchName @@ -1466,7 +1472,7 @@ Output only the JSON array.`, params.includeUnpublishedJobPostingIds === 'true' || params.includeUnpublishedJobPostingIds === true ) { - if (params.operation === 'list_jobs') result.includeUnpublishedJobPostingsIds = true + if (operation === 'list_jobs') result.includeUnpublishedJobPostingsIds = true else result.includeUnpublishedJobPostingIds = true } if (params.excludeFormDefinition === 'true' || params.excludeFormDefinition === true) { @@ -1486,7 +1492,7 @@ Output only the JSON array.`, if (applicationHistory.length > 0) result.applicationHistory = applicationHistory } if ( - (params.operation === 'create_candidate' || params.operation === 'update_candidate') && + (operation === 'create_candidate' || operation === 'update_candidate') && params.candidateLocation !== undefined && params.candidateLocation !== '' ) { @@ -1507,28 +1513,30 @@ Output only the JSON array.`, ) { result.startAutomaticActivities = true } - if (params.operation === 'search_jobs' || params.operation === 'search_candidates') { - result.limit = params.perPage ? Number(params.perPage) : undefined + if (operation === 'search_jobs' || operation === 'search_candidates') { + result.limit = params.perPage + ? Number(params.perPage) + : toolCallArg(context, params.limit) } - if (params.operation === 'upload_resume' || params.operation === 'upload_candidate_file') { + if (operation === 'upload_resume' || operation === 'upload_candidate_file') { const file = normalizeFileInput(params.file, { single: true }) if (!file) throw new Error('A candidate file is required.') result.file = file } - if (params.operation === 'create_application' && params.appCandidateId) { + if (operation === 'create_application' && params.appCandidateId) { result.candidateId = params.appCandidateId } - if (params.operation === 'create_application' && params.appCreatedAt) { + if (operation === 'create_application' && params.appCreatedAt) { result.createdAt = params.appCreatedAt } if ( - (params.operation === 'create_candidate' || params.operation === 'update_candidate') && + (operation === 'create_candidate' || operation === 'update_candidate') && params.candidateCreatedAt !== undefined && params.candidateCreatedAt !== '' ) { result.createdAt = params.candidateCreatedAt } - if (params.operation === 'create_note' && params.noteCreatedAt) { + if (operation === 'create_note' && params.noteCreatedAt) { result.createdAt = params.noteCreatedAt } if (params.updateName !== undefined && params.updateName !== '') { @@ -1544,7 +1552,7 @@ Output only the JSON array.`, ) { result.includeLocationHierarchy = true } - if (params.operation === 'list_offers' && params.offerApplicationId) { + if (operation === 'list_offers' && params.offerApplicationId) { result.applicationId = params.offerApplicationId } if (params.alternateEmailAddresses) { @@ -1559,13 +1567,15 @@ Output only the JSON array.`, result.socialLinks = parseSocialLinksInput(socialLinksValue) } } - if (params.operation === 'set_custom_field_value') { + if (operation === 'set_custom_field_value') { result.fieldValue = parseCustomFieldValueInput(params.fieldValue) } - if (params.operation === 'set_custom_field_values') { - result.values = parseCustomFieldValuesInput(params.fieldValues) + if (operation === 'set_custom_field_values') { + result.values = parseCustomFieldValuesInput( + params.fieldValues || toolCallArg(context, params.values) + ) } - if (params.operation === 'change_application_source') { + if (operation === 'change_application_source') { // sourceId is always assigned, never conditionally, because the executor // merges `{ ...inputs, ...transformedParams }` and a key this mapping // leaves unset simply inherits whatever was in inputs. The create-path @@ -1576,8 +1586,9 @@ Output only the JSON array.`, // Inheriting it would attribute a source nobody asked for, or collide // with a clear request and fail with no visible cause. const unsetSource = params.unsetSource === 'true' || params.unsetSource === true + const requestedSourceId = params.changeSourceId || toolCallArg(context, params.sourceId) const changeSourceId = - typeof params.changeSourceId === 'string' ? params.changeSourceId.trim() : '' + typeof requestedSourceId === 'string' ? requestedSourceId.trim() : '' result.sourceId = unsetSource || !changeSourceId ? undefined : changeSourceId if (unsetSource) result.unsetSource = true } diff --git a/apps/sim/blocks/blocks/brightdata.test.ts b/apps/sim/blocks/blocks/brightdata.test.ts new file mode 100644 index 00000000000..db28714d8a9 --- /dev/null +++ b/apps/sim/blocks/blocks/brightdata.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from 'vitest' +import { BrightDataBlock } from '@/blocks/blocks/brightdata' + +const mapper = BrightDataBlock.tools.config?.params +if (!mapper) throw new Error('BrightDataBlock has no params mapper') +const mapToolParams = mapper + +/** + * Agent tool calls carry the operation only in `context` and key model args by the tool's + * param names; the result is spread over the merged params, as `buildBlockToolParamsTransform` does. + */ +const toolCall = (operation: string, merged: Record) => ({ + ...merged, + ...mapToolParams(merged, { operation }), +}) + +describe('BrightDataBlock tool calls', () => { + it('maps stored block fields and keeps the model dataset and URLs for sync scrape', () => { + const params = toolCall('sync_scrape', { + apiKey: 'key', + datasetId: 'gd_model', + urls: '[{"url":"https://example.com"}]', + syncFormat: 'csv', + }) + + expect(params.datasetId).toBe('gd_model') + expect(params.urls).toBe('[{"url":"https://example.com"}]') + expect(params.format).toBe('csv') + }) +}) diff --git a/apps/sim/blocks/blocks/brightdata.ts b/apps/sim/blocks/blocks/brightdata.ts index ea9ee0d21d9..60bc40eb46f 100644 --- a/apps/sim/blocks/blocks/brightdata.ts +++ b/apps/sim/blocks/blocks/brightdata.ts @@ -1,7 +1,7 @@ import { BrightDataIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' export const BrightDataBlock: BlockConfig = { type: 'brightdata', @@ -341,10 +341,10 @@ export const BrightDataBlock: BlockConfig = { ], config: { tool: (params) => `brightdata_${params.operation}`, - params: (params) => { + params: (params, context) => { const result: Record = { apiKey: params.apiKey } - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'scrape_url': result.zone = params.zone result.url = params.url @@ -363,7 +363,7 @@ export const BrightDataBlock: BlockConfig = { break case 'discover': - result.query = params.discoverQuery + result.query = params.discoverQuery ?? toolCallArg(context, params.query) if (params.numResults) result.numResults = Number(params.numResults) if (params.mode) result.mode = params.mode if (params.intent) result.intent = params.intent @@ -374,8 +374,8 @@ export const BrightDataBlock: BlockConfig = { break case 'sync_scrape': - result.datasetId = params.syncDatasetId - result.urls = params.syncUrls + result.datasetId = params.syncDatasetId ?? toolCallArg(context, params.datasetId) + result.urls = params.syncUrls ?? toolCallArg(context, params.urls) if (params.syncFormat) result.format = params.syncFormat if (params.syncIncludeErrors != null) result.includeErrors = params.syncIncludeErrors break diff --git a/apps/sim/blocks/blocks/buffer.test.ts b/apps/sim/blocks/blocks/buffer.test.ts new file mode 100644 index 00000000000..0e371573abb --- /dev/null +++ b/apps/sim/blocks/blocks/buffer.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from 'vitest' +import { BufferBlock } from '@/blocks/blocks/buffer' + +const mapper = BufferBlock.tools.config?.params +if (!mapper) throw new Error('BufferBlock has no params mapper') +const mapToolParams = mapper + +describe('BufferBlock tool calls', () => { + it('turns the default share mode into addToQueue when creating a post', () => { + const merged = { apiKey: 'key', channelId: 'ch_1', text: 'Hello', mode: 'default' } + const params: Record = { + ...merged, + ...mapToolParams(merged, { operation: 'create_post' }), + } + + expect(params.mode).toBe('addToQueue') + expect(params.schedulingType).toBeUndefined() + }) +}) diff --git a/apps/sim/blocks/blocks/buffer.ts b/apps/sim/blocks/blocks/buffer.ts index b1704172957..9a275f5a3be 100644 --- a/apps/sim/blocks/blocks/buffer.ts +++ b/apps/sim/blocks/blocks/buffer.ts @@ -1,7 +1,7 @@ import { BufferIcon } from '@/components/icons' import type { BlockConfig, BlockMeta, SubBlockConfig } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput, withSavedCredential } from '@/blocks/utils' +import { mapperOperation, normalizeFileInput, withSavedCredential } from '@/blocks/utils' import { getToolMetadata } from '@/tools/metadata' const POST_EDIT_OPS = ['create_post', 'edit_post'] @@ -658,7 +658,8 @@ export const BufferBlock: BlockConfig = { ], config: { tool: (params) => `buffer_${params.operation}`, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const result: Record = {} for (const [key, value] of Object.entries(params)) { if ( @@ -674,7 +675,7 @@ export const BufferBlock: BlockConfig = { } if ((key === 'mode' || key === 'schedulingType') && value === 'default') { result[key] = - params.operation === 'create_post' + operation === 'create_post' ? key === 'mode' ? 'addToQueue' : 'automatic' @@ -699,7 +700,7 @@ export const BufferBlock: BlockConfig = { throw new Error('Choose one media input: uploaded/reference file or public URL') if (params.assets && (normalizedMedia || mediaUrl)) throw new Error('Choose assets or a single media input') - if (params.operation === 'edit_post' && params.clearText === true) result.text = null + if (operation === 'edit_post' && params.clearText === true) result.text = null if (normalizedMedia) { result.media = normalizedMedia } else if (mediaUrl) { diff --git a/apps/sim/blocks/blocks/cbinsights.test.ts b/apps/sim/blocks/blocks/cbinsights.test.ts index d581a6c0f34..2713ade0fcd 100644 --- a/apps/sim/blocks/blocks/cbinsights.test.ts +++ b/apps/sim/blocks/blocks/cbinsights.test.ts @@ -101,4 +101,12 @@ describe('CbInsightsBlock', () => { expect(maturity.startDate).toBe('2025-01-01') expect(maturity.endDate).toBe('2025-06-01') }) + + it('keeps model filters on a firmographics tool call, which carries no operation in params', () => { + const merged = { clientId: 'id', clientSecret: 'secret', keyword: 'fintech', orgIds: [1, 2] } + const params = { ...merged, ...buildParams(merged, { operation: 'search_firmographics' }) } + + expect(params.keyword).toBe('fintech') + expect(params.orgIds).toEqual([1, 2]) + }) }) diff --git a/apps/sim/blocks/blocks/cbinsights.ts b/apps/sim/blocks/blocks/cbinsights.ts index d7d73cbaaf1..1eaea4770b3 100644 --- a/apps/sim/blocks/blocks/cbinsights.ts +++ b/apps/sim/blocks/blocks/cbinsights.ts @@ -2,7 +2,7 @@ import { Building, ListChecks, Search, Sparkles, Sprout, Users } from '@sim/emcn import { CbInsightsIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' /** Operations that take a single organization ID on the path. */ const ORG_OPERATIONS = [ @@ -654,8 +654,8 @@ export const CbInsightsBlock: BlockConfig = { * advanced field is serialized on non-emptiness alone, even while the UI * hides it. `undefined` is what actually drops one. */ - params: (params) => { - const operation = String(params.operation ?? '') + params: (params, context) => { + const operation = mapperOperation(params, context) const isOrg = (ORG_OPERATIONS as readonly string[]).includes(operation) const isOrgList = (ORG_LIST_OPERATIONS as readonly string[]).includes(operation) const isFirmographics = operation === 'search_firmographics' @@ -670,11 +670,15 @@ export const CbInsightsBlock: BlockConfig = { clientId: params.clientId, clientSecret: params.clientSecret, orgId: isOrg ? params.orgId : undefined, - orgIds: isOrgList ? params.orgIds : firmographic(params.orgIdFilter), + orgIds: isOrgList + ? params.orgIds + : firmographic(params.orgIdFilter ?? toolCallArg(context, params.orgIds)), message: isAi ? params.message : undefined, chatId: isChat ? params.chatId : undefined, names: isLookup ? params.names : undefined, - urls: isLookup ? params.urls : firmographic(params.firmographicsUrls), + urls: isLookup + ? params.urls + : firmographic(params.firmographicsUrls ?? toolCallArg(context, params.urls)), profileUrl: isLookup ? params.profileUrl : undefined, keyword: firmographic(params.keyword), orgNames: firmographic(params.orgNames), diff --git a/apps/sim/blocks/blocks/checkr.test.ts b/apps/sim/blocks/blocks/checkr.test.ts new file mode 100644 index 00000000000..4a7444ceb54 --- /dev/null +++ b/apps/sim/blocks/blocks/checkr.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from 'vitest' +import { CheckrBlock } from '@/blocks/blocks/checkr' + +const mapper = CheckrBlock.tools.config?.params +if (!mapper) throw new Error('CheckrBlock has no params mapper') +const mapToolParams = mapper + +/** + * Agent tool calls carry the operation only in `context` and key model args by the tool's + * param names; the result is spread over the merged params, as `buildBlockToolParamsTransform` does. + */ +const toolCall = (operation: string, merged: Record) => ({ + ...merged, + ...mapToolParams(merged, { operation }), +}) + +describe('CheckrBlock tool calls', () => { + it('sends the stored report tags when ordering a report', () => { + const params = toolCall('create_report', { + apiKey: 'key', + candidateId: 'cand_1', + package: 'basic', + reportTags: 'urgent, onsite', + }) + + expect(params.tags).toEqual(['urgent', 'onsite']) + }) + + it('keeps the model node and work locations when updating a continuous check', () => { + const params = toolCall('update_continuous_check', { + apiKey: 'key', + continuousCheckId: 'cc_1', + node: 'node_1', + workLocations: [{ country: 'US', state: 'CA' }], + }) + + expect(params.node).toBe('node_1') + expect(params.workLocations).toEqual([{ country: 'US', state: 'CA' }]) + }) +}) diff --git a/apps/sim/blocks/blocks/checkr.ts b/apps/sim/blocks/blocks/checkr.ts index 5fad3954ed3..3c97794fa9a 100644 --- a/apps/sim/blocks/blocks/checkr.ts +++ b/apps/sim/blocks/blocks/checkr.ts @@ -1,6 +1,6 @@ import { CheckrIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' import { getTrigger } from '@/triggers' const CANDIDATE_ID_REQUIRED_OPS = [ @@ -1271,7 +1271,8 @@ export const CheckrBlock: BlockConfig = { ], config: { tool: (params) => `checkr_${params.operation}`, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { candidateAdjudication, reportAdjudication, @@ -1293,18 +1294,21 @@ export const CheckrBlock: BlockConfig = { } = params const result: Record = { ...rest } - if (params.operation === 'create_invitation' || params.operation === 'create_report') { - result.tags = toStringList(reportTags) + if (operation === 'create_invitation' || operation === 'create_report') { + result.tags = toStringList(reportTags ?? toolCallArg(context, rest.tags)) } else { result.tags = toStringList(rest.tags) } - if (params.operation === 'list_candidates') { - result.geoId = filterGeoId || undefined - result.programId = filterProgramId || undefined + if (operation === 'list_candidates') { + result.geoId = filterGeoId || toolCallArg(context, rest.geoId) || undefined + result.programId = filterProgramId || toolCallArg(context, rest.programId) || undefined } - if (params.operation === 'update_continuous_check') { - result.node = continuousCheckNode || undefined - result.workLocations = toJsonArray(continuousCheckWorkLocations, 'work locations') + if (operation === 'update_continuous_check') { + result.node = continuousCheckNode || toolCallArg(context, rest.node) || undefined + result.workLocations = toJsonArray( + continuousCheckWorkLocations ?? toolCallArg(context, rest.workLocations), + 'work locations' + ) } else { result.workLocations = toJsonArray(rest.workLocations, 'work locations') } @@ -1314,10 +1318,9 @@ export const CheckrBlock: BlockConfig = { result.selfDisclosures = toJsonArray(rest.selfDisclosures, 'self disclosures') const adjudication = - params.operation === 'update_report' ? reportAdjudication : candidateAdjudication + operation === 'update_report' ? reportAdjudication : candidateAdjudication if (adjudication) result.adjudication = adjudication - const status = - params.operation === 'list_subscriptions' ? subscriptionStatus : invitationStatus + const status = operation === 'list_subscriptions' ? subscriptionStatus : invitationStatus if (status) result.status = status const noMiddle = toOptionalBoolean(noMiddleName) diff --git a/apps/sim/blocks/blocks/circleback.test.ts b/apps/sim/blocks/blocks/circleback.test.ts new file mode 100644 index 00000000000..69eb152b182 --- /dev/null +++ b/apps/sim/blocks/blocks/circleback.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest' +import { CirclebackBlock } from '@/blocks/blocks/circleback' + +/** + * A tool call merges the stored row with the model's args (keyed by tool param names) and spreads + * the mapper result over them; the operation arrives only in `context`. + */ +const toolCall = (args: Record, operation: string) => ({ + ...args, + ...CirclebackBlock.tools.config?.params?.(args, { operation }), +}) + +describe('CirclebackBlock tool calls', () => { + it('sends the stored action-item filters under the tool param names', () => { + const params = toolCall( + { statusFilter: 'DONE', assigneeFilterProfileId: 'profile-1' }, + 'list_action_items' + ) + expect(params.status).toBe('DONE') + expect(params.assigneeProfileId).toBe('profile-1') + }) +}) diff --git a/apps/sim/blocks/blocks/circleback.ts b/apps/sim/blocks/blocks/circleback.ts index 40a8007ddda..58c24542757 100644 --- a/apps/sim/blocks/blocks/circleback.ts +++ b/apps/sim/blocks/blocks/circleback.ts @@ -1,7 +1,7 @@ import { ClipboardList, Table } from '@sim/emcn/icons' import { CirclebackIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, withSavedCredential } from '@/blocks/utils' import { getTrigger } from '@/triggers' export const CirclebackBlock: BlockConfig = { @@ -452,18 +452,19 @@ export const CirclebackBlock: BlockConfig = { ], config: { tool: (params) => `circleback_${params.operation}`, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) /* Filter variants live on their own subBlocks so an operation switch cannot leak a mutation input into a list filter; remap them onto the tool param names here. */ const result: Record = {} - if (params.operation === 'list_action_items') { + if (operation === 'list_action_items') { if (params.statusFilter) result.status = params.statusFilter if (params.assigneeFilterProfileId) { result.assigneeProfileId = params.assigneeFilterProfileId } } - if (params.operation === 'search_meetings' && params.searchMeetingIds) { + if (operation === 'search_meetings' && params.searchMeetingIds) { result.meetingIds = params.searchMeetingIds } return result diff --git a/apps/sim/blocks/blocks/clerk.test.ts b/apps/sim/blocks/blocks/clerk.test.ts new file mode 100644 index 00000000000..02cff4fc4d3 --- /dev/null +++ b/apps/sim/blocks/blocks/clerk.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest' +import { ClerkBlock } from '@/blocks/blocks/clerk' + +/** + * A tool call merges the stored row with the model's args (keyed by tool param names) and spreads + * the mapper result over them; the operation arrives only in `context`. + */ +const toolCall = (args: Record, operation: string) => ({ + ...args, + ...ClerkBlock.tools.config?.params?.(args, { operation }), +}) + +describe('ClerkBlock tool calls', () => { + it('parses metadata the model sends as a JSON string', () => { + const params = toolCall( + { secretKey: 'sk', emailAddress: ['a@example.com'], publicMetadata: '{"plan":"pro"}' }, + 'clerk_create_user' + ) + expect(params.publicMetadata).toEqual({ plan: 'pro' }) + expect(params.emailAddress).toEqual(['a@example.com']) + }) +}) diff --git a/apps/sim/blocks/blocks/clerk.ts b/apps/sim/blocks/blocks/clerk.ts index f0cd40bec9b..be1ad8d9917 100644 --- a/apps/sim/blocks/blocks/clerk.ts +++ b/apps/sim/blocks/blocks/clerk.ts @@ -1,7 +1,7 @@ import { ClerkIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, withSavedCredential } from '@/blocks/utils' import { getTrigger } from '@/triggers' /** @@ -820,9 +820,9 @@ export const ClerkBlock: BlockConfig = { ], config: { tool: (params) => params.operation as string, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { - operation, secretKey, emailAddressFilter, usernameFilter, diff --git a/apps/sim/blocks/blocks/coda.test.ts b/apps/sim/blocks/blocks/coda.test.ts new file mode 100644 index 00000000000..1e9773cee31 --- /dev/null +++ b/apps/sim/blocks/blocks/coda.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from 'vitest' +import { CodaBlock } from '@/blocks/blocks/coda' + +const mapParams = CodaBlock.tools.config?.params + +/** + * A tool call merges the stored row with the model's args (keyed by tool param names) and spreads + * the mapper result over them; the operation arrives only in `context`. + */ +const toolCall = (args: Record, operation: string) => ({ + ...args, + ...mapParams?.(args, { operation }), +}) + +describe('CodaBlock', () => { + it('keeps the model args a tool call sends under the tool param names', () => { + const params = toolCall( + { docId: 'doc-1', tableId: 'grid-1', query: 'Status:"Done"', sortBy: 'natural', limit: 5 }, + 'list_rows' + ) + expect(params.query).toBe('Status:"Done"') + expect(params.sortBy).toBe('natural') + expect(params.limit).toBe(5) + }) + + it('does not restore a sentinel or off switch the coercion dropped on a tool call', () => { + const params = toolCall( + { docId: 'd', tableTypes: 'all', isPublished: false, visibleOnly: 'false' }, + 'list_tables' + ) + expect(params.tableTypes).toBeUndefined() + expect(params.isPublished).toBeUndefined() + expect(params.visibleOnly).toBeUndefined() + }) + + it('keeps the array form of table types a tool call sends', () => { + const params = toolCall({ docId: 'd', tableTypes: ['table'] }, 'list_tables') + expect(params.tableTypes).toEqual(['table']) + }) + + it('still drops a stale raw input on the canvas', () => { + const inputs = { operation: 'list_docs', query: 'stale', docSearch: 'roadmap', title: 'old' } + const params = { ...inputs, ...mapParams?.(inputs) } + expect(params.query).toBe('roadmap') + expect(params.title).toBeUndefined() + }) +}) diff --git a/apps/sim/blocks/blocks/coda.ts b/apps/sim/blocks/blocks/coda.ts index 25137f72fee..7f5334e64fc 100644 --- a/apps/sim/blocks/blocks/coda.ts +++ b/apps/sim/blocks/blocks/coda.ts @@ -1,5 +1,6 @@ import { CodaIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' const DOC_FIELD = ['docSelector', 'manualDocId'] const PAGE_FIELD = ['pageSelector', 'manualPageId'] @@ -110,6 +111,30 @@ const PAGE_TOKEN_OPERATIONS = [...LIMIT_OPERATIONS, 'list_workspace_members'] const LIST_SORT_OPERATIONS = ['list_tables', 'list_formulas', 'list_controls'] +/** + * Tool params the mapper reads from the same-named field, so a tool call's own value was + * already coerced; the tool-call fallback must not restore a value the coercion rejected + * (the `'all'` table-type sentinel, an off switch). + */ +const SELF_MAPPED_PARAMS = new Set([ + 'tableTypes', + 'limit', + 'discoverable', + 'allowEditorsToChangePermissions', + 'allowCopying', + 'allowViewersToRequestEditing', + 'includeSubpages', + 'isOwner', + 'isPublished', + 'inGallery', + 'useColumnNames', + 'useUpdatedTableLayouts', + 'visibleOnly', + 'disableParsing', + 'suppressEmail', + 'degradeGracefully', +]) + /** Switches only send `true`; an off switch leaves the Coda filter unset. */ function trueOrUndefined(value: unknown): true | undefined { return value === true || value === 'true' ? true : undefined @@ -1534,11 +1559,11 @@ Return ONLY the JSON object.`, ], config: { tool: (params) => `coda_${params.operation || 'list_rows'}`, - params: (params) => { - const operation = params.operation + params: (params, context) => { + const operation = mapperOperation(params, context) const isFolderWrite = operation === 'create_folder' || operation === 'update_folder' const pageVisibility = params.pageVisibility - return { + const mapped: Record = { query: operation === 'list_rows' ? params.rowFilter @@ -1571,7 +1596,9 @@ Return ONLY the JSON object.`, : params.listSortBy === 'name' ? 'name' : undefined, - tableTypes: unlessDefault(params.tableTypes, 'all'), + tableTypes: Array.isArray(params.tableTypes) + ? params.tableTypes + : unlessDefault(params.tableTypes, 'all'), mode: unlessDefault(params.publishMode, 'unchanged'), discoverable: triState(params.discoverable), allowEditorsToChangePermissions: triState(params.allowEditorsToChangePermissions), @@ -1593,6 +1620,14 @@ Return ONLY the JSON object.`, suppressEmail: trueOrUndefined(params.suppressEmail), degradeGracefully: trueOrUndefined(params.degradeGracefully), } + /* A tool call keeps each model arg this mapping leaves unset instead of wiping it; + {@link SELF_MAPPED_PARAMS} lists the keys whose drop must stand. */ + for (const [key, value] of Object.entries(mapped)) { + if (value === undefined && !SELF_MAPPED_PARAMS.has(key)) { + mapped[key] = toolCallArg(context, params[key]) + } + } + return mapped }, }, }, diff --git a/apps/sim/blocks/blocks/context_dev.test.ts b/apps/sim/blocks/blocks/context_dev.test.ts new file mode 100644 index 00000000000..62e6bcd215d --- /dev/null +++ b/apps/sim/blocks/blocks/context_dev.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest' +import { ContextDevBlock } from '@/blocks/blocks/context_dev' + +/** + * A tool call merges the stored row with the model's args (keyed by tool param names) and spreads + * the mapper result over them; the operation arrives only in `context`. + */ +const toolCall = (args: Record, operation: string) => ({ + ...args, + ...ContextDevBlock.tools.config?.params?.(args, { operation }), +}) + +describe('ContextDevBlock tool calls', () => { + it('parses an extraction schema the model sends as a JSON string', () => { + const params = toolCall( + { apiKey: 'key', url: 'https://example.com', schema: '{"type":"object"}', maxPages: 3 }, + 'extract' + ) + expect(params.schema).toEqual({ type: 'object' }) + expect(params.maxPages).toBe(3) + }) +}) diff --git a/apps/sim/blocks/blocks/context_dev.ts b/apps/sim/blocks/blocks/context_dev.ts index cc8eaadfb7e..98ff5574718 100644 --- a/apps/sim/blocks/blocks/context_dev.ts +++ b/apps/sim/blocks/blocks/context_dev.ts @@ -1,6 +1,7 @@ import { ContextDevIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation } from '@/blocks/utils' /** Operations whose primary input is a full page URL. */ const URL_OPS = [ @@ -628,9 +629,9 @@ Do not include any explanations, markdown formatting, or other text outside the config: { tool: (params) => params.operation ? `context_dev_${params.operation}` : 'context_dev_scrape_markdown', - params: (params) => { - const { operation, apiKey } = params - const result: Record = { apiKey } + params: (params, context) => { + const operation = mapperOperation(params, context) + const result: Record = { apiKey: params.apiKey } const setBool = (key: string) => { if (params[key] != null) result[key] = params[key] diff --git a/apps/sim/blocks/blocks/crunchbase.test.ts b/apps/sim/blocks/blocks/crunchbase.test.ts index 45f6c67c5ff..ed4c8805d6f 100644 --- a/apps/sim/blocks/blocks/crunchbase.test.ts +++ b/apps/sim/blocks/blocks/crunchbase.test.ts @@ -87,4 +87,23 @@ describe('CrunchbaseBlock', () => { expect(deleted.collection).toBe('people') expect(deleted.deletedCollection).toBeUndefined() }) + + /* + * A tool call merges the stored row with the model's args, keyed by the tool's + * param names, and carries the operation only in `context`. + */ + it('keeps the model args a tool call sends under the tool param names', () => { + const args = { + apiKey: 'key', + collection: 'organizations', + query: [{ type: 'predicate', field_id: 'num_employees_enum' }], + fieldIds: ['identifier'], + limit: 10, + } + const params = { ...args, ...buildParams(args, { operation: 'search_entities' }) } + expect(params.collection).toBe('organizations') + expect(params.query).toEqual(args.query) + expect(params.fieldIds).toEqual(['identifier']) + expect(params.limit).toBe(10) + }) }) diff --git a/apps/sim/blocks/blocks/crunchbase.ts b/apps/sim/blocks/blocks/crunchbase.ts index 0ed7810ed62..8d78ff352b9 100644 --- a/apps/sim/blocks/blocks/crunchbase.ts +++ b/apps/sim/blocks/blocks/crunchbase.ts @@ -2,7 +2,7 @@ import { Building, ListChecks, Search, Sprout, Trash, Users } from '@sim/emcn/ic import { CrunchbaseIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' import { CRUNCHBASE_CARD_COLLECTIONS, CRUNCHBASE_COLLECTIONS, @@ -394,8 +394,8 @@ export const CrunchbaseBlock: BlockConfig = { * advanced field is serialized on non-emptiness alone, even while the UI * hides it. `undefined` is what actually drops one. */ - params: (params) => { - const operation = String(params.operation ?? '') + params: (params, context) => { + const operation = mapperOperation(params, context) const isSearch = (SEARCH_OPERATIONS as readonly string[]).includes(operation) const isLookup = (LOOKUP_OPERATIONS as readonly string[]).includes(operation) const isCollectionScoped = (COLLECTION_OPERATIONS as readonly string[]).includes(operation) @@ -406,13 +406,16 @@ export const CrunchbaseBlock: BlockConfig = { const paginates = isSearch || isCard || isDeleted let query: unknown - if (isSearch) query = params.searchQuery - else if (isAutocomplete) query = params.autocompleteQuery + if (isSearch) query = params.searchQuery ?? toolCallArg(context, params.query) + else if (isAutocomplete) + query = params.autocompleteQuery ?? toolCallArg(context, params.query) let collection: unknown if (isCollectionScoped) collection = params.collection - else if (isCard) collection = params.cardCollection - else if (isDeleted) collection = params.deletedCollection + else if (isCard) + collection = params.cardCollection ?? toolCallArg(context, params.collection) + else if (isDeleted) + collection = params.deletedCollection ?? toolCallArg(context, params.collection) return { apiKey: params.apiKey, @@ -422,7 +425,7 @@ export const CrunchbaseBlock: BlockConfig = { cardId: isCard ? params.cardId : undefined, fieldIds: operation === 'search_entities' - ? params.searchFieldIds + ? (params.searchFieldIds ?? toolCallArg(context, params.fieldIds)) : isSearch || isLookup ? params.fieldIds : undefined, diff --git a/apps/sim/blocks/blocks/deployments.test.ts b/apps/sim/blocks/blocks/deployments.test.ts new file mode 100644 index 00000000000..6c6c2330a21 --- /dev/null +++ b/apps/sim/blocks/blocks/deployments.test.ts @@ -0,0 +1,13 @@ +import { describe, expect, it } from 'vitest' +import { DeploymentsBlock } from '@/blocks/blocks/deployments' + +describe('DeploymentsBlock params on a tool call', () => { + it('keeps the model version label and description for deploy', () => { + expect( + DeploymentsBlock.tools.config?.params?.( + { workflowId: 'wf-1', name: 'Release 4', description: 'Adds retries' }, + { operation: 'deployments_deploy' } + ) + ).toEqual({ workflowId: 'wf-1', name: 'Release 4', description: 'Adds retries' }) + }) +}) diff --git a/apps/sim/blocks/blocks/deployments.ts b/apps/sim/blocks/blocks/deployments.ts index b9e419a7ea6..187db8b7b37 100644 --- a/apps/sim/blocks/blocks/deployments.ts +++ b/apps/sim/blocks/blocks/deployments.ts @@ -1,5 +1,6 @@ import { Rocket } from '@sim/emcn/icons' import type { BlockConfig } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' const WORKFLOW_FIELD = ['workflowSelector', 'manualWorkflowId'] as const @@ -117,8 +118,8 @@ export const DeploymentsBlock: BlockConfig = { ], config: { tool: (params: Record) => params.operation || 'deployments_deploy', - params: (params: Record) => { - const operation = params.operation || 'deployments_deploy' + params: (params: Record, context) => { + const operation = mapperOperation(params, context) || 'deployments_deploy' const workflowId = typeof params.workflowId === 'string' ? params.workflowId.trim() : '' if (!workflowId) { throw new Error('Deployments Block Error: Workflow is required') @@ -127,8 +128,11 @@ export const DeploymentsBlock: BlockConfig = { if (operation === 'deployments_deploy') { return { workflowId, - name: params.versionName?.trim() || undefined, - description: params.versionDescription?.trim() || undefined, + name: params.versionName?.trim() || toolCallArg(context, params.name) || undefined, + description: + params.versionDescription?.trim() || + toolCallArg(context, params.description) || + undefined, } } diff --git a/apps/sim/blocks/blocks/docusign.test.ts b/apps/sim/blocks/blocks/docusign.test.ts index 75a3f62e05c..7176cd0b835 100644 --- a/apps/sim/blocks/blocks/docusign.test.ts +++ b/apps/sim/blocks/blocks/docusign.test.ts @@ -28,3 +28,17 @@ describe('DocuSign List Envelopes status filter', () => { expect(merged.envelopeStatus).toBe('completed') }) }) + +describe('DocuSign agent tool calls', () => { + it('sends the tool row Status setting for Send Envelope', () => { + const mapper = DocuSignBlock.tools.config?.params + if (!mapper) throw new Error('DocuSign block has no params mapper') + + const result = mapper( + { envelopeStatus: 'created', emailSubject: 'Sign', signerEmail: 'a@b.co', signerName: 'A' }, + { operation: 'send_envelope' } + ) + + expect(result.status).toBe('created') + }) +}) diff --git a/apps/sim/blocks/blocks/docusign.ts b/apps/sim/blocks/blocks/docusign.ts index 9efc2329b38..2f854966e70 100644 --- a/apps/sim/blocks/blocks/docusign.ts +++ b/apps/sim/blocks/blocks/docusign.ts @@ -2,7 +2,7 @@ import { DocuSignIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput, toolCallArg } from '@/blocks/utils' +import { mapperOperation, normalizeFileInput, toolCallArg } from '@/blocks/utils' const DOCUMENT_FIELD = ['uploadDocument', 'documentRef'] as const @@ -315,7 +315,8 @@ export const DocuSignBlock: BlockConfig = { config: { tool: (params) => `docusign_${params.operation}`, params: (params, context) => { - const { oauthCredential, operation, documentFile, listEnvelopeStatus, ...rest } = params + const { oauthCredential, documentFile, listEnvelopeStatus, ...rest } = params + const operation = mapperOperation(params, context) const cleanParams: Record = { oauthCredential, @@ -331,14 +332,13 @@ export const DocuSignBlock: BlockConfig = { * merges raw inputs under this result, so the list filter is always assigned explicitly: * otherwise that stored `sent` reached List Envelopes and "All" listed only sent envelopes. */ - if ((operation ?? context?.operation) === 'list_envelopes') { + if (operation === 'list_envelopes') { cleanParams.envelopeStatus = listEnvelopeStatus || toolCallArg(context, rest.envelopeStatus) || undefined } - if (operation === 'create_from_template') { - cleanParams.status = rest.envelopeStatus - } else if (operation === 'send_envelope') { + // A model-supplied `status` is copied over this by the loop below. + if (operation === 'create_from_template' || operation === 'send_envelope') { cleanParams.status = rest.envelopeStatus } diff --git a/apps/sim/blocks/blocks/downdetector.test.ts b/apps/sim/blocks/blocks/downdetector.test.ts new file mode 100644 index 00000000000..eac35c6b617 --- /dev/null +++ b/apps/sim/blocks/blocks/downdetector.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from 'vitest' +import { DowndetectorBlock } from '@/blocks/blocks/downdetector' + +describe('Downdetector agent tool calls', () => { + it('forwards the model page token for Get Site Companies', () => { + const mapper = DowndetectorBlock.tools.config?.params + if (!mapper) throw new Error('Downdetector block has no params mapper') + + const result = mapper( + { siteId: '12', page: 'opaque-token' }, + { operation: 'downdetector_get_site_companies' } + ) + + expect(result.page).toBe('opaque-token') + }) +}) diff --git a/apps/sim/blocks/blocks/downdetector.ts b/apps/sim/blocks/blocks/downdetector.ts index 68a9f570ec1..7d0e8411eb4 100644 --- a/apps/sim/blocks/blocks/downdetector.ts +++ b/apps/sim/blocks/blocks/downdetector.ts @@ -1,6 +1,7 @@ import { DowndetectorIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' const COMPANY_ID_OPERATIONS = [ 'downdetector_get_company', @@ -348,7 +349,7 @@ export const DowndetectorBlock: BlockConfig = { ], config: { tool: (params) => params.operation, - params: (params) => { + params: (params, context) => { const result: Record = {} if (params.categoryId) result.categoryId = Number(params.categoryId) if (params.pageSize) result.pageSize = Number(params.pageSize) @@ -359,8 +360,8 @@ export const DowndetectorBlock: BlockConfig = { // operation uses an integer page number. Always overwrite `page` (with the // token, a number, or undefined) so a stale value from a now-hidden field // can never leak into the wrong endpoint via the merged inputs. - if (params.operation === 'downdetector_get_site_companies') { - result.page = params.pageToken || undefined + if (mapperOperation(params, context) === 'downdetector_get_site_companies') { + result.page = params.pageToken || toolCallArg(context, params.page) || undefined } else { result.page = params.page ? Number(params.page) : undefined } diff --git a/apps/sim/blocks/blocks/dub.test.ts b/apps/sim/blocks/blocks/dub.test.ts new file mode 100644 index 00000000000..f67b3f5fa3f --- /dev/null +++ b/apps/sim/blocks/blocks/dub.test.ts @@ -0,0 +1,64 @@ +/** + * Workflow runs hand a tool `{ ...rawInputs, ...mappedParams }`, so the mapper must clear values + * another operation left in a shared subBlock. Agent tool calls pass the operation in context and + * supply arguments under the tool's param names, which the mapper must keep. + */ +import { describe, expect, it } from 'vitest' +import { DubBlock } from '@/blocks/blocks/dub' +import { createLinkTool } from '@/tools/dub/create_link' +import { getAnalyticsTool } from '@/tools/dub/get_analytics' +import type { ToolConfig } from '@/tools/types' + +function workflowParams(inputs: Record): Record { + return { ...inputs, ...(DubBlock.tools.config.params?.(inputs) ?? {}) } +} + +function agentParams(operation: string, args: Record): Record { + return { ...args, ...(DubBlock.tools.config.params?.(args, { operation }) ?? {}) } +} + +function requestUrl(tool: ToolConfig, params: Record): URL { + const url = tool.request.url + return new URL(typeof url === 'function' ? url(params) : url) +} + +function requestBody(tool: ToolConfig, params: Record) { + const body = tool.request.body + if (typeof body !== 'function') throw new Error(`${tool.id} has no request body`) + return body(params) +} + +describe('Dub block parameter mapping', () => { + it('keeps the destination, slug, and conversion flag an agent passes to Create Link', () => { + const params = agentParams('create_link', { + apiKey: 'dub_test', + url: 'https://sim.ai', + domain: 'go.sim.ai', + key: 'launch', + trackConversion: true, + }) + expect(requestBody(createLinkTool, params)).toEqual({ + url: 'https://sim.ai', + domain: 'go.sim.ai', + key: 'launch', + trackConversion: true, + }) + }) + + it('keeps the link and domain filters an agent passes to Get Analytics', () => { + const url = requestUrl( + getAnalyticsTool, + agentParams('get_analytics', { apiKey: 'dub_test', linkId: 'link_1', domain: 'go.sim.ai' }) + ) + expect(url.searchParams.get('linkId')).toBe('link_1') + expect(url.searchParams.get('domain')).toBe('go.sim.ai') + }) + + it('drops a create-link domain left behind when a workflow switches to Get Analytics', () => { + const url = requestUrl( + getAnalyticsTool, + workflowParams({ operation: 'get_analytics', apiKey: 'dub_test', domain: 'stale.sh' }) + ) + expect(url.searchParams.get('domain')).toBeNull() + }) +}) diff --git a/apps/sim/blocks/blocks/dub.ts b/apps/sim/blocks/blocks/dub.ts index 21fa25a17fb..4393a76784c 100644 --- a/apps/sim/blocks/blocks/dub.ts +++ b/apps/sim/blocks/blocks/dub.ts @@ -1,8 +1,8 @@ import { omit } from '@sim/utils/object' import { DubIcon } from '@/components/icons' -import type { BlockConfig, BlockMeta } from '@/blocks/types' +import type { BlockConfig, BlockMeta, BlockToolParamsContext } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { isToolCall, mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' const GET_LINK_FIELD = ['linkId', 'getLinkExternalId', 'getLinkKey'] as const const BULK_UPDATE_TARGET_FIELD = ['bulkUpdateLinkIds', 'bulkUpdateExternalIds'] as const @@ -1032,44 +1032,46 @@ export const DubBlock = { ], config: { tool: (params) => `dub_${params.operation}`, - params: (params) => { + params: (params, context?: BlockToolParamsContext) => { + const operation = mapperOperation(params, context) const result: Record = {} const isLinkMutation = - params.operation === 'create_link' || - params.operation === 'upsert_link' || - params.operation === 'update_link' + operation === 'create_link' || operation === 'upsert_link' || operation === 'update_link' - // The executor merges { ...inputs, ...transformedParams }, so a raw subBlock - // id that shares its name with a tool param (e.g. 'domain', 'linkId') passes - // through untouched unless explicitly cleared here. These fields are only - // shown for the operations below; every other operation must null them out - // so a value left over from a previous operation selection can't leak in. - if (!isLinkMutation) { - result.domain = undefined - result.key = undefined - result.title = undefined - result.description = undefined - result.externalId = undefined - result.tagIds = undefined - result.tenantId = undefined - result.folderId = undefined - result.trackConversion = undefined - } - if (params.operation !== 'create_link' && params.operation !== 'upsert_link') { - result.url = undefined - } - if ( - params.operation !== 'get_link' && - params.operation !== 'update_link' && - params.operation !== 'delete_link' - ) { - result.linkId = undefined - } - if (params.operation !== 'list_links') { - result.search = undefined - result.showArchived = undefined - result.page = undefined - result.pageSize = undefined + /** + * The canvas merges `{ ...inputs, ...mapped }`, so a raw subBlock id that shares its name + * with a tool param (e.g. `domain`, `linkId`) passes through unless cleared here, and a + * value left by another operation would leak in. A tool call carries the model's args + * under those same names for the selected tool, so nothing is cleared there. + */ + if (!isToolCall(context)) { + if (!isLinkMutation) { + result.domain = undefined + result.key = undefined + result.title = undefined + result.description = undefined + result.externalId = undefined + result.tagIds = undefined + result.tenantId = undefined + result.folderId = undefined + result.trackConversion = undefined + } + if (operation !== 'create_link' && operation !== 'upsert_link') { + result.url = undefined + } + if ( + operation !== 'get_link' && + operation !== 'update_link' && + operation !== 'delete_link' + ) { + result.linkId = undefined + } + if (operation !== 'list_links') { + result.search = undefined + result.showArchived = undefined + result.page = undefined + result.pageSize = undefined + } } if (isLinkMutation) { @@ -1077,20 +1079,26 @@ export const DubBlock = { if (params.linkArchived === 'true') result.archived = true if (params.tenantId) result.tenantId = params.tenantId if (params.folderId) result.folderId = params.folderId - // Only ever send `true` or omit — an explicit `false` on update_link would - // silently disable conversion tracking on links that already had it enabled, - // since Dub's update is a partial PATCH (matches linkRewrite/linkArchived). - result.trackConversion = params.trackConversion === 'true' ? true : undefined + // The dropdown only ever sends `true` or omits: a stored `false` on update_link would + // disable tracking on links that had it, since Dub's update is a partial PATCH. A tool + // call keeps the model's own boolean. + result.trackConversion = + params.trackConversion === 'true' + ? true + : toolCallArg( + context, + typeof params.trackConversion === 'boolean' ? params.trackConversion : undefined + ) } - if (params.operation === 'get_link') { + if (operation === 'get_link') { if (params.getLinkExternalId) result.externalId = params.getLinkExternalId if (params.getLinkDomain) result.domain = params.getLinkDomain if (params.getLinkKey) result.key = params.getLinkKey } - if (params.operation === 'update_link' && params.updateUrl) { + if (operation === 'update_link' && params.updateUrl) { result.url = params.updateUrl } - if (params.operation === 'list_links') { + if (operation === 'list_links') { if (params.listDomain) result.domain = params.listDomain if (params.listTagIds) result.tagIds = params.listTagIds if (params.listTenantId) result.tenantId = params.listTenantId @@ -1101,7 +1109,7 @@ export const DubBlock = { if (params.startingAfter) result.startingAfter = params.startingAfter if (params.endingBefore) result.endingBefore = params.endingBefore } - if (params.operation === 'get_analytics') { + if (operation === 'get_analytics') { if (params.analyticsEvent) result.event = params.analyticsEvent if (params.analyticsGroupBy) result.groupBy = params.analyticsGroupBy if (params.analyticsLinkId) result.linkId = params.analyticsLinkId @@ -1113,7 +1121,7 @@ export const DubBlock = { if (params.analyticsCountry) result.country = params.analyticsCountry if (params.analyticsTimezone) result.timezone = params.analyticsTimezone } - if (params.operation === 'get_links_count') { + if (operation === 'get_links_count') { if (params.countSearch) result.search = params.countSearch if (params.countDomain) result.domain = params.countDomain if (params.countTagIds) result.tagIds = params.countTagIds @@ -1122,18 +1130,18 @@ export const DubBlock = { if (params.countShowArchived === 'true') result.showArchived = true if (params.countGroupBy) result.groupBy = params.countGroupBy } - if (params.operation === 'bulk_create_links') { + if (operation === 'bulk_create_links') { if (params.bulkLinks) result.links = params.bulkLinks } - if (params.operation === 'bulk_update_links') { + if (operation === 'bulk_update_links') { if (params.bulkUpdateLinkIds) result.linkIds = params.bulkUpdateLinkIds if (params.bulkUpdateExternalIds) result.externalIds = params.bulkUpdateExternalIds if (params.bulkUpdateData) result.data = params.bulkUpdateData } - if (params.operation === 'bulk_delete_links') { + if (operation === 'bulk_delete_links') { if (params.bulkDeleteLinkIds) result.linkIds = params.bulkDeleteLinkIds } - if (params.operation === 'get_events') { + if (operation === 'get_events') { if (params.eventsEvent) result.event = params.eventsEvent if (params.eventsLinkId) result.linkId = params.eventsLinkId if (params.eventsExternalId) result.externalId = params.eventsExternalId @@ -1147,7 +1155,7 @@ export const DubBlock = { if (params.eventsPage) result.page = Number(params.eventsPage) if (params.eventsLimit) result.limit = Number(params.eventsLimit) } - if (params.operation === 'get_qr_code') { + if (operation === 'get_qr_code') { if (params.qrUrl) result.url = params.qrUrl if (params.qrLogo) result.logo = params.qrLogo if (params.qrSize) result.size = Number(params.qrSize) @@ -1157,24 +1165,24 @@ export const DubBlock = { if (params.qrHideLogo === 'true') result.hideLogo = true if (params.qrMargin) result.margin = Number(params.qrMargin) } - if (params.operation === 'list_domains') { + if (operation === 'list_domains') { if (params.domainsSearch) result.search = params.domainsSearch if (params.domainsArchived === 'true') result.archived = true if (params.domainsPage) result.page = Number(params.domainsPage) if (params.domainsPageSize) result.pageSize = Number(params.domainsPageSize) } - if (params.operation === 'list_tags') { + if (operation === 'list_tags') { if (params.tagsSearch) result.search = params.tagsSearch if (params.tagsSortBy) result.sortBy = params.tagsSortBy if (params.tagsSortOrder) result.sortOrder = params.tagsSortOrder if (params.tagsPage) result.page = Number(params.tagsPage) if (params.tagsPageSize) result.pageSize = Number(params.tagsPageSize) } - if (params.operation === 'create_tag') { + if (operation === 'create_tag') { if (params.tagName) result.name = params.tagName if (params.tagColor) result.color = params.tagColor } - if (params.operation === 'list_folders') { + if (operation === 'list_folders') { if (params.foldersSearch) result.search = params.foldersSearch if (params.foldersPage) result.page = Number(params.foldersPage) if (params.foldersPageSize) result.pageSize = Number(params.foldersPageSize) diff --git a/apps/sim/blocks/blocks/elevenlabs.test.ts b/apps/sim/blocks/blocks/elevenlabs.test.ts new file mode 100644 index 00000000000..c228cb5f503 --- /dev/null +++ b/apps/sim/blocks/blocks/elevenlabs.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from 'vitest' +import { ElevenLabsBlock } from '@/blocks/blocks/elevenlabs' + +describe('ElevenLabs agent tool calls', () => { + it('keeps the model voice settings for Edit Voice Settings', () => { + const mapper = ElevenLabsBlock.tools.config?.params + if (!mapper) throw new Error('ElevenLabs block has no params mapper') + + const result = mapper( + { apiKey: 'key', voiceId: 'voice-1', stability: 0.4, style: 0.2, speed: 1.1 }, + { operation: 'edit_voice_settings' } + ) + + expect(result).toMatchObject({ stability: 0.4, style: 0.2, speed: 1.1 }) + }) +}) diff --git a/apps/sim/blocks/blocks/elevenlabs.ts b/apps/sim/blocks/blocks/elevenlabs.ts index 070fc7bc67f..577f3aff755 100644 --- a/apps/sim/blocks/blocks/elevenlabs.ts +++ b/apps/sim/blocks/blocks/elevenlabs.ts @@ -1,6 +1,11 @@ import { ElevenLabsIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' -import { normalizeFileInput, withSavedCredential } from '@/blocks/utils' +import { + mapperOperation, + normalizeFileInput, + toolCallArg, + withSavedCredential, +} from '@/blocks/utils' const VOICE_OPERATIONS = [ 'tts', @@ -331,8 +336,9 @@ export const ElevenLabsBlock: BlockConfig = { ], config: { tool: (params) => `elevenlabs_${params.operation || 'tts'}`, - params: (params) => { + params: (params, context) => { const audioFile = normalizeFileInput(params.audioFile, { single: true }) + const isEditVoiceSettings = mapperOperation(params, context) === 'edit_voice_settings' return { apiKey: params.apiKey, text: params.text, @@ -343,17 +349,18 @@ export const ElevenLabsBlock: BlockConfig = { category: params.category || undefined, nextPageToken: params.nextPageToken || undefined, pageSize: toNumber(params.pageSize), - stability: toNumber( - params.operation === 'edit_voice_settings' ? params.editStability : params.stability - ), - similarityBoost: toNumber( - params.operation === 'edit_voice_settings' - ? params.editSimilarityBoost - : params.similarityBoost - ), - style: toNumber(params.editStyle), - speed: toNumber(params.editSpeed), - useSpeakerBoost: toBoolean(params.editUseSpeakerBoost), + stability: isEditVoiceSettings + ? (toNumber(params.editStability) ?? toNumber(toolCallArg(context, params.stability))) + : toNumber(params.stability), + similarityBoost: isEditVoiceSettings + ? (toNumber(params.editSimilarityBoost) ?? + toNumber(toolCallArg(context, params.similarityBoost))) + : toNumber(params.similarityBoost), + style: toNumber(params.editStyle) ?? toNumber(toolCallArg(context, params.style)), + speed: toNumber(params.editSpeed) ?? toNumber(toolCallArg(context, params.speed)), + useSpeakerBoost: + toBoolean(params.editUseSpeakerBoost) ?? + toBoolean(toolCallArg(context, params.useSpeakerBoost)), durationSeconds: toNumber(params.durationSeconds), promptInfluence: toNumber(params.promptInfluence), loop: toBoolean(params.loop), diff --git a/apps/sim/blocks/blocks/emailbison.test.ts b/apps/sim/blocks/blocks/emailbison.test.ts new file mode 100644 index 00000000000..b55dd5d991a --- /dev/null +++ b/apps/sim/blocks/blocks/emailbison.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from 'vitest' +import { EmailBisonBlock } from '@/blocks/blocks/emailbison' + +describe('Email Bison agent tool calls', () => { + it('keeps the model reply filters for List Replies', () => { + const mapper = EmailBisonBlock.tools.config?.params + if (!mapper) throw new Error('Email Bison block has no params mapper') + + const result = mapper( + { apiKey: 'key', status: 'interested', leadId: 7, tagIds: [3, 4] }, + { operation: 'list_replies' } + ) + + expect(result).toMatchObject({ status: 'interested', leadId: 7, tagIds: [3, 4] }) + }) + + it('keeps the model tag name for Create Tag', () => { + const mapper = EmailBisonBlock.tools.config?.params + if (!mapper) throw new Error('Email Bison block has no params mapper') + + const result = mapper({ apiKey: 'key', name: 'VIP' }, { operation: 'create_tag' }) + + expect(result.name).toBe('VIP') + }) +}) diff --git a/apps/sim/blocks/blocks/emailbison.ts b/apps/sim/blocks/blocks/emailbison.ts index 906fe981a87..2deaaf76726 100644 --- a/apps/sim/blocks/blocks/emailbison.ts +++ b/apps/sim/blocks/blocks/emailbison.ts @@ -1,7 +1,7 @@ import { EmailBisonIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { isToolCall, mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' import { getTrigger } from '@/triggers' const LEAD_MUTATION_OPERATIONS = ['create_lead', 'update_lead'] as const @@ -524,42 +524,58 @@ export const EmailBisonBlock: BlockConfig = { ], config: { tool: (params) => `emailbison_${params.operation}`, - params: (params) => ({ - apiBaseUrl: params.apiBaseUrl, - leadId: - params.operation === 'list_replies' ? toNumberParam(params.replyLeadId) : params.leadId, - leadIds: parseNumberList(params.leadIds), - tagIds: parseNumberList( - params.operation === 'attach_tags_to_leads' ? params.tagIds : params.filterTagIds - ), - excludedTagIds: parseNumberList(params.excludedTagIds), - customVariables: parseJsonArray(params.customVariables), - campaignId: toNumberParam(params.campaignId), - campaignType: emptyToUndefined(params.campaignType), - name: - params.operation === 'create_tag' || params.operation === 'create_campaign' - ? params.operation === 'create_tag' - ? params.tagName - : params.campaignName - : emptyToUndefined(params.campaignName), - action: params.action, - maxEmailsPerDay: toNumberParam(params.maxEmailsPerDay), - maxNewLeadsPerDay: toNumberParam(params.maxNewLeadsPerDay), - sequencePrioritization: emptyToUndefined(params.sequencePrioritization), - plainText: toBooleanParam(params.plainText), - openTracking: toBooleanParam(params.openTracking), - reputationBuilding: toBooleanParam(params.reputationBuilding), - canUnsubscribe: toBooleanParam(params.canUnsubscribe), - includeAutoRepliesInStats: toBooleanParam(params.includeAutoRepliesInStats), - allowParallelSending: toBooleanParam(params.allowParallelSending), - skipWebhooks: toBooleanParam(params.skipWebhooks), - withoutTags: toBooleanParam(params.withoutTags), - read: toBooleanParam(params.read), - senderEmailId: toNumberParam(params.senderEmailId), - campaignStatus: emptyToUndefined(params.campaignStatus), - status: - params.operation === 'list_replies' ? emptyToUndefined(params.replyStatus) : undefined, - }), + params: (params, context) => { + const operation = mapperOperation(params, context) + const toolCall = isToolCall(context) + /** A block-only field; on a tool call a blank one yields to the model's arg under the tool's param name. */ + const blockFieldOr = (blockValue: unknown, modelArg: unknown) => + toolCall ? (emptyToUndefined(blockValue) ?? modelArg) : blockValue + return { + apiBaseUrl: params.apiBaseUrl, + leadId: + operation === 'list_replies' + ? (toNumberParam(params.replyLeadId) ?? + toNumberParam(toolCallArg(context, params.leadId))) + : params.leadId, + leadIds: parseNumberList(params.leadIds), + tagIds: + operation === 'attach_tags_to_leads' + ? parseNumberList(params.tagIds) + : (parseNumberList(params.filterTagIds) ?? + parseNumberList(toolCallArg(context, params.tagIds))), + excludedTagIds: parseNumberList(params.excludedTagIds), + customVariables: parseJsonArray(params.customVariables), + campaignId: toNumberParam(params.campaignId), + campaignType: emptyToUndefined(params.campaignType), + name: + operation === 'create_tag' + ? blockFieldOr(params.tagName, params.name) + : operation === 'create_campaign' + ? blockFieldOr(params.campaignName, params.name) + : (emptyToUndefined(params.campaignName) ?? + emptyToUndefined(toolCallArg(context, params.name))), + action: params.action, + maxEmailsPerDay: toNumberParam(params.maxEmailsPerDay), + maxNewLeadsPerDay: toNumberParam(params.maxNewLeadsPerDay), + sequencePrioritization: emptyToUndefined(params.sequencePrioritization), + plainText: toBooleanParam(params.plainText), + openTracking: toBooleanParam(params.openTracking), + reputationBuilding: toBooleanParam(params.reputationBuilding), + canUnsubscribe: toBooleanParam(params.canUnsubscribe), + includeAutoRepliesInStats: toBooleanParam(params.includeAutoRepliesInStats), + allowParallelSending: toBooleanParam(params.allowParallelSending), + skipWebhooks: toBooleanParam(params.skipWebhooks), + withoutTags: toBooleanParam(params.withoutTags), + read: toBooleanParam(params.read), + senderEmailId: toNumberParam(params.senderEmailId), + campaignStatus: emptyToUndefined(params.campaignStatus), + status: + operation === 'list_replies' + ? (emptyToUndefined(params.replyStatus) ?? + emptyToUndefined(toolCallArg(context, params.status))) + : undefined, + } + }, }, }, inputs: { diff --git a/apps/sim/blocks/blocks/enrich.test.ts b/apps/sim/blocks/blocks/enrich.test.ts new file mode 100644 index 00000000000..7a50b724e4f --- /dev/null +++ b/apps/sim/blocks/blocks/enrich.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from 'vitest' +import { EnrichBlock } from '@/blocks/blocks/enrich' + +describe('Enrich agent tool calls', () => { + it('forwards the model company ID list and location for Search Jobs', () => { + const mapper = EnrichBlock.tools.config?.params + if (!mapper) throw new Error('Enrich block has no params mapper') + + const result = mapper( + { apiKey: 'key', keywords: 'engineer', companyIds: '2048, 3050', location: 'London' }, + { operation: 'search_jobs' } + ) + + expect(result).toMatchObject({ companyIds: '2048, 3050', location: 'London' }) + }) +}) diff --git a/apps/sim/blocks/blocks/enrich.ts b/apps/sim/blocks/blocks/enrich.ts index bc241787cb9..afa0a9a9c80 100644 --- a/apps/sim/blocks/blocks/enrich.ts +++ b/apps/sim/blocks/blocks/enrich.ts @@ -1,7 +1,7 @@ import { EnrichSoIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { isToolCall, mapperOperation, withSavedCredential } from '@/blocks/utils' /** * City and country are independent filters rather than a canonical pair, so the @@ -755,41 +755,51 @@ export const EnrichBlock: BlockConfig = { ], config: { tool: (params) => `enrich_${params.operation}`, - params: (params) => { - const { operation, ...rest } = params - const parsedParams: Record = { ...rest } + params: (params, context) => { + const operation = mapperOperation(params, context) + const toolCall = isToolCall(context) + /** A block-only field; on a tool call a blank one yields to the model's arg under the tool's param name. */ + const blockFieldOr = (blockValue: unknown, modelArg: unknown) => + toolCall && (blockValue === undefined || blockValue === null || blockValue === '') + ? modelArg + : blockValue + const parsedParams: Record = { ...params } try { - if (rest.currentJobTitles && typeof rest.currentJobTitles === 'string') { - parsedParams.currentJobTitles = JSON.parse(rest.currentJobTitles) + if (params.currentJobTitles && typeof params.currentJobTitles === 'string') { + parsedParams.currentJobTitles = JSON.parse(params.currentJobTitles) } - if (rest.skills && typeof rest.skills === 'string') { - parsedParams.skills = JSON.parse(rest.skills) + if (params.skills && typeof params.skills === 'string') { + parsedParams.skills = JSON.parse(params.skills) } - if (rest.industries && typeof rest.industries === 'string') { - parsedParams.industries = JSON.parse(rest.industries) + if (params.industries && typeof params.industries === 'string') { + parsedParams.industries = JSON.parse(params.industries) } - if (rest.companyIds && typeof rest.companyIds === 'string') { - parsedParams.companyIds = JSON.parse(rest.companyIds) + if ( + operation !== 'search_jobs' && + params.companyIds && + typeof params.companyIds === 'string' + ) { + parsedParams.companyIds = JSON.parse(params.companyIds) } - if (rest.jobTitles && typeof rest.jobTitles === 'string') { - parsedParams.jobTitles = JSON.parse(rest.jobTitles) + if (params.jobTitles && typeof params.jobTitles === 'string') { + parsedParams.jobTitles = JSON.parse(params.jobTitles) } - if (rest.accountLocation && typeof rest.accountLocation === 'string') { - parsedParams.accountLocation = JSON.parse(rest.accountLocation) + if (params.accountLocation && typeof params.accountLocation === 'string') { + parsedParams.accountLocation = JSON.parse(params.accountLocation) } - if (rest.employeeSizeRange && typeof rest.employeeSizeRange === 'string') { - parsedParams.employeeSizeRange = JSON.parse(rest.employeeSizeRange) + if (params.employeeSizeRange && typeof params.employeeSizeRange === 'string') { + parsedParams.employeeSizeRange = JSON.parse(params.employeeSizeRange) } - if (rest.filters && typeof rest.filters === 'string') { - parsedParams.filters = JSON.parse(rest.filters) + if (params.filters && typeof params.filters === 'string') { + parsedParams.filters = JSON.parse(params.filters) } } catch (error: any) { throw new Error(`Invalid JSON input: ${error.message}`) } if (operation === 'linkedin_profile') { - parsedParams.url = rest.linkedinUrl + parsedParams.url = blockFieldOr(params.linkedinUrl, params.url) parsedParams.linkedinUrl = undefined } if ( @@ -797,32 +807,32 @@ export const EnrichBlock: BlockConfig = { operation === 'linkedin_to_personal_email' || operation === 'phone_finder' ) { - parsedParams.linkedinProfile = rest.linkedinUrl + parsedParams.linkedinProfile = blockFieldOr(params.linkedinUrl, params.linkedinProfile) parsedParams.linkedinUrl = undefined } if (operation === 'company_lookup') { - parsedParams.name = rest.companyName + parsedParams.name = blockFieldOr(params.companyName, params.name) parsedParams.companyName = undefined } if (operation === 'search_company') { - parsedParams.name = rest.searchCompanyName + parsedParams.name = blockFieldOr(params.searchCompanyName, params.name) parsedParams.searchCompanyName = undefined } if (operation === 'search_similar_companies') { - parsedParams.url = rest.linkedinCompanyUrl + parsedParams.url = blockFieldOr(params.linkedinCompanyUrl, params.url) parsedParams.linkedinCompanyUrl = undefined } if (operation === 'get_post_details') { - parsedParams.url = rest.postUrl + parsedParams.url = blockFieldOr(params.postUrl, params.url) parsedParams.postUrl = undefined } if (operation === 'search_logo') { - parsedParams.url = rest.domain + parsedParams.url = blockFieldOr(params.domain, params.url) } if (operation === 'search_jobs') { - parsedParams.location = rest.jobLocation + parsedParams.location = blockFieldOr(params.jobLocation, params.location) parsedParams.jobLocation = undefined - parsedParams.companyIds = rest.jobCompanyIds + parsedParams.companyIds = blockFieldOr(params.jobCompanyIds, params.companyIds) parsedParams.jobCompanyIds = undefined } diff --git a/apps/sim/blocks/blocks/enrichment.test.ts b/apps/sim/blocks/blocks/enrichment.test.ts new file mode 100644 index 00000000000..c2e0c52ebe5 --- /dev/null +++ b/apps/sim/blocks/blocks/enrichment.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest' +import { EnrichmentBlock } from '@/blocks/blocks/enrichment' +import type { BlockToolParamsContext } from '@/blocks/types' + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = EnrichmentBlock.tools.config?.params + if (!mapper) throw new Error('Enrichment block has no params mapper') + return mapper(params, context) +} + +describe('Enrichment tool calls', () => { + it('runs the row enrichment with the model inputs when the operation arrives only in the context', () => { + expect(mapParams({ inputs: { domain: 'acme.com' } }, { operation: 'company-info' })).toEqual({ + enrichmentId: 'company-info', + inputs: { domain: 'acme.com' }, + }) + }) + + it('lets a value filled on the tool row override the model input', () => { + const mapped = mapParams( + { 'company-info__domain': 'stored.com', inputs: '{"domain":"model.com"}' }, + { operation: 'company-info' } + ) + expect(mapped.inputs).toEqual({ domain: 'stored.com' }) + }) + + it('keeps the model enrichment id when the tool row carries no operation', () => { + expect(mapParams({ enrichmentId: 'company-info' }, { operation: undefined }).enrichmentId).toBe( + 'company-info' + ) + }) +}) diff --git a/apps/sim/blocks/blocks/enrichment.ts b/apps/sim/blocks/blocks/enrichment.ts index 14e6f4f207d..b24c68a75f5 100644 --- a/apps/sim/blocks/blocks/enrichment.ts +++ b/apps/sim/blocks/blocks/enrichment.ts @@ -1,6 +1,8 @@ +import { isPlainRecord } from '@sim/utils/object' import { EnrichmentIcon } from '@/components/icons' import type { BlockConfig, BlockMeta, OutputFieldDefinition, ParamType } from '@/blocks/types' import { IntegrationType } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' import { ALL_ENRICHMENTS, getEnrichment } from '@/enrichments' import { mapFieldType } from '@/enrichments/providers' import type { EnrichmentOutputField } from '@/enrichments/types' @@ -8,6 +10,22 @@ import type { EnrichmentOutputField } from '@/enrichments/types' /** Stable subBlock id for an enrichment input (unique across enrichments). */ const inputFieldId = (enrichmentId: string, inputId: string) => `${enrichmentId}__${inputId}` +/** + * The `inputs` map a model passed on a tool call, as an object or its JSON text. Fields filled on + * the tool row override its entries. + */ +function parseModelInputs(value: unknown): Record { + if (typeof value === 'string') { + try { + const parsed: unknown = JSON.parse(value) + return isPlainRecord(parsed) ? parsed : {} + } catch { + return {} + } + } + return isPlainRecord(value) ? value : {} +} + // One input field per (enrichment, input), shown only for its enrichment. const inputSubBlocks = ALL_ENRICHMENTS.flatMap((enrichment) => enrichment.inputs.map((input) => ({ @@ -141,16 +159,19 @@ export const EnrichmentBlock: BlockConfig = { access: ['enrichment_run'], config: { tool: () => 'enrichment_run', - params: (params) => { - const enrichment = getEnrichment(params.operation) - const inputs: Record = {} + params: (params, context) => { + const operation = mapperOperation(params, context) + const enrichment = getEnrichment(operation) + const inputs: Record = { + ...parseModelInputs(toolCallArg(context, params.inputs)), + } if (enrichment) { for (const input of enrichment.inputs) { const value = params[inputFieldId(enrichment.id, input.id)] if (value !== undefined && value !== '') inputs[input.id] = value } } - return { enrichmentId: params.operation, inputs } + return { enrichmentId: operation || params.enrichmentId, inputs } }, }, }, diff --git a/apps/sim/blocks/blocks/exa.test.ts b/apps/sim/blocks/blocks/exa.test.ts new file mode 100644 index 00000000000..a828ea1ba38 --- /dev/null +++ b/apps/sim/blocks/blocks/exa.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from 'vitest' +import { ExaBlock } from '@/blocks/blocks/exa' +import type { BlockToolParamsContext } from '@/blocks/types' + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = ExaBlock.tools.config?.params + if (!mapper) throw new Error('Exa block has no params mapper') + return mapper(params, context) +} + +describe('Exa legacy Research tool rows', () => { + it('maps the stored research model to an Agent effort when the operation arrives only in the context', () => { + expect( + mapParams({ query: 'q', model: 'exa-research-pro' }, { operation: 'exa_research' }).effort + ).toBe('high') + }) +}) diff --git a/apps/sim/blocks/blocks/exa.ts b/apps/sim/blocks/blocks/exa.ts index 91909da489d..f650d0b5c1a 100644 --- a/apps/sim/blocks/blocks/exa.ts +++ b/apps/sim/blocks/blocks/exa.ts @@ -1,6 +1,7 @@ import { ExaAIIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation } from '@/blocks/utils' /** Categories Exa currently supports. Shared by Search and Find Similar Links. */ const CATEGORY_OPTIONS = [ @@ -588,7 +589,7 @@ export const ExaBlock: BlockConfig = { return 'exa_search' } }, - params: (params) => { + params: (params, context) => { const result: Record = {} if (params.numResults) { result.numResults = Number(params.numResults) @@ -614,7 +615,7 @@ export const ExaBlock: BlockConfig = { * unset value maps to the same depth rather than falling through to * the Agent default of `auto`. */ - if (params.operation === LEGACY_RESEARCH_OPERATION) { + if (mapperOperation(params, context) === LEGACY_RESEARCH_OPERATION) { result.effort = RESEARCH_MODEL_TO_EFFORT[params.model as string] ?? 'medium' } return result diff --git a/apps/sim/blocks/blocks/file.test.ts b/apps/sim/blocks/blocks/file.test.ts index 4355c17297e..1dfa1a1cc32 100644 --- a/apps/sim/blocks/blocks/file.test.ts +++ b/apps/sim/blocks/blocks/file.test.ts @@ -186,4 +186,89 @@ describe('FileV5Block', () => { }) ).toThrow('Manage Sharing accepts a single file at a time') }) + + describe('on a tool call, where the operation arrives only in context', () => { + it('sends the file picked on a Get Content row', () => { + expect( + FileV5Block.tools.config?.params?.( + { getContentInput: 'file-1', offset: 5 }, + { operation: 'file_get_content' } + ) + ).toEqual({ fileId: ['file-1'], workspaceId: undefined }) + }) + + it('keeps the model folder the canonical pass republished as folderRef on write', () => { + expect( + FileV5Block.tools.config?.params?.( + { fileName: 'notes.md', content: 'hi', folderRef: '/Reports' }, + { operation: 'file_write' } + ) + ).toMatchObject({ fileName: 'notes.md', folderPath: '/Reports', content: 'hi' }) + }) + + it('moves the model-named folder under the destination parent the row pins', () => { + expect( + FileV5Block.tools.config?.params?.( + { destinationParentRef: '/Archive', path: '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/Reports/Q1', destinationPath: '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/Other/Q1' }, + { operation: 'file_update_folder' } + ) + ).toMatchObject({ path: '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/Reports/Q1', destinationPath: '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/Archive/Q1' }) + }) + + it('creates the model-named folder under the parent the row pins', () => { + expect( + FileV5Block.tools.config?.params?.( + { createParentRef: '/Reports', path: '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/Other/New' }, + { operation: 'file_create_folder' } + ) + ).toMatchObject({ path: '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/Reports/New' }) + }) + + it('keeps the model path for Create Folder when the row pins no parent', () => { + expect( + FileV5Block.tools.config?.params?.( + { path: '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/Other/New' }, + { operation: 'file_create_folder' } + ) + ).toMatchObject({ path: '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/Other/New' }) + }) + + /** The tool-call executor spreads the mapper result over the merged row and model params. */ + const toolCallRequest = (params: Record, operation: string) => ({ + ...params, + ...FileV5Block.tools.config?.params?.(params, { operation }), + }) + + it('sends only the row folder on Append when the model also names folderPaths', () => { + const request = toolCallRequest( + { + folderScopeRef: '/Reports', + fileName: 'notes.md', + content: 'x', + folderPaths: ['/Reports'], + }, + 'file_append' + ) + expect(request).toMatchObject({ fileName: 'notes.md', folderPath: '/Reports', content: 'x' }) + expect(request.folderPaths).toBeUndefined() + }) + + it('sends only the model folderPath on Edit when the model names both folder args', () => { + const request = toolCallRequest( + { fileName: 'notes.md', content: 'x', folderRef: '/Reports', folderPaths: ['/Other'] }, + 'file_edit' + ) + expect(request).toMatchObject({ fileName: 'notes.md', folderPath: '/Reports' }) + expect(request.folderPaths).toBeUndefined() + }) + + it('keeps the model folderPaths on Append when the row pins no folder', () => { + const request = toolCallRequest( + { fileName: 'notes.md', content: 'x', folderPaths: ['/Reports', '/Archive'] }, + 'file_append' + ) + expect(request.folderPaths).toEqual(['/Reports', '/Archive']) + expect(request.folderPath).toBeUndefined() + }) + }) }) diff --git a/apps/sim/blocks/blocks/file.ts b/apps/sim/blocks/blocks/file.ts index 628f34a5170..4f54fcd88f3 100644 --- a/apps/sim/blocks/blocks/file.ts +++ b/apps/sim/blocks/blocks/file.ts @@ -8,12 +8,15 @@ import { } from '@/lib/folders/paths' import { readFolderPaths } from '@/lib/folders/selection' import { inferContextFromKey } from '@/lib/uploads/utils/file' -import type { BlockConfig, SubBlockType } from '@/blocks/types' +import type { BlockConfig, BlockToolParamsContext, SubBlockType } from '@/blocks/types' import { IntegrationType } from '@/blocks/types' import { createVersionedToolSelector, + isToolCall, + mapperOperation, normalizeFileInput, parseOptionalNumberInput, + toolCallArg, } from '@/blocks/utils' const logger = createLogger('FileBlock') @@ -184,7 +187,8 @@ interface FileFamilyParams { function fileFamilyInput( params: FileFamilyParams, label: string, - pickerValue: unknown + pickerValue: unknown, + context?: BlockToolParamsContext ): Record { const workspaceId = params._context?.workspaceId const fileIds = pickerValue ? parseReadFileIds(pickerValue) : null @@ -195,6 +199,9 @@ function fileFamilyInput( const folderPaths = folderScopePaths(params.folderScopeRef) if (!folderPaths) { + /* A tool call names its target in the tool's own `fileId` / `folderPaths` args, + which the merged params already carry. */ + if (isToolCall(context)) return { workspaceId } throw new Error(`File or folder is required for ${label}`) } return { @@ -275,6 +282,34 @@ function namedFileTarget( } } +/** + * {@link namedFileTarget} for a mapper that also runs on tool calls, where the stored picker may + * be empty and the model names the file with the tool's own `fileName` and `folderPath` args. The + * model's folder applies only to the model's name, and never beside a scope the row already pins. + * + * The result is spread over the merged row and model params, so a folder arg the model sent stays + * in the request unless it is cleared here; the tool refuses `folderPath` and `folderPaths` together. + */ +function namedFileTargetWithModelFolder( + params: FileFamilyParams & { fileName?: unknown }, + pickerValue: unknown, + label: string, + context: BlockToolParamsContext | undefined, + modelFolderPath: string | undefined +): ReturnType { + const target = namedFileTarget( + params, + pickerValue || toolCallArg(context, params.fileName), + label + ) + if (!isToolCall(context)) return target + if (pickerValue || target.folderPath || target.folderPaths) { + return { folderPath: undefined, folderPaths: undefined, ...target } + } + if (!modelFolderPath) return target + return { ...target, folderPath: modelFolderPath, folderPaths: undefined } +} + /** * A whole number above zero, or nothing. * @@ -663,8 +698,8 @@ export const FileV3Block: BlockConfig = { access: ['file_parser_v3', 'file_get', 'file_write', 'file_append'], config: { tool: (params) => params.operation || 'file_parser_v3', - params: (params) => { - const operation = params.operation || 'file_parser_v3' + params: (params, context) => { + const operation = mapperOperation(params, context) || 'file_parser_v3' if (operation === 'file_write') { return { @@ -676,7 +711,7 @@ export const FileV3Block: BlockConfig = { } if (operation === 'file_append') { - const appendInput = params.appendFileInput + const appendInput = params.appendFileInput || toolCallArg(context, params.fileName) if (!appendInput) { throw new Error('File is required for append') } @@ -696,13 +731,13 @@ export const FileV3Block: BlockConfig = { return { fileName, - content: params.appendContent, + content: params.appendContent ?? toolCallArg(context, params.content), workspaceId: params._context?.workspaceId, } } if (operation === 'file_get') { - const getInput = params.getFileInput + const getInput = params.getFileInput || toolCallArg(context, params.fileId) if (!getInput) { throw new Error('File is required for get') } @@ -974,8 +1009,8 @@ export const FileV4Block: BlockConfig = { if (operation === 'file_fetch') return 'file_fetch' return operation }, - params: (params) => { - const operation = params.operation || 'file_read' + params: (params, context) => { + const operation = mapperOperation(params, context) || 'file_read' if (operation === 'file_write') { return { @@ -987,7 +1022,7 @@ export const FileV4Block: BlockConfig = { } if (operation === 'file_append') { - const appendInput = params.appendFileInput + const appendInput = params.appendFileInput || toolCallArg(context, params.fileName) if (!appendInput) { throw new Error('File is required for append') } @@ -1007,13 +1042,13 @@ export const FileV4Block: BlockConfig = { return { fileName, - content: params.appendContent, + content: params.appendContent ?? toolCallArg(context, params.content), workspaceId: params._context?.workspaceId, } } if (operation === 'file_read') { - const readInput = params.readFileInput + const readInput = params.readFileInput || toolCallArg(context, params.fileId) if (!readInput) { throw new Error('File is required for read') } @@ -1930,8 +1965,13 @@ export const FileV5Block: BlockConfig = { ], config: { tool: (params) => params.operation || 'file_read', - params: (params) => { - const operation = params.operation || 'file_read' + params: (params, context) => { + const operation = mapperOperation(params, context) || 'file_read' + /** + * A tool call's `folderPath` arg shares its name with the basic half of the `folderRef` + * pair, so the canonical pass republishes it as `folderRef`. Read on tool calls only. + */ + const modelFolderPath = toolCallArg(context, optionalText(params.folderRef)) if (operation === 'file_search') { const maxResultsInput = @@ -1968,7 +2008,7 @@ export const FileV5Block: BlockConfig = { Boolean(fileInput) && (params.content == null || params.content === '') return { fileName: params.fileName, - folderPath: optionalText(params.writeFolderRef), + folderPath: optionalText(params.writeFolderRef) ?? modelFolderPath, content: omitContent ? undefined : params.content, ...(fileInput ? { fileInput } : {}), contentType: params.contentType ?? undefined, @@ -1979,21 +2019,26 @@ export const FileV5Block: BlockConfig = { if (operation === 'file_list') { return { - path: optionalText(params.folderRef), - recursive: switchValue(params.folderRecursive), + path: optionalText(params.folderRef) ?? toolCallArg(context, params.path), + recursive: switchValue( + params.folderRecursive, + switchValue(toolCallArg(context, params.recursive)) + ), /* Bounded here as well as at the contract, so a typo fails while configuring rather than on the first run. */ - depth: parseOptionalNumberInput(params.folderDepth, 'Max Depth', { - integer: true, - min: 1, - max: MAX_FOLDER_PATH_SEGMENTS, - }), - search: optionalText(params.folderSearch), - limit: parseOptionalNumberInput(params.folderLimit, 'Limit', { - integer: true, - min: 1, - max: MAX_FILE_LIST_LIMIT, - }), + depth: + parseOptionalNumberInput(params.folderDepth, 'Max Depth', { + integer: true, + min: 1, + max: MAX_FOLDER_PATH_SEGMENTS, + }) ?? toolCallArg(context, params.depth), + search: optionalText(params.folderSearch) ?? toolCallArg(context, params.search), + limit: + parseOptionalNumberInput(params.folderLimit, 'Limit', { + integer: true, + min: 1, + max: MAX_FILE_LIST_LIMIT, + }) ?? toolCallArg(context, params.limit), workspaceId: params._context?.workspaceId, } } @@ -2006,9 +2051,17 @@ export const FileV5Block: BlockConfig = { * tool takes a canonical path. */ const name = optionalText(params.folderName) - const parentPrefix = folderPathPrefix(optionalText(params.createParentRef)) + const createParent = optionalText(params.createParentRef) + const parentPrefix = folderPathPrefix(createParent) + /* A model-supplied path keeps only its last segment when the row pins a parent. */ + const modelPath = toolCallArg(context, optionalText(params.path)) + const modelSegment = modelPath?.split('/').filter(Boolean).pop() return { - path: name ? `${parentPrefix}/${encodeFolderPathSegment(name)}` : undefined, + path: name + ? `${parentPrefix}/${encodeFolderPathSegment(name)}` + : createParent && modelSegment + ? `${parentPrefix}/${modelSegment}` + : modelPath, workspaceId: params._context?.workspaceId, } } @@ -2021,80 +2074,106 @@ export const FileV5Block: BlockConfig = { * carried from the source path's last segment. An unset parent means * the workspace root. Renaming is not a move and is not offered here. */ - const sourcePath = optionalText(params.folderRef) + const sourcePath = + optionalText(params.folderRef) ?? toolCallArg(context, optionalText(params.path)) const segment = sourcePath?.split('/').pop() - const parentPrefix = folderPathPrefix(optionalText(params.destinationParentRef)) + const destinationParent = optionalText(params.destinationParentRef) + const parentPrefix = folderPathPrefix(destinationParent) + /* A model-supplied full destination applies unless the row pins a destination parent. */ + const modelDestination = destinationParent + ? undefined + : toolCallArg(context, optionalText(params.destinationPath)) return { path: sourcePath, - destinationPath: segment ? `${parentPrefix}/${segment}` : undefined, + destinationPath: + modelDestination ?? (segment ? `${parentPrefix}/${segment}` : undefined), workspaceId: params._context?.workspaceId, } } if (operation === 'file_delete_folder') { return { - path: optionalText(params.folderRef), - recursive: switchValue(params.deleteFolderRecursive), + path: optionalText(params.folderRef) ?? toolCallArg(context, params.path), + recursive: switchValue( + params.deleteFolderRecursive, + switchValue(toolCallArg(context, params.recursive)) + ), workspaceId: params._context?.workspaceId, } } if (operation === 'file_move') { return { - fileId: optionalText(params.moveFileId), - folderPath: optionalText(params.moveTargetRef), + fileId: optionalText(params.moveFileId) ?? toolCallArg(context, params.fileId), + folderPath: optionalText(params.moveTargetRef) ?? modelFolderPath, workspaceId: params._context?.workspaceId, } } if (operation === 'file_restore_folder') { return { - folderId: optionalText(params.restoreFolderId), + folderId: optionalText(params.restoreFolderId) ?? toolCallArg(context, params.folderId), workspaceId: params._context?.workspaceId, } } if (operation === 'file_append') { return { - ...namedFileTarget(params, params.appendFileInput, 'append'), - content: params.appendContent, + ...namedFileTargetWithModelFolder( + params, + params.appendFileInput, + 'append', + context, + modelFolderPath + ), + content: params.appendContent ?? toolCallArg(context, params.content), workspaceId: params._context?.workspaceId, } } if (operation === 'file_edit') { - const mode = optionalText(params.editMode) ?? 'search_replace' + const mode = + optionalText(params.editMode) ?? + toolCallArg(context, optionalText(params.mode)) ?? + 'search_replace' if (!FILE_EDIT_MODES.has(mode)) throw new Error('Edit Type is invalid') return { - ...namedFileTarget(params, params.editFileInput, 'edit'), + ...namedFileTargetWithModelFolder( + params, + params.editFileInput, + 'edit', + context, + modelFolderPath + ), mode, - search: params.editSearch, - content: params.editContent ?? '', + search: params.editSearch ?? toolCallArg(context, params.search), + content: params.editContent ?? toolCallArg(context, params.content) ?? '', replaceAll: switchValue(params.replaceAll), beforeAnchor: params.beforeAnchor, afterAnchor: params.afterAnchor, anchor: params.anchor, startAnchor: params.startAnchor, endAnchor: params.endAnchor, - occurrence: parseOptionalNumberInput(params.editOccurrence, 'Anchor Occurrence', { - integer: true, - min: 1, - }), + occurrence: + parseOptionalNumberInput(params.editOccurrence, 'Anchor Occurrence', { + integer: true, + min: 1, + }) ?? toolCallArg(context, params.occurrence), workspaceId: params._context?.workspaceId, } } if (operation === 'file_compress') { return { - ...fileFamilyInput(params, 'compress', params.compressInput), + ...fileFamilyInput(params, 'compress', params.compressInput, context), archiveName: optionalText(params.archiveName), } } if (operation === 'file_decompress') { - const decompressInput = params.decompressInput + const decompressInput = params.decompressInput || toolCallArg(context, params.fileId) if (!decompressInput) { throw new Error('File is required for decompress') } @@ -2126,26 +2205,34 @@ export const FileV5Block: BlockConfig = { } if (operation === 'file_manage_sharing') { - const shareInput = params.shareInput + const shareInput = params.shareInput || toolCallArg(context, params.fileId) if (!shareInput) { throw new Error('File is required to manage sharing') } - const allowedEmails = + const rowEmails = typeof params.shareAllowedEmails === 'string' ? params.shareAllowedEmails .split(/[\n,]/) .map((email) => email.trim()) .filter(Boolean) : undefined + const allowedEmails = rowEmails?.length + ? rowEmails + : (toolCallArg(context, params.allowedEmails) ?? rowEmails) + /* A tool row has no visibility dropdown, so a tool call states the link + with the tool's own `isActive` / `authType` args. */ + const modelSharing = !params.shareVisibility && isToolCall(context) const visibility = (params.shareVisibility as string) || 'public' - const isActive = visibility !== 'private' + const isActive = modelSharing + ? switchValue(params.isActive, true) + : visibility !== 'private' const shareParams = { isActive, // When disabling, leave authType unset so the stored access mode is preserved. - authType: isActive ? visibility : undefined, - password: params.sharePassword, + authType: isActive ? (modelSharing ? params.authType : visibility) : undefined, + password: params.sharePassword ?? toolCallArg(context, params.password), allowedEmails, workspaceId: params._context?.workspaceId, } @@ -2189,13 +2276,13 @@ export const FileV5Block: BlockConfig = { const range = optionalPositiveInt(params.contentOffset, 'Start Line') const count = optionalPositiveInt(params.contentLimit, 'Line Count') return { - ...fileFamilyInput(params, 'get content', params.getContentInput), + ...fileFamilyInput(params, 'get content', params.getContentInput, context), ...(range === undefined ? {} : { offset: range }), ...(count === undefined ? {} : { limit: count }), } } - return fileFamilyInput(params, 'read', params.readFileInput) + return fileFamilyInput(params, 'read', params.readFileInput, context) }, }, }, diff --git a/apps/sim/blocks/blocks/firecrawl.test.ts b/apps/sim/blocks/blocks/firecrawl.test.ts new file mode 100644 index 00000000000..fd3dab6b31a --- /dev/null +++ b/apps/sim/blocks/blocks/firecrawl.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from 'vitest' +import { FirecrawlBlock } from '@/blocks/blocks/firecrawl' +import type { BlockToolParamsContext } from '@/blocks/types' + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = FirecrawlBlock.tools.config?.params + if (!mapper) throw new Error('Firecrawl block has no params mapper') + return mapper(params, context) +} + +describe('Firecrawl tool calls', () => { + it('sends Parse a single document when the model passes it in a list', () => { + const file = { id: 'file-1' } + expect(mapParams({ file: [file] }, { operation: 'parse' }).file).toEqual(file) + }) +}) diff --git a/apps/sim/blocks/blocks/firecrawl.ts b/apps/sim/blocks/blocks/firecrawl.ts index 323f3b8a4b3..128bb994734 100644 --- a/apps/sim/blocks/blocks/firecrawl.ts +++ b/apps/sim/blocks/blocks/firecrawl.ts @@ -1,7 +1,7 @@ import { FirecrawlIcon } from '@/components/icons' import type { BlockConfig, BlockMeta, SubBlockType } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput } from '@/blocks/utils' +import { mapperOperation, normalizeFileInput } from '@/blocks/utils' /** The document being parsed, whether it was uploaded or passed in by reference. */ const DOCUMENT_FIELD = ['fileUpload', 'fileReference'] as const @@ -592,9 +592,9 @@ Example 2 - Product Data: return 'firecrawl_scrape' } }, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { - operation, limit, urls, formats, diff --git a/apps/sim/blocks/blocks/fireflies.test.ts b/apps/sim/blocks/blocks/fireflies.test.ts new file mode 100644 index 00000000000..06ee181af64 --- /dev/null +++ b/apps/sim/blocks/blocks/fireflies.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from 'vitest' +import { FirefliesBlock, FirefliesV2Block } from '@/blocks/blocks/fireflies' +import type { BlockConfig, BlockToolParamsContext } from '@/blocks/types' + +function mapParams( + block: BlockConfig, + params: Record, + context?: BlockToolParamsContext +) { + const mapper = block.tools.config?.params + if (!mapper) throw new Error('Fireflies block has no params mapper') + return mapper(params, context) +} + +describe('Fireflies tool calls', () => { + it('uploads a picked file by its https URL when the operation arrives only in the context', () => { + const mapped = mapParams( + FirefliesV2Block, + { audioFile: { name: 'call.mp3', url: 'https://files.example.com/call.mp3' } }, + { operation: 'fireflies_upload_audio' } + ) + expect(mapped.audioUrl).toBe('https://files.example.com/call.mp3') + expect(mapped.audioFile).toBeUndefined() + }) + + it('keeps the model bite name and a zero start time', () => { + const mapped = mapParams( + FirefliesBlock, + { transcriptId: 't1', startTime: 0, endTime: 30, name: 'Intro', summary: 'Opening' }, + { operation: 'fireflies_create_bite' } + ) + expect(mapped).toMatchObject({ startTime: 0, endTime: 30, name: 'Intro', summary: 'Opening' }) + }) +}) diff --git a/apps/sim/blocks/blocks/fireflies.ts b/apps/sim/blocks/blocks/fireflies.ts index f2da0288c59..cf971fff653 100644 --- a/apps/sim/blocks/blocks/fireflies.ts +++ b/apps/sim/blocks/blocks/fireflies.ts @@ -3,11 +3,21 @@ import { FirefliesIcon } from '@/components/icons' import { resolveHttpsUrlFromFileInput } from '@/lib/uploads/utils/file' 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' import { getTrigger } from '@/triggers' const AUDIO_FILE_FIELD = ['audioFile', 'audioFileReference'] as const +/** A bite boundary the caller never set; `0` is a valid start time. */ +function isBlankTime(value: unknown): boolean { + return value === undefined || value === null || value === '' +} + export const FirefliesBlock: BlockConfig = { type: 'fireflies', name: 'Fireflies (Legacy)', @@ -523,12 +533,12 @@ Return ONLY the summary text - no quotes, no labels.`, tool: (params) => { return params.operation || 'fireflies_list_transcripts' }, - params: (params) => { + params: (params, context) => { const baseParams: Record = { apiKey: params.apiKey, } - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'fireflies_list_transcripts': return { ...baseParams, @@ -605,7 +615,7 @@ Return ONLY the summary text - no quotes, no labels.`, if (!params.transcriptId?.trim()) { throw new Error('Transcript ID is required.') } - if (!params.startTime || !params.endTime) { + if (isBlankTime(params.startTime) || isBlankTime(params.endTime)) { throw new Error('Start time and end time are required.') } return { @@ -613,16 +623,17 @@ Return ONLY the summary text - no quotes, no labels.`, transcriptId: params.transcriptId.trim(), startTime: Number(params.startTime), endTime: Number(params.endTime), - name: params.biteName?.trim() || undefined, + name: params.biteName?.trim() || toolCallArg(context, params.name) || undefined, mediaType: params.mediaType?.trim() || undefined, - summary: params.biteSummary?.trim() || undefined, + summary: + params.biteSummary?.trim() || toolCallArg(context, params.summary) || undefined, } case 'fireflies_list_bites': return { ...baseParams, transcriptId: params.transcriptId?.trim() || undefined, - mine: true, + mine: toolCallArg(context, params.mine) ?? true, limit: params.limit ? Number(params.limit) : undefined, skip: params.skip ? Number(params.skip) : undefined, } @@ -717,16 +728,18 @@ export const FirefliesV2Block: BlockConfig = { FirefliesBlock.tools?.config?.tool ? FirefliesBlock.tools.config.tool(params) : params.operation || 'fireflies_list_transcripts', - params: (params) => { + params: (params, context) => { const baseParams = FirefliesBlock.tools?.config?.params if (!baseParams) { return params } - if (params.operation === 'fireflies_upload_audio') { - // Use canonical 'audioFile' param directly + if (mapperOperation(params, context) === 'fireflies_upload_audio') { const audioFile = normalizeFileInput(params.audioFile, { single: true }) if (!audioFile) { + if (toolCallArg(context, params.audioUrl?.trim())) { + return baseParams(params, context) + } throw new Error('Audio file is required.') } const audioUrl = resolveHttpsUrlFromFileInput(audioFile) @@ -734,14 +747,17 @@ export const FirefliesV2Block: BlockConfig = { throw new Error('Audio file must include a https URL.') } - return baseParams({ - ...params, - audioUrl, - audioFile: undefined, - }) + return baseParams( + { + ...params, + audioUrl, + audioFile: undefined, + }, + context + ) } - return baseParams(params) + return baseParams(params, context) }, }, }, diff --git a/apps/sim/blocks/blocks/flint.ts b/apps/sim/blocks/blocks/flint.ts index 02be8b453c4..2ce183ee4f6 100644 --- a/apps/sim/blocks/blocks/flint.ts +++ b/apps/sim/blocks/blocks/flint.ts @@ -1,7 +1,7 @@ import { FlintIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, withSavedCredential } from '@/blocks/utils' /** * Coerces the publish switch value to an explicit boolean, preserving an @@ -155,10 +155,10 @@ Return ONLY the raw JSON array starting with [ and ending with ] - no explanatio access: ['flint_create_task', 'flint_generate_pages', 'flint_get_task'], config: { tool: (params) => params.operation || 'flint_create_task', - params: (params) => { + params: (params, context) => { const base: Record = { apiKey: params.apiKey } - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'flint_generate_pages': return { ...base, diff --git a/apps/sim/blocks/blocks/gong.test.ts b/apps/sim/blocks/blocks/gong.test.ts new file mode 100644 index 00000000000..5d13dd8b9f7 --- /dev/null +++ b/apps/sim/blocks/blocks/gong.test.ts @@ -0,0 +1,20 @@ +/** + * Agent tool calls pass the operation in context and supply arguments under the tool's param + * names, which the mapper spreads over and must keep. + */ +import { describe, expect, it } from 'vitest' +import { GongBlock } from '@/blocks/blocks/gong' + +function agentParams(operation: string, args: Record): Record { + return { ...args, ...(GongBlock.tools.config?.params?.(args, { operation }) ?? {}) } +} + +describe('GongBlock agent tool calls', () => { + it('keeps the model flowId when unassigning flow prospects', () => { + const params = agentParams('unassign_flow_prospects', { + crmProspectId: 'lead-1', + flowId: 'flow-9', + }) + expect(params.flowId).toBe('flow-9') + }) +}) diff --git a/apps/sim/blocks/blocks/gong.ts b/apps/sim/blocks/blocks/gong.ts index 7599830cc87..938bf3b09f5 100644 --- a/apps/sim/blocks/blocks/gong.ts +++ b/apps/sim/blocks/blocks/gong.ts @@ -1,6 +1,6 @@ import { GongIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' import { getTrigger } from '@/triggers' export const GongBlock: BlockConfig = { @@ -1088,11 +1088,11 @@ Return ONLY the timestamp string in ISO 8601 format - no explanations, no quotes ], config: { tool: (params) => `gong_${params.operation}`, - params: (params) => { + params: (params, context) => { const result: Record = {} // Map operation-specific subBlock IDs to tool param names, gated by the // selected operation so stale values from other operations never leak in - const operation = params.operation as string + const operation = mapperOperation(params, context) if (operation === 'get_call_transcript' || operation === 'get_extensive_calls') { if (params.transcriptFromDateTime) result.fromDateTime = params.transcriptFromDateTime if (params.transcriptToDateTime) result.toDateTime = params.transcriptToDateTime @@ -1123,7 +1123,7 @@ Return ONLY the timestamp string in ISO 8601 format - no explanations, no quotes if (params.logsToDateTime) result.toDateTime = params.logsToDateTime } if (operation === 'unassign_flow_prospects') { - result.flowId = params.unassignFlowId || undefined + result.flowId = params.unassignFlowId || toolCallArg(context, params.flowId) || undefined } return result }, diff --git a/apps/sim/blocks/blocks/grain.test.ts b/apps/sim/blocks/blocks/grain.test.ts new file mode 100644 index 00000000000..8d93892d126 --- /dev/null +++ b/apps/sim/blocks/blocks/grain.test.ts @@ -0,0 +1,29 @@ +/** + * Agent tool calls pass the operation in context and supply arguments under the tool's param + * names, which the mapper spreads over and must keep. + */ +import { describe, expect, it } from 'vitest' +import { GrainV2Block } from '@/blocks/blocks/grain' + +function agentParams(operation: string, args: Record): Record { + return { ...args, ...(GrainV2Block.tools.config?.params?.(args, { operation }) ?? {}) } +} + +describe('GrainV2Block agent tool calls', () => { + it('keeps the model include options when creating a webhook', () => { + const params = agentParams('grain_create_hook_v2', { + hookUrl: 'https://example.com/hook', + hookType: 'recording_added', + include: { participants: true }, + }) + expect(params.include).toEqual({ participants: true }) + }) + + it('keeps the model event type and state filters when listing webhooks', () => { + const params = agentParams('grain_list_hooks_v2', { + hookType: 'highlight_added', + state: 'enabled', + }) + expect(params).toMatchObject({ hookType: 'highlight_added', state: 'enabled' }) + }) +}) diff --git a/apps/sim/blocks/blocks/grain.ts b/apps/sim/blocks/blocks/grain.ts index 4c5181114b4..fbcd860c004 100644 --- a/apps/sim/blocks/blocks/grain.ts +++ b/apps/sim/blocks/blocks/grain.ts @@ -2,7 +2,7 @@ import { omit } from '@sim/utils/object' import { GrainIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' import { getTrigger } from '@/triggers' import { GRAIN_HOOK_TYPE_OPTIONS, grainTriggerOptions } from '@/triggers/grain/utils' @@ -368,12 +368,12 @@ Return ONLY the search term - no explanations, no quotes, no extra text.`, tool: (params) => { return params.operation || 'grain_list_recordings' }, - params: (params) => { + params: (params, context) => { const baseParams: Record = { apiKey: params.apiKey, } - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'grain_list_recordings': return { ...baseParams, @@ -705,12 +705,12 @@ export const GrainV2Block: BlockConfig = { tool: (params) => { return params.operation || 'grain_list_recordings' }, - params: (params) => { + params: (params, context) => { const baseParams: Record = { apiKey: params.apiKey, } - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'grain_create_hook_v2': { if (!params.hookUrl?.trim()) { throw new Error('Webhook URL is required.') @@ -719,12 +719,10 @@ export const GrainV2Block: BlockConfig = { throw new Error('Event type is required.') } let include: unknown - if (params.hookInclude) { + const rawInclude = params.hookInclude || toolCallArg(context, params.include) + if (rawInclude) { try { - include = - typeof params.hookInclude === 'string' - ? JSON.parse(params.hookInclude) - : params.hookInclude + include = typeof rawInclude === 'string' ? JSON.parse(rawInclude) : rawInclude } catch { throw new Error('Invalid JSON for include options') } @@ -740,8 +738,8 @@ export const GrainV2Block: BlockConfig = { case 'grain_list_hooks_v2': return { ...baseParams, - hookType: params.hookTypeFilter || undefined, - state: params.hookState || undefined, + hookType: params.hookTypeFilter || toolCallArg(context, params.hookType) || undefined, + state: params.hookState || toolCallArg(context, params.state) || undefined, } case 'grain_delete_hook_v2': @@ -754,7 +752,7 @@ export const GrainV2Block: BlockConfig = { } default: - return GrainBlock.tools!.config!.params!(params) + return GrainBlock.tools!.config!.params!(params, context) } }, }, diff --git a/apps/sim/blocks/blocks/greenhouse.ts b/apps/sim/blocks/blocks/greenhouse.ts index cf4ba4c1fd3..acae12ce0c0 100644 --- a/apps/sim/blocks/blocks/greenhouse.ts +++ b/apps/sim/blocks/blocks/greenhouse.ts @@ -1,6 +1,7 @@ import { GreenhouseIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' +import { mapperOperation } from '@/blocks/utils' import { getTrigger } from '@/triggers' export const GreenhouseBlock: BlockConfig = { @@ -362,16 +363,17 @@ Return ONLY the ISO 8601 timestamp - no explanations, no extra text.`, ], config: { tool: (params) => `${params.operation}`, - params: (params) => { + params: (params, context) => { const result: Record = {} + const operation = mapperOperation(params, context) if (params.per_page) result.per_page = Number(params.per_page) if (params.page) result.page = Number(params.page) - if (params.operation === 'greenhouse_list_applications' && params.applicationStatus) { + if (operation === 'greenhouse_list_applications' && params.applicationStatus) { result.status = params.applicationStatus } - if (params.operation === 'greenhouse_list_jobs' && params.status === '') { + if (operation === 'greenhouse_list_jobs' && params.status === '') { result.status = undefined } diff --git a/apps/sim/blocks/blocks/harmonic.test.ts b/apps/sim/blocks/blocks/harmonic.test.ts index 78f3f0a8b4f..37b08bd04eb 100644 --- a/apps/sim/blocks/blocks/harmonic.test.ts +++ b/apps/sim/blocks/blocks/harmonic.test.ts @@ -55,6 +55,12 @@ describe('HarmonicBlock', () => { expect(direct.personUrns).toEqual(['urn:harmonic:person:44']) }) + it('keeps model arguments on agent tool calls, where the operation arrives in context', () => { + const args = { oauthCredential: 'credential-id', personId: '22', companyContextUrns: ['urn:c'] } + const params = { ...args, ...buildParams(args, { operation: 'harmonic_get_person' }) } + expect(params).toMatchObject({ personId: '22', companyContextUrns: ['urn:c'] }) + }) + it('does not parse malformed batch JSON before the secret-safe tool boundary', () => { expect( resolve({ diff --git a/apps/sim/blocks/blocks/harmonic.ts b/apps/sim/blocks/blocks/harmonic.ts index f20b4ceee54..e46e94dbf98 100644 --- a/apps/sim/blocks/blocks/harmonic.ts +++ b/apps/sim/blocks/blocks/harmonic.ts @@ -1,6 +1,7 @@ import { HarmonicIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation } from '@/blocks/utils' const HARMONIC_OPERATIONS = [ 'harmonic_search_people_scout', @@ -497,8 +498,8 @@ export const HarmonicBlock: BlockConfig = { * operation-specific key is therefore assigned explicitly; `undefined` * is what removes a stale value after the operation changes. */ - params: (params) => { - const operation = String(params.operation ?? '') + params: (params, context) => { + const operation = mapperOperation(params, context) const isPaged = (PAGED_OPERATIONS as readonly string[]).includes(operation) const usesSavedSearch = (SAVED_SEARCH_OPERATIONS as readonly string[]).includes(operation) const usesPersonUrns = (PERSON_URN_OPERATIONS as readonly string[]).includes(operation) diff --git a/apps/sim/blocks/blocks/helpscout.test.ts b/apps/sim/blocks/blocks/helpscout.test.ts new file mode 100644 index 00000000000..06f06eda6a6 --- /dev/null +++ b/apps/sim/blocks/blocks/helpscout.test.ts @@ -0,0 +1,35 @@ +/** + * Agent tool calls pass the operation in context and supply arguments under the tool's param + * names (`status`, `type`, `sortField`), which the mapper spreads over and must keep. + */ +import { describe, expect, it } from 'vitest' +import { HelpScoutBlock } from '@/blocks/blocks/helpscout' + +function agentParams(operation: string, args: Record): Record { + return { ...args, ...(HelpScoutBlock.tools.config?.params?.(args, { operation }) ?? {}) } +} + +describe('HelpScoutBlock agent tool calls', () => { + it('keeps the model status when updating a conversation status', () => { + const params = agentParams('update_conversation_status', { + conversationId: '123', + status: 'closed', + }) + expect(params.status).toBe('closed') + }) + + it('keeps the model type and status when creating a conversation', () => { + const params = agentParams('create_conversation', { + mailboxId: '1', + subject: 'Hi', + type: 'chat', + status: 'pending', + }) + expect(params).toMatchObject({ type: 'chat', status: 'pending' }) + }) + + it('keeps the model sort field when listing customers', () => { + const params = agentParams('list_customers', { sortField: 'lastName' }) + expect(params.sortField).toBe('lastName') + }) +}) diff --git a/apps/sim/blocks/blocks/helpscout.ts b/apps/sim/blocks/blocks/helpscout.ts index 167c47364d3..7d5bb29f707 100644 --- a/apps/sim/blocks/blocks/helpscout.ts +++ b/apps/sim/blocks/blocks/helpscout.ts @@ -2,6 +2,7 @@ import { HelpScoutIcon } 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' const CONVERSATION_OPERATIONS = [ @@ -71,8 +72,8 @@ const TIMESTAMP_WAND = { } as const /** The status dropdown the active operation shows, collapsed onto the tools' shared `status` param. */ -function resolveStatus(params: Record): unknown { - switch (params.operation) { +function resolveStatus(params: Record, operation: string): unknown { + switch (operation) { case 'list_conversations': return params.listStatus case 'update_conversation_status': @@ -934,21 +935,29 @@ export const HelpScoutBlock: BlockConfig = { ], config: { tool: (params) => `helpscout_${params.operation || 'list_conversations'}`, - params: (params) => ({ - status: optionalString(resolveStatus(params)), - type: optionalString(params.conversationType), - sortField: optionalString( - params.operation === 'list_customers' - ? params.customerSortField - : params.conversationSortField - ), - sortOrder: optionalString(params.sortOrder), - gender: optionalString(params.gender), - workflowType: optionalString(params.workflowType), - organizationSort: optionalString(params.organizationSort), - page: optionalNumber(params.page), - number: optionalNumber(params.number), - }), + params: (params, context) => { + const operation = mapperOperation(params, context) + return { + status: + optionalString(resolveStatus(params, operation)) ?? + optionalString(toolCallArg(context, params.status)), + type: + optionalString(params.conversationType) ?? + optionalString(toolCallArg(context, params.type)), + sortField: + optionalString( + operation === 'list_customers' + ? params.customerSortField + : params.conversationSortField + ) ?? optionalString(toolCallArg(context, params.sortField)), + sortOrder: optionalString(params.sortOrder), + gender: optionalString(params.gender), + workflowType: optionalString(params.workflowType), + organizationSort: optionalString(params.organizationSort), + page: optionalNumber(params.page), + number: optionalNumber(params.number), + } + }, }, }, inputs: { diff --git a/apps/sim/blocks/blocks/hex.test.ts b/apps/sim/blocks/blocks/hex.test.ts index 5e632ff4f64..8e71341a5e2 100644 --- a/apps/sim/blocks/blocks/hex.test.ts +++ b/apps/sim/blocks/blocks/hex.test.ts @@ -6,6 +6,7 @@ import { describe, expect, it } from 'vitest' import { HexBlock } from '@/blocks/blocks/hex' import type { BlockToolParamsContext } from '@/blocks/types' +import { getGroupTool } from '@/tools/hex/get_group' import { getProjectRunsTool } from '@/tools/hex/get_project_runs' import { getQueriedTablesTool } from '@/tools/hex/get_queried_tables' import { listGroupsTool } from '@/tools/hex/list_groups' @@ -77,13 +78,13 @@ describe('Hex block keeps stale subBlock values out of tool requests', () => { }) it('get project runs keeps a run status an agent passes directly', () => { - const args = { operation: 'get_project_runs', projectId: PROJECT_ID, statusFilter: 'errored' } + const args = { projectId: PROJECT_ID, statusFilter: 'errored' } const built = requestUrl(getProjectRunsTool, args, { operation: 'get_project_runs' }) expect(built.searchParams.get('statusFilter')).toBe('errored') }) it('list groups keeps a user id an agent passes directly', () => { - const args = { operation: 'list_groups', userId: PROJECT_ID } + const args = { userId: PROJECT_ID } const built = requestUrl(listGroupsTool, args, { operation: 'list_groups' }) expect(built.searchParams.get('userId')).toBe(PROJECT_ID) }) @@ -94,8 +95,13 @@ describe('Hex block keeps stale subBlock values out of tool requests', () => { }) it('get queried tables keeps a cursor an agent passes directly', () => { - const args = { operation: 'get_queried_tables', projectId: PROJECT_ID, after: 'tables-cursor' } + const args = { projectId: PROJECT_ID, after: 'tables-cursor' } const built = requestUrl(getQueriedTablesTool, args, { operation: 'get_queried_tables' }) expect(built.searchParams.get('after')).toBe('tables-cursor') }) + + it('get group sends the Group ID stored on an agent tool row', () => { + const built = requestUrl(getGroupTool, { groupIdInput: PROJECT_ID }, { operation: 'get_group' }) + expect(built.pathname).toBe(`/api/v1/groups/${PROJECT_ID}`) + }) }) diff --git a/apps/sim/blocks/blocks/hex.ts b/apps/sim/blocks/blocks/hex.ts index 9d23f46547d..7c6950cf67a 100644 --- a/apps/sim/blocks/blocks/hex.ts +++ b/apps/sim/blocks/blocks/hex.ts @@ -1,7 +1,7 @@ import { HexIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { isToolCall, toolCallArg, withSavedCredential } from '@/blocks/utils' +import { isToolCall, mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' /** * Sort fields each list endpoint accepts. The only Sort By field is the List Projects one, so a @@ -711,7 +711,7 @@ Do not include any explanations, markdown formatting, or other text outside the }, params: (params, context) => { const result: Record = {} - const op = params.operation + const op = mapperOperation(params, context) const fieldOrToolArg = (field: unknown, arg: unknown) => emptyToUndefined(field) ?? emptyToUndefined(toolCallArg(context, arg)) diff --git a/apps/sim/blocks/blocks/instagram.test.ts b/apps/sim/blocks/blocks/instagram.test.ts index d1948b9a428..917c1a82c88 100644 --- a/apps/sim/blocks/blocks/instagram.test.ts +++ b/apps/sim/blocks/blocks/instagram.test.ts @@ -76,4 +76,26 @@ describe('InstagramBlock', () => { buildParams({ operation: 'instagram_get_account_insights', period: 'week' }) ).toThrow('Instagram account insights period must be day or lifetime') }) + + it('forwards the media and metrics an agent passes under the tool param names', () => { + const file = { + id: 'file-1', + key: 'execution/workflow/execution/photo.jpg', + name: 'photo.jpg', + size: 1024, + type: 'image/jpeg', + } + const carousel = buildParams( + { oauthCredential: 'credential-1', media: [file, { ...file, id: 'file-2' }], caption: 'hi' }, + { operation: 'instagram_publish_carousel' } + ) + expect(carousel).toMatchObject({ caption: 'hi' }) + expect(carousel.media).toHaveLength(2) + + const insights = buildParams( + { oauthCredential: 'credential-1', mediaId: 'media-1', metrics: 'reach,views' }, + { operation: 'instagram_get_media_insights' } + ) + expect(insights).toMatchObject({ mediaId: 'media-1', metrics: 'reach,views' }) + }) }) diff --git a/apps/sim/blocks/blocks/instagram.ts b/apps/sim/blocks/blocks/instagram.ts index 6862204a45b..da0749eede4 100644 --- a/apps/sim/blocks/blocks/instagram.ts +++ b/apps/sim/blocks/blocks/instagram.ts @@ -2,7 +2,7 @@ import { InstagramIcon } 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' const IG_USER_ID_OPS = [ 'instagram_list_media', @@ -780,8 +780,8 @@ Return ONLY the timestamp or date - no explanations, no extra text.`, } return operation }, - params: (params) => { - const operation = typeof params.operation === 'string' ? params.operation : '' + params: (params, context) => { + const operation = mapperOperation(params, context) const result: Record = { credential: params.oauthCredential, } @@ -805,12 +805,17 @@ Return ONLY the timestamp or date - no explanations, no extra text.`, const resolved = normalizeFileInput(params.media, { single: true }) if (resolved) result.media = resolved } else if (operation === 'instagram_publish_carousel') { - const resolved = normalizeFileInput(params.carouselMedia) + const resolved = + normalizeFileInput(params.carouselMedia) ?? + normalizeFileInput(toolCallArg(context, params.media)) if (resolved) result.media = resolved } for (const key of OPERATION_PARAM_KEYS[operation] ?? []) { - const value = params[key] + const value = + key === 'insightMetrics' + ? params.insightMetrics || toolCallArg(context, params.metrics) + : params[key] if (value === undefined || value === null || value === '') continue if (key === 'insightMetrics') { diff --git a/apps/sim/blocks/blocks/instantly.test.ts b/apps/sim/blocks/blocks/instantly.test.ts new file mode 100644 index 00000000000..a616b454f7f --- /dev/null +++ b/apps/sim/blocks/blocks/instantly.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from 'vitest' +import { InstantlyV2Block } from '@/blocks/blocks/instantly' +import type { BlockToolParamsContext } from '@/blocks/types' + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = InstantlyV2Block.tools.config?.params + if (!mapper) throw new Error('Instantly block has no params mapper') + return { ...params, ...mapper(params, context) } +} + +describe('Instantly agent tool calls', () => { + it('keeps the model interest value so the update does not fail as missing', () => { + const merged = mapParams( + { lead_email: 'ann@example.com', interest_value: 1, campaign_id: 'camp-1' }, + { operation: 'update_lead_interest_status' } + ) + + expect(merged.interest_value).toBe(1) + expect(merged.campaign_id).toBe('camp-1') + }) + + it('keeps model lead fields named by the tool instead of wiping them', () => { + const merged = mapParams( + { email: 'ann@example.com', first_name: 'Ann', campaign: 'camp-1', skip_if_in_list: true }, + { operation: 'create_lead' } + ) + + expect(merged).toMatchObject({ first_name: 'Ann', campaign: 'camp-1', skip_if_in_list: true }) + }) + + it('keeps the model reply body when the block body fields are empty', () => { + const merged = mapParams( + { reply_to_uuid: 'email-1', eaccount: 'me@example.com', subject: 'Re', body: { text: 'Hi' } }, + { operation: 'reply_to_email' } + ) + + expect(merged.body).toEqual({ text: 'Hi' }) + }) +}) diff --git a/apps/sim/blocks/blocks/instantly.ts b/apps/sim/blocks/blocks/instantly.ts index 08c22aecefe..9484186e167 100644 --- a/apps/sim/blocks/blocks/instantly.ts +++ b/apps/sim/blocks/blocks/instantly.ts @@ -2,7 +2,7 @@ import { isRecordLike } from '@sim/utils/object' import { InstantlyIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { isToolCall, mapperOperation, withSavedCredential } from '@/blocks/utils' import { getTrigger } from '@/triggers' const LEAD_LIST_OPERATIONS = ['list_leads'] as const @@ -932,81 +932,198 @@ export const InstantlyBlock: BlockConfig = { ], config: { tool: (params) => `instantly_${params.operation}`, - params: (params) => ({ - campaign: mapCampaignParam(params), - list_id: mapListIdParam(params), - campaign_id: mapCampaignIdParam(params), - leadId: params.leadId, - email: emptyToUndefined(params.email), - first_name: emptyToUndefined(params.firstName), - last_name: emptyToUndefined(params.lastName), - company_name: emptyToUndefined(params.companyName), - job_title: emptyToUndefined(params.jobTitle), - phone: emptyToUndefined(params.phone), - website: emptyToUndefined(params.website), - personalization: emptyToUndefined(params.personalization), - custom_variables: parseJsonObject(params.customVariables), - lt_interest_status: toNumberParam(params.leadInterestStatus), - pl_value_lead: emptyToUndefined(params.potentialLeadValue), - assigned_to: optionalIdParam(params.assignedTo), - blocklist_id: optionalIdParam(params.blocklistId), - skip_if_in_workspace: toBooleanParam(params.skipIfInWorkspace), - skip_if_in_campaign: toBooleanParam(params.skipIfInCampaign), - skip_if_in_list: toBooleanParam(params.skipIfInList), - verify_leads_for_lead_finder: toBooleanParam(params.verifyLeadsForLeadFinder), - verify_leads_on_import: toBooleanParam(params.verifyLeadsOnImport), - filter: emptyToUndefined(params.leadFilter), - ids: mapIdsParam(params), - excluded_ids: parseStringList(params.excludedLeadIds), - contacts: parseStringList(params.contacts), - organization_user_ids: parseStringList(params.organizationUserIds), - smart_view_id: optionalIdParam(params.smartViewId), - is_website_visitor: toBooleanParam(params.websiteVisitor), - distinct_contacts: toBooleanParam(params.distinctContacts), - enrichment_status: toNumberParam(params.enrichmentStatus), - esg_code: emptyToUndefined(params.esgCode), - in_campaign: toBooleanParam(params.inCampaign), - in_list: toBooleanParam(params.inList), - status: mapStatusParam(params), - limit: mapLimitParam(params), - starting_after: mapStartingAfterParam(params), - lead_email: emptyToUndefined(params.leadEmail), - interest_value: - params.operation === 'update_lead_interest_status' - ? toNullableNumberParam(params.interestValue, true) - : undefined, - ai_interest_value: toNumberParam(params.aiInterestValue), - disable_auto_interest: toBooleanParam(params.disableAutoInterest), - name: mapNameParam(params), - campaign_schedule: parseJsonObject(params.campaignSchedule), - sequences: parseJsonArray(params.sequences), - email_list: parseStringList(params.emailList), - daily_limit: toNumberParam(params.dailyLimit), - daily_max_leads: toNumberParam(params.dailyMaxLeads), - open_tracking: toBooleanParam(params.openTracking), - stop_on_reply: toBooleanParam(params.stopOnReply), - pl_value: toNumberParam(params.positiveLeadValue), - email_gap: toNumberParam(params.emailGap), - link_tracking: toBooleanParam(params.linkTracking), - text_only: toBooleanParam(params.textOnly), - tag_ids: emptyToUndefined(params.tagIds), - ai_sales_agent_id: optionalIdParam(params.aiSalesAgentId), - search: mapSearchParam(params), - eaccount: emptyToUndefined(params.emailAccount), - i_status: toNumberParam(params.emailStatus), - lead: emptyToUndefined(params.emailLead), - is_unread: toBooleanParam(params.emailIsUnread), - reply_to_uuid: emptyToUndefined(params.replyToUuid), - subject: emptyToUndefined(params.subject), - body: { - text: emptyToUndefined(params.bodyText), - html: emptyToUndefined(params.bodyHtml), - }, - cc_address_email_list: emptyToUndefined(params.ccRecipients), - bcc_address_email_list: emptyToUndefined(params.bccRecipients), - has_enrichment_task: toBooleanParam(params.hasEnrichmentTask), - owned_by: optionalIdParam(params.ownedBy), - }), + params: (params, context) => { + const operation = mapperOperation(params, context) + const toolCall = isToolCall(context) + /** + * The block field's value, else on a tool call the model's arg under the tool's own param + * name: the result is spread over the merged params, so an `undefined` here wipes that arg. + */ + const orArg = ( + blockValue: T | undefined, + toolKey: string, + coerce: (value: unknown) => T | undefined + ): T | undefined => + blockValue !== undefined || !toolCall ? blockValue : coerce(params[toolKey]) + + return { + campaign: orArg(mapCampaignParam(params, operation), 'campaign', optionalIdParam), + list_id: orArg(mapListIdParam(params, operation), 'list_id', optionalIdParam), + campaign_id: orArg(mapCampaignIdParam(params, operation), 'campaign_id', optionalIdParam), + leadId: params.leadId, + email: emptyToUndefined(params.email), + first_name: orArg(emptyToUndefined(params.firstName), 'first_name', emptyToUndefined), + last_name: orArg(emptyToUndefined(params.lastName), 'last_name', emptyToUndefined), + company_name: orArg( + emptyToUndefined(params.companyName), + 'company_name', + emptyToUndefined + ), + job_title: orArg(emptyToUndefined(params.jobTitle), 'job_title', emptyToUndefined), + phone: emptyToUndefined(params.phone), + website: emptyToUndefined(params.website), + personalization: emptyToUndefined(params.personalization), + custom_variables: orArg( + parseJsonObject(params.customVariables), + 'custom_variables', + parseJsonObject + ), + lt_interest_status: orArg( + toNumberParam(params.leadInterestStatus), + 'lt_interest_status', + toNumberParam + ), + pl_value_lead: orArg( + emptyToUndefined(params.potentialLeadValue), + 'pl_value_lead', + emptyToUndefined + ), + assigned_to: orArg(optionalIdParam(params.assignedTo), 'assigned_to', optionalIdParam), + blocklist_id: orArg(optionalIdParam(params.blocklistId), 'blocklist_id', optionalIdParam), + skip_if_in_workspace: orArg( + toBooleanParam(params.skipIfInWorkspace), + 'skip_if_in_workspace', + toBooleanParam + ), + skip_if_in_campaign: orArg( + toBooleanParam(params.skipIfInCampaign), + 'skip_if_in_campaign', + toBooleanParam + ), + skip_if_in_list: orArg( + toBooleanParam(params.skipIfInList), + 'skip_if_in_list', + toBooleanParam + ), + verify_leads_for_lead_finder: orArg( + toBooleanParam(params.verifyLeadsForLeadFinder), + 'verify_leads_for_lead_finder', + toBooleanParam + ), + verify_leads_on_import: orArg( + toBooleanParam(params.verifyLeadsOnImport), + 'verify_leads_on_import', + toBooleanParam + ), + filter: orArg(emptyToUndefined(params.leadFilter), 'filter', emptyToUndefined), + ids: orArg(mapIdsParam(params, operation), 'ids', parseStringList), + excluded_ids: orArg( + parseStringList(params.excludedLeadIds), + 'excluded_ids', + parseStringList + ), + contacts: parseStringList(params.contacts), + organization_user_ids: orArg( + parseStringList(params.organizationUserIds), + 'organization_user_ids', + parseStringList + ), + smart_view_id: orArg( + optionalIdParam(params.smartViewId), + 'smart_view_id', + optionalIdParam + ), + is_website_visitor: orArg( + toBooleanParam(params.websiteVisitor), + 'is_website_visitor', + toBooleanParam + ), + distinct_contacts: orArg( + toBooleanParam(params.distinctContacts), + 'distinct_contacts', + toBooleanParam + ), + enrichment_status: orArg( + toNumberParam(params.enrichmentStatus), + 'enrichment_status', + toNumberParam + ), + esg_code: orArg(emptyToUndefined(params.esgCode), 'esg_code', emptyToUndefined), + in_campaign: orArg(toBooleanParam(params.inCampaign), 'in_campaign', toBooleanParam), + in_list: orArg(toBooleanParam(params.inList), 'in_list', toBooleanParam), + status: orArg(mapStatusParam(params, operation), 'status', toNumberParam), + limit: orArg(mapLimitParam(params, operation), 'limit', toNumberParam), + starting_after: orArg( + mapStartingAfterParam(params, operation), + 'starting_after', + emptyToUndefined + ), + lead_email: orArg(emptyToUndefined(params.leadEmail), 'lead_email', emptyToUndefined), + interest_value: mapInterestValueParam(params, operation, toolCall), + ai_interest_value: orArg( + toNumberParam(params.aiInterestValue), + 'ai_interest_value', + toNumberParam + ), + disable_auto_interest: orArg( + toBooleanParam(params.disableAutoInterest), + 'disable_auto_interest', + toBooleanParam + ), + name: orArg(mapNameParam(params, operation), 'name', emptyToUndefined), + campaign_schedule: orArg( + parseJsonObject(params.campaignSchedule), + 'campaign_schedule', + parseJsonObject + ), + sequences: parseJsonArray(params.sequences), + email_list: orArg(parseStringList(params.emailList), 'email_list', parseStringList), + daily_limit: orArg(toNumberParam(params.dailyLimit), 'daily_limit', toNumberParam), + daily_max_leads: orArg( + toNumberParam(params.dailyMaxLeads), + 'daily_max_leads', + toNumberParam + ), + open_tracking: orArg( + toBooleanParam(params.openTracking), + 'open_tracking', + toBooleanParam + ), + stop_on_reply: orArg(toBooleanParam(params.stopOnReply), 'stop_on_reply', toBooleanParam), + pl_value: orArg(toNumberParam(params.positiveLeadValue), 'pl_value', toNumberParam), + email_gap: orArg(toNumberParam(params.emailGap), 'email_gap', toNumberParam), + link_tracking: orArg( + toBooleanParam(params.linkTracking), + 'link_tracking', + toBooleanParam + ), + text_only: orArg(toBooleanParam(params.textOnly), 'text_only', toBooleanParam), + tag_ids: orArg(emptyToUndefined(params.tagIds), 'tag_ids', emptyToUndefined), + ai_sales_agent_id: orArg( + optionalIdParam(params.aiSalesAgentId), + 'ai_sales_agent_id', + optionalIdParam + ), + search: orArg(mapSearchParam(params, operation), 'search', emptyToUndefined), + eaccount: orArg(emptyToUndefined(params.emailAccount), 'eaccount', emptyToUndefined), + i_status: orArg(toNumberParam(params.emailStatus), 'i_status', toNumberParam), + lead: orArg(emptyToUndefined(params.emailLead), 'lead', emptyToUndefined), + is_unread: orArg(toBooleanParam(params.emailIsUnread), 'is_unread', toBooleanParam), + reply_to_uuid: orArg( + emptyToUndefined(params.replyToUuid), + 'reply_to_uuid', + emptyToUndefined + ), + subject: emptyToUndefined(params.subject), + body: mapBodyParam(params, toolCall), + cc_address_email_list: orArg( + emptyToUndefined(params.ccRecipients), + 'cc_address_email_list', + emptyToUndefined + ), + bcc_address_email_list: orArg( + emptyToUndefined(params.bccRecipients), + 'bcc_address_email_list', + emptyToUndefined + ), + has_enrichment_task: orArg( + toBooleanParam(params.hasEnrichmentTask), + 'has_enrichment_task', + toBooleanParam + ), + owned_by: orArg(optionalIdParam(params.ownedBy), 'owned_by', optionalIdParam), + } + }, }, }, inputs: { @@ -1232,14 +1349,14 @@ function emptyToUndefined(value: unknown): unknown { return trimmed === '' || trimmed === '-' ? undefined : trimmed } -function mapCampaignParam(params: Record): string | undefined { - if (params.operation === 'list_leads') return optionalIdParam(params.campaignId) - if (params.operation !== 'create_lead' || params.leadDestination !== 'campaign') return undefined +function mapCampaignParam(params: Record, operation: string): string | undefined { + if (operation === 'list_leads') return optionalIdParam(params.campaignId) + if (operation !== 'create_lead' || params.leadDestination !== 'campaign') return undefined return optionalIdParam(params.leadDestinationId) } -function mapListIdParam(params: Record): string | undefined { - switch (params.operation) { +function mapListIdParam(params: Record, operation: string): string | undefined { + switch (operation) { case 'delete_leads': return params.deleteSource === 'list' ? optionalIdParam(params.deleteSourceId) : undefined case 'create_lead': @@ -1255,42 +1372,45 @@ function mapListIdParam(params: Record): string | undefined { } } -function mapCampaignIdParam(params: Record): string | undefined { - if (params.operation === 'delete_leads') { +function mapCampaignIdParam( + params: Record, + operation: string +): string | undefined { + if (operation === 'delete_leads') { return params.deleteSource === 'campaign' ? optionalIdParam(params.deleteSourceId) : undefined } - if (params.operation === 'update_lead_interest_status' || params.operation === 'list_emails') { + if (operation === 'update_lead_interest_status' || operation === 'list_emails') { return optionalIdParam(params.campaignId) } return undefined } -function mapIdsParam(params: Record): string[] | undefined { - if (params.operation === 'delete_leads') return parseStringList(params.deleteLeadIds) - if (params.operation === 'list_leads') return parseStringList(params.leadIds) +function mapIdsParam(params: Record, operation: string): string[] | undefined { + if (operation === 'delete_leads') return parseStringList(params.deleteLeadIds) + if (operation === 'list_leads') return parseStringList(params.leadIds) return undefined } -function mapStatusParam(params: Record): number | undefined { - if (params.operation === 'delete_leads') return toNumberParam(params.deleteStatus) - if (params.operation === 'list_campaigns') return toNumberParam(params.campaignStatus) +function mapStatusParam(params: Record, operation: string): number | undefined { + if (operation === 'delete_leads') return toNumberParam(params.deleteStatus) + if (operation === 'list_campaigns') return toNumberParam(params.campaignStatus) return undefined } -function mapLimitParam(params: Record): number | undefined { - if (params.operation === 'delete_leads') return toNumberParam(params.deleteLimit) - if (isPaginatedOperation(params.operation)) return toNumberParam(params.limit) +function mapLimitParam(params: Record, operation: string): number | undefined { + if (operation === 'delete_leads') return toNumberParam(params.deleteLimit) + if (isPaginatedOperation(operation)) return toNumberParam(params.limit) return undefined } -function mapStartingAfterParam(params: Record): unknown { - return isPaginatedOperation(params.operation) ? emptyToUndefined(params.startingAfter) : undefined +function mapStartingAfterParam(params: Record, operation: string): unknown { + return isPaginatedOperation(operation) ? emptyToUndefined(params.startingAfter) : undefined } -function mapNameParam(params: Record): unknown { - switch (params.operation) { +function mapNameParam(params: Record, operation: string): unknown { + switch (operation) { case 'create_lead_list': return emptyToUndefined(params.leadListName) case 'create_campaign': @@ -1301,12 +1421,34 @@ function mapNameParam(params: Record): unknown { } } -function mapSearchParam(params: Record): unknown { - if (params.operation === 'list_emails') return emptyToUndefined(params.emailSearch) - if (isSearchOperation(params.operation)) return emptyToUndefined(params.search) +function mapSearchParam(params: Record, operation: string): unknown { + if (operation === 'list_emails') return emptyToUndefined(params.emailSearch) + if (isSearchOperation(operation)) return emptyToUndefined(params.search) return undefined } +function mapInterestValueParam( + params: Record, + operation: string, + toolCall: boolean +): number | null | undefined { + if (operation !== 'update_lead_interest_status') return undefined + const blockValueEmpty = + params.interestValue === undefined || + (typeof params.interestValue === 'string' && params.interestValue.trim() === '') + if (toolCall && blockValueEmpty) return toNullableNumberParam(params.interest_value) + return toNullableNumberParam(params.interestValue, true) +} + +function mapBodyParam(params: Record, toolCall: boolean): unknown { + const text = emptyToUndefined(params.bodyText) + const html = emptyToUndefined(params.bodyHtml) + if (toolCall && text === undefined && html === undefined) { + return parseJsonObject(params.body) ?? emptyToUndefined(params.body) + } + return { text, html } +} + function isPaginatedOperation(value: unknown): boolean { return ( value === 'list_leads' || diff --git a/apps/sim/blocks/blocks/knowledge.test.ts b/apps/sim/blocks/blocks/knowledge.test.ts new file mode 100644 index 00000000000..280384bffb9 --- /dev/null +++ b/apps/sim/blocks/blocks/knowledge.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from 'vitest' +import { KnowledgeBlock } from '@/blocks/blocks/knowledge' + +function mapToolCall(params: Record, operation: string) { + const mapper = KnowledgeBlock.tools.config?.params + if (!mapper) throw new Error('Knowledge block has no params mapper') + return mapper(params, { operation }) +} + +describe('Knowledge mapper on tool calls (operation only in context)', () => { + it('coerces a model-sent "false" to a boolean for update_chunk', () => { + const mapped = mapToolCall( + { knowledgeBaseId: 'kb-1', documentId: 'doc-1', chunkId: 'chunk-1', enabled: 'false' }, + 'update_chunk' + ) + + expect(mapped.enabled).toBe(false) + }) + + it('forwards the stored status filter and search for list_chunks', () => { + const mapped = mapToolCall( + { + knowledgeBaseId: 'kb-1', + documentId: 'doc-1', + chunkSearch: 'pricing', + chunkEnabledFilter: 'false', + }, + 'list_chunks' + ) + + expect(mapped).toMatchObject({ search: 'pricing', enabled: 'false' }) + }) + + it('keeps the model status filter when the stored row holds the default "all"', () => { + const mapped = mapToolCall( + { knowledgeBaseId: 'kb-1', documentId: 'doc-1', chunkEnabledFilter: 'all', enabled: 'true' }, + 'list_chunks' + ) + + expect(mapped.enabled).toBe('true') + }) + + it('sends the stored upsert document id as documentId', () => { + const mapped = mapToolCall( + { knowledgeBaseId: 'kb-1', upsertDocumentId: ' doc-9 ', name: 'Doc', content: 'Body' }, + 'upsert_document' + ) + + expect(mapped.documentId).toBe('doc-9') + }) +}) diff --git a/apps/sim/blocks/blocks/knowledge.ts b/apps/sim/blocks/blocks/knowledge.ts index 1c89a28c419..291988eddee 100644 --- a/apps/sim/blocks/blocks/knowledge.ts +++ b/apps/sim/blocks/blocks/knowledge.ts @@ -2,7 +2,7 @@ import { isPlainRecord } from '@sim/utils/object' import { PackageSearchIcon } from '@/components/icons' import { DEFAULT_RERANKER_MODEL, SUPPORTED_RERANKER_MODELS } from '@/lib/knowledge/reranker-models' import type { BlockConfig } from '@/blocks/types' -import { getCohereRerankerApiKeyCondition } from '@/blocks/utils' +import { getCohereRerankerApiKeyCondition, mapperOperation, toolCallArg } from '@/blocks/utils' /* * Canonical basic/advanced pairs, shared by the card sentences below. Listing @@ -448,8 +448,9 @@ export const KnowledgeBlock: BlockConfig = { return 'knowledge_search' } }, - params: (params) => { + params: (params, context) => { params = { ...params } + const operation = mapperOperation(params, context) const knowledgeBaseId = params.knowledgeBaseId ? String(params.knowledgeBaseId).trim() : '' if (!knowledgeBaseId) { throw new Error('Knowledge base ID is required') @@ -464,45 +465,53 @@ export const KnowledgeBlock: BlockConfig = { 'update_chunk', 'delete_chunk', ] - if (docOps.includes(params.operation)) { + if (docOps.includes(operation)) { const documentId = params.documentId ? String(params.documentId).trim() : '' if (!documentId) { - throw new Error(`Document ID is required for ${params.operation} operation`) + throw new Error(`Document ID is required for ${operation} operation`) } params.documentId = documentId } const chunkOps = ['update_chunk', 'delete_chunk'] - if (chunkOps.includes(params.operation)) { + if (chunkOps.includes(operation)) { const chunkId = params.chunkId ? String(params.chunkId).trim() : '' if (!chunkId) { - throw new Error(`Chunk ID is required for ${params.operation} operation`) + throw new Error(`Chunk ID is required for ${operation} operation`) } params.chunkId = chunkId } const connectorOps = ['get_connector', 'trigger_sync'] - if (connectorOps.includes(params.operation)) { + if (connectorOps.includes(operation)) { const connectorId = params.connectorId ? String(params.connectorId).trim() : '' if (!connectorId) { - throw new Error(`Connector ID is required for ${params.operation} operation`) + throw new Error(`Connector ID is required for ${operation} operation`) } params.connectorId = connectorId } // Map list_chunks sub-block fields to tool params - if (params.operation === 'list_chunks') { + if (operation === 'list_chunks') { if (params.chunkSearch) params.search = params.chunkSearch - if (params.chunkEnabledFilter) params.enabled = params.chunkEnabledFilter + if (params.chunkEnabledFilter) { + const modelEnabled = + params.chunkEnabledFilter === 'all' ? toolCallArg(context, params.enabled) : undefined + /* The tool takes a string; a model may send the boolean `false`, which must survive. */ + params.enabled = + modelEnabled === undefined || modelEnabled === null || modelEnabled === '' + ? params.chunkEnabledFilter + : String(modelEnabled) + } } // Map upsert sub-block field to tool param - if (params.operation === 'upsert_document' && params.upsertDocumentId) { + if (operation === 'upsert_document' && params.upsertDocumentId) { params.documentId = String(params.upsertDocumentId).trim() } if ( - (params.operation === 'create_document' || params.operation === 'upsert_document') && + (operation === 'create_document' || operation === 'upsert_document') && typeof params.documentTags === 'string' && params.documentTags.trim().length > 0 ) { @@ -515,7 +524,7 @@ export const KnowledgeBlock: BlockConfig = { } // Convert enabled dropdown string to boolean for update_chunk - if (params.operation === 'update_chunk' && typeof params.enabled === 'string') { + if (operation === 'update_chunk' && typeof params.enabled === 'string') { params.enabled = params.enabled === 'true' } diff --git a/apps/sim/blocks/blocks/latex.test.ts b/apps/sim/blocks/blocks/latex.test.ts new file mode 100644 index 00000000000..19a05f57653 --- /dev/null +++ b/apps/sim/blocks/blocks/latex.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest' +import { LatexBlock } from '@/blocks/blocks/latex' + +const mapParams = LatexBlock.tools.config?.params +if (!mapParams) throw new Error('LatexBlock has no params mapper') + +describe('LatexBlock agent tool calls', () => { + it('forwards a search query typed into the tool row, which carries no operation in its params', () => { + expect( + mapParams({ packageQuery: 'chemistry' }, { operation: 'latex_search_packages' }) + ).toEqual({ query: 'chemistry' }) + }) + + it('keeps the model query and name when the tool row leaves the block fields blank', () => { + expect( + mapParams({ packageQuery: '', query: 'tikz' }, { operation: 'latex_search_packages' }) + ).toEqual({ query: 'tikz' }) + expect(mapParams({ name: ' amsmath ' }, { operation: 'latex_get_package' })).toEqual({ + name: 'amsmath', + }) + }) +}) diff --git a/apps/sim/blocks/blocks/latex.ts b/apps/sim/blocks/blocks/latex.ts index f47c343128a..323e29a92e3 100644 --- a/apps/sim/blocks/blocks/latex.ts +++ b/apps/sim/blocks/blocks/latex.ts @@ -1,6 +1,7 @@ import { LatexIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { IntegrationType } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' export const LatexBlock: BlockConfig = { type: 'latex', @@ -158,9 +159,9 @@ Return ONLY the JSON array - no explanations, no markdown, no extra text.`, return 'latex_compile' } }, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { - operation, compiler, fileName, resources, @@ -179,13 +180,14 @@ Return ONLY the JSON array - no explanations, no markdown, no extra text.`, if (operation === 'latex_search_packages') { return { - query: packageQuery, + query: toolCallArg(context, packageQuery || params.query) ?? packageQuery, ...maxResultsParam, } } if (operation === 'latex_get_package') { - const effectivePackageName = typeof packageName === 'string' ? packageName.trim() : '' + const requestedName = toolCallArg(context, packageName || params.name) ?? packageName + const effectivePackageName = typeof requestedName === 'string' ? requestedName.trim() : '' if (!effectivePackageName) { throw new Error('Package name is required.') } diff --git a/apps/sim/blocks/blocks/logs.test.ts b/apps/sim/blocks/blocks/logs.test.ts index 3ecfb864333..44b0c1cf5a9 100644 --- a/apps/sim/blocks/blocks/logs.test.ts +++ b/apps/sim/blocks/blocks/logs.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { LogsV2Block } from '@/blocks/blocks/logs' +import { LogsBlock, LogsV2Block } from '@/blocks/blocks/logs' function buildQueryParams(params: Record) { return LogsV2Block.tools.config!.params!({ operation: 'query', ...params }) @@ -77,3 +77,25 @@ describe('LogsV2Block backwards compatibility', () => { expect(JSON.stringify(params)).not.toContain('triggers') }) }) + +describe('LogsBlock agent tool calls', () => { + const mapParams = LogsBlock.tools.config?.params + if (!mapParams) throw new Error('LogsBlock has no params mapper') + + it('sends the log id typed into the tool row instead of query filters', () => { + expect(mapParams({ logId: 'log-1' }, { operation: 'get_log' })).toEqual({ id: 'log-1' }) + }) + + it('sends the execution id typed into the tool row instead of query filters', () => { + expect(mapParams({ executionIdLookup: 'exec-1' }, { operation: 'get_execution' })).toEqual({ + executionId: 'exec-1', + }) + }) + + it('keeps the model-supplied id when the tool row leaves the block field blank', () => { + expect(mapParams({ id: 'log-2' }, { operation: 'get_log' })).toEqual({ id: 'log-2' }) + expect(mapParams({ executionId: 'exec-2' }, { operation: 'get_execution' })).toEqual({ + executionId: 'exec-2', + }) + }) +}) diff --git a/apps/sim/blocks/blocks/logs.ts b/apps/sim/blocks/blocks/logs.ts index 7970a8b0d03..8050abf9fac 100644 --- a/apps/sim/blocks/blocks/logs.ts +++ b/apps/sim/blocks/blocks/logs.ts @@ -1,5 +1,6 @@ import { Library } from '@sim/emcn/icons' import type { BlockConfig } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' export const LogsBlock: BlockConfig = { type: 'logs', @@ -191,23 +192,25 @@ export const LogsBlock: BlockConfig = { if (operation === 'get_execution') return 'logs_get_execution' return 'logs_query' }, - params: (params: Record) => { - const operation = params.operation || 'query' + params: (params: Record, context) => { + const operation = mapperOperation(params, context) || 'query' if (operation === 'get_log') { - if (!params.logId) { + const logId = params.logId || toolCallArg(context, params.id) + if (!logId) { throw new Error('Logs Block Error: Log ID is required for get_log operation') } - return { id: params.logId } + return { id: logId } } if (operation === 'get_execution') { - if (!params.executionIdLookup) { + const executionId = params.executionIdLookup || toolCallArg(context, params.executionId) + if (!executionId) { throw new Error( 'Logs Block Error: Execution ID is required for get_execution operation' ) } - return { executionId: params.executionIdLookup } + return { executionId } } const rawLimit = @@ -551,8 +554,8 @@ export const LogsV2Block: BlockConfig = { if (operation === 'get_run_details') return 'logs_get_run_details' return 'logs_query_runs' }, - params: (params: Record) => { - const operation = params.operation || 'query' + params: (params: Record, context) => { + const operation = mapperOperation(params, context) || 'query' if (operation === 'get_run_details') { if (!params.runId) { diff --git a/apps/sim/blocks/blocks/memory.ts b/apps/sim/blocks/blocks/memory.ts index 8858883156d..463d3bb0a9d 100644 --- a/apps/sim/blocks/blocks/memory.ts +++ b/apps/sim/blocks/blocks/memory.ts @@ -1,5 +1,6 @@ import { BrainIcon } from '@/components/icons' import type { BlockConfig } from '@/blocks/types' +import { mapperOperation } from '@/blocks/utils' export const MemoryBlock: BlockConfig = { type: 'memory', @@ -121,24 +122,25 @@ export const MemoryBlock: BlockConfig = { return 'memory_add' } }, - params: (params: Record) => { + params: (params: Record, context) => { + const operation = mapperOperation(params, context) const errors: string[] = [] - if (!params.operation) { + if (!operation) { errors.push('Operation is required') } const conversationId = params.id || params.conversationId - if (params.operation === 'add') { + if (operation === 'add') { if (!conversationId) { errors.push('Conversation ID is required for add operation') } } - if (params.operation === 'get' || params.operation === 'delete') { + if (operation === 'get' || operation === 'delete') { if (!conversationId) { - errors.push(`Conversation ID is required for ${params.operation} operation`) + errors.push(`Conversation ID is required for ${operation} operation`) } } @@ -148,7 +150,7 @@ export const MemoryBlock: BlockConfig = { const baseResult: Record = {} - if (params.operation === 'add') { + if (operation === 'add') { return { ...baseResult, conversationId: conversationId, @@ -157,14 +159,14 @@ export const MemoryBlock: BlockConfig = { } } - if (params.operation === 'get') { + if (operation === 'get') { return { ...baseResult, conversationId: conversationId, } } - if (params.operation === 'delete') { + if (operation === 'delete') { return { ...baseResult, conversationId: conversationId, diff --git a/apps/sim/blocks/blocks/table.test.ts b/apps/sim/blocks/blocks/table.test.ts index 127789492a8..ed9208ffb6f 100644 --- a/apps/sim/blocks/blocks/table.test.ts +++ b/apps/sim/blocks/blocks/table.test.ts @@ -5,8 +5,11 @@ vi.mock('@/triggers', () => triggersMock) import { TableBlock } from '@/blocks/blocks/table' -function params(input: Record): Record { - return TableBlock.tools.config?.params?.(input as never) as Record +function params( + input: Record, + context?: { operation: string } +): Record { + return TableBlock.tools.config?.params?.(input as never, context) as Record } describe('table query_rows transformer', () => { @@ -33,3 +36,60 @@ describe('table query_rows transformer', () => { ).toBeUndefined() }) }) + +describe('table transformers on an Agent tool call (operation only in context)', () => { + const winsRule = [ + { id: '1', logicalOperator: 'and', column: 'wins', operator: 'gte', value: '10' }, + ] + + it('compiles the tool row builder filter and sort and coerces the limit', () => { + const out = params( + { + tableId: 'table-1', + builderMode: 'builder', + filterBuilder: winsRule, + sortBuilder: [{ id: '1', column: 'wins', direction: 'desc' }], + limit: 5, + }, + { operation: 'query_rows' } + ) + expect(out.filter).toEqual({ wins: { $gte: 10 } }) + expect(out.sort).toEqual({ wins: 'desc' }) + expect(out.limit).toBe(5) + }) + + it('keeps the model filter and sort when the stored builder rule list is empty', () => { + const out = params( + { + tableId: 'table-1', + builderMode: 'builder', + filterBuilder: [], + sortBuilder: [], + filter: { status: 'active' }, + sort: '{"wins":"desc"}', + }, + { operation: 'query_rows' } + ) + expect(out.filter).toEqual({ status: 'active' }) + expect(out.sort).toEqual({ wins: 'desc' }) + }) + + it('keeps the model filter for a bulk delete when the stored bulk builder is empty', () => { + const out = params( + { tableId: 'table-1', bulkFilterMode: 'builder', bulkFilterBuilder: [], filter: '{"a":1}' }, + { operation: 'delete_rows_by_filter' } + ) + expect(out.filter).toEqual({ a: 1 }) + }) + + it('leaves an empty canvas builder with no filter even when a stale JSON filter is saved', () => { + const out = params({ + operation: 'query_rows', + tableId: 'table-1', + builderMode: 'builder', + filterBuilder: [], + filter: '{"stale":true}', + }) + expect(out.filter).toBeUndefined() + }) +}) diff --git a/apps/sim/blocks/blocks/table.ts b/apps/sim/blocks/blocks/table.ts index 9a969db1d60..affb9ae5f1b 100644 --- a/apps/sim/blocks/blocks/table.ts +++ b/apps/sim/blocks/blocks/table.ts @@ -2,12 +2,15 @@ import { Table } from '@sim/emcn/icons' import { toError } from '@sim/utils/errors' import { TABLE_LIMITS } from '@/lib/table/constants' import { filterRulesToFilter, sortRulesToSort } from '@/lib/table/query-builder/converters' -import type { BlockConfig } from '@/blocks/types' +import type { BlockConfig, BlockToolParamsContext } from '@/blocks/types' import { + isToolCall, + mapperOperation, parseOptionalNumberInput, resolveTableColumnSelection, TABLE_OUTPUT_COLUMNS_INPUT, TABLE_OUTPUT_COLUMNS_SUBBLOCK, + toolCallArg, } from '@/blocks/utils' import { TABLE_ID_PARAM } from '@/tools/table/params' import { getTrigger } from '@/triggers' @@ -68,6 +71,8 @@ interface TableBlockParams { bulkFilterMode?: string bulkFilterBuilder?: unknown conflictColumn?: string + /** The tool's own `conflictTarget` param, set in an Agent tool row. */ + conflictTarget?: string } /** Normalized params after parsing, ready for tool request body */ @@ -83,17 +88,57 @@ interface ParsedParams { conflictTarget?: string } +/** + * Resolves a filter or sort from its builder rules when the builder is active, else from the + * JSON field. On a tool call a builder that yields nothing (a stored empty or incomplete rule + * list) falls back to the model's `filter`/`sort` arg instead of discarding it; the canvas keeps + * the builder's result. + */ +function resolveBuilderOrJson( + builderActive: boolean, + fromBuilder: () => unknown, + json: unknown, + fieldName: string, + context: BlockToolParamsContext | undefined +): unknown { + if (builderActive) { + const built = fromBuilder() || undefined + if (built !== undefined || !isToolCall(context) || !json) return built + } else if (!json) { + return undefined + } + return parseJSON(json, fieldName) +} + +function resolveBulkFilter( + params: TableBlockParams, + context: BlockToolParamsContext | undefined +): unknown { + return resolveBuilderOrJson( + params.bulkFilterMode === 'builder' && Boolean(params.bulkFilterBuilder), + () => + filterRulesToFilter(params.bulkFilterBuilder as Parameters[0]), + params.filter, + 'Filter', + context + ) +} + /** Transforms raw block params into tool request params for each operation */ -const paramTransformers: Record ParsedParams> = { +const paramTransformers: Record< + string, + (params: TableBlockParams, context: BlockToolParamsContext | undefined) => ParsedParams +> = { insert_row: (params) => ({ tableId: params.tableId, data: parseJSON(params.data, 'Row Data'), }), - upsert_row: (params) => ({ + upsert_row: (params, context) => ({ tableId: params.tableId, data: parseJSON(params.data, 'Row Data'), - conflictTarget: params.conflictColumn || undefined, + conflictTarget: + params.conflictColumn || toolCallArg(context, params.conflictTarget) || undefined, }), batch_insert_rows: (params) => ({ @@ -107,20 +152,10 @@ const paramTransformers: Record ParsedPara data: parseJSON(params.data, 'Row Data'), }), - update_rows_by_filter: (params) => { - let filter: unknown - if (params.bulkFilterMode === 'builder' && params.bulkFilterBuilder) { - filter = - filterRulesToFilter( - params.bulkFilterBuilder as Parameters[0] - ) || undefined - } else if (params.filter) { - filter = parseJSON(params.filter, 'Filter') - } - + update_rows_by_filter: (params, context) => { return { tableId: params.tableId, - filter, + filter: resolveBulkFilter(params, context), data: parseJSON(params.data, 'Row Data'), limit: parseOptionalNumberInput(params.limit, 'Limit', { integer: true, @@ -135,20 +170,10 @@ const paramTransformers: Record ParsedPara rowId: params.rowId, }), - delete_rows_by_filter: (params) => { - let filter: unknown - if (params.bulkFilterMode === 'builder' && params.bulkFilterBuilder) { - filter = - filterRulesToFilter( - params.bulkFilterBuilder as Parameters[0] - ) || undefined - } else if (params.filter) { - filter = parseJSON(params.filter, 'Filter') - } - + delete_rows_by_filter: (params, context) => { return { tableId: params.tableId, - filter, + filter: resolveBulkFilter(params, context), limit: parseOptionalNumberInput(params.limit, 'Limit', { integer: true, min: 1, @@ -166,23 +191,22 @@ const paramTransformers: Record ParsedPara tableId: params.tableId, }), - query_rows: (params) => { - let filter: unknown - if (params.builderMode === 'builder' && params.filterBuilder) { - filter = - filterRulesToFilter(params.filterBuilder as Parameters[0]) || - undefined - } else if (params.filter) { - filter = parseJSON(params.filter, 'Filter') - } - - let sort: unknown - if (params.builderMode === 'builder' && params.sortBuilder) { - sort = - sortRulesToSort(params.sortBuilder as Parameters[0]) || undefined - } else if (params.sort) { - sort = parseJSON(params.sort, 'Sort') - } + query_rows: (params, context) => { + const builderMode = params.builderMode === 'builder' + const filter = resolveBuilderOrJson( + builderMode && Boolean(params.filterBuilder), + () => filterRulesToFilter(params.filterBuilder as Parameters[0]), + params.filter, + 'Filter', + context + ) + const sort = resolveBuilderOrJson( + builderMode && Boolean(params.sortBuilder), + () => sortRulesToSort(params.sortBuilder as Parameters[0]), + params.sort, + 'Sort', + context + ) return { tableId: params.tableId, @@ -731,12 +755,12 @@ Return ONLY the sort JSON:`, } return toolMap[params.operation] || 'table_query_rows' }, - params: (params) => { + params: (params, context) => { const { operation, ...rest } = params - const transformer = paramTransformers[operation] + const transformer = paramTransformers[mapperOperation(params, context)] if (transformer) { - return transformer(rest as TableBlockParams) + return transformer(rest as TableBlockParams, context) } return rest diff --git a/apps/sim/blocks/blocks/table_v2.test.ts b/apps/sim/blocks/blocks/table_v2.test.ts index 356ca950197..0a320087e80 100644 --- a/apps/sim/blocks/blocks/table_v2.test.ts +++ b/apps/sim/blocks/blocks/table_v2.test.ts @@ -10,8 +10,11 @@ vi.mock('@/triggers', () => triggersMock) import { TableV2Block } from '@/blocks/blocks/table_v2' -function params(input: Record): Record { - return TableV2Block.tools.config?.params?.(input as never) as Record +function params( + input: Record, + context?: { operation: string } +): Record { + return TableV2Block.tools.config?.params?.(input as never, context) as Record } describe('table_v2 query_rows transformer', () => { @@ -173,3 +176,36 @@ describe('table_v2 blank and malformed editor inputs', () => { ) }) }) + +/** + * On an Agent tool call the operation arrives only in context, and the model's `filter`/`order` + * args have already been folded into the `filterInput`/`sortInput` canonical values. + */ +describe('table_v2 transformers on an Agent tool call', () => { + it('forwards the model filter as a predicate for a bulk update', () => { + const out = params( + { + tableId: 't', + filterInput: { field: 'status', op: 'eq', value: 'stale' }, + data: { archived: true }, + limit: 50, + }, + { operation: 'update_rows_by_filter' } + ) + expect(out.filter).toEqual({ all: [{ field: 'status', op: 'eq', value: 'stale' }] }) + expect(out.limit).toBe(50) + }) + + it('forwards the model order and filter for a query', () => { + const out = params( + { + tableId: 't', + filterInput: '{"field":"wins","op":"gte","value":10}', + sortInput: [{ field: 'wins', direction: 'desc' }], + }, + { operation: 'query_rows' } + ) + expect(out.filter).toEqual({ all: [{ field: 'wins', op: 'gte', value: 10 }] }) + expect(out.order).toEqual([{ field: 'wins', direction: 'desc' }]) + }) +}) diff --git a/apps/sim/blocks/blocks/table_v2.ts b/apps/sim/blocks/blocks/table_v2.ts index 94efed49f91..2f340ee80f3 100644 --- a/apps/sim/blocks/blocks/table_v2.ts +++ b/apps/sim/blocks/blocks/table_v2.ts @@ -11,11 +11,13 @@ import type { TablePredicate, TablePredicateInput, } from '@/lib/table/types' -import type { BlockConfig } from '@/blocks/types' +import type { BlockConfig, BlockToolParamsContext } from '@/blocks/types' import { + mapperOperation, resolveTableColumnSelection, TABLE_OUTPUT_COLUMNS_INPUT, TABLE_OUTPUT_COLUMNS_SUBBLOCK, + toolCallArg, } from '@/blocks/utils' import { TABLE_ID_PARAM } from '@/tools/table/params' import { getTrigger } from '@/triggers' @@ -62,9 +64,12 @@ interface TableBlockParams { columns?: unknown filterInput?: unknown sortInput?: unknown - limit?: string + /** A string on the canvas; a number when a model supplies it on a tool call. */ + limit?: string | number cursor?: string conflictColumn?: string + /** The tool's own `conflictTarget` param, set in an Agent tool row. */ + conflictTarget?: string } /** @@ -86,9 +91,24 @@ function resolveFilter(params: TableBlockParams): TablePredicate | undefined { return normalizeTablePredicate(predicate) } +/** + * A sort-spec array (`[{field, direction}]`), as a model passes the tool's `order` arg, rather + * than the visual builder's rules, which always carry `column`. + */ +function isSortSpec(raw: unknown[]): raw is SortSpec { + return ( + raw.length > 0 && + raw.every( + (entry) => + typeof entry === 'object' && entry !== null && 'field' in entry && !('column' in entry) + ) + ) +} + function resolveOrder(params: TableBlockParams): SortSpec | undefined { const raw = params.sortInput if (Array.isArray(raw)) { + if (isSortSpec(raw)) return raw return raw.length > 0 ? (sortRulesToSortSpec(raw as SortRule[]) ?? undefined) : undefined } const parsed = parseJSON(raw, 'Sort') @@ -112,11 +132,11 @@ interface ParsedParams { * Fail-fast limit parsing for bulk ops: an unparseable limit must never * silently widen the operation to every matching row. */ -function parseOptionalLimit(raw: string | undefined): number | undefined { - if (!raw) return undefined - const value = Number.parseInt(raw, 10) +function parseOptionalLimit(raw: unknown): number | undefined { + if (raw === undefined || raw === null || raw === '') return undefined + const value = typeof raw === 'number' ? Math.trunc(raw) : Number.parseInt(String(raw), 10) if (Number.isNaN(value)) { - throw new Error(`Invalid Limit "${raw}" — expected a number.`) + throw new Error(`Invalid Limit "${String(raw)}" — expected a number.`) } return value } @@ -130,16 +150,20 @@ function resolveCursor(raw: string | undefined): string | undefined { return raw } -const paramTransformers: Record ParsedParams> = { +const paramTransformers: Record< + string, + (params: TableBlockParams, context: BlockToolParamsContext | undefined) => ParsedParams +> = { insert_row: (params) => ({ tableId: params.tableId, data: parseJSON(params.data, 'Row Data'), }), - upsert_row: (params) => ({ + upsert_row: (params, context) => ({ tableId: params.tableId, data: parseJSON(params.data, 'Row Data'), - conflictTarget: params.conflictColumn || undefined, + conflictTarget: + params.conflictColumn || toolCallArg(context, params.conflictTarget) || undefined, }), batch_insert_rows: (params) => ({ @@ -542,11 +566,11 @@ Return ONLY the JSON object:`, } return toolMap[params.operation] || 'table_query_rows_v2' }, - params: (params) => { + params: (params, context) => { const { operation, ...rest } = params - const transformer = paramTransformers[operation] + const transformer = paramTransformers[mapperOperation(params, context)] if (transformer) { - return transformer(rest as TableBlockParams) + return transformer(rest as TableBlockParams, context) } return rest }, diff --git a/scripts/check-explicit-any.baseline.json b/scripts/check-explicit-any.baseline.json index 2bbf9f1f690..79166545ab7 100644 --- a/scripts/check-explicit-any.baseline.json +++ b/scripts/check-explicit-any.baseline.json @@ -78,7 +78,6 @@ "apps/sim/blocks/blocks/agent.ts": 6, "apps/sim/blocks/blocks/apify.ts": 2, "apps/sim/blocks/blocks/browser_use.ts": 2, - "apps/sim/blocks/blocks/context_dev.ts": 1, "apps/sim/blocks/blocks/deployments.ts": 2, "apps/sim/blocks/blocks/enrich.ts": 2, "apps/sim/blocks/blocks/evaluator.ts": 4, @@ -1194,7 +1193,6 @@ "apps/sim/background/workflow-execution.ts": 2, "apps/sim/blocks/blocks.test.ts": 7, "apps/sim/blocks/blocks/airtable.test.ts": 1, - "apps/sim/blocks/blocks/ashby.test.ts": 11, "apps/sim/blocks/blocks/cbinsights.test.ts": 2, "apps/sim/blocks/blocks/crunchbase.test.ts": 2, "apps/sim/blocks/blocks/google_slides.ts": 3, diff --git a/scripts/check-mapper-operation.baseline.json b/scripts/check-mapper-operation.baseline.json index f458b03593d..f6d8c547a3c 100644 --- a/scripts/check-mapper-operation.baseline.json +++ b/scripts/check-mapper-operation.baseline.json @@ -1,55 +1,14 @@ { - "apps/sim/blocks/blocks/affinity.ts": 1, - "apps/sim/blocks/blocks/agentmail.ts": 1, - "apps/sim/blocks/blocks/agentphone.ts": 1, - "apps/sim/blocks/blocks/algolia.ts": 1, - "apps/sim/blocks/blocks/amplitude.ts": 1, - "apps/sim/blocks/blocks/apollo.ts": 11, - "apps/sim/blocks/blocks/ashby.ts": 16, - "apps/sim/blocks/blocks/brightdata.ts": 1, - "apps/sim/blocks/blocks/buffer.ts": 2, - "apps/sim/blocks/blocks/cbinsights.ts": 1, - "apps/sim/blocks/blocks/checkr.ts": 6, - "apps/sim/blocks/blocks/circleback.ts": 2, - "apps/sim/blocks/blocks/clerk.ts": 1, - "apps/sim/blocks/blocks/coda.ts": 1, - "apps/sim/blocks/blocks/context_dev.ts": 1, - "apps/sim/blocks/blocks/crunchbase.ts": 1, - "apps/sim/blocks/blocks/deployments.ts": 1, - "apps/sim/blocks/blocks/docusign.ts": 1, - "apps/sim/blocks/blocks/downdetector.ts": 1, - "apps/sim/blocks/blocks/dub.ts": 23, - "apps/sim/blocks/blocks/elevenlabs.ts": 2, - "apps/sim/blocks/blocks/emailbison.ts": 6, - "apps/sim/blocks/blocks/enrich.ts": 1, - "apps/sim/blocks/blocks/enrichment.ts": 2, - "apps/sim/blocks/blocks/exa.ts": 1, - "apps/sim/blocks/blocks/file.ts": 3, - "apps/sim/blocks/blocks/firecrawl.ts": 1, - "apps/sim/blocks/blocks/fireflies.ts": 2, - "apps/sim/blocks/blocks/flint.ts": 1, - "apps/sim/blocks/blocks/gong.ts": 1, - "apps/sim/blocks/blocks/grain.ts": 2, - "apps/sim/blocks/blocks/greenhouse.ts": 2, - "apps/sim/blocks/blocks/harmonic.ts": 1, - "apps/sim/blocks/blocks/helpscout.ts": 2, - "apps/sim/blocks/blocks/hex.ts": 1, - "apps/sim/blocks/blocks/instagram.ts": 2, - "apps/sim/blocks/blocks/instantly.ts": 17, "apps/sim/blocks/blocks/jotform.ts": 1, "apps/sim/blocks/blocks/kalshi.ts": 1, "apps/sim/blocks/blocks/ketch.ts": 4, - "apps/sim/blocks/blocks/knowledge.ts": 11, "apps/sim/blocks/blocks/langsmith.ts": 4, - "apps/sim/blocks/blocks/latex.ts": 1, "apps/sim/blocks/blocks/launchdarkly.ts": 1, "apps/sim/blocks/blocks/linkedin.ts": 1, "apps/sim/blocks/blocks/linq.ts": 2, - "apps/sim/blocks/blocks/logs.ts": 2, "apps/sim/blocks/blocks/loops.ts": 1, "apps/sim/blocks/blocks/manageengine-sdp.ts": 2, "apps/sim/blocks/blocks/mem0.ts": 1, - "apps/sim/blocks/blocks/memory.ts": 8, "apps/sim/blocks/blocks/microsoft_dynamics_365.ts": 2, "apps/sim/blocks/blocks/mintlify.ts": 1, "apps/sim/blocks/blocks/netsuite.ts": 2, @@ -75,8 +34,6 @@ "apps/sim/blocks/blocks/smartlead.ts": 5, "apps/sim/blocks/blocks/snowflake.ts": 1, "apps/sim/blocks/blocks/stripe.ts": 1, - "apps/sim/blocks/blocks/table.ts": 1, - "apps/sim/blocks/blocks/table_v2.ts": 1, "apps/sim/blocks/blocks/tiktok.ts": 1, "apps/sim/blocks/blocks/vanta.ts": 1, "apps/sim/blocks/blocks/wealthbox.ts": 1, diff --git a/scripts/check-test-types.baseline.json b/scripts/check-test-types.baseline.json index 36e295e7ee2..ee5eba32d85 100644 --- a/scripts/check-test-types.baseline.json +++ b/scripts/check-test-types.baseline.json @@ -624,9 +624,6 @@ "apps/sim/blocks/blocks/airtable.test.ts": { "TS18048": 1 }, - "apps/sim/blocks/blocks/ashby.test.ts": { - "TS18048": 11 - }, "apps/sim/blocks/blocks/cloudtrail.test.ts": { "TS2554": 1 },