From 5ccfb37af2ab2ee53ab6d64d71b9cfc9dd60dc28 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 15 Nov 2026 16:41:46 -0800 Subject: [PATCH 1/4] =?UTF-8?q?fix(integrations):=20sweep2=20m1=20?= =?UTF-8?q?=E2=80=94=20read=20the=20mapper=20operation=20from=20the=20tool?= =?UTF-8?q?-call=20context=20and=20validate=20integrations=20against=20ven?= =?UTF-8?q?dor=20specs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/sim/blocks/blocks/athena.test.ts | 41 ++++++ apps/sim/blocks/blocks/athena.ts | 60 ++++---- apps/sim/blocks/blocks/azure_data_explorer.ts | 10 +- apps/sim/blocks/blocks/cloudflare.test.ts | 37 +++++ apps/sim/blocks/blocks/cloudflare.ts | 17 ++- apps/sim/blocks/blocks/cloudformation.test.ts | 32 +++++ apps/sim/blocks/blocks/cloudformation.ts | 24 ++-- apps/sim/blocks/blocks/cloudtrail.test.ts | 19 +++ apps/sim/blocks/blocks/cloudtrail.ts | 15 +- apps/sim/blocks/blocks/cloudwatch.test.ts | 26 ++++ apps/sim/blocks/blocks/cloudwatch.ts | 36 +++-- apps/sim/blocks/blocks/codepipeline.test.ts | 33 +++++ apps/sim/blocks/blocks/codepipeline.ts | 20 ++- apps/sim/blocks/blocks/crowdstrike.test.ts | 15 +- apps/sim/blocks/blocks/crowdstrike.ts | 18 ++- apps/sim/blocks/blocks/dagster.test.ts | 60 ++++++++ apps/sim/blocks/blocks/dagster.ts | 49 ++++--- apps/sim/blocks/blocks/daytona.test.ts | 38 +++++ apps/sim/blocks/blocks/daytona.ts | 18 ++- apps/sim/blocks/blocks/dynamodb.test.ts | 50 +++++++ apps/sim/blocks/blocks/dynamodb.ts | 27 ++-- apps/sim/blocks/blocks/dynatrace.test.ts | 44 ++++++ apps/sim/blocks/blocks/dynatrace.ts | 133 ++++++++++-------- apps/sim/blocks/blocks/fivetran.test.ts | 37 +++++ apps/sim/blocks/blocks/fivetran.ts | 54 ++++--- apps/sim/blocks/blocks/google_bigquery.ts | 5 +- apps/sim/blocks/blocks/grafana.test.ts | 29 ++++ apps/sim/blocks/blocks/grafana.ts | 16 +-- apps/sim/blocks/blocks/iam.test.ts | 30 ++++ apps/sim/blocks/blocks/iam.ts | 9 +- .../sim/blocks/blocks/identity_center.test.ts | 20 +++ apps/sim/blocks/blocks/identity_center.ts | 11 +- apps/sim/blocks/blocks/infisical.ts | 6 +- apps/sim/blocks/blocks/jupyter.ts | 49 ++++--- apps/sim/blocks/blocks/lambda.test.ts | 18 +++ apps/sim/blocks/blocks/lambda.ts | 8 +- apps/sim/blocks/blocks/logfire.ts | 6 +- apps/sim/blocks/blocks/logrocket.ts | 5 +- apps/sim/blocks/blocks/modal.test.ts | 17 +++ apps/sim/blocks/blocks/modal.ts | 9 +- apps/sim/blocks/blocks/new_relic.ts | 6 +- apps/sim/blocks/blocks/planetscale.test.ts | 21 +++ apps/sim/blocks/blocks/planetscale.ts | 48 ++++--- apps/sim/blocks/blocks/railway.test.ts | 21 +++ apps/sim/blocks/blocks/railway.ts | 128 +++++++++-------- apps/sim/blocks/blocks/rds.ts | 7 +- apps/sim/blocks/blocks/s3.test.ts | 42 ++++++ apps/sim/blocks/blocks/s3.ts | 43 ++++-- .../sim/blocks/blocks/secrets_manager.test.ts | 25 ++++ apps/sim/blocks/blocks/secrets_manager.ts | 10 +- apps/sim/blocks/blocks/ses.test.ts | 27 ++++ apps/sim/blocks/blocks/ses.ts | 21 ++- apps/sim/blocks/blocks/sftp.test.ts | 16 +++ apps/sim/blocks/blocks/sftp.ts | 12 +- apps/sim/blocks/blocks/splunk.test.ts | 29 +++- apps/sim/blocks/blocks/splunk.ts | 27 +++- apps/sim/blocks/blocks/sqs.test.ts | 22 +++ apps/sim/blocks/blocks/sqs.ts | 7 +- apps/sim/blocks/blocks/ssh.test.ts | 16 +++ apps/sim/blocks/blocks/ssh.ts | 31 ++-- apps/sim/blocks/blocks/ssm.test.ts | 36 +++++ apps/sim/blocks/blocks/ssm.ts | 71 ++++++---- apps/sim/blocks/blocks/stagehand.ts | 6 +- apps/sim/blocks/blocks/sts.ts | 8 +- apps/sim/blocks/blocks/supabase.ts | 6 +- apps/sim/blocks/blocks/tailscale.test.ts | 54 +++++++ apps/sim/blocks/blocks/tailscale.ts | 18 ++- apps/sim/blocks/blocks/temporal.test.ts | 37 +++++ apps/sim/blocks/blocks/temporal.ts | 59 +++++--- apps/sim/blocks/blocks/textract.test.ts | 38 +++++ apps/sim/blocks/blocks/textract.ts | 41 ++++-- apps/sim/blocks/blocks/tinybird.test.ts | 28 ++++ apps/sim/blocks/blocks/tinybird.ts | 11 +- apps/sim/blocks/blocks/tinyfish.ts | 9 +- apps/sim/blocks/blocks/trigger_dev.test.ts | 28 ++++ apps/sim/blocks/blocks/trigger_dev.ts | 14 +- apps/sim/blocks/blocks/vercel.test.ts | 52 +++++++ apps/sim/blocks/blocks/vercel.ts | 100 +++++++------ apps/sim/tools/tinyfish/tinyfish.test.ts | 6 + 79 files changed, 1797 insertions(+), 535 deletions(-) create mode 100644 apps/sim/blocks/blocks/athena.test.ts create mode 100644 apps/sim/blocks/blocks/cloudformation.test.ts create mode 100644 apps/sim/blocks/blocks/cloudwatch.test.ts create mode 100644 apps/sim/blocks/blocks/codepipeline.test.ts create mode 100644 apps/sim/blocks/blocks/dagster.test.ts create mode 100644 apps/sim/blocks/blocks/daytona.test.ts create mode 100644 apps/sim/blocks/blocks/dynamodb.test.ts create mode 100644 apps/sim/blocks/blocks/dynatrace.test.ts create mode 100644 apps/sim/blocks/blocks/fivetran.test.ts create mode 100644 apps/sim/blocks/blocks/grafana.test.ts create mode 100644 apps/sim/blocks/blocks/identity_center.test.ts create mode 100644 apps/sim/blocks/blocks/planetscale.test.ts create mode 100644 apps/sim/blocks/blocks/railway.test.ts create mode 100644 apps/sim/blocks/blocks/s3.test.ts create mode 100644 apps/sim/blocks/blocks/secrets_manager.test.ts create mode 100644 apps/sim/blocks/blocks/ses.test.ts create mode 100644 apps/sim/blocks/blocks/sftp.test.ts create mode 100644 apps/sim/blocks/blocks/ssh.test.ts create mode 100644 apps/sim/blocks/blocks/ssm.test.ts create mode 100644 apps/sim/blocks/blocks/tailscale.test.ts create mode 100644 apps/sim/blocks/blocks/temporal.test.ts create mode 100644 apps/sim/blocks/blocks/textract.test.ts create mode 100644 apps/sim/blocks/blocks/tinybird.test.ts create mode 100644 apps/sim/blocks/blocks/trigger_dev.test.ts create mode 100644 apps/sim/blocks/blocks/vercel.test.ts diff --git a/apps/sim/blocks/blocks/athena.test.ts b/apps/sim/blocks/blocks/athena.test.ts new file mode 100644 index 00000000000..cdbee96774b --- /dev/null +++ b/apps/sim/blocks/blocks/athena.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, it } from 'vitest' +import { AthenaBlock } from '@/blocks/blocks/athena' + +/** + * An agent tool call sends model args under the tool's param names (`workGroup`, `queryStatement`, + * `name`) with the operation only on `context`; the handler forwards `{ ...args, ...mapped }`. + */ +const agentCall = (operation: string, args: Record): Record => ({ + ...args, + ...(AthenaBlock.tools.config?.params?.(args, { operation }) ?? {}), +}) + +const CREDENTIALS = { awsRegion: 'us-east-1', awsAccessKeyId: 'AKIA', awsSecretAccessKey: 'secret' } + +describe('AthenaBlock agent tool calls', () => { + it('keeps the model prepared statement workgroup and statement instead of throwing', () => { + expect( + agentCall('create_prepared_statement', { + ...CREDENTIALS, + statementName: 'by_day', + workGroup: 'primary', + queryStatement: 'SELECT * FROM t WHERE d = ?', + description: 'Daily rows', + }) + ).toMatchObject({ + statementName: 'by_day', + workGroup: 'primary', + queryStatement: 'SELECT * FROM t WHERE d = ?', + description: 'Daily rows', + }) + }) + + it('keeps the model catalog name and coerces maxResults on list calls', () => { + expect(agentCall('get_data_catalog', { ...CREDENTIALS, name: 'AwsDataCatalog' })).toMatchObject( + { name: 'AwsDataCatalog' } + ) + expect(agentCall('list_named_queries', { ...CREDENTIALS, maxResults: '5' })).toMatchObject({ + maxResults: 5, + }) + }) +}) diff --git a/apps/sim/blocks/blocks/athena.ts b/apps/sim/blocks/blocks/athena.ts index eb99711a3ca..a3b2d4580c2 100644 --- a/apps/sim/blocks/blocks/athena.ts +++ b/apps/sim/blocks/blocks/athena.ts @@ -1,7 +1,7 @@ import { AthenaIcon } 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' /** * Normalizes a switch value that may arrive as a boolean or as the strings 'true' / 'false'. @@ -681,8 +681,9 @@ Return ONLY a JSON array of strings — no explanations, no markdown code blocks throw new Error(`Invalid Athena operation: ${params.operation}`) } }, - params: (params) => { - const { operation, maxResults, ...rest } = params + params: (params, context) => { + const { maxResults, ...rest } = params + const operation = mapperOperation(params, context) const awsRegion = rest.awsRegion const awsAccessKeyId = rest.awsAccessKeyId @@ -696,6 +697,9 @@ Return ONLY a JSON array of strings — no explanations, no markdown code blocks rest.resultReuseMaxAgeInMinutes !== '' ? Number.parseInt(String(rest.resultReuseMaxAgeInMinutes), 10) : undefined + const queryName = rest.queryName || toolCallArg(context, rest.name) + const queryDescription = rest.queryDescription || toolCallArg(context, rest.description) + const workGroupName = rest.workGroupName || toolCallArg(context, rest.workGroup) switch (operation) { case 'start_query': @@ -766,7 +770,7 @@ Return ONLY a JSON array of strings — no explanations, no markdown code blocks } case 'create_named_query': { - if (!rest.queryName) { + if (!queryName) { throw new Error('Query name is required') } if (!rest.database) { @@ -779,10 +783,10 @@ Return ONLY a JSON array of strings — no explanations, no markdown code blocks awsRegion, awsAccessKeyId, awsSecretAccessKey, - name: rest.queryName, + name: queryName, database: rest.database, queryString: rest.queryString, - ...(rest.queryDescription && { description: rest.queryDescription }), + ...(queryDescription && { description: queryDescription }), ...(rest.workGroup && { workGroup: rest.workGroup }), } } @@ -879,7 +883,7 @@ Return ONLY a JSON array of strings — no explanations, no markdown code blocks if (!rest.namedQueryId) { throw new Error('Named query ID is required') } - if (!rest.queryName) { + if (!queryName) { throw new Error('Query name is required') } if (!rest.queryString) { @@ -888,64 +892,66 @@ Return ONLY a JSON array of strings — no explanations, no markdown code blocks return { ...connection, namedQueryId: rest.namedQueryId, - name: rest.queryName, + name: queryName, queryString: rest.queryString, - ...(rest.queryDescription && { description: rest.queryDescription }), + ...(queryDescription && { description: queryDescription }), } case 'create_prepared_statement': - case 'update_prepared_statement': + case 'update_prepared_statement': { + const queryStatement = rest.queryString || toolCallArg(context, rest.queryStatement) if (!rest.statementName) { throw new Error('Statement name is required') } - if (!rest.workGroupName) { + if (!workGroupName) { throw new Error('Workgroup is required') } - if (!rest.queryString) { + if (!queryStatement) { throw new Error('SQL query statement is required') } return { ...connection, statementName: rest.statementName, - workGroup: rest.workGroupName, - queryStatement: rest.queryString, - ...(rest.queryDescription && { description: rest.queryDescription }), + workGroup: workGroupName, + queryStatement, + ...(queryDescription && { description: queryDescription }), } + } case 'get_prepared_statement': case 'delete_prepared_statement': if (!rest.statementName) { throw new Error('Statement name is required') } - if (!rest.workGroupName) { + if (!workGroupName) { throw new Error('Workgroup is required') } return { ...connection, statementName: rest.statementName, - workGroup: rest.workGroupName, + workGroup: workGroupName, } case 'batch_get_prepared_statement': if (!rest.preparedStatementNames) { throw new Error('Statement names are required') } - if (!rest.workGroupName) { + if (!workGroupName) { throw new Error('Workgroup is required') } return { ...connection, preparedStatementNames: rest.preparedStatementNames, - workGroup: rest.workGroupName, + workGroup: workGroupName, } case 'list_prepared_statements': - if (!rest.workGroupName) { + if (!workGroupName) { throw new Error('Workgroup is required') } return { ...connection, - workGroup: rest.workGroupName, + workGroup: workGroupName, ...(parsedMaxResults !== undefined && { maxResults: parsedMaxResults }), ...(rest.nextToken && { nextToken: rest.nextToken }), } @@ -958,15 +964,17 @@ Return ONLY a JSON array of strings — no explanations, no markdown code blocks ...(rest.nextToken && { nextToken: rest.nextToken }), } - case 'get_data_catalog': - if (!rest.catalogName) { + case 'get_data_catalog': { + const catalogName = rest.catalogName || toolCallArg(context, rest.name) + if (!catalogName) { throw new Error('Data catalog name is required') } return { ...connection, - name: rest.catalogName, + name: catalogName, ...(rest.workGroup && { workGroup: rest.workGroup }), } + } case 'get_database': if (!rest.catalogName) { @@ -1008,10 +1016,10 @@ Return ONLY a JSON array of strings — no explanations, no markdown code blocks } case 'get_work_group': - if (!rest.workGroupName) { + if (!workGroupName) { throw new Error('Workgroup is required') } - return { ...connection, workGroup: rest.workGroupName } + return { ...connection, workGroup: workGroupName } default: throw new Error(`Invalid Athena operation: ${operation}`) diff --git a/apps/sim/blocks/blocks/azure_data_explorer.ts b/apps/sim/blocks/blocks/azure_data_explorer.ts index 8327179942c..58822a49571 100644 --- a/apps/sim/blocks/blocks/azure_data_explorer.ts +++ b/apps/sim/blocks/blocks/azure_data_explorer.ts @@ -1,7 +1,7 @@ import { AzureDataExplorerIcon } 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' /** Every operation except the cluster-level database listing runs in a database. */ const DATABASE_SCOPED_OPERATIONS = [ @@ -423,7 +423,7 @@ export const AzureDataExplorerBlock: BlockConfig = { ], config: { tool: (params) => params.operation, - params: (params) => { + params: (params, context) => { const auth = { clusterUri: params.clusterUri, tenantId: params.tenantId, @@ -432,7 +432,7 @@ export const AzureDataExplorerBlock: BlockConfig = { resource: params.resource || undefined, } - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'azure_data_explorer_query': return { ...auth, @@ -467,9 +467,9 @@ export const AzureDataExplorerBlock: BlockConfig = { ...auth, database: params.database, table: params.table, - mode: params.ingestMode || undefined, + mode: params.ingestMode || toolCallArg(context, params.mode) || undefined, sourceQuery: params.sourceQuery, - async: toBoolean(params.ingestAsync), + async: toBoolean(params.ingestAsync) ?? toBoolean(toolCallArg(context, params.async)), ingestionProperties: params.ingestionProperties || undefined, } case 'azure_data_explorer_create_table': diff --git a/apps/sim/blocks/blocks/cloudflare.test.ts b/apps/sim/blocks/blocks/cloudflare.test.ts index 320d41cb2dc..ac1de8b7123 100644 --- a/apps/sim/blocks/blocks/cloudflare.test.ts +++ b/apps/sim/blocks/blocks/cloudflare.test.ts @@ -233,3 +233,40 @@ describe('Cloudflare migration convergence', () => { expect(second.blocks['block-1'].subBlocks.recordProxied?.value).toBe('true') }) }) + +/** + * An agent tool call sends model args under the tool's param names (`type`, `files`) with the + * operation only on `context`; the handler forwards `{ ...args, ...mapped }`. + */ +describe('Cloudflare agent tool calls', () => { + const agentCall = ( + operation: string, + args: Record + ): Record => ({ + ...args, + ...CloudflareBlock.tools.config?.params?.(args, { operation }), + }) + + it('keeps the model record type that the canvas reads from an alias subBlock', () => { + expect( + agentCall('create_dns_record', { + ...CREDENTIALS, + zoneId: 'zone-1', + type: 'CNAME', + name: 'app.example.com', + content: 'origin.example.com', + }) + ).toMatchObject({ type: 'CNAME' }) + }) + + it('drops file targets when the model purges everything', () => { + expect( + agentCall('purge_cache', { + ...CREDENTIALS, + zoneId: 'zone-1', + purge_everything: true, + files: 'https://example.com/a.css', + }).files + ).toBeUndefined() + }) +}) diff --git a/apps/sim/blocks/blocks/cloudflare.ts b/apps/sim/blocks/blocks/cloudflare.ts index b1b6ce473b2..f2bbe0ba8c4 100644 --- a/apps/sim/blocks/blocks/cloudflare.ts +++ b/apps/sim/blocks/blocks/cloudflare.ts @@ -1,6 +1,6 @@ import { CloudflareIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { isToolCall, mapperOperation, withSavedCredential } from '@/blocks/utils' /** Advanced inputs serialize before conditions; separate aliases prevent hidden values crossing operations. */ const SUBBLOCK_ALIASES: Record> = { @@ -4521,11 +4521,16 @@ export const CloudflareBlock: BlockConfig = { ], config: { tool: (params) => `cloudflare_${params.operation}`, - params: (params) => { + params: (params, context) => { const result = { ...params } - const operation = typeof result.operation === 'string' ? result.operation : '' - for (const [toolParam, aliasId] of Object.entries(SUBBLOCK_ALIASES[operation] ?? {})) - result[toolParam] = result[aliasId] + const operation = mapperOperation(params, context) ?? '' + const toolCall = isToolCall(context) + for (const [toolParam, aliasId] of Object.entries(SUBBLOCK_ALIASES[operation] ?? {})) { + const aliasValue = result[aliasId] + const aliasBlank = aliasValue === undefined || aliasValue === null || aliasValue === '' + // A tool call carries the model's value under the tool's own param name. + if (!(toolCall && aliasBlank)) result[toolParam] = aliasValue + } for (const aliasId of ALIASED_SUBBLOCK_IDS) result[aliasId] = void 0 if (result.proxied === 'true') result.proxied = !0 else if (result.proxied === 'false') result.proxied = !1 @@ -4545,7 +4550,7 @@ export const CloudflareBlock: BlockConfig = { if (result.match === '') result.match = void 0 if (result.tag_match === '') result.tag_match = void 0 if (result.deploy === '') result.deploy = void 0 - if (result.operation === 'update_dns_record') { + if (operation === 'update_dns_record') { if (result.content === '') result.content = void 0 if (result.name === '') result.name = void 0 if (result.comment === '') result.comment = void 0 diff --git a/apps/sim/blocks/blocks/cloudformation.test.ts b/apps/sim/blocks/blocks/cloudformation.test.ts new file mode 100644 index 00000000000..5b6165f6f86 --- /dev/null +++ b/apps/sim/blocks/blocks/cloudformation.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest' +import { CloudFormationBlock } from '@/blocks/blocks/cloudformation' + +/** + * An agent tool call sends model args under the tool's param names (`description`, `tags`) with + * the operation only on `context`; the handler forwards `{ ...args, ...mapped }`. + */ +const agentCall = (operation: string, args: Record): Record => ({ + ...args, + ...(CloudFormationBlock.tools.config?.params?.(args, { operation }) ?? {}), +}) + +describe('CloudFormationBlock agent tool calls', () => { + it('keeps the model change set description and tags', () => { + expect( + agentCall('create_change_set', { + awsRegion: 'us-east-1', + awsAccessKeyId: 'AKIA', + awsSecretAccessKey: 'secret', + stackName: 'app', + changeSetName: 'cs-1', + usePreviousTemplate: true, + description: 'Bump instance size', + tags: [{ Key: 'team', Value: 'infra' }], + }) + ).toMatchObject({ + usePreviousTemplate: true, + description: 'Bump instance size', + tags: [{ Key: 'team', Value: 'infra' }], + }) + }) +}) diff --git a/apps/sim/blocks/blocks/cloudformation.ts b/apps/sim/blocks/blocks/cloudformation.ts index 75eb9753de0..443c84f62dc 100644 --- a/apps/sim/blocks/blocks/cloudformation.ts +++ b/apps/sim/blocks/blocks/cloudformation.ts @@ -2,7 +2,7 @@ import { getErrorMessage } from '@sim/utils/errors' import { CloudFormationIcon } 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' export const CloudFormationBlock: BlockConfig = { type: 'cloudformation', @@ -420,16 +420,9 @@ Return ONLY valid JSON - no explanations, no markdown code blocks.`, throw new Error(`Invalid CloudFormation operation: ${params.operation}`) } }, - params: (params) => { - const { - operation, - limit, - usePreviousTemplate, - parameters, - tags, - timeoutInMinutes, - ...rest - } = params + params: (params, context) => { + const { limit, usePreviousTemplate, parameters, tags, timeoutInMinutes, ...rest } = params + const operation = mapperOperation(params, context) const awsRegion = rest.awsRegion const awsAccessKeyId = rest.awsAccessKeyId @@ -530,6 +523,7 @@ Return ONLY valid JSON - no explanations, no markdown code blocks.`, } case 'create_change_set': { + const description = rest.changeSetDescription || toolCallArg(context, rest.description) if (!rest.stackName) throw new Error('Stack name is required') if (!rest.changeSetName) throw new Error('Change set name is required') if (!rest.templateBody && !parsedUsePreviousTemplate) { @@ -548,8 +542,12 @@ Return ONLY valid JSON - no explanations, no markdown code blocks.`, ...(parameters && { parameters: parseJson(parameters, 'parameters') }), ...(rest.capabilities && { capabilities: rest.capabilities }), ...(rest.changeSetType && { changeSetType: rest.changeSetType }), - ...(rest.changeSetDescription && { description: rest.changeSetDescription }), - tags: rest.changeSetTags ? parseJson(rest.changeSetTags, 'tags') : undefined, + ...(description && { description }), + tags: rest.changeSetTags + ? parseJson(rest.changeSetTags, 'tags') + : isToolCall(context) + ? parseJson(tags, 'tags') + : undefined, ...(rest.roleArn && { roleArn: rest.roleArn }), } } diff --git a/apps/sim/blocks/blocks/cloudtrail.test.ts b/apps/sim/blocks/blocks/cloudtrail.test.ts index 71f7bd44062..bcc734a9ace 100644 --- a/apps/sim/blocks/blocks/cloudtrail.test.ts +++ b/apps/sim/blocks/blocks/cloudtrail.test.ts @@ -50,3 +50,22 @@ describe('CloudTrail block defaults', () => { expect(() => CloudTrailBlock.tools.config?.params?.(params)).toThrow(/filter/i) }) }) + +/** + * An agent tool call sends model args under the tool's param names (`name` for a trail) with the + * operation only on `context`; the handler forwards `{ ...args, ...mapped }`. + */ +describe('CloudTrail agent tool calls', () => { + it('keeps the model trail name for get_trail', () => { + const args = { + awsRegion: 'us-east-1', + awsAccessKeyId: 'AKIA', + awsSecretAccessKey: 'secret', + name: 'org-trail', + } + expect({ + ...args, + ...CloudTrailBlock.tools.config?.params?.(args, { operation: 'get_trail' }), + }).toMatchObject({ name: 'org-trail' }) + }) +}) diff --git a/apps/sim/blocks/blocks/cloudtrail.ts b/apps/sim/blocks/blocks/cloudtrail.ts index 75d437d0530..7ea4372fef2 100644 --- a/apps/sim/blocks/blocks/cloudtrail.ts +++ b/apps/sim/blocks/blocks/cloudtrail.ts @@ -1,7 +1,7 @@ import { CloudTrailIcon } 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 accept an opaque AWS pagination token. */ const PAGINATED_OPERATIONS = [ @@ -427,8 +427,9 @@ Return ONLY the SQL query — no explanations, no markdown code blocks.`, throw new Error(`Invalid CloudTrail operation: ${params.operation}`) } }, - params: (params) => { - const { operation, ...rest } = params + params: (params, context) => { + const rest = params + const operation = mapperOperation(params, context) const awsRegion = rest.awsRegion const awsAccessKeyId = rest.awsAccessKeyId @@ -466,11 +467,13 @@ Return ONLY the SQL query — no explanations, no markdown code blocks.`, } case 'get_trail': - case 'get_trail_status': - if (!rest.trailName) { + case 'get_trail_status': { + const name = rest.trailName || toolCallArg(context, rest.name) + if (!name) { throw new Error('Trail name or ARN is required') } - return { ...credentials, name: rest.trailName } + return { ...credentials, name } + } case 'list_trails': return { diff --git a/apps/sim/blocks/blocks/cloudwatch.test.ts b/apps/sim/blocks/blocks/cloudwatch.test.ts new file mode 100644 index 00000000000..f4b70cde60e --- /dev/null +++ b/apps/sim/blocks/blocks/cloudwatch.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from 'vitest' +import { CloudWatchV2Block } from '@/blocks/blocks/cloudwatch' +import type { BlockToolParamsContext } from '@/blocks/types' + +const mapParams = CloudWatchV2Block.tools.config?.params +if (!mapParams) { + throw new Error('CloudWatch block must define tools.config.params') +} + +/** The tool-call merge: the mapped params land over the model's args (`{ ...args, ...mapped }`). */ +function merge(args: Record, context?: BlockToolParamsContext) { + return { ...args, ...mapParams(args, context) } +} + +describe('CloudWatch block params', () => { + it('publishes a metric from model args named by the tool when the operation is only in the context', () => { + const merged = merge( + { namespace: 'Custom/App', metricName: 'Hits', value: 3 }, + { operation: 'put_metric_data' } + ) + + expect(merged.namespace).toBe('Custom/App') + expect(merged.metricName).toBe('Hits') + expect(merged.value).toBe(3) + }) +}) diff --git a/apps/sim/blocks/blocks/cloudwatch.ts b/apps/sim/blocks/blocks/cloudwatch.ts index 83445492d2e..e99edcd0141 100644 --- a/apps/sim/blocks/blocks/cloudwatch.ts +++ b/apps/sim/blocks/blocks/cloudwatch.ts @@ -1,7 +1,7 @@ import { CloudWatchIcon } 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' /* * Canonical basic/advanced pairs, shared by the card sentences below. Listing @@ -761,8 +761,9 @@ Return ONLY the numeric timestamp - no explanations, no quotes, no extra text.`, throw new Error(`Invalid CloudWatch operation: ${params.operation}`) } }, - params: (params) => { - const { operation, startTime, endTime, limit, ...rest } = params + params: (params, context) => { + const operation = mapperOperation(params, context) + const { startTime, endTime, limit, ...rest } = params const awsRegion = rest.awsRegion const awsAccessKeyId = rest.awsAccessKeyId @@ -903,7 +904,8 @@ Return ONLY the numeric timestamp - no explanations, no quotes, no extra text.`, } case 'get_metric_statistics': { - if (!rest.metricNamespace) { + const namespace = rest.metricNamespace || toolCallArg(context, rest.namespace) + if (!namespace) { throw new Error('Namespace is required') } if (!rest.metricName) { @@ -915,12 +917,13 @@ Return ONLY the numeric timestamp - no explanations, no quotes, no extra text.`, if (!endTime) { throw new Error('End time is required') } - if (!rest.metricPeriod) { + const period = rest.metricPeriod || toolCallArg(context, rest.period) + if (!period) { throw new Error('Period is required') } - const stat = rest.metricStatistics - if (!stat) { + const stat = rest.metricStatistics || toolCallArg(context, rest.statistics) + if (!stat && !toolCallArg(context, rest.extendedStatistics)) { throw new Error('Statistics is required') } @@ -928,12 +931,12 @@ Return ONLY the numeric timestamp - no explanations, no quotes, no extra text.`, awsRegion, awsAccessKeyId, awsSecretAccessKey, - namespace: rest.metricNamespace, + namespace, metricName: rest.metricName, startTime: Number(startTime), endTime: Number(endTime), - period: Number(rest.metricPeriod), - statistics: Array.isArray(stat) ? stat : [stat], + period: Number(period), + ...(stat && { statistics: Array.isArray(stat) ? stat : [stat] }), ...(rest.metricExtendedStatistics && { extendedStatistics: Array.isArray(rest.metricExtendedStatistics) ? rest.metricExtendedStatistics @@ -963,16 +966,21 @@ Return ONLY the numeric timestamp - no explanations, no quotes, no extra text.`, } case 'put_metric_data': { - if (!rest.metricNamespace) { + const namespace = rest.metricNamespace || toolCallArg(context, rest.namespace) + if (!namespace) { throw new Error('Namespace is required') } if (!rest.metricName) { throw new Error('Metric name is required') } - if (rest.metricValue === undefined || rest.metricValue === '') { + const metricValue = + rest.metricValue === undefined || rest.metricValue === '' + ? toolCallArg(context, rest.value) + : rest.metricValue + if (metricValue === undefined || metricValue === '') { throw new Error('Metric value is required') } - const numericValue = Number(rest.metricValue) + const numericValue = Number(metricValue) if (!Number.isFinite(numericValue)) { throw new Error('Metric value must be a finite number') } @@ -981,7 +989,7 @@ Return ONLY the numeric timestamp - no explanations, no quotes, no extra text.`, awsRegion, awsAccessKeyId, awsSecretAccessKey, - namespace: rest.metricNamespace, + namespace, metricName: rest.metricName, value: numericValue, ...(rest.metricUnit && rest.metricUnit !== 'None' && { unit: rest.metricUnit }), diff --git a/apps/sim/blocks/blocks/codepipeline.test.ts b/apps/sim/blocks/blocks/codepipeline.test.ts new file mode 100644 index 00000000000..23d9ae67134 --- /dev/null +++ b/apps/sim/blocks/blocks/codepipeline.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from 'vitest' +import { CodePipelineV2Block } from '@/blocks/blocks/codepipeline' +import type { BlockToolParamsContext } from '@/blocks/types' + +const mapParams = CodePipelineV2Block.tools.config?.params +if (!mapParams) { + throw new Error('CodePipeline block must define tools.config.params') +} + +/** The tool-call merge: the mapped params land over the model's args (`{ ...args, ...mapped }`). */ +function merge(args: Record, context?: BlockToolParamsContext) { + return { ...args, ...mapParams(args, context) } +} + +describe('CodePipeline block params', () => { + it('keeps the model approval decision on a tool call, where the operation is only in the context', () => { + const merged = merge( + { + pipelineName: 'deploy', + stageName: 'Prod', + actionName: 'ManualApproval', + token: 'tok-1', + status: 'Rejected', + summary: 'Failing canary', + }, + { operation: 'put_approval_result' } + ) + + expect(merged.token).toBe('tok-1') + expect(merged.status).toBe('Rejected') + expect(merged.summary).toBe('Failing canary') + }) +}) diff --git a/apps/sim/blocks/blocks/codepipeline.ts b/apps/sim/blocks/blocks/codepipeline.ts index 1a67d1dcced..53774759002 100644 --- a/apps/sim/blocks/blocks/codepipeline.ts +++ b/apps/sim/blocks/blocks/codepipeline.ts @@ -2,9 +2,11 @@ import { CodePipelineIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' import { + mapperOperation, parseOptionalBooleanInput, parseOptionalJsonInput, parseOptionalNumberInput, + toolCallArg, withSavedCredential, } from '@/blocks/utils' @@ -397,8 +399,14 @@ export const CodePipelineBlock: BlockConfig = { throw new Error(`Invalid CodePipeline operation: ${params.operation}`) } }, - params: (params) => { - const { operation, maxResults, getPipelineVersion, ...rest } = params + params: (params, context) => { + const operation = mapperOperation(params, context) + const { maxResults, getPipelineVersion, ...rest } = params + /** A blank block-only field yields, on a tool call, the model's arg under the tool's name. */ + const orToolArg = (blockValue: unknown, toolValue: unknown) => + blockValue === undefined || blockValue === '' + ? (toolCallArg(context, toolValue) ?? blockValue) + : blockValue const awsRegion = rest.awsRegion const awsAccessKeyId = rest.awsAccessKeyId @@ -530,9 +538,9 @@ export const CodePipelineBlock: BlockConfig = { pipelineName: rest.pipelineName, stageName: rest.stageName, actionName: rest.actionName, - token: rest.approvalToken, - status: rest.approvalStatus, - summary: rest.approvalSummary, + token: orToolArg(rest.approvalToken, rest.token), + status: orToolArg(rest.approvalStatus, rest.status), + summary: orToolArg(rest.approvalSummary, rest.summary), } case 'disable_stage_transition': @@ -543,7 +551,7 @@ export const CodePipelineBlock: BlockConfig = { pipelineName: rest.pipelineName, stageName: rest.stageName, transitionType: rest.transitionType, - reason: rest.transitionReason, + reason: orToolArg(rest.transitionReason, rest.reason), } case 'enable_stage_transition': diff --git a/apps/sim/blocks/blocks/crowdstrike.test.ts b/apps/sim/blocks/blocks/crowdstrike.test.ts index 646c499a851..488a41da81c 100644 --- a/apps/sim/blocks/blocks/crowdstrike.test.ts +++ b/apps/sim/blocks/blocks/crowdstrike.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest' import { CrowdStrikeBlock } from '@/blocks/blocks/crowdstrike' +import type { BlockToolParamsContext } from '@/blocks/types' const mapParams = CrowdStrikeBlock.tools.config?.params if (!mapParams) { @@ -18,8 +19,8 @@ const credentials = { * subBlock value. Every assertion here runs against the merged result, because a * mapper-only assertion passes even when the raw value survives onto the wire. */ -function merge(inputs: Record) { - return { ...inputs, ...mapParams(inputs) } +function merge(inputs: Record, context?: BlockToolParamsContext) { + return { ...inputs, ...mapParams(inputs, context) } } describe('CrowdStrike block params', () => { @@ -146,4 +147,14 @@ describe('CrowdStrike block params', () => { expect(merged.includeHidden).toBe(false) }) + + it('keeps the model host action and hosts on a tool call, where the operation is only in the context', () => { + const merged = merge( + { ...credentials, actionName: 'lift_containment', deviceIds: ['aid-1'] }, + { operation: 'crowdstrike_perform_host_action' } + ) + + expect(merged.actionName).toBe('lift_containment') + expect(merged.deviceIds).toEqual(['aid-1']) + }) }) diff --git a/apps/sim/blocks/blocks/crowdstrike.ts b/apps/sim/blocks/blocks/crowdstrike.ts index 0e713d6bec7..a9e7d5a1415 100644 --- a/apps/sim/blocks/blocks/crowdstrike.ts +++ b/apps/sim/blocks/blocks/crowdstrike.ts @@ -2,9 +2,11 @@ import { CrowdStrikeIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' import { + mapperOperation, parseOptionalBooleanInput, parseOptionalJsonInput, parseOptionalNumberInput, + toolCallArg, withSavedCredential, } from '@/blocks/utils' @@ -840,8 +842,8 @@ export const CrowdStrikeBlock: BlockConfig = { config: { tool: (params) => typeof params.operation === 'string' ? params.operation : 'crowdstrike_query_alerts', - params: (params) => { - const operation = typeof params.operation === 'string' ? params.operation : '' + params: (params, context) => { + const operation = mapperOperation(params, context) /** * The executor merges this result over the raw block inputs, so a key this @@ -928,14 +930,20 @@ export const CrowdStrikeBlock: BlockConfig = { setJson('actionParameters', params.actionParameters, 'action parameters') break case 'crowdstrike_perform_host_action': - setString('actionName', params.hostActionName) + setString( + 'actionName', + params.hostActionName || toolCallArg(context, params.actionName) + ) setJson('deviceIds', params.deviceIds, 'host agent IDs') break case 'crowdstrike_get_host_group_details': setJson('hostGroupIds', params.hostGroupIds, 'host group IDs') break case 'crowdstrike_perform_host_group_action': - setString('actionName', params.hostGroupActionName) + setString( + 'actionName', + params.hostGroupActionName || toolCallArg(context, params.actionName) + ) setString('hostGroupId', params.hostGroupId) setJson('deviceIds', params.deviceIds, 'host agent IDs') break @@ -951,7 +959,7 @@ export const CrowdStrikeBlock: BlockConfig = { break case 'crowdstrike_delete_indicators': setJson('indicatorIds', params.indicatorIds, 'indicator IDs') - setString('filter', params.deleteFilter) + setString('filter', params.deleteFilter || toolCallArg(context, params.filter)) setString('comment', params.comment) break case 'crowdstrike_get_vulnerability_details': diff --git a/apps/sim/blocks/blocks/dagster.test.ts b/apps/sim/blocks/blocks/dagster.test.ts new file mode 100644 index 00000000000..de353d98bed --- /dev/null +++ b/apps/sim/blocks/blocks/dagster.test.ts @@ -0,0 +1,60 @@ +/** + * An Agent tool call runs the block mapper over `{ ...storedRowParams, ...modelArgs }` with the + * operation only in `context`; the tool then receives `{ ...merged, ...mapped }`. + */ +import { describe, expect, it } from 'vitest' +import { DagsterBlock } from '@/blocks/blocks/dagster' +import { materializeAssetsTool } from '@/tools/dagster/materialize_assets' +import { reportAssetMaterializationTool } from '@/tools/dagster/report_asset_materialization' + +function materializeVariables(args: Record) { + const mapped = + DagsterBlock.tools.config?.params?.(args, { operation: 'materialize_assets' }) ?? {} + const body = materializeAssetsTool.request.body + if (typeof body !== 'function') throw new Error('materialize_assets has no body builder') + return (body({ ...args, ...mapped } as never) as { variables: Record }).variables +} + +const BASE_ARGS = { + host: 'https://dagster.example.com', + repositoryLocationName: 'loc', + repositoryName: 'repo', + assetSelection: 'orders', +} + +describe('Dagster materialize assets on an Agent tool call', () => { + it('sends the job name stored on the tool row', () => { + expect(materializeVariables({ ...BASE_ARGS, assetJobName: 'stored_job' }).jobName).toBe( + 'stored_job' + ) + }) + + it('keeps the job name the model supplied', () => { + expect(materializeVariables({ ...BASE_ARGS, jobName: 'model_job' }).jobName).toBe('model_job') + }) +}) + +function reportedEventType(args: Record) { + const mapped = + DagsterBlock.tools.config?.params?.(args, { operation: 'report_asset_materialization' }) ?? {} + const body = reportAssetMaterializationTool.request.body + if (typeof body !== 'function') + throw new Error('report_asset_materialization has no body builder') + const { variables } = body({ ...args, ...mapped } as never) as { + variables: { eventParams: { eventType: unknown } } + } + return variables.eventParams.eventType +} + +describe('Dagster report asset event on an Agent tool call', () => { + it('keeps the event type the model supplied over the seeded dropdown default', () => { + expect( + reportedEventType({ + host: 'https://dagster.example.com', + assetKey: 'orders', + reportEventType: 'ASSET_MATERIALIZATION', + eventType: 'ASSET_OBSERVATION', + }) + ).toBe('ASSET_OBSERVATION') + }) +}) diff --git a/apps/sim/blocks/blocks/dagster.ts b/apps/sim/blocks/blocks/dagster.ts index deb79ba2013..a445401dcce 100644 --- a/apps/sim/blocks/blocks/dagster.ts +++ b/apps/sim/blocks/blocks/dagster.ts @@ -1,6 +1,7 @@ import { DagsterIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { IntegrationType } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' /** Coerces a subBlock value to a finite number, returning undefined for empty or non-numeric input. */ function toFiniteNumber(value: unknown): number | undefined { @@ -548,46 +549,56 @@ Return ONLY the comma-separated asset keys - no explanations, no extra text.`, ], config: { tool: (params) => `dagster_${params.operation}`, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const result: Record = {} - if (params.operation === 'list_runs') { + if (operation === 'list_runs') { result.limit = toFiniteNumber(params.limit) - result.jobName = params.listRunsJobName || undefined + result.jobName = + params.listRunsJobName || toolCallArg(context, params.jobName) || undefined result.createdAfter = toFiniteNumber(params.createdAfter) result.createdBefore = toFiniteNumber(params.createdBefore) - result.cursor = params.runsCursor || undefined + result.cursor = params.runsCursor || toolCallArg(context, params.cursor) || undefined } - if (params.operation === 'get_run_logs') { - result.limit = toFiniteNumber(params.logsLimit) + if (operation === 'get_run_logs') { + result.limit = + toFiniteNumber(params.logsLimit) ?? toolCallArg(context, toFiniteNumber(params.limit)) } - if (params.operation === 'reexecute_run') { + if (operation === 'reexecute_run') { if (params.runId) result.parentRunId = params.runId } - if (params.operation === 'list_schedules' && !params.scheduleStatus) { + if (operation === 'list_schedules' && !params.scheduleStatus) { result.scheduleStatus = undefined } - if (params.operation === 'list_sensors' && !params.sensorStatus) { + if (operation === 'list_sensors' && !params.sensorStatus) { result.sensorStatus = undefined } - if (params.operation === 'list_assets') { - result.prefix = params.assetPrefix || undefined - result.limit = toFiniteNumber(params.assetsLimit) - result.cursor = params.assetsCursor || undefined + if (operation === 'list_assets') { + result.prefix = params.assetPrefix || toolCallArg(context, params.prefix) || undefined + result.limit = + toFiniteNumber(params.assetsLimit) ?? toolCallArg(context, toFiniteNumber(params.limit)) + result.cursor = params.assetsCursor || toolCallArg(context, params.cursor) || undefined } - if (params.operation === 'materialize_assets') { - result.jobName = params.assetJobName + if (operation === 'materialize_assets') { + result.jobName = + params.assetJobName || toolCallArg(context, params.jobName) || params.assetJobName } - if (params.operation === 'report_asset_materialization') { - result.eventType = params.reportEventType || 'ASSET_MATERIALIZATION' - result.partitionKeys = params.reportPartitionKeys || undefined - result.description = params.reportDescription || undefined + if (operation === 'report_asset_materialization') { + result.eventType = + toolCallArg(context, params.eventType) || + params.reportEventType || + 'ASSET_MATERIALIZATION' + result.partitionKeys = + params.reportPartitionKeys || toolCallArg(context, params.partitionKeys) || undefined + result.description = + params.reportDescription || toolCallArg(context, params.description) || undefined } return result diff --git a/apps/sim/blocks/blocks/daytona.test.ts b/apps/sim/blocks/blocks/daytona.test.ts new file mode 100644 index 00000000000..8529767cac1 --- /dev/null +++ b/apps/sim/blocks/blocks/daytona.test.ts @@ -0,0 +1,38 @@ +/** + * An Agent tool call runs the block mapper over `{ ...storedRowParams, ...modelArgs }` with the + * operation only in `context`; the tool then receives `{ ...merged, ...mapped }`. + */ +import { describe, expect, it } from 'vitest' +import { DaytonaBlock } from '@/blocks/blocks/daytona' +import { daytonaGitCloneTool } from '@/tools/daytona/git_clone' + +function gitCloneBody(args: Record) { + const mapped = DaytonaBlock.tools.config?.params?.(args, { operation: 'git_clone' }) ?? {} + const body = daytonaGitCloneTool.request.body + if (typeof body !== 'function') throw new Error('git_clone has no body builder') + return body({ ...args, ...mapped } as never) +} + +describe('Daytona git clone on an Agent tool call', () => { + it('sends the repository and path stored on the tool row', () => { + expect( + gitCloneBody({ + apiKey: 'key', + sandboxId: 'sb-1', + repoUrl: 'https://github.com/acme/app.git', + clonePath: '/home/daytona/app', + }) + ).toMatchObject({ url: 'https://github.com/acme/app.git', path: '/home/daytona/app' }) + }) + + it('keeps the repository and path the model supplied', () => { + expect( + gitCloneBody({ + apiKey: 'key', + sandboxId: 'sb-1', + url: 'https://github.com/acme/model.git', + path: '/home/daytona/model', + }) + ).toMatchObject({ url: 'https://github.com/acme/model.git', path: '/home/daytona/model' }) + }) +}) diff --git a/apps/sim/blocks/blocks/daytona.ts b/apps/sim/blocks/blocks/daytona.ts index 46ca0fc2eed..244a47ce9f2 100644 --- a/apps/sim/blocks/blocks/daytona.ts +++ b/apps/sim/blocks/blocks/daytona.ts @@ -1,7 +1,12 @@ import { DaytonaIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput, withSavedCredential } from '@/blocks/utils' +import { + mapperOperation, + normalizeFileInput, + toolCallArg, + withSavedCredential, +} from '@/blocks/utils' const SANDBOX_SCOPED_OPERATIONS = [ 'execute_command', @@ -452,12 +457,13 @@ export const DaytonaBlock: BlockConfig = { ], config: { tool: (params) => `daytona_${params.operation}`, - params: (params) => { - const { operation, apiKey, ...rest } = params + params: (params, context) => { + const { apiKey, ...rest } = params + const operation = mapperOperation(params, context) const baseParams: Record = { apiKey } - if (SANDBOX_SCOPED_OPERATIONS.includes(operation)) { + if (operation && SANDBOX_SCOPED_OPERATIONS.includes(operation)) { baseParams.sandboxId = rest.sandboxId } @@ -515,8 +521,8 @@ export const DaytonaBlock: BlockConfig = { if (rest.directoryPath) baseParams.path = rest.directoryPath break case 'git_clone': - baseParams.url = rest.repoUrl - baseParams.path = rest.clonePath + baseParams.url = rest.repoUrl || toolCallArg(context, rest.url) || rest.repoUrl + baseParams.path = rest.clonePath || toolCallArg(context, rest.path) || rest.clonePath if (rest.gitBranch) baseParams.branch = rest.gitBranch if (rest.gitCommitId) baseParams.commitId = rest.gitCommitId if (rest.gitUsername) baseParams.username = rest.gitUsername diff --git a/apps/sim/blocks/blocks/dynamodb.test.ts b/apps/sim/blocks/blocks/dynamodb.test.ts new file mode 100644 index 00000000000..0c12275b26a --- /dev/null +++ b/apps/sim/blocks/blocks/dynamodb.test.ts @@ -0,0 +1,50 @@ +/** + * An Agent tool call runs the block mapper over `{ ...storedRowParams, ...modelArgs }` with the + * operation only in `context`; the internal tool then receives `{ ...merged, ...mapped }`. + */ +import { describe, expect, it } from 'vitest' +import { DynamoDBBlock } from '@/blocks/blocks/dynamodb' + +function toolParams(operation: string, args: Record) { + return { ...args, ...DynamoDBBlock.tools.config?.params?.(args, { operation }) } +} + +const AWS_ARGS = { + region: 'us-east-1', + accessKeyId: 'AKIA', + secretAccessKey: 'secret', + tableName: 'orders', +} + +describe('DynamoDB on an Agent tool call', () => { + it('get sends the primary key stored on the tool row', () => { + expect(toolParams('get', { ...AWS_ARGS, getKey: '{"id":"1"}' }).key).toEqual({ id: '1' }) + }) + + it('scan keeps the index, projection, and consistent read the model supplied', () => { + expect( + toolParams('scan', { + ...AWS_ARGS, + indexName: 'by-status', + projectionExpression: 'id, status', + consistentRead: true, + }) + ).toMatchObject({ + indexName: 'by-status', + projectionExpression: 'id, status', + consistentRead: true, + }) + }) + + it('update keeps the return values the model supplied over the seeded dropdown default', () => { + expect( + toolParams('update', { + ...AWS_ARGS, + updateKey: '{"id":"1"}', + updateExpression: 'SET #s = :s', + updateReturnValues: 'ALL_NEW', + returnValues: 'UPDATED_OLD', + }).returnValues + ).toBe('UPDATED_OLD') + }) +}) diff --git a/apps/sim/blocks/blocks/dynamodb.ts b/apps/sim/blocks/blocks/dynamodb.ts index 1a67c12ad29..a819a1b7486 100644 --- a/apps/sim/blocks/blocks/dynamodb.ts +++ b/apps/sim/blocks/blocks/dynamodb.ts @@ -2,7 +2,7 @@ import { toError } from '@sim/utils/errors' import { DynamoDBIcon } 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 DynamoDBBlock: BlockConfig = { type: 'dynamodb', @@ -731,7 +731,7 @@ Return ONLY the expression - no explanations.`, throw new Error(`Invalid DynamoDB operation: ${params.operation}`) } }, - params: (params) => { + params: (params, context) => { const parseJson = (value: unknown, fieldName: string) => { if (!value) return undefined if (typeof value === 'object') return value @@ -745,7 +745,7 @@ Return ONLY the expression - no explanations.`, return undefined } - const op = params.operation as string + const op = mapperOperation(params, context) const result: Record = { region: params.region, accessKeyId: params.accessKeyId, @@ -772,7 +772,10 @@ Return ONLY the expression - no explanations.`, if (params.consistentRead === 'true' || params.consistentRead === true) { result.consistentRead = true } - result.projectionExpression = params.getProjectionExpression || undefined + result.projectionExpression = + params.getProjectionExpression || + toolCallArg(context, params.projectionExpression) || + undefined const getNames = parseJson(params.getExpressionAttributeNames, 'expressionAttributeNames') if (getNames !== undefined) result.expressionAttributeNames = getNames } @@ -817,11 +820,14 @@ Return ONLY the expression - no explanations.`, params.scanIndexForward === 'false' || params.scanIndexForward === false ? false : undefined - result.projectionExpression = params.queryProjectionExpression || undefined + result.projectionExpression = + params.queryProjectionExpression || + toolCallArg(context, params.projectionExpression) || + undefined result.consistentRead = params.queryConsistentRead === 'true' || params.queryConsistentRead === true ? true - : undefined + : toolCallArg(context, params.consistentRead) } if (op === 'scan') { @@ -846,11 +852,12 @@ Return ONLY the expression - no explanations.`, if (lim) result.limit = Number.parseInt(String(lim), 10) const esk = parseJson(params.scanExclusiveStartKey, 'exclusiveStartKey') if (esk !== undefined) result.exclusiveStartKey = esk - result.indexName = params.scanIndexName || undefined + result.indexName = + params.scanIndexName || toolCallArg(context, params.indexName) || undefined result.consistentRead = params.scanConsistentRead === 'true' || params.scanConsistentRead === true ? true - : undefined + : toolCallArg(context, params.consistentRead) if ( params.scanSegment !== undefined && params.scanSegment !== null && @@ -882,7 +889,9 @@ Return ONLY the expression - no explanations.`, if (values !== undefined) result.expressionAttributeValues = values if (params.updateConditionExpression) result.conditionExpression = params.updateConditionExpression - if (params.updateReturnValues) result.returnValues = params.updateReturnValues + const returnValues = + toolCallArg(context, params.returnValues) || params.updateReturnValues + if (returnValues) result.returnValues = returnValues } if (op === 'delete') { diff --git a/apps/sim/blocks/blocks/dynatrace.test.ts b/apps/sim/blocks/blocks/dynatrace.test.ts new file mode 100644 index 00000000000..d641f71917b --- /dev/null +++ b/apps/sim/blocks/blocks/dynatrace.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from 'vitest' +import { DynatraceBlock } from '@/blocks/blocks/dynatrace' + +/** + * An agent tool call: the stored row's values and the model's args (keyed by the tool's param + * names) arrive merged, the operation only on `context`, and the executor forwards + * `{ ...params, ...mapped }`. + */ +const agentCall = ( + operation: string, + params: Record +): Record => ({ + ...params, + ...(DynatraceBlock.tools.config?.params?.(params, { operation }) ?? {}), +}) + +describe('DynatraceBlock agent tool calls', () => { + it('forwards the tag key and value set on the tool row to delete_tag', () => { + const mapped = agentCall('dynatrace_delete_tag', { + entitySelector: 'type(HOST)', + tagKey: 'env', + tagValue: 'prod', + }) + expect(mapped).toMatchObject({ key: 'env', value: 'prod' }) + }) + + it('keeps model args named after the tool params when the row fields are blank', () => { + const mapped = agentCall('dynatrace_delete_tag', { + entitySelector: 'type(HOST)', + tagKey: '', + tagValue: '', + key: 'team', + value: 'payments', + }) + expect(mapped).toMatchObject({ key: 'team', value: 'payments' }) + + const monitors = agentCall('dynatrace_list_synthetic_monitors', { + monitorEnabled: '', + enabled: false, + managementZone: 42, + }) + expect(monitors).toMatchObject({ enabled: false, managementZone: 42 }) + }) +}) diff --git a/apps/sim/blocks/blocks/dynatrace.ts b/apps/sim/blocks/blocks/dynatrace.ts index 7d22d6a2153..9cf4edf147f 100644 --- a/apps/sim/blocks/blocks/dynatrace.ts +++ b/apps/sim/blocks/blocks/dynatrace.ts @@ -1,7 +1,7 @@ import { DynatraceIcon } 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 accept the shared `from` timeframe parameter. */ const FROM_OPERATIONS = [ @@ -1560,7 +1560,8 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, ], config: { tool: (params) => params.operation, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const baseParams: Record = { environmentUrl: params.environmentUrl, apiToken: params.apiToken, @@ -1581,6 +1582,22 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, return undefined } + /** + * A dedicated block field, else on a tool call the model's arg under the + * tool's own param name. Blank strings fall through to `undefined`. + */ + const pick = (dedicated: unknown, toolParam: string) => + dedicated || toolCallArg(context, params[toolParam]) || undefined + + /** + * A required tool param fed by a differently named block field: the field's + * value, else on a tool call the model's arg when the field is blank. + */ + const orModelArg = (dedicated: unknown, toolParam: string) => + dedicated === undefined || dedicated === null || dedicated === '' + ? (toolCallArg(context, params[toolParam]) ?? dedicated) + : dedicated + const pagination = { pageSize: toNumber(params.pageSize), nextPageKey: params.nextPageKey || undefined, @@ -1588,21 +1605,21 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, // Create and update SLO take the identical definition. const sloWriteParams = { - name: params.sloName, - target: toNumber(params.sloTarget), - warning: toNumber(params.sloWarning), - timeframe: params.sloTimeframe, - evaluationType: params.sloEvaluationType || 'AGGREGATE', - description: params.sloDescription || undefined, - enabled: params.sloEnabled, - filter: params.sloFilter || undefined, - metricExpression: params.sloMetricExpression || undefined, - metricName: params.sloMetricName || undefined, + name: orModelArg(params.sloName, 'name'), + target: toNumber(orModelArg(params.sloTarget, 'target')), + warning: toNumber(orModelArg(params.sloWarning, 'warning')), + timeframe: orModelArg(params.sloTimeframe, 'timeframe'), + evaluationType: pick(params.sloEvaluationType, 'evaluationType') || 'AGGREGATE', + description: pick(params.sloDescription, 'description'), + enabled: orModelArg(params.sloEnabled, 'enabled'), + filter: pick(params.sloFilter, 'filter'), + metricExpression: pick(params.sloMetricExpression, 'metricExpression'), + metricName: pick(params.sloMetricName, 'metricName'), burnRateVisualizationEnabled: params.burnRateVisualizationEnabled, fastBurnThreshold: toNumber(params.fastBurnThreshold), } - switch (params.operation) { + switch (operation) { case 'dynatrace_list_problems': return { ...baseParams, @@ -1611,15 +1628,15 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, to: params.to || undefined, problemSelector: params.problemSelector || undefined, entitySelector: params.entitySelector || undefined, - sort: params.problemSort || undefined, - fields: params.problemFields || undefined, + sort: pick(params.problemSort, 'sort'), + fields: pick(params.problemFields, 'fields'), } case 'dynatrace_get_problem': return { ...baseParams, problemId: params.problemId, - fields: params.problemFields || undefined, + fields: pick(params.problemFields, 'fields'), } case 'dynatrace_close_problem': @@ -1633,7 +1650,7 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, ...baseParams, problemId: params.problemId, message: params.message, - context: params.commentContext || undefined, + context: pick(params.commentContext, 'context'), } case 'dynatrace_query_metrics': @@ -1653,7 +1670,7 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, ...pagination, metricSelector: params.metricSelector || undefined, text: params.text || undefined, - fields: params.metricFields || undefined, + fields: pick(params.metricFields, 'fields'), writtenSince: params.writtenSince || undefined, writtenSinceMode: params.writtenSinceMode || undefined, metadataSelector: params.metadataSelector || undefined, @@ -1663,7 +1680,7 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, return { ...baseParams, metricKey: params.metricKey } case 'dynatrace_ingest_metrics': - return { ...baseParams, payload: params.metricPayload } + return { ...baseParams, payload: orModelArg(params.metricPayload, 'payload') } case 'dynatrace_list_entities': return { @@ -1672,8 +1689,8 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, entitySelector: params.entitySelector, from: params.from || undefined, to: params.to || undefined, - fields: params.entityFields || undefined, - sort: params.entitySort || undefined, + fields: pick(params.entityFields, 'fields'), + sort: pick(params.entitySort, 'sort'), } case 'dynatrace_get_entity': @@ -1682,7 +1699,7 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, entityId: params.entityId, from: params.from || undefined, to: params.to || undefined, - fields: params.entityFields || undefined, + fields: pick(params.entityFields, 'fields'), } case 'dynatrace_list_entity_types': @@ -1710,16 +1727,16 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, startTime: toNumber(params.startTime), endTime: toNumber(params.endTime), eventTimeout: toNumber(params.eventTimeout), - properties: params.eventProperties || undefined, + properties: pick(params.eventProperties, 'properties'), } case 'dynatrace_search_logs': return { ...baseParams, - query: params.logQuery || undefined, + query: pick(params.logQuery, 'query'), from: params.from || undefined, to: params.to || undefined, - sort: params.logSort || undefined, + sort: pick(params.logSort, 'sort'), limit: toNumber(params.limit), nextSliceKey: params.nextSliceKey || undefined, } @@ -1735,7 +1752,7 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, from: params.from || undefined, to: params.to || undefined, timeFrame: params.timeFrame || undefined, - sort: params.sloSort || undefined, + sort: pick(params.sloSort, 'sort'), enabledSlos: params.enabledSlos || undefined, evaluate: params.evaluate, showGlobalSlos: params.showGlobalSlos, @@ -1757,15 +1774,15 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, securityProblemSelector: params.securityProblemSelector || undefined, from: params.from || undefined, to: params.to || undefined, - fields: params.securityFields || undefined, - sort: params.securitySort || undefined, + fields: pick(params.securityFields, 'fields'), + sort: pick(params.securitySort, 'sort'), } case 'dynatrace_get_security_problem': return { ...baseParams, securityProblemId: params.securityProblemId, - fields: params.securityFields || undefined, + fields: pick(params.securityFields, 'fields'), managementZoneFilter: params.managementZoneFilter || undefined, from: params.from || undefined, } @@ -1774,18 +1791,18 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, return { ...baseParams, ...pagination, - filter: params.auditFilter || undefined, + filter: pick(params.auditFilter, 'filter'), from: params.from || undefined, to: params.to || undefined, - sort: params.auditSort || undefined, + sort: pick(params.auditSort, 'sort'), } case 'dynatrace_mute_security_problem': return { ...baseParams, securityProblemId: params.securityProblemId, - reason: params.muteReason, - comment: params.muteComment || undefined, + reason: orModelArg(params.muteReason, 'reason'), + comment: pick(params.muteComment, 'comment'), } case 'dynatrace_unmute_security_problem': @@ -1793,15 +1810,15 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, ...baseParams, securityProblemId: params.securityProblemId, reason: UNMUTE_REASON, - comment: params.muteComment || undefined, + comment: pick(params.muteComment, 'comment'), } case 'dynatrace_mute_security_problems': return { ...baseParams, securityProblemIds: params.securityProblemIds, - reason: params.muteReason, - comment: params.muteComment || undefined, + reason: orModelArg(params.muteReason, 'reason'), + comment: pick(params.muteComment, 'comment'), } case 'dynatrace_unmute_security_problems': @@ -1809,7 +1826,7 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, ...baseParams, securityProblemIds: params.securityProblemIds, reason: UNMUTE_REASON, - comment: params.muteComment || undefined, + comment: pick(params.muteComment, 'comment'), } case 'dynatrace_list_remediation_items': @@ -1826,15 +1843,15 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, attackSelector: params.attackSelector || undefined, from: params.from || undefined, to: params.to || undefined, - fields: params.attackFields || undefined, - sort: params.attackSort || undefined, + fields: pick(params.attackFields, 'fields'), + sort: pick(params.attackSort, 'sort'), } case 'dynatrace_get_attack': return { ...baseParams, attackId: params.attackId, - fields: params.attackFields || undefined, + fields: pick(params.attackFields, 'fields'), } case 'dynatrace_list_tags': @@ -1858,15 +1875,15 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, return { ...baseParams, entitySelector: params.entitySelector, - key: params.tagKey, - value: params.tagValue || undefined, + key: orModelArg(params.tagKey, 'key'), + value: pick(params.tagValue, 'value'), deleteAllWithKey: params.deleteAllWithKey, from: params.from || undefined, to: params.to || undefined, } case 'dynatrace_list_settings_schemas': - return { ...baseParams, fields: params.schemaFields || undefined } + return { ...baseParams, fields: pick(params.schemaFields, 'fields') } case 'dynatrace_list_settings_objects': return { @@ -1875,9 +1892,9 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, schemaIds: params.schemaIds || undefined, scopes: params.scopes || undefined, externalIds: params.externalIds || undefined, - fields: params.settingsFields || undefined, - filter: params.settingsFilter || undefined, - sort: params.settingsSort || undefined, + fields: pick(params.settingsFields, 'fields'), + filter: pick(params.settingsFilter, 'filter'), + sort: pick(params.settingsSort, 'sort'), } case 'dynatrace_get_settings_object': @@ -1888,9 +1905,9 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, ...baseParams, schemaId: params.schemaId, scope: params.scope, - value: params.settingsValue, + value: orModelArg(params.settingsValue, 'value'), schemaVersion: params.schemaVersion || undefined, - externalId: params.settingsExternalId || undefined, + externalId: pick(params.settingsExternalId, 'externalId'), validateOnly: params.validateOnly, } @@ -1898,7 +1915,7 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, return { ...baseParams, objectId: params.objectId, - value: params.settingsValue, + value: orModelArg(params.settingsValue, 'value'), schemaVersion: params.schemaVersion || undefined, updateToken: params.updateToken || undefined, validateOnly: params.validateOnly, @@ -1914,13 +1931,17 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, case 'dynatrace_list_synthetic_monitors': return { ...baseParams, - type: params.monitorType || undefined, + type: pick(params.monitorType, 'type'), // "Any" must send no filter — enabled=false would return only the // disabled monitors, the opposite of what was asked for. - enabled: toOptionalBoolean(params.monitorEnabled), - location: params.monitorLocation || undefined, - tag: params.monitorTag || undefined, - managementZone: toNumber(params.monitorManagementZone), + enabled: + toOptionalBoolean(params.monitorEnabled) ?? + toOptionalBoolean(toolCallArg(context, params.enabled)), + location: pick(params.monitorLocation, 'location'), + tag: pick(params.monitorTag, 'tag'), + managementZone: + toNumber(params.monitorManagementZone) ?? + toNumber(toolCallArg(context, params.managementZone)), } case 'dynatrace_execute_synthetic_monitors': @@ -1931,7 +1952,7 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, failOnPerformanceIssue: params.failOnPerformanceIssue, stopOnProblem: params.stopOnProblem, takeScreenshotsOnSuccess: params.takeScreenshotsOnSuccess, - metadata: params.batchMetadata || undefined, + metadata: pick(params.batchMetadata, 'metadata'), } case 'dynatrace_get_synthetic_batch': @@ -1951,7 +1972,7 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, problemId: params.problemId, commentId: params.commentId, message: params.message, - context: params.commentContext || undefined, + context: pick(params.commentContext, 'context'), } case 'dynatrace_create_slo': diff --git a/apps/sim/blocks/blocks/fivetran.test.ts b/apps/sim/blocks/blocks/fivetran.test.ts new file mode 100644 index 00000000000..8ff9bd4e83f --- /dev/null +++ b/apps/sim/blocks/blocks/fivetran.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from 'vitest' +import { FivetranBlock } from '@/blocks/blocks/fivetran' +import type { BlockToolParamsContext } from '@/blocks/types' + +/** Mirrors the tool-call path: the mapper result is spread over the merged params. */ +function toolCallParams(args: Record, context: BlockToolParamsContext) { + const mapper = FivetranBlock.tools.config?.params + if (!mapper) throw new Error('Fivetran block has no params mapper') + return { ...args, ...mapper(args, context) } +} + +describe('Fivetran agent tool calls', () => { + it('pauses the connection when the operation arrives only in the context', () => { + const sent = toolCallParams( + { connectionId: 'c1', syncFrequency: 60 }, + { operation: 'pause_connection' } + ) + expect(sent.paused).toBe(true) + expect(sent.syncFrequency).toBeUndefined() + }) + + it.each([ + ['create_group', { name: 'Analytics' }], + ['create_destination', { groupId: 'g1', service: 'snowflake', config: { host: 'h' } }], + ['update_schema_config', { connectionId: 'c1', schemas: { public: { enabled: true } } }], + [ + 'update_connection_schema', + { connectionId: 'c1', schemaName: 'public', enabled: false, tables: { t: {} } }, + ], + [ + 'update_connection_table', + { connectionId: 'c1', schemaName: 'public', tableName: 't', enabled: true }, + ], + ])('keeps the model arguments for %s', (operation, args) => { + expect(toolCallParams(args, { operation })).toMatchObject(args) + }) +}) diff --git a/apps/sim/blocks/blocks/fivetran.ts b/apps/sim/blocks/blocks/fivetran.ts index 49eb01fe8a5..ec6e82a1ff5 100644 --- a/apps/sim/blocks/blocks/fivetran.ts +++ b/apps/sim/blocks/blocks/fivetran.ts @@ -1,5 +1,6 @@ import { FivetranIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' import { getTrigger } from '@/triggers' const CONNECTION_ID_OPS = [ @@ -1058,16 +1059,17 @@ export const FivetranBlock: BlockConfig = { } return `fivetran_${params.operation}` }, - params: (params) => { + params: (params, context) => { const result: Record = {} + const operation = mapperOperation(params, context) ?? '' const isConnectionSettings = (CONNECTION_SETTINGS_OPS as readonly string[]).includes( - params.operation + operation ) - if (params.operation === 'pause_connection' || params.operation === 'resume_connection') { + if (operation === 'pause_connection' || operation === 'resume_connection') { return { ...PAUSE_ONLY_UPDATE, - paused: params.operation === 'pause_connection', + paused: operation === 'pause_connection', } } @@ -1077,43 +1079,51 @@ export const FivetranBlock: BlockConfig = { result.pauseAfterTrial = toOptionalBoolean(params.pauseAfterTrial) result.dataDelayThreshold = toOptionalNumber(params.dataDelayThreshold) } - if (isConnectionSettings || params.operation === 'create_destination') { + if (isConnectionSettings || operation === 'create_destination') { result.runSetupTests = toOptionalBoolean(params.runSetupTests) } - if (params.operation === 'create_destination') { - result.service = params.destinationService - result.config = params.destinationConfig + if (operation === 'create_destination') { + result.service = params.destinationService ?? toolCallArg(context, params.service) + result.config = params.destinationConfig ?? toolCallArg(context, params.config) result.daylightSavingTimeEnabled = toOptionalBoolean(params.daylightSavingTimeEnabled) } - if (params.operation === 'create_group') result.name = params.groupName - if (params.operation === 'update_schema_config') result.schemas = params.schemasConfig - if (params.operation === 'update_connection_schema') { - result.enabled = toOptionalBoolean(params.schemaEnabled) - result.tables = params.schemaTables + if (operation === 'create_group') { + result.name = params.groupName ?? toolCallArg(context, params.name) + } + if (operation === 'update_schema_config') { + result.schemas = params.schemasConfig ?? toolCallArg(context, params.schemas) + } + if (operation === 'update_connection_schema') { + result.enabled = + toOptionalBoolean(params.schemaEnabled) ?? + toOptionalBoolean(toolCallArg(context, params.enabled)) + result.tables = params.schemaTables ?? toolCallArg(context, params.tables) } - if (params.operation === 'update_connection') { + if (operation === 'update_connection') { result.isHistoricalSync = toOptionalBoolean(params.isHistoricalSync) } - if ((SETUP_TEST_OPS as readonly string[]).includes(params.operation)) { + if ((SETUP_TEST_OPS as readonly string[]).includes(operation)) { result.trustCertificates = toOptionalBoolean(params.trustCertificates) result.trustFingerprints = toOptionalBoolean(params.trustFingerprints) } - if (params.operation === 'sync_connection') result.force = toOptionalBoolean(params.force) - if (params.operation === 'update_connection_table') { - result.enabled = toOptionalBoolean(params.tableEnabled) + if (operation === 'sync_connection') result.force = toOptionalBoolean(params.force) + if (operation === 'update_connection_table') { + result.enabled = + toOptionalBoolean(params.tableEnabled) ?? + toOptionalBoolean(toolCallArg(context, params.enabled)) } - if (params.operation === 'create_connect_card') { + if (operation === 'create_connect_card') { result.hideSetupGuide = toOptionalBoolean(params.hideSetupGuide) result.allFields = toOptionalBoolean(params.allFields) } - if (params.operation === 'run_transformation') { + if (operation === 'run_transformation') { result.fullRefresh = toOptionalBoolean(params.fullRefresh) } - if (params.operation === 'list_users') { + if (operation === 'list_users') { result.active = toOptionalBoolean(params.active) result.hasApiKey = toOptionalBoolean(params.hasApiKey) } - if ((PAGINATED_OPS as readonly string[]).includes(params.operation)) { + if ((PAGINATED_OPS as readonly string[]).includes(operation)) { result.limit = toOptionalNumber(params.limit) } return result diff --git a/apps/sim/blocks/blocks/google_bigquery.ts b/apps/sim/blocks/blocks/google_bigquery.ts index 5c9844d06b2..bc8354f531a 100644 --- a/apps/sim/blocks/blocks/google_bigquery.ts +++ b/apps/sim/blocks/blocks/google_bigquery.ts @@ -2,6 +2,7 @@ import { GoogleBigQueryIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation } from '@/blocks/utils' const EXISTING_DATASET_OPS = [ 'list_tables', @@ -420,7 +421,7 @@ Return ONLY the JSON array - no explanations, no wrapping, no extra text.`, throw new Error(`Invalid Google BigQuery operation: ${params.operation}`) } }, - params: (params) => { + params: (params, context) => { const { oauthCredential, rows, @@ -435,7 +436,7 @@ Return ONLY the JSON array - no explanations, no wrapping, no extra text.`, tableId, ...rest } = params - const operation = String(params.operation) + const operation = mapperOperation(params, context) return { ...rest, oauthCredential, diff --git a/apps/sim/blocks/blocks/grafana.test.ts b/apps/sim/blocks/blocks/grafana.test.ts new file mode 100644 index 00000000000..eac82d598dd --- /dev/null +++ b/apps/sim/blocks/blocks/grafana.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from 'vitest' +import { GrafanaBlock } from '@/blocks/blocks/grafana' +import type { BlockToolParamsContext } from '@/blocks/types' + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = GrafanaBlock.tools.config?.params + if (!mapper) throw new Error('Grafana block has no params mapper') + return mapper(params, context) +} + +describe('Grafana tool calls', () => { + it('keeps the model folder UID and parent UID when moving a folder', () => { + const mapped = mapParams( + { folderUid: 'child', parentUid: 'parent' }, + { operation: 'grafana_move_folder' } + ) + + expect(mapped).toMatchObject({ folderUid: 'child', parentUid: 'parent' }) + }) + + it('keeps the model folder UID and rule group when reading an alert rule group', () => { + const mapped = mapParams( + { folderUid: 'folder-1', ruleGroup: 'cpu' }, + { operation: 'grafana_get_alert_rule_group' } + ) + + expect(mapped).toMatchObject({ folderUid: 'folder-1', ruleGroup: 'cpu' }) + }) +}) diff --git a/apps/sim/blocks/blocks/grafana.ts b/apps/sim/blocks/blocks/grafana.ts index e5811970090..cfb95065be8 100644 --- a/apps/sim/blocks/blocks/grafana.ts +++ b/apps/sim/blocks/blocks/grafana.ts @@ -1,7 +1,7 @@ import { GrafanaIcon } 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 GrafanaBlock: BlockConfig = { type: 'grafana', @@ -1110,9 +1110,9 @@ Return ONLY the JSON object - no explanations, no markdown, no extra text.`, ], config: { tool: (params) => params.operation, - params: (params) => { + params: (params, context) => { const result: Record = {} - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'grafana_list_dashboards': if (params.page) result.page = Number(params.page) if (params.limit) result.limit = Number(params.limit) @@ -1144,17 +1144,17 @@ Return ONLY the JSON object - no explanations, no markdown, no extra text.`, if (params.contactPointSettings) result.settings = params.contactPointSettings break case 'grafana_query_data_source': - result.queries = params.dataSourceQueries + result.queries = params.dataSourceQueries ?? toolCallArg(context, params.queries) if (params.queryFrom) result.from = params.queryFrom if (params.queryTo) result.to = params.queryTo break case 'grafana_move_folder': - result.folderUid = params.manageFolderUid - result.parentUid = params.newParentUid ?? '' + result.folderUid = params.manageFolderUid ?? toolCallArg(context, params.folderUid) + result.parentUid = params.newParentUid ?? toolCallArg(context, params.parentUid) ?? '' break case 'grafana_get_alert_rule_group': - result.folderUid = params.manageFolderUid - result.ruleGroup = params.ruleGroupName + result.folderUid = params.manageFolderUid ?? toolCallArg(context, params.folderUid) + result.ruleGroup = params.ruleGroupName ?? toolCallArg(context, params.ruleGroup) break case 'grafana_create_annotation': if (params.annotationTags) result.tags = params.annotationTags diff --git a/apps/sim/blocks/blocks/iam.test.ts b/apps/sim/blocks/blocks/iam.test.ts index 6fbaaa58c5f..1f2a6a6b0f7 100644 --- a/apps/sim/blocks/blocks/iam.test.ts +++ b/apps/sim/blocks/blocks/iam.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest' import { IAMBlock } from '@/blocks/blocks/iam' +import type { BlockToolParamsContext } from '@/blocks/types' const SHAPE_ERROR = 'Condition Context Keys must be a JSON array of { contextKeyName, contextKeyValues, contextKeyType }' @@ -48,3 +49,32 @@ describe('IAMBlock contextEntries parsing', () => { expect(result.contextEntries).toBeUndefined() }) }) + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = IAMBlock.tools.config?.params + if (!mapper) throw new Error('IAM block has no params mapper') + return mapper(params, context) +} + +describe('IAMBlock tool calls', () => { + it('parses stored context entries when the operation arrives only in the context', () => { + const result = mapParams( + { + region: 'us-east-1', + policySourceArn: 'arn:aws:iam::000000000000:role/example', + actionNames: 's3:GetObject', + contextEntries: JSON.stringify([CONTEXT_ENTRY]), + }, + { operation: 'simulate_principal_policy' } + ) + expect(result.contextEntries).toEqual([CONTEXT_ENTRY]) + }) + + it('keeps the model access key status on update_access_key', () => { + const result = mapParams( + { region: 'us-east-1', accessKeyIdToUpdate: 'AKIAEXAMPLE', status: 'Active' }, + { operation: 'update_access_key' } + ) + expect(result.status).toBe('Active') + }) +}) diff --git a/apps/sim/blocks/blocks/iam.ts b/apps/sim/blocks/blocks/iam.ts index ce502858d6a..ea5e898b984 100644 --- a/apps/sim/blocks/blocks/iam.ts +++ b/apps/sim/blocks/blocks/iam.ts @@ -2,7 +2,7 @@ import { isRecordLike } from '@sim/utils/object' import { IAMIcon } 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' /** * Converts the Tags table, a `[{ key, value }]` list (or its JSON string), a plain @@ -632,9 +632,8 @@ export const IAMBlock: BlockConfig = { throw new Error(`Invalid IAM operation: ${params.operation}`) } }, - params: (params) => { + params: (params, context) => { const { - operation, maxItems, maxSessionDuration, onlyAttached, @@ -651,7 +650,7 @@ export const IAMBlock: BlockConfig = { const result: Record = { ...connectionConfig } - switch (operation) { + switch (mapperOperation(params, context)) { case 'list_users': case 'list_roles': case 'list_groups': @@ -737,7 +736,7 @@ export const IAMBlock: BlockConfig = { break case 'update_access_key': result.accessKeyIdToUpdate = rest.accessKeyIdToUpdate - result.status = rest.accessKeyStatus + result.status = rest.accessKeyStatus ?? toolCallArg(context, rest.status) if (rest.userName) result.userName = rest.userName break case 'add_user_to_group': diff --git a/apps/sim/blocks/blocks/identity_center.test.ts b/apps/sim/blocks/blocks/identity_center.test.ts new file mode 100644 index 00000000000..d38760d42be --- /dev/null +++ b/apps/sim/blocks/blocks/identity_center.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest' +import { IdentityCenterBlock } from '@/blocks/blocks/identity_center' +import type { BlockToolParamsContext } from '@/blocks/types' + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = IdentityCenterBlock.tools.config?.params + if (!mapper) throw new Error('Identity Center block has no params mapper') + return mapper(params, context) +} + +describe('Identity Center list_account_assignments tool calls', () => { + it('keeps the model accountId when no account filter is stored', () => { + const mapped = mapParams( + { instanceArn: 'arn:i', principalId: 'u1', principalType: 'USER', accountId: '222' }, + { operation: 'list_account_assignments' } + ) + + expect(mapped.accountId).toBe('222') + }) +}) diff --git a/apps/sim/blocks/blocks/identity_center.ts b/apps/sim/blocks/blocks/identity_center.ts index a9b885903ac..a46a9c2ff58 100644 --- a/apps/sim/blocks/blocks/identity_center.ts +++ b/apps/sim/blocks/blocks/identity_center.ts @@ -1,7 +1,7 @@ import { IdentityCenterIcon } 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 IdentityCenterBlock: BlockConfig = { type: 'identity_center', @@ -418,8 +418,8 @@ export const IdentityCenterBlock: BlockConfig = { throw new Error(`Invalid Identity Center operation: ${params.operation}`) } }, - params: (params) => { - const { operation, maxResults, ...rest } = params + params: (params, context) => { + const { maxResults, ...rest } = params const connectionConfig = { region: rest.region, @@ -429,7 +429,7 @@ export const IdentityCenterBlock: BlockConfig = { const result: Record = { ...connectionConfig } - switch (operation) { + switch (mapperOperation(params, context)) { case 'list_instances': if (maxResults) { const parsed = Number.parseInt(String(maxResults), 10) @@ -505,7 +505,8 @@ export const IdentityCenterBlock: BlockConfig = { result.instanceArn = rest.instanceArn result.principalId = rest.principalId result.principalType = rest.principalType - result.accountId = rest.filterAccountId || undefined + result.accountId = + rest.filterAccountId || toolCallArg(context, rest.accountId) || undefined if (maxResults) { const parsed = Number.parseInt(String(maxResults), 10) if (!Number.isNaN(parsed)) result.maxResults = parsed diff --git a/apps/sim/blocks/blocks/infisical.ts b/apps/sim/blocks/blocks/infisical.ts index b233d6f3744..71a40032a63 100644 --- a/apps/sim/blocks/blocks/infisical.ts +++ b/apps/sim/blocks/blocks/infisical.ts @@ -1,7 +1,7 @@ import { InfisicalIcon } 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' export const InfisicalBlock: BlockConfig = { type: 'infisical', @@ -192,7 +192,7 @@ export const InfisicalBlock: BlockConfig = { ], config: { tool: (params) => `infisical_${params.operation}`, - params: (params) => { + params: (params, context) => { const result: Record = { apiKey: params.apiKey, projectId: params.projectId, @@ -202,7 +202,7 @@ export const InfisicalBlock: BlockConfig = { if (params.baseUrl) result.baseUrl = params.baseUrl if (params.secretPath) result.secretPath = params.secretPath - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'list_secrets': if (params.recursive != null) result.recursive = params.recursive if (params.includeImports != null) result.includeImports = params.includeImports diff --git a/apps/sim/blocks/blocks/jupyter.ts b/apps/sim/blocks/blocks/jupyter.ts index 12f41d9f88e..891d4c3dffc 100644 --- a/apps/sim/blocks/blocks/jupyter.ts +++ b/apps/sim/blocks/blocks/jupyter.ts @@ -3,6 +3,7 @@ import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' import { createVersionedToolSelector, + mapperOperation, normalizeFileInput, withSavedCredential, } from '@/blocks/utils' @@ -292,61 +293,59 @@ export const JupyterBlock = { ], config: { tool: (params) => params.operation as string, - params: (params) => { + params: (params, context) => { const normalizedFile = normalizeFileInput(params.file, { single: true }) if (normalizedFile) { params.file = normalizedFile } - const { operation, ...rest } = params - const baseParams: Record = { - serverUrl: rest.serverUrl, - token: rest.token, + serverUrl: params.serverUrl, + token: params.token, } - switch (operation) { + switch (mapperOperation(params, context)) { case 'jupyter_list_contents': - if (rest.path) baseParams.path = rest.path + if (params.path) baseParams.path = params.path break case 'jupyter_get_content': case 'jupyter_delete_content': - baseParams.path = rest.path + baseParams.path = params.path break case 'jupyter_create_file': - baseParams.path = rest.path - baseParams.type = rest.type - if (rest.content) baseParams.content = rest.content + baseParams.path = params.path + baseParams.type = params.type + if (params.content) baseParams.content = params.content break case 'jupyter_upload_file': - if (rest.directory) baseParams.directory = rest.directory - baseParams.file = rest.file - if (rest.uploadFileName) baseParams.fileName = rest.uploadFileName + if (params.directory) baseParams.directory = params.directory + baseParams.file = params.file + if (params.uploadFileName) baseParams.fileName = params.uploadFileName break case 'jupyter_rename_content': - baseParams.path = rest.path - baseParams.newPath = rest.newPath + baseParams.path = params.path + baseParams.newPath = params.newPath break case 'jupyter_copy_content': - baseParams.path = rest.path - baseParams.copyFromPath = rest.copyFromPath + baseParams.path = params.path + baseParams.copyFromPath = params.copyFromPath break case 'jupyter_start_kernel': - if (rest.kernelName) baseParams.kernelName = rest.kernelName + if (params.kernelName) baseParams.kernelName = params.kernelName break case 'jupyter_stop_kernel': case 'jupyter_restart_kernel': case 'jupyter_interrupt_kernel': - baseParams.kernelId = rest.kernelId + baseParams.kernelId = params.kernelId break case 'jupyter_create_session': - baseParams.path = rest.path - if (rest.kernelName) baseParams.kernelName = rest.kernelName - if (rest.sessionName) baseParams.name = rest.sessionName - if (rest.sessionType) baseParams.type = rest.sessionType + baseParams.path = params.path + if (params.kernelName) baseParams.kernelName = params.kernelName + if (params.sessionName) baseParams.name = params.sessionName + if (params.sessionType) baseParams.type = params.sessionType break case 'jupyter_delete_session': - baseParams.sessionId = rest.sessionId + baseParams.sessionId = params.sessionId break } diff --git a/apps/sim/blocks/blocks/lambda.test.ts b/apps/sim/blocks/blocks/lambda.test.ts index 2b6558ebb63..7ecf979d872 100644 --- a/apps/sim/blocks/blocks/lambda.test.ts +++ b/apps/sim/blocks/blocks/lambda.test.ts @@ -168,4 +168,22 @@ describe('LambdaBlock params mapping', () => { }) ).toThrow('filterPatterns must be a JSON array') }) + + it('maps an agent tool call, where the operation arrives only in the context', () => { + const modelArgs = { + ...CONNECTION, + functionName: 'alpha', + eventSourceArn: 'arn:aws:sqs:us-east-1:1:queue', + batchSize: '10', + filterPatterns: [{ body: { status: ['open'] } }], + } + + const mapped = toolConfig?.params?.(modelArgs, { + operation: 'create_event_source_mapping', + }) as Record + + expect(mapped.batchSize).toBe(10) + expect(mapped.filterPatterns).toEqual(['{"body":{"status":["open"]}}']) + expect(mapped.functionName).toBe('alpha') + }) }) diff --git a/apps/sim/blocks/blocks/lambda.ts b/apps/sim/blocks/blocks/lambda.ts index 1bebcaf688b..b5cadb0a155 100644 --- a/apps/sim/blocks/blocks/lambda.ts +++ b/apps/sim/blocks/blocks/lambda.ts @@ -2,7 +2,7 @@ import { getErrorMessage } from '@sim/utils/errors' import { LambdaIcon } 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' type ParamKind = 'string' | 'number' | 'boolean' | 'json' | 'array' | 'jsonArray' @@ -1957,11 +1957,11 @@ export const LambdaBlock: BlockConfig = { } return `lambda_${operation}` }, - params: (params) => { - const operation = String(params.operation ?? '') + params: (params, context) => { + const operation = mapperOperation(params, context) const owned = OPERATION_PARAMS[operation] if (!owned) { - throw new Error(`Invalid Lambda operation: ${params.operation}`) + throw new Error(`Invalid Lambda operation: ${operation}`) } const ownedNames = new Set(owned) diff --git a/apps/sim/blocks/blocks/logfire.ts b/apps/sim/blocks/blocks/logfire.ts index 7c651b997ab..afe1544209a 100644 --- a/apps/sim/blocks/blocks/logfire.ts +++ b/apps/sim/blocks/blocks/logfire.ts @@ -2,7 +2,7 @@ import { Bug, ClipboardList, Clock, Database, File, Search, Server } from '@sim/ import { LogfireIcon } 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 toBoolean = (value: unknown): boolean | undefined => { if (value === true || value === 'true') return true @@ -311,7 +311,7 @@ Return ONLY the IANA timezone string - no explanations or quotes.`, ], config: { tool: (params) => String(params.operation || 'logfire_search_records'), - params: (params) => { + params: (params, context) => { const baseParams = { apiKey: params.apiKey, region: params.region || 'auto', @@ -324,7 +324,7 @@ Return ONLY the IANA timezone string - no explanations or quotes.`, limit: toNumber(params.limit), } - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'logfire_query': return { ...baseParams, diff --git a/apps/sim/blocks/blocks/logrocket.ts b/apps/sim/blocks/blocks/logrocket.ts index 462782e64c5..1f48f274aef 100644 --- a/apps/sim/blocks/blocks/logrocket.ts +++ b/apps/sim/blocks/blocks/logrocket.ts @@ -1,5 +1,6 @@ import { LogRocketIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' +import { mapperOperation } from '@/blocks/utils' /** * A highlights request identifies its subject by email or user ID — either one @@ -286,10 +287,10 @@ export const LogRocketBlock: BlockConfig = { ], config: { tool: (params) => `logrocket_${params.operation}`, - params: (params) => { + params: (params, context) => { const result: Record = {} - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'request_highlights': if (params.highlightsUserEmail) result.userEmail = params.highlightsUserEmail if (params.highlightsUserId) result.userID = params.highlightsUserId diff --git a/apps/sim/blocks/blocks/modal.test.ts b/apps/sim/blocks/blocks/modal.test.ts index 5ef7fcfad21..d8fea6a8268 100644 --- a/apps/sim/blocks/blocks/modal.test.ts +++ b/apps/sim/blocks/blocks/modal.test.ts @@ -50,4 +50,21 @@ describe('ModalBlock', () => { expect(params).not.toHaveProperty('temperature') expect(params).not.toHaveProperty('topP') }) + + it('coerces sampling controls on an agent tool call, where the operation arrives only in the context', () => { + const params = buildParams( + { model: 'Qwen/Qwen3.5-4B', content: 'hello', maxTokens: '256', temperature: 0.2 }, + { operation: 'chat_completion' } + ) + + expect(params).toMatchObject({ maxTokens: 256, temperature: 0.2 }) + }) + + it("keeps the model's function URL on an agent tool call", () => { + const modelArgs = { url: 'https://ws--app-fn.modal.run', method: 'GET' } + + const params = { ...modelArgs, ...buildParams(modelArgs, { operation: 'call_function' }) } + + expect(params.url).toBe('https://ws--app-fn.modal.run') + }) }) diff --git a/apps/sim/blocks/blocks/modal.ts b/apps/sim/blocks/blocks/modal.ts index 507c7996f95..c1a917aeed3 100644 --- a/apps/sim/blocks/blocks/modal.ts +++ b/apps/sim/blocks/blocks/modal.ts @@ -1,6 +1,7 @@ import { ModalIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' import { MODAL_SHARED_INFERENCE_URL } from '@/tools/modal/utils' /** Operations that talk to a Modal Endpoint's OpenAI-compatible `/v1` API. */ @@ -199,14 +200,14 @@ export const ModalBlock: BlockConfig = { access: ['modal_call_function', 'modal_chat_completion', 'modal_list_models'], config: { tool: (params) => `modal_${params.operation}`, - params: (params) => { - const { operation, tokenId, tokenSecret, ...rest } = params + params: (params, context) => { + const { tokenId, tokenSecret, ...rest } = params const baseParams: Record = { tokenId, tokenSecret } - switch (operation) { + switch (mapperOperation(params, context)) { case 'call_function': - baseParams.url = rest.functionUrl + baseParams.url = rest.functionUrl ?? toolCallArg(context, rest.url) if (rest.method) baseParams.method = rest.method if (rest.requestBody !== undefined && rest.requestBody !== '') { baseParams.body = rest.requestBody diff --git a/apps/sim/blocks/blocks/new_relic.ts b/apps/sim/blocks/blocks/new_relic.ts index 18783044c72..7e7f4a2e6ef 100644 --- a/apps/sim/blocks/blocks/new_relic.ts +++ b/apps/sim/blocks/blocks/new_relic.ts @@ -2,7 +2,7 @@ import { getErrorMessage } from '@sim/utils/errors' import { NewRelicIcon } 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 type { NewRelicCustomAttributes } from '@/tools/new_relic/types' import { NEW_RELIC_REGIONS } from '@/tools/new_relic/utils' @@ -285,13 +285,13 @@ Return ONLY the numeric timestamp - no explanations, no extra text.`, ], config: { tool: (params) => String(params.operation || 'new_relic_nrql_query'), - params: (params) => { + params: (params, context) => { const baseParams = { apiKey: params.apiKey, region: params.region || 'us', } - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'new_relic_nrql_query': return { ...baseParams, diff --git a/apps/sim/blocks/blocks/planetscale.test.ts b/apps/sim/blocks/blocks/planetscale.test.ts new file mode 100644 index 00000000000..29d6d5cff73 --- /dev/null +++ b/apps/sim/blocks/blocks/planetscale.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from 'vitest' +import { PlanetScaleBlock } from '@/blocks/blocks/planetscale' + +const mapParams = PlanetScaleBlock.tools.config?.params +if (!mapParams) { + throw new Error('PlanetScale block must define tools.config.params') +} + +/** + * On an agent tool call the operation arrives only on `context` and the model sends the tool's + * `state` param, which the block collects as `backupState`, `deployRequestState`, or `reviewState`. + */ +describe('PlanetScale block agent tool calls', () => { + it('keeps the state filter the model sent', () => { + const args = { organization: 'org', database: 'db', branch: 'main', state: 'success' } + + const params = { ...args, ...mapParams(args, { operation: 'list_backups' }) } + + expect(params.state).toBe('success') + }) +}) diff --git a/apps/sim/blocks/blocks/planetscale.ts b/apps/sim/blocks/blocks/planetscale.ts index b9fa9557230..11095dd2651 100644 --- a/apps/sim/blocks/blocks/planetscale.ts +++ b/apps/sim/blocks/blocks/planetscale.ts @@ -1,6 +1,6 @@ import { PlanetScaleIcon } 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' function optionalBoolean(value: unknown): boolean | undefined { if (value === undefined || value === null || value === '') return undefined @@ -973,29 +973,33 @@ export const PlanetScaleBlock: BlockConfig = { ], config: { tool: (params) => `planetscale_${params.operation}`, - params: (params) => ({ - ...params, - page: optionalNumber(params.page), - perPage: optionalNumber(params.perPage), - production: optionalBoolean(params.production), - safeMigrations: optionalBoolean(params.safeMigrations), - deletionProtected: optionalBoolean(params.deletionProtected), - replicas: optionalNumber(params.replicas), - deleteDescendants: optionalBoolean(params.deleteDescendants), - all: optionalBoolean(params.all), - retentionValue: optionalNumber(params.retentionValue), - emergency: optionalBoolean(params.emergency), - autoCutover: optionalBoolean(params.autoCutover), - autoDeleteBranch: optionalBoolean(params.autoDeleteBranch), - deployRequestNumber: optionalNumber(params.deployRequestNumber), - instantDdl: optionalBoolean(params.instantDdl), - state: - params.operation === 'list_backups' + params: (params, context) => { + const operation = mapperOperation(params, context) + const blockState = + operation === 'list_backups' ? params.backupState - : params.operation === 'list_deploy_requests' + : operation === 'list_deploy_requests' ? params.deployRequestState - : params.reviewState, - }), + : params.reviewState + return { + ...params, + page: optionalNumber(params.page), + perPage: optionalNumber(params.perPage), + production: optionalBoolean(params.production), + safeMigrations: optionalBoolean(params.safeMigrations), + deletionProtected: optionalBoolean(params.deletionProtected), + replicas: optionalNumber(params.replicas), + deleteDescendants: optionalBoolean(params.deleteDescendants), + all: optionalBoolean(params.all), + retentionValue: optionalNumber(params.retentionValue), + emergency: optionalBoolean(params.emergency), + autoCutover: optionalBoolean(params.autoCutover), + autoDeleteBranch: optionalBoolean(params.autoDeleteBranch), + deployRequestNumber: optionalNumber(params.deployRequestNumber), + instantDdl: optionalBoolean(params.instantDdl), + state: blockState ?? toolCallArg(context, params.state) ?? blockState, + } + }, }, }, outputs: { diff --git a/apps/sim/blocks/blocks/railway.test.ts b/apps/sim/blocks/blocks/railway.test.ts new file mode 100644 index 00000000000..076e24e38d4 --- /dev/null +++ b/apps/sim/blocks/blocks/railway.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from 'vitest' +import { RailwayBlock } from '@/blocks/blocks/railway' + +const mapParams = RailwayBlock.tools.config?.params +if (!mapParams) { + throw new Error('Railway block must define tools.config.params') +} + +/** + * On an agent tool call the operation arrives only on `context`. A yes/no dropdown filled in the + * tool row stays the string `'true'`, which Railway's GraphQL `Boolean` variables reject. + */ +describe('Railway block agent tool calls', () => { + it('sends a dropdown answer from the tool row as a boolean and keeps the model args', () => { + const args = { apiKey: 'token', name: 'my-project', isPublic: false, prDeploys: 'true' } + + const params = { ...args, ...mapParams(args, { operation: 'create_project' }) } + + expect(params).toMatchObject({ name: 'my-project', isPublic: false, prDeploys: true }) + }) +}) diff --git a/apps/sim/blocks/blocks/railway.ts b/apps/sim/blocks/blocks/railway.ts index 3f3d397bc69..d95332ce5e3 100644 --- a/apps/sim/blocks/blocks/railway.ts +++ b/apps/sim/blocks/blocks/railway.ts @@ -1,7 +1,15 @@ import { RailwayIcon } 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' + +/** + * Reads a Railway yes/no dropdown (`'true'`/`'false'`, blank for unset) or a boolean a model sent. + */ +function dropdownBoolean(value: unknown): boolean | undefined { + if (typeof value === 'boolean') return value + return value ? value === 'true' : undefined +} export const RailwayBlock: BlockConfig = { type: 'railway', @@ -690,114 +698,110 @@ export const RailwayBlock: BlockConfig = { ], config: { tool: (params) => `railway_${params.operation}`, - params: (params) => { + params: (params, context) => { + const arg = (key: string) => toolCallArg(context, params[key]) + /** The block field, else (on a tool call) the model's arg for the tool param `key`. */ + const field = (value: unknown, key: string) => value ?? arg(key) ?? value const baseParams = { apiKey: params.apiKey, tokenType: params.tokenType, } - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'list_projects': return { ...baseParams, - workspaceId: params.listProjectsWorkspaceId, + workspaceId: field(params.listProjectsWorkspaceId, 'workspaceId'), first: params.first ? Number(params.first) : undefined, after: params.after, } case 'create_project': return { ...baseParams, - name: params.createProjectName, - description: params.createProjectDescription, - workspaceId: params.createProjectWorkspaceId, - isPublic: params.createProjectIsPublic - ? params.createProjectIsPublic === 'true' - : undefined, + name: field(params.createProjectName, 'name'), + description: field(params.createProjectDescription, 'description'), + workspaceId: field(params.createProjectWorkspaceId, 'workspaceId'), + isPublic: + dropdownBoolean(params.createProjectIsPublic) ?? dropdownBoolean(arg('isPublic')), defaultEnvironmentName: params.defaultEnvironmentName, - prDeploys: params.prDeploys ? params.prDeploys === 'true' : undefined, + prDeploys: dropdownBoolean(params.prDeploys), } case 'update_project': return { ...baseParams, - projectId: params.updateProjectId, - name: params.updateProjectName, - description: params.updateProjectDescription, - isPublic: params.updateProjectIsPublic - ? params.updateProjectIsPublic === 'true' - : undefined, - prDeploys: params.updateProjectPrDeploys - ? params.updateProjectPrDeploys === 'true' - : undefined, + projectId: field(params.updateProjectId, 'projectId'), + name: field(params.updateProjectName, 'name'), + description: field(params.updateProjectDescription, 'description'), + isPublic: + dropdownBoolean(params.updateProjectIsPublic) ?? dropdownBoolean(arg('isPublic')), + prDeploys: + dropdownBoolean(params.updateProjectPrDeploys) ?? dropdownBoolean(arg('prDeploys')), } case 'delete_project': return { ...baseParams, - projectId: params.deleteProjectId, + projectId: field(params.deleteProjectId, 'projectId'), } case 'transfer_project': return { ...baseParams, - projectId: params.transferProjectId, + projectId: field(params.transferProjectId, 'projectId'), workspaceId: params.workspaceId, } case 'list_project_members': return { ...baseParams, - projectId: params.membersProjectId, + projectId: field(params.membersProjectId, 'projectId'), } case 'create_environment': return { ...baseParams, - projectId: params.createEnvironmentProjectId, - name: params.environmentName, + projectId: field(params.createEnvironmentProjectId, 'projectId'), + name: field(params.environmentName, 'name'), sourceEnvironmentId: params.sourceEnvironmentId, - ephemeral: params.ephemeral ? params.ephemeral === 'true' : undefined, - skipInitialDeploys: params.skipInitialDeploys - ? params.skipInitialDeploys === 'true' - : undefined, - stageInitialChanges: params.stageInitialChanges - ? params.stageInitialChanges === 'true' - : undefined, + ephemeral: dropdownBoolean(params.ephemeral), + skipInitialDeploys: dropdownBoolean(params.skipInitialDeploys), + stageInitialChanges: dropdownBoolean(params.stageInitialChanges), } case 'delete_environment': return { ...baseParams, - environmentId: params.deleteEnvironmentId, + environmentId: field(params.deleteEnvironmentId, 'environmentId'), } case 'get_project': return { ...baseParams, - projectId: params.detailProjectId, + projectId: field(params.detailProjectId, 'projectId'), } case 'list_deployments': return { ...baseParams, - projectId: params.deploymentProjectId, - serviceId: params.deploymentServiceId, - environmentId: params.deploymentEnvironmentId, - first: params.deploymentFirst ? Number(params.deploymentFirst) : undefined, - after: params.deploymentAfter, + projectId: field(params.deploymentProjectId, 'projectId'), + serviceId: field(params.deploymentServiceId, 'serviceId'), + environmentId: field(params.deploymentEnvironmentId, 'environmentId'), + first: params.deploymentFirst ? Number(params.deploymentFirst) : arg('first'), + after: field(params.deploymentAfter, 'after'), } case 'deploy_service': return { ...baseParams, - serviceId: params.deployServiceId, - environmentId: params.deployEnvironmentId, - commitSha: params.deployCommitSha, + serviceId: field(params.deployServiceId, 'serviceId'), + environmentId: field(params.deployEnvironmentId, 'environmentId'), + commitSha: field(params.deployCommitSha, 'commitSha'), } case 'create_service': return { ...baseParams, - projectId: params.createServiceProjectId, - name: params.createServiceName, - repo: params.createServiceRepo, - image: params.createServiceImage, - branch: params.createServiceBranch, + projectId: field(params.createServiceProjectId, 'projectId'), + name: field(params.createServiceName, 'name'), + repo: field(params.createServiceRepo, 'repo'), + image: field(params.createServiceImage, 'image'), + branch: field(params.createServiceBranch, 'branch'), } case 'delete_service': return { ...baseParams, - serviceId: params.deleteServiceId, + serviceId: field(params.deleteServiceId, 'serviceId'), } case 'get_deployment': return { @@ -818,32 +822,32 @@ export const RailwayBlock: BlockConfig = { return { ...baseParams, deploymentId: params.deploymentId, - limit: params.logsLimit ? Number(params.logsLimit) : undefined, + limit: params.logsLimit ? Number(params.logsLimit) : arg('limit'), } case 'list_variables': return { ...baseParams, - projectId: params.variablesProjectId, - environmentId: params.variablesEnvironmentId, - serviceId: params.variablesServiceId, + projectId: field(params.variablesProjectId, 'projectId'), + environmentId: field(params.variablesEnvironmentId, 'environmentId'), + serviceId: field(params.variablesServiceId, 'serviceId'), } case 'upsert_variable': return { ...baseParams, - projectId: params.upsertProjectId, - environmentId: params.upsertEnvironmentId, - serviceId: params.upsertServiceId, - name: params.variableName, - value: params.variableValue, - skipDeploys: params.skipDeploys ? params.skipDeploys === 'true' : undefined, + projectId: field(params.upsertProjectId, 'projectId'), + environmentId: field(params.upsertEnvironmentId, 'environmentId'), + serviceId: field(params.upsertServiceId, 'serviceId'), + name: field(params.variableName, 'name'), + value: field(params.variableValue, 'value'), + skipDeploys: dropdownBoolean(params.skipDeploys), } case 'delete_variable': return { ...baseParams, - projectId: params.deleteVariableProjectId, - environmentId: params.deleteVariableEnvironmentId, - serviceId: params.deleteVariableServiceId, - name: params.deleteVariableName, + projectId: field(params.deleteVariableProjectId, 'projectId'), + environmentId: field(params.deleteVariableEnvironmentId, 'environmentId'), + serviceId: field(params.deleteVariableServiceId, 'serviceId'), + name: field(params.deleteVariableName, 'name'), } default: return baseParams diff --git a/apps/sim/blocks/blocks/rds.ts b/apps/sim/blocks/blocks/rds.ts index 89799071952..6df9d3bf6da 100644 --- a/apps/sim/blocks/blocks/rds.ts +++ b/apps/sim/blocks/blocks/rds.ts @@ -2,7 +2,7 @@ import { getErrorMessage } from '@sim/utils/errors' import { RDSIcon } 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' export const RDSBlock: BlockConfig = { type: 'rds', @@ -451,8 +451,9 @@ Return ONLY valid JSON - no explanations, no markdown code blocks.`, throw new Error(`Invalid RDS operation: ${params.operation}`) } }, - params: (params) => { - const { operation, data, conditions, schema, engine, parameters, ...rest } = params + params: (params, context) => { + const operation = mapperOperation(params, context) + const { data, conditions, schema, engine, parameters, ...rest } = params // Parse JSON fields const parseJson = (value: unknown, fieldName: string) => { diff --git a/apps/sim/blocks/blocks/s3.test.ts b/apps/sim/blocks/blocks/s3.test.ts new file mode 100644 index 00000000000..32020227dbb --- /dev/null +++ b/apps/sim/blocks/blocks/s3.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from 'vitest' +import { S3Block } from '@/blocks/blocks/s3' + +const mapParams = S3Block.tools.config?.params +if (!mapParams) { + throw new Error('S3 block must define tools.config.params') +} + +const CONNECTION = { + accessKeyId: 'AKIAIOSFODNN7EXAMPLE', + secretAccessKey: 'secret', + region: 'us-east-1', +} + +/** Runs the mapper the way an agent tool call does: no `operation` in params, merged over them. */ +function toolCall(args: Record, operation: string) { + return { ...args, ...mapParams?.(args, { operation }) } +} + +/** + * On an agent tool call the operation arrives only on `context` and the model's args use the + * tool's param names (`keys`, `method`), not the block's field ids (`objectKeys`, `presignedMethod`). + */ +describe('S3 block agent tool calls', () => { + it('deletes the keys the model sent', () => { + const params = toolCall( + { ...CONNECTION, bucketName: 'bucket', keys: ['a.txt', 'b.txt'] }, + 'delete_objects' + ) + + expect(params.keys).toEqual(['a.txt', 'b.txt']) + }) + + it('presigns with the URL method the model sent', () => { + const params = toolCall( + { ...CONNECTION, bucketName: 'bucket', objectKey: 'a.txt', method: 'put', expiresIn: 600 }, + 'presigned_url' + ) + + expect(params).toMatchObject({ method: 'put', expiresIn: 600, bucketName: 'bucket' }) + }) +}) diff --git a/apps/sim/blocks/blocks/s3.ts b/apps/sim/blocks/blocks/s3.ts index 7c3bee8f9c5..98fc9421064 100644 --- a/apps/sim/blocks/blocks/s3.ts +++ b/apps/sim/blocks/blocks/s3.ts @@ -1,7 +1,17 @@ import { S3Icon } from '@/components/icons' -import type { BlockConfig, BlockMeta, BlockToolParams } from '@/blocks/types' +import type { + BlockConfig, + BlockMeta, + BlockToolParams, + BlockToolParamsContext, +} from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput, withSavedCredential } from '@/blocks/utils' +import { + mapperOperation, + normalizeFileInput, + toolCallArg, + withSavedCredential, +} from '@/blocks/utils' /** * Normalize the batch-delete keys input into a string array. Accepts an array, @@ -33,9 +43,11 @@ function parseObjectKeys(value: unknown): string[] { const UPLOAD_SOURCE_FIELD = ['uploadFile', 'fileReference', 'content'] as const /** Tool params for an S3 operation; credentials are validated by the caller. */ -function s3ToolParams(params: BlockToolParams) { +function s3ToolParams(params: BlockToolParams, context?: BlockToolParamsContext) { // Default to get_object for backward compatibility with existing workflows - const operation = params.operation || 'get_object' + const operation = mapperOperation(params, context) || 'get_object' + /** The block field, else (on a tool call) the model's arg for the tool param `key`. */ + const field = (value: unknown, key: string) => value ?? toolCallArg(context, params[key]) ?? value // Operation-specific parameters switch (operation) { @@ -63,7 +75,7 @@ function s3ToolParams(params: BlockToolParams) { content: params.content, contentType: params.contentType, acl: params.acl, - metadata: params.objectMetadata, + metadata: field(params.objectMetadata, 'metadata'), storageClass: params.storageClass, serverSideEncryption: params.serverSideEncryption, sseKmsKeyId: @@ -155,11 +167,11 @@ function s3ToolParams(params: BlockToolParams) { accessKeyId: params.accessKeyId, secretAccessKey: params.secretAccessKey, region: params.region, - prefix: params.bucketPrefix, + prefix: field(params.bucketPrefix, 'prefix'), maxBuckets: params.maxBuckets ? Number.parseInt(params.maxBuckets as string, 10) : undefined, - continuationToken: params.bucketsContinuationToken, + continuationToken: field(params.bucketsContinuationToken, 'continuationToken'), } case 'head_object': @@ -178,7 +190,7 @@ function s3ToolParams(params: BlockToolParams) { region: params.region, bucketName: params.bucketName, objectKey: params.objectKey, - versionId: params.headVersionId, + versionId: field(params.headVersionId, 'versionId'), } case 'create_bucket': @@ -193,7 +205,7 @@ function s3ToolParams(params: BlockToolParams) { secretAccessKey: params.secretAccessKey, region: params.region, bucketName: params.bucketName, - acl: params.createBucketAcl, + acl: field(params.createBucketAcl, 'acl'), } case 'delete_bucket': @@ -220,7 +232,8 @@ function s3ToolParams(params: BlockToolParams) { if (!params.objectKey) { throw new Error('Object Key is required') } - if (!params.presignedMethod) { + const method = params.presignedMethod || toolCallArg(context, params.method) + if (!method) { throw new Error('URL Type (get or put) is required') } return { @@ -229,9 +242,9 @@ function s3ToolParams(params: BlockToolParams) { region: params.region, bucketName: params.bucketName, objectKey: params.objectKey, - method: params.presignedMethod, + method, expiresIn: params.expiresIn ? Number.parseInt(params.expiresIn as string, 10) : undefined, - contentType: params.presignedContentType, + contentType: field(params.presignedContentType, 'contentType'), } } @@ -242,7 +255,7 @@ function s3ToolParams(params: BlockToolParams) { if (!params.bucketName) { throw new Error('Bucket Name is required') } - const keys = parseObjectKeys(params.objectKeys) + const keys = parseObjectKeys(field(params.objectKeys, 'keys')) if (keys.length === 0) { throw new Error('At least one object key is required') } @@ -783,7 +796,7 @@ export const S3Block: BlockConfig = { throw new Error(`Invalid S3 operation: ${operation}`) } }, - params: (params) => { + params: (params, context) => { // Validate required fields (common to all operations) if (!params.accessKeyId) { throw new Error('Access Key ID is required') @@ -792,7 +805,7 @@ export const S3Block: BlockConfig = { throw new Error('Secret Access Key is required') } - return s3ToolParams(params) + return s3ToolParams(params, context) }, }, }, diff --git a/apps/sim/blocks/blocks/secrets_manager.test.ts b/apps/sim/blocks/blocks/secrets_manager.test.ts new file mode 100644 index 00000000000..997b43391ab --- /dev/null +++ b/apps/sim/blocks/blocks/secrets_manager.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from 'vitest' +import { SecretsManagerBlock } from '@/blocks/blocks/secrets_manager' + +/** + * On an agent tool call the operation arrives only on `context`, and the merged row and model + * values are keyed by the tool's param names (row fields hold strings). The handler forwards + * `{ ...merged, ...mapped }`. + */ +const agentCall = (operation: string, merged: Record) => ({ + ...merged, + ...SecretsManagerBlock.tools.config?.params?.(merged, { operation }), +}) + +describe('SecretsManagerBlock agent tool calls', () => { + it('coerces the max results typed in the tool row when listing secrets', () => { + expect(agentCall('list_secrets', { maxResults: '10' })).toMatchObject({ maxResults: 10 }) + }) + + it('keeps the tags the model supplied when creating a secret', () => { + const tags = [{ Key: 'team', Value: 'core' }] + expect(agentCall('create_secret', { name: 'db', secretValue: 'x', tags })).toMatchObject({ + tags, + }) + }) +}) diff --git a/apps/sim/blocks/blocks/secrets_manager.ts b/apps/sim/blocks/blocks/secrets_manager.ts index c17b40be430..756f32d8d92 100644 --- a/apps/sim/blocks/blocks/secrets_manager.ts +++ b/apps/sim/blocks/blocks/secrets_manager.ts @@ -2,7 +2,7 @@ import { getErrorMessage } from '@sim/utils/errors' import { SecretsManagerIcon } 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' /** Parses a JSON field typed into the block, naming the field when it is invalid. */ function parseJsonField(value: unknown, fieldName: string): unknown { @@ -412,9 +412,9 @@ Return ONLY the JSON array - no explanations, no markdown code blocks.`, throw new Error(`Invalid Secrets Manager operation: ${params.operation}`) } }, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { - operation, forceDelete, recoveryWindowInDays, maxResults, @@ -457,7 +457,9 @@ Return ONLY the JSON array - no explanations, no markdown code blocks.`, result.secretValue = rest.secretValue if (rest.description) result.description = rest.description result.kmsKeyId = rest.kmsKeyId || undefined - result.tags = rest.createTags ? parseJsonField(rest.createTags, 'Tags') : undefined + result.tags = rest.createTags + ? parseJsonField(rest.createTags, 'Tags') + : toolCallArg(context, rest.tags) break case 'update_secret': result.secretId = rest.secretId diff --git a/apps/sim/blocks/blocks/ses.test.ts b/apps/sim/blocks/blocks/ses.test.ts new file mode 100644 index 00000000000..5106351c119 --- /dev/null +++ b/apps/sim/blocks/blocks/ses.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'vitest' +import { SESBlock } from '@/blocks/blocks/ses' + +/** + * On an agent tool call the operation arrives only on `context`, and the merged row and model + * values are keyed by the tool's param names (row fields hold strings). The handler forwards + * `{ ...merged, ...mapped }`. + */ +const agentCall = (operation: string, merged: Record) => ({ + ...merged, + ...SESBlock.tools.config?.params?.(merged, { operation }), +}) + +describe('SESBlock agent tool calls', () => { + it('coerces the page size typed in the tool row when listing templates', () => { + expect(agentCall('list_templates', { pageSize: '20' })).toMatchObject({ pageSize: 20 }) + }) + + it('keeps the model-supplied configuration set name and reply-to', () => { + expect( + agentCall('create_configuration_set', { configurationSetName: 'transactional' }) + ).toMatchObject({ configurationSetName: 'transactional' }) + expect(agentCall('send_bulk_email', { replyToAddresses: 'ops@example.com' })).toMatchObject({ + replyToAddresses: 'ops@example.com', + }) + }) +}) diff --git a/apps/sim/blocks/blocks/ses.ts b/apps/sim/blocks/blocks/ses.ts index ed55f6f6a02..ed0821fa9cc 100644 --- a/apps/sim/blocks/blocks/ses.ts +++ b/apps/sim/blocks/blocks/ses.ts @@ -1,7 +1,7 @@ import { SESIcon } 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' export const SESBlock: BlockConfig = { type: 'ses', @@ -671,8 +671,9 @@ export const SESBlock: BlockConfig = { throw new Error(`Invalid SES operation: ${params.operation}`) } }, - params: (params) => { - const { operation, pageSize, ...rest } = params + params: (params, context) => { + const operation = mapperOperation(params, context) + const { pageSize, ...rest } = params const parseEmailTags = (value: unknown) => { if (value === undefined || value === null || value === '') return undefined @@ -741,7 +742,9 @@ export const SESBlock: BlockConfig = { result.emailIdentity = rest.emailIdentity break case 'create_configuration_set': - result.configurationSetName = rest.newConfigurationSetName + result.configurationSetName = isToolCall(context) + ? rest.newConfigurationSetName || rest.configurationSetName + : rest.newConfigurationSetName if (rest.customRedirectDomain) result.customRedirectDomain = rest.customRedirectDomain if (rest.httpsPolicy) result.httpsPolicy = rest.httpsPolicy if (rest.tlsPolicy) result.tlsPolicy = rest.tlsPolicy @@ -778,7 +781,10 @@ export const SESBlock: BlockConfig = { if (rest.ccAddresses) result.ccAddresses = rest.ccAddresses if (rest.bccAddresses) result.bccAddresses = rest.bccAddresses if (rest.configurationSetName) result.configurationSetName = rest.configurationSetName - applySendOptions(result, rest.templateReplyToAddresses) + applySendOptions( + result, + rest.templateReplyToAddresses || toolCallArg(context, rest.replyToAddresses) + ) break case 'send_bulk_email': result.fromAddress = rest.fromAddress @@ -786,7 +792,10 @@ export const SESBlock: BlockConfig = { result.destinations = rest.destinations if (rest.defaultTemplateData) result.defaultTemplateData = rest.defaultTemplateData if (rest.configurationSetName) result.configurationSetName = rest.configurationSetName - applySendOptions(result, rest.templateReplyToAddresses) + applySendOptions( + result, + rest.templateReplyToAddresses || toolCallArg(context, rest.replyToAddresses) + ) break case 'list_identities': if (pageSize != null) { diff --git a/apps/sim/blocks/blocks/sftp.test.ts b/apps/sim/blocks/blocks/sftp.test.ts new file mode 100644 index 00000000000..3cf2c931513 --- /dev/null +++ b/apps/sim/blocks/blocks/sftp.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from 'vitest' +import { SftpV2Block } from '@/blocks/blocks/sftp' + +/** + * On an agent tool call the operation arrives only on `context`, and the create-directory tool row + * has no Create Parent Directories field, so the mapper applies the switch's default. + */ +describe('SftpV2Block agent tool calls', () => { + it('creates parent directories by default on a create-directory call', () => { + const merged = { host: 'h', username: 'u', password: 'p', remotePath: '/a/b' } + expect({ + ...merged, + ...SftpV2Block.tools.config?.params?.(merged, { operation: 'sftp_mkdir' }), + }).toMatchObject({ recursive: true }) + }) +}) diff --git a/apps/sim/blocks/blocks/sftp.ts b/apps/sim/blocks/blocks/sftp.ts index aaf84f3126b..536082dffcc 100644 --- a/apps/sim/blocks/blocks/sftp.ts +++ b/apps/sim/blocks/blocks/sftp.ts @@ -1,9 +1,9 @@ import { ClipboardList, Download, File, Search, Server, Trash, Upload } from '@sim/emcn/icons' import { omit } from '@sim/utils/object' import { SftpIcon } 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 { createVersionedToolSelector, normalizeFileInput } from '@/blocks/utils' +import { createVersionedToolSelector, mapperOperation, normalizeFileInput } from '@/blocks/utils' export const SftpBlock = { type: 'sftp', @@ -227,7 +227,7 @@ export const SftpBlock = { if (operation === 'sftp_create') return 'sftp_upload' return operation }, - params: (params) => { + params: (params, context?: BlockToolParamsContext) => { const connectionConfig: Record = { host: params.host, port: @@ -244,7 +244,7 @@ export const SftpBlock = { connectionConfig.password = params.password } - const operation = params.operation || 'sftp_upload' + const operation = mapperOperation(params, context) || 'sftp_upload' switch (operation) { case 'sftp_upload': @@ -360,8 +360,8 @@ export const SftpV2Block: BlockConfig = { params.operation === 'sftp_download' ? selectSftpV2Tool(params) : SftpBlock.tools.config.tool(params), - params: (params) => { - const input: Record = SftpBlock.tools.config.params(params) + params: (params, context) => { + const input: Record = SftpBlock.tools.config.params(params, context) return omit(input, ['encoding']) }, }, diff --git a/apps/sim/blocks/blocks/splunk.test.ts b/apps/sim/blocks/blocks/splunk.test.ts index bd94ebe951f..27fadc72545 100644 --- a/apps/sim/blocks/blocks/splunk.test.ts +++ b/apps/sim/blocks/blocks/splunk.test.ts @@ -4,13 +4,14 @@ import { describe, expect, it, vi } from 'vitest' vi.mock('@/triggers', () => triggersMock) import { SplunkBlock } from '@/blocks/blocks/splunk' +import type { BlockToolParamsContext } from '@/blocks/types' import { buildSplunkFormBody, buildSplunkUrl } from '@/tools/splunk/utils' const toParams = SplunkBlock.tools.config?.params -function mapParams(params: Record) { +function mapParams(params: Record, context?: BlockToolParamsContext) { if (!toParams) throw new Error('SplunkBlock is missing tools.config.params') - return toParams(params as Parameters[0]) + return toParams(params as Parameters[0], context) } /** @@ -141,3 +142,27 @@ describe('SplunkBlock numeric coercion', () => { expect(buildSplunkFormBody({ max_count: merged.count as number | undefined })).toBe('') }) }) + +/** + * On an agent tool call the operation arrives only on `context`, and the merged row and model + * values are keyed by the tool's param names (row switches hold strings). The handler forwards + * `{ ...merged, ...mapped }`. + */ +describe('SplunkBlock agent tool calls', () => { + const agentCall = (operation: string, merged: Record) => ({ + ...merged, + ...mapParams(merged, { operation }), + }) + + it('coerces the switches typed in the tool row when dispatching a saved search', () => { + expect( + agentCall('splunk_dispatch_saved_search', { name: 'Errors', forceDispatch: 'false' }) + ).toMatchObject({ name: 'Errors', forceDispatch: false }) + }) + + it('keeps the name the model supplied for fired alerts', () => { + expect(agentCall('splunk_get_fired_alerts', { name: 'Disk full' })).toMatchObject({ + name: 'Disk full', + }) + }) +}) diff --git a/apps/sim/blocks/blocks/splunk.ts b/apps/sim/blocks/blocks/splunk.ts index 0c8a45511ff..4263f437a04 100644 --- a/apps/sim/blocks/blocks/splunk.ts +++ b/apps/sim/blocks/blocks/splunk.ts @@ -1,7 +1,7 @@ import { SplunkIcon } 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, withSavedCredential } from '@/blocks/utils' /** * Normalize a Splunk toggle. A dropdown supplies the strings `'true'`/`'false'`, @@ -40,6 +40,18 @@ function assignSplunkNumber(target: Record, key: string, value: target[key] = Number.isFinite(parsed) ? parsed : undefined } +/** + * A dedicated block field, or on a tool call the model's arg under the tool's own param name + * when that field is blank: the model fills `name`/`search`, never the block-only field. + */ +function blockFieldOrToolArg( + dedicated: unknown, + toolArg: unknown, + context: BlockToolParamsContext | undefined +): unknown { + return isToolCall(context) && (dedicated == null || dedicated === '') ? toolArg : dedicated +} + export const SplunkBlock: BlockConfig = { type: 'splunk', hideFromToolbar: true, @@ -492,13 +504,13 @@ Examples: ], config: { tool: (params) => params.operation, - params: (params) => { + params: (params, context) => { const result: Record = {} assignSplunkNumber(result, 'count', params.count) assignSplunkNumber(result, 'offset', params.offset) - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'splunk_run_search': assignSplunkNumber(result, 'autoCancel', params.autoCancel) assignSplunkNumber(result, 'maxCount', params.maxCount) @@ -513,11 +525,12 @@ Examples: result.addSummaryToMetadata = toSplunkToggle(params.addSummaryToMetadata) break case 'splunk_list_saved_searches': - result.search = params.savedSearchFilter ?? '' + result.search = + blockFieldOrToolArg(params.savedSearchFilter, params.search, context) ?? '' break case 'splunk_get_saved_search': case 'splunk_dispatch_saved_search': - result.name = params.savedSearchName + result.name = blockFieldOrToolArg(params.savedSearchName, params.name, context) result.triggerActions = toSplunkToggle(params.triggerActions) result.forceDispatch = toSplunkToggle(params.forceDispatch) assignSplunkNumber(result, 'dispatchMaxCount', params.dispatchMaxCount) @@ -525,7 +538,7 @@ Examples: assignSplunkNumber(result, 'dispatchTtl', params.dispatchTtl) break case 'splunk_get_fired_alerts': - result.name = params.alertName + result.name = blockFieldOrToolArg(params.alertName, params.name, context) break } diff --git a/apps/sim/blocks/blocks/sqs.test.ts b/apps/sim/blocks/blocks/sqs.test.ts index fc49c5b1d31..2294e0778ee 100644 --- a/apps/sim/blocks/blocks/sqs.test.ts +++ b/apps/sim/blocks/blocks/sqs.test.ts @@ -32,3 +32,25 @@ describe('SQS block integer parsing', () => { ).toThrow('maxNumberOfMessages must be a whole number') }) }) + +/** + * On an agent tool call the operation arrives only on `context`, and the merged row and model + * values are keyed by the tool's param names (row fields hold strings). + */ +describe('SQS block agent tool calls', () => { + it('coerces the delay typed in the tool row when sending a message', () => { + const merged = { ...CONNECTION, queueUrl: QUEUE_URL, data: '{"a":1}', delaySeconds: '5' } + expect({ ...merged, ...mapParams(merged, { operation: 'send' }) }).toMatchObject({ + delaySeconds: 5, + data: { a: 1 }, + }) + }) + + it('keeps the batch entries the model supplied', () => { + const entries = [{ id: '1', data: { a: 1 } }] + const merged = { ...CONNECTION, queueUrl: QUEUE_URL, entries } + expect({ ...merged, ...mapParams(merged, { operation: 'send_message_batch' }) }).toMatchObject({ + entries, + }) + }) +}) diff --git a/apps/sim/blocks/blocks/sqs.ts b/apps/sim/blocks/blocks/sqs.ts index 9fd7845e452..0abb55e62ec 100644 --- a/apps/sim/blocks/blocks/sqs.ts +++ b/apps/sim/blocks/blocks/sqs.ts @@ -2,7 +2,7 @@ import { getErrorMessage } from '@sim/utils/errors' import { SQSIcon } 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' export const SQSBlock: BlockConfig = { type: 'sqs', @@ -603,8 +603,9 @@ export const SQSBlock: BlockConfig = { throw new Error(`Invalid SQS operation: ${params.operation}`) } }, - params: (params) => { - const { operation, ...rest } = params + params: (params, context) => { + const operation = mapperOperation(params, context) + const rest = params const parseJson = (value: unknown, fieldName: string) => { if (value === undefined || value === null || value === '') return undefined diff --git a/apps/sim/blocks/blocks/ssh.test.ts b/apps/sim/blocks/blocks/ssh.test.ts new file mode 100644 index 00000000000..e77e8d60572 --- /dev/null +++ b/apps/sim/blocks/blocks/ssh.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from 'vitest' +import { SSHBlock } from '@/blocks/blocks/ssh' + +const CONNECTION = { host: 'example.com', port: 22, username: 'deploy', password: 'pw' } + +/** + * On an agent tool call the operation arrives only on `context` and the model sends the tool's + * `path`, which the block collects under a per-operation field (`listPath`, `readPath`, ...). + */ +describe('SSH block agent tool calls', () => { + it('keeps the model path and coerces maxSize when reading a file', () => { + const merged = { ...CONNECTION, path: '/etc/hosts', maxSize: '5' } + const mapped = SSHBlock.tools.config.params(merged, { operation: 'ssh_read_file_content' }) + expect({ ...merged, ...mapped }).toMatchObject({ path: '/etc/hosts', maxSize: 5 }) + }) +}) diff --git a/apps/sim/blocks/blocks/ssh.ts b/apps/sim/blocks/blocks/ssh.ts index e85e51bbbb8..d313b3a5a85 100644 --- a/apps/sim/blocks/blocks/ssh.ts +++ b/apps/sim/blocks/blocks/ssh.ts @@ -3,7 +3,7 @@ import { omit } from '@sim/utils/object' import { SshIcon, SshTerminalIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { createVersionedToolSelector } from '@/blocks/utils' +import { createVersionedToolSelector, mapperOperation, toolCallArg } from '@/blocks/utils' export const SSHBlock = { type: 'ssh', @@ -524,7 +524,7 @@ Examples: tool: (params) => { return params.operation || 'ssh_execute_command' }, - params: (params) => { + params: (params, context) => { // Build connection config const connectionConfig: Record = { host: params.host, @@ -544,7 +544,7 @@ Examples: } // Build operation-specific parameters based on the selected operation - const operation = params.operation || 'ssh_execute_command' + const operation = mapperOperation(params, context) || 'ssh_execute_command' switch (operation) { case 'ssh_execute_command': @@ -558,7 +558,8 @@ Examples: ...connectionConfig, script: params.script, interpreter: params.interpreter || '/bin/bash', - workingDirectory: params.scriptWorkingDirectory, + workingDirectory: + params.scriptWorkingDirectory ?? toolCallArg(context, params.workingDirectory), } case 'ssh_check_command_exists': return { @@ -576,31 +577,31 @@ Examples: case 'ssh_download_file': return { ...connectionConfig, - remotePath: params.downloadRemotePath, + remotePath: params.downloadRemotePath ?? toolCallArg(context, params.remotePath), } case 'ssh_list_directory': return { ...connectionConfig, - path: params.listPath, + path: params.listPath ?? toolCallArg(context, params.path), detailed: params.detailed, } case 'ssh_check_file_exists': return { ...connectionConfig, - path: params.checkPath, - type: params.checkType || 'any', + path: params.checkPath ?? toolCallArg(context, params.path), + type: params.checkType || toolCallArg(context, params.type) || 'any', } case 'ssh_create_directory': return { ...connectionConfig, - path: params.createPath, + path: params.createPath ?? toolCallArg(context, params.path), recursive: params.recursive !== false, } case 'ssh_delete_file': return { ...connectionConfig, - path: params.deletePath, - recursive: params.deleteRecursive, + path: params.deletePath ?? toolCallArg(context, params.path), + recursive: params.deleteRecursive ?? toolCallArg(context, params.recursive), force: params.force, } case 'ssh_move_rename': @@ -615,17 +616,17 @@ Examples: case 'ssh_read_file_content': return { ...connectionConfig, - path: params.readPath, + path: params.readPath ?? toolCallArg(context, params.path), encoding: params.encoding || 'utf-8', maxSize: params.maxSize ? Number.parseInt(params.maxSize, 10) : 10, } case 'ssh_write_file_content': return { ...connectionConfig, - path: params.writePath, + path: params.writePath ?? toolCallArg(context, params.path), content: params.content, - mode: params.writeMode || 'overwrite', - permissions: params.writePermissions, + mode: params.writeMode || toolCallArg(context, params.mode) || 'overwrite', + permissions: params.writePermissions ?? toolCallArg(context, params.permissions), } default: return connectionConfig diff --git a/apps/sim/blocks/blocks/ssm.test.ts b/apps/sim/blocks/blocks/ssm.test.ts new file mode 100644 index 00000000000..e09f8362844 --- /dev/null +++ b/apps/sim/blocks/blocks/ssm.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from 'vitest' +import { SSMBlock } from '@/blocks/blocks/ssm' + +const mapParams = SSMBlock.tools.config?.params +if (!mapParams) { + throw new Error('SSM block must define tools.config.params') +} + +const CONNECTION = { + region: 'us-east-1', + accessKeyId: 'AKIAIOSFODNN7EXAMPLE', + secretAccessKey: 'secret', +} + +/** + * On an agent tool call the operation arrives only on `context` and the model's args are keyed by + * the tool's param names, so the mapper must coerce them and never replace them with an empty + * block-only field. + */ +describe('SSM block agent tool calls', () => { + it.each([ + { + operation: 'get_parameters', + args: { names: '["/app/db","/app/key"]' }, + expected: { names: ['/app/db', '/app/key'] }, + }, + { + operation: 'get_parameter', + args: { name: '/app/db', withDecryption: 'true' }, + expected: { name: '/app/db', withDecryption: true }, + }, + ])('$operation keeps and coerces the model args', ({ operation, args, expected }) => { + const merged = { ...CONNECTION, ...args } + expect({ ...merged, ...mapParams(merged, { operation }) }).toMatchObject(expected) + }) +}) diff --git a/apps/sim/blocks/blocks/ssm.ts b/apps/sim/blocks/blocks/ssm.ts index df5d2736d0f..c581ce0d92c 100644 --- a/apps/sim/blocks/blocks/ssm.ts +++ b/apps/sim/blocks/blocks/ssm.ts @@ -1,7 +1,7 @@ import { SSMIcon } 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 whose SSM API caps `MaxResults` at 50. */ const STANDARD_PAGE_OPERATIONS = [ @@ -798,7 +798,7 @@ export const SSMBlock: BlockConfig = { throw new Error(`Invalid Systems Manager operation: ${params.operation}`) } }, - params: (params) => { + params: (params, context) => { const result: Record = { region: params.region, accessKeyId: params.accessKeyId, @@ -822,7 +822,7 @@ export const SSMBlock: BlockConfig = { result[key] = String(value) } - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'send_command': result.documentName = params.documentName setJson('instanceIds', params.instanceIds) @@ -840,14 +840,14 @@ export const SSMBlock: BlockConfig = { case 'list_commands': setString('commandId', params.commandId) setString('instanceId', params.instanceId) - setJson('filters', params.commandFilters) + setJson('filters', params.commandFilters ?? toolCallArg(context, params.filters)) setNumber('maxResults', params.maxResults) setString('nextToken', params.nextToken) break case 'list_command_invocations': setString('commandId', params.commandId) setString('instanceId', params.instanceId) - setJson('filters', params.commandFilters) + setJson('filters', params.commandFilters ?? toolCallArg(context, params.filters)) setBoolean('details', params.details) setNumber('maxResults', params.maxResults) setString('nextToken', params.nextToken) @@ -862,35 +862,41 @@ export const SSMBlock: BlockConfig = { setJson('instanceIds', params.instanceIds) break case 'get_parameter': - result.name = params.parameterName + result.name = params.parameterName ?? toolCallArg(context, params.name) setBoolean('withDecryption', params.withDecryption) break case 'get_parameters': - setJson('names', params.parameterNames) + setJson('names', params.parameterNames ?? toolCallArg(context, params.names)) setBoolean('withDecryption', params.withDecryption) break case 'get_parameters_by_path': - result.path = params.parameterPath + result.path = params.parameterPath ?? toolCallArg(context, params.path) setBoolean('recursive', params.recursive) setBoolean('withDecryption', params.withDecryption) setJson('parameterFilters', params.parameterFilters) - setNumber('maxResults', params.pathMaxResults) + setNumber( + 'maxResults', + params.pathMaxResults ?? toolCallArg(context, params.maxResults) + ) setString('nextToken', params.nextToken) break case 'put_parameter': - result.name = params.parameterName - result.value = params.parameterValue - setString('type', params.parameterType) - setString('description', params.parameterDescription) - setString('keyId', params.kmsKeyId) + result.name = params.parameterName ?? toolCallArg(context, params.name) + result.value = params.parameterValue ?? toolCallArg(context, params.value) + setString('type', params.parameterType ?? toolCallArg(context, params.type)) + setString( + 'description', + params.parameterDescription ?? toolCallArg(context, params.description) + ) + setString('keyId', params.kmsKeyId ?? toolCallArg(context, params.keyId)) setBoolean('overwrite', params.overwrite) setString('allowedPattern', params.allowedPattern) - setString('tier', params.parameterTier) - setString('dataType', params.parameterDataType) - setString('policies', params.parameterPolicies) + setString('tier', params.parameterTier ?? toolCallArg(context, params.tier)) + setString('dataType', params.parameterDataType ?? toolCallArg(context, params.dataType)) + setString('policies', params.parameterPolicies ?? toolCallArg(context, params.policies)) break case 'delete_parameter': - result.name = params.parameterName + result.name = params.parameterName ?? toolCallArg(context, params.name) break case 'describe_parameters': setJson('parameterFilters', params.parameterFilters) @@ -899,30 +905,39 @@ export const SSMBlock: BlockConfig = { setString('nextToken', params.nextToken) break case 'describe_instance_information': - setJson('filters', params.instanceInfoFilters) - setNumber('maxResults', params.instanceInfoMaxResults) + setJson('filters', params.instanceInfoFilters ?? toolCallArg(context, params.filters)) + setNumber( + 'maxResults', + params.instanceInfoMaxResults ?? toolCallArg(context, params.maxResults) + ) setString('nextToken', params.nextToken) break case 'describe_instance_patches': result.instanceId = params.instanceId - setJson('filters', params.patchFilters) - setNumber('maxResults', params.patchMaxResults) + setJson('filters', params.patchFilters ?? toolCallArg(context, params.filters)) + setNumber( + 'maxResults', + params.patchMaxResults ?? toolCallArg(context, params.maxResults) + ) setString('nextToken', params.nextToken) break case 'describe_instance_patch_states': setJson('instanceIds', params.instanceIds) - setNumber('maxResults', params.patchMaxResults) + setNumber( + 'maxResults', + params.patchMaxResults ?? toolCallArg(context, params.maxResults) + ) setString('nextToken', params.nextToken) break case 'list_compliance_items': setJson('resourceIds', params.resourceIds) setJson('resourceTypes', params.resourceTypes) - setJson('filters', params.complianceFilters) + setJson('filters', params.complianceFilters ?? toolCallArg(context, params.filters)) setNumber('maxResults', params.maxResults) setString('nextToken', params.nextToken) break case 'list_compliance_summaries': - setJson('filters', params.complianceFilters) + setJson('filters', params.complianceFilters ?? toolCallArg(context, params.filters)) setNumber('maxResults', params.maxResults) setString('nextToken', params.nextToken) break @@ -938,7 +953,7 @@ export const SSMBlock: BlockConfig = { setString('clientToken', params.clientToken) break case 'describe_automation_executions': - setJson('filters', params.automationFilters) + setJson('filters', params.automationFilters ?? toolCallArg(context, params.filters)) setNumber('maxResults', params.maxResults) setString('nextToken', params.nextToken) break @@ -950,12 +965,12 @@ export const SSMBlock: BlockConfig = { setString('stopType', params.stopType) break case 'list_documents': - setJson('filters', params.documentFilters) + setJson('filters', params.documentFilters ?? toolCallArg(context, params.filters)) setNumber('maxResults', params.maxResults) setString('nextToken', params.nextToken) break case 'get_document': - result.name = params.documentName + result.name = params.documentName ?? toolCallArg(context, params.name) setString('documentVersion', params.documentVersion) setString('versionName', params.versionName) setString('documentFormat', params.documentFormat) diff --git a/apps/sim/blocks/blocks/stagehand.ts b/apps/sim/blocks/blocks/stagehand.ts index e4b555f8072..b7ffdbd226d 100644 --- a/apps/sim/blocks/blocks/stagehand.ts +++ b/apps/sim/blocks/blocks/stagehand.ts @@ -1,5 +1,6 @@ import { StagehandIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' +import { mapperOperation } from '@/blocks/utils' import type { StagehandAgentResponse, StagehandExtractResponse } from '@/tools/stagehand/types' export type StagehandResponse = StagehandExtractResponse | StagehandAgentResponse @@ -375,14 +376,13 @@ Example 3 (Data Collection): tool: (params) => { return params.operation === 'agent' ? 'stagehand_agent' : 'stagehand_extract' }, - params: (params) => { + params: (params, context) => { const baseParams = { - operation: params.operation, provider: params.provider, apiKey: params.apiKey, } - if (params.operation !== 'agent') { + if (mapperOperation(params, context) !== 'agent') { return { ...baseParams, url: params.url, diff --git a/apps/sim/blocks/blocks/sts.ts b/apps/sim/blocks/blocks/sts.ts index d520fbe56eb..d6f3c1437c6 100644 --- a/apps/sim/blocks/blocks/sts.ts +++ b/apps/sim/blocks/blocks/sts.ts @@ -1,7 +1,7 @@ import { STSIcon } 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' export const STSBlock: BlockConfig = { type: 'sts', @@ -296,12 +296,12 @@ export const STSBlock: BlockConfig = { throw new Error(`Invalid STS operation: ${params.operation}`) } }, - params: (params) => { - const { operation, durationSeconds, ...rest } = params + params: (params, context) => { + const { durationSeconds, ...rest } = params const result: Record = { region: rest.region } - switch (operation) { + switch (mapperOperation(params, context)) { case 'assume_role': result.accessKeyId = rest.accessKeyId result.secretAccessKey = rest.secretAccessKey diff --git a/apps/sim/blocks/blocks/supabase.ts b/apps/sim/blocks/blocks/supabase.ts index 01187471c6d..9491c0cf066 100644 --- a/apps/sim/blocks/blocks/supabase.ts +++ b/apps/sim/blocks/blocks/supabase.ts @@ -1,7 +1,7 @@ import { getErrorMessage } from '@sim/utils/errors' import { SupabaseIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' -import { normalizeFileInput, withSavedCredential } from '@/blocks/utils' +import { mapperOperation, normalizeFileInput, withSavedCredential } from '@/blocks/utils' /** Canonical basic/advanced pair for the storage upload payload. */ const FILE_DATA_FIELD = ['file', 'fileContent'] as const @@ -1178,9 +1178,9 @@ Return ONLY the PostgREST filter expression - no explanations, no markdown, no e throw new Error(`Invalid Supabase operation: ${params.operation}`) } }, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { - operation, data, filter, queryEmbedding, diff --git a/apps/sim/blocks/blocks/tailscale.test.ts b/apps/sim/blocks/blocks/tailscale.test.ts new file mode 100644 index 00000000000..c2ab64d91cf --- /dev/null +++ b/apps/sim/blocks/blocks/tailscale.test.ts @@ -0,0 +1,54 @@ +/** + * Agent tool calls pass the operation only in context and supply arguments under the tool's + * param names, so the mapper must keep them rather than overwrite them from block-only fields. + */ +import { describe, expect, it } from 'vitest' +import { TailscaleBlock } from '@/blocks/blocks/tailscale' +import { tailscaleCreateAuthKeyTool } from '@/tools/tailscale/create_auth_key' +import { tailscaleListUsersTool } from '@/tools/tailscale/list_users' +import { tailscaleSetDnsNameserversTool } from '@/tools/tailscale/set_dns_nameservers' +import type { ToolConfig } from '@/tools/types' + +const STORED = { apiKey: 'tskey-api-test', tailnet: '-' } + +function agentParams(operation: string, args: Record): Record { + const inputs = { ...STORED, ...args } + const mapped = TailscaleBlock.tools.config?.params?.(inputs, { operation }) ?? {} + return { ...inputs, ...mapped } +} + +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) +} + +function requestUrl(tool: ToolConfig, params: Record) { + const url = tool.request.url + return typeof url === 'function' ? url(params) : url +} + +describe('Tailscale block agent tool calls', () => { + it('sends the model description and expiry when creating an auth key', () => { + const params = agentParams('create_auth_key', { + description: 'ci runner', + expirySeconds: 3600, + }) + expect(requestBody(tailscaleCreateAuthKeyTool, params)).toMatchObject({ + description: 'ci runner', + expirySeconds: 3600, + }) + }) + + it('sends the model nameservers when setting DNS nameservers', () => { + const params = agentParams('set_dns_nameservers', { dns: '8.8.8.8, 1.1.1.1' }) + expect(requestBody(tailscaleSetDnsNameserversTool, params)).toEqual({ + dns: ['8.8.8.8', '1.1.1.1'], + }) + }) + + it('keeps the model role filter when listing users', () => { + const params = agentParams('list_users', { role: 'admin' }) + expect(requestUrl(tailscaleListUsersTool, params)).toContain('role=admin') + }) +}) diff --git a/apps/sim/blocks/blocks/tailscale.ts b/apps/sim/blocks/blocks/tailscale.ts index 9962aa450ab..011e1888a75 100644 --- a/apps/sim/blocks/blocks/tailscale.ts +++ b/apps/sim/blocks/blocks/tailscale.ts @@ -1,7 +1,7 @@ import { TailscaleIcon } 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' const SWITCH_DEFAULTS = { authorize_device: { authorized: true }, @@ -750,18 +750,22 @@ export const TailscaleBlock: BlockConfig = { ], config: { tool: (params) => `tailscale_${params.operation}`, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const mapped: Record = { ...params, - dns: params.dnsServers, - description: params.authKeyDescription, + dns: params.dnsServers ?? toolCallArg(context, params.dns), + description: params.authKeyDescription ?? toolCallArg(context, params.description), expirySeconds: undefined, name: params.name ?? '', - role: params.operation === 'list_users' ? params.roleFilter || undefined : params.role, + role: + operation === 'list_users' + ? params.roleFilter || toolCallArg(context, params.role) || undefined + : params.role, } const defaults = Object.entries(SWITCH_DEFAULTS).find( - ([operation]) => operation === params.operation + ([switchOperation]) => switchOperation === operation )?.[1] ?? {} for (const [field, defaultValue] of Object.entries(defaults)) { const value = params[field] @@ -776,7 +780,7 @@ export const TailscaleBlock: BlockConfig = { } } if ( - params.operation === 'create_auth_key' && + operation === 'create_auth_key' && params.expirySeconds != null && !(typeof params.expirySeconds === 'string' && params.expirySeconds.trim() === '') ) { diff --git a/apps/sim/blocks/blocks/temporal.test.ts b/apps/sim/blocks/blocks/temporal.test.ts new file mode 100644 index 00000000000..88122d8ed58 --- /dev/null +++ b/apps/sim/blocks/blocks/temporal.test.ts @@ -0,0 +1,37 @@ +/** + * Temporal block mapper on the agent tool-call path, where the operation arrives only in the + * mapper context and the merged params mix stored block fields with model args keyed by tool params. + */ +import { describe, expect, it } from 'vitest' +import { TemporalBlock } from '@/blocks/blocks/temporal' + +function params( + input: Record, + context?: { operation: string } +): Record { + return TemporalBlock.tools.config?.params?.(input as never, context) as Record +} + +describe('temporal mapper on tool calls', () => { + it('forwards a stored schedule query and keeps the model page size and token', () => { + expect( + params( + { scheduleQuery: 'TemporalScheduledById = "x"', maximumPageSize: 25, nextPageToken: 'abc' }, + { operation: 'list_schedules' } + ) + ).toMatchObject({ + query: 'TemporalScheduledById = "x"', + maximumPageSize: 25, + nextPageToken: 'abc', + }) + }) + + it('does not create a paused schedule when the model sends paused as the string "false"', () => { + expect( + params( + { scheduleId: 's', cronExpressions: '0 12 * * *', paused: 'false' }, + { operation: 'create_schedule' } + ) + ).toMatchObject({ cronExpressions: '0 12 * * *', paused: false }) + }) +}) diff --git a/apps/sim/blocks/blocks/temporal.ts b/apps/sim/blocks/blocks/temporal.ts index 5a5790c4448..c6f3ea2464b 100644 --- a/apps/sim/blocks/blocks/temporal.ts +++ b/apps/sim/blocks/blocks/temporal.ts @@ -1,6 +1,7 @@ import { TemporalIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { IntegrationType } from '@/blocks/types' +import { mapperOperation, parseOptionalBooleanInput, toolCallArg } from '@/blocks/utils' /** Coerces a subBlock value to a finite number, returning undefined for empty or non-numeric input. */ function toFiniteNumber(value: unknown): number | undefined { @@ -665,56 +666,72 @@ Return ONLY a valid JSON object - no explanations, no extra text.`, ], config: { tool: (params) => `temporal_${params.operation}`, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const result: Record = {} - if (params.operation === 'start_workflow' || params.operation === 'signal_with_start') { + if (operation === 'start_workflow' || operation === 'signal_with_start') { result.executionTimeoutSeconds = toFiniteNumber(params.executionTimeoutSeconds) result.runTimeoutSeconds = toFiniteNumber(params.runTimeoutSeconds) if (!params.workflowIdReusePolicy) result.workflowIdReusePolicy = undefined if (!params.workflowIdConflictPolicy) result.workflowIdConflictPolicy = undefined } - if (params.operation === 'list_workflows' || params.operation === 'count_workflows') { - result.query = params.listQuery || undefined + if (operation === 'list_workflows' || operation === 'count_workflows') { + result.query = params.listQuery || toolCallArg(context, params.query) || undefined } - if (params.operation === 'list_workflows') { + if (operation === 'list_workflows') { result.pageSize = toFiniteNumber(params.pageSize) } - if (params.operation === 'get_workflow_history') { - result.maximumPageSize = toFiniteNumber(params.historyPageSize) - result.nextPageToken = params.historyNextPageToken || undefined + if (operation === 'get_workflow_history') { + result.maximumPageSize = + toFiniteNumber(params.historyPageSize) ?? + toolCallArg(context, toFiniteNumber(params.maximumPageSize)) + result.nextPageToken = + params.historyNextPageToken || toolCallArg(context, params.nextPageToken) || undefined if (!params.historyEventFilterType) result.historyEventFilterType = undefined } - if (params.operation === 'reset_workflow') { + if (operation === 'reset_workflow') { result.workflowTaskFinishEventId = toFiniteNumber(params.workflowTaskFinishEventId) } - if (params.operation === 'create_schedule') { - result.cronExpressions = params.scheduleCronExpressions || undefined - result.intervalSeconds = toFiniteNumber(params.scheduleIntervalSeconds) - result.timezone = params.scheduleTimezone || undefined - result.notes = params.scheduleNotes || undefined - result.paused = params.schedulePaused === 'true' ? true : undefined + if (operation === 'create_schedule') { + result.cronExpressions = + params.scheduleCronExpressions || + toolCallArg(context, params.cronExpressions) || + undefined + result.intervalSeconds = + toFiniteNumber(params.scheduleIntervalSeconds) ?? + toolCallArg(context, toFiniteNumber(params.intervalSeconds)) + result.timezone = + params.scheduleTimezone || toolCallArg(context, params.timezone) || undefined + result.notes = params.scheduleNotes || toolCallArg(context, params.notes) || undefined + result.paused = + params.schedulePaused === 'true' + ? true + : toolCallArg(context, parseOptionalBooleanInput(params.paused)) } - if (params.operation === 'list_schedules') { - result.query = params.scheduleQuery || undefined - result.maximumPageSize = toFiniteNumber(params.schedulePageSize) - result.nextPageToken = params.scheduleNextPageToken || undefined + if (operation === 'list_schedules') { + result.query = params.scheduleQuery || toolCallArg(context, params.query) || undefined + result.maximumPageSize = + toFiniteNumber(params.schedulePageSize) ?? + toolCallArg(context, toFiniteNumber(params.maximumPageSize)) + result.nextPageToken = + params.scheduleNextPageToken || toolCallArg(context, params.nextPageToken) || undefined } if ( - (params.operation === 'trigger_schedule' || params.operation === 'create_schedule') && + (operation === 'trigger_schedule' || operation === 'create_schedule') && !params.overlapPolicy ) { result.overlapPolicy = undefined } - if (params.operation === 'describe_task_queue' && !params.taskQueueType) { + if (operation === 'describe_task_queue' && !params.taskQueueType) { result.taskQueueType = undefined } diff --git a/apps/sim/blocks/blocks/textract.test.ts b/apps/sim/blocks/blocks/textract.test.ts new file mode 100644 index 00000000000..68e3b5565d5 --- /dev/null +++ b/apps/sim/blocks/blocks/textract.test.ts @@ -0,0 +1,38 @@ +/** + * An Agent tool call runs the block mapper over `{ ...storedRowParams, ...modelArgs }` with the + * operation only in `context`; the tool then receives `{ ...merged, ...mapped }`. + */ +import { describe, expect, it } from 'vitest' +import { TextractV2Block } from '@/blocks/blocks/textract' + +const AWS = { accessKeyId: 'key', secretAccessKey: 'secret', region: 'us-east-1' } + +function toolCallParams(args: Record, operation: string) { + const mapped = TextractV2Block.tools.config?.params?.(args, { operation }) ?? {} + return { ...args, ...mapped } +} + +describe('Textract on an Agent tool call', () => { + it('sends the identity document URL stored on an Analyze ID tool row', () => { + expect( + toolCallParams({ ...AWS, document: 'https://example.com/id.png' }, 'analyze_id') + ).toMatchObject({ filePath: 'https://example.com/id.png' }) + }) + + it('keeps the feature types the model chose when it also sends queries', () => { + expect( + toolCallParams( + { + ...AWS, + document: { name: 'doc.png', key: 'k', url: 'https://example.com/doc.png' }, + featureTypes: ['FORMS'], + queries: [{ Text: 'What is the total?' }], + }, + 'analyze_document' + ) + ).toMatchObject({ + featureTypes: ['FORMS', 'QUERIES'], + queries: [{ Text: 'What is the total?' }], + }) + }) +}) diff --git a/apps/sim/blocks/blocks/textract.ts b/apps/sim/blocks/blocks/textract.ts index 9fc0c6a3ec2..707eb8c7a7b 100644 --- a/apps/sim/blocks/blocks/textract.ts +++ b/apps/sim/blocks/blocks/textract.ts @@ -5,10 +5,16 @@ import { type BlockConfig, type BlockMeta, type BlockToolParams, + type BlockToolParamsContext, IntegrationType, type SubBlockType, } from '@/blocks/types' -import { normalizeFileInput, withSavedCredential } from '@/blocks/utils' +import { + mapperOperation, + normalizeFileInput, + toolCallArg, + withSavedCredential, +} from '@/blocks/utils' const LEGACY_DOCUMENT_FIELD = ['fileUpload', 'filePath', 's3Uri'] as const const DOCUMENT_FIELD = ['fileUpload', 'fileReference', 's3Uri'] as const @@ -333,9 +339,13 @@ function requireAwsRegion(params: Record): string { * Tool params for a Textract v2+ operation. `accessKeys` is empty when a saved * AWS credential supplies them server-side. */ -function textractToolParams(params: BlockToolParams, accessKeys: Partial) { +function textractToolParams( + params: BlockToolParams, + accessKeys: Partial, + context?: BlockToolParamsContext +) { const region = requireAwsRegion(params) - const operation = params.operation || 'analyze_document' + const operation = mapperOperation(params, context) || 'analyze_document' if (operation === 'analyze_id') { const front = resolveDocumentParam(params.document) @@ -376,17 +386,23 @@ function textractToolParams(params: BlockToolParams, accessKeys: Partial( + Array.isArray(modelFeatureTypes) + ? modelFeatureTypes.filter((type): type is string => typeof type === 'string') + : [] + ) + if (params.extractTables) featureTypes.add('TABLES') + if (params.extractForms) featureTypes.add('FORMS') + if (params.detectSignatures) featureTypes.add('SIGNATURES') + if (params.analyzeLayout) featureTypes.add('LAYOUT') const queries = parseTextractQueries(params.queries) if (queries.length > 0) { - featureTypes.push('QUERIES') + featureTypes.add('QUERIES') parameters.queries = queries } - if (featureTypes.length > 0) parameters.featureTypes = featureTypes + if (featureTypes.size > 0) parameters.featureTypes = [...featureTypes] return parameters } @@ -566,7 +582,8 @@ export const TextractV2Block: BlockConfig = { if (operation === 'analyze_id') return 'textract_analyze_id' return 'textract_parser_v2' }, - params: (params) => textractToolParams(params, requireAwsAccessKeys(params)), + params: (params, context) => + textractToolParams(params, requireAwsAccessKeys(params), context), }, }, inputs: { @@ -644,7 +661,7 @@ export const TextractV3Block: BlockConfig = { ...withSavedCredential( TextractV2Block, { id: 'credential', type: 'oauth-input', serviceId: 'aws', title: 'AWS Credential' }, - { params: (params) => textractToolParams(params, {}) } + { params: (params, context) => textractToolParams(params, {}, context) } ), } diff --git a/apps/sim/blocks/blocks/tinybird.test.ts b/apps/sim/blocks/blocks/tinybird.test.ts new file mode 100644 index 00000000000..cefbad56692 --- /dev/null +++ b/apps/sim/blocks/blocks/tinybird.test.ts @@ -0,0 +1,28 @@ +/** + * An Agent tool call runs the block mapper over `{ ...storedRowParams, ...modelArgs }` with the + * operation only in `context`; the tool then receives `{ ...merged, ...mapped }`. + */ +import { describe, expect, it } from 'vitest' +import { TinybirdBlock } from '@/blocks/blocks/tinybird' + +function toolCallParams(args: Record, operation: string) { + const mapped = TinybirdBlock.tools.config?.params?.(args, { operation }) ?? {} + return { ...args, ...mapped } +} + +describe('Tinybird on an Agent tool call', () => { + it('runs the selected operation instead of requiring Send Events fields', () => { + expect(toolCallParams({ token: 'tok', query: 'SELECT 1' }, 'tinybird_query')).toMatchObject({ + query: 'SELECT 1', + }) + }) + + it('appends from the source URL the model supplied as url', () => { + expect( + toolCallParams( + { token: 'tok', datasource: 'events', url: 'https://example.com/data.csv' }, + 'tinybird_append_datasource' + ) + ).toMatchObject({ datasource: 'events', url: 'https://example.com/data.csv', format: 'csv' }) + }) +}) diff --git a/apps/sim/blocks/blocks/tinybird.ts b/apps/sim/blocks/blocks/tinybird.ts index 0beee5c963c..0e43756211a 100644 --- a/apps/sim/blocks/blocks/tinybird.ts +++ b/apps/sim/blocks/blocks/tinybird.ts @@ -1,7 +1,7 @@ import { TinybirdIcon } 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 TinybirdBlock: BlockConfig = { type: 'tinybird', @@ -247,8 +247,8 @@ export const TinybirdBlock: BlockConfig = { ], config: { tool: (params) => params.operation || 'tinybird_events', - params: (params) => { - const operation = params.operation || 'tinybird_events' + params: (params, context) => { + const operation = mapperOperation(params, context) || 'tinybird_events' const result: Record = { base_url: params.base_url, token: params.token, @@ -302,12 +302,13 @@ export const TinybirdBlock: BlockConfig = { if (!params.datasource) { throw new Error('Data Source is required for Append Data Source operation') } - if (!params.source_url) { + const sourceUrl = params.source_url || toolCallArg(context, params.url) + if (!sourceUrl) { throw new Error('Source File URL is required for Append Data Source operation') } result.datasource = params.datasource - result.url = params.source_url + result.url = sourceUrl result.format = params.source_format || 'csv' } else if (operation === 'tinybird_truncate_datasource') { // Truncate Data Source operation diff --git a/apps/sim/blocks/blocks/tinyfish.ts b/apps/sim/blocks/blocks/tinyfish.ts index 45dd058a02b..41cfa4139a6 100644 --- a/apps/sim/blocks/blocks/tinyfish.ts +++ b/apps/sim/blocks/blocks/tinyfish.ts @@ -1,6 +1,7 @@ import { TinyFishIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { isToolCall, mapperOperation } from '@/blocks/utils' /** Operations that build and submit an automation run. */ const AUTOMATION_OPERATIONS = ['tinyfish_run', 'tinyfish_run_async'] @@ -497,7 +498,7 @@ Return ONLY the comma-separated URL list - no explanations, no extra text.`, return 'tinyfish_run' } }, - params: (params) => { + params: (params, context) => { const result: Record = {} /** @@ -528,10 +529,10 @@ Return ONLY the comma-separated URL list - no explanations, no extra text.`, /** * The list filter has its own sub-block id so it does not collide with * the automation goal, and is renamed here to the `goal` query the tool - * sends. + * sends. A tool call's model arg arrives as `goal` already. */ - if (params.operation === 'tinyfish_list_runs') { - result.goal = params.goalFilter + if (mapperOperation(params, context) === 'tinyfish_list_runs') { + result.goal = isToolCall(context) ? params.goalFilter || params.goal : params.goalFilter } return result diff --git a/apps/sim/blocks/blocks/trigger_dev.test.ts b/apps/sim/blocks/blocks/trigger_dev.test.ts new file mode 100644 index 00000000000..9bc985ff6ea --- /dev/null +++ b/apps/sim/blocks/blocks/trigger_dev.test.ts @@ -0,0 +1,28 @@ +/** + * An Agent tool call runs the block mapper over `{ ...storedRowParams, ...modelArgs }` with the + * operation only in `context`; the tool then receives `{ ...merged, ...mapped }`. + */ +import { describe, expect, it } from 'vitest' +import { TriggerDevBlock } from '@/blocks/blocks/trigger_dev' + +function toolCallParams(args: Record, operation: string) { + const mapped = TriggerDevBlock.tools.config?.params?.(args, { operation }) ?? {} + return { ...args, ...mapped } +} + +describe('Trigger.dev on an Agent tool call', () => { + it('keeps the filters the model supplied under the tool param names', () => { + expect( + toolCallParams( + { apiKey: 'tr_dev_x', taskIdentifier: 'send-email', status: 'COMPLETED', pageSize: 10 }, + 'trigger_dev_list_runs' + ) + ).toMatchObject({ taskIdentifier: 'send-email', status: 'COMPLETED', pageSize: 10 }) + }) + + it('keeps the deployment status filter the model supplied', () => { + expect( + toolCallParams({ apiKey: 'tr_dev_x', status: 'DEPLOYED' }, 'trigger_dev_list_deployments') + ).toMatchObject({ status: 'DEPLOYED' }) + }) +}) diff --git a/apps/sim/blocks/blocks/trigger_dev.ts b/apps/sim/blocks/blocks/trigger_dev.ts index c2ccb3ebe3e..c7542f11f3c 100644 --- a/apps/sim/blocks/blocks/trigger_dev.ts +++ b/apps/sim/blocks/blocks/trigger_dev.ts @@ -1,7 +1,8 @@ +import { filterUndefined } from '@sim/utils/object' import { TriggerDevIcon } 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' const TASK_IDENTIFIER_OPERATIONS = ['trigger_dev_trigger_task', 'trigger_dev_batch_trigger_task'] const RUN_ID_OPERATIONS = [ @@ -965,8 +966,8 @@ Return ONLY the valid JSON object - no explanations, no markdown.`, ], config: { tool: (params) => params.operation, - params: (params) => { - const operation = params.operation as string + params: (params, context) => { + const operation = mapperOperation(params, context) const result: Record = {} const scoped = (value: unknown, operations: string[]) => @@ -1012,7 +1013,12 @@ Return ONLY the valid JSON object - no explanations, no markdown.`, result.page = scopedNumber(params.page, NUMBERED_PAGE_OPERATIONS) result.perPage = scopedNumber(params.perPage, NUMBERED_PAGE_OPERATIONS) - return result + /** + * The canvas blanks every key the operation does not use, so a value saved under another + * operation never leaks into the request. On a tool call the result is spread over the + * model's args, so an unset key is dropped instead of wiping the model's value. + */ + return isToolCall(context) ? filterUndefined(result) : result }, }, }, diff --git a/apps/sim/blocks/blocks/vercel.test.ts b/apps/sim/blocks/blocks/vercel.test.ts new file mode 100644 index 00000000000..9652da687eb --- /dev/null +++ b/apps/sim/blocks/blocks/vercel.test.ts @@ -0,0 +1,52 @@ +/** + * An Agent tool call runs the block mapper over `{ ...storedRowParams, ...modelArgs }` with the + * operation only in `context`; the tool then receives `{ ...merged, ...mapped }`. + */ +import { describe, expect, it } from 'vitest' +import { VercelBlock } from '@/blocks/blocks/vercel' + +function toolCallParams(args: Record, operation: string) { + const mapped = VercelBlock.tools.config?.params?.(args, { operation }) ?? {} + return { ...args, ...mapped } +} + +describe('Vercel on an Agent tool call', () => { + it('keeps the domain the model supplied', () => { + expect( + toolCallParams({ apiKey: 'tok', domain: 'example.com' }, 'list_dns_records') + ).toMatchObject({ domain: 'example.com' }) + }) + + it('sends Create Check blocking as a boolean', () => { + expect( + toolCallParams( + { apiKey: 'tok', deploymentId: 'dpl_1', name: 'e2e', blocking: 'true' }, + 'create_check' + ) + ).toMatchObject({ blocking: true }) + expect( + toolCallParams({ apiKey: 'tok', deploymentId: 'dpl_1', name: 'e2e' }, 'create_check') + ).toMatchObject({ blocking: false }) + }) + + it('keeps the args the model supplied under the tool param names', () => { + expect( + toolCallParams( + { apiKey: 'tok', deploymentId: 'dpl_1', name: 'e2e', blocking: true }, + 'create_check' + ) + ).toMatchObject({ deploymentId: 'dpl_1', name: 'e2e', blocking: true }) + expect( + toolCallParams({ apiKey: 'tok', recordId: 'rec_1', name: 'api' }, 'update_dns_record') + ).toMatchObject({ recordId: 'rec_1', name: 'api' }) + }) + + it('maps block field names on a tool row written by Copilot or the API', () => { + expect( + toolCallParams( + { apiKey: 'tok', recordId: 'rec_1', updateRecordName: 'www', updateSrvPort: '5060' }, + 'update_dns_record' + ) + ).toMatchObject({ recordId: 'rec_1', name: 'www', srvPort: 5060 }) + }) +}) diff --git a/apps/sim/blocks/blocks/vercel.ts b/apps/sim/blocks/blocks/vercel.ts index 964b3e1fd6e..3081a91bb16 100644 --- a/apps/sim/blocks/blocks/vercel.ts +++ b/apps/sim/blocks/blocks/vercel.ts @@ -1,7 +1,12 @@ import { VercelIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { + isToolCall, + mapperOperation, + parseOptionalBooleanInput, + withSavedCredential, +} from '@/blocks/utils' import { getTrigger } from '@/triggers' /** @@ -1634,10 +1639,9 @@ export const VercelBlock: BlockConfig = { ], config: { tool: (params) => `vercel_${params.operation}`, - params: (params) => { + params: (params, context) => { const { apiKey, - operation, deploymentsProjectId, deploymentsApp, deploymentsSince, @@ -1734,11 +1738,20 @@ export const VercelBlock: BlockConfig = { const base = { ...rest, apiKey, ...(teamSlug ? { slug: teamSlug } : {}) } - switch (operation) { + /** + * On a tool call the model sends the tool's own param name, so it fills a blank dedicated + * field. The canvas keeps the dedicated field as is. + */ + const orModelArg = (dedicated: unknown, modelArg: unknown) => + isToolCall(context) && (dedicated === undefined || dedicated === null || dedicated === '') + ? modelArg + : dedicated + + switch (mapperOperation(params, context)) { case 'list_deployments': return { ...base, - projectId: deploymentsProjectId || undefined, + projectId: orModelArg(deploymentsProjectId, rest.projectId) || undefined, ...(deploymentsApp ? { app: deploymentsApp } : {}), ...(deploymentsSince ? { since: Number(deploymentsSince) } : {}), ...(deploymentsUntil ? { until: Number(deploymentsUntil) } : {}), @@ -1758,21 +1771,21 @@ export const VercelBlock: BlockConfig = { case 'create_deployment': return { ...base, - deploymentId: redeployId || undefined, - target: deployTarget || undefined, + deploymentId: orModelArg(redeployId, rest.deploymentId) || undefined, + target: orModelArg(deployTarget, rest.target) || undefined, ...(deploymentGitSource ? { gitSource: deploymentGitSource } : {}), ...(deploymentForceNew ? { forceNew: deploymentForceNew } : {}), } case 'create_project': - return { ...base, name: projectName } + return { ...base, name: orModelArg(projectName, rest.name) } case 'update_project': - return { ...base, name: updateProjectName || undefined } + return { ...base, name: orModelArg(updateProjectName, rest.name) || undefined } case 'list_projects': return { ...base, ...(projectsFrom ? { from: projectsFrom } : {}) } case 'add_project_domain': return { ...base, - domain: domainName, + domain: orModelArg(domainName, rest.domain), ...(updateDomainRedirect ? { redirect: updateDomainRedirect } : {}), ...(updateDomainRedirectStatusCode ? { redirectStatusCode: Number(updateDomainRedirectStatusCode) } @@ -1781,11 +1794,11 @@ export const VercelBlock: BlockConfig = { } case 'remove_project_domain': case 'verify_project_domain': - return { ...base, domain: domainName } + return { ...base, domain: orModelArg(domainName, rest.domain) } case 'update_project_domain': return { ...base, - domain: domainName, + domain: orModelArg(domainName, rest.domain), ...(updateDomainRedirect ? { redirect: updateDomainRedirect } : {}), ...(updateDomainRedirectStatusCode ? { redirectStatusCode: Number(updateDomainRedirectStatusCode) } @@ -1795,13 +1808,13 @@ export const VercelBlock: BlockConfig = { case 'get_domain': case 'delete_domain': case 'get_domain_config': - return { ...base, domain: domainName } + return { ...base, domain: orModelArg(domainName, rest.domain) } case 'add_domain': - return { ...base, name: domainName } + return { ...base, name: orModelArg(domainName, rest.name) } case 'list_dns_records': return { ...base, - domain: domainName, + domain: orModelArg(domainName, rest.domain), ...(dnsRecordsLimit ? { limit: Number(dnsRecordsLimit) } : {}), } case 'list_project_domains': @@ -1812,7 +1825,7 @@ export const VercelBlock: BlockConfig = { case 'create_dns_record': return { ...base, - domain: domainName, + domain: orModelArg(domainName, rest.domain), recordName, recordType, ...(recordValue ? { value: recordValue } : {}), @@ -1833,12 +1846,12 @@ export const VercelBlock: BlockConfig = { ...(recordComment ? { comment: recordComment } : {}), } case 'delete_dns_record': - return { ...base, domain: domainName, recordId } + return { ...base, domain: orModelArg(domainName, rest.domain), recordId } case 'update_dns_record': return { ...base, recordId, - name: updateRecordName || undefined, + name: orModelArg(updateRecordName, rest.name) || undefined, ...(updateRecordType ? { type: updateRecordType } : {}), ...(updateRecordValue ? { value: updateRecordValue } : {}), ...(updateRecordTtl ? { ttl: updateRecordTtl } : {}), @@ -1871,10 +1884,10 @@ export const VercelBlock: BlockConfig = { case 'create_env_var': return { ...base, - key: envKey, - value: envValue, - target: envTarget, - type: envType, + key: orModelArg(envKey, rest.key), + value: orModelArg(envValue, rest.value), + target: orModelArg(envTarget, rest.target), + type: orModelArg(envType, rest.type), ...(envGitBranch ? { gitBranch: envGitBranch } : {}), ...(envComment ? { comment: envComment } : {}), } @@ -1883,7 +1896,7 @@ export const VercelBlock: BlockConfig = { ...base, ...(envKey ? { key: envKey } : {}), ...(envValue ? { value: envValue } : {}), - target: envTarget || undefined, + target: orModelArg(envTarget, rest.target) || undefined, ...(envType ? { type: envType } : {}), ...(envGitBranch ? { gitBranch: envGitBranch } : {}), ...(envComment ? { comment: envComment } : {}), @@ -1894,8 +1907,8 @@ export const VercelBlock: BlockConfig = { case 'create_alias': return { ...base, - deploymentId: aliasDeploymentId, - alias: aliasName, + deploymentId: orModelArg(aliasDeploymentId, rest.deploymentId), + alias: orModelArg(aliasName, rest.alias), ...(aliasRedirect ? { redirect: aliasRedirect } : {}), } case 'get_edge_config': @@ -1903,14 +1916,14 @@ export const VercelBlock: BlockConfig = { case 'delete_edge_config': return { ...base, edgeConfigId } case 'create_edge_config': - return { ...base, slug: edgeConfigSlug } + return { ...base, slug: orModelArg(edgeConfigSlug, rest.slug) } case 'update_edge_config_items': - return { ...base, edgeConfigId, items: edgeConfigItems } + return { ...base, edgeConfigId, items: orModelArg(edgeConfigItems, rest.items) } case 'create_webhook': return { ...base, - url: webhookUrl, - events: webhookEvents, + url: orModelArg(webhookUrl, rest.url), + events: orModelArg(webhookEvents, rest.events), ...(webhookProjectIds ? { projectIds: webhookProjectIds } : {}), } case 'delete_webhook': @@ -1919,31 +1932,38 @@ export const VercelBlock: BlockConfig = { case 'create_check': return { ...base, - deploymentId: checkDeploymentId, - name: checkName, - blocking: checkBlocking === 'true', + deploymentId: orModelArg(checkDeploymentId, rest.deploymentId), + name: orModelArg(checkName, rest.name), + blocking: + isToolCall(context) && !checkBlocking + ? (parseOptionalBooleanInput(rest.blocking) ?? false) + : checkBlocking === 'true', ...(checkPath ? { path: checkPath } : {}), ...(checkDetailsUrl ? { detailsUrl: checkDetailsUrl } : {}), ...(checkExternalId ? { externalId: checkExternalId } : {}), ...(checkRerequestable ? { rerequestable: checkRerequestable === 'true' } : {}), } case 'get_check': - return { ...base, deploymentId: checkDeploymentId, checkId } + return { + ...base, + deploymentId: orModelArg(checkDeploymentId, rest.deploymentId), + checkId, + } case 'rerequest_check': return { ...base, - deploymentId: checkDeploymentId, + deploymentId: orModelArg(checkDeploymentId, rest.deploymentId), checkId, ...(checkAutoUpdate ? { autoUpdate: checkAutoUpdate === 'true' } : {}), } case 'list_checks': - return { ...base, deploymentId: checkDeploymentId } + return { ...base, deploymentId: orModelArg(checkDeploymentId, rest.deploymentId) } case 'update_check': return { ...base, - deploymentId: checkDeploymentId, + deploymentId: orModelArg(checkDeploymentId, rest.deploymentId), checkId, - name: checkName || undefined, + name: orModelArg(checkName, rest.name) || undefined, ...(checkStatus ? { status: checkStatus } : {}), ...(checkConclusion ? { conclusion: checkConclusion } : {}), ...(checkPath ? { path: checkPath } : {}), @@ -1952,16 +1972,16 @@ export const VercelBlock: BlockConfig = { ...(checkOutput ? { output: checkOutput } : {}), } case 'get_team': - return { ...base, teamId: teamIdParam } + return { ...base, teamId: orModelArg(teamIdParam, rest.teamId) } case 'list_team_members': return { ...base, - teamId: teamIdParam, + teamId: orModelArg(teamIdParam, rest.teamId), ...(memberRole ? { role: memberRole } : {}), ...(teamMembersLimit ? { limit: Number(teamMembersLimit) } : {}), ...(teamMembersSince ? { since: Number(teamMembersSince) } : {}), ...(teamMembersUntil ? { until: Number(teamMembersUntil) } : {}), - search: teamMembersSearch || undefined, + search: orModelArg(teamMembersSearch, rest.search) || undefined, } case 'list_teams': return { diff --git a/apps/sim/tools/tinyfish/tinyfish.test.ts b/apps/sim/tools/tinyfish/tinyfish.test.ts index 66290a087f9..e93b0b135f6 100644 --- a/apps/sim/tools/tinyfish/tinyfish.test.ts +++ b/apps/sim/tools/tinyfish/tinyfish.test.ts @@ -775,6 +775,12 @@ describe('TinyFish block', () => { expect(params).toMatchObject({ goal: 'pricing' }) }) + it('keeps the goal filter the model supplied on an Agent tool call', () => { + const args = { apiKey: API_KEY, goal: 'checkout' } + const mapped = TinyFishBlock.tools.config?.params?.(args, { operation: 'tinyfish_list_runs' }) + expect({ ...args, ...mapped }).toMatchObject({ goal: 'checkout' }) + }) + it('leaves the automation goal alone on a run operation', () => { const params = TinyFishBlock.tools.config?.params?.({ operation: 'tinyfish_run', From ab98fd20e3b99761d819efc05c3f34487366f151 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 15 Nov 2026 16:48:06 -0800 Subject: [PATCH 2/4] chore: regenerate tool metadata, docs and ratchet baselines --- scripts/check-mapper-operation.baseline.json | 45 -------------------- 1 file changed, 45 deletions(-) diff --git a/scripts/check-mapper-operation.baseline.json b/scripts/check-mapper-operation.baseline.json index 13228879bf4..7632400c719 100644 --- a/scripts/check-mapper-operation.baseline.json +++ b/scripts/check-mapper-operation.baseline.json @@ -6,8 +6,6 @@ "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/athena.ts": 1, - "apps/sim/blocks/blocks/azure_data_explorer.ts": 1, "apps/sim/blocks/blocks/azure_devops.ts": 1, "apps/sim/blocks/blocks/bitbucket.ts": 3, "apps/sim/blocks/blocks/brex.ts": 1, @@ -18,26 +16,16 @@ "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/cloudflare.ts": 3, - "apps/sim/blocks/blocks/cloudformation.ts": 1, - "apps/sim/blocks/blocks/cloudtrail.ts": 1, - "apps/sim/blocks/blocks/cloudwatch.ts": 1, "apps/sim/blocks/blocks/coda.ts": 1, - "apps/sim/blocks/blocks/codepipeline.ts": 1, "apps/sim/blocks/blocks/confluence.ts": 2, "apps/sim/blocks/blocks/context_dev.ts": 1, - "apps/sim/blocks/blocks/crowdstrike.ts": 2, "apps/sim/blocks/blocks/crunchbase.ts": 1, - "apps/sim/blocks/blocks/dagster.ts": 8, "apps/sim/blocks/blocks/datadog.ts": 1, - "apps/sim/blocks/blocks/daytona.ts": 1, "apps/sim/blocks/blocks/deployments.ts": 1, "apps/sim/blocks/blocks/discord.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/dynamodb.ts": 1, - "apps/sim/blocks/blocks/dynatrace.ts": 1, "apps/sim/blocks/blocks/elevenlabs.ts": 2, "apps/sim/blocks/blocks/emailbison.ts": 6, "apps/sim/blocks/blocks/enrich.ts": 1, @@ -46,14 +34,12 @@ "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/fivetran.ts": 17, "apps/sim/blocks/blocks/flint.ts": 1, "apps/sim/blocks/blocks/github.ts": 2, "apps/sim/blocks/blocks/gitlab.ts": 2, "apps/sim/blocks/blocks/gmail.ts": 4, "apps/sim/blocks/blocks/gong.ts": 1, "apps/sim/blocks/blocks/google_appsheet.ts": 1, - "apps/sim/blocks/blocks/google_bigquery.ts": 1, "apps/sim/blocks/blocks/google_calendar.ts": 1, "apps/sim/blocks/blocks/google_drive.ts": 22, "apps/sim/blocks/blocks/google_forms.ts": 1, @@ -62,34 +48,26 @@ "apps/sim/blocks/blocks/google_sheets.ts": 1, "apps/sim/blocks/blocks/google_slides.ts": 50, "apps/sim/blocks/blocks/google_vault.ts": 5, - "apps/sim/blocks/blocks/grafana.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/iam.ts": 1, - "apps/sim/blocks/blocks/identity_center.ts": 1, "apps/sim/blocks/blocks/incidentio.ts": 9, - "apps/sim/blocks/blocks/infisical.ts": 1, "apps/sim/blocks/blocks/instagram.ts": 2, "apps/sim/blocks/blocks/instantly.ts": 17, "apps/sim/blocks/blocks/jira.ts": 1, "apps/sim/blocks/blocks/jira_service_management.ts": 1, "apps/sim/blocks/blocks/jotform.ts": 1, - "apps/sim/blocks/blocks/jupyter.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/lambda.ts": 2, "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/linear.ts": 1, "apps/sim/blocks/blocks/linkedin.ts": 1, "apps/sim/blocks/blocks/linq.ts": 2, - "apps/sim/blocks/blocks/logfire.ts": 1, - "apps/sim/blocks/blocks/logrocket.ts": 1, "apps/sim/blocks/blocks/logs.ts": 2, "apps/sim/blocks/blocks/loops.ts": 1, "apps/sim/blocks/blocks/mailgun.ts": 1, @@ -104,9 +82,7 @@ "apps/sim/blocks/blocks/microsoft_teams.ts": 1, "apps/sim/blocks/blocks/microsoft_word.ts": 1, "apps/sim/blocks/blocks/mintlify.ts": 1, - "apps/sim/blocks/blocks/modal.ts": 1, "apps/sim/blocks/blocks/netsuite.ts": 2, - "apps/sim/blocks/blocks/new_relic.ts": 1, "apps/sim/blocks/blocks/okta.ts": 2, "apps/sim/blocks/blocks/onedrive.ts": 3, "apps/sim/blocks/blocks/otter.ts": 1, @@ -118,52 +94,31 @@ "apps/sim/blocks/blocks/persona.ts": 1, "apps/sim/blocks/blocks/pitchbook.ts": 1, "apps/sim/blocks/blocks/plane.ts": 1, - "apps/sim/blocks/blocks/planetscale.ts": 2, "apps/sim/blocks/blocks/polymarket.ts": 1, "apps/sim/blocks/blocks/powerbi.ts": 1, "apps/sim/blocks/blocks/profound.ts": 1, - "apps/sim/blocks/blocks/railway.ts": 1, - "apps/sim/blocks/blocks/rds.ts": 1, "apps/sim/blocks/blocks/reddit.ts": 1, "apps/sim/blocks/blocks/revenuecat.ts": 2, "apps/sim/blocks/blocks/rippling.ts": 1, "apps/sim/blocks/blocks/rocketlane.ts": 1, "apps/sim/blocks/blocks/rootly.ts": 1, - "apps/sim/blocks/blocks/s3.ts": 1, "apps/sim/blocks/blocks/sailpoint.ts": 1, - "apps/sim/blocks/blocks/secrets_manager.ts": 1, "apps/sim/blocks/blocks/sendblue.ts": 1, "apps/sim/blocks/blocks/sendgrid.ts": 1, - "apps/sim/blocks/blocks/ses.ts": 1, - "apps/sim/blocks/blocks/sftp.ts": 1, "apps/sim/blocks/blocks/sharepoint.ts": 6, "apps/sim/blocks/blocks/shopify.ts": 1, "apps/sim/blocks/blocks/sixtyfour.ts": 4, "apps/sim/blocks/blocks/slack.ts": 6, "apps/sim/blocks/blocks/smartlead.ts": 5, "apps/sim/blocks/blocks/snowflake.ts": 1, - "apps/sim/blocks/blocks/splunk.ts": 1, - "apps/sim/blocks/blocks/sqs.ts": 1, - "apps/sim/blocks/blocks/ssh.ts": 1, - "apps/sim/blocks/blocks/ssm.ts": 1, - "apps/sim/blocks/blocks/stagehand.ts": 2, "apps/sim/blocks/blocks/stripe.ts": 1, - "apps/sim/blocks/blocks/sts.ts": 1, - "apps/sim/blocks/blocks/supabase.ts": 1, "apps/sim/blocks/blocks/table.ts": 1, "apps/sim/blocks/blocks/table_v2.ts": 1, - "apps/sim/blocks/blocks/tailscale.ts": 3, "apps/sim/blocks/blocks/telegram.ts": 1, - "apps/sim/blocks/blocks/temporal.ts": 12, - "apps/sim/blocks/blocks/textract.ts": 1, "apps/sim/blocks/blocks/tiktok.ts": 1, - "apps/sim/blocks/blocks/tinybird.ts": 1, - "apps/sim/blocks/blocks/tinyfish.ts": 1, "apps/sim/blocks/blocks/trello.ts": 1, - "apps/sim/blocks/blocks/trigger_dev.ts": 1, "apps/sim/blocks/blocks/twilio_voice.ts": 1, "apps/sim/blocks/blocks/vanta.ts": 1, - "apps/sim/blocks/blocks/vercel.ts": 1, "apps/sim/blocks/blocks/wealthbox.ts": 1, "apps/sim/blocks/blocks/webflow.ts": 4, "apps/sim/blocks/blocks/whatsapp.ts": 1, From 494cb8a7a61e5656e876901bc3b81b527b89a507 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 15 Nov 2026 17:01:21 -0800 Subject: [PATCH 3/4] refactor: simplify and clean up the sweep changes --- apps/sim/blocks/blocks/cloudflare.ts | 2 +- apps/sim/blocks/blocks/cloudtrail.ts | 107 ++++++++++++------------ apps/sim/blocks/blocks/daytona.ts | 2 +- apps/sim/blocks/blocks/fivetran.ts | 2 +- apps/sim/blocks/blocks/sqs.ts | 113 +++++++++++++------------- apps/sim/blocks/blocks/trigger_dev.ts | 7 +- 6 files changed, 114 insertions(+), 119 deletions(-) diff --git a/apps/sim/blocks/blocks/cloudflare.ts b/apps/sim/blocks/blocks/cloudflare.ts index f2bbe0ba8c4..fe3a894c7df 100644 --- a/apps/sim/blocks/blocks/cloudflare.ts +++ b/apps/sim/blocks/blocks/cloudflare.ts @@ -4523,7 +4523,7 @@ export const CloudflareBlock: BlockConfig = { tool: (params) => `cloudflare_${params.operation}`, params: (params, context) => { const result = { ...params } - const operation = mapperOperation(params, context) ?? '' + const operation = mapperOperation(params, context) const toolCall = isToolCall(context) for (const [toolParam, aliasId] of Object.entries(SUBBLOCK_ALIASES[operation] ?? {})) { const aliasValue = result[aliasId] diff --git a/apps/sim/blocks/blocks/cloudtrail.ts b/apps/sim/blocks/blocks/cloudtrail.ts index 7ea4372fef2..03be182c6dd 100644 --- a/apps/sim/blocks/blocks/cloudtrail.ts +++ b/apps/sim/blocks/blocks/cloudtrail.ts @@ -428,47 +428,46 @@ Return ONLY the SQL query — no explanations, no markdown code blocks.`, } }, params: (params, context) => { - const rest = params const operation = mapperOperation(params, context) - const awsRegion = rest.awsRegion - const awsAccessKeyId = rest.awsAccessKeyId - const awsSecretAccessKey = rest.awsSecretAccessKey + const awsRegion = params.awsRegion + const awsAccessKeyId = params.awsAccessKeyId + const awsSecretAccessKey = params.awsSecretAccessKey const credentials = { awsRegion, awsAccessKeyId, awsSecretAccessKey } switch (operation) { case 'lookup_events': { - const maxResults = parseBoundedInt(rest.lookupMaxResults) - if (Boolean(rest.attributeKey) !== Boolean(rest.attributeValue)) { + const maxResults = parseBoundedInt(params.lookupMaxResults) + if (Boolean(params.attributeKey) !== Boolean(params.attributeValue)) { throw new Error('Provide both a filter attribute and a filter value, or neither') } return { ...credentials, - ...(rest.attributeKey && { - attributeKey: rest.attributeKey, - attributeValue: rest.attributeValue, + ...(params.attributeKey && { + attributeKey: params.attributeKey, + attributeValue: params.attributeValue, }), - ...(rest.startTime && { startTime: rest.startTime }), - ...(rest.endTime && { endTime: rest.endTime }), - ...(rest.eventCategory === 'insight' && { eventCategory: 'insight' }), + ...(params.startTime && { startTime: params.startTime }), + ...(params.endTime && { endTime: params.endTime }), + ...(params.eventCategory === 'insight' && { eventCategory: 'insight' }), ...(maxResults !== undefined && { maxResults }), - ...(rest.nextToken && { nextToken: rest.nextToken }), + ...(params.nextToken && { nextToken: params.nextToken }), } } case 'describe_trails': return { ...credentials, - ...(rest.trailNameList && { trailNameList: rest.trailNameList }), - ...(rest.includeShadowTrails !== undefined && - rest.includeShadowTrails !== '' && { - includeShadowTrails: String(rest.includeShadowTrails) !== 'false', + ...(params.trailNameList && { trailNameList: params.trailNameList }), + ...(params.includeShadowTrails !== undefined && + params.includeShadowTrails !== '' && { + includeShadowTrails: String(params.includeShadowTrails) !== 'false', }), } case 'get_trail': case 'get_trail_status': { - const name = rest.trailName || toolCallArg(context, rest.name) + const name = params.trailName || toolCallArg(context, params.name) if (!name) { throw new Error('Trail name or ARN is required') } @@ -478,107 +477,107 @@ Return ONLY the SQL query — no explanations, no markdown code blocks.`, case 'list_trails': return { ...credentials, - ...(rest.nextToken && { nextToken: rest.nextToken }), + ...(params.nextToken && { nextToken: params.nextToken }), } case 'get_event_selectors': - if (!rest.trailName) { + if (!params.trailName) { throw new Error('Trail name or ARN is required') } - return { ...credentials, trailName: rest.trailName } + return { ...credentials, trailName: params.trailName } case 'get_insight_selectors': - if (Boolean(rest.trailName) === Boolean(rest.eventDataStore)) { + if (Boolean(params.trailName) === Boolean(params.eventDataStore)) { throw new Error( 'Specify exactly one of trail name or event data store for Insights selectors' ) } return { ...credentials, - ...(rest.trailName && { trailName: rest.trailName }), - ...(rest.eventDataStore && { eventDataStore: rest.eventDataStore }), + ...(params.trailName && { trailName: params.trailName }), + ...(params.eventDataStore && { eventDataStore: params.eventDataStore }), } case 'start_query': - if (Boolean(rest.queryStatement) === Boolean(rest.queryAlias)) { + if (Boolean(params.queryStatement) === Boolean(params.queryAlias)) { throw new Error('Specify exactly one of Lake SQL query or query template alias') } return { ...credentials, - ...(rest.queryStatement && { queryStatement: rest.queryStatement }), - ...(rest.queryAlias && { queryAlias: rest.queryAlias }), - ...(rest.queryParameters && { queryParameters: rest.queryParameters }), - ...(rest.deliveryS3Uri && { deliveryS3Uri: rest.deliveryS3Uri }), - ...(rest.eventDataStoreOwnerAccountId && { - eventDataStoreOwnerAccountId: rest.eventDataStoreOwnerAccountId, + ...(params.queryStatement && { queryStatement: params.queryStatement }), + ...(params.queryAlias && { queryAlias: params.queryAlias }), + ...(params.queryParameters && { queryParameters: params.queryParameters }), + ...(params.deliveryS3Uri && { deliveryS3Uri: params.deliveryS3Uri }), + ...(params.eventDataStoreOwnerAccountId && { + eventDataStoreOwnerAccountId: params.eventDataStoreOwnerAccountId, }), } case 'describe_query': - if (Boolean(rest.queryId) === Boolean(rest.queryAlias)) { + if (Boolean(params.queryId) === Boolean(params.queryAlias)) { throw new Error('Specify exactly one of query ID or query template alias') } return { ...credentials, - ...(rest.queryId && { queryId: rest.queryId }), - ...(rest.queryAlias && { queryAlias: rest.queryAlias }), - ...(rest.refreshId && { refreshId: rest.refreshId }), - ...(rest.eventDataStoreOwnerAccountId && { - eventDataStoreOwnerAccountId: rest.eventDataStoreOwnerAccountId, + ...(params.queryId && { queryId: params.queryId }), + ...(params.queryAlias && { queryAlias: params.queryAlias }), + ...(params.refreshId && { refreshId: params.refreshId }), + ...(params.eventDataStoreOwnerAccountId && { + eventDataStoreOwnerAccountId: params.eventDataStoreOwnerAccountId, }), } case 'get_query_results': { - if (!rest.queryId) { + if (!params.queryId) { throw new Error('Query ID is required') } - const maxQueryResults = parseBoundedInt(rest.maxQueryResults) + const maxQueryResults = parseBoundedInt(params.maxQueryResults) return { ...credentials, - queryId: rest.queryId, + queryId: params.queryId, ...(maxQueryResults !== undefined && { maxQueryResults }), - ...(rest.nextToken && { nextToken: rest.nextToken }), - ...(rest.eventDataStoreOwnerAccountId && { - eventDataStoreOwnerAccountId: rest.eventDataStoreOwnerAccountId, + ...(params.nextToken && { nextToken: params.nextToken }), + ...(params.eventDataStoreOwnerAccountId && { + eventDataStoreOwnerAccountId: params.eventDataStoreOwnerAccountId, }), } } case 'cancel_query': - if (!rest.queryId) { + if (!params.queryId) { throw new Error('Query ID is required') } return { ...credentials, - queryId: rest.queryId, - ...(rest.eventDataStoreOwnerAccountId && { - eventDataStoreOwnerAccountId: rest.eventDataStoreOwnerAccountId, + queryId: params.queryId, + ...(params.eventDataStoreOwnerAccountId && { + eventDataStoreOwnerAccountId: params.eventDataStoreOwnerAccountId, }), } case 'list_event_data_stores': { - const maxResults = parseBoundedInt(rest.eventDataStoreMaxResults) + const maxResults = parseBoundedInt(params.eventDataStoreMaxResults) return { ...credentials, ...(maxResults !== undefined && { maxResults }), - ...(rest.nextToken && { nextToken: rest.nextToken }), + ...(params.nextToken && { nextToken: params.nextToken }), } } case 'get_event_data_store': - if (!rest.eventDataStore) { + if (!params.eventDataStore) { throw new Error('Event data store ARN or ID is required') } - return { ...credentials, eventDataStore: rest.eventDataStore } + return { ...credentials, eventDataStore: params.eventDataStore } case 'list_tags': - if (!rest.resourceIdList) { + if (!params.resourceIdList) { throw new Error('At least one resource ARN is required') } return { ...credentials, - resourceIdList: rest.resourceIdList, - ...(rest.nextToken && { nextToken: rest.nextToken }), + resourceIdList: params.resourceIdList, + ...(params.nextToken && { nextToken: params.nextToken }), } default: diff --git a/apps/sim/blocks/blocks/daytona.ts b/apps/sim/blocks/blocks/daytona.ts index 244a47ce9f2..b75d0c6dca3 100644 --- a/apps/sim/blocks/blocks/daytona.ts +++ b/apps/sim/blocks/blocks/daytona.ts @@ -463,7 +463,7 @@ export const DaytonaBlock: BlockConfig = { const baseParams: Record = { apiKey } - if (operation && SANDBOX_SCOPED_OPERATIONS.includes(operation)) { + if (SANDBOX_SCOPED_OPERATIONS.includes(operation)) { baseParams.sandboxId = rest.sandboxId } diff --git a/apps/sim/blocks/blocks/fivetran.ts b/apps/sim/blocks/blocks/fivetran.ts index ec6e82a1ff5..8eb1d6833a9 100644 --- a/apps/sim/blocks/blocks/fivetran.ts +++ b/apps/sim/blocks/blocks/fivetran.ts @@ -1061,7 +1061,7 @@ export const FivetranBlock: BlockConfig = { }, params: (params, context) => { const result: Record = {} - const operation = mapperOperation(params, context) ?? '' + const operation = mapperOperation(params, context) const isConnectionSettings = (CONNECTION_SETTINGS_OPS as readonly string[]).includes( operation ) diff --git a/apps/sim/blocks/blocks/sqs.ts b/apps/sim/blocks/blocks/sqs.ts index 0abb55e62ec..a41fe97878c 100644 --- a/apps/sim/blocks/blocks/sqs.ts +++ b/apps/sim/blocks/blocks/sqs.ts @@ -605,7 +605,6 @@ export const SQSBlock: BlockConfig = { }, params: (params, context) => { const operation = mapperOperation(params, context) - const rest = params const parseJson = (value: unknown, fieldName: string) => { if (value === undefined || value === null || value === '') return undefined @@ -638,166 +637,166 @@ export const SQSBlock: BlockConfig = { } const result: Record = { - region: rest.region, - accessKeyId: rest.accessKeyId, - secretAccessKey: rest.secretAccessKey, + region: params.region, + accessKeyId: params.accessKeyId, + secretAccessKey: params.secretAccessKey, } switch (operation) { case 'send': { - result.queueUrl = rest.queueUrl - const data = parseJson(rest.data, 'data') + result.queueUrl = params.queueUrl + const data = parseJson(params.data, 'data') if (data !== undefined) result.data = data - const delaySeconds = parseInteger(rest.delaySeconds, 'delaySeconds') + const delaySeconds = parseInteger(params.delaySeconds, 'delaySeconds') if (delaySeconds !== undefined) result.delaySeconds = delaySeconds - const messageAttributes = parseJson(rest.messageAttributes, 'messageAttributes') + const messageAttributes = parseJson(params.messageAttributes, 'messageAttributes') if (messageAttributes !== undefined) result.messageAttributes = messageAttributes - if (rest.messageGroupId) result.messageGroupId = rest.messageGroupId - if (rest.messageDeduplicationId) { - result.messageDeduplicationId = rest.messageDeduplicationId + if (params.messageGroupId) result.messageGroupId = params.messageGroupId + if (params.messageDeduplicationId) { + result.messageDeduplicationId = params.messageDeduplicationId } break } case 'send_message_batch': { - result.queueUrl = rest.queueUrl - const entries = parseJson(rest.sendEntries, 'entries') + result.queueUrl = params.queueUrl + const entries = parseJson(params.sendEntries, 'entries') if (entries !== undefined) result.entries = entries break } case 'receive_message': { - result.queueUrl = rest.queueUrl + result.queueUrl = params.queueUrl const maxNumberOfMessages = parseInteger( - rest.maxNumberOfMessages, + params.maxNumberOfMessages, 'maxNumberOfMessages' ) if (maxNumberOfMessages !== undefined) result.maxNumberOfMessages = maxNumberOfMessages - const waitTimeSeconds = parseInteger(rest.waitTimeSeconds, 'waitTimeSeconds') + const waitTimeSeconds = parseInteger(params.waitTimeSeconds, 'waitTimeSeconds') if (waitTimeSeconds !== undefined) result.waitTimeSeconds = waitTimeSeconds const visibilityTimeout = parseInteger( - rest.receiveVisibilityTimeout, + params.receiveVisibilityTimeout, 'visibilityTimeout' ) if (visibilityTimeout !== undefined) result.visibilityTimeout = visibilityTimeout const messageAttributeNames = parseJson( - rest.messageAttributeNames, + params.messageAttributeNames, 'messageAttributeNames' ) if (messageAttributeNames !== undefined) { result.messageAttributeNames = messageAttributeNames } const messageSystemAttributeNames = parseJson( - rest.messageSystemAttributeNames, + params.messageSystemAttributeNames, 'messageSystemAttributeNames' ) if (messageSystemAttributeNames !== undefined) { result.messageSystemAttributeNames = messageSystemAttributeNames } - if (rest.receiveRequestAttemptId) { - result.receiveRequestAttemptId = rest.receiveRequestAttemptId + if (params.receiveRequestAttemptId) { + result.receiveRequestAttemptId = params.receiveRequestAttemptId } break } case 'delete_message': { - result.queueUrl = rest.queueUrl - result.receiptHandle = rest.receiptHandle + result.queueUrl = params.queueUrl + result.receiptHandle = params.receiptHandle break } case 'delete_message_batch': { - result.queueUrl = rest.queueUrl - const entries = parseJson(rest.deleteEntries, 'entries') + result.queueUrl = params.queueUrl + const entries = parseJson(params.deleteEntries, 'entries') if (entries !== undefined) result.entries = entries break } case 'change_message_visibility': { - result.queueUrl = rest.queueUrl - result.receiptHandle = rest.receiptHandle - const visibilityTimeout = parseInteger(rest.visibilityTimeout, 'visibilityTimeout') + result.queueUrl = params.queueUrl + result.receiptHandle = params.receiptHandle + const visibilityTimeout = parseInteger(params.visibilityTimeout, 'visibilityTimeout') if (visibilityTimeout !== undefined) result.visibilityTimeout = visibilityTimeout break } case 'change_message_visibility_batch': { - result.queueUrl = rest.queueUrl - const entries = parseJson(rest.visibilityEntries, 'entries') + result.queueUrl = params.queueUrl + const entries = parseJson(params.visibilityEntries, 'entries') if (entries !== undefined) result.entries = entries break } case 'list_queues': { - if (rest.queueNamePrefix) result.queueNamePrefix = rest.queueNamePrefix - const maxResults = parseInteger(rest.maxResults, 'maxResults') + if (params.queueNamePrefix) result.queueNamePrefix = params.queueNamePrefix + const maxResults = parseInteger(params.maxResults, 'maxResults') if (maxResults !== undefined) result.maxResults = maxResults - if (rest.nextToken) result.nextToken = rest.nextToken + if (params.nextToken) result.nextToken = params.nextToken break } case 'get_queue_url': { - result.queueName = rest.queueName - if (rest.queueOwnerAwsAccountId) { - result.queueOwnerAwsAccountId = rest.queueOwnerAwsAccountId + result.queueName = params.queueName + if (params.queueOwnerAwsAccountId) { + result.queueOwnerAwsAccountId = params.queueOwnerAwsAccountId } break } case 'get_queue_attributes': { - result.queueUrl = rest.queueUrl - const attributeNames = parseJson(rest.attributeNames, 'attributeNames') + result.queueUrl = params.queueUrl + const attributeNames = parseJson(params.attributeNames, 'attributeNames') if (attributeNames !== undefined) result.attributeNames = attributeNames break } case 'set_queue_attributes': { - result.queueUrl = rest.queueUrl - const attributes = parseJson(rest.queueAttributes, 'attributes') + result.queueUrl = params.queueUrl + const attributes = parseJson(params.queueAttributes, 'attributes') if (attributes !== undefined) result.attributes = attributes break } case 'create_queue': { - result.queueName = rest.queueName - const attributes = parseJson(rest.createQueueAttributes, 'attributes') + result.queueName = params.queueName + const attributes = parseJson(params.createQueueAttributes, 'attributes') if (attributes !== undefined) result.attributes = attributes - const tags = parseJson(rest.createQueueTags, 'tags') + const tags = parseJson(params.createQueueTags, 'tags') if (tags !== undefined) result.tags = tags break } case 'delete_queue': case 'purge_queue': case 'list_queue_tags': { - result.queueUrl = rest.queueUrl + result.queueUrl = params.queueUrl break } case 'list_dead_letter_source_queues': { - result.queueUrl = rest.queueUrl - const maxResults = parseInteger(rest.maxResults, 'maxResults') + result.queueUrl = params.queueUrl + const maxResults = parseInteger(params.maxResults, 'maxResults') if (maxResults !== undefined) result.maxResults = maxResults - if (rest.nextToken) result.nextToken = rest.nextToken + if (params.nextToken) result.nextToken = params.nextToken break } case 'tag_queue': { - result.queueUrl = rest.queueUrl - const tags = parseJson(rest.queueTags, 'tags') + result.queueUrl = params.queueUrl + const tags = parseJson(params.queueTags, 'tags') if (tags !== undefined) result.tags = tags break } case 'untag_queue': { - result.queueUrl = rest.queueUrl - const tagKeys = parseJson(rest.tagKeys, 'tagKeys') + result.queueUrl = params.queueUrl + const tagKeys = parseJson(params.tagKeys, 'tagKeys') if (tagKeys !== undefined) result.tagKeys = tagKeys break } case 'start_message_move_task': { - result.sourceArn = rest.sourceArn - if (rest.destinationArn) result.destinationArn = rest.destinationArn + result.sourceArn = params.sourceArn + if (params.destinationArn) result.destinationArn = params.destinationArn const maxPerSecond = parseInteger( - rest.maxNumberOfMessagesPerSecond, + params.maxNumberOfMessagesPerSecond, 'maxNumberOfMessagesPerSecond' ) if (maxPerSecond !== undefined) result.maxNumberOfMessagesPerSecond = maxPerSecond break } case 'list_message_move_tasks': { - result.sourceArn = rest.sourceArn - const maxResults = parseInteger(rest.moveTaskMaxResults, 'maxResults') + result.sourceArn = params.sourceArn + const maxResults = parseInteger(params.moveTaskMaxResults, 'maxResults') if (maxResults !== undefined) result.maxResults = maxResults break } case 'cancel_message_move_task': { - result.taskHandle = rest.taskHandle + result.taskHandle = params.taskHandle break } } diff --git a/apps/sim/blocks/blocks/trigger_dev.ts b/apps/sim/blocks/blocks/trigger_dev.ts index c7542f11f3c..7fa9bd996b0 100644 --- a/apps/sim/blocks/blocks/trigger_dev.ts +++ b/apps/sim/blocks/blocks/trigger_dev.ts @@ -1013,11 +1013,8 @@ Return ONLY the valid JSON object - no explanations, no markdown.`, result.page = scopedNumber(params.page, NUMBERED_PAGE_OPERATIONS) result.perPage = scopedNumber(params.perPage, NUMBERED_PAGE_OPERATIONS) - /** - * The canvas blanks every key the operation does not use, so a value saved under another - * operation never leaks into the request. On a tool call the result is spread over the - * model's args, so an unset key is dropped instead of wiping the model's value. - */ + // The canvas blanks unused keys so stale values never leak; a tool call's result spreads + // over the model's args, so an unset key is dropped instead of wiping the model's value. return isToolCall(context) ? filterUndefined(result) : result }, }, From b14c870eca0462eadca895dcbd15b3db37d9db41 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 15 Nov 2026 17:12:30 -0800 Subject: [PATCH 4/4] fix(blocks): keep model format, recursive and extended statistics on tool calls - tinybird append: fall back to the model's format before the csv default - sftp mkdir: fall back to the model's recursive before the default - cloudwatch get_metric_statistics: accept and normalize extendedStatistics from either source - azure data explorer ingest: an explicitly disabled Run in background stays off - cloudwatch/codepipeline tests: narrow the mapper so test-types passes --- apps/sim/blocks/blocks/azure_data_explorer.ts | 6 +++++- apps/sim/blocks/blocks/cloudwatch.test.ts | 21 +++++++++++++++++-- apps/sim/blocks/blocks/cloudwatch.ts | 12 ++++++----- apps/sim/blocks/blocks/codepipeline.test.ts | 5 +++-- apps/sim/blocks/blocks/sftp.test.ts | 13 ++++++++++++ apps/sim/blocks/blocks/sftp.ts | 10 +++++++-- apps/sim/blocks/blocks/tinybird.test.ts | 13 ++++++++++++ apps/sim/blocks/blocks/tinybird.ts | 2 +- 8 files changed, 69 insertions(+), 13 deletions(-) diff --git a/apps/sim/blocks/blocks/azure_data_explorer.ts b/apps/sim/blocks/blocks/azure_data_explorer.ts index 58822a49571..a4955d44ce4 100644 --- a/apps/sim/blocks/blocks/azure_data_explorer.ts +++ b/apps/sim/blocks/blocks/azure_data_explorer.ts @@ -469,7 +469,11 @@ export const AzureDataExplorerBlock: BlockConfig = { table: params.table, mode: params.ingestMode || toolCallArg(context, params.mode) || undefined, sourceQuery: params.sourceQuery, - async: toBoolean(params.ingestAsync) ?? toBoolean(toolCallArg(context, params.async)), + async: + params.ingestAsync === false || params.ingestAsync === 'false' + ? undefined + : (toBoolean(params.ingestAsync) ?? + toBoolean(toolCallArg(context, params.async))), ingestionProperties: params.ingestionProperties || undefined, } case 'azure_data_explorer_create_table': diff --git a/apps/sim/blocks/blocks/cloudwatch.test.ts b/apps/sim/blocks/blocks/cloudwatch.test.ts index f4b70cde60e..e174f1aa0f5 100644 --- a/apps/sim/blocks/blocks/cloudwatch.test.ts +++ b/apps/sim/blocks/blocks/cloudwatch.test.ts @@ -2,10 +2,11 @@ import { describe, expect, it } from 'vitest' import { CloudWatchV2Block } from '@/blocks/blocks/cloudwatch' import type { BlockToolParamsContext } from '@/blocks/types' -const mapParams = CloudWatchV2Block.tools.config?.params -if (!mapParams) { +const configuredParams = CloudWatchV2Block.tools.config?.params +if (!configuredParams) { throw new Error('CloudWatch block must define tools.config.params') } +const mapParams = configuredParams /** The tool-call merge: the mapped params land over the model's args (`{ ...args, ...mapped }`). */ function merge(args: Record, context?: BlockToolParamsContext) { @@ -23,4 +24,20 @@ describe('CloudWatch block params', () => { expect(merged.metricName).toBe('Hits') expect(merged.value).toBe(3) }) + it('splits a comma-separated extendedStatistics the model sent without statistics', () => { + const merged = merge( + { + namespace: 'AWS/EC2', + metricName: 'CPUUtilization', + startTime: 1700000000, + endTime: 1700003600, + period: 300, + extendedStatistics: 'p99, p95', + }, + { operation: 'get_metric_statistics' } + ) + + expect(merged.extendedStatistics).toEqual(['p99', 'p95']) + expect(merged.statistics).toBeUndefined() + }) }) diff --git a/apps/sim/blocks/blocks/cloudwatch.ts b/apps/sim/blocks/blocks/cloudwatch.ts index e99edcd0141..31e439ff7de 100644 --- a/apps/sim/blocks/blocks/cloudwatch.ts +++ b/apps/sim/blocks/blocks/cloudwatch.ts @@ -923,7 +923,9 @@ Return ONLY the numeric timestamp - no explanations, no quotes, no extra text.`, } const stat = rest.metricStatistics || toolCallArg(context, rest.statistics) - if (!stat && !toolCallArg(context, rest.extendedStatistics)) { + const extendedStat = + rest.metricExtendedStatistics || toolCallArg(context, rest.extendedStatistics) + if (!stat && !extendedStat) { throw new Error('Statistics is required') } @@ -937,10 +939,10 @@ Return ONLY the numeric timestamp - no explanations, no quotes, no extra text.`, endTime: Number(endTime), period: Number(period), ...(stat && { statistics: Array.isArray(stat) ? stat : [stat] }), - ...(rest.metricExtendedStatistics && { - extendedStatistics: Array.isArray(rest.metricExtendedStatistics) - ? rest.metricExtendedStatistics - : String(rest.metricExtendedStatistics) + ...(extendedStat && { + extendedStatistics: Array.isArray(extendedStat) + ? extendedStat + : String(extendedStat) .split(',') .map((s: string) => s.trim()) .filter(Boolean), diff --git a/apps/sim/blocks/blocks/codepipeline.test.ts b/apps/sim/blocks/blocks/codepipeline.test.ts index 23d9ae67134..d3c5ff370c1 100644 --- a/apps/sim/blocks/blocks/codepipeline.test.ts +++ b/apps/sim/blocks/blocks/codepipeline.test.ts @@ -2,10 +2,11 @@ import { describe, expect, it } from 'vitest' import { CodePipelineV2Block } from '@/blocks/blocks/codepipeline' import type { BlockToolParamsContext } from '@/blocks/types' -const mapParams = CodePipelineV2Block.tools.config?.params -if (!mapParams) { +const configuredParams = CodePipelineV2Block.tools.config?.params +if (!configuredParams) { throw new Error('CodePipeline block must define tools.config.params') } +const mapParams = configuredParams /** The tool-call merge: the mapped params land over the model's args (`{ ...args, ...mapped }`). */ function merge(args: Record, context?: BlockToolParamsContext) { diff --git a/apps/sim/blocks/blocks/sftp.test.ts b/apps/sim/blocks/blocks/sftp.test.ts index 3cf2c931513..880240e6ff8 100644 --- a/apps/sim/blocks/blocks/sftp.test.ts +++ b/apps/sim/blocks/blocks/sftp.test.ts @@ -13,4 +13,17 @@ describe('SftpV2Block agent tool calls', () => { ...SftpV2Block.tools.config?.params?.(merged, { operation: 'sftp_mkdir' }), }).toMatchObject({ recursive: true }) }) + it('keeps recursive: false the model supplied on a create-directory call', () => { + const merged = { + host: 'h', + username: 'u', + password: 'p', + remotePath: '/a/b', + recursive: false, + } + expect({ + ...merged, + ...SftpV2Block.tools.config?.params?.(merged, { operation: 'sftp_mkdir' }), + }).toMatchObject({ recursive: false }) + }) }) diff --git a/apps/sim/blocks/blocks/sftp.ts b/apps/sim/blocks/blocks/sftp.ts index 536082dffcc..9cc27574f62 100644 --- a/apps/sim/blocks/blocks/sftp.ts +++ b/apps/sim/blocks/blocks/sftp.ts @@ -3,7 +3,12 @@ import { omit } from '@sim/utils/object' import { SftpIcon } from '@/components/icons' import type { BlockConfig, BlockMeta, BlockToolParamsContext } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { createVersionedToolSelector, mapperOperation, normalizeFileInput } from '@/blocks/utils' +import { + createVersionedToolSelector, + mapperOperation, + normalizeFileInput, + toolCallArg, +} from '@/blocks/utils' export const SftpBlock = { type: 'sftp', @@ -287,7 +292,8 @@ export const SftpBlock = { return { ...connectionConfig, remotePath: params.remotePath, - recursive: params.mkdirRecursive !== false, + recursive: + (params.mkdirRecursive ?? toolCallArg(context, params.recursive)) !== false, } default: return { diff --git a/apps/sim/blocks/blocks/tinybird.test.ts b/apps/sim/blocks/blocks/tinybird.test.ts index cefbad56692..0518791e6dd 100644 --- a/apps/sim/blocks/blocks/tinybird.test.ts +++ b/apps/sim/blocks/blocks/tinybird.test.ts @@ -25,4 +25,17 @@ describe('Tinybird on an Agent tool call', () => { ) ).toMatchObject({ datasource: 'events', url: 'https://example.com/data.csv', format: 'csv' }) }) + it('keeps the source format the model supplied as format', () => { + expect( + toolCallParams( + { + token: 'tok', + datasource: 'events', + url: 'https://example.com/data.ndjson', + format: 'ndjson', + }, + 'tinybird_append_datasource' + ) + ).toMatchObject({ format: 'ndjson' }) + }) }) diff --git a/apps/sim/blocks/blocks/tinybird.ts b/apps/sim/blocks/blocks/tinybird.ts index 0e43756211a..167fe2bcd57 100644 --- a/apps/sim/blocks/blocks/tinybird.ts +++ b/apps/sim/blocks/blocks/tinybird.ts @@ -309,7 +309,7 @@ export const TinybirdBlock: BlockConfig = { result.datasource = params.datasource result.url = sourceUrl - result.format = params.source_format || 'csv' + result.format = params.source_format || toolCallArg(context, params.format) || 'csv' } else if (operation === 'tinybird_truncate_datasource') { // Truncate Data Source operation if (!params.datasource) {