diff --git a/apps/sim/blocks/blocks/airtable.ts b/apps/sim/blocks/blocks/airtable.ts index 139dafaa2ad..e6f8d1f4329 100644 --- a/apps/sim/blocks/blocks/airtable.ts +++ b/apps/sim/blocks/blocks/airtable.ts @@ -3,7 +3,7 @@ import { AirtableIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { toolCallArg } from '@/blocks/utils' +import { mapperOperation, toolCallArg } from '@/blocks/utils' import { getTrigger } from '@/triggers' /** Canonical account pair — an advanced-mode card only fills `manualCredential`. */ @@ -429,7 +429,7 @@ Return ONLY the valid JSON array of record ID strings - no explanations, no mark ...rest } = params /** Agent tool calls carry the stored operation only on `context`, not in `params`. */ - const operation = params.operation ?? context?.operation + const operation = mapperOperation(params, context) let parsedRecords: unknown let parsedFields: unknown let parsedFieldsToMergeOn: unknown diff --git a/apps/sim/blocks/blocks/asana.ts b/apps/sim/blocks/blocks/asana.ts index 37f4325dbd3..c7678b64c98 100644 --- a/apps/sim/blocks/blocks/asana.ts +++ b/apps/sim/blocks/blocks/asana.ts @@ -2,7 +2,7 @@ import { AsanaIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { toolCallArg } from '@/blocks/utils' +import { mapperOperation, toolCallArg } from '@/blocks/utils' const WORKSPACE_FIELD = ['workspaceSelector', 'workspace'] as const const GET_TASKS_WORKSPACE_FIELD = ['getTasksWorkspaceSelector', 'getTasks_workspace'] as const @@ -521,7 +521,7 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n params: (params, context) => { const { oauthCredential } = params /** Agent tool calls carry the stored operation only on `context`, not in `params`. */ - const operation = params.operation ?? context?.operation + const operation = mapperOperation(params, context) const splitGids = (value: unknown): string[] | undefined => { if (Array.isArray(value)) return value.map(String) diff --git a/apps/sim/blocks/blocks/attio.ts b/apps/sim/blocks/blocks/attio.ts index 37a9aff63ab..7b4a406f937 100644 --- a/apps/sim/blocks/blocks/attio.ts +++ b/apps/sim/blocks/blocks/attio.ts @@ -1,6 +1,7 @@ import { AttioIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation } from '@/blocks/utils' import { getTrigger } from '@/triggers' /* @@ -1613,7 +1614,7 @@ Record reference: {"allowed_objects": ["people", "companies"]}`, const cleanParams: Record = { oauthCredential: params.oauthCredential, } - const op = params.operation ?? context?.operation + const op = mapperOperation(params, context) // Record params — each field is only sent for the operations whose subBlock condition // actually exposes it, so a stale value left over from switching operations never leaks diff --git a/apps/sim/blocks/blocks/box.ts b/apps/sim/blocks/blocks/box.ts index c9d3113b371..90b2f9bc1eb 100644 --- a/apps/sim/blocks/blocks/box.ts +++ b/apps/sim/blocks/blocks/box.ts @@ -3,7 +3,7 @@ import { BoxCompanyIcon } 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' /** Canonical pair for the upload payload: file picker in basic mode, file reference in advanced. */ const UPLOAD_FILE_FIELD = ['uploadFile', 'fileRef'] as const @@ -534,8 +534,8 @@ export const BoxBlock = { if (normalizedFile) { params.file = normalizedFile } - const { credential, operation: storedOperation, ...rest } = params - const operation = storedOperation ?? context?.operation + const { credential, ...rest } = params + const operation = mapperOperation(params, context) const baseParams: Record = { accessToken: credential, diff --git a/apps/sim/blocks/blocks/clickup.ts b/apps/sim/blocks/blocks/clickup.ts index b958b465af4..5f2c73162b0 100644 --- a/apps/sim/blocks/blocks/clickup.ts +++ b/apps/sim/blocks/blocks/clickup.ts @@ -4,6 +4,7 @@ import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' import { isToolCall, + mapperOperation, normalizeFileInput, parseOptionalBooleanInput, toolCallArg, @@ -1479,7 +1480,7 @@ Return ONLY the value (plain string, number, or JSON) - no explanations, no extr params: (params, context) => { const { oauthCredential } = params /** Agent tool calls carry the stored operation only on `context`, not in `params`. */ - const operation = params.operation ?? context?.operation + const operation = mapperOperation(params, context) const baseParams = { accessToken: oauthCredential?.accessToken, diff --git a/apps/sim/blocks/blocks/dropbox.ts b/apps/sim/blocks/blocks/dropbox.ts index 5ef0717c153..7ab43aae8ae 100644 --- a/apps/sim/blocks/blocks/dropbox.ts +++ b/apps/sim/blocks/blocks/dropbox.ts @@ -3,7 +3,7 @@ import { DropboxIcon } 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' /* * Canonical basic/advanced pair for the upload source, shared by the card @@ -483,7 +483,7 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, }, params: (params, context) => { const result: Record = {} - const operation = params.operation ?? context?.operation + const operation = mapperOperation(params, context) // `cursor` is List Shared Links' field; List Folder and Search page with their own if (operation === 'dropbox_list_folder') { result.cursor = params.listFolderCursor || toolCallArg(context, params.cursor) diff --git a/apps/sim/blocks/blocks/gauge.ts b/apps/sim/blocks/blocks/gauge.ts index af734b73eb6..5fdce04a6be 100644 --- a/apps/sim/blocks/blocks/gauge.ts +++ b/apps/sim/blocks/blocks/gauge.ts @@ -1,5 +1,6 @@ import { GaugeIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' +import { mapperOperation } from '@/blocks/utils' export const GaugeBlock: BlockConfig = { type: 'gauge', @@ -972,7 +973,7 @@ export const GaugeBlock: BlockConfig = { config: { tool: (params) => params.operation, params: (params, context) => { - const operation = context?.operation ?? params.operation + const operation = mapperOperation(params, context) const patch = ['gauge_bulk_update_prompts', 'gauge_update_prompt'].includes(operation) return { ...params, diff --git a/apps/sim/blocks/blocks/higgsfield.ts b/apps/sim/blocks/blocks/higgsfield.ts index 4aff26c8b90..149a094e8ed 100644 --- a/apps/sim/blocks/blocks/higgsfield.ts +++ b/apps/sim/blocks/blocks/higgsfield.ts @@ -1,6 +1,6 @@ import { HiggsfieldIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' -import { parseOptionalNumberInput } from '@/blocks/utils' +import { mapperOperation, parseOptionalNumberInput } from '@/blocks/utils' const GENERATE_OPERATIONS = ['higgsfield_generate', 'higgsfield_generate_soul_image'] const REQUEST_OPERATIONS = [ @@ -315,7 +315,7 @@ export const HiggsfieldBlock: BlockConfig = { config: { tool: (params) => params.operation, params: (params, context) => { - const operation = context?.operation ?? params.operation + const operation = mapperOperation(params, context) const isSoul = operation === SOUL const isGenerate = GENERATE_OPERATIONS.includes(operation) const isList = operation === 'higgsfield_list_characters' diff --git a/apps/sim/blocks/blocks/hubspot.ts b/apps/sim/blocks/blocks/hubspot.ts index 4909c3b0516..6c50936b3b2 100644 --- a/apps/sim/blocks/blocks/hubspot.ts +++ b/apps/sim/blocks/blocks/hubspot.ts @@ -2,7 +2,7 @@ import { HubspotIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { toolCallArg } from '@/blocks/utils' +import { mapperOperation, toolCallArg } from '@/blocks/utils' import { getTrigger } from '@/triggers' export const HubSpotBlock: BlockConfig = { @@ -1635,7 +1635,6 @@ Return ONLY the JSON array of property names - no explanations, no markdown, no params: (params, context) => { const { oauthCredential, - operation: storedOperation, propertiesToSet, properties, searchProperties, @@ -1647,7 +1646,7 @@ Return ONLY the JSON array of property names - no explanations, no markdown, no archived, ...rest } = params - const operation = storedOperation ?? context?.operation + const operation = mapperOperation(params, context) const cleanParams: Record = { oauthCredential, diff --git a/apps/sim/blocks/blocks/intercom.ts b/apps/sim/blocks/blocks/intercom.ts index 6121c2c4e32..d95966cc3e8 100644 --- a/apps/sim/blocks/blocks/intercom.ts +++ b/apps/sim/blocks/blocks/intercom.ts @@ -2,7 +2,12 @@ import { toBooleanFromInput } from '@sim/utils/coerce' import { IntercomIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { createVersionedToolSelector, toolCallArg, withSavedCredential } from '@/blocks/utils' +import { + createVersionedToolSelector, + mapperOperation, + toolCallArg, + withSavedCredential, +} from '@/blocks/utils' import { getTrigger } from '@/triggers' /** @@ -38,7 +43,6 @@ type IntercomParamsMapper = NonNullable { const { - operation: storedOperation, message_type_msg, company_name, contact_company_id, @@ -68,7 +72,7 @@ const mapIntercomParams: IntercomParamsMapper = (params, context) => { event_created_at, ...rest } = params - const operation = storedOperation ?? context?.operation + const operation = mapperOperation(params, context) const cleanParams: Record = {} if (operation === 'create_message' && message_type_msg) { diff --git a/apps/sim/blocks/blocks/monaco.ts b/apps/sim/blocks/blocks/monaco.ts index aa3af55c992..9e46f1d72e9 100644 --- a/apps/sim/blocks/blocks/monaco.ts +++ b/apps/sim/blocks/blocks/monaco.ts @@ -2,6 +2,7 @@ import { toBooleanFromInput } from '@sim/utils/coerce' import { MonacoIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation } from '@/blocks/utils' type FieldKind = 'string' | 'number' | 'boolean' | 'value' @@ -1431,7 +1432,7 @@ export const MonacoBlock: BlockConfig = { * subBlock has a different id falls back to the model's value. */ params: (params, context) => { - const operation = context?.operation ?? params.operation + const operation = mapperOperation(params, context) const result: Record = { operation: undefined, credential: undefined, diff --git a/apps/sim/blocks/blocks/monday.ts b/apps/sim/blocks/blocks/monday.ts index e349eb610c6..f0e44840152 100644 --- a/apps/sim/blocks/blocks/monday.ts +++ b/apps/sim/blocks/blocks/monday.ts @@ -2,7 +2,7 @@ import { MondayIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { toolCallArg } from '@/blocks/utils' +import { mapperOperation, toolCallArg } from '@/blocks/utils' import { getTrigger } from '@/triggers' const BOARD_OPS = [ @@ -525,9 +525,7 @@ export const MondayBlock: BlockConfig = { const baseParams: Record = { oauthCredential: params.oauthCredential, } - /** Agent tool calls carry the stored operation only on `context`, not in `params`. */ - const rawOperation = params.operation ?? context?.operation - const op = typeof rawOperation === 'string' ? rawOperation.trim() : 'list_boards' + const op = mapperOperation(params, context).trim() || 'list_boards' switch (op) { case 'list_boards': diff --git a/apps/sim/blocks/blocks/notion.ts b/apps/sim/blocks/blocks/notion.ts index 39744ee29c6..d9f45810388 100644 --- a/apps/sim/blocks/blocks/notion.ts +++ b/apps/sim/blocks/blocks/notion.ts @@ -3,7 +3,11 @@ import { toError } from '@sim/utils/errors' import { NotionIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { createVersionedToolSelector, parseOptionalJsonInput } from '@/blocks/utils' +import { + createVersionedToolSelector, + mapperOperation, + parseOptionalJsonInput, +} from '@/blocks/utils' import { getTrigger } from '@/triggers' /** @@ -625,7 +629,6 @@ export const NotionBlock: BlockConfig = { params: (params, context) => { const { oauthCredential, - operation: storedOperation, properties, filter, sorts, @@ -637,7 +640,7 @@ export const NotionBlock: BlockConfig = { commentContent, ...rest } = params - const operation = storedOperation ?? context?.operation + const operation = mapperOperation(params, context) // Parse properties from JSON string for create/add operations let parsedProperties diff --git a/apps/sim/blocks/blocks/quickbooks.ts b/apps/sim/blocks/blocks/quickbooks.ts index 3c6fc46500a..7f05d9c43a9 100644 --- a/apps/sim/blocks/blocks/quickbooks.ts +++ b/apps/sim/blocks/blocks/quickbooks.ts @@ -2,7 +2,7 @@ import { QuickBooksIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta, OutputCondition, SubBlockConfig } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput, toolCallArg } from '@/blocks/utils' +import { mapperOperation, normalizeFileInput, toolCallArg } from '@/blocks/utils' import { getQuickBooksReportTypesSupporting, type QuickBooksReportControl, @@ -2526,7 +2526,7 @@ export const QuickBooksBlock: BlockConfig = { return operation }, params: (params, context) => { - const operation = String(params.operation ?? context?.operation) + const operation = mapperOperation(params, context) const oauthCredentialValue = params.oauthCredential /** * Resolves a tool param filled by a differently-named subBlock. On an agent tool call diff --git a/apps/sim/blocks/blocks/sap_concur.ts b/apps/sim/blocks/blocks/sap_concur.ts index e0d2443c65e..e4b2bdb8b7c 100644 --- a/apps/sim/blocks/blocks/sap_concur.ts +++ b/apps/sim/blocks/blocks/sap_concur.ts @@ -1,7 +1,7 @@ import { SapConcurIcon } from '@/components/icons' 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 type { UserFileLike } from '@/tools/sap_concur/types' const toBool = (v: unknown): boolean | undefined => { @@ -2030,7 +2030,7 @@ Return ONLY the JSON object - no explanations, no extra text.`, config: { tool: (params) => params.operation, params: (params, context) => { - const operation = params.operation ?? context?.operation + const operation = mapperOperation(params, context) const auth = { datacenter: params.datacenter || undefined, grantType: params.grantType || undefined, diff --git a/apps/sim/blocks/blocks/sap_s4hana.ts b/apps/sim/blocks/blocks/sap_s4hana.ts index 24c267b5400..121b0e426cc 100644 --- a/apps/sim/blocks/blocks/sap_s4hana.ts +++ b/apps/sim/blocks/blocks/sap_s4hana.ts @@ -1,7 +1,7 @@ import { SapS4HanaIcon } from '@/components/icons' import type { BlockConfig, BlockMeta, CanvasSentence } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { isToolCall } from '@/blocks/utils' +import { isToolCall, mapperOperation } from '@/blocks/utils' /** * Whichever name a new business partner carries: an organization has @@ -1048,7 +1048,7 @@ Return ONLY the JSON array - no explanations, no extra text.`, tool: (params) => params.operation, params: (params, context) => { /** Agent tool calls carry the stored operation only on `context`, not in `params`. */ - const operation = params.operation ?? context?.operation + const operation = mapperOperation(params, context) /** * A differently named sub-block feeds each tool param below. On a tool call the model's * arg arrives under the tool param name, so a blank sub-block falls back to it. diff --git a/apps/sim/blocks/blocks/servicenow.ts b/apps/sim/blocks/blocks/servicenow.ts index d1eb197c8e4..2f29f8b090e 100644 --- a/apps/sim/blocks/blocks/servicenow.ts +++ b/apps/sim/blocks/blocks/servicenow.ts @@ -1,7 +1,13 @@ import { ServiceNowIcon } from '@/components/icons' import type { BlockConfig, BlockMeta, BlockToolParamsContext } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { isToolCall, normalizeFileInput, toolCallArg, withSavedCredential } from '@/blocks/utils' +import { + isToolCall, + mapperOperation, + normalizeFileInput, + toolCallArg, + withSavedCredential, +} from '@/blocks/utils' import { APPROVAL_DECISION_OPTIONS, APPROVAL_STATE, @@ -1624,7 +1630,6 @@ Output: {"state": "2", "assigned_to": "john.doe", "work_notes": "Assigned and st tool: (params) => params.operation, params: (params, context?: BlockToolParamsContext) => { const { - operation: storedOperation, fields, readFields, returnFields, @@ -1644,7 +1649,7 @@ Output: {"state": "2", "assigned_to": "john.doe", "work_notes": "Assigned and st knowledgeQuery, ...rest } = params - const operation = context?.operation ?? storedOperation + const operation = mapperOperation(params, context) /** * A dedicated subblock's value, or on a tool call where it is blank, the * model's arg under the tool param name. Without a model arg the subblock diff --git a/apps/sim/blocks/blocks/workday.ts b/apps/sim/blocks/blocks/workday.ts index 78b2acd5d66..99c75b997c0 100644 --- a/apps/sim/blocks/blocks/workday.ts +++ b/apps/sim/blocks/blocks/workday.ts @@ -1,6 +1,7 @@ import { WorkdayIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { IntegrationType } from '@/blocks/types' +import { mapperOperation } from '@/blocks/utils' export const WorkdayBlock: BlockConfig = { type: 'workday', @@ -409,17 +410,9 @@ Output: {"Marital_Status_Reference":{"ID":{"attributes":{"wd:type":"Marital_Stat config: { tool: (params) => `workday_${params.operation}`, params: (params, context) => { - const { - operation: storedOperation, - orgType, - fields, - jobProfileId, - locationId, - supervisoryOrgId, - ...rest - } = params + const { orgType, fields, jobProfileId, locationId, supervisoryOrgId, ...rest } = params /** Agent tool calls carry the stored operation only on `context`, not in `params`. */ - const operation = storedOperation ?? context?.operation + const operation = mapperOperation(params, context) if (rest.limit != null && rest.limit !== '') rest.limit = Number(rest.limit) if (rest.offset != null && rest.offset !== '') rest.offset = Number(rest.offset) diff --git a/apps/sim/blocks/utils.ts b/apps/sim/blocks/utils.ts index ceffb5ed61d..7e554c256da 100644 --- a/apps/sim/blocks/utils.ts +++ b/apps/sim/blocks/utils.ts @@ -948,6 +948,21 @@ export function toolCallArg( return isToolCall(context) ? value : undefined } +/** + * The operation a block's `tools.config.params` mapper runs for. A tool call passes it only in + * `context`: a stored tool row keeps its operation outside its params, and a tool that declares its + * own `operation` param (Slack `edit_canvas`) gets the model's value there. The canvas passes no + * context, so the block's serialized `operation` input is used. Returns `''` when neither supplies + * one, so a default needs `||`, not `??`. + */ +export function mapperOperation( + params: { operation?: unknown }, + context: BlockToolParamsContext | undefined +): string { + if (context?.operation) return context.operation + return typeof params.operation === 'string' ? params.operation : '' +} + /** * Parses an optional boolean block input value. * Returns `undefined` for empty or unrecognized values. diff --git a/package.json b/package.json index 5bfee8991b3..c47de135725 100644 --- a/package.json +++ b/package.json @@ -88,6 +88,7 @@ "check:route-verbs": "bun run scripts/check-route-verbs.ts", "check:unused-exports": "bun run scripts/check-unused-exports.ts", "check:explicit-any": "bun run scripts/check-explicit-any.ts", + "check:mapper-operation": "bun run scripts/check-mapper-operation.ts", "check:file-names": "bun run scripts/check-file-names.ts", "check:source-conventions": "bun run scripts/check-source-conventions.ts", "check:test-types": "bun run scripts/check-test-types.ts", diff --git a/scripts/check-mapper-operation.baseline.json b/scripts/check-mapper-operation.baseline.json new file mode 100644 index 00000000000..13228879bf4 --- /dev/null +++ b/scripts/check-mapper-operation.baseline.json @@ -0,0 +1,175 @@ +{ + "apps/sim/blocks/blocks/affinity.ts": 1, + "apps/sim/blocks/blocks/agentmail.ts": 1, + "apps/sim/blocks/blocks/agentphone.ts": 1, + "apps/sim/blocks/blocks/algolia.ts": 1, + "apps/sim/blocks/blocks/amplitude.ts": 1, + "apps/sim/blocks/blocks/apollo.ts": 11, + "apps/sim/blocks/blocks/ashby.ts": 16, + "apps/sim/blocks/blocks/athena.ts": 1, + "apps/sim/blocks/blocks/azure_data_explorer.ts": 1, + "apps/sim/blocks/blocks/azure_devops.ts": 1, + "apps/sim/blocks/blocks/bitbucket.ts": 3, + "apps/sim/blocks/blocks/brex.ts": 1, + "apps/sim/blocks/blocks/brightdata.ts": 1, + "apps/sim/blocks/blocks/buffer.ts": 2, + "apps/sim/blocks/blocks/calcom.ts": 1, + "apps/sim/blocks/blocks/cbinsights.ts": 1, + "apps/sim/blocks/blocks/checkr.ts": 6, + "apps/sim/blocks/blocks/circleback.ts": 2, + "apps/sim/blocks/blocks/clerk.ts": 1, + "apps/sim/blocks/blocks/cloudflare.ts": 3, + "apps/sim/blocks/blocks/cloudformation.ts": 1, + "apps/sim/blocks/blocks/cloudtrail.ts": 1, + "apps/sim/blocks/blocks/cloudwatch.ts": 1, + "apps/sim/blocks/blocks/coda.ts": 1, + "apps/sim/blocks/blocks/codepipeline.ts": 1, + "apps/sim/blocks/blocks/confluence.ts": 2, + "apps/sim/blocks/blocks/context_dev.ts": 1, + "apps/sim/blocks/blocks/crowdstrike.ts": 2, + "apps/sim/blocks/blocks/crunchbase.ts": 1, + "apps/sim/blocks/blocks/dagster.ts": 8, + "apps/sim/blocks/blocks/datadog.ts": 1, + "apps/sim/blocks/blocks/daytona.ts": 1, + "apps/sim/blocks/blocks/deployments.ts": 1, + "apps/sim/blocks/blocks/discord.ts": 1, + "apps/sim/blocks/blocks/docusign.ts": 1, + "apps/sim/blocks/blocks/downdetector.ts": 1, + "apps/sim/blocks/blocks/dub.ts": 23, + "apps/sim/blocks/blocks/dynamodb.ts": 1, + "apps/sim/blocks/blocks/dynatrace.ts": 1, + "apps/sim/blocks/blocks/elevenlabs.ts": 2, + "apps/sim/blocks/blocks/emailbison.ts": 6, + "apps/sim/blocks/blocks/enrich.ts": 1, + "apps/sim/blocks/blocks/enrichment.ts": 2, + "apps/sim/blocks/blocks/exa.ts": 1, + "apps/sim/blocks/blocks/file.ts": 3, + "apps/sim/blocks/blocks/firecrawl.ts": 1, + "apps/sim/blocks/blocks/fireflies.ts": 2, + "apps/sim/blocks/blocks/fivetran.ts": 17, + "apps/sim/blocks/blocks/flint.ts": 1, + "apps/sim/blocks/blocks/github.ts": 2, + "apps/sim/blocks/blocks/gitlab.ts": 2, + "apps/sim/blocks/blocks/gmail.ts": 4, + "apps/sim/blocks/blocks/gong.ts": 1, + "apps/sim/blocks/blocks/google_appsheet.ts": 1, + "apps/sim/blocks/blocks/google_bigquery.ts": 1, + "apps/sim/blocks/blocks/google_calendar.ts": 1, + "apps/sim/blocks/blocks/google_drive.ts": 22, + "apps/sim/blocks/blocks/google_forms.ts": 1, + "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/grafana.ts": 1, + "apps/sim/blocks/blocks/grain.ts": 2, + "apps/sim/blocks/blocks/greenhouse.ts": 2, + "apps/sim/blocks/blocks/harmonic.ts": 1, + "apps/sim/blocks/blocks/helpscout.ts": 2, + "apps/sim/blocks/blocks/hex.ts": 1, + "apps/sim/blocks/blocks/iam.ts": 1, + "apps/sim/blocks/blocks/identity_center.ts": 1, + "apps/sim/blocks/blocks/incidentio.ts": 9, + "apps/sim/blocks/blocks/infisical.ts": 1, + "apps/sim/blocks/blocks/instagram.ts": 2, + "apps/sim/blocks/blocks/instantly.ts": 17, + "apps/sim/blocks/blocks/jira.ts": 1, + "apps/sim/blocks/blocks/jira_service_management.ts": 1, + "apps/sim/blocks/blocks/jotform.ts": 1, + "apps/sim/blocks/blocks/jupyter.ts": 1, + "apps/sim/blocks/blocks/kalshi.ts": 1, + "apps/sim/blocks/blocks/ketch.ts": 4, + "apps/sim/blocks/blocks/knowledge.ts": 11, + "apps/sim/blocks/blocks/lambda.ts": 2, + "apps/sim/blocks/blocks/langsmith.ts": 4, + "apps/sim/blocks/blocks/latex.ts": 1, + "apps/sim/blocks/blocks/launchdarkly.ts": 1, + "apps/sim/blocks/blocks/linear.ts": 1, + "apps/sim/blocks/blocks/linkedin.ts": 1, + "apps/sim/blocks/blocks/linq.ts": 2, + "apps/sim/blocks/blocks/logfire.ts": 1, + "apps/sim/blocks/blocks/logrocket.ts": 1, + "apps/sim/blocks/blocks/logs.ts": 2, + "apps/sim/blocks/blocks/loops.ts": 1, + "apps/sim/blocks/blocks/mailgun.ts": 1, + "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/modal.ts": 1, + "apps/sim/blocks/blocks/netsuite.ts": 2, + "apps/sim/blocks/blocks/new_relic.ts": 1, + "apps/sim/blocks/blocks/okta.ts": 2, + "apps/sim/blocks/blocks/onedrive.ts": 3, + "apps/sim/blocks/blocks/otter.ts": 1, + "apps/sim/blocks/blocks/outlook.ts": 17, + "apps/sim/blocks/blocks/pagerduty.ts": 1, + "apps/sim/blocks/blocks/parallel.ts": 1, + "apps/sim/blocks/blocks/peopledatalabs.ts": 1, + "apps/sim/blocks/blocks/perplexity.ts": 1, + "apps/sim/blocks/blocks/persona.ts": 1, + "apps/sim/blocks/blocks/pitchbook.ts": 1, + "apps/sim/blocks/blocks/plane.ts": 1, + "apps/sim/blocks/blocks/planetscale.ts": 2, + "apps/sim/blocks/blocks/polymarket.ts": 1, + "apps/sim/blocks/blocks/powerbi.ts": 1, + "apps/sim/blocks/blocks/profound.ts": 1, + "apps/sim/blocks/blocks/railway.ts": 1, + "apps/sim/blocks/blocks/rds.ts": 1, + "apps/sim/blocks/blocks/reddit.ts": 1, + "apps/sim/blocks/blocks/revenuecat.ts": 2, + "apps/sim/blocks/blocks/rippling.ts": 1, + "apps/sim/blocks/blocks/rocketlane.ts": 1, + "apps/sim/blocks/blocks/rootly.ts": 1, + "apps/sim/blocks/blocks/s3.ts": 1, + "apps/sim/blocks/blocks/sailpoint.ts": 1, + "apps/sim/blocks/blocks/secrets_manager.ts": 1, + "apps/sim/blocks/blocks/sendblue.ts": 1, + "apps/sim/blocks/blocks/sendgrid.ts": 1, + "apps/sim/blocks/blocks/ses.ts": 1, + "apps/sim/blocks/blocks/sftp.ts": 1, + "apps/sim/blocks/blocks/sharepoint.ts": 6, + "apps/sim/blocks/blocks/shopify.ts": 1, + "apps/sim/blocks/blocks/sixtyfour.ts": 4, + "apps/sim/blocks/blocks/slack.ts": 6, + "apps/sim/blocks/blocks/smartlead.ts": 5, + "apps/sim/blocks/blocks/snowflake.ts": 1, + "apps/sim/blocks/blocks/splunk.ts": 1, + "apps/sim/blocks/blocks/sqs.ts": 1, + "apps/sim/blocks/blocks/ssh.ts": 1, + "apps/sim/blocks/blocks/ssm.ts": 1, + "apps/sim/blocks/blocks/stagehand.ts": 2, + "apps/sim/blocks/blocks/stripe.ts": 1, + "apps/sim/blocks/blocks/sts.ts": 1, + "apps/sim/blocks/blocks/supabase.ts": 1, + "apps/sim/blocks/blocks/table.ts": 1, + "apps/sim/blocks/blocks/table_v2.ts": 1, + "apps/sim/blocks/blocks/tailscale.ts": 3, + "apps/sim/blocks/blocks/telegram.ts": 1, + "apps/sim/blocks/blocks/temporal.ts": 12, + "apps/sim/blocks/blocks/textract.ts": 1, + "apps/sim/blocks/blocks/tiktok.ts": 1, + "apps/sim/blocks/blocks/tinybird.ts": 1, + "apps/sim/blocks/blocks/tinyfish.ts": 1, + "apps/sim/blocks/blocks/trello.ts": 1, + "apps/sim/blocks/blocks/trigger_dev.ts": 1, + "apps/sim/blocks/blocks/twilio_voice.ts": 1, + "apps/sim/blocks/blocks/vanta.ts": 1, + "apps/sim/blocks/blocks/vercel.ts": 1, + "apps/sim/blocks/blocks/wealthbox.ts": 1, + "apps/sim/blocks/blocks/webflow.ts": 4, + "apps/sim/blocks/blocks/whatsapp.ts": 1, + "apps/sim/blocks/blocks/wordpress.ts": 1, + "apps/sim/blocks/blocks/zendesk.ts": 1, + "apps/sim/blocks/blocks/zep.ts": 1, + "apps/sim/blocks/blocks/zoho-desk.ts": 38, + "apps/sim/blocks/blocks/zoom.ts": 1 +} diff --git a/scripts/check-mapper-operation.test.ts b/scripts/check-mapper-operation.test.ts new file mode 100644 index 00000000000..fd06118ade7 --- /dev/null +++ b/scripts/check-mapper-operation.test.ts @@ -0,0 +1,135 @@ +import { describe, expect, it } from 'vitest' +import { countMapperOperationReads } from './check-mapper-operation' + +/** Wraps a mapper body in the block shape the audit walks. */ +function block(mapper: string, extra = ''): string { + return `${extra}\nexport const XBlock = { tools: { access: [], config: { tool: (p) => p.operation, params: ${mapper} } } }` +} + +const count = (source: string) => countMapperOperationReads('x.ts', source) + +describe('countMapperOperationReads', () => { + it('flags every way a mapper can read the operation from its params', () => { + expect(count(block(`(params) => (params.operation === 'a' ? {} : {})`))).toBe(1) + expect(count(block(`(params) => (params?.operation === 'a' ? {} : {})`))).toBe(1) + expect(count(block(`(params) => (params['operation'] === 'a' ? {} : {})`))).toBe(1) + expect(count(block(`(params) => ((params as X).operation === 'a' ? {} : {})`))).toBe(1) + expect(count(block(`({ operation }) => (operation === 'a' ? {} : {})`))).toBe(1) + expect( + count( + block( + `(params) => { const { operation, ...rest } = params; return operation === 'a' ? rest : {} }` + ) + ) + ).toBe(1) + }) + + it('follows aliases of params and same-file helpers the mapper hands them to', () => { + expect( + count(block(`(params) => { const p = params; return p.operation === 'a' ? {} : {} }`)) + ).toBe(1) + expect( + count(block(`(params) => { const p = { ...params }; return p.operation ? {} : {} }`)) + ).toBe(1) + expect( + count(block(`(params) => { const { a, ...rest } = params; return rest.operation ? {} : {} }`)) + ).toBe(1) + expect( + count( + block( + '(params) => build(params)', + `function build(input) { return input.operation === 'a' ? {} : {} }` + ) + ) + ).toBe(1) + expect(count(block('mapX', `const mapX = (params) => (params.operation ? {} : {})`))).toBe(1) + }) + + it('tracks the argument position a helper receives params at, a destructured rest, and helper results', () => { + expect( + count( + block( + '(params) => build({}, params)', + `function build(options, input) { return input.operation === 'a' ? options : {} }` + ) + ) + ).toBe(1) + expect( + count( + block( + '(params) => build(params, {})', + `function build(input, options) { return options.operation === 'a' ? input : {} }` + ) + ) + ).toBe(0) + expect(count(block(`({ credential, ...rest }) => (rest.operation === 'a' ? {} : {})`))).toBe(1) + expect( + count( + block( + `(params) => { const normalized = normalize(params); return normalized.operation === 'a' ? {} : {} }`, + 'function normalize(input) { return { ...input } }' + ) + ) + ).toBe(1) + }) + + it('reads helper arguments, destructures from spread aliases, and trusts helpers that build a new object', () => { + expect( + count( + block( + '(params) => { const built = build(params, params.operation); return built }', + 'function build(input, extra) { return { input, extra } }' + ) + ) + ).toBe(1) + expect( + count( + block( + `(params) => { const { operation } = { ...params }; return operation === 'a' ? {} : {} }` + ) + ) + ).toBe(1) + expect( + count( + block( + `(params) => { const built = build(params); return built.operation === 'a' ? {} : {} }`, + `function build(input) { return { operation: 'derived', mode: input.mode } }` + ) + ) + ).toBe(0) + expect( + count( + block( + `(params) => { const result = normalize(params); return result.operation === 'a' ? {} : {} }`, + 'function normalize(input) { const copy = { ...input }; return copy }' + ) + ) + ).toBe(1) + }) + + it('does not count a nested callback parameter that reuses an alias name', () => { + expect( + count(block(`(params) => ({ items: params.items.map((params) => params.operation) })`)) + ).toBe(0) + expect( + count( + block( + `(params) => { const { operation, ...rest } = params; return { list: rest.items.map((operation) => operation) } }` + ) + ) + ).toBe(0) + }) + + it('does not flag strip-only destructuring, the helper, or the tool selector', () => { + expect(count(block(`(params) => { const { operation, ...rest } = params; return rest }`))).toBe( + 0 + ) + expect( + count(block(`(params) => { const { operation: _operation, ...rest } = params; return rest }`)) + ).toBe(0) + expect( + count(block(`(params, context) => (mapperOperation(params, context) === 'a' ? {} : {})`)) + ).toBe(0) + expect(count(block('(params) => ({ ...params })'))).toBe(0) + }) +}) diff --git a/scripts/check-mapper-operation.ts b/scripts/check-mapper-operation.ts new file mode 100644 index 00000000000..97a09cb4944 --- /dev/null +++ b/scripts/check-mapper-operation.ts @@ -0,0 +1,411 @@ +#!/usr/bin/env bun +/** + * Ratchets block mappers that read the operation from their params down to zero, file by file. + * + * A block's `tools.config.params` mapper runs on two paths with different inputs. On the canvas it + * receives the block's serialized inputs, `operation` included, and no second argument. On a tool + * call (an Agent tool row, Pi, Human-in-the-loop v2) it receives the stored tool row's params merged + * with the model's args, and the operation arrives only as `context.operation`: a stored row keeps + * its operation outside its params, and six tools declare their own `operation` param that the model + * fills with a tool value (Slack `edit_canvas`'s `'insert_after'`). A mapper that branches on + * `params.operation` therefore takes its no-operation path on every tool call: it skips the + * coercions and field renames the tool needs, drops a file the user picked, or throws + * `Invalid operation: undefined` and leaves the tool with unmerged raw params. + * + * The fix is `mapperOperation(params, context)` from `@/blocks/utils`, which reads the trusted + * context first and falls back to the canvas input. Switching to it makes branches live on tool + * calls that never ran there, so review each one: where a branch assigns a tool param from a + * block-only field, keep the model's value with `dedicated ?? toolCallArg(context, params.x)`. + * + * Flagged, inside a mapper and in same-file helpers it hands its params to: + * - `params.operation`, `params?.operation`, `params['operation']`, through any alias of `params` + * (`const p = params`, `const { a, ...rest } = params`, `const p = { ...params }`); + * - a destructured `operation` binding that is used. Strip-only destructuring + * (`const { operation, ...rest } = params` with `operation` unused) is not a read. + * + * - A file whose count rises, or a file that gains its first read, fails. + * - A file whose count drops fails until the baseline is rewritten, so the baseline only shrinks. + * + * Regenerate after fixing mappers: `bun run scripts/check-mapper-operation.ts --update` (it refuses to + * raise any file's count). + * + * Run: `bun run check:mapper-operation` + */ +import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import ts from '@typescript/typescript6' + +const ROOT = fileURLToPath(new URL('..', import.meta.url)) +const BLOCKS_DIR = path.join(ROOT, 'apps/sim/blocks/blocks') +const BASELINE = path.join(ROOT, 'scripts/check-mapper-operation.baseline.json') + +type Fn = ts.ArrowFunction | ts.FunctionExpression | ts.FunctionDeclaration | ts.MethodDeclaration + +function isFn(node: ts.Node): node is Fn { + return ( + ts.isArrowFunction(node) || + ts.isFunctionExpression(node) || + ts.isFunctionDeclaration(node) || + ts.isMethodDeclaration(node) + ) +} + +function keyName(name: ts.Node | undefined): string | undefined { + if (!name) return undefined + if (ts.isIdentifier(name) || ts.isStringLiteral(name)) return name.text + return undefined +} + +/** Strips `(x)`, `x as T`, `x!`, and `x satisfies T` so an aliased read is still seen. */ +function unwrap(node: ts.Expression): ts.Expression { + let current = node + while ( + ts.isParenthesizedExpression(current) || + ts.isAsExpression(current) || + ts.isNonNullExpression(current) || + ts.isSatisfiesExpression(current) || + ts.isTypeAssertionExpression(current) + ) { + current = current.expression + } + return current +} + +function findLocalFn(source: ts.SourceFile, name: string): Fn | undefined { + let found: Fn | undefined + const visit = (node: ts.Node) => { + if (found) return + if (ts.isFunctionDeclaration(node) && node.name?.text === name) { + found = node + return + } + if ( + ts.isVariableDeclaration(node) && + ts.isIdentifier(node.name) && + node.name.text === name && + node.initializer + ) { + const init = unwrap(node.initializer) + if (isFn(init)) { + found = init + return + } + } + ts.forEachChild(node, visit) + } + visit(source) + return found +} + +/** Names a binding pattern or identifier declares. */ +function boundNames(name: ts.BindingName, into: Set = new Set()): Set { + if (ts.isIdentifier(name)) into.add(name.text) + else + for (const element of name.elements) + if (!ts.isOmittedExpression(element)) boundNames(element.name, into) + return into +} + +/** Names a nested function's own parameters declare, which shadow the outer ones in its body. */ +function shadowedBy(node: ts.Node): Set { + const names = new Set() + if (isFn(node)) for (const parameter of node.parameters) boundNames(parameter.name, names) + return names +} + +/** Identifier uses of `name` inside `scope`, excluding declarations, property names, and shadowed scopes. */ +function referencesOf(scope: ts.Node, name: string, declaration: ts.Node): number { + let count = 0 + const visit = (node: ts.Node) => { + if (node !== scope && shadowedBy(node).has(name)) return + if (ts.isIdentifier(node) && node.text === name && node !== declaration) { + const parent = node.parent + const isPropertyName = + (ts.isPropertyAccessExpression(parent) && parent.name === node) || + (ts.isPropertyAssignment(parent) && parent.name === node) || + (ts.isBindingElement(parent) && parent.propertyName === node) + if (!isPropertyName) count++ + } + ts.forEachChild(node, visit) + } + visit(scope) + return count +} + +function enclosingFn(node: ts.Node): ts.Node { + let current: ts.Node = node + while (current.parent && !isFn(current)) current = current.parent + return current +} + +/** Counts destructured `operation` bindings that are used afterwards. */ +function usedOperationBindings(pattern: ts.ObjectBindingPattern): number { + let reads = 0 + for (const element of pattern.elements) { + if (element.dotDotDotToken) continue + const key = keyName(element.propertyName) ?? keyName(element.name) + if (key !== 'operation') continue + if (!ts.isIdentifier(element.name)) { + reads++ + continue + } + if (referencesOf(enclosingFn(element), element.name.text, element.name) > 0) reads++ + } + return reads +} + +/** Rest bindings of a destructuring are aliases of the object they were taken from. */ +function restAlias(pattern: ts.ObjectBindingPattern): string | undefined { + const rest = pattern.elements.find((element) => element.dotDotDotToken) + return rest && ts.isIdentifier(rest.name) ? rest.name.text : undefined +} + +/** + * Whether `fn` returns its parameter `index` itself, a local copy of it, or an object literal spreading + * either, so the + * caller's result still carries the input's `operation`. + */ +function returnsInput(fn: Fn, index: number): boolean { + const parameter = fn.parameters[index] + if (!parameter || !ts.isIdentifier(parameter.name) || !fn.body) return false + const names = new Set([parameter.name.text]) + const carries = (expression: ts.Expression): boolean => { + const value = unwrap(expression) + if (ts.isIdentifier(value)) return names.has(value.text) + return ( + ts.isObjectLiteralExpression(value) && + value.properties.some( + (property) => ts.isSpreadAssignment(property) && carries(property.expression) + ) + ) + } + if (!ts.isBlock(fn.body)) return carries(fn.body) + let found = false + const visit = (node: ts.Node) => { + if (found || (node !== fn.body && isFn(node))) return + if ( + ts.isVariableDeclaration(node) && + ts.isIdentifier(node.name) && + node.initializer && + carries(node.initializer) + ) { + names.add(node.name.text) + } + if (ts.isReturnStatement(node) && node.expression && carries(node.expression)) found = true + ts.forEachChild(node, visit) + } + visit(fn.body) + return found +} + +/** + * Counts operation reads from parameter `index` of `fn`: through aliases of it, and through + * same-file helpers it is handed to (at whichever argument position), whose returned value is + * treated as an alias too. Names a nested function rebinds are not aliases inside it. + */ +function operationReads(source: ts.SourceFile, fn: Fn, index: number, seen: Set): number { + const key = `${fn.pos}:${index}` + if (seen.has(key)) return 0 + seen.add(key) + const parameter = fn.parameters[index] + if (!parameter || !fn.body) return 0 + + let reads = 0 + const initial = new Set() + if (ts.isIdentifier(parameter.name)) initial.add(parameter.name.text) + else if (ts.isObjectBindingPattern(parameter.name)) { + reads += usedOperationBindings(parameter.name) + const rest = restAlias(parameter.name) + if (rest) initial.add(rest) + } + if (initial.size === 0) return reads + + const isAlias = (expression: ts.Expression, aliases: Set) => { + const value = unwrap(expression) + return ts.isIdentifier(value) && aliases.has(value.text) + } + + /** + * Counts reads inside a same-file helper at each argument position that receives an alias. + * Returns whether the helper hands one of those inputs back (see {@link returnsInput}), which + * makes its result an alias too. + */ + const helperCall = (node: ts.Expression, aliases: Set): boolean => { + const call = unwrap(node) + if (!ts.isCallExpression(call) || !ts.isIdentifier(call.expression)) return false + const helper = findLocalFn(source, call.expression.text) + if (!helper) return false + let carriesInput = false + call.arguments.forEach((argument, position) => { + if (!isAlias(argument, aliases)) return + reads += operationReads(source, helper, position, seen) + if (returnsInput(helper, position)) carriesInput = true + }) + return carriesInput + } + + const visit = (node: ts.Node, inherited: Set) => { + let aliases = inherited + if (node !== fn) { + const shadowed = shadowedBy(node) + if (shadowed.size) aliases = new Set([...inherited].filter((name) => !shadowed.has(name))) + } + if (ts.isVariableDeclaration(node) && node.initializer) { + const init = unwrap(node.initializer) + const fromAlias = isAlias(init, aliases) + const spreadsAlias = + ts.isObjectLiteralExpression(init) && + init.properties.some( + (property) => ts.isSpreadAssignment(property) && isAlias(property.expression, aliases) + ) + const fromHelper = helperCall(init, aliases) + if ((fromAlias || spreadsAlias || fromHelper) && ts.isObjectBindingPattern(node.name)) { + reads += usedOperationBindings(node.name) + const rest = restAlias(node.name) + if (rest) inherited.add(rest) + } else if ((fromAlias || spreadsAlias || fromHelper) && ts.isIdentifier(node.name)) { + inherited.add(node.name.text) + } + if ( + ts.isCallExpression(init) && + ts.isIdentifier(init.expression) && + findLocalFn(source, init.expression.text) + ) { + for (const argument of init.arguments) visit(argument, aliases) + return + } + } + if (ts.isPropertyAccessExpression(node) && node.name.text === 'operation') { + if (isAlias(node.expression, aliases)) reads++ + } + if (ts.isElementAccessExpression(node)) { + const argument = node.argumentExpression + if ( + isAlias(node.expression, aliases) && + ts.isStringLiteralLike(argument) && + argument.text === 'operation' + ) { + reads++ + } + } + if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) { + if (findLocalFn(source, node.expression.text)) { + helperCall(node, aliases) + for (const argument of node.arguments) visit(argument, aliases) + return + } + } + ts.forEachChild(node, (child) => visit(child, aliases)) + } + visit(fn.body, initial) + return reads +} + +/** Counts operation reads across every `tools.config.params` mapper in one block file. */ +export function countMapperOperationReads(fileName: string, text: string): number { + const source = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true) + let reads = 0 + const visit = (node: ts.Node) => { + if ( + ts.isPropertyAssignment(node) && + keyName(node.name) === 'config' && + ts.isObjectLiteralExpression(node.initializer) && + ts.isPropertyAssignment(node.parent.parent) && + keyName(node.parent.parent.name) === 'tools' + ) { + for (const property of node.initializer.properties) { + if (keyName(property.name) !== 'params') continue + let mapper: Fn | undefined + if (ts.isMethodDeclaration(property)) mapper = property + else if (ts.isPropertyAssignment(property)) { + const init = unwrap(property.initializer) + mapper = isFn(init) + ? init + : ts.isIdentifier(init) + ? findLocalFn(source, init.text) + : undefined + } else if (ts.isShorthandPropertyAssignment(property)) { + mapper = findLocalFn(source, property.name.text) + } + if (mapper) reads += operationReads(source, mapper, 0, new Set()) + } + } + ts.forEachChild(node, visit) + } + visit(source) + return reads +} + +function collect(): Record { + const counts: Record = {} + for (const entry of readdirSync(BLOCKS_DIR).sort()) { + if (!entry.endsWith('.ts') || entry.endsWith('.test.ts')) continue + const file = path.join(BLOCKS_DIR, entry) + const reads = countMapperOperationReads(entry, readFileSync(file, 'utf8')) + if (reads > 0) counts[path.relative(ROOT, file)] = reads + } + return counts +} + +if (import.meta.main) { + const current = collect() + const init = process.argv.includes('--init') + if (!existsSync(BASELINE) && !init) { + console.error( + `✗ ${path.relative(ROOT, BASELINE)} is missing. Restore it from git; create one only with --update --init.` + ) + process.exit(1) + } + const baseline: Record = existsSync(BASELINE) + ? JSON.parse(readFileSync(BASELINE, 'utf8')) + : current + + if (process.argv.includes('--update')) { + const raised = Object.entries(current).filter(([file, count]) => count > (baseline[file] ?? 0)) + if (raised.length) { + console.error( + `✗ Refused to raise the baseline for ${raised.length} file(s); fix them instead:` + ) + for (const [file, count] of raised) + console.error(` ${file}: ${count} (baseline ${baseline[file] ?? 0})`) + process.exit(1) + } + writeFileSync(BASELINE, `${JSON.stringify(current, null, 2)}\n`) + const total = Object.values(current).reduce((sum, count) => sum + count, 0) + console.log(`Wrote ${Object.keys(current).length} files (${total} reads) to ${BASELINE}`) + process.exit(0) + } + + const rose: string[] = [] + const dropped: string[] = [] + for (const file of new Set([...Object.keys(baseline), ...Object.keys(current)])) { + const was = baseline[file] ?? 0 + const now = current[file] ?? 0 + if (now > was) rose.push(` ${file}: ${was} → ${now}`) + else if (now < was) dropped.push(` ${file}: ${was} → ${now}`) + } + + if (rose.length) { + console.error( + '✗ Block mappers read the operation from params, which is undefined on tool calls:' + ) + for (const line of rose) console.error(line) + console.error( + 'Read it with `mapperOperation(params, context)` from `@/blocks/utils` (declare the mapper as ' + + '`(params, context?: BlockToolParamsContext)`), and keep model args in branches that become live ' + + 'with `dedicated ?? toolCallArg(context, params.x)`.' + ) + } + if (dropped.length) { + console.error('✗ Mapper operation reads dropped; shrink the baseline:') + for (const line of dropped) console.error(line) + console.error('Run: bun run scripts/check-mapper-operation.ts --update') + } + if (rose.length || dropped.length) process.exit(1) + + const total = Object.values(current).reduce((sum, count) => sum + count, 0) + console.log( + `✓ Mapper operation reads match the baseline (${total} in ${Object.keys(current).length} files)` + ) +}