diff --git a/apps/sim/blocks/blocks/azure_devops.test.ts b/apps/sim/blocks/blocks/azure_devops.test.ts index df28ca4d0fc..0d39de51e21 100644 --- a/apps/sim/blocks/blocks/azure_devops.test.ts +++ b/apps/sim/blocks/blocks/azure_devops.test.ts @@ -11,11 +11,12 @@ const buildParams = ( /** * On an agent call the model supplies `continuationToken`/`top`/`iterationPath`/`format` under the * tool's own names; the per-operation fields (`pipelinesContinuationToken`, `queryTop`, …) are never - * rendered in the agent tool input. The handler forwards `{ ...inputs, ...mapped }`. + * rendered in the agent tool input. A tool call carries the operation only in `context`, and the + * handler forwards `{ ...inputs, ...mapped }`. */ describe('AzureDevOpsBlock agent tool calls', () => { const agentCall = (operation: string, args: Record): Record => { - const inputs = { ...args, operation, organization: 'org', project: 'proj' } + const inputs = { ...args, organization: 'org', project: 'proj' } return { ...inputs, ...buildParams(inputs, { operation }) } } @@ -28,6 +29,21 @@ describe('AzureDevOpsBlock agent tool calls', () => { } ) + it.each(['azure_devops_create_work_item', 'azure_devops_update_work_item'])( + 'keeps a model zero for remainingWork, completedWork and effort on %s', + (operation) => { + const mapped = agentCall(operation, { + workItemId: 5, + workItemType: 'Task', + title: 't', + remainingWork: 0, + completedWork: 0, + effort: 0, + }) + expect([mapped.remainingWork, mapped.completedWork, mapped.effort]).toEqual([0, 0, 0]) + } + ) + it('keeps the model top on azure_devops_query_work_items', () => { expect(agentCall('azure_devops_query_work_items', { wiqlQuery: 'q', top: 5 }).top).toBe(5) }) @@ -45,6 +61,23 @@ describe('AzureDevOpsBlock agent tool calls', () => { expect(mapped.format).toBe('markdown') }) + it('keeps the model ids on azure_devops_get_work_items_batch', () => { + expect(agentCall('azure_devops_get_work_items_batch', { ids: '1,2' }).ids).toBe('1,2') + }) + + it('keeps the model text on azure_devops_add_comment', () => { + expect(agentCall('azure_devops_add_comment', { workItemId: 1, text: 'hi' }).text).toBe('hi') + }) + + it('expands a bare model start date on azure_devops_create_work_item', () => { + const mapped = agentCall('azure_devops_create_work_item', { + workItemType: 'Epic', + title: 't', + startDate: '2026-01-15', + }) + expect(mapped.startDate).toBe('2026-01-15T00:00:00Z') + }) + it('drops a List Builds token left over on the canvas under list pipelines', () => { const inputs = { operation: 'azure_devops_list_pipelines', continuationToken: 'stale' } expect({ ...inputs, ...buildParams(inputs) }.continuationToken).toBeUndefined() diff --git a/apps/sim/blocks/blocks/azure_devops.ts b/apps/sim/blocks/blocks/azure_devops.ts index f4a0a56b46c..af8defd0c07 100644 --- a/apps/sim/blocks/blocks/azure_devops.ts +++ b/apps/sim/blocks/blocks/azure_devops.ts @@ -1,7 +1,7 @@ import { AzureIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { toolCallArg, withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' import type { AzureDevOpsBasicWorkItemType } from '@/tools/azure_devops/types' import { AZURE_DEVOPS_BASIC_WORK_ITEM_STATES } from '@/tools/azure_devops/utils' import { getTrigger } from '@/triggers' @@ -22,6 +22,11 @@ function resolveTop(dedicated: unknown, shared: unknown): number | undefined { return value ? Number(value) : undefined } +/** Coerces an optional numeric field, keeping `0` (a model may send it to clear remaining work). */ +function optionalNumber(value: unknown): number | undefined { + return value === undefined || value === null || value === '' ? undefined : Number(value) +} + export const AzureDevOpsBlock: BlockConfig = { type: 'azure_devops', hideFromToolbar: true, @@ -724,7 +729,7 @@ export const AzureDevOpsBlock: BlockConfig = { organization: params.organization as string, project: params.project as string, } - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'azure_devops_list_pipelines': return { ...base, @@ -782,7 +787,10 @@ export const AzureDevOpsBlock: BlockConfig = { case 'azure_devops_get_work_item': return { ...base, workItemId: Number(params.workItemId) } case 'azure_devops_get_work_items_batch': - return { ...base, ids: params.workItemIds as string } + return { + ...base, + ids: (params.workItemIds as string) || toolCallArg(context, params.ids as string), + } case 'azure_devops_create_work_item': return { ...base, @@ -791,12 +799,12 @@ export const AzureDevOpsBlock: BlockConfig = { description: (params.description as string) || undefined, assignedTo: (params.assignedTo as string) || undefined, priority: params.priority ? Number(params.priority) : undefined, - effort: params.effort ? Number(params.effort) : undefined, + effort: optionalNumber(params.effort), startDate: normalizeDate(params.startDate), targetDate: normalizeDate(params.targetDate), activity: (params.activity as string) || undefined, - remainingWork: params.remainingWork ? Number(params.remainingWork) : undefined, - completedWork: params.completedWork ? Number(params.completedWork) : undefined, + remainingWork: optionalNumber(params.remainingWork), + completedWork: optionalNumber(params.completedWork), areaPath: (params.areaPath as string) || undefined, iterationPath: (params.iterationPath as string) || undefined, tags: (params.tags as string) || undefined, @@ -809,12 +817,12 @@ export const AzureDevOpsBlock: BlockConfig = { state: (params.state as string) || undefined, assignedTo: (params.assignedTo as string) || undefined, priority: params.priority ? Number(params.priority) : undefined, - effort: params.effort ? Number(params.effort) : undefined, + effort: optionalNumber(params.effort), startDate: normalizeDate(params.startDate), targetDate: normalizeDate(params.targetDate), activity: (params.activity as string) || undefined, - remainingWork: params.remainingWork ? Number(params.remainingWork) : undefined, - completedWork: params.completedWork ? Number(params.completedWork) : undefined, + remainingWork: optionalNumber(params.remainingWork), + completedWork: optionalNumber(params.completedWork), description: (params.description as string) || undefined, areaPath: (params.areaPath as string) || undefined, iterationPath: @@ -827,7 +835,7 @@ export const AzureDevOpsBlock: BlockConfig = { return { ...base, workItemId: Number(params.workItemId), - text: params.commentText as string, + text: (params.commentText as string) || toolCallArg(context, params.text as string), format: (params.commentFormat as string) || toolCallArg(context, params.format) || diff --git a/apps/sim/blocks/blocks/bitbucket.test.ts b/apps/sim/blocks/blocks/bitbucket.test.ts new file mode 100644 index 00000000000..7e765b3d855 --- /dev/null +++ b/apps/sim/blocks/blocks/bitbucket.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from 'vitest' +import { BitbucketBlock } from '@/blocks/blocks/bitbucket' + +/** + * On a tool call the model supplies args under the tool's param names (`refName`, `reviewerUuids`, + * …) and the operation arrives only in `context`; the handler forwards `{ ...args, ...mapped }`. + */ +const toolCall = (operation: string, args: Record): Record => { + const inputs = { workspaceSlug: 'ws', repoSlug: 'repo', ...args } + return { ...inputs, ...BitbucketBlock.tools.config?.params?.(inputs, { operation }) } +} + +describe('BitbucketBlock tool calls', () => { + it('defaults the ref type and keeps the model ref name on bitbucket_trigger_pipeline', () => { + const mapped = toolCall('bitbucket_trigger_pipeline', { refName: 'main' }) + expect(mapped).toMatchObject({ refType: 'branch', refName: 'main' }) + }) + + it('splits model reviewers and keeps closeSourceBranch on bitbucket_create_pull_request', () => { + const mapped = toolCall('bitbucket_create_pull_request', { + title: 'PR', + sourceBranch: 'feature', + reviewerUuids: '{a}, {b}', + closeSourceBranch: true, + }) + expect(mapped).toMatchObject({ reviewerUuids: ['{a}', '{b}'], closeSourceBranch: true }) + }) + + it('keeps the model commit, path and filter on bitbucket_list_directory', () => { + const mapped = toolCall('bitbucket_list_directory', { commit: 'abc', path: 'src', q: 'x' }) + expect(mapped).toMatchObject({ commit: 'abc', path: 'src', q: 'x' }) + }) +}) diff --git a/apps/sim/blocks/blocks/bitbucket.ts b/apps/sim/blocks/blocks/bitbucket.ts index 75f6a873b90..4fb95b28807 100644 --- a/apps/sim/blocks/blocks/bitbucket.ts +++ b/apps/sim/blocks/blocks/bitbucket.ts @@ -1,6 +1,7 @@ import { BitbucketIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' import { getTrigger } from '@/triggers' const WORKSPACE_FIELD = ['workspacePicker', 'workspaceSlugInput'] as const @@ -925,10 +926,21 @@ export const BitbucketBlock: BlockConfig = { } return params.operation }, - params: (params) => { - if (!isBitbucketOperation(params.operation)) { - throw new Error(`Invalid Bitbucket operation: ${String(params.operation)}`) + params: (params, context) => { + const operation = mapperOperation(params, context) + if (!isBitbucketOperation(operation)) { + throw new Error(`Invalid Bitbucket operation: ${operation}`) } + /** + * The block field, else (on a tool call only) the model's arg, which arrives under the + * tool's param name rather than the block field id. + */ + const fieldOrModelArg = ( + parse: (value: unknown, name: string) => T | undefined, + field: string, + toolParam: string + ): T | undefined => + parse(params[field], field) ?? parse(toolCallArg(context, params[toolParam]), toolParam) const common = { oauthCredential: params.oauthCredential, @@ -940,7 +952,7 @@ export const BitbucketBlock: BlockConfig = { nextUrl: optionalString(params.nextUrl, 'nextUrl'), } - switch (params.operation) { + switch (operation) { case 'bitbucket_list_workspaces': return { oauthCredential: params.oauthCredential, @@ -953,30 +965,31 @@ export const BitbucketBlock: BlockConfig = { oauthCredential: params.oauthCredential, workspaceSlug: optionalString(params.workspaceSlug, 'workspaceSlug'), role: optionalString(params.role, 'role'), - q: optionalString(params.query, 'query'), + q: fieldOrModelArg(optionalString, 'query', 'q'), sort: optionalString(params.sort, 'sort'), ...pagination, } case 'bitbucket_list_branches': return { ...common, - q: optionalString(params.query, 'query'), + q: fieldOrModelArg(optionalString, 'query', 'q'), sort: optionalString(params.sort, 'sort'), ...pagination, } case 'bitbucket_list_pipelines': return { ...common, - refType: optionalString(params.pipelineRefType, 'pipelineRefType'), - refName: optionalString(params.pipelineRefName, 'pipelineRefName'), - commitHash: optionalString(params.pipelineCommitHash, 'pipelineCommitHash'), - selectorType: optionalString(params.pipelineSelectorType, 'pipelineSelectorType'), - selectorPattern: optionalString( - params.pipelineSelectorPattern, - 'pipelineSelectorPattern' + refType: fieldOrModelArg(optionalString, 'pipelineRefType', 'refType'), + refName: fieldOrModelArg(optionalString, 'pipelineRefName', 'refName'), + commitHash: fieldOrModelArg(optionalString, 'pipelineCommitHash', 'commitHash'), + selectorType: fieldOrModelArg(optionalString, 'pipelineSelectorType', 'selectorType'), + selectorPattern: fieldOrModelArg( + optionalString, + 'pipelineSelectorPattern', + 'selectorPattern' ), - triggerType: optionalString(params.pipelineTriggerType, 'pipelineTriggerType'), - status: optionalString(params.pipelineStatus, 'pipelineStatus'), + triggerType: fieldOrModelArg(optionalString, 'pipelineTriggerType', 'triggerType'), + status: fieldOrModelArg(optionalString, 'pipelineStatus', 'status'), sort: optionalString(params.sort, 'sort'), ...pagination, } @@ -985,40 +998,40 @@ export const BitbucketBlock: BlockConfig = { case 'bitbucket_create_branch': return { ...common, - name: optionalString(params.branchName, 'branchName'), + name: fieldOrModelArg(optionalString, 'branchName', 'name'), target: optionalString(params.target, 'target'), } case 'bitbucket_delete_branch': - return { ...common, name: optionalString(params.branchName, 'branchName') } + return { ...common, name: fieldOrModelArg(optionalString, 'branchName', 'name') } case 'bitbucket_list_commits': return { ...common, - include: stringList(params.commitInclude, 'commitInclude'), - exclude: stringList(params.commitExclude, 'commitExclude'), - path: optionalString(params.commitPath, 'commitPath'), + include: fieldOrModelArg(stringList, 'commitInclude', 'include'), + exclude: fieldOrModelArg(stringList, 'commitExclude', 'exclude'), + path: fieldOrModelArg(optionalString, 'commitPath', 'path'), ...pagination, } case 'bitbucket_get_commit': - return { ...common, commit: optionalString(params.revision, 'revision') } + return { ...common, commit: fieldOrModelArg(optionalString, 'revision', 'commit') } case 'bitbucket_list_directory': return { ...common, - commit: optionalString(params.revision, 'revision'), + commit: fieldOrModelArg(optionalString, 'revision', 'commit'), path: optionalText(params.path, 'path'), - q: optionalString(params.query, 'query'), + q: fieldOrModelArg(optionalString, 'query', 'q'), sort: optionalString(params.sort, 'sort'), ...pagination, } case 'bitbucket_get_file_metadata': return { ...common, - commit: optionalString(params.revision, 'revision'), + commit: fieldOrModelArg(optionalString, 'revision', 'commit'), path: optionalText(params.path, 'path'), } case 'bitbucket_get_file': return { ...common, - commit: optionalString(params.revision, 'revision'), + commit: fieldOrModelArg(optionalString, 'revision', 'commit'), path: optionalText(params.path, 'path'), maxCharacters: optionalInteger(params.maxCharacters, 'maxCharacters'), } @@ -1026,7 +1039,7 @@ export const BitbucketBlock: BlockConfig = { return { ...common, state: optionalString(params.state, 'state'), - q: optionalString(params.query, 'query'), + q: fieldOrModelArg(optionalString, 'query', 'q'), sort: optionalString(params.sort, 'sort'), ...pagination, } @@ -1042,10 +1055,11 @@ export const BitbucketBlock: BlockConfig = { sourceBranch: optionalString(params.sourceBranch, 'sourceBranch'), destinationBranch: optionalString(params.destinationBranch, 'destinationBranch'), description: optionalText(params.description, 'description'), - reviewerUuids: stringList(params.reviewerAccountIds, 'reviewerAccountIds'), - closeSourceBranch: optionalBoolean( - params.createCloseSourceBranch, - 'createCloseSourceBranch' + reviewerUuids: fieldOrModelArg(stringList, 'reviewerAccountIds', 'reviewerUuids'), + closeSourceBranch: fieldOrModelArg( + optionalBoolean, + 'createCloseSourceBranch', + 'closeSourceBranch' ), draft: optionalBoolean(params.draft, 'draft'), } @@ -1055,9 +1069,10 @@ export const BitbucketBlock: BlockConfig = { prId: optionalInteger(params.prId, 'prId'), mergeStrategy: optionalString(params.mergeStrategy, 'mergeStrategy'), message: optionalText(params.message, 'message'), - closeSourceBranch: optionalBoolean( - params.mergeCloseSourceBranch, - 'mergeCloseSourceBranch' + closeSourceBranch: fieldOrModelArg( + optionalBoolean, + 'mergeCloseSourceBranch', + 'closeSourceBranch' ), } case 'bitbucket_get_pull_request_merge_task_status': @@ -1080,7 +1095,7 @@ export const BitbucketBlock: BlockConfig = { return { ...common, prId: optionalInteger(params.prId, 'prId'), - q: optionalString(params.query, 'query'), + q: fieldOrModelArg(optionalString, 'query', 'q'), sort: optionalString(params.sort, 'sort'), ...pagination, } @@ -1097,9 +1112,9 @@ export const BitbucketBlock: BlockConfig = { case 'bitbucket_trigger_pipeline': return { ...common, - refType: optionalString(params.targetRefType, 'targetRefType') ?? 'branch', - refName: optionalString(params.targetRef, 'targetRef'), - commitHash: optionalString(params.targetCommitHash, 'targetCommitHash'), + refType: fieldOrModelArg(optionalString, 'targetRefType', 'refType') ?? 'branch', + refName: fieldOrModelArg(optionalString, 'targetRef', 'refName'), + commitHash: fieldOrModelArg(optionalString, 'targetCommitHash', 'commitHash'), } case 'bitbucket_list_pipeline_steps': return { diff --git a/apps/sim/blocks/blocks/confluence.test.ts b/apps/sim/blocks/blocks/confluence.test.ts index 90a188d3b67..817445f8a34 100644 --- a/apps/sim/blocks/blocks/confluence.test.ts +++ b/apps/sim/blocks/blocks/confluence.test.ts @@ -67,3 +67,31 @@ describe('Confluence search-in-space values saved before the selector split', () expect(params.spaceId).toBeUndefined() }) }) + +/** + * On a tool call the model supplies args under the tool's param names and the operation arrives + * only in `context`; the handler forwards `{ ...args, ...mapped }`. + */ +describe('ConfluenceV2Block tool calls', () => { + const toolCall = (operation: string, args: Record): Record => ({ + ...args, + ...ConfluenceV2Block.tools.config?.params?.(args, { operation }), + }) + + it('normalizes the model file on upload_attachment', () => { + const file = { name: 'a.txt', key: 'k', size: 1, type: 'text/plain' } + expect(toolCall('upload_attachment', { pageId: '1', file: [file] }).file).toEqual(file) + }) + + it('keeps the model args the operation branches rename', () => { + expect(toolCall('search_in_space', { spaceKey: 'ENG', cursor: 'c' })).toMatchObject({ + spaceKey: 'ENG', + cursor: 'c', + }) + expect(toolCall('search', { query: 'q', cursor: 'c' }).cursor).toBe('c') + expect(toolCall('delete_space_property', { spaceId: 's', propertyId: 'p' }).propertyId).toBe( + 'p' + ) + expect(toolCall('create_page_property', { pageId: '1', key: 'k', value: 1 }).key).toBe('k') + }) +}) diff --git a/apps/sim/blocks/blocks/confluence.ts b/apps/sim/blocks/blocks/confluence.ts index 4e1d31a0c05..536cf35fb45 100644 --- a/apps/sim/blocks/blocks/confluence.ts +++ b/apps/sim/blocks/blocks/confluence.ts @@ -3,7 +3,7 @@ import { ConfluenceIcon, PagerDutyIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput } from '@/blocks/utils' +import { mapperOperation, normalizeFileInput, toolCallArg } from '@/blocks/utils' import { getTrigger } from '@/triggers' /** Canonical basic/advanced pair for the page target, shared by both versions. */ @@ -341,11 +341,10 @@ export const ConfluenceBlock: BlockConfig = { return 'confluence_retrieve' } }, - params: (params) => { + params: (params, context) => { const { oauthCredential, pageId, - operation, attachmentFile, attachmentFileName, attachmentComment, @@ -354,11 +353,10 @@ export const ConfluenceBlock: BlockConfig = { const effectivePageId = pageId ? String(pageId).trim() : '' - if (operation === 'upload_attachment') { + if (mapperOperation(params, context) === 'upload_attachment') { return { credential: oauthCredential, pageId: effectivePageId, - operation, file: attachmentFile, fileName: attachmentFileName, comment: attachmentComment, @@ -369,7 +367,6 @@ export const ConfluenceBlock: BlockConfig = { return { credential: oauthCredential, pageId: effectivePageId || undefined, - operation, ...rest, } }, @@ -1472,11 +1469,10 @@ export const ConfluenceV2Block: BlockConfig = { return 'confluence_retrieve' } }, - params: (params) => { + params: (params, context) => { const { oauthCredential, pageId, - operation, attachmentFile, attachmentFileName, attachmentComment, @@ -1507,50 +1503,48 @@ export const ConfluenceV2Block: BlockConfig = { parentCommentId, cql, searchCursor, + file: modelFile, ...rest } = params + const op = mapperOperation(params, context) const effectivePageId = pageId ? String(pageId).trim() : '' const scopedBodyFormat = - ['get_blogpost', 'list_pages_in_space', 'list_blogposts_in_space'].includes(operation) && + ['get_blogpost', 'list_pages_in_space', 'list_blogposts_in_space'].includes(op) && contentBodyFormat ? { bodyFormat: contentBodyFormat } : {} - if (operation === 'add_label') { + if (op === 'add_label') { return { credential: oauthCredential, pageId: effectivePageId, - operation, prefix: labelPrefix || 'global', ...rest, } } - if (operation === 'create_blogpost') { + if (op === 'create_blogpost') { return { credential: oauthCredential, - operation, status: blogPostStatus || 'current', ...rest, } } - if (operation === 'delete') { + if (op === 'delete') { return { credential: oauthCredential, pageId: effectivePageId, - operation, purge: purge || false, ...rest, } } - if (operation === 'list_comments') { + if (op === 'list_comments') { return { credential: oauthCredential, pageId: effectivePageId, - operation, bodyFormat: bodyFormat || 'storage', cursor: cursor || undefined, commentType: commentType || undefined, @@ -1558,22 +1552,20 @@ export const ConfluenceV2Block: BlockConfig = { } } - if (operation === 'create_comment') { + if (op === 'create_comment') { return { credential: oauthCredential, pageId: effectivePageId, - operation, parentCommentId: parentCommentId ? String(parentCommentId).trim() : undefined, ...rest, } } - if (operation === 'search') { + if (op === 'search') { return { credential: oauthCredential, - operation, cql: cql || undefined, - cursor: searchCursor || undefined, + cursor: searchCursor || toolCallArg(context, cursor) || undefined, ...rest, } } @@ -1596,69 +1588,66 @@ export const ConfluenceV2Block: BlockConfig = { 'list_space_properties', ] - if (supportsCursor.includes(operation) && cursor) { + if (supportsCursor.includes(op) && cursor) { return { credential: oauthCredential, pageId: effectivePageId || undefined, - operation, cursor, ...scopedBodyFormat, ...rest, } } - if (operation === 'create_page_property') { - if (!propertyKey) { + if (op === 'create_page_property') { + if (!propertyKey && !toolCallArg(context, rest.key)) { throw new Error('Property key is required for this operation.') } return { credential: oauthCredential, pageId: effectivePageId, - operation, key: propertyKey, value: propertyValue, ...rest, } } - if (operation === 'delete_page_property') { + if (op === 'delete_page_property') { return { credential: oauthCredential, pageId: effectivePageId, - operation, propertyId, ...rest, } } - if (operation === 'get_pages_by_label') { + if (op === 'get_pages_by_label') { return { credential: oauthCredential, - operation, labelId, cursor: cursor || undefined, ...rest, } } - if (operation === 'list_space_labels') { + if (op === 'list_space_labels') { return { credential: oauthCredential, - operation, cursor: cursor || undefined, ...rest, } } - if (operation === 'upload_attachment') { - const normalizedFile = normalizeFileInput(attachmentFile, { single: true }) + if (op === 'upload_attachment') { + const normalizedFile = normalizeFileInput( + attachmentFile ?? toolCallArg(context, modelFile), + { single: true } + ) if (!normalizedFile) { throw new Error('File is required for upload attachment operation.') } return { credential: oauthCredential, pageId: effectivePageId, - operation, file: normalizedFile, fileName: attachmentFileName, comment: attachmentComment, @@ -1666,28 +1655,25 @@ export const ConfluenceV2Block: BlockConfig = { } } - if (operation === 'get_user') { + if (op === 'get_user') { return { credential: oauthCredential, - operation, accountId: accountId ? String(accountId).trim() : undefined, ...rest, } } - if (operation === 'update_blogpost' || operation === 'delete_blogpost') { + if (op === 'update_blogpost' || op === 'delete_blogpost') { return { credential: oauthCredential, - operation, blogPostId: blogPostId || undefined, ...rest, } } - if (operation === 'create_space') { + if (op === 'create_space') { return { credential: oauthCredential, - operation, name: spaceName, key: spaceKey, description: spaceDescription, @@ -1695,95 +1681,85 @@ export const ConfluenceV2Block: BlockConfig = { } } - if (operation === 'search_in_space') { + if (op === 'search_in_space') { return { credential: oauthCredential, - operation, - spaceKey: selectedSpaceKey, - cursor: searchCursor || undefined, + spaceKey: selectedSpaceKey || toolCallArg(context, spaceKey), + cursor: searchCursor || toolCallArg(context, cursor) || undefined, ...rest, } } - if (operation === 'update_space') { + if (op === 'update_space') { return { credential: oauthCredential, - operation, name: spaceName || rest.title, description: spaceDescription, ...rest, } } - if (operation === 'delete_space') { + if (op === 'delete_space') { return { credential: oauthCredential, - operation, ...rest, } } - if (operation === 'create_space_property') { + if (op === 'create_space_property') { return { credential: oauthCredential, - operation, key: spacePropertyKey, value: spacePropertyValue, ...rest, } } - if (operation === 'delete_space_property') { + if (op === 'delete_space_property') { return { credential: oauthCredential, - operation, - propertyId: spacePropertyId, + propertyId: spacePropertyId || toolCallArg(context, propertyId), ...rest, } } - if (operation === 'list_space_permissions' || operation === 'list_space_properties') { + if (op === 'list_space_permissions' || op === 'list_space_properties') { return { credential: oauthCredential, - operation, cursor: cursor || undefined, ...rest, } } - if (operation === 'get_page_descendants') { + if (op === 'get_page_descendants') { return { credential: oauthCredential, pageId: effectivePageId, - operation, cursor: cursor || undefined, ...rest, } } - if (operation === 'get_task') { + if (op === 'get_task') { return { credential: oauthCredential, - operation, taskId, ...rest, } } - if (operation === 'update_task') { + if (op === 'update_task') { return { credential: oauthCredential, - operation, taskId, status: taskStatus, ...rest, } } - if (operation === 'list_tasks') { + if (op === 'list_tasks') { return { credential: oauthCredential, - operation, pageId: effectivePageId || undefined, assignedTo: taskAssignedTo || undefined, status: taskStatus || undefined, @@ -1797,7 +1773,6 @@ export const ConfluenceV2Block: BlockConfig = { pageId: effectivePageId || undefined, blogPostId: blogPostId || undefined, versionNumber: versionNumber ? Number.parseInt(String(versionNumber), 10) : undefined, - operation, ...scopedBodyFormat, ...rest, } diff --git a/apps/sim/blocks/blocks/gmail.test.ts b/apps/sim/blocks/blocks/gmail.test.ts index 6f999b9c3e6..92f00dc3067 100644 --- a/apps/sim/blocks/blocks/gmail.test.ts +++ b/apps/sim/blocks/blocks/gmail.test.ts @@ -11,12 +11,12 @@ const buildParams = ( /** * On an agent call the model supplies `threadId`/`format`/`name`/`query`/`labelIds` under the * tool's own names; the dedicated V2 fields (`targetThreadId`, `threadFormat`, `labelName`, - * `listQuery`, `threadLabelIds`) are never rendered in the agent tool input. + * `listQuery`, `threadLabelIds`) are never rendered in the agent tool input. A tool call carries + * the operation only in `context`. */ describe('GmailV2Block agent tool calls', () => { const agentCall = (operation: string, args: Record): Record => { - const inputs = { ...args, operation } - return { ...inputs, ...buildParams(inputs, { operation }) } + return { ...args, ...buildParams(args, { operation }) } } it('keeps the model threadId and format on get_thread_gmail', () => { @@ -41,6 +41,11 @@ describe('GmailV2Block agent tool calls', () => { } ) + it('joins model labelIds sent as an array on list_threads_gmail', () => { + const mapped = agentCall('list_threads_gmail', { labelIds: ['INBOX', 'UNREAD'] }) + expect(mapped.labelIds).toBe('INBOX,UNREAD') + }) + it('drops a Send threadId left over on the canvas under get_thread_gmail', () => { const inputs = { operation: 'get_thread_gmail', threadId: 'stale' } expect({ ...inputs, ...buildParams(inputs) }.threadId).toBeUndefined() diff --git a/apps/sim/blocks/blocks/gmail.ts b/apps/sim/blocks/blocks/gmail.ts index 2f120055b2a..66b30745683 100644 --- a/apps/sim/blocks/blocks/gmail.ts +++ b/apps/sim/blocks/blocks/gmail.ts @@ -6,6 +6,7 @@ import { AuthMode, IntegrationType } from '@/blocks/types' import { createVersionedToolSelector, isToolCall, + mapperOperation, normalizeFileInput, SERVICE_ACCOUNT_SUBBLOCKS, toolCallArg, @@ -543,7 +544,8 @@ Return ONLY the search query - no explanations, no extra text.`, ], config: { tool: selectGmailToolId, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { oauthCredential, folder, @@ -560,12 +562,12 @@ Return ONLY the search query - no explanations, no extra text.`, // Use canonical 'folder' param directly const effectiveFolder = folder ? String(folder).trim() : '' - if (rest.operation === 'read_gmail') { + if (operation === 'read_gmail') { rest.folder = effectiveFolder || 'INBOX' } // Handle move operation - use canonical params addLabelIds and removeLabelIds - if (rest.operation === 'move_gmail') { + if (operation === 'move_gmail') { if (moveMessageId) { rest.messageId = moveMessageId } @@ -585,14 +587,14 @@ Return ONLY the search query - no explanations, no extra text.`, 'archive_gmail', 'unarchive_gmail', 'delete_gmail', - ].includes(rest.operation) + ].includes(operation) ) { if (actionMessageId) { rest.messageId = actionMessageId } } - if (['add_label_gmail', 'remove_label_gmail'].includes(rest.operation)) { + if (['add_label_gmail', 'remove_label_gmail'].includes(operation)) { if (labelActionMessageId) { rest.messageId = labelActionMessageId } @@ -972,6 +974,7 @@ export const GmailV2Block: BlockConfig = { fallbackToolId: 'gmail_send_v2', }), params: (params, context) => { + const operation = mapperOperation(params, context) const mapped = GmailBlock.tools?.config?.params?.(params, context) ?? params const { labelName, @@ -983,16 +986,16 @@ export const GmailV2Block: BlockConfig = { labelListVisibility, ...rest } = mapped - if (LABEL_WRITE_OPERATIONS.includes(rest.operation)) { + if (LABEL_WRITE_OPERATIONS.includes(operation)) { rest.name = labelName || toolCallArg(context, rest.name) || undefined rest.messageListVisibility = messageListVisibility || undefined rest.labelListVisibility = labelListVisibility || undefined } - if (THREAD_TARGET_OPERATIONS.includes(rest.operation)) { + if (THREAD_TARGET_OPERATIONS.includes(operation)) { rest.threadId = isToolCall(context) ? targetThreadId || rest.threadId : targetThreadId rest.format = threadFormat || toolCallArg(context, rest.format) || undefined } - if (LIST_OPERATIONS.includes(rest.operation)) { + if (LIST_OPERATIONS.includes(operation)) { rest.query = listQuery || toolCallArg(context, rest.query) || undefined const labelIds = threadLabelIds || toolCallArg(context, rest.labelIds) rest.labelIds = labelIds ? String(labelIds).trim() : undefined diff --git a/apps/sim/blocks/blocks/google_appsheet.ts b/apps/sim/blocks/blocks/google_appsheet.ts index be2726ac42c..2c79ec9cf67 100644 --- a/apps/sim/blocks/blocks/google_appsheet.ts +++ b/apps/sim/blocks/blocks/google_appsheet.ts @@ -1,6 +1,8 @@ +import { getErrorMessage } from '@sim/utils/errors' import { GoogleAppsheetIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation } from '@/blocks/utils' export const GoogleAppsheetBlock: BlockConfig = { type: 'google_appsheet', @@ -163,15 +165,15 @@ Return ONLY the valid JSON array - no explanations, no markdown.`, ], config: { tool: (params) => params.operation, - params: (params) => { + params: (params, context) => { const { rows, ...rest } = params const result: Record = { ...rest } - if (params.operation !== 'google_appsheet_find_rows' && rows) { + if (mapperOperation(params, context) !== 'google_appsheet_find_rows' && rows) { let parsedRows: unknown try { parsedRows = typeof rows === 'string' ? JSON.parse(rows) : rows - } catch (error: any) { - throw new Error(`Invalid JSON in Rows field: ${error.message}`) + } catch (error) { + throw new Error(`Invalid JSON in Rows field: ${getErrorMessage(error)}`) } if (!Array.isArray(parsedRows)) { throw new Error('Rows must be a JSON array of row objects, e.g. [{ "RowID": "123" }]') diff --git a/apps/sim/blocks/blocks/google_calendar.test.ts b/apps/sim/blocks/blocks/google_calendar.test.ts index 07beac3b4d8..f0d5487904d 100644 --- a/apps/sim/blocks/blocks/google_calendar.test.ts +++ b/apps/sim/blocks/blocks/google_calendar.test.ts @@ -14,7 +14,7 @@ const buildParams = ( */ describe('GoogleCalendarBlock list timeZone', () => { it('keeps the model timeZone on an agent list call', () => { - const inputs = { operation: 'list', timeZone: 'America/New_York' } + const inputs = { timeZone: 'America/New_York' } const mapped = buildParams(inputs, { operation: 'list' }) expect({ ...inputs, ...mapped }.timeZone).toBe('America/New_York') }) @@ -24,3 +24,11 @@ describe('GoogleCalendarBlock list timeZone', () => { expect({ ...inputs, ...buildParams(inputs) }.timeZone).toBeUndefined() }) }) + +describe('GoogleCalendarBlock invite replaceExisting', () => { + it('keeps a boolean replaceExisting the model sends on an agent invite call', () => { + const inputs = { eventId: 'evt1', attendees: 'a@example.com', replaceExisting: true } + const mapped = buildParams(inputs, { operation: 'invite' }) + expect({ ...inputs, ...mapped }.replaceExisting).toBe(true) + }) +}) diff --git a/apps/sim/blocks/blocks/google_calendar.ts b/apps/sim/blocks/blocks/google_calendar.ts index a514ef29a54..f994d6960b2 100644 --- a/apps/sim/blocks/blocks/google_calendar.ts +++ b/apps/sim/blocks/blocks/google_calendar.ts @@ -2,7 +2,12 @@ import { GoogleCalendarIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { createVersionedToolSelector, SERVICE_ACCOUNT_SUBBLOCKS, toolCallArg } from '@/blocks/utils' +import { + createVersionedToolSelector, + mapperOperation, + SERVICE_ACCOUNT_SUBBLOCKS, + toolCallArg, +} from '@/blocks/utils' import { getTrigger } from '@/triggers' const CALENDAR_FIELD = ['calendarId', 'manualCalendarId'] as const @@ -994,13 +999,13 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, params: (params, context) => { const { oauthCredential, - operation, attendees, replaceExisting, calendarId, destinationCalendarId, ...rest } = params + const operation = mapperOperation(params, context) const effectiveCalendarId = calendarId ? String(calendarId).trim() : '' @@ -1029,7 +1034,7 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, } if (operation === 'invite' && replaceExisting !== undefined) { - processedParams.replaceExisting = replaceExisting === 'true' + processedParams.replaceExisting = replaceExisting === true || replaceExisting === 'true' } if (processedParams.addGoogleMeet !== undefined) { diff --git a/apps/sim/blocks/blocks/google_drive.test.ts b/apps/sim/blocks/blocks/google_drive.test.ts index 51168d39875..0db286a23c9 100644 --- a/apps/sim/blocks/blocks/google_drive.test.ts +++ b/apps/sim/blocks/blocks/google_drive.test.ts @@ -76,10 +76,14 @@ describe('GoogleDriveBlock pagination', () => { * the per-operation fields (`permissionsPageSize`, `searchPageToken`, `searchQuery`) are never rendered. */ describe('GoogleDriveBlock agent tool calls', () => { - const agentCall = (operation: string, args: Record): Record => { - const inputs = { ...args, operation } - return { ...inputs, ...buildParams(inputs, { operation }) } - } + /** A stored agent tool keeps its operation on the tool, so it reaches the mapper only in `context`. */ + const agentCall = ( + operation: string, + args: Record + ): Record => ({ + ...args, + ...buildParams(args, { operation }), + }) it.each(['search', 'list_permissions', 'list_revisions', 'list_comments'])( 'keeps the model pageSize and pageToken on %s', @@ -103,4 +107,39 @@ describe('GoogleDriveBlock agent tool calls', () => { const args = { fileId: 'f-1', pageToken: 'next' } expect({ ...args, ...buildParams(args, { operation: 'list_comments' }) }.pageToken).toBe('next') }) + + it('sends the file picked on the tool row over the fileId the model supplies', () => { + expect(agentCall('get_file', { getFileId: 'picked-1', fileId: 'model-1' }).fileId).toBe( + 'picked-1' + ) + }) + + it('sends the folders picked on the tool row over the ids the model supplies', () => { + const moved = agentCall('move', { + fileId: 'f-1', + moveDestFolderId: 'picked-dest', + destinationFolderId: 'model-dest', + }) + expect(moved.destinationFolderId).toBe('picked-dest') + expect( + agentCall('list', { listFolderId: 'picked-folder', folderId: 'model-folder' }).folderId + ).toBe('picked-folder') + }) + + it('keeps the model fileId when the tool row has no file picked', () => { + expect(agentCall('get_file', { fileId: 'model-1' }).fileId).toBe('model-1') + }) + + it('keeps the export format the model supplies', () => { + expect(agentCall('export', { fileId: 'f-1', mimeType: 'text/plain' }).mimeType).toBe( + 'text/plain' + ) + }) + + it('keeps boolean args the model sends as booleans', () => { + expect(agentCall('update', { fileId: 'f-1', starred: true }).starred).toBe(true) + expect(agentCall('move', { fileId: 'f-1', removeFromCurrent: false }).removeFromCurrent).toBe( + false + ) + }) }) diff --git a/apps/sim/blocks/blocks/google_drive.ts b/apps/sim/blocks/blocks/google_drive.ts index 18e709cff6d..f6aec85be9a 100644 --- a/apps/sim/blocks/blocks/google_drive.ts +++ b/apps/sim/blocks/blocks/google_drive.ts @@ -5,7 +5,9 @@ import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' import { isToolCall, + mapperOperation, normalizeFileInput, + parseOptionalBooleanInput, SERVICE_ACCOUNT_SUBBLOCKS, toolCallArg, } from '@/blocks/utils' @@ -1591,13 +1593,17 @@ Return ONLY the comment text - no explanations, no quotes, no extra formatting.` shareExpirationTime, shareAllowFileDiscovery, shareMoveToNewOwnersRoot, + fileId, + folderId, + destinationFolderId, ...rest } = params + const operation = mapperOperation(params, context) const normalizedFile = normalizeFileInput(file, { single: true }) let effectiveFolderId: string | undefined - switch (params.operation) { + switch (operation) { case 'create_file': case 'upload': effectiveFolderId = uploadFolderId?.trim() || undefined @@ -1611,7 +1617,7 @@ Return ONLY the comment text - no explanations, no quotes, no extra formatting.` } let effectiveFileId: string | undefined - switch (params.operation) { + switch (operation) { case 'download': effectiveFileId = downloadFileId?.trim() || undefined break @@ -1669,69 +1675,53 @@ Return ONLY the comment text - no explanations, no quotes, no extra formatting.` } let effectiveDestinationFolderId: string | undefined - if (params.operation === 'copy') { + if (operation === 'copy') { effectiveDestinationFolderId = copyDestFolderId?.trim() || undefined - } else if (params.operation === 'move') { + } else if (operation === 'move') { effectiveDestinationFolderId = moveDestFolderId?.trim() || undefined } - const starredValue = starred === 'true' ? true : starred === 'false' ? false : undefined - - const sendNotificationValue = - sendNotification === 'true' ? true : sendNotification === 'false' ? false : undefined - - const removeFromCurrentValue = - removeFromCurrent === 'true' ? true : removeFromCurrent === 'false' ? false : undefined - - const includeRevisionsValue = - includeRevisions === 'true' ? true : includeRevisions === 'false' ? false : undefined - - const includeDeletedValue = - includeDeleted === 'true' ? true : includeDeleted === 'false' ? false : undefined + const starredValue = parseOptionalBooleanInput(starred) + const sendNotificationValue = parseOptionalBooleanInput(sendNotification) + const removeFromCurrentValue = parseOptionalBooleanInput(removeFromCurrent) + const includeRevisionsValue = parseOptionalBooleanInput(includeRevisions) + const includeDeletedValue = parseOptionalBooleanInput(includeDeleted) let effectivePageSize: string | undefined = pageSize // `pageSize`, `pageToken` and `query` are List's fields; other operations trust them only from a tool call const agentPageSize = toolCallArg(context, pageSize) - if (params.operation === 'search') effectivePageSize = searchPageSize || agentPageSize - else if (params.operation === 'list_revisions') + if (operation === 'search') effectivePageSize = searchPageSize || agentPageSize + else if (operation === 'list_revisions') effectivePageSize = revisionsPageSize || agentPageSize - else if (params.operation === 'list_comments') + else if (operation === 'list_comments') effectivePageSize = commentsPageSize || agentPageSize - else if (params.operation === 'list_permissions') + else if (operation === 'list_permissions') effectivePageSize = permissionsPageSize || agentPageSize const agentPageToken = toolCallArg(context, pageToken) let effectivePageToken: string | undefined = pageToken - if (params.operation === 'search') effectivePageToken = searchPageToken || agentPageToken - else if (params.operation === 'list_permissions') + if (operation === 'search') effectivePageToken = searchPageToken || agentPageToken + else if (operation === 'list_permissions') effectivePageToken = permissionsPageToken || agentPageToken - else if (params.operation === 'list_revisions') + else if (operation === 'list_revisions') effectivePageToken = revisionsPageToken || agentPageToken - else if (params.operation === 'list_comments') + else if (operation === 'list_comments') effectivePageToken = commentsPageToken || agentPageToken - else if (params.operation !== 'list') effectivePageToken = agentPageToken + else if (operation !== 'list') effectivePageToken = agentPageToken const effectiveQuery = - params.operation === 'search' + operation === 'search' ? isToolCall(context) && !searchQuery ? query : searchQuery : query const effectiveOrderBy = - params.operation === 'list' - ? listOrderBy - : params.operation === 'search' - ? searchOrderBy - : undefined + operation === 'list' ? listOrderBy : operation === 'search' ? searchOrderBy : undefined const effectiveDriveId = - params.operation === 'list' - ? listDriveId - : params.operation === 'search' - ? searchDriveId - : undefined + operation === 'list' ? listDriveId : operation === 'search' ? searchDriveId : undefined - const isShare = params.operation === 'share' + const isShare = operation === 'share' const isUserOrGroupShare = isShare && (shareType === 'user' || shareType === 'group') const isDomainOrAnyoneShare = isShare && (shareType === 'domain' || shareType === 'anyone') const allowFileDiscoveryValue = !isDomainOrAnyoneShare @@ -1748,17 +1738,17 @@ Return ONLY the comment text - no explanations, no quotes, no extra formatting.` ? true : undefined const effectiveMimeType = - params.operation === 'get_content' - ? getContentExportMimeType - : params.operation === 'export' - ? exportMimeType + operation === 'get_content' + ? getContentExportMimeType || toolCallArg(context, mimeType) + : operation === 'export' + ? exportMimeType || toolCallArg(context, mimeType) : mimeType return { oauthCredential, - folderId: effectiveFolderId, - fileId: effectiveFileId, - destinationFolderId: effectiveDestinationFolderId, + folderId: effectiveFolderId || folderId, + fileId: effectiveFileId || fileId, + destinationFolderId: effectiveDestinationFolderId || destinationFolderId, file: normalizedFile, pageSize: effectivePageSize ? Number.parseInt(effectivePageSize as string, 10) @@ -1776,7 +1766,7 @@ Return ONLY the comment text - no explanations, no quotes, no extra formatting.` orderBy: effectiveOrderBy?.trim() || undefined, driveId: effectiveDriveId?.trim() || undefined, startModifiedTime: - params.operation === 'list_comments' + operation === 'list_comments' ? commentsStartModifiedTime?.trim() || undefined : undefined, expirationTime: isUserOrGroupShare ? shareExpirationTime?.trim() || undefined : undefined, diff --git a/apps/sim/blocks/blocks/google_forms.test.ts b/apps/sim/blocks/blocks/google_forms.test.ts new file mode 100644 index 00000000000..b55c0670b23 --- /dev/null +++ b/apps/sim/blocks/blocks/google_forms.test.ts @@ -0,0 +1,13 @@ +import { describe, expect, it } from 'vitest' +import { GoogleFormsBlock } from '@/blocks/blocks/google_forms' + +/** + * On an agent tool call the operation arrives only in `context`, never in the stored row params. + */ +describe('GoogleFormsBlock agent tool calls', () => { + it('maps a get_responses call instead of rejecting the missing params operation', () => { + const inputs = { oauthCredential: 'cred-1', formId: ' form-1 ', pageSize: 5 } + const mapped = GoogleFormsBlock.tools.config?.params?.(inputs, { operation: 'get_responses' }) + expect(mapped).toMatchObject({ formId: 'form-1', pageSize: 5 }) + }) +}) diff --git a/apps/sim/blocks/blocks/google_forms.ts b/apps/sim/blocks/blocks/google_forms.ts index 4ee9fe1a337..765a518334f 100644 --- a/apps/sim/blocks/blocks/google_forms.ts +++ b/apps/sim/blocks/blocks/google_forms.ts @@ -2,7 +2,7 @@ import { GoogleFormsIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { IntegrationType } from '@/blocks/types' -import { SERVICE_ACCOUNT_SUBBLOCKS } from '@/blocks/utils' +import { mapperOperation, SERVICE_ACCOUNT_SUBBLOCKS } from '@/blocks/utils' import { getTrigger } from '@/triggers' /* @@ -314,10 +314,9 @@ Example for "Add a required multiple choice question about favorite color": throw new Error(`Invalid Google Forms operation: ${params.operation}`) } }, - params: (params) => { + params: (params, context) => { const { oauthCredential, - operation, formId, // Canonical param from formSelector (basic) or manualFormId (advanced) responseId, pageSize, @@ -336,6 +335,7 @@ Example for "Add a required multiple choice question about favorite color": ...rest } = params + const operation = mapperOperation(params, context) const baseParams = { ...rest, oauthCredential } const effectiveFormId = formId ? String(formId).trim() : undefined diff --git a/apps/sim/blocks/blocks/google_groups.test.ts b/apps/sim/blocks/blocks/google_groups.test.ts index 8889b65fa97..0b48c760cb8 100644 --- a/apps/sim/blocks/blocks/google_groups.test.ts +++ b/apps/sim/blocks/blocks/google_groups.test.ts @@ -47,8 +47,16 @@ describe('GoogleGroupsBlock update settings', () => { describe('GoogleGroupsBlock agent tool calls', () => { it('keeps the model orderBy on list_groups when no sort order is chosen', () => { - const inputs = { operation: 'list_groups', customer: 'my_customer', orderBy: 'email' } + const inputs = { customer: 'my_customer', orderBy: 'email' } const mapped = GoogleGroupsBlock.tools.config?.params?.(inputs, { operation: 'list_groups' }) expect({ ...inputs, ...mapped }.orderBy).toBe('email') }) + + it.each([ + ['update_group', { groupKey: 'team@example.com', name: 'Team', email: 'new@example.com' }], + ['add_member', { groupKey: 'team@example.com', email: 'member@example.com', role: 'MEMBER' }], + ])('keeps the model name and email on %s', (operation, inputs) => { + const mapped = GoogleGroupsBlock.tools.config?.params?.(inputs, { operation }) + expect({ ...inputs, ...mapped }).toMatchObject(inputs) + }) }) diff --git a/apps/sim/blocks/blocks/google_groups.ts b/apps/sim/blocks/blocks/google_groups.ts index 5948e35f745..7b27a75b608 100644 --- a/apps/sim/blocks/blocks/google_groups.ts +++ b/apps/sim/blocks/blocks/google_groups.ts @@ -2,7 +2,7 @@ import { GoogleGroupsIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { SERVICE_ACCOUNT_SUBBLOCKS, toolCallArg } from '@/blocks/utils' +import { mapperOperation, SERVICE_ACCOUNT_SUBBLOCKS, toolCallArg } from '@/blocks/utils' /** Settings the Update Settings operation forwards when set; empty means unchanged. */ const UPDATE_SETTINGS_FIELDS = [ @@ -727,9 +727,9 @@ Return ONLY the description text - no explanations, no quotes, no extra text.`, } }, params: (params, context) => { - const { oauthCredential, operation, ...rest } = params + const { oauthCredential, ...rest } = params - switch (operation) { + switch (mapperOperation(params, context)) { case 'list_groups': return { oauthCredential, @@ -759,8 +759,8 @@ Return ONLY the description text - no explanations, no quotes, no extra text.`, return { oauthCredential, groupKey: rest.groupKey, - name: rest.newName, - email: rest.newEmail, + name: rest.newName ?? toolCallArg(context, rest.name), + email: rest.newEmail ?? toolCallArg(context, rest.email), description: rest.description, } case 'list_members': @@ -786,7 +786,7 @@ Return ONLY the description text - no explanations, no quotes, no extra text.`, return { oauthCredential, groupKey: rest.groupKey, - email: rest.memberEmail, + email: rest.memberEmail ?? toolCallArg(context, rest.email), role: rest.role, } case 'update_member': diff --git a/apps/sim/blocks/blocks/google_maps.test.ts b/apps/sim/blocks/blocks/google_maps.test.ts new file mode 100644 index 00000000000..46cc107705a --- /dev/null +++ b/apps/sim/blocks/blocks/google_maps.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from 'vitest' +import { GoogleMapsBlock } from '@/blocks/blocks/google_maps' + +/** + * On an agent tool call the model supplies args under the tool's own param names (`lat`, `lng`, + * `address`, arrays for JSON params), not the block's dedicated fields. + */ +describe('GoogleMapsBlock agent tool calls', () => { + it.each([ + ['reverse_geocode', { lat: 40.7128, lng: -74.006 }], + ['validate_address', { address: '1600 Amphitheatre Pkwy', regionCode: 'US' }], + ['distance_matrix', { origin: 'Boston', destinations: ['New York', 'Albany'] }], + ['places_nearby', { lat: 1, lng: 2, radius: 500, includedTypes: ['cafe'] }], + ['speed_limits', { placeIds: ['place-1'], units: 'MPH' }], + ])('keeps the model args on %s', (operation, inputs) => { + const mapped = GoogleMapsBlock.tools.config?.params?.(inputs, { operation }) + expect({ ...inputs, ...mapped }).toMatchObject(inputs) + }) +}) diff --git a/apps/sim/blocks/blocks/google_maps.ts b/apps/sim/blocks/blocks/google_maps.ts index 4daaa4025dd..86eacb433ca 100644 --- a/apps/sim/blocks/blocks/google_maps.ts +++ b/apps/sim/blocks/blocks/google_maps.ts @@ -1,6 +1,7 @@ import { GoogleMapsIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' export const GoogleMapsBlock: BlockConfig = { type: 'google_maps', @@ -582,8 +583,9 @@ export const GoogleMapsBlock: BlockConfig = { ], config: { tool: (params) => `google_maps_${params.operation}`, - params: (params) => { - const { operation, locationBias, addressToValidate, ...rest } = params + params: (params, context) => { + const { locationBias, addressToValidate, ...rest } = params + const operation = mapperOperation(params, context) let location: { lat: number; lng: number } | undefined if (locationBias && typeof locationBias === 'string' && locationBias.includes(',')) { @@ -617,6 +619,8 @@ export const GoogleMapsBlock: BlockConfig = { let destinations: string[] | undefined if (params.destinations && typeof params.destinations === 'string') { destinations = params.destinations.split('|').map((d: string) => d.trim()) + } else if (Array.isArray(params.destinations)) { + destinations = toolCallArg(context, params.destinations) } let waypoints: string[] | undefined @@ -625,6 +629,8 @@ export const GoogleMapsBlock: BlockConfig = { .split('|') .map((w: string) => w.trim()) .filter(Boolean) + } else if (Array.isArray(params.waypoints)) { + waypoints = toolCallArg(context, params.waypoints) } let radius: number | undefined @@ -639,6 +645,8 @@ export const GoogleMapsBlock: BlockConfig = { .split('|') .map((p: string) => p.trim()) .filter(Boolean) + } else if (Array.isArray(params.placeIds)) { + placeIds = toolCallArg(context, params.placeIds) } let wifiAccessPoints: unknown[] | undefined @@ -648,6 +656,8 @@ export const GoogleMapsBlock: BlockConfig = { } catch { // Ignore parse errors } + } else if (Array.isArray(params.wifiAccessPoints)) { + wifiAccessPoints = toolCallArg(context, params.wifiAccessPoints) } let cellTowers: unknown[] | undefined @@ -657,9 +667,14 @@ export const GoogleMapsBlock: BlockConfig = { } catch { // Ignore parse errors } + } else if (Array.isArray(params.cellTowers)) { + cellTowers = toolCallArg(context, params.cellTowers) } - const address = operation === 'validate_address' ? addressToValidate : params.address + const address = + operation === 'validate_address' + ? (addressToValidate ?? toolCallArg(context, params.address)) + : params.address // Parse boolean switches (can come as string or boolean from form) let interpolate: boolean | undefined @@ -710,9 +725,9 @@ export const GoogleMapsBlock: BlockConfig = { return { ...rest, address, - location, - lat, - lng, + location: location ?? toolCallArg(context, params.location), + lat: lat ?? toolCallArg(context, params.lat), + lng: lng ?? toolCallArg(context, params.lng), timestamp, destinations, waypoints, @@ -729,11 +744,16 @@ export const GoogleMapsBlock: BlockConfig = { homeMobileCountryCode, homeMobileNetworkCode, requiredQuality: params.requiredQuality || undefined, - type: params.placeType || undefined, - includedTypes: params.placeType ? [params.placeType] : undefined, + type: params.placeType || toolCallArg(context, params.type) || undefined, + includedTypes: params.placeType + ? [params.placeType] + : toolCallArg(context, params.includedTypes), avoid: params.avoid || undefined, radioType: params.radioType || undefined, - units: operation === 'speed_limits' ? params.speedUnits || undefined : params.units, + units: + operation === 'speed_limits' + ? params.speedUnits || toolCallArg(context, params.units) || undefined + : params.units, } }, }, diff --git a/apps/sim/blocks/blocks/google_sheets.test.ts b/apps/sim/blocks/blocks/google_sheets.test.ts new file mode 100644 index 00000000000..19531b45bd0 --- /dev/null +++ b/apps/sim/blocks/blocks/google_sheets.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from 'vitest' +import { GoogleSheetsV2Block } from '@/blocks/blocks/google_sheets' + +/** + * On an agent tool call the operation arrives only in `context`, and the model supplies args under + * the tool's own param names with JSON params already parsed. + */ +describe('GoogleSheetsV2Block agent tool calls', () => { + it.each([ + ['delete_sheet', { spreadsheetId: 'ss-1', sheetId: 42 }], + ['delete_rows', { spreadsheetId: 'ss-1', sheetId: 42, startIndex: 0, endIndex: 3 }], + ['copy_sheet', { sourceSpreadsheetId: 'ss-1', sheetId: 42, destinationSpreadsheetId: 'ss-2' }], + ['batch_get', { spreadsheetId: 'ss-1', ranges: ['Sheet1!A1:B2'], majorDimension: 'COLUMNS' }], + ['batch_update', { spreadsheetId: 'ss-1', data: [{ range: 'Sheet1!A1', values: [['x']] }] }], + ['create', { title: 'Budget', sheetTitles: ['Q1', 'Q2'] }], + ['read', { spreadsheetId: 'ss-1', sheetName: 'Sheet1', majorDimension: 'COLUMNS' }], + [ + 'append', + { spreadsheetId: 'ss-1', sheetName: 'Sheet1', values: [['a']], valueInputOption: 'RAW' }, + ], + ])('keeps the model args on %s', (operation, inputs) => { + const mapped = GoogleSheetsV2Block.tools.config?.params?.(inputs, { operation }) + expect({ ...inputs, ...mapped }).toMatchObject(inputs) + }) +}) diff --git a/apps/sim/blocks/blocks/google_sheets.ts b/apps/sim/blocks/blocks/google_sheets.ts index 5563dbae06e..0a88a693b95 100644 --- a/apps/sim/blocks/blocks/google_sheets.ts +++ b/apps/sim/blocks/blocks/google_sheets.ts @@ -2,7 +2,13 @@ import { GoogleSheetsIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { createVersionedToolSelector, SERVICE_ACCOUNT_SUBBLOCKS } from '@/blocks/utils' +import { + createVersionedToolSelector, + isToolCall, + mapperOperation, + SERVICE_ACCOUNT_SUBBLOCKS, + toolCallArg, +} from '@/blocks/utils' import { getTrigger } from '@/triggers' /** @@ -927,7 +933,7 @@ Return ONLY the JSON array - no explanations, no markdown, no extra text.`, suffix: '_v2', fallbackToolId: 'google_sheets_read_v2', }), - params: (params) => { + params: (params, context) => { const { oauthCredential, values, @@ -951,12 +957,19 @@ Return ONLY the JSON array - no explanations, no markdown, no extra text.`, ...rest } = params - const operation = params.operation as string + const operation = mapperOperation(params, context) + + /** A model sends JSON-typed tool params already parsed; the canvas sends JSON text. */ + const parseJsonInput = (value: unknown) => + typeof value !== 'string' && isToolCall(context) ? value : JSON.parse(value as string) if (operation === 'create') { - const sheetTitlesArray = sheetTitles - ? (sheetTitles as string).split(',').map((s: string) => s.trim()) - : undefined + const sheetTitlesArray = + Array.isArray(sheetTitles) && isToolCall(context) + ? sheetTitles + : sheetTitles + ? (sheetTitles as string).split(',').map((s: string) => s.trim()) + : undefined return { title: (title as string)?.trim(), sheetTitles: sheetTitlesArray, @@ -964,7 +977,10 @@ Return ONLY the JSON array - no explanations, no markdown, no extra text.`, } } - const effectiveSpreadsheetId = spreadsheetId ? String(spreadsheetId).trim() : '' + const rawSpreadsheetId = + spreadsheetId || + (operation === 'copy_sheet' ? toolCallArg(context, rest.sourceSpreadsheetId) : undefined) + const effectiveSpreadsheetId = rawSpreadsheetId ? String(rawSpreadsheetId).trim() : '' if (!effectiveSpreadsheetId) { throw new Error('Spreadsheet ID is required.') @@ -978,7 +994,7 @@ Return ONLY the JSON array - no explanations, no markdown, no extra text.`, } if (operation === 'batch_get') { - const parsedRanges = ranges ? JSON.parse(ranges as string) : [] + const parsedRanges = ranges ? parseJsonInput(ranges) : [] return { spreadsheetId: effectiveSpreadsheetId, ranges: parsedRanges, @@ -992,7 +1008,9 @@ Return ONLY the JSON array - no explanations, no markdown, no extra text.`, } if (operation === 'batch_update') { - const parsedData = batchData ? JSON.parse(batchData as string) : [] + const parsedData = batchData + ? JSON.parse(batchData as string) + : (toolCallArg(context, rest.data) ?? []) return { ...rest, spreadsheetId: effectiveSpreadsheetId, @@ -1002,7 +1020,7 @@ Return ONLY the JSON array - no explanations, no markdown, no extra text.`, } if (operation === 'batch_clear') { - const parsedRanges = ranges ? JSON.parse(ranges as string) : [] + const parsedRanges = ranges ? parseJsonInput(ranges) : [] return { spreadsheetId: effectiveSpreadsheetId, ranges: parsedRanges, @@ -1027,7 +1045,10 @@ Return ONLY the JSON array - no explanations, no markdown, no extra text.`, } if (operation === 'delete_sheet') { - const parsedSheetId = Number.parseInt(deleteSheetId as string, 10) + const parsedSheetId = Number.parseInt( + (deleteSheetId ?? toolCallArg(context, sheetId)) as string, + 10 + ) if (Number.isNaN(parsedSheetId)) { throw new Error('Sheet ID must be a valid number') } @@ -1039,7 +1060,10 @@ Return ONLY the JSON array - no explanations, no markdown, no extra text.`, } if (operation === 'delete_rows') { - const parsedSheetId = Number.parseInt(deleteSheetId as string, 10) + const parsedSheetId = Number.parseInt( + (deleteSheetId ?? toolCallArg(context, sheetId)) as string, + 10 + ) const parsedStartIndex = Number.parseInt(startIndex as string, 10) const parsedEndIndex = Number.parseInt(endIndex as string, 10) if ( @@ -1064,7 +1088,7 @@ Return ONLY the JSON array - no explanations, no markdown, no extra text.`, throw new Error('Sheet name is required. Please select or enter a sheet name.') } - const parsedValues = values ? JSON.parse(values as string) : undefined + const parsedValues = values ? parseJsonInput(values) : undefined return { ...rest, @@ -1079,9 +1103,14 @@ Return ONLY the JSON array - no explanations, no markdown, no extra text.`, : {}), ...(filterMatchType ? { filterMatchType: filterMatchType as string } : {}), ...(operation === 'append' - ? { valueInputOption: appendValueInputOption || undefined } + ? { + valueInputOption: + appendValueInputOption || + toolCallArg(context, rest.valueInputOption) || + undefined, + } : {}), - majorDimension: undefined, + majorDimension: operation === 'read' ? toolCallArg(context, majorDimension) : undefined, } }, }, diff --git a/apps/sim/blocks/blocks/google_slides.test.ts b/apps/sim/blocks/blocks/google_slides.test.ts new file mode 100644 index 00000000000..2910f1f6563 --- /dev/null +++ b/apps/sim/blocks/blocks/google_slides.test.ts @@ -0,0 +1,96 @@ +import { describe, expect, it } from 'vitest' +import { GoogleSlidesBlock, GoogleSlidesV2Block } from '@/blocks/blocks/google_slides' +import type { BlockConfig, BlockToolParamsContext } from '@/blocks/types' + +function mapParams( + block: BlockConfig, + params: Record, + context?: BlockToolParamsContext +) { + const mapper = block.tools.config?.params + if (!mapper) throw new Error(`${block.type} has no params mapper`) + return mapper(params, context) +} + +describe('Google Slides agent tool calls', () => { + it('forwards the model slide index for write', () => { + const mapped = mapParams( + GoogleSlidesV2Block, + { presentationId: 'p1', content: 'Hello', slideIndex: 2 }, + { operation: 'write' } + ) + expect(mapped.slideIndex).toBe(2) + }) + + it('forwards the model folder for create and copy', () => { + expect( + mapParams(GoogleSlidesV2Block, { title: 'Deck', folderId: 'f1' }, { operation: 'create' }) + .folderId + ).toBe('f1') + expect( + mapParams( + GoogleSlidesV2Block, + { sourcePresentationId: 'src', title: 'Copy', folderId: 'f2' }, + { operation: 'copy_presentation' } + ).folderId + ).toBe('f2') + }) + + it('keeps the model object id instead of the empty block field', () => { + const mapped = mapParams( + GoogleSlidesV2Block, + { presentationId: 'p1', objectId: 'shape_1' }, + { operation: 'delete_object' } + ) + expect(mapped.objectId).toBe('shape_1') + }) + + it('keeps the model z-order enum in the tool operation param', () => { + const mapped = mapParams( + GoogleSlidesV2Block, + { presentationId: 'p1', objectIds: 'a,b', operation: 'SEND_TO_BACK' }, + { operation: 'update_page_elements_z_order' } + ) + expect(mapped.operation).toBe('SEND_TO_BACK') + }) + + it('accepts a model image URL for add_image without an uploaded file', () => { + const mapped = mapParams( + GoogleSlidesV2Block, + { presentationId: 'p1', pageObjectId: 's1', imageUrl: 'https://example.com/a.png' }, + { operation: 'add_image' } + ) + expect(mapped.imageUrl).toBe('https://example.com/a.png') + }) +}) + +describe('Google Slides canvas', () => { + it('never sends the block operation name as the z-order enum', () => { + const mapped = mapParams(GoogleSlidesV2Block, { + operation: 'update_page_elements_z_order', + presentationId: 'p1', + zOrderObjectIds: 'a', + }) + expect(mapped.operation).toBeUndefined() + }) + + it('sends the legacy image source as the image URL', () => { + const mapped = mapParams(GoogleSlidesBlock, { + operation: 'add_image', + presentationId: 'p1', + pageObjectId: 's1', + imageSource: 'https://example.com/a.png', + }) + expect(mapped.imageUrl).toBe('https://example.com/a.png') + }) + + it('extracts the URL from a referenced file serialized into the legacy image source', () => { + const mapped = mapParams(GoogleSlidesBlock, { + operation: 'add_image', + presentationId: 'p1', + pageObjectId: 's1', + imageSource: JSON.stringify({ name: 'a.png', url: 'https://files.example.com/a.png' }), + }) + expect(mapped.imageUrl).toBe('https://files.example.com/a.png') + }) +}) diff --git a/apps/sim/blocks/blocks/google_slides.ts b/apps/sim/blocks/blocks/google_slides.ts index f58dcaf077b..328bbd22d36 100644 --- a/apps/sim/blocks/blocks/google_slides.ts +++ b/apps/sim/blocks/blocks/google_slides.ts @@ -4,7 +4,13 @@ import { getScopesForService } from '@/lib/oauth/utils' import { resolveHttpsUrlFromFileInput } from '@/lib/uploads/utils/file' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput, SERVICE_ACCOUNT_SUBBLOCKS } from '@/blocks/utils' +import { + isToolCall, + mapperOperation, + normalizeFileInput, + SERVICE_ACCOUNT_SUBBLOCKS, + toolCallArg, +} from '@/blocks/utils' const PRESENTATION_FIELD = ['presentationId', 'manualPresentationId'] as const const SOURCE_PRESENTATION_FIELD = [ @@ -2690,7 +2696,17 @@ Return ONLY the text content - no explanations, no markdown formatting markers, throw new Error(`Invalid Google Slides operation: ${params.operation}`) } }, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) + /** + * The block field on the canvas. On a tool call a blank block field falls back to the + * model's arg, which arrives under the tool's param name. + */ + const orModelArg = (blockValue: unknown, modelArg: unknown): unknown => + isToolCall(context) && + (blockValue === undefined || blockValue === null || blockValue === '') + ? modelArg + : blockValue const { oauthCredential, presentationId, @@ -2712,22 +2728,32 @@ Return ONLY the text content - no explanations, no markdown formatting markers, oauthCredential, } - if (params.operation === 'write' && slideIndex) { + if (operation === 'write' && slideIndex) { result.slideIndex = Number.parseInt(slideIndex as string, 10) } - if (params.operation === 'create') { + if (operation === 'create') { result.folderId = effectiveFolderId || undefined if (createContent) { result.content = createContent } } - if (params.operation === 'add_slide' && params.insertionIndex) { + if (operation === 'add_slide' && params.insertionIndex) { result.insertionIndex = Number.parseInt(params.insertionIndex as string, 10) } - if (params.operation === 'add_image') { + if (operation === 'add_image') { + const source = params.imageSource + if (source) { + const fileObject = normalizeFileInput(source, { single: true }) + if (fileObject) { + const fileUrl = resolveHttpsUrlFromFileInput(fileObject) + if (fileUrl) result.imageUrl = fileUrl + } else if (typeof source === 'string') { + result.imageUrl = source.trim() + } + } if (imageWidth) { result.width = Number.parseInt(imageWidth as string, 10) } @@ -2742,34 +2768,34 @@ Return ONLY the text content - no explanations, no markdown formatting markers, } } - if (params.operation === 'get_thumbnail') { - result.pageObjectId = thumbnailPageId + if (operation === 'get_thumbnail') { + result.pageObjectId = orModelArg(thumbnailPageId, params.pageObjectId) } - if (params.operation === 'get_page') { - result.pageObjectId = params.getPageObjectId + if (operation === 'get_page') { + result.pageObjectId = orModelArg(params.getPageObjectId, params.pageObjectId) } - if (params.operation === 'delete_object') { - result.objectId = params.deleteObjectId + if (operation === 'delete_object') { + result.objectId = orModelArg(params.deleteObjectId, params.objectId) } - if (params.operation === 'duplicate_object') { - result.objectId = params.duplicateObjectId + if (operation === 'duplicate_object') { + result.objectId = orModelArg(params.duplicateObjectId, params.objectId) if (params.duplicateObjectIds) { result.objectIds = params.duplicateObjectIds } } - if (params.operation === 'reorder_slides') { - result.slideObjectIds = params.reorderSlideIds + if (operation === 'reorder_slides') { + result.slideObjectIds = orModelArg(params.reorderSlideIds, params.slideObjectIds) if (params.reorderInsertionIndex) { result.insertionIndex = Number.parseInt(params.reorderInsertionIndex as string, 10) } } - if (params.operation === 'create_table') { - result.pageObjectId = params.tablePageObjectId + if (operation === 'create_table') { + result.pageObjectId = orModelArg(params.tablePageObjectId, params.pageObjectId) if (params.tableRows) { result.rows = Number.parseInt(params.tableRows as string, 10) } @@ -2790,8 +2816,8 @@ Return ONLY the text content - no explanations, no markdown formatting markers, } } - if (params.operation === 'create_shape') { - result.pageObjectId = params.shapePageObjectId + if (operation === 'create_shape') { + result.pageObjectId = orModelArg(params.shapePageObjectId, params.pageObjectId) result.shapeType = params.shapeType if (params.shapeWidth) { result.width = Number.parseInt(params.shapeWidth as string, 10) @@ -2807,9 +2833,9 @@ Return ONLY the text content - no explanations, no markdown formatting markers, } } - if (params.operation === 'insert_text') { - result.objectId = params.insertTextObjectId - result.text = params.insertTextContent + if (operation === 'insert_text') { + result.objectId = orModelArg(params.insertTextObjectId, params.objectId) + result.text = orModelArg(params.insertTextContent, params.text) if (params.insertTextIndex) { result.insertionIndex = Number.parseInt(params.insertTextIndex as string, 10) } @@ -2828,8 +2854,8 @@ Return ONLY the text content - no explanations, no markdown formatting markers, 'create_paragraph_bullets', 'delete_paragraph_bullets', ]) - if (TEXT_RANGE_OPS.has(params.operation as string)) { - result.objectId = params.textObjectId + if (TEXT_RANGE_OPS.has(operation)) { + result.objectId = orModelArg(params.textObjectId, params.objectId) const rowIdx = toNum(params.textRowIndex) const colIdx = toNum(params.textColumnIndex) if (rowIdx !== undefined) result.rowIndex = rowIdx @@ -2841,7 +2867,7 @@ Return ONLY the text content - no explanations, no markdown formatting markers, if (endIdx !== undefined) result.endIndex = endIdx } - if (params.operation === 'update_text_style') { + if (operation === 'update_text_style') { if (params.textBold !== undefined) result.bold = params.textBold if (params.textItalic !== undefined) result.italic = params.textItalic if (params.textUnderline !== undefined) result.underline = params.textUnderline @@ -2859,7 +2885,7 @@ Return ONLY the text content - no explanations, no markdown formatting markers, if (params.textStyleFields) result.fields = params.textStyleFields } - if (params.operation === 'update_paragraph_style') { + if (operation === 'update_paragraph_style') { if (params.paragraphAlignment) result.alignment = params.paragraphAlignment const ls = toNum(params.paragraphLineSpacing) if (ls !== undefined) result.lineSpacing = ls @@ -2879,13 +2905,13 @@ Return ONLY the text content - no explanations, no markdown formatting markers, if (params.paragraphStyleFields) result.fields = params.paragraphStyleFields } - if (params.operation === 'create_paragraph_bullets' && params.bulletPreset) { + if (operation === 'create_paragraph_bullets' && params.bulletPreset) { result.bulletPreset = params.bulletPreset } - if (params.operation === 'replace_all_shapes_with_image') { - result.imageUrl = params.replaceShapesImageUrl - result.findText = params.replaceShapesFindText + if (operation === 'replace_all_shapes_with_image') { + result.imageUrl = orModelArg(params.replaceShapesImageUrl, rest.imageUrl) + result.findText = orModelArg(params.replaceShapesFindText, params.findText) if (params.replaceShapesMatchCase !== undefined) result.matchCase = params.replaceShapesMatchCase if (params.replaceShapesImageMethod) @@ -2894,14 +2920,14 @@ Return ONLY the text content - no explanations, no markdown formatting markers, result.pageObjectIds = params.replaceShapesPageObjectIds } - if (params.operation === 'replace_image') { - result.imageObjectId = params.replaceImageObjectId - result.imageUrl = params.replaceImageUrl + if (operation === 'replace_image') { + result.imageObjectId = orModelArg(params.replaceImageObjectId, params.imageObjectId) + result.imageUrl = orModelArg(params.replaceImageUrl, rest.imageUrl) if (params.replaceImageMethod) result.imageReplaceMethod = params.replaceImageMethod } - if (params.operation === 'update_image_properties') { - result.objectId = params.imagePropsObjectId + if (operation === 'update_image_properties') { + result.objectId = orModelArg(params.imagePropsObjectId, params.objectId) const brightness = toNum(params.imageBrightness) if (brightness !== undefined) result.brightness = brightness const contrast = toNum(params.imageContrast) @@ -2917,8 +2943,8 @@ Return ONLY the text content - no explanations, no markdown formatting markers, if (params.imagePropertiesFields) result.fields = params.imagePropertiesFields } - if (params.operation === 'update_shape_properties') { - result.objectId = params.shapePropsObjectId + if (operation === 'update_shape_properties') { + result.objectId = orModelArg(params.shapePropsObjectId, params.objectId) if (params.shapeFillColor) result.fillColor = params.shapeFillColor const fillAlpha = toNum(params.shapeFillAlpha) if (fillAlpha !== undefined) result.fillAlpha = fillAlpha @@ -2935,8 +2961,8 @@ Return ONLY the text content - no explanations, no markdown formatting markers, if (params.shapePropertiesFields) result.fields = params.shapePropertiesFields } - if (params.operation === 'update_page_properties') { - result.objectId = params.pagePropsObjectId + if (operation === 'update_page_properties') { + result.objectId = orModelArg(params.pagePropsObjectId, params.objectId) if (params.pageBackgroundColor) result.backgroundColor = params.pageBackgroundColor const bgAlpha = toNum(params.pageBackgroundAlpha) if (bgAlpha !== undefined) result.backgroundAlpha = bgAlpha @@ -2948,22 +2974,22 @@ Return ONLY the text content - no explanations, no markdown formatting markers, if (params.pagePropertiesFields) result.fields = params.pagePropertiesFields } - if (params.operation === 'update_slide_properties') { - result.objectId = params.slidePropsObjectId + if (operation === 'update_slide_properties') { + result.objectId = orModelArg(params.slidePropsObjectId, params.objectId) if (params.slideIsSkipped !== undefined) result.isSkipped = params.slideIsSkipped if (params.slidePropertiesJson) result.propertiesJson = params.slidePropertiesJson if (params.slidePropertiesFields) result.fields = params.slidePropertiesFields } - if (params.operation === 'update_page_element_alt_text') { - result.objectId = params.altTextObjectId + if (operation === 'update_page_element_alt_text') { + result.objectId = orModelArg(params.altTextObjectId, params.objectId) if (params.altTextTitle !== undefined) result.title = params.altTextTitle if (params.altTextDescription !== undefined) result.description = params.altTextDescription } - if (params.operation === 'update_page_element_transform') { - result.objectId = params.transformObjectId + if (operation === 'update_page_element_transform') { + result.objectId = orModelArg(params.transformObjectId, params.objectId) const sx = toNum(params.transformScaleX) const sy = toNum(params.transformScaleY) const shx = toNum(params.transformShearX) @@ -2979,25 +3005,30 @@ Return ONLY the text content - no explanations, no markdown formatting markers, if (params.transformApplyMode) result.applyMode = params.transformApplyMode } - if (params.operation === 'update_page_elements_z_order') { - result.objectIds = params.zOrderObjectIds - // Always overwrite — even when zOrderOperation is empty — so the block-level - // operation name 'update_page_elements_z_order' can never leak through as the - // z-order enum value and produce a confusing API error. - result.operation = params.zOrderOperation || undefined + if (operation === 'update_page_elements_z_order') { + result.objectIds = orModelArg(params.zOrderObjectIds, params.objectIds) + // The tool's z-order enum shares the block's `operation` key. On the canvas always + // overwrite it so the block operation name never reaches the API; on a tool call + // `rest` already holds the model's enum under the tool's own `operation` param. + if (params.zOrderOperation || !isToolCall(context)) { + Object.assign(result, { operation: params.zOrderOperation || undefined }) + } } - if (params.operation === 'group_objects') { - result.childrenObjectIds = params.groupChildrenObjectIds + if (operation === 'group_objects') { + result.childrenObjectIds = orModelArg( + params.groupChildrenObjectIds, + params.childrenObjectIds + ) if (params.groupObjectIdInput) result.groupObjectId = params.groupObjectIdInput } - if (params.operation === 'ungroup_objects') { - result.objectIds = params.ungroupObjectIds + if (operation === 'ungroup_objects') { + result.objectIds = orModelArg(params.ungroupObjectIds, params.objectIds) } - if (params.operation === 'create_line') { - result.pageObjectId = params.linePageObjectId + if (operation === 'create_line') { + result.pageObjectId = orModelArg(params.linePageObjectId, params.pageObjectId) if (params.lineCategory) result.lineCategory = params.lineCategory const lw = toNum(params.lineWidth) const lh = toNum(params.lineHeight) @@ -3009,8 +3040,8 @@ Return ONLY the text content - no explanations, no markdown formatting markers, if (lpy !== undefined) result.positionY = lpy } - if (params.operation === 'update_line_properties') { - result.objectId = params.linePropsObjectId + if (operation === 'update_line_properties') { + result.objectId = orModelArg(params.linePropsObjectId, params.objectId) if (params.lineColor) result.lineColor = params.lineColor const lineWeight = toNum(params.lineWeight) if (lineWeight !== undefined) result.lineWeight = lineWeight @@ -3022,13 +3053,13 @@ Return ONLY the text content - no explanations, no markdown formatting markers, if (params.linePropertiesFields) result.fields = params.linePropertiesFields } - if (params.operation === 'update_line_category') { - result.objectId = params.lineCategoryObjectId + if (operation === 'update_line_category') { + result.objectId = orModelArg(params.lineCategoryObjectId, params.objectId) if (params.newLineCategory) result.lineCategory = params.newLineCategory } - if (params.operation === 'reroute_line') { - result.objectId = params.rerouteLineObjectId + if (operation === 'reroute_line') { + result.objectId = orModelArg(params.rerouteLineObjectId, params.objectId) } const TABLE_CELL_REF_OPS = new Set([ @@ -3037,24 +3068,21 @@ Return ONLY the text content - no explanations, no markdown formatting markers, 'delete_table_row', 'delete_table_column', ]) - if (TABLE_CELL_REF_OPS.has(params.operation as string)) { - result.tableObjectId = params.tableTargetObjectId + if (TABLE_CELL_REF_OPS.has(operation)) { + result.tableObjectId = orModelArg(params.tableTargetObjectId, params.tableObjectId) const rIdx = toNum(params.tableCellRowIndex) const cIdx = toNum(params.tableCellColumnIndex) if (rIdx !== undefined) result.rowIndex = rIdx if (cIdx !== undefined) result.columnIndex = cIdx } - if ( - params.operation === 'insert_table_rows' || - params.operation === 'insert_table_columns' - ) { + if (operation === 'insert_table_rows' || operation === 'insert_table_columns') { const n = toNum(params.tableInsertNumber) if (n !== undefined) result.number = n } - if (params.operation === 'insert_table_rows' && params.tableInsertBelow !== undefined) { + if (operation === 'insert_table_rows' && params.tableInsertBelow !== undefined) { result.insertBelow = params.tableInsertBelow } - if (params.operation === 'insert_table_columns' && params.tableInsertRight !== undefined) { + if (operation === 'insert_table_columns' && params.tableInsertRight !== undefined) { result.insertRight = params.tableInsertRight } @@ -3064,8 +3092,8 @@ Return ONLY the text content - no explanations, no markdown formatting markers, 'update_table_cell_properties', 'update_table_border_properties', ]) - if (TABLE_RANGE_OPS.has(params.operation as string)) { - result.objectId = params.tableRangeObjectId + if (TABLE_RANGE_OPS.has(operation)) { + result.objectId = orModelArg(params.tableRangeObjectId, params.objectId) const rIdx = toNum(params.tableRangeRowIndex) const cIdx = toNum(params.tableRangeColumnIndex) const rSpan = toNum(params.tableRangeRowSpan) @@ -3076,7 +3104,7 @@ Return ONLY the text content - no explanations, no markdown formatting markers, if (cSpan !== undefined) result.columnSpan = cSpan } - if (params.operation === 'update_table_cell_properties') { + if (operation === 'update_table_cell_properties') { if (params.tableCellBackgroundColor) result.backgroundColor = params.tableCellBackgroundColor const cellAlpha = toNum(params.tableCellBackgroundAlpha) @@ -3087,7 +3115,7 @@ Return ONLY the text content - no explanations, no markdown formatting markers, if (params.tableCellPropertiesFields) result.fields = params.tableCellPropertiesFields } - if (params.operation === 'update_table_border_properties') { + if (operation === 'update_table_border_properties') { if (params.tableBorderPosition) result.borderPosition = params.tableBorderPosition if (params.tableBorderColor) result.borderColor = params.tableBorderColor const borderWeight = toNum(params.tableBorderWeight) @@ -3098,8 +3126,8 @@ Return ONLY the text content - no explanations, no markdown formatting markers, if (params.tableBorderPropertiesFields) result.fields = params.tableBorderPropertiesFields } - if (params.operation === 'update_table_column_properties') { - result.objectId = params.tableColumnPropsObjectId + if (operation === 'update_table_column_properties') { + result.objectId = orModelArg(params.tableColumnPropsObjectId, params.objectId) if (params.tableColumnIndices) result.columnIndices = params.tableColumnIndices const colWidth = toNum(params.tableColumnWidth) if (colWidth !== undefined) result.columnWidth = colWidth @@ -3108,8 +3136,8 @@ Return ONLY the text content - no explanations, no markdown formatting markers, if (params.tableColumnPropertiesFields) result.fields = params.tableColumnPropertiesFields } - if (params.operation === 'update_table_row_properties') { - result.objectId = params.tableRowPropsObjectId + if (operation === 'update_table_row_properties') { + result.objectId = orModelArg(params.tableRowPropsObjectId, params.objectId) if (params.tableRowIndices) result.rowIndices = params.tableRowIndices const minHeight = toNum(params.tableMinRowHeight) if (minHeight !== undefined) result.minRowHeight = minHeight @@ -3117,8 +3145,8 @@ Return ONLY the text content - no explanations, no markdown formatting markers, if (params.tableRowPropertiesFields) result.fields = params.tableRowPropertiesFields } - if (params.operation === 'create_sheets_chart') { - result.pageObjectId = params.chartPageObjectId + if (operation === 'create_sheets_chart') { + result.pageObjectId = orModelArg(params.chartPageObjectId, params.pageObjectId) if (params.chartSpreadsheetId) result.spreadsheetId = params.chartSpreadsheetId const cId = toNum(params.chartId) if (cId !== undefined) result.chartId = cId @@ -3133,15 +3161,15 @@ Return ONLY the text content - no explanations, no markdown formatting markers, if (cpy !== undefined) result.positionY = cpy } - if (params.operation === 'refresh_sheets_chart') { - result.objectId = params.refreshChartObjectId + if (operation === 'refresh_sheets_chart') { + result.objectId = orModelArg(params.refreshChartObjectId, params.objectId) } - if (params.operation === 'replace_all_shapes_with_sheets_chart') { + if (operation === 'replace_all_shapes_with_sheets_chart') { if (params.chartSpreadsheetId) result.spreadsheetId = params.chartSpreadsheetId const cId = toNum(params.chartId) if (cId !== undefined) result.chartId = cId - result.findText = params.replaceShapesChartFindText + result.findText = orModelArg(params.replaceShapesChartFindText, params.findText) if (params.replaceShapesChartMatchCase !== undefined) result.matchCase = params.replaceShapesChartMatchCase if (params.chartLinkingMode) result.linkingMode = params.chartLinkingMode @@ -3149,8 +3177,8 @@ Return ONLY the text content - no explanations, no markdown formatting markers, result.pageObjectIds = params.replaceShapesChartPageObjectIds } - if (params.operation === 'create_video') { - result.pageObjectId = params.videoPageObjectId + if (operation === 'create_video') { + result.pageObjectId = orModelArg(params.videoPageObjectId, params.pageObjectId) if (params.videoSource) result.source = params.videoSource if (params.videoId) result.videoId = params.videoId const vw = toNum(params.videoWidth) @@ -3163,8 +3191,8 @@ Return ONLY the text content - no explanations, no markdown formatting markers, if (vpy !== undefined) result.positionY = vpy } - if (params.operation === 'update_video_properties') { - result.objectId = params.videoPropsObjectId + if (operation === 'update_video_properties') { + result.objectId = orModelArg(params.videoPropsObjectId, params.objectId) if (params.videoAutoPlay !== undefined) result.autoPlay = params.videoAutoPlay if (params.videoMute !== undefined) result.mute = params.videoMute const vStart = toNum(params.videoStart) @@ -3179,15 +3207,16 @@ Return ONLY the text content - no explanations, no markdown formatting markers, if (params.videoPropertiesFields) result.fields = params.videoPropertiesFields } - if (params.operation === 'batch_update') { + if (operation === 'batch_update') { if (params.requestsJson) result.requests = params.requestsJson if (params.writeControlJson) result.writeControl = params.writeControlJson } - if (params.operation === 'copy_presentation') { + if (operation === 'copy_presentation') { if (params.sourcePresentationId) result.sourcePresentationId = params.sourcePresentationId if (params.copyTitle) result.title = params.copyTitle if (params.copyFolderId) result.folderId = params.copyFolderId + else if (isToolCall(context) && effectiveFolderId) result.folderId = effectiveFolderId result.presentationId = undefined } @@ -3599,15 +3628,16 @@ export const GoogleSlidesV2Block: BlockConfig = { access: GoogleSlidesBlock.tools!.access, config: { tool: GoogleSlidesBlock.tools!.config!.tool, - params: (params) => { + params: (params, context) => { const baseParams = GoogleSlidesBlock.tools?.config?.params if (!baseParams) { return params } - if (params.operation === 'add_image') { + if (mapperOperation(params, context) === 'add_image') { const fileObject = normalizeFileInput(params.imageFile, { single: true }) if (!fileObject) { + if (toolCallArg(context, params.imageUrl)) return baseParams(params, context) throw new Error('Image file is required.') } const imageUrl = resolveHttpsUrlFromFileInput(fileObject) @@ -3615,13 +3645,16 @@ export const GoogleSlidesV2Block: BlockConfig = { throw new Error('Image file must include a https URL.') } - return baseParams({ - ...params, - imageUrl, - }) + return baseParams( + { + ...params, + imageUrl, + }, + context + ) } - return baseParams(params) + return baseParams(params, context) }, }, }, diff --git a/apps/sim/blocks/blocks/google_vault.test.ts b/apps/sim/blocks/blocks/google_vault.test.ts index 9cb2b713243..634bf27e9e0 100644 --- a/apps/sim/blocks/blocks/google_vault.test.ts +++ b/apps/sim/blocks/blocks/google_vault.test.ts @@ -16,7 +16,7 @@ describe('GoogleVaultBlock includeSharedDrives', () => { it.each(['create_matters_export', 'create_saved_query'])( 'keeps the model value on an agent %s call', (operation) => { - const inputs = { operation, matterId: 'm-1', corpus: 'DRIVE', includeSharedDrives: true } + const inputs = { matterId: 'm-1', corpus: 'DRIVE', includeSharedDrives: true } expect(buildParams(inputs, { operation }).includeSharedDrives).toBe(true) } ) @@ -30,3 +30,13 @@ describe('GoogleVaultBlock includeSharedDrives', () => { expect(buildParams(inputs).includeSharedDrives).toBe(false) }) }) + +/** A tool call carries its operation only in `context`, never in the stored row params. */ +describe('GoogleVaultBlock list_matters tool call', () => { + it('sends the Detail Level set on the agent tool row as view', () => { + const inputs = { matterView: 'FULL', matterState: 'OPEN' } + const params = buildParams(inputs, { operation: 'list_matters' }) + expect(params.view).toBe('FULL') + expect(params.state).toBe('OPEN') + }) +}) diff --git a/apps/sim/blocks/blocks/google_vault.ts b/apps/sim/blocks/blocks/google_vault.ts index a8823cb7f7c..6bb333ef239 100644 --- a/apps/sim/blocks/blocks/google_vault.ts +++ b/apps/sim/blocks/blocks/google_vault.ts @@ -3,7 +3,12 @@ import { GoogleVaultIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { parseOptionalBooleanInput, SERVICE_ACCOUNT_SUBBLOCKS, toolCallArg } from '@/blocks/utils' +import { + mapperOperation, + parseOptionalBooleanInput, + SERVICE_ACCOUNT_SUBBLOCKS, + toolCallArg, +} from '@/blocks/utils' export const GoogleVaultBlock: BlockConfig = { type: 'google_vault', @@ -929,8 +934,9 @@ Return ONLY the description text - no explanations, no quotes, no extra text.`, dataScope, ...rest } = params + const operation = mapperOperation(params, context) const isQueryOperation = - params.operation === 'create_matters_export' || params.operation === 'create_saved_query' + operation === 'create_matters_export' || operation === 'create_saved_query' return { ...rest, oauthCredential, @@ -954,8 +960,8 @@ Return ONLY the description text - no explanations, no quotes, no extra text.`, ...(listExportId && { exportId: listExportId }), ...(listHoldId && { holdId: listHoldId }), ...(listSavedQueryId && { savedQueryId: listSavedQueryId }), - ...(params.operation === 'list_matters' && matterView && { view: matterView }), - ...(params.operation === 'list_matters' && matterState && { state: matterState }), + ...(operation === 'list_matters' && matterView && { view: matterView }), + ...(operation === 'list_matters' && matterState && { state: matterState }), ...(isQueryOperation && { includeSharedDrives: exportIncludeSharedDrives == null @@ -964,7 +970,7 @@ Return ONLY the description text - no explanations, no quotes, no extra text.`, : exportIncludeSharedDrives === true || exportIncludeSharedDrives === 'true', ...(dataScope && { dataScope }), }), - ...(params.operation === 'create_matters_export' && exportFormat && { exportFormat }), + ...(operation === 'create_matters_export' && exportFormat && { exportFormat }), } }, }, diff --git a/apps/sim/blocks/blocks/jira.test.ts b/apps/sim/blocks/blocks/jira.test.ts new file mode 100644 index 00000000000..e44eebff1ba --- /dev/null +++ b/apps/sim/blocks/blocks/jira.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from 'vitest' +import { JiraBlock } from '@/blocks/blocks/jira' + +/** + * What a tool call (agent, Pi, Human v2) hands the tool: the merged stored-row and model args, + * overlaid with the block mapper's output. The operation arrives only in `context`. + */ +function toolCallParams(operation: string, args: Record) { + const mapper = JiraBlock.tools.config?.params + if (!mapper) throw new Error('Jira block is missing tools.config.params') + return { ...args, ...mapper(args, { operation }) } +} + +describe('JiraBlock tool calls', () => { + it('maps fields set on the agent tool row to the tool param names', () => { + expect( + toolCallParams('add_comment', { issueKey: 'PROJ-1', commentBody: 'From the row' }).body + ).toBe('From the row') + expect( + toolCallParams('get_users', { userAccountId: 'acc-1', usersMaxResults: '5' }) + ).toMatchObject({ accountId: 'acc-1', maxResults: 5 }) + }) + + it.each([ + ['add_comment', { issueKey: 'PROJ-1', body: 'Model comment' }], + ['transition', { issueKey: 'PROJ-1', transitionId: '31', comment: 'Done', fields: { a: 1 } }], + ['update_worklog', { issueKey: 'PROJ-1', worklogId: '9', timeSpentSeconds: 600 }], + ['search_users', { query: 'ada', maxResults: 10, startAt: 20 }], + ['list_projects', { query: 'core', maxResults: 10, startAt: 0 }], + [ + 'create_link', + { inwardIssueKey: 'A-1', outwardIssueKey: 'B-1', linkType: 'Blocks', comment: 'x' }, + ], + ['update', { issueKey: 'PROJ-1', parent: { key: 'PROJ-0' }, notifyUsers: false }], + ])('keeps model args for %s', (operation, args) => { + expect(toolCallParams(operation, args)).toMatchObject(args) + }) + + it('accepts model-sent arrays for list params instead of throwing', () => { + const params = toolCallParams('write', { + projectId: '10000', + summary: 'Bug', + labels: ['a', ' b '], + parent: { key: 'PROJ-0' }, + }) + expect(params.labels).toEqual(['a', 'b']) + expect(params.parent).toEqual({ key: 'PROJ-0' }) + expect(toolCallParams('search', { jql: 'x', fields: ['key', 'summary'] }).fields).toEqual([ + 'key', + 'summary', + ]) + expect( + toolCallParams('delete', { issueKey: 'PROJ-1', deleteSubtasks: true }).deleteSubtasks + ).toBe(true) + }) +}) diff --git a/apps/sim/blocks/blocks/jira.ts b/apps/sim/blocks/blocks/jira.ts index 454636cd4e4..337c508691b 100644 --- a/apps/sim/blocks/blocks/jira.ts +++ b/apps/sim/blocks/blocks/jira.ts @@ -2,7 +2,12 @@ import { JiraIcon } from '@/components/icons' import { getDefaultToolScopesForProvider } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput } from '@/blocks/utils' +import { + mapperOperation, + normalizeFileInput, + parseOptionalBooleanInput, + toolCallArg, +} from '@/blocks/utils' import { getTrigger } from '@/triggers' /** Canonical `issueKey` pair: issue picker (basic) and raw issue key (advanced). */ @@ -12,6 +17,29 @@ const PROJECT_FIELD = ['projectId', 'manualProjectId'] as const /** Canonical `files` pair: upload (basic) and file reference (advanced). */ const ATTACHMENT_FIELD = ['attachmentFiles', 'files'] as const +/** A comma-separated canvas string or a model-sent array as a trimmed list; `undefined` when empty. */ +function parseList(value: unknown): string[] | undefined { + const items = Array.isArray(value) + ? value.map((item) => String(item).trim()) + : typeof value === 'string' + ? value.split(',').map((item) => item.trim()) + : [] + const nonEmpty = items.filter((item) => item !== '') + return nonEmpty.length > 0 ? nonEmpty : undefined +} + +/** Parses a worklog duration in seconds; `undefined` when blank, throws when not positive. */ +function parseTimeSpentSeconds(raw: unknown): number | undefined { + if (raw === undefined || raw === null || String(raw).trim() === '') return undefined + const seconds = Number(String(raw).trim()) + if (!Number.isFinite(seconds) || seconds <= 0) { + throw new Error( + 'Time Spent (seconds) must be a positive number of seconds (e.g., 3600 for 1 hour)' + ) + } + return seconds +} + export const JiraBlock: BlockConfig = { type: 'jira', name: 'Jira', @@ -1085,8 +1113,9 @@ Return ONLY the comment text - no explanations.`, return 'jira_retrieve' } }, - params: (params) => { + params: (params, context) => { const { oauthCredential, projectId, issueKey } = params + const operation = mapperOperation(params, context) // Use canonical param IDs (raw subBlock IDs are deleted after serialization) const effectiveProjectId = projectId ? String(projectId).trim() : '' @@ -1097,7 +1126,7 @@ Return ONLY the comment text - no explanations.`, domain: params.domain, } - switch (params.operation) { + switch (operation) { case 'create_sprint': { return { ...baseParams, @@ -1109,14 +1138,6 @@ Return ONLY the comment text - no explanations.`, } } case 'write': { - const parseCommaSeparated = (value: string | undefined): string[] | undefined => { - if (!value || value.trim() === '') return undefined - return value - .split(',') - .map((item) => item.trim()) - .filter((item) => item !== '') - } - const customFieldValue = params.customFieldValue || undefined const writeParams = { @@ -1124,13 +1145,15 @@ Return ONLY the comment text - no explanations.`, summary: params.summary || '', description: params.description || '', issueType: params.issueType || 'Task', - parent: params.parentIssue ? { key: params.parentIssue } : undefined, + parent: params.parentIssue + ? { key: params.parentIssue } + : toolCallArg(context, params.parent), assignee: params.assignee || undefined, priority: params.priority || undefined, - labels: parseCommaSeparated(params.labels), - components: parseCommaSeparated(params.components), + labels: parseList(params.labels), + components: parseList(params.components), duedate: params.duedate || undefined, - fixVersions: parseCommaSeparated(params.fixVersions), + fixVersions: parseList(params.fixVersions), reporter: params.reporter || undefined, environment: params.environment || undefined, customFieldId: params.customFieldId || undefined, @@ -1143,14 +1166,6 @@ Return ONLY the comment text - no explanations.`, } } case 'update': { - const parseCommaSeparated = (value: string | undefined): string[] | undefined => { - if (!value || value.trim() === '') return undefined - return value - .split(',') - .map((item) => item.trim()) - .filter((item) => item !== '') - } - const updateParams = { projectId: effectiveProjectId, issueKey: effectiveIssueKey, @@ -1158,21 +1173,18 @@ Return ONLY the comment text - no explanations.`, description: params.description || undefined, assignee: params.assignee || undefined, priority: params.priority || undefined, - labels: parseCommaSeparated(params.labels), - components: parseCommaSeparated(params.components), + labels: parseList(params.labels), + components: parseList(params.components), duedate: params.duedate || undefined, - fixVersions: parseCommaSeparated(params.fixVersions), + fixVersions: parseList(params.fixVersions), environment: params.environment || undefined, customFieldId: params.customFieldId || undefined, customFieldValue: params.customFieldValue || undefined, customFields: params.customFields || undefined, - parent: String(params.updateParentIssue ?? '').trim() || undefined, - notifyUsers: - params.notifyUsers === 'false' - ? false - : params.notifyUsers === 'true' - ? true - : undefined, + parent: + String(params.updateParentIssue ?? '').trim() || + toolCallArg(context, params.parent), + notifyUsers: parseOptionalBooleanInput(params.notifyUsers), } return { ...baseParams, @@ -1184,10 +1196,7 @@ Return ONLY the comment text - no explanations.`, ...baseParams, issueKey: effectiveIssueKey, ...(effectiveProjectId && { projectId: effectiveProjectId }), - includeAttachments: - params.includeAttachments === true || params.includeAttachments === 'true' - ? true - : undefined, + includeAttachments: parseOptionalBooleanInput(params.includeAttachments) || undefined, } } case 'read-bulk': { @@ -1200,7 +1209,7 @@ Return ONLY the comment text - no explanations.`, return { ...baseParams, issueKey: effectiveIssueKey, - deleteSubtasks: params.deleteSubtasks === 'true', + deleteSubtasks: parseOptionalBooleanInput(params.deleteSubtasks) === true, } } case 'assign': { @@ -1215,9 +1224,9 @@ Return ONLY the comment text - no explanations.`, ...baseParams, issueKey: effectiveIssueKey, transitionId: params.transitionId, - comment: params.transitionComment, + comment: params.transitionComment ?? toolCallArg(context, params.comment), resolution: params.resolution || undefined, - fields: params.transitionFields || undefined, + fields: params.transitionFields || toolCallArg(context, params.fields), } } case 'search': { @@ -1226,12 +1235,7 @@ Return ONLY the comment text - no explanations.`, jql: params.jql, nextPageToken: params.nextPageToken || undefined, maxResults: params.maxResults ? Number.parseInt(params.maxResults) : undefined, - fields: params.fields - ? params.fields - .split(',') - .map((f: string) => f.trim()) - .filter(Boolean) - : undefined, + fields: parseList(params.fields), expand: params.expand ? String(params.expand).trim() || undefined : undefined, } } @@ -1239,7 +1243,7 @@ Return ONLY the comment text - no explanations.`, return { ...baseParams, issueKey: effectiveIssueKey, - body: params.commentBody, + body: params.commentBody ?? toolCallArg(context, params.body), } } case 'get_comments': { @@ -1255,7 +1259,7 @@ Return ONLY the comment text - no explanations.`, ...baseParams, issueKey: effectiveIssueKey, commentId: params.commentId, - body: params.commentBody, + body: params.commentBody ?? toolCallArg(context, params.body), } } case 'delete_comment': { @@ -1269,10 +1273,7 @@ Return ONLY the comment text - no explanations.`, return { ...baseParams, issueKey: effectiveIssueKey, - includeAttachments: - params.includeAttachments === true || params.includeAttachments === 'true' - ? true - : undefined, + includeAttachments: parseOptionalBooleanInput(params.includeAttachments) || undefined, } } case 'add_attachment': { @@ -1293,21 +1294,11 @@ Return ONLY the comment text - no explanations.`, } } case 'add_worklog': { - const rawTime = params.timeSpentSeconds - const parsedTime = - rawTime !== undefined && rawTime !== null && String(rawTime).trim() !== '' - ? Number(String(rawTime).trim()) - : undefined - if (parsedTime !== undefined && (!Number.isFinite(parsedTime) || parsedTime <= 0)) { - throw new Error( - 'Time Spent (seconds) must be a positive number of seconds (e.g., 3600 for 1 hour)' - ) - } return { ...baseParams, issueKey: effectiveIssueKey, - timeSpentSeconds: parsedTime, - comment: params.worklogComment, + timeSpentSeconds: parseTimeSpentSeconds(params.timeSpentSeconds), + comment: params.worklogComment ?? toolCallArg(context, params.comment), started: params.started, } } @@ -1324,18 +1315,10 @@ Return ONLY the comment text - no explanations.`, ...baseParams, issueKey: effectiveIssueKey, worklogId: params.worklogId, - timeSpentSeconds: (() => { - const raw = params.timeSpentSecondsUpdate - if (raw === undefined || raw === null || String(raw).trim() === '') return undefined - const n = Number(String(raw).trim()) - if (!Number.isFinite(n) || n <= 0) { - throw new Error( - 'Time Spent (seconds) must be a positive number of seconds (e.g., 3600 for 1 hour)' - ) - } - return n - })(), - comment: params.worklogComment, + timeSpentSeconds: parseTimeSpentSeconds( + params.timeSpentSecondsUpdate ?? toolCallArg(context, params.timeSpentSeconds) + ), + comment: params.worklogComment ?? toolCallArg(context, params.comment), started: params.started, } } @@ -1352,7 +1335,7 @@ Return ONLY the comment text - no explanations.`, inwardIssueKey: params.inwardIssueKey, outwardIssueKey: params.outwardIssueKey, linkType: params.linkType, - comment: params.linkComment, + comment: params.linkComment ?? toolCallArg(context, params.comment), } } case 'delete_link': { @@ -1378,35 +1361,37 @@ Return ONLY the comment text - no explanations.`, case 'get_users': { return { ...baseParams, - accountId: params.userAccountId || undefined, - startAt: params.usersStartAt ? Number.parseInt(params.usersStartAt) : undefined, + accountId: params.userAccountId || toolCallArg(context, params.accountId), + startAt: params.usersStartAt + ? Number.parseInt(params.usersStartAt) + : toolCallArg(context, params.startAt), maxResults: params.usersMaxResults ? Number.parseInt(params.usersMaxResults) - : undefined, + : toolCallArg(context, params.maxResults), } } case 'search_users': { return { ...baseParams, - query: params.searchUsersQuery, + query: params.searchUsersQuery ?? toolCallArg(context, params.query), maxResults: params.searchUsersMaxResults ? Number.parseInt(params.searchUsersMaxResults) - : undefined, + : toolCallArg(context, params.maxResults), startAt: params.searchUsersStartAt ? Number.parseInt(params.searchUsersStartAt) - : undefined, + : toolCallArg(context, params.startAt), } } case 'list_projects': { return { ...baseParams, - query: params.projectSearchQuery || undefined, + query: params.projectSearchQuery || toolCallArg(context, params.query), startAt: params.listProjectsStartAt ? Number.parseInt(params.listProjectsStartAt) - : undefined, + : toolCallArg(context, params.startAt), maxResults: params.listProjectsMaxResults ? Number.parseInt(params.listProjectsMaxResults) - : undefined, + : toolCallArg(context, params.maxResults), } } case 'get_project': { diff --git a/apps/sim/blocks/blocks/jira_service_management.test.ts b/apps/sim/blocks/blocks/jira_service_management.test.ts index 2d6d40439f4..2e7f2736f98 100644 --- a/apps/sim/blocks/blocks/jira_service_management.test.ts +++ b/apps/sim/blocks/blocks/jira_service_management.test.ts @@ -136,3 +136,40 @@ describe.each(PAGINATED_CASES.map((testCase) => [testCase.operation, testCase] a }) } ) + +/** + * What a tool call (agent, Pi, Human v2) hands the tool: the merged stored-row and model args, + * overlaid with the block mapper's output. The operation arrives only in `context`. + */ +function toolCallParams(operation: string, args: Record) { + const mapper = JiraServiceManagementBlock.tools.config?.params + if (!mapper) throw new Error('Block is missing tools.config.params') + return { ...args, ...mapper({ domain: DOMAIN, ...args }, { operation }) } +} + +describe('JiraServiceManagementBlock tool calls', () => { + it('maps fields set on the agent tool row to the tool param names', () => { + expect( + toolCallParams('add_comment', { issueIdOrKey: 'SD-1', commentBody: 'From the row' }).body + ).toBe('From the row') + expect(toolCallParams('get_queues', { serviceDeskId: '1', startIndex: '5' }).start).toBe(5) + }) + + it.each([ + ['add_comment', { issueIdOrKey: 'SD-1', body: 'Model comment', isPublic: true }], + ['get_comments', { issueIdOrKey: 'SD-1', isPublic: false, start: 10, limit: 5 }], + ['create_organization', { name: 'Acme' }], + ['add_participants', { issueIdOrKey: 'SD-1', accountIds: 'a,b' }], + ['answer_approval', { issueIdOrKey: 'SD-1', approvalId: '2', decision: 'approve' }], + ['save_form_answers', { issueIdOrKey: 'SD-1', formId: 'f', answers: { '1': { text: 'x' } } }], + ['copy_forms', { sourceIssueIdOrKey: 'SD-1', targetIssueIdOrKey: 'SD-2', formIds: ['u1'] }], + [ + 'create_request', + { serviceDeskId: '1', requestTypeId: '2', summary: 's', requestFieldValues: { a: 1 } }, + ], + ['search_objects_aql', { qlQuery: 'Name = x', page: 2, objectTypeId: '7', workspaceId: 'w' }], + ['create_object', { objectTypeId: '7', attributes: [{ objectTypeAttributeId: '1' }] }], + ])('keeps model args for %s without throwing', (operation, args) => { + expect(toolCallParams(operation, args)).toMatchObject(args) + }) +}) diff --git a/apps/sim/blocks/blocks/jira_service_management.ts b/apps/sim/blocks/blocks/jira_service_management.ts index 52b59ff2da5..6dabfb552be 100644 --- a/apps/sim/blocks/blocks/jira_service_management.ts +++ b/apps/sim/blocks/blocks/jira_service_management.ts @@ -2,6 +2,7 @@ import { JiraServiceManagementIcon } from '@/components/icons' import { getDefaultToolScopesForProvider } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation, parseOptionalBooleanInput, toolCallArg } from '@/blocks/utils' import { getTrigger } from '@/triggers' /** Operations that accept Atlassian's `start`/`limit` pagination query params. */ @@ -23,12 +24,22 @@ const PAGINATED_OPERATIONS = [ * Coerce an optional numeric block input into an integer, returning undefined for * empty or non-numeric values so no `NaN` reaches the API query string. */ -function toOptionalInt(value: string | undefined): number | undefined { +function toOptionalInt(value: unknown): number | undefined { if (!value) return undefined - const parsed = Number.parseInt(value, 10) + const parsed = Number.parseInt(String(value), 10) return Number.isNaN(parsed) ? undefined : parsed } +/** Parses a JSON string input; a model-sent object or array is already parsed and passes through. */ +function parseJsonInput(value: unknown, errorMessage: string): unknown { + if (typeof value !== 'string') return value + try { + return JSON.parse(value) + } catch { + throw new Error(errorMessage) + } +} + /** * Parse the Assets attributes input into the API payload array. Accepts either a * JSON string (from the block input) or an already-parsed array (from a dynamic @@ -1177,7 +1188,12 @@ Return ONLY the comment text - no explanations.`, return 'jsm_get_service_desks' } }, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) + const pagination = { + start: toOptionalInt(params.startIndex) ?? toolCallArg(context, params.start), + limit: toOptionalInt(params.maxResults) ?? toolCallArg(context, params.limit), + } const baseParams = { oauthCredential: params.oauthCredential, domain: params.domain, @@ -1187,15 +1203,14 @@ Return ONLY the comment text - no explanations.`, // route resolves the site's single Assets workspace automatically. const assetBaseParams = { ...baseParams, - workspaceId: params.assetWorkspaceId || undefined, + workspaceId: params.assetWorkspaceId || toolCallArg(context, params.workspaceId), } - switch (params.operation) { + switch (operation) { case 'get_service_desks': return { ...baseParams, - start: toOptionalInt(params.startIndex), - limit: toOptionalInt(params.maxResults), + ...pagination, } case 'get_request_types': if (!params.serviceDeskId) { @@ -1206,8 +1221,7 @@ Return ONLY the comment text - no explanations.`, serviceDeskId: params.serviceDeskId, searchQuery: params.searchQuery, groupId: params.groupId, - start: toOptionalInt(params.startIndex), - limit: toOptionalInt(params.maxResults), + ...pagination, } case 'create_request': if (!params.serviceDeskId) { @@ -1229,22 +1243,10 @@ Return ONLY the comment text - no explanations.`, requestParticipants: params.requestParticipants, channel: params.channel, requestFieldValues: params.requestFieldValues - ? (() => { - try { - return JSON.parse(params.requestFieldValues) - } catch { - throw new Error('requestFieldValues must be valid JSON') - } - })() + ? parseJsonInput(params.requestFieldValues, 'requestFieldValues must be valid JSON') : undefined, formAnswers: params.formAnswers - ? (() => { - try { - return JSON.parse(params.formAnswers) - } catch { - throw new Error('formAnswers must be valid JSON') - } - })() + ? parseJsonInput(params.formAnswers, 'formAnswers must be valid JSON') : undefined, } case 'get_request': @@ -1263,32 +1265,33 @@ Return ONLY the comment text - no explanations.`, requestOwnership: params.requestOwnership, requestStatus: params.requestStatus, approvalStatus: - params.requestOwnership === 'APPROVER' + (params.requestOwnership === 'APPROVER' ? params.requestApprovalStatus || undefined - : undefined, + : undefined) ?? toolCallArg(context, params.approvalStatus), organizationId: - params.requestOwnership === 'ORGANIZATION' + (params.requestOwnership === 'ORGANIZATION' ? params.requestOrganizationId || undefined - : undefined, - requestTypeId: params.requestTypeFilter || undefined, + : undefined) ?? toolCallArg(context, params.organizationId), + requestTypeId: params.requestTypeFilter || toolCallArg(context, params.requestTypeId), searchTerm: params.searchTerm, expand: params.expand, - start: toOptionalInt(params.startIndex), - limit: toOptionalInt(params.maxResults), + ...pagination, } - case 'add_comment': + case 'add_comment': { if (!params.issueIdOrKey) { throw new Error('Issue ID or key is required') } - if (!params.commentBody) { + const body = params.commentBody ?? toolCallArg(context, params.body) + if (!body) { throw new Error('Comment body is required') } return { ...baseParams, issueIdOrKey: params.issueIdOrKey, - body: params.commentBody, - isPublic: params.isPublic === 'true', + body, + isPublic: parseOptionalBooleanInput(params.isPublic) === true, } + } case 'get_comments': if (!params.issueIdOrKey) { throw new Error('Issue ID or key is required') @@ -1296,11 +1299,16 @@ Return ONLY the comment text - no explanations.`, return { ...baseParams, issueIdOrKey: params.issueIdOrKey, - isPublic: params.includePublicComments === 'false' ? false : undefined, - internal: params.includeInternalComments === 'false' ? false : undefined, + isPublic: + params.includePublicComments === 'false' + ? false + : toolCallArg(context, params.isPublic), + internal: + params.includeInternalComments === 'false' + ? false + : toolCallArg(context, params.internal), expand: params.expand, - start: toOptionalInt(params.startIndex), - limit: toOptionalInt(params.maxResults), + ...pagination, } case 'get_customers': if (!params.serviceDeskId) { @@ -1309,9 +1317,8 @@ Return ONLY the comment text - no explanations.`, return { ...baseParams, serviceDeskId: params.serviceDeskId, - query: params.customerQuery, - start: toOptionalInt(params.startIndex), - limit: toOptionalInt(params.maxResults), + query: params.customerQuery ?? toolCallArg(context, params.query), + ...pagination, } case 'add_customer': { if (!params.serviceDeskId) { @@ -1333,8 +1340,7 @@ Return ONLY the comment text - no explanations.`, return { ...baseParams, serviceDeskId: params.serviceDeskId, - start: toOptionalInt(params.startIndex), - limit: toOptionalInt(params.maxResults), + ...pagination, } case 'get_queues': if (!params.serviceDeskId) { @@ -1343,9 +1349,8 @@ Return ONLY the comment text - no explanations.`, return { ...baseParams, serviceDeskId: params.serviceDeskId, - includeCount: params.includeCount === 'true', - start: toOptionalInt(params.startIndex), - limit: toOptionalInt(params.maxResults), + includeCount: parseOptionalBooleanInput(params.includeCount) === true, + ...pagination, } case 'get_sla': if (!params.issueIdOrKey) { @@ -1354,8 +1359,7 @@ Return ONLY the comment text - no explanations.`, return { ...baseParams, issueIdOrKey: params.issueIdOrKey, - start: toOptionalInt(params.startIndex), - limit: toOptionalInt(params.maxResults), + ...pagination, } case 'get_transitions': if (!params.issueIdOrKey) { @@ -1364,8 +1368,7 @@ Return ONLY the comment text - no explanations.`, return { ...baseParams, issueIdOrKey: params.issueIdOrKey, - start: toOptionalInt(params.startIndex), - limit: toOptionalInt(params.maxResults), + ...pagination, } case 'transition_request': if (!params.issueIdOrKey) { @@ -1378,16 +1381,15 @@ Return ONLY the comment text - no explanations.`, ...baseParams, issueIdOrKey: params.issueIdOrKey, transitionId: params.transitionId, - comment: params.transitionComment, + comment: params.transitionComment ?? toolCallArg(context, params.comment), } - case 'create_organization': - if (!params.organizationName) { + case 'create_organization': { + const name = params.organizationName ?? toolCallArg(context, params.name) + if (!name) { throw new Error('Organization name is required') } - return { - ...baseParams, - name: params.organizationName, - } + return { ...baseParams, name } + } case 'add_organization': if (!params.serviceDeskId) { throw new Error('Service Desk ID is required') @@ -1407,21 +1409,19 @@ Return ONLY the comment text - no explanations.`, return { ...baseParams, issueIdOrKey: params.issueIdOrKey, - start: toOptionalInt(params.startIndex), - limit: toOptionalInt(params.maxResults), + ...pagination, } - case 'add_participants': + case 'add_participants': { if (!params.issueIdOrKey) { throw new Error('Issue ID or key is required') } - if (!params.participantAccountIds) { + const accountIds = + params.participantAccountIds ?? toolCallArg(context, params.accountIds) + if (!accountIds) { throw new Error('Account IDs are required') } - return { - ...baseParams, - issueIdOrKey: params.issueIdOrKey, - accountIds: params.participantAccountIds, - } + return { ...baseParams, issueIdOrKey: params.issueIdOrKey, accountIds } + } case 'get_approvals': if (!params.issueIdOrKey) { throw new Error('Issue ID or key is required') @@ -1429,25 +1429,26 @@ Return ONLY the comment text - no explanations.`, return { ...baseParams, issueIdOrKey: params.issueIdOrKey, - start: toOptionalInt(params.startIndex), - limit: toOptionalInt(params.maxResults), + ...pagination, } - case 'answer_approval': + case 'answer_approval': { if (!params.issueIdOrKey) { throw new Error('Issue ID or key is required') } if (!params.approvalId) { throw new Error('Approval ID is required') } - if (!params.approvalDecision) { + const decision = params.approvalDecision ?? toolCallArg(context, params.decision) + if (!decision) { throw new Error('Decision is required') } return { ...baseParams, issueIdOrKey: params.issueIdOrKey, approvalId: params.approvalId, - decision: params.approvalDecision, + decision, } + } case 'get_request_type_fields': if (!params.serviceDeskId) { throw new Error('Service Desk ID is required') @@ -1500,28 +1501,24 @@ Return ONLY the comment text - no explanations.`, issueIdOrKey: params.issueIdOrKey, formTemplateId: params.formTemplateId, } - case 'save_form_answers': + case 'save_form_answers': { if (!params.issueIdOrKey) { throw new Error('Issue ID or key is required') } if (!params.formId) { throw new Error('Form ID is required') } - if (!params.formAnswers) { + const answers = params.formAnswers ?? toolCallArg(context, params.answers) + if (!answers) { throw new Error('Form answers are required') } return { ...baseParams, issueIdOrKey: params.issueIdOrKey, formId: params.formId, - answers: (() => { - try { - return JSON.parse(params.formAnswers) - } catch { - throw new Error('formAnswers must be valid JSON') - } - })(), + answers: parseJsonInput(answers, 'formAnswers must be valid JSON'), } + } case 'submit_form': if (!params.issueIdOrKey) { throw new Error('Issue ID or key is required') @@ -1619,6 +1616,7 @@ Return ONLY the comment text - no explanations.`, targetIssueIdOrKey: params.targetIssueIdOrKey, formIds: params.formIds ? (() => { + if (Array.isArray(params.formIds)) return params.formIds try { const parsed = JSON.parse(params.formIds) if (!Array.isArray(parsed)) { @@ -1636,76 +1634,114 @@ Return ONLY the comment text - no explanations.`, case 'list_object_schemas': return { ...assetBaseParams, - startAt: toOptionalInt(params.assetStartAt), - maxResults: toOptionalInt(params.assetMaxResults), - includeCounts: params.assetIncludeCounts === 'true' ? true : undefined, - } - case 'get_object_schema': - if (!params.assetSchemaId) { + startAt: toOptionalInt(params.assetStartAt) ?? toolCallArg(context, params.startAt), + maxResults: + toOptionalInt(params.assetMaxResults) ?? toolCallArg(context, params.maxResults), + includeCounts: + params.assetIncludeCounts === 'true' + ? true + : toolCallArg(context, params.includeCounts), + } + case 'get_object_schema': { + const schemaId = params.assetSchemaId ?? toolCallArg(context, params.schemaId) + if (!schemaId) { throw new Error('Schema ID is required') } - return { ...assetBaseParams, schemaId: params.assetSchemaId } - case 'list_object_types': - if (!params.assetSchemaId) { + return { ...assetBaseParams, schemaId } + } + case 'list_object_types': { + const schemaId = params.assetSchemaId ?? toolCallArg(context, params.schemaId) + if (!schemaId) { throw new Error('Schema ID is required') } return { ...assetBaseParams, - schemaId: params.assetSchemaId, - excludeAbstract: params.assetExcludeAbstract === 'true' ? true : undefined, + schemaId, + excludeAbstract: + params.assetExcludeAbstract === 'true' + ? true + : toolCallArg(context, params.excludeAbstract), } - case 'get_object_type_attributes': - if (!params.assetObjectTypeId) { + } + case 'get_object_type_attributes': { + const objectTypeId = + params.assetObjectTypeId ?? toolCallArg(context, params.objectTypeId) + if (!objectTypeId) { throw new Error('Object type ID is required') } return { ...assetBaseParams, - objectTypeId: params.assetObjectTypeId, - onlyValueEditable: params.assetOnlyValueEditable === 'true' ? true : undefined, - query: params.assetAttributeQuery || undefined, + objectTypeId, + onlyValueEditable: + params.assetOnlyValueEditable === 'true' + ? true + : toolCallArg(context, params.onlyValueEditable), + query: params.assetAttributeQuery || toolCallArg(context, params.query), } - case 'search_objects_aql': - if (!params.assetQlQuery) { + } + case 'search_objects_aql': { + const qlQuery = params.assetQlQuery ?? toolCallArg(context, params.qlQuery) + if (!qlQuery) { throw new Error('AQL query is required') } return { ...assetBaseParams, - qlQuery: params.assetQlQuery, - page: toOptionalInt(params.assetPage), - resultsPerPage: toOptionalInt(params.assetResultsPerPage), - includeAttributes: params.assetIncludeAttributes === 'false' ? false : undefined, - objectTypeId: params.assetObjectTypeId || undefined, - objectSchemaId: params.assetObjectSchemaId || undefined, + qlQuery, + page: toOptionalInt(params.assetPage) ?? toolCallArg(context, params.page), + resultsPerPage: + toOptionalInt(params.assetResultsPerPage) ?? + toolCallArg(context, params.resultsPerPage), + includeAttributes: + params.assetIncludeAttributes === 'false' + ? false + : toolCallArg(context, params.includeAttributes), + objectTypeId: params.assetObjectTypeId || toolCallArg(context, params.objectTypeId), + objectSchemaId: + params.assetObjectSchemaId || toolCallArg(context, params.objectSchemaId), } - case 'get_object': - if (!params.assetObjectId) { + } + case 'get_object': { + const objectId = params.assetObjectId ?? toolCallArg(context, params.objectId) + if (!objectId) { throw new Error('Object ID is required') } - return { ...assetBaseParams, objectId: params.assetObjectId } - case 'create_object': - if (!params.assetObjectTypeId) { + return { ...assetBaseParams, objectId } + } + case 'create_object': { + const objectTypeId = + params.assetObjectTypeId ?? toolCallArg(context, params.objectTypeId) + if (!objectTypeId) { throw new Error('Object type ID is required') } return { ...assetBaseParams, - objectTypeId: params.assetObjectTypeId, - attributes: parseAssetAttributes(params.assetAttributes), + objectTypeId, + attributes: parseAssetAttributes( + params.assetAttributes ?? toolCallArg(context, params.attributes) + ), } - case 'update_object': - if (!params.assetObjectId) { + } + case 'update_object': { + const objectId = params.assetObjectId ?? toolCallArg(context, params.objectId) + if (!objectId) { throw new Error('Object ID is required') } return { ...assetBaseParams, - objectId: params.assetObjectId, - attributes: parseAssetAttributes(params.assetAttributes), - objectTypeId: params.assetObjectTypeId || undefined, + objectId, + attributes: parseAssetAttributes( + params.assetAttributes ?? toolCallArg(context, params.attributes) + ), + objectTypeId: params.assetObjectTypeId || toolCallArg(context, params.objectTypeId), } - case 'delete_object': - if (!params.assetObjectId) { + } + case 'delete_object': { + const objectId = params.assetObjectId ?? toolCallArg(context, params.objectId) + if (!objectId) { throw new Error('Object ID is required') } - return { ...assetBaseParams, objectId: params.assetObjectId } + return { ...assetBaseParams, objectId } + } default: return baseParams } diff --git a/apps/sim/blocks/blocks/microsoft_ad.test.ts b/apps/sim/blocks/blocks/microsoft_ad.test.ts index 12f343f31a8..85d1be88a5e 100644 --- a/apps/sim/blocks/blocks/microsoft_ad.test.ts +++ b/apps/sim/blocks/blocks/microsoft_ad.test.ts @@ -84,10 +84,14 @@ describe('MicrosoftAdBlock', () => { * the per-operation fields (`signInFilter`, `deviceSearch`, `membershipScope`) are never rendered. */ describe('MicrosoftAdBlock agent tool calls', () => { - const agentCall = (operation: string, args: Record): Record => { - const inputs = { ...args, operation } - return { ...inputs, ...buildParams(inputs, { operation }) } - } + /** A tool call carries the operation only in `context`, never in the merged params. */ + const agentCall = ( + operation: string, + args: Record + ): Record => ({ + ...args, + ...buildParams(args, { operation }), + }) it('keeps the model filter on an operation with a dedicated filter field', () => { const mapped = agentCall('list_sign_ins', { filter: 'status/errorCode eq 0' }) @@ -105,6 +109,21 @@ describe('MicrosoftAdBlock agent tool calls', () => { ) }) + it('forwards a dedicated filter saved on the tool row', () => { + const mapped = agentCall('list_sign_ins', { signInFilter: 'status/errorCode ne 0' }) + expect(mapped.filter).toBe('status/errorCode ne 0') + }) + + it('keeps boolean group flags the model sends', () => { + const mapped = agentCall('create_group', { + displayName: 'Eng', + mailEnabled: true, + securityEnabled: false, + }) + expect(mapped.mailEnabled).toBe(true) + expect(mapped.securityEnabled).toBe(false) + }) + it('drops a shared filter left over on the canvas for an operation with its own field', () => { const inputs = { operation: 'list_sign_ins', filter: 'stale' } expect({ ...inputs, ...buildParams(inputs) }.filter).toBeUndefined() diff --git a/apps/sim/blocks/blocks/microsoft_ad.ts b/apps/sim/blocks/blocks/microsoft_ad.ts index 6e46d5e6bb6..2e5e0b07ba6 100644 --- a/apps/sim/blocks/blocks/microsoft_ad.ts +++ b/apps/sim/blocks/blocks/microsoft_ad.ts @@ -2,7 +2,15 @@ import { AzureIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { parseOptionalBooleanInput, toolCallArg } from '@/blocks/utils' +import { mapperOperation, parseOptionalBooleanInput, toolCallArg } from '@/blocks/utils' + +/** + * A Yes/No dropdown value as a boolean: `'true'` is true and any other string (including a blank + * one) is false, while a boolean a model sent on a tool call passes through unchanged. + */ +function dropdownFlag(value: unknown): boolean { + return typeof value === 'boolean' ? value : value === 'true' +} /** Operations that act on a single user and therefore require the User ID field. */ const USER_ID_OPERATIONS = [ @@ -856,54 +864,55 @@ export const MicrosoftAdBlock: BlockConfig = { config: { tool: (params) => `microsoft_ad_${params.operation}`, params: (params, context) => { + const operation = mapperOperation(params, context) const result: Record = {} const top = Number(params.top) result.top = params.top && Number.isFinite(top) ? top : undefined if (params.nextLink) result.nextLink = params.nextLink const values = params as Record result.filter = - values[FILTER_FIELD_BY_OPERATION[params.operation]] || + values[FILTER_FIELD_BY_OPERATION[operation]] || toolCallArg(context, params.filter) || undefined result.search = - values[SEARCH_FIELD_BY_OPERATION[params.operation]] || + values[SEARCH_FIELD_BY_OPERATION[operation]] || toolCallArg(context, params.search) || undefined - if (params.operation === 'get_user') { + if (operation === 'get_user') { result.includeManager = params.includeManager === true || params.includeManager === 'true' } - if (params.operation === 'list_user_memberships') { + if (operation === 'list_user_memberships') { result.transitive = params.membershipScope ? params.membershipScope === 'transitive' : (parseOptionalBooleanInput(toolCallArg(context, params.transitive)) ?? false) } - if (params.operation === 'set_password') { - result.forceChangePasswordNextSignIn = params.forceChangePasswordNextSignIn !== 'false' - result.forceChangePasswordNextSignInWithMfa = params.forceChangePasswordNextSignInWithMfa - ? params.forceChangePasswordNextSignInWithMfa === 'true' - : undefined + if (operation === 'set_password') { + result.forceChangePasswordNextSignIn = + parseOptionalBooleanInput(params.forceChangePasswordNextSignIn) ?? true + result.forceChangePasswordNextSignInWithMfa = parseOptionalBooleanInput( + params.forceChangePasswordNextSignInWithMfa + ) } - if (params.operation === 'update_user') { - result.accountEnabled = params.accountEnabled - ? params.accountEnabled === 'true' - : undefined - } else if (params.operation === 'create_user') { + if (operation === 'update_user') { + result.accountEnabled = parseOptionalBooleanInput(params.accountEnabled) + } else if (operation === 'create_user') { result.accountEnabled = params.accountEnabledCreate ? params.accountEnabledCreate === 'true' - : undefined + : parseOptionalBooleanInput(toolCallArg(context, params.accountEnabled)) } - if (params.mailEnabled !== undefined) result.mailEnabled = params.mailEnabled === 'true' + if (params.mailEnabled !== undefined) result.mailEnabled = dropdownFlag(params.mailEnabled) if (params.securityEnabled !== undefined) - result.securityEnabled = params.securityEnabled === 'true' + result.securityEnabled = dropdownFlag(params.securityEnabled) // Map group-specific fields to tool param names if (params.groupDisplayName) result.displayName = params.groupDisplayName if (params.groupMailNickname) result.mailNickname = params.groupMailNickname if (params.groupDescription) result.description = params.groupDescription if (params.groupTypes !== undefined) result.groupTypes = params.groupTypes - if (params.operation === 'update_group') { + if (operation === 'update_group') { result.visibility = params.visibility || undefined - } else if (params.operation === 'create_group') { - result.visibility = params.visibilityCreate || undefined + } else if (operation === 'create_group') { + result.visibility = + params.visibilityCreate || toolCallArg(context, params.visibility) || undefined } return result }, diff --git a/apps/sim/blocks/blocks/microsoft_dataverse.test.ts b/apps/sim/blocks/blocks/microsoft_dataverse.test.ts new file mode 100644 index 00000000000..8a87a87e509 --- /dev/null +++ b/apps/sim/blocks/blocks/microsoft_dataverse.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from 'vitest' +import { MicrosoftDataverseBlock } from '@/blocks/blocks/microsoft_dataverse' +import type { BlockToolParamsContext } from '@/blocks/types' + +/** + * The params the tool receives: both the canvas handler and the agent tool path spread the mapper's + * result over the inputs, so a key the mapper omits still reaches the tool raw. + */ +const forwarded = ( + inputs: Record, + context?: BlockToolParamsContext +): Record => ({ + ...inputs, + ...MicrosoftDataverseBlock.tools.config.params(inputs, context), +}) + +describe('MicrosoftDataverseBlock params mapper', () => { + it('keeps a record-column select saved for another operation out of the metadata request', () => { + const mapped = forwarded({ + operation: 'get_entity_metadata', + entityLogicalName: 'account', + select: 'name,accountid', + }) + expect(mapped.select).toBeUndefined() + }) + + it('forwards the model select on a get_entity_metadata tool call', () => { + const mapped = forwarded( + { entityLogicalName: 'account', select: 'LogicalName,EntitySetName' }, + { operation: 'get_entity_metadata' } + ) + expect(mapped.select).toBe('LogicalName,EntitySetName') + }) + + it('forwards search entities saved on the tool row as the tool entities param', () => { + const searchEntities = '[{"Name":"account"}]' + const mapped = forwarded({ searchTerm: 'contoso', searchEntities }, { operation: 'search' }) + expect(mapped.entities).toBe(searchEntities) + }) +}) diff --git a/apps/sim/blocks/blocks/microsoft_dataverse.ts b/apps/sim/blocks/blocks/microsoft_dataverse.ts index d12ccbaa543..63f75cab1e6 100644 --- a/apps/sim/blocks/blocks/microsoft_dataverse.ts +++ b/apps/sim/blocks/blocks/microsoft_dataverse.ts @@ -3,7 +3,7 @@ import { MicrosoftDataverseIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput } from '@/blocks/utils' +import { mapperOperation, normalizeFileInput, toolCallArg } from '@/blocks/utils' /** Canonical upload pair for the file column payload, basic then advanced. */ const FILE_FIELD = ['uploadFile', 'fileReference'] as const @@ -642,8 +642,9 @@ Return ONLY the expand expression - no $expand= prefix, no explanations.`, ], config: { tool: (params) => `microsoft_dataverse_${params.operation}`, - params: (params) => { - const { credential, operation, file, ...rest } = params + params: (params, context) => { + const operation = mapperOperation(params, context) + const { credential, file, ...rest } = params const cleanParams: Record = { credential, @@ -667,11 +668,10 @@ Return ONLY the expand expression - no $expand= prefix, no explanations.`, rest.parameters = undefined } if (operation === 'get_entity_metadata') { - if (rest.metadataSelect) { - cleanParams.select = rest.metadataSelect - } - // The shared `select` subBlock belongs to list/get record operations - clear it so a - // stale record-column $select can't override or fight the mapped metadataSelect value + // The shared `select` subBlock belongs to list/get record operations, so a stale + // record-column $select must not reach the metadata request; only a tool call's own + // `select` arg stands in for an empty metadataSelect. + cleanParams.select = rest.metadataSelect || toolCallArg(context, rest.select) || undefined rest.select = undefined } // Always clean up mapped subBlock IDs so they don't leak through the loop below diff --git a/apps/sim/blocks/blocks/microsoft_excel.ts b/apps/sim/blocks/blocks/microsoft_excel.ts index c4e6be972d7..0168fc10ee8 100644 --- a/apps/sim/blocks/blocks/microsoft_excel.ts +++ b/apps/sim/blocks/blocks/microsoft_excel.ts @@ -2,7 +2,7 @@ import { MicrosoftExcelIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { createVersionedToolSelector } from '@/blocks/utils' +import { createVersionedToolSelector, isToolCall, mapperOperation } from '@/blocks/utils' /** Maps the read/write operation to its `_v2` tool id, falling back to read on unknown ops. */ const versionedReadWriteSelector = createVersionedToolSelector>({ @@ -66,7 +66,10 @@ function optionalNumber(value: unknown): number | undefined { return num } -/** Normalizes stored agent inputs when the selected operation is carried outside the parameter map. */ +/** + * Normalizes tool-call params (a stored tool row merged with model args keyed by the tool's own + * param names) and canvas inputs that carry no operation, without the per-operation validation. + */ function normalizeExcelAgentParams(params: Record, separateSheet: boolean) { const result: Record = { ...params } for (const field of ['index', 'top', 'skip', 'position', 'fontSize', 'sortColumn']) { @@ -702,8 +705,9 @@ Return ONLY the JSON array - no explanations, no markdown, no extra text.`, throw new Error(`Invalid Microsoft Excel operation: ${params.operation}`) } }, - params: (params) => { - if (!params.operation) return normalizeExcelAgentParams(params, false) + params: (params, context) => { + const operation = mapperOperation(params, context) + if (isToolCall(context) || !operation) return normalizeExcelAgentParams(params, false) const { oauthCredential, values, @@ -712,7 +716,6 @@ Return ONLY the JSON array - no explanations, no markdown, no extra text.`, worksheetName, driveId, range, - operation, applyTo, fillColor, fontBold, @@ -1845,8 +1848,9 @@ Return ONLY the JSON array - no explanations, no markdown, no extra text.`, return versionedReadWriteSelector(params) } }, - params: (params) => { - if (!params.operation) return normalizeExcelAgentParams(params, true) + params: (params, context) => { + const operation = mapperOperation(params, context) + if (isToolCall(context) || !operation) return normalizeExcelAgentParams(params, true) const { oauthCredential, values, @@ -1856,7 +1860,6 @@ Return ONLY the JSON array - no explanations, no markdown, no extra text.`, driveId, siteId: _siteId, fileSource: _fileSource, - operation, applyTo, fillColor, fontBold, diff --git a/apps/sim/blocks/blocks/microsoft_planner.test.ts b/apps/sim/blocks/blocks/microsoft_planner.test.ts new file mode 100644 index 00000000000..4481f936c1d --- /dev/null +++ b/apps/sim/blocks/blocks/microsoft_planner.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from 'vitest' +import { MicrosoftPlannerBlock } from '@/blocks/blocks/microsoft_planner' +import type { BlockToolParamsContext } from '@/blocks/types' + +/** What the tool receives: the mapper's result spread over its own input, as both callers merge it. */ +const forwarded = (inputs: Record, context?: BlockToolParamsContext) => ({ + ...inputs, + ...(MicrosoftPlannerBlock.tools.config?.params?.(inputs, context) ?? {}), +}) + +describe('MicrosoftPlannerBlock tool-call params', () => { + it('keeps the model-supplied task id on an update', () => { + const result = forwarded( + { oauthCredential: 'cred', taskId: 'task-1', etag: 'W/"1"', title: 'Renamed' }, + { operation: 'update_task' } + ) + + expect(result.taskId).toBe('task-1') + }) + + it('keeps the model-supplied plan title', () => { + const result = forwarded( + { oauthCredential: 'cred', groupId: 'group-1', title: 'Q3 plan' }, + { operation: 'create_plan' } + ) + + expect(result.title).toBe('Q3 plan') + }) + + it('maps the stored update-task picker and forwards an object checklist', () => { + const checklist = { 'item-1': { title: 'Review', isChecked: false } } + const result = forwarded( + { oauthCredential: 'cred', updateTaskId: ' task-2 ', etag: 'W/"2"', checklist }, + { operation: 'update_task_details' } + ) + + expect(result.taskId).toBe('task-2') + expect(result.checklist).toEqual(checklist) + }) +}) diff --git a/apps/sim/blocks/blocks/microsoft_planner.ts b/apps/sim/blocks/blocks/microsoft_planner.ts index b5fead93b20..0beeee4ff5a 100644 --- a/apps/sim/blocks/blocks/microsoft_planner.ts +++ b/apps/sim/blocks/blocks/microsoft_planner.ts @@ -2,6 +2,7 @@ import { MicrosoftPlannerIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' interface MicrosoftPlannerBlockParams { oauthCredential: string @@ -571,10 +572,10 @@ Return ONLY the comma-separated category keys - no explanations, no extra text.` throw new Error(`Invalid Microsoft Planner operation: ${params.operation}`) } }, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { oauthCredential, - operation, groupId, planId, readTaskId, // Canonical param from taskSelector (basic) or manualReadTaskId (advanced) for read_task @@ -606,7 +607,10 @@ Return ONLY the comma-separated category keys - no explanations, no extra text.` } const effectiveReadTaskId = readTaskId ? String(readTaskId).trim() : '' - const effectiveUpdateTaskId = updateTaskId ? String(updateTaskId).trim() : '' + const effectiveUpdateTaskId = + (updateTaskId ? String(updateTaskId).trim() : '') || + toolCallArg(context, rest.taskId) || + '' const effectiveBucketId = (bucketIdForRead || bucketId || '').trim() if (operation === 'list_plans') { @@ -624,7 +628,7 @@ Return ONLY the comma-separated category keys - no explanations, no extra text.` return { ...baseParams, groupId: groupId?.trim(), - title: planTitle?.trim(), + title: planTitle?.trim() || toolCallArg(context, title), } } @@ -633,7 +637,7 @@ Return ONLY the comma-separated category keys - no explanations, no extra text.` ...baseParams, planId: planId?.trim(), etag: etag?.trim(), - title: planTitle?.trim(), + title: planTitle?.trim() || toolCallArg(context, title), } } @@ -650,10 +654,10 @@ Return ONLY the comma-separated category keys - no explanations, no extra text.` planId: planId?.trim(), etag: etag?.trim(), } - if (categoryDescriptions?.trim()) { + if (typeof categoryDescriptions === 'string' && categoryDescriptions.trim()) { updatePlanDetailsParams.categoryDescriptions = categoryDescriptions.trim() } - if (sharedWith?.trim()) { + if (typeof sharedWith === 'string' && sharedWith.trim()) { updatePlanDetailsParams.sharedWith = sharedWith.trim() } return updatePlanDetailsParams @@ -813,10 +817,10 @@ Return ONLY the comma-separated category keys - no explanations, no extra text.` if (description?.trim()) { updateDetailsParams.description = description.trim() } - if (checklist?.trim()) { + if (typeof checklist === 'string' && checklist.trim()) { updateDetailsParams.checklist = checklist.trim() } - if (references?.trim()) { + if (typeof references === 'string' && references.trim()) { updateDetailsParams.references = references.trim() } if (previewType?.trim()) { diff --git a/apps/sim/blocks/blocks/microsoft_teams.test.ts b/apps/sim/blocks/blocks/microsoft_teams.test.ts new file mode 100644 index 00000000000..e8d31d52933 --- /dev/null +++ b/apps/sim/blocks/blocks/microsoft_teams.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from 'vitest' +import { MicrosoftTeamsBlock } from '@/blocks/blocks/microsoft_teams' +import type { BlockToolParamsContext } from '@/blocks/types' + +/** What the tool receives: the mapper's result spread over its own input, as both callers merge it. */ +const forwarded = (inputs: Record, context?: BlockToolParamsContext) => ({ + ...inputs, + ...(MicrosoftTeamsBlock.tools.config?.params?.(inputs, context) ?? {}), +}) + +describe('MicrosoftTeamsBlock tool-call params', () => { + it('sends a single attached file as the file list the tool expects', () => { + const file = { + name: 'report.pdf', + key: 'workspace/report.pdf', + size: 10, + type: 'application/pdf', + } + const result = forwarded( + { oauthCredential: 'cred', chatId: 'chat-1', content: 'See attached', files: file }, + { operation: 'write_chat' } + ) + + expect(result.files).toEqual([file]) + }) +}) diff --git a/apps/sim/blocks/blocks/microsoft_teams.ts b/apps/sim/blocks/blocks/microsoft_teams.ts index 978da9e3382..22ac8c149ab 100644 --- a/apps/sim/blocks/blocks/microsoft_teams.ts +++ b/apps/sim/blocks/blocks/microsoft_teams.ts @@ -2,7 +2,7 @@ import { MicrosoftTeamsIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput } from '@/blocks/utils' +import { mapperOperation, normalizeFileInput } from '@/blocks/utils' import { getTrigger } from '@/triggers' /** @@ -514,10 +514,10 @@ export const MicrosoftTeamsBlock: BlockConfig = { return 'microsoft_teams_read_chat' } }, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { oauthCredential, - operation, teamId, // Canonical param from teamSelector (basic) or manualTeamId (advanced) chatId, // Canonical param from chatSelector (basic) or manualChatId (advanced) channelId, // Canonical param from channelSelector (basic) or manualChannelId (advanced) diff --git a/apps/sim/blocks/blocks/microsoft_word.test.ts b/apps/sim/blocks/blocks/microsoft_word.test.ts new file mode 100644 index 00000000000..db445e7b0d7 --- /dev/null +++ b/apps/sim/blocks/blocks/microsoft_word.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from 'vitest' +import { MicrosoftWordBlock } from '@/blocks/blocks/microsoft_word' +import type { BlockToolParamsContext } from '@/blocks/types' + +/** What the tool receives: the mapper's result spread over its own input, as both callers merge it. */ +const forwarded = (inputs: Record, context?: BlockToolParamsContext) => ({ + ...inputs, + ...(MicrosoftWordBlock.tools.config?.params?.(inputs, context) ?? {}), +}) + +describe('MicrosoftWordBlock tool-call params', () => { + it('appends the content the model passes under the tool param name', () => { + const result = forwarded( + { oauthCredential: 'cred', documentId: 'doc-1', content: 'More text' }, + { operation: 'append' } + ) + + expect(result.content).toBe('More text') + }) + + it('keeps the model-supplied folder and coerces matchCase when creating from a template', () => { + const result = forwarded( + { + oauthCredential: 'cred', + templateDocumentId: 'tpl-1', + name: 'Offer', + folderId: 'folder-1', + matchCase: 'true', + }, + { operation: 'create_from_template' } + ) + + expect(result.folderId).toBe('folder-1') + expect(result.matchCase).toBe(true) + }) +}) diff --git a/apps/sim/blocks/blocks/microsoft_word.ts b/apps/sim/blocks/blocks/microsoft_word.ts index b746ca48e5a..003154c8bab 100644 --- a/apps/sim/blocks/blocks/microsoft_word.ts +++ b/apps/sim/blocks/blocks/microsoft_word.ts @@ -2,6 +2,7 @@ import { MicrosoftWordIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' const DOCUMENT_FIELD = ['documentSelector', 'manualDocumentId'] as const @@ -399,10 +400,10 @@ export const MicrosoftWordBlock: BlockConfig = { throw new Error(`Invalid Microsoft Word operation: ${params.operation}`) } }, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { oauthCredential, - operation, documentId, templateDocumentId, replacements, @@ -422,6 +423,7 @@ export const MicrosoftWordBlock: BlockConfig = { } = params const base = { oauthCredential, driveId: optionalString(driveId) } + const modelFolderId = toolCallArg(context, optionalString(params.folderId)) switch (operation) { case 'create': @@ -429,7 +431,7 @@ export const MicrosoftWordBlock: BlockConfig = { ...base, name: requireString(name, 'Document name'), content: optionalString(content), - folderId: optionalString(createFolderId), + folderId: optionalString(createFolderId) ?? modelFolderId, } case 'create_from_template': return { @@ -438,7 +440,7 @@ export const MicrosoftWordBlock: BlockConfig = { name: requireString(name, 'Document name'), replacements: optionalJson(replacements), matchCase: optionalBoolean(matchCase) ?? false, - folderId: optionalString(createFolderId), + folderId: optionalString(createFolderId) ?? modelFolderId, } case 'read': return { ...base, documentId: requireString(documentId, 'Document') } @@ -452,7 +454,10 @@ export const MicrosoftWordBlock: BlockConfig = { return { ...base, documentId: requireString(documentId, 'Document'), - content: requireString(appendContent, 'Content to append'), + content: requireString( + optionalString(appendContent) ?? toolCallArg(context, content), + 'Content to append' + ), } case 'replace_text': return { @@ -466,7 +471,7 @@ export const MicrosoftWordBlock: BlockConfig = { return { ...base, query: optionalString(query), - folderId: optionalString(listFolderId), + folderId: optionalString(listFolderId) ?? modelFolderId, pageSize: optionalNumber(pageSize), pageToken: optionalString(pageToken), } diff --git a/apps/sim/blocks/blocks/onedrive.test.ts b/apps/sim/blocks/blocks/onedrive.test.ts new file mode 100644 index 00000000000..cffffa79b13 --- /dev/null +++ b/apps/sim/blocks/blocks/onedrive.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from 'vitest' +import { OneDriveBlock } from '@/blocks/blocks/onedrive' +import type { BlockToolParamsContext } from '@/blocks/types' + +/** What the tool receives: the mapper's result spread over its own input, as both callers merge it. */ +const forwarded = (inputs: Record, context?: BlockToolParamsContext) => ({ + ...inputs, + ...(OneDriveBlock.tools.config?.params?.(inputs, context) ?? {}), +}) + +describe('OneDriveBlock tool-call params', () => { + it('keeps the model-supplied file and destination ids on a move', () => { + const result = forwarded( + { oauthCredential: 'cred', fileId: 'item-1', destinationFolderId: 'folder-2' }, + { operation: 'move' } + ) + + expect(result.fileId).toBe('item-1') + expect(result.destinationFolderId).toBe('folder-2') + }) + + it('resolves the per-operation picker stored on the tool row', () => { + const result = forwarded( + { oauthCredential: 'cred', listFolderId: ' folder-9 ' }, + { operation: 'list' } + ) + + expect(result.folderId).toBe('folder-9') + }) +}) diff --git a/apps/sim/blocks/blocks/onedrive.ts b/apps/sim/blocks/blocks/onedrive.ts index 0c315112db6..a867888c9e4 100644 --- a/apps/sim/blocks/blocks/onedrive.ts +++ b/apps/sim/blocks/blocks/onedrive.ts @@ -2,7 +2,7 @@ import { MicrosoftOneDriveIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput } from '@/blocks/utils' +import { mapperOperation, normalizeFileInput, toolCallArg } from '@/blocks/utils' import { normalizeExcelValuesForToolParams } from '@/tools/onedrive/utils' const UPLOAD_FILE_FIELD = ['file', 'fileReference'] as const @@ -659,7 +659,8 @@ export const OneDriveBlock: BlockConfig = { throw new Error(`Invalid OneDrive operation: ${params.operation}`) } }, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { oauthCredential, // Folder canonical params (per-operation) @@ -692,7 +693,7 @@ export const OneDriveBlock: BlockConfig = { // Resolve folderId based on operation let resolvedFolderId: string | undefined - switch (params.operation) { + switch (operation) { case 'create_file': case 'upload': resolvedFolderId = uploadFolderId?.trim() || undefined @@ -707,7 +708,7 @@ export const OneDriveBlock: BlockConfig = { // Resolve fileId based on operation let resolvedFileId: string | undefined - switch (params.operation) { + switch (operation) { case 'download': resolvedFileId = downloadFileId?.trim() || undefined break @@ -730,7 +731,7 @@ export const OneDriveBlock: BlockConfig = { // Resolve destinationFolderId based on operation let resolvedDestinationFolderId: string | undefined - switch (params.operation) { + switch (operation) { case 'move': resolvedDestinationFolderId = moveDestinationFolderId?.trim() || undefined break @@ -744,9 +745,10 @@ export const OneDriveBlock: BlockConfig = { ...rest, values: normalizedValues, file: normalizedFile, - folderId: resolvedFolderId, - fileId: resolvedFileId, - destinationFolderId: resolvedDestinationFolderId, + folderId: resolvedFolderId ?? toolCallArg(context, rest.folderId), + fileId: resolvedFileId ?? toolCallArg(context, rest.fileId), + destinationFolderId: + resolvedDestinationFolderId ?? toolCallArg(context, rest.destinationFolderId), pageSize: rest.pageSize ? Number.parseInt(rest.pageSize as string, 10) : undefined, mimeType: mimeType, conflictBehavior: rest.conflictBehavior || undefined, diff --git a/apps/sim/blocks/blocks/outlook.test.ts b/apps/sim/blocks/blocks/outlook.test.ts index a305043d206..360f060de35 100644 --- a/apps/sim/blocks/blocks/outlook.test.ts +++ b/apps/sim/blocks/blocks/outlook.test.ts @@ -96,12 +96,12 @@ describe('OutlookBlock values stored for another operation', () => { }) /** - * On an agent call the model supplies `cc`/`bcc`/`importance` under the tool's own names, and the - * dedicated `replyCc`/`replyBcc`/`mailImportance` fields are never rendered in the agent tool input. + * On an agent call the operation arrives only in the mapper context, the model supplies args under + * the tool's own names, and the dedicated block fields are never rendered in the agent tool input. */ describe('OutlookBlock agent tool calls', () => { const agentCall = (operation: string, args: Record): Record => { - const inputs = { ...args, operation, oauthCredential: 'cred-1' } + const inputs = { ...args, oauthCredential: 'cred-1' } return { ...inputs, ...block.tools.config?.params?.(inputs, { operation }) } } @@ -125,4 +125,12 @@ describe('OutlookBlock agent tool calls', () => { const mapped = agentCall('reply_outlook', { replyCc: 'stored@example.com', cc: 'model@x.com' }) expect(mapped.cc).toBe('stored@example.com') }) + + it('keeps the model booleans on create_event_calendar and respond_calendar', () => { + const created = agentCall('create_event_calendar', { isAllDay: true, isOnlineMeeting: 'true' }) + expect(created.isAllDay).toBe(true) + expect(created.isOnlineMeeting).toBe(true) + expect(agentCall('create_folder_outlook', { isHidden: true }).isHidden).toBe(true) + expect(agentCall('respond_calendar', { sendResponse: false }).sendResponse).toBe(false) + }) }) diff --git a/apps/sim/blocks/blocks/outlook.ts b/apps/sim/blocks/blocks/outlook.ts index 01a6d4e49f9..78f6b8d4489 100644 --- a/apps/sim/blocks/blocks/outlook.ts +++ b/apps/sim/blocks/blocks/outlook.ts @@ -2,7 +2,7 @@ import { OutlookIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput, toolCallArg } from '@/blocks/utils' +import { mapperOperation, normalizeFileInput, toolCallArg } from '@/blocks/utils' import { getTrigger } from '@/triggers' /** @@ -991,9 +991,18 @@ Return ONLY the comma-separated email list - no explanations, no extra text.`, ...rest } = params + const operation = mapperOperation(params, context) + // Agent calls may deliver booleans as the strings "true"/"false" const toBool = (value: unknown): boolean => value === true || value === 'true' + const isSet = (value: unknown): boolean => + value !== undefined && value !== null && value !== '' + + /** The dedicated block field when set, else the model's arg under the tool's own name. */ + const fieldOrToolArg = (field: unknown, toolArg: unknown): unknown => + isSet(field) ? field : toolCallArg(context, toolArg) + const effectiveFolder = folder ? String(folder).trim() : '' const normalizedAttachments = normalizeFileInput(attachments) @@ -1005,40 +1014,40 @@ Return ONLY the comma-separated email list - no explanations, no extra text.`, rest.maxResults = Number(maxResults) } - if (rest.operation === 'read_outlook') { + if (operation === 'read_outlook') { rest.folder = effectiveFolder || 'INBOX' } - if (['send_outlook', 'draft_outlook'].includes(rest.operation)) { + if (['send_outlook', 'draft_outlook'].includes(operation)) { rest.importance = mailImportance || toolCallArg(context, rest.importance) || null } // Assign explicitly so a cc/bcc/importance stored for another operation never reaches these tools - if (['reply_outlook', 'reply_all_outlook', 'forward_outlook'].includes(rest.operation)) { + if (['reply_outlook', 'reply_all_outlook', 'forward_outlook'].includes(operation)) { rest.cc = - rest.operation === 'reply_all_outlook' + operation === 'reply_all_outlook' ? null : replyCc || toolCallArg(context, rest.cc) || null rest.bcc = replyBcc || toolCallArg(context, rest.bcc) || null rest.importance = undefined } - if (rest.operation === 'search_outlook' && searchQuery) { + if (operation === 'search_outlook' && searchQuery) { rest.query = String(searchQuery).trim() } - if (rest.operation === 'list_folders_outlook') { + if (operation === 'list_folders_outlook') { rest.includeHiddenFolders = toBool(includeHiddenFolders) } - if (rest.operation === 'create_folder_outlook') { + if (operation === 'create_folder_outlook') { if (folderName) { rest.displayName = String(folderName).trim() } - rest.isHidden = toBool(folderIsHidden) + rest.isHidden = toBool(fieldOrToolArg(folderIsHidden, rest.isHidden)) } - if (rest.operation === 'move_outlook') { + if (operation === 'move_outlook') { if (moveMessageId) { rest.messageId = moveMessageId } @@ -1058,22 +1067,18 @@ Return ONLY the comma-separated email list - no explanations, no extra text.`, 'update_message_outlook', 'list_attachments_outlook', 'get_attachment_outlook', - ].includes(rest.operation) + ].includes(operation) ) { if (actionMessageId) { rest.messageId = actionMessageId } } - if ( - rest.operation === 'update_message_outlook' && - categories != null && - categories !== '' - ) { + if (operation === 'update_message_outlook' && categories != null && categories !== '') { rest.categories = categories } - if (rest.operation === 'copy_outlook') { + if (operation === 'copy_outlook') { if (copyMessageId) { rest.messageId = copyMessageId } @@ -1086,18 +1091,15 @@ Return ONLY the comma-separated email list - no explanations, no extra text.`, } } - const isSet = (value: unknown): boolean => - value !== undefined && value !== null && value !== '' - // Blank means the default calendar, so only forward it when the user actually picked one. - if (['list_events_calendar', 'create_event_calendar'].includes(rest.operation)) { + if (['list_events_calendar', 'create_event_calendar'].includes(operation)) { const effectiveCalendarId = calendarId ? String(calendarId).trim() : '' if (effectiveCalendarId) { rest.calendarId = effectiveCalendarId } } - if (rest.operation === 'list_events_calendar') { + if (operation === 'list_events_calendar') { if (calWindowStart) rest.startDateTime = String(calWindowStart).trim() if (calWindowEnd) rest.endDateTime = String(calWindowEnd).trim() if (isSet(calMaxResults)) rest.maxResults = Number(calMaxResults) @@ -1111,12 +1113,12 @@ Return ONLY the comma-separated email list - no explanations, no extra text.`, 'update_event_calendar', 'delete_event_calendar', 'respond_calendar', - ].includes(rest.operation) + ].includes(operation) ) { if (calEventId) rest.eventId = String(calEventId).trim() } - if (rest.operation === 'create_event_calendar') { + if (operation === 'create_event_calendar') { if (calSubject) rest.subject = calSubject if (calStartDateTime) rest.startDateTime = String(calStartDateTime).trim() if (calEndDateTime) rest.endDateTime = String(calEndDateTime).trim() @@ -1125,11 +1127,11 @@ Return ONLY the comma-separated email list - no explanations, no extra text.`, if (isSet(calLocation)) rest.location = calLocation if (isSet(calAttendees)) rest.attendees = calAttendees if (calTimeZone) rest.timeZone = String(calTimeZone).trim() - rest.isAllDay = toBool(calIsAllDay) - rest.isOnlineMeeting = toBool(calIsOnlineMeeting) + rest.isAllDay = toBool(fieldOrToolArg(calIsAllDay, rest.isAllDay)) + rest.isOnlineMeeting = toBool(fieldOrToolArg(calIsOnlineMeeting, rest.isOnlineMeeting)) } - if (rest.operation === 'update_event_calendar') { + if (operation === 'update_event_calendar') { if (isSet(calSubject)) rest.subject = calSubject if (calStartDateTime) rest.startDateTime = String(calStartDateTime).trim() if (calEndDateTime) rest.endDateTime = String(calEndDateTime).trim() @@ -1142,11 +1144,12 @@ Return ONLY the comma-separated email list - no explanations, no extra text.`, if (isSet(calIsOnlineMeeting)) rest.isOnlineMeeting = toBool(calIsOnlineMeeting) } - if (rest.operation === 'respond_calendar') { + if (operation === 'respond_calendar') { if (calResponseType) rest.responseType = calResponseType if (isSet(calComment)) rest.comment = calComment // Notifying the organizer is the default; an unset dropdown must not read as "no". - rest.sendResponse = isSet(calSendResponse) ? toBool(calSendResponse) : true + const sendResponse = fieldOrToolArg(calSendResponse, rest.sendResponse) + rest.sendResponse = isSet(sendResponse) ? toBool(sendResponse) : true } return { diff --git a/apps/sim/blocks/blocks/sharepoint.test.ts b/apps/sim/blocks/blocks/sharepoint.test.ts new file mode 100644 index 00000000000..b91ef0a15f7 --- /dev/null +++ b/apps/sim/blocks/blocks/sharepoint.test.ts @@ -0,0 +1,23 @@ +import { triggersMock } from '@sim/testing/mocks/triggers.mock' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@/triggers', () => triggersMock) + +import { SharepointV2Block } from '@/blocks/blocks/sharepoint' + +const mapParams = SharepointV2Block.tools.config?.params + +describe('SharePoint v2 mapper on agent tool calls', () => { + it('maps get list item select fields from the row or the model', () => { + if (!mapParams) throw new Error('SharePoint v2 block has no params mapper') + const operation = 'sharepoint_get_list_item' + const target = { siteId: 'site', listId: 'list', itemId: '7' } + + expect( + mapParams({ ...target, itemSelectFields: 'Title,Status' }, { operation }).selectFields + ).toBe('Title,Status') + expect(mapParams({ ...target, selectFields: 'Title' }, { operation }).selectFields).toBe( + 'Title' + ) + }) +}) diff --git a/apps/sim/blocks/blocks/sharepoint.ts b/apps/sim/blocks/blocks/sharepoint.ts index 7769a061467..09c16a2dadc 100644 --- a/apps/sim/blocks/blocks/sharepoint.ts +++ b/apps/sim/blocks/blocks/sharepoint.ts @@ -4,7 +4,7 @@ import { MicrosoftSharepointIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput } from '@/blocks/utils' +import { isToolCall, mapperOperation, normalizeFileInput, toolCallArg } from '@/blocks/utils' const logger = createLogger('SharepointBlock') @@ -653,7 +653,8 @@ Return ONLY the JSON object - no explanations, no markdown, no extra text.`, throw new Error(`Invalid Sharepoint operation: ${params.operation}`) } }, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { oauthCredential, siteId, mimeType, ...rest } = params // siteId is the canonical param from siteSelector (basic) or manualSiteId (advanced) @@ -696,7 +697,7 @@ Return ONLY the JSON object - no explanations, no markdown, no extra text.`, return undefined } - if (others.operation === 'update_list' || others.operation === 'add_list_items') { + if (operation === 'update_list' || operation === 'add_list_items') { logger.info('SharepointBlock list item param check', { siteId: effectiveSiteId || undefined, listId: listId, @@ -729,7 +730,7 @@ Return ONLY the JSON object - no explanations, no markdown, no extra text.`, baseParams.files = normalizedFiles } - if (columnDefinitions && others.operation === 'create_list') { + if (columnDefinitions && operation === 'create_list') { baseParams.pageContent = columnDefinitions } @@ -1427,7 +1428,8 @@ Return ONLY the JSON object - no explanations, no markdown, no extra text.`, access: [...SHAREPOINT_V2_TOOL_IDS], config: { tool: (params) => params.operation || 'sharepoint_create_page', - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { oauthCredential, siteId, @@ -1481,17 +1483,24 @@ Return ONLY the JSON object - no explanations, no markdown, no extra text.`, top: cleanString(top) ? Number(cleanString(top)) : undefined, } - if (result.includeColumns === true && rest.operation === 'sharepoint_get_list') { + // Canvas only: a model's own filter/top/selectFields reach the tool, which rejects the mix clearly. + if ( + result.includeColumns === true && + operation === 'sharepoint_get_list' && + !isToolCall(context) + ) { result.filter = undefined result.top = undefined result.selectFields = undefined } - if (rest.operation === 'sharepoint_get_list_item') { - result.selectFields = cleanString(result.itemSelectFields) + if (operation === 'sharepoint_get_list_item') { + result.selectFields = + cleanString(result.itemSelectFields) ?? + toolCallArg(context, cleanString(result.selectFields)) } result.itemSelectFields = undefined - if (columnDefinitions && rest.operation === 'sharepoint_create_list') { + if (columnDefinitions && operation === 'sharepoint_create_list') { result.pageContent = columnDefinitions } if (normalizedFiles) { diff --git a/apps/sim/blocks/blocks/trello.test.ts b/apps/sim/blocks/blocks/trello.test.ts new file mode 100644 index 00000000000..e2b8e2a361f --- /dev/null +++ b/apps/sim/blocks/blocks/trello.test.ts @@ -0,0 +1,28 @@ +import { triggersMock } from '@sim/testing/mocks/triggers.mock' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@/triggers', () => triggersMock) + +import { TrelloBlock } from '@/blocks/blocks/trello' + +const mapParams = TrelloBlock.tools.config?.params + +describe('Trello mapper on agent tool calls', () => { + it('maps args keyed by the tool param names for the operation in context', () => { + if (!mapParams) throw new Error('Trello block has no params mapper') + + expect( + mapParams( + { oauthCredential: 'cred', name: 'Roadmap', desc: 'Q1 plans', defaultLists: false }, + { operation: 'trello_create_board' } + ) + ).toMatchObject({ name: 'Roadmap', desc: 'Q1 plans', defaultLists: false }) + + expect( + mapParams( + { oauthCredential: 'cred', query: 'bug', idBoards: ['b1', 'b2'], cardsLimit: 5 }, + { operation: 'trello_search' } + ) + ).toMatchObject({ query: 'bug', idBoards: ['b1', 'b2'], cardsLimit: 5 }) + }) +}) diff --git a/apps/sim/blocks/blocks/trello.ts b/apps/sim/blocks/blocks/trello.ts index 2e1d4598243..6457658d3c7 100644 --- a/apps/sim/blocks/blocks/trello.ts +++ b/apps/sim/blocks/blocks/trello.ts @@ -2,7 +2,12 @@ import { TrelloIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { parseOptionalBooleanInput, parseOptionalNumberInput } from '@/blocks/utils' +import { + mapperOperation, + parseOptionalBooleanInput, + parseOptionalNumberInput, + toolCallArg, +} from '@/blocks/utils' function getTrimmedString(value: unknown): string | undefined { if (typeof value !== 'string') { @@ -1074,8 +1079,14 @@ Return ONLY the date/timestamp string - no explanations, no extra text.`, ], config: { tool: (params) => getTrimmedString(params.operation) ?? 'trello_list_lists', - params: (params) => { - const operation = getTrimmedString(params.operation) ?? 'trello_list_lists' + params: (params, context) => { + const operation = mapperOperation(params, context).trim() || 'trello_list_lists' + /** The model's arg under the tool's own param name; only read on tool calls. */ + const toolArg = (key: string): unknown => toolCallArg(context, params[key]) + const trimmedArg = (key: string) => getTrimmedString(toolArg(key)) + const booleanArg = (key: string) => parseOptionalBooleanInput(toolArg(key)) + const numberArg = (key: string) => parseOptionalNumberInput(toolArg(key), key) + const listArg = (key: string) => parseStringArray(toolArg(key)) const baseParams: Record = { oauthCredential: params.oauthCredential, } @@ -1091,7 +1102,7 @@ Return ONLY the date/timestamp string - no explanations, no extra text.`, return { ...baseParams, boardId, - filter: getTrimmedString(params.listFilter), + filter: getTrimmedString(params.listFilter) ?? trimmedArg('filter'), } } @@ -1111,14 +1122,14 @@ Return ONLY the date/timestamp string - no explanations, no extra text.`, ...baseParams, boardId, listId, - filter: getTrimmedString(params.cardFilter), - since: getTrimmedString(params.cardSince), - before: getTrimmedString(params.cardBefore), + filter: getTrimmedString(params.cardFilter) ?? trimmedArg('filter'), + since: getTrimmedString(params.cardSince) ?? trimmedArg('since'), + before: getTrimmedString(params.cardBefore) ?? trimmedArg('before'), } } case 'trello_search': { - const query = getTrimmedString(params.searchQuery) + const query = getTrimmedString(params.searchQuery) ?? trimmedArg('query') if (!query) { throw new Error('Search query is required.') @@ -1127,12 +1138,18 @@ Return ONLY the date/timestamp string - no explanations, no extra text.`, return { ...baseParams, query, - idBoards: parseStringArray(params.searchBoardIds), - modelTypes: getTrimmedString(params.searchModelTypes), - cardsLimit: parseOptionalNumberInput(params.searchCardsLimit, 'cardsLimit'), - cardsPage: parseOptionalNumberInput(params.searchCardsPage, 'cardsPage'), - boardsLimit: parseOptionalNumberInput(params.searchBoardsLimit, 'boardsLimit'), - partial: parseOptionalBooleanInput(params.searchPartial), + idBoards: parseStringArray(params.searchBoardIds) ?? listArg('idBoards'), + modelTypes: getTrimmedString(params.searchModelTypes) ?? trimmedArg('modelTypes'), + cardsLimit: + parseOptionalNumberInput(params.searchCardsLimit, 'cardsLimit') ?? + numberArg('cardsLimit'), + cardsPage: + parseOptionalNumberInput(params.searchCardsPage, 'cardsPage') ?? + numberArg('cardsPage'), + boardsLimit: + parseOptionalNumberInput(params.searchBoardsLimit, 'boardsLimit') ?? + numberArg('boardsLimit'), + partial: parseOptionalBooleanInput(params.searchPartial) ?? booleanArg('partial'), } } @@ -1179,10 +1196,10 @@ Return ONLY the date/timestamp string - no explanations, no extra text.`, due: getTrimmedString(params.due), dueComplete: parseOptionalBooleanInput(params.dueComplete), start: getTrimmedString(params.start), - pos: getTrimmedString(params.updatePos), - idBoard: getTrimmedString(params.moveCardToBoardId), - labelIds: parseStringArray(params.updateLabelIds), - memberIds: parseStringArray(params.updateMemberIds), + pos: getTrimmedString(params.updatePos) ?? trimmedArg('pos'), + idBoard: getTrimmedString(params.moveCardToBoardId) ?? trimmedArg('idBoard'), + labelIds: parseStringArray(params.updateLabelIds) ?? listArg('labelIds'), + memberIds: parseStringArray(params.updateMemberIds) ?? listArg('memberIds'), } } @@ -1243,7 +1260,7 @@ Return ONLY the date/timestamp string - no explanations, no extra text.`, } case 'trello_create_board': { - const name = getTrimmedString(params.boardName) + const name = getTrimmedString(params.boardName) ?? trimmedArg('name') if (!name) { throw new Error('Board name is required.') @@ -1252,7 +1269,7 @@ Return ONLY the date/timestamp string - no explanations, no extra text.`, return { ...baseParams, name, - desc: getTrimmedString(params.boardDesc), + desc: getTrimmedString(params.boardDesc) ?? trimmedArg('desc'), idOrganization: getTrimmedString(params.idOrganization), defaultLists: parseOptionalBooleanInput(params.defaultLists), } @@ -1273,7 +1290,7 @@ Return ONLY the date/timestamp string - no explanations, no extra text.`, case 'trello_create_list': { const boardId = getTrimmedString(params.boardId) - const name = getTrimmedString(params.listName) + const name = getTrimmedString(params.listName) ?? trimmedArg('name') if (!boardId) { throw new Error('Board ID is required.') @@ -1287,7 +1304,7 @@ Return ONLY the date/timestamp string - no explanations, no extra text.`, ...baseParams, boardId, name, - pos: getTrimmedString(params.listPos), + pos: getTrimmedString(params.listPos) ?? trimmedArg('pos'), } } @@ -1301,10 +1318,10 @@ Return ONLY the date/timestamp string - no explanations, no extra text.`, return { ...baseParams, listId, - name: getTrimmedString(params.listName), - closed: parseOptionalBooleanInput(params.listClosed), - idBoard: getTrimmedString(params.moveListToBoardId), - pos: getTrimmedString(params.listPos), + name: getTrimmedString(params.listName) ?? trimmedArg('name'), + closed: parseOptionalBooleanInput(params.listClosed) ?? booleanArg('closed'), + idBoard: getTrimmedString(params.moveListToBoardId) ?? trimmedArg('idBoard'), + pos: getTrimmedString(params.listPos) ?? trimmedArg('pos'), } } @@ -1326,7 +1343,7 @@ Return ONLY the date/timestamp string - no explanations, no extra text.`, case 'trello_add_checklist': { const cardId = getTrimmedString(params.cardId) - const name = getTrimmedString(params.checklistName) + const name = getTrimmedString(params.checklistName) ?? trimmedArg('name') if (!cardId) { throw new Error('Card ID is required.') @@ -1340,13 +1357,13 @@ Return ONLY the date/timestamp string - no explanations, no extra text.`, ...baseParams, cardId, name, - pos: getTrimmedString(params.checklistPos), + pos: getTrimmedString(params.checklistPos) ?? trimmedArg('pos'), } } case 'trello_add_checklist_item': { const checklistId = getTrimmedString(params.checklistId) - const name = getTrimmedString(params.itemName) + const name = getTrimmedString(params.itemName) ?? trimmedArg('name') if (!checklistId) { throw new Error('Checklist ID is required.') @@ -1360,8 +1377,8 @@ Return ONLY the date/timestamp string - no explanations, no extra text.`, ...baseParams, checklistId, name, - pos: getTrimmedString(params.itemPos), - checked: parseOptionalBooleanInput(params.itemChecked), + pos: getTrimmedString(params.itemPos) ?? trimmedArg('pos'), + checked: parseOptionalBooleanInput(params.itemChecked) ?? booleanArg('checked'), } } @@ -1377,10 +1394,10 @@ Return ONLY the date/timestamp string - no explanations, no extra text.`, throw new Error('Checklist item ID is required.') } - const state = getTrimmedString(params.checkItemState) + const state = getTrimmedString(params.checkItemState) ?? trimmedArg('state') const normalizedState = state === 'complete' || state === 'incomplete' ? state : undefined - const name = getTrimmedString(params.checkItemName) + const name = getTrimmedString(params.checkItemName) ?? trimmedArg('name') if (!normalizedState && !name) { throw new Error('Provide a State or a New Item Name to update.') diff --git a/scripts/check-explicit-any.baseline.json b/scripts/check-explicit-any.baseline.json index 156de5cc4b5..2bbf9f1f690 100644 --- a/scripts/check-explicit-any.baseline.json +++ b/scripts/check-explicit-any.baseline.json @@ -85,7 +85,6 @@ "apps/sim/blocks/blocks/firecrawl.ts": 1, "apps/sim/blocks/blocks/github.ts": 2, "apps/sim/blocks/blocks/gmail.ts": 1, - "apps/sim/blocks/blocks/google_appsheet.ts": 1, "apps/sim/blocks/blocks/google_calendar.ts": 1, "apps/sim/blocks/blocks/google_contacts.ts": 1, "apps/sim/blocks/blocks/google_slides.ts": 1, diff --git a/scripts/check-mapper-operation.baseline.json b/scripts/check-mapper-operation.baseline.json index f145da07118..f458b03593d 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/azure_devops.ts": 1, - "apps/sim/blocks/blocks/bitbucket.ts": 3, "apps/sim/blocks/blocks/brightdata.ts": 1, "apps/sim/blocks/blocks/buffer.ts": 2, "apps/sim/blocks/blocks/cbinsights.ts": 1, @@ -15,7 +13,6 @@ "apps/sim/blocks/blocks/circleback.ts": 2, "apps/sim/blocks/blocks/clerk.ts": 1, "apps/sim/blocks/blocks/coda.ts": 1, - "apps/sim/blocks/blocks/confluence.ts": 2, "apps/sim/blocks/blocks/context_dev.ts": 1, "apps/sim/blocks/blocks/crunchbase.ts": 1, "apps/sim/blocks/blocks/deployments.ts": 1, @@ -31,17 +28,7 @@ "apps/sim/blocks/blocks/firecrawl.ts": 1, "apps/sim/blocks/blocks/fireflies.ts": 2, "apps/sim/blocks/blocks/flint.ts": 1, - "apps/sim/blocks/blocks/gmail.ts": 4, "apps/sim/blocks/blocks/gong.ts": 1, - "apps/sim/blocks/blocks/google_appsheet.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, - "apps/sim/blocks/blocks/google_groups.ts": 1, - "apps/sim/blocks/blocks/google_maps.ts": 1, - "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/grain.ts": 2, "apps/sim/blocks/blocks/greenhouse.ts": 2, "apps/sim/blocks/blocks/harmonic.ts": 1, @@ -49,8 +36,6 @@ "apps/sim/blocks/blocks/hex.ts": 1, "apps/sim/blocks/blocks/instagram.ts": 2, "apps/sim/blocks/blocks/instantly.ts": 17, - "apps/sim/blocks/blocks/jira.ts": 1, - "apps/sim/blocks/blocks/jira_service_management.ts": 1, "apps/sim/blocks/blocks/jotform.ts": 1, "apps/sim/blocks/blocks/kalshi.ts": 1, "apps/sim/blocks/blocks/ketch.ts": 4, @@ -65,19 +50,11 @@ "apps/sim/blocks/blocks/manageengine-sdp.ts": 2, "apps/sim/blocks/blocks/mem0.ts": 1, "apps/sim/blocks/blocks/memory.ts": 8, - "apps/sim/blocks/blocks/microsoft_ad.ts": 9, - "apps/sim/blocks/blocks/microsoft_dataverse.ts": 1, "apps/sim/blocks/blocks/microsoft_dynamics_365.ts": 2, - "apps/sim/blocks/blocks/microsoft_excel.ts": 4, - "apps/sim/blocks/blocks/microsoft_planner.ts": 1, - "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/netsuite.ts": 2, "apps/sim/blocks/blocks/okta.ts": 2, - "apps/sim/blocks/blocks/onedrive.ts": 3, "apps/sim/blocks/blocks/otter.ts": 1, - "apps/sim/blocks/blocks/outlook.ts": 17, "apps/sim/blocks/blocks/parallel.ts": 1, "apps/sim/blocks/blocks/peopledatalabs.ts": 1, "apps/sim/blocks/blocks/perplexity.ts": 1, @@ -94,7 +71,6 @@ "apps/sim/blocks/blocks/rootly.ts": 1, "apps/sim/blocks/blocks/sailpoint.ts": 1, "apps/sim/blocks/blocks/sendblue.ts": 1, - "apps/sim/blocks/blocks/sharepoint.ts": 6, "apps/sim/blocks/blocks/sixtyfour.ts": 4, "apps/sim/blocks/blocks/smartlead.ts": 5, "apps/sim/blocks/blocks/snowflake.ts": 1, @@ -102,7 +78,6 @@ "apps/sim/blocks/blocks/table.ts": 1, "apps/sim/blocks/blocks/table_v2.ts": 1, "apps/sim/blocks/blocks/tiktok.ts": 1, - "apps/sim/blocks/blocks/trello.ts": 1, "apps/sim/blocks/blocks/vanta.ts": 1, "apps/sim/blocks/blocks/wealthbox.ts": 1, "apps/sim/blocks/blocks/zendesk.ts": 1,