diff --git a/apps/docs/content/docs/integrations/brex.mdx b/apps/docs/content/docs/integrations/brex.mdx index db1e97f70a1..22c4ed719e3 100644 --- a/apps/docs/content/docs/integrations/brex.mdx +++ b/apps/docs/content/docs/integrations/brex.mdx @@ -39,7 +39,7 @@ List expenses in the Brex account with optional filters for user, status, paymen | --------- | ---- | -------- | ----------- | | `userIds` | string | No | Comma-separated user IDs to filter expenses by owner | | `statuses` | string | No | Comma-separated expense statuses to filter by: DRAFT, SUBMITTED, APPROVED, OUT_OF_POLICY, VOID, CANCELED, SPLIT, SETTLED | -| `paymentStatuses` | string | No | Comma-separated payment statuses to filter by: NOT_STARTED, PROCESSING, CANCELED, DECLINED, CLEARED, REFUNDING, REFUNDED, CASH_ADVANCE, CREDITED, AWAITING_PAYMENT, SCHEDULED | +| `paymentStatuses` | string | No | Comma-separated payment statuses to filter by: NOT_STARTED, PROCESSING, CANCELED, DECLINED, CLEARED, REFUNDING, REFUNDED, CASH_ADVANCE, CREDITED, AWAITING_PAYMENT, SCHEDULED, HELD | | `purchasedAtStart` | string | No | Only include expenses purchased at or after this ISO 8601 timestamp | | `purchasedAtEnd` | string | No | Only include expenses purchased at or before this ISO 8601 timestamp | | `cursor` | string | No | Pagination cursor from a previous response | @@ -53,7 +53,7 @@ List expenses in the Brex account with optional filters for user, status, paymen | ↳ `id` | string | Unique expense ID | | ↳ `memo` | string | Memo on the expense | | ↳ `status` | string | Expense status \(DRAFT, SUBMITTED, APPROVED, OUT_OF_POLICY, VOID, CANCELED, SPLIT, SETTLED\) | -| ↳ `payment_status` | string | Payment status \(NOT_STARTED, PROCESSING, CANCELED, DECLINED, CLEARED, REFUNDING, REFUNDED, CASH_ADVANCE, CREDITED, AWAITING_PAYMENT, SCHEDULED\) | +| ↳ `payment_status` | string | Payment status \(NOT_STARTED, PROCESSING, CANCELED, DECLINED, CLEARED, REFUNDING, REFUNDED, CASH_ADVANCE, CREDITED, AWAITING_PAYMENT, SCHEDULED, HELD\) | | ↳ `expense_type` | string | Expense type \(CARD, BILLPAY, REIMBURSEMENT, CLAWBACK, UNSET\) | | ↳ `category` | string | Expense category \(e.g., RESTAURANTS, RECURRING_SOFTWARE_AND_SAAS, AIRLINE_EXPENSES\) | | ↳ `merchant` | json | Merchant details | @@ -111,7 +111,7 @@ Get a single Brex expense by its ID, including merchant, user, and receipt detai | `id` | string | Unique expense ID | | `memo` | string | Memo on the expense | | `status` | string | Expense status \(DRAFT, SUBMITTED, APPROVED, OUT_OF_POLICY, VOID, CANCELED, SPLIT, SETTLED\) | -| `paymentStatus` | string | Payment status \(NOT_STARTED, PROCESSING, CANCELED, DECLINED, CLEARED, REFUNDING, REFUNDED, CASH_ADVANCE, CREDITED, AWAITING_PAYMENT, SCHEDULED\) | +| `paymentStatus` | string | Payment status \(NOT_STARTED, PROCESSING, CANCELED, DECLINED, CLEARED, REFUNDING, REFUNDED, CASH_ADVANCE, CREDITED, AWAITING_PAYMENT, SCHEDULED, HELD\) | | `expenseType` | string | Expense type \(CARD, BILLPAY, REIMBURSEMENT, CLAWBACK, UNSET\) | | `category` | string | Expense category \(e.g., RESTAURANTS, RECURRING_SOFTWARE_AND_SAAS, AIRLINE_EXPENSES\) | | `merchantId` | string | Merchant ID | @@ -178,7 +178,7 @@ Update the memo of a Brex card expense | `id` | string | Unique expense ID | | `memo` | string | Updated memo on the expense | | `status` | string | Expense status \(DRAFT, SUBMITTED, APPROVED, OUT_OF_POLICY, VOID, CANCELED, SPLIT, SETTLED\) | -| `paymentStatus` | string | Payment status \(NOT_STARTED, PROCESSING, CANCELED, DECLINED, CLEARED, REFUNDING, REFUNDED, CASH_ADVANCE, CREDITED, AWAITING_PAYMENT, SCHEDULED\) | +| `paymentStatus` | string | Payment status \(NOT_STARTED, PROCESSING, CANCELED, DECLINED, CLEARED, REFUNDING, REFUNDED, CASH_ADVANCE, CREDITED, AWAITING_PAYMENT, SCHEDULED, HELD\) | | `category` | string | Expense category \(e.g., RESTAURANTS, RECURRING_SOFTWARE_AND_SAAS, AIRLINE_EXPENSES\) | | `merchantId` | string | Merchant ID | | `budgetId` | string | Budget ID | @@ -491,7 +491,7 @@ List users in the Brex account, optionally filtered by email | ↳ `first_name` | string | First name | | ↳ `last_name` | string | Last name | | ↳ `email` | string | Email address | -| ↳ `status` | string | User status \(INVITED, ACTIVE, CLOSED, DISABLED, DELETED, PENDING_ACTIVATION, INACTIVE, ARCHIVED\) | +| ↳ `status` | string | User status \(INVITED, ACTIVE, DISABLED, PENDING_ACTIVATION, INACTIVE, ARCHIVED\) | | ↳ `manager_id` | string | ID of the manager | | ↳ `department_id` | string | Department ID | | ↳ `location_id` | string | Location ID | @@ -520,7 +520,7 @@ Get a Brex user by their ID | `firstName` | string | First name | | `lastName` | string | Last name | | `email` | string | Email address | -| `status` | string | User status \(INVITED, ACTIVE, CLOSED, DISABLED, DELETED, PENDING_ACTIVATION, INACTIVE, ARCHIVED\) | +| `status` | string | User status \(INVITED, ACTIVE, DISABLED, PENDING_ACTIVATION, INACTIVE, ARCHIVED\) | | `managerId` | string | ID of the manager | | `departmentId` | string | Department ID | | `locationId` | string | Location ID | @@ -547,7 +547,7 @@ Get the Brex user associated with the API token | `firstName` | string | First name | | `lastName` | string | Last name | | `email` | string | Email address | -| `status` | string | User status \(INVITED, ACTIVE, CLOSED, DISABLED, DELETED, PENDING_ACTIVATION, INACTIVE, ARCHIVED\) | +| `status` | string | User status \(INVITED, ACTIVE, DISABLED, PENDING_ACTIVATION, INACTIVE, ARCHIVED\) | | `managerId` | string | ID of the manager | | `departmentId` | string | Department ID | | `locationId` | string | Location ID | @@ -656,6 +656,7 @@ List cards in the Brex account, optionally filtered by card owner | ↳ `status` | string | Card status | | ↳ `last_four` | string | Last four digits of the card number | | ↳ `card_name` | string | Card name | +| ↳ `created_at` | string | Card creation timestamp | | ↳ `card_type` | string | Card type \(VIRTUAL or PHYSICAL\) | | ↳ `limit_type` | string | Limit type \(CARD or USER\) | | ↳ `spend_controls` | json | Spend controls on the card | @@ -752,7 +753,7 @@ Get a Brex budget by its ID | `amount` | json | Budget amount | | ↳ `amount` | number | Amount in the smallest unit of the currency \(e.g., cents for USD\) | | ↳ `currency` | string | ISO 4217 currency code \(e.g., USD\) | -| `spendBudgetStatus` | string | Budget status \(ACTIVE, ARCHIVED, DELETED\) | +| `spendBudgetStatus` | string | Budget status \(ACTIVE, ARCHIVED, DELETED, EXPIRED\) | | `limitType` | string | Budget limit type \(HARD or SOFT\) | @@ -887,7 +888,7 @@ Get a Brex spend limit by its ID | `name` | string | Spend limit name | | `description` | string | Spend limit description | | `parentBudgetId` | string | Parent budget ID | -| `status` | string | Spend limit status \(ACTIVE, EXPIRED, ARCHIVED\) | +| `status` | string | Spend limit status \(ACTIVE, EXPIRED, ARCHIVED, DELETED\) | | `periodRecurrenceType` | string | Period recurrence \(PER_WEEK, PER_MONTH, PER_QUARTER, PER_YEAR, ONE_TIME\) | | `spendType` | string | Spend type of the limit | | `startDate` | string | Spend limit start date | @@ -932,7 +933,7 @@ Create a new spend limit (hard-authorization card program) in the Brex account | `currency` | string | No | ISO 4217 currency code for the base limit \(defaults to USD\) | | `authorizationType` | string | Yes | Whether authorizations decline based on available balance \(HARD, SOFT\) | | `rolloverRefreshRate` | string | Yes | Recurrence at which rolled-over unused funds stop rolling over \(OFF, NEVER, PER_MONTH, PER_QUARTER, PER_YEAR\) | -| `limitBufferPercentage` | number | No | Flexible buffer on the limit as a 0-100 percentage | +| `limitBufferPercentage` | number | No | Flexible buffer on the limit as a whole-number percentage from 0 to 100 | | `description` | string | No | Description of what the spend limit is used for | | `parentBudgetId` | string | No | ID of the parent budget | | `startDate` | string | No | Date the spend limit should start counting \(YYYY-MM-DD\) | diff --git a/apps/docs/content/docs/integrations/calcom.mdx b/apps/docs/content/docs/integrations/calcom.mdx index 9f23780f0de..a9b0c5ce177 100644 --- a/apps/docs/content/docs/integrations/calcom.mdx +++ b/apps/docs/content/docs/integrations/calcom.mdx @@ -156,7 +156,7 @@ Get details of a specific booking by its UID ### Cal.com List Bookings -List all bookings with optional status filter +List bookings, optionally filtered by status, attendee email, or time range @@ -167,6 +167,10 @@ List all bookings with optional status filter | `status` | string | No | Filter bookings by status: upcoming, recurring, past, cancelled, or unconfirmed | | `take` | number | No | Number of bookings to return \(pagination limit\) | | `skip` | number | No | Number of bookings to skip \(pagination offset\) | +| `attendeeEmail` | string | No | Only return bookings that include an attendee with this email | +| `afterStart` | string | No | Only return bookings starting after this ISO 8601 time | +| `beforeEnd` | string | No | Only return bookings ending before this ISO 8601 time | +| `sortStart` | string | No | Sort bookings by start time: asc or desc | #### Output @@ -485,6 +489,9 @@ Create a new event type in Cal.com | ↳ `disableGuests` | boolean | Whether guests are disabled | | ↳ `createdAt` | string | ISO timestamp of creation | | ↳ `updatedAt` | string | ISO timestamp of last update | +| ↳ `bookingUrl` | string | Public booking page URL for the event type | +| ↳ `hidden` | boolean | Whether the event type is hidden from the profile | +| ↳ `ownerId` | number | ID of the user who owns the event type | @@ -519,6 +526,9 @@ Get detailed information about a specific event type | ↳ `disableGuests` | boolean | Whether guests are disabled | | ↳ `createdAt` | string | ISO timestamp of creation | | ↳ `updatedAt` | string | ISO timestamp of last update | +| ↳ `bookingUrl` | string | Public booking page URL for the event type | +| ↳ `hidden` | boolean | Whether the event type is hidden from the profile | +| ↳ `ownerId` | number | ID of the user who owns the event type | @@ -553,6 +563,9 @@ Retrieve a list of all event types | ↳ `disableGuests` | boolean | Whether guests are disabled | | ↳ `createdAt` | string | ISO timestamp of creation | | ↳ `updatedAt` | string | ISO timestamp of last update | +| ↳ `bookingUrl` | string | Public booking page URL for the event type | +| ↳ `hidden` | boolean | Whether the event type is hidden from the profile | +| ↳ `ownerId` | number | ID of the user who owns the event type | @@ -597,6 +610,9 @@ Update an existing event type in Cal.com | ↳ `disableGuests` | boolean | Whether guests are disabled | | ↳ `createdAt` | string | ISO timestamp of creation | | ↳ `updatedAt` | string | ISO timestamp of last update | +| ↳ `bookingUrl` | string | Public booking page URL for the event type | +| ↳ `hidden` | boolean | Whether the event type is hidden from the profile | +| ↳ `ownerId` | number | ID of the user who owns the event type | diff --git a/apps/docs/content/docs/integrations/calendly.mdx b/apps/docs/content/docs/integrations/calendly.mdx index 1b257c6091d..bdd8e9efefd 100644 --- a/apps/docs/content/docs/integrations/calendly.mdx +++ b/apps/docs/content/docs/integrations/calendly.mdx @@ -17,7 +17,7 @@ Webhook subscriptions require a paid plan and the permissions for their user or ## Use the block [#usage-instructions] -Manage event types, scheduled events, invitees, and webhooks. Trigger workflows based on Calendly webhook events (invitee scheduled, invitee canceled, routing form submitted). +Manage event types, scheduled events, invitees, bookings, availability, and routing forms. Trigger workflows based on Calendly webhook events (invitee scheduled, invitee canceled, routing form submitted). ## Actions @@ -93,12 +93,12 @@ Retrieve a list of all event types for a user or organization | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `user` | string | No | Return only event types that belong to this user. Format: URI \(e.g., "https://api.calendly.com/users/abc123-def456") | -| `organization` | string | No | Return only event types that belong to this organization. Format: URI \(e.g., "https://api.calendly.com/organizations/abc123-def456") | +| `user` | string | No | Return event types available to this user. Either user or organization is required. Format: URI \(e.g., "https://api.calendly.com/users/abc123-def456") | +| `organization` | string | No | Return event types that belong to this organization. Either user or organization is required. Format: URI \(e.g., "https://api.calendly.com/organizations/abc123-def456") | | `count` | number | No | Number of results per page. Format: integer \(default: 20, max: 100\) | | `pageToken` | string | No | Page token for pagination. Format: opaque string from previous response next_page_token | | `sort` | string | No | Sort order for results. Format: "field:direction" \(e.g., "name:asc", "name:desc"\) | -| `active` | boolean | No | When true, show only active event types. When false or unchecked, show all event types \(both active and inactive\). | +| `active` | boolean | No | When true, return only active event types. When false, return only inactive event types. When omitted, return all event types. | #### Output @@ -416,6 +416,8 @@ Book a meeting by creating an invitee on an event type at a chosen time. Require | `inviteeLastName` | string | No | Last name of the invitee | | `textReminderNumber` | string | No | Phone number for SMS reminders. Format: E.164 phone number \(e.g., "+14155551234"\) | | `eventGuests` | json | No | Additional guests to copy on the invite. Format: array of email strings \(max 10, e.g., \["guest@example.com"\]\) | +| `location` | json | No | Meeting location. Must match a location configured on the event type; omit for round robin event types. Format: object with "kind" \(physical, inbound_call, outbound_call, zoom_conference, google_conference, gotomeeting_conference, microsoft_teams_conference, webex_conference, ask_invitee, custom\) and, for physical, outbound_call, ask_invitee and custom, a "location" string \(e.g., \{"kind": "outbound_call", "location": "+14155551234"\}\) | +| `questionsAndAnswers` | json | No | Answers to the event type's booking questions. Required questions must be answered, and each question must match the event type's question text exactly. Format: array of objects with "question", "answer" and "position" \(e.g., \[\{"question": "Company", "answer": "Acme", "position": 0\}\]\) | #### Output diff --git a/apps/docs/content/docs/integrations/datadog.mdx b/apps/docs/content/docs/integrations/datadog.mdx index b143fadca99..eba115b3cc0 100644 --- a/apps/docs/content/docs/integrations/datadog.mdx +++ b/apps/docs/content/docs/integrations/datadog.mdx @@ -72,7 +72,7 @@ Query metric timeseries data from Datadog. Use for analyzing trends, creating re ### Datadog Create Event -Post an event to the Datadog event stream. Use for deployment notifications, alerts, or any significant occurrences. +Post an event to the Datadog event stream. Use for deployment notifications, alerts, or any significant occurrences. Uses the v1 events endpoint, which Datadog has deprecated and serves only to organizations that have used it before. @@ -95,7 +95,8 @@ Post an event to the Datadog event stream. Use for deployment notifications, ale | Parameter | Type | Description | | --------- | ---- | ----------- | | `event` | object | The created event details | -| ↳ `id` | number | Event ID | +| ↳ `id` | number | Event ID. Can lose precision above 2^53; prefer id_str | +| ↳ `id_str` | string | Event ID as an exact string | | ↳ `title` | string | Event title | | ↳ `text` | string | Event text | | ↳ `date_happened` | number | Unix timestamp when event occurred | @@ -280,7 +281,7 @@ Search and retrieve logs from Datadog. Use for troubleshooting, analysis, or mon | `query` | string | Yes | Log search query using Datadog query syntax \(e.g., "service:web-app status:error", "host:prod-* @http.status_code:500"\) | | `from` | string | Yes | Start time in ISO-8601 format or relative time \(e.g., "now-1h", "now-15m", "2024-01-15T10:00:00Z"\) | | `to` | string | Yes | End time in ISO-8601 format or relative time \(e.g., "now", "now-5m", "2024-01-15T12:00:00Z"\) | -| `limit` | number | No | Maximum number of logs to return \(e.g., 50, 100, max: 1000\) | +| `limit` | number | No | Maximum number of logs to return \(default: 50, max: 5000\) | | `cursor` | string | No | Pagination cursor from a previous call, taken from its nextLogId output. Omit for the first page. | | `sort` | string | No | Sort order: "timestamp" for oldest first, "-timestamp" for newest first | | `indexes` | string | No | Comma-separated list of log indexes to search | @@ -476,6 +477,7 @@ Get the details of a single incident by ID. Requires the Incident Management `in | ↳ `modified` | string | Last modification timestamp | | ↳ `resolved` | string | Resolution timestamp | | ↳ `time_to_resolve` | number | Seconds from creation to resolution | +| `included` | array | Related resources requested through include \(users, attachments\) | @@ -705,7 +707,7 @@ Update a service level objective. Reads the current SLO first and applies only t | --------- | ---- | -------- | ----------- | | `sloId` | string | Yes | The ID of the service level objective to update | | `name` | string | No | New name for the SLO. Leave blank to keep the current name. | -| `type` | string | No | SLO type: "metric" or "monitor". Leave blank to keep the current type. Changing type requires supplying the matching query or monitorIds. | +| `type` | string | No | SLO type: "metric" or "monitor". Leave blank to keep the current type. Changing type requires supplying the matching query or monitorIds. Converting to a "time_slice" SLO is not supported. | | `thresholds` | string | No | JSON array of thresholds replacing the stored ones, e.g. \[\{"timeframe": "30d", "target": 99.9, "warning": 99.95\}\]. Leave blank to keep the current thresholds. | | `description` | string | No | Description of the SLO | | `tags` | string | No | Comma-separated tags \(e.g., "env:prod,team:core"\) | @@ -785,6 +787,7 @@ Get an SLO’s history over a time window, including the overall SLI value and r | ↳ `monitors` | array | Per-monitor SLI data for multi-monitor SLOs | | ↳ `thresholds` | object | Thresholds keyed by timeframe | | `sliValue` | number | Overall SLI value over the window | +| `errors` | array | Errors Datadog hit while querying the history; the call can succeed with partial data | diff --git a/apps/docs/content/docs/integrations/discord.mdx b/apps/docs/content/docs/integrations/discord.mdx index d63441d0f7a..4fa9fa03acf 100644 --- a/apps/docs/content/docs/integrations/discord.mdx +++ b/apps/docs/content/docs/integrations/discord.mdx @@ -40,14 +40,14 @@ Send a message to a Discord channel | --------- | ---- | -------- | ----------- | | `channelId` | string | Yes | The Discord channel ID to send the message to, e.g., 123456789012345678 | | `content` | string | No | The text content of the message | -| `serverId` | string | Yes | The Discord server ID \(guild ID\), e.g., 123456789012345678 | +| `serverId` | string | No | The Discord server ID \(guild ID\), e.g., 123456789012345678 | | `files` | file[] | No | Files to attach to the message | #### Output | Parameter | Type | Description | | --------- | ---- | ----------- | -| `message` | string | Success or error message | +| `message` | string | Content of the sent message | | `files` | file[] | Files attached to the message | | `data` | object | Discord message data | | ↳ `id` | string | Message ID | @@ -80,6 +80,9 @@ Retrieve messages from a Discord channel | --------- | ---- | -------- | ----------- | | `channelId` | string | Yes | The Discord channel ID to retrieve messages from, e.g., 123456789012345678 | | `limit` | number | No | Maximum number of messages to retrieve \(default: 10, max: 100\) | +| `before` | string | No | Return messages before this message ID, to page back through history. Use only one of before, after, or around. | +| `after` | string | No | Return messages after this message ID, e.g. to read only messages newer than the last one seen | +| `around` | string | No | Return messages around this message ID | #### Output @@ -157,11 +160,12 @@ Retrieve information about a Discord user | ↳ `id` | string | User ID | | ↳ `username` | string | Username | | ↳ `discriminator` | string | User discriminator \(4-digit number\) | +| ↳ `global_name` | string | User display name, if set | | ↳ `avatar` | string | User avatar hash | | ↳ `bot` | boolean | Whether user is a bot | | ↳ `system` | boolean | Whether user is a system user | -| ↳ `email` | string | User email \(if available\) | -| ↳ `verified` | boolean | Whether user email is verified | +| ↳ `email` | string | User email. Not returned for a user looked up by ID | +| ↳ `verified` | boolean | Whether the user email is verified. Not returned for a user looked up by ID | @@ -178,7 +182,7 @@ Edit an existing message in a Discord channel | `channelId` | string | Yes | The Discord channel ID containing the message, e.g., 123456789012345678 | | `messageId` | string | Yes | The ID of the message to edit, e.g., 123456789012345678 | | `content` | string | No | The new text content for the message | -| `serverId` | string | Yes | The Discord server ID \(guild ID\), e.g., 123456789012345678 | +| `serverId` | string | No | The Discord server ID \(guild ID\), e.g., 123456789012345678 | #### Output @@ -205,7 +209,7 @@ Delete a message from a Discord channel | --------- | ---- | -------- | ----------- | | `channelId` | string | Yes | The Discord channel ID containing the message, e.g., 123456789012345678 | | `messageId` | string | Yes | The ID of the message to delete, e.g., 123456789012345678 | -| `serverId` | string | Yes | The Discord server ID \(guild ID\), e.g., 123456789012345678 | +| `serverId` | string | No | The Discord server ID \(guild ID\), e.g., 123456789012345678 | #### Output @@ -227,7 +231,7 @@ Delete 2-100 messages from a Discord channel in a single request | --------- | ---- | -------- | ----------- | | `channelId` | string | Yes | The Discord channel ID to delete messages from, e.g., 123456789012345678 | | `messageIds` | json | Yes | Array of 2-100 message IDs to delete. Messages older than 2 weeks cannot be bulk deleted. | -| `serverId` | string | Yes | The Discord server ID \(guild ID\), e.g., 123456789012345678 | +| `serverId` | string | No | The Discord server ID \(guild ID\), e.g., 123456789012345678 | #### Output @@ -250,7 +254,7 @@ Add a reaction emoji to a Discord message | `channelId` | string | Yes | The Discord channel ID containing the message, e.g., 123456789012345678 | | `messageId` | string | Yes | The ID of the message to react to, e.g., 123456789012345678 | | `emoji` | string | Yes | The emoji to react with \(unicode emoji or custom emoji in name:id format\) | -| `serverId` | string | Yes | The Discord server ID \(guild ID\), e.g., 123456789012345678 | +| `serverId` | string | No | The Discord server ID \(guild ID\), e.g., 123456789012345678 | #### Output @@ -274,7 +278,7 @@ Remove a reaction from a Discord message | `messageId` | string | Yes | The ID of the message with the reaction, e.g., 123456789012345678 | | `emoji` | string | Yes | The emoji to remove \(unicode emoji or custom emoji in name:id format\) | | `userId` | string | No | The user ID whose reaction to remove \(omit to remove bot's own reaction\), e.g., 123456789012345678 | -| `serverId` | string | Yes | The Discord server ID \(guild ID\), e.g., 123456789012345678 | +| `serverId` | string | No | The Discord server ID \(guild ID\), e.g., 123456789012345678 | #### Output @@ -296,7 +300,7 @@ Pin a message in a Discord channel | --------- | ---- | -------- | ----------- | | `channelId` | string | Yes | The Discord channel ID containing the message, e.g., 123456789012345678 | | `messageId` | string | Yes | The ID of the message to pin, e.g., 123456789012345678 | -| `serverId` | string | Yes | The Discord server ID \(guild ID\), e.g., 123456789012345678 | +| `serverId` | string | No | The Discord server ID \(guild ID\), e.g., 123456789012345678 | #### Output @@ -318,7 +322,7 @@ Unpin a message in a Discord channel | --------- | ---- | -------- | ----------- | | `channelId` | string | Yes | The Discord channel ID containing the message, e.g., 123456789012345678 | | `messageId` | string | Yes | The ID of the message to unpin, e.g., 123456789012345678 | -| `serverId` | string | Yes | The Discord server ID \(guild ID\), e.g., 123456789012345678 | +| `serverId` | string | No | The Discord server ID \(guild ID\), e.g., 123456789012345678 | #### Output @@ -375,7 +379,7 @@ Create a thread in a Discord channel | `messageId` | string | No | The message ID to create a thread from \(if creating from existing message\), e.g., 123456789012345678 | | `autoArchiveDuration` | number | No | Duration in minutes to auto-archive the thread \(60, 1440, 4320, 10080\) | | `isPublic` | boolean | No | Whether the standalone thread is public \(visible to everyone in the channel\) or private. Ignored when creating a thread from an existing message, which always inherits the parent channel visibility. Defaults to public if omitted. | -| `serverId` | string | Yes | The Discord server ID \(guild ID\), e.g., 123456789012345678 | +| `serverId` | string | No | The Discord server ID \(guild ID\), e.g., 123456789012345678 | #### Output @@ -402,7 +406,7 @@ Join a thread in Discord | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `threadId` | string | Yes | The thread ID to join, e.g., 123456789012345678 | -| `serverId` | string | Yes | The Discord server ID \(guild ID\), e.g., 123456789012345678 | +| `serverId` | string | No | The Discord server ID \(guild ID\), e.g., 123456789012345678 | #### Output @@ -423,7 +427,7 @@ Leave a thread in Discord | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `threadId` | string | Yes | The thread ID to leave, e.g., 123456789012345678 | -| `serverId` | string | Yes | The Discord server ID \(guild ID\), e.g., 123456789012345678 | +| `serverId` | string | No | The Discord server ID \(guild ID\), e.g., 123456789012345678 | #### Output @@ -445,7 +449,7 @@ Archive or unarchive a thread in Discord | --------- | ---- | -------- | ----------- | | `threadId` | string | Yes | The thread ID to archive/unarchive, e.g., 123456789012345678 | | `archived` | boolean | Yes | Whether to archive \(true\) or unarchive \(false\) the thread | -| `serverId` | string | Yes | The Discord server ID \(guild ID\), e.g., 123456789012345678 | +| `serverId` | string | No | The Discord server ID \(guild ID\), e.g., 123456789012345678 | #### Output @@ -470,8 +474,8 @@ Create a new channel in a Discord server | --------- | ---- | -------- | ----------- | | `serverId` | string | Yes | The Discord server ID \(guild ID\), e.g., 123456789012345678 | | `name` | string | Yes | The name of the channel \(1-100 characters\) | -| `type` | number | No | Channel type \(0=text, 2=voice, 4=category, 5=announcement, 13=stage\) | -| `topic` | string | No | Channel topic \(0-1024 characters\) | +| `type` | number | No | Channel type \(0=text, 2=voice, 4=category, 5=announcement, 13=stage, 15=forum\) | +| `topic` | string | No | Channel topic \(up to 1024 characters for text channels, 4096 for forum channels\) | | `parentId` | string | No | Parent category ID for the channel, e.g., 123456789012345678 | #### Output @@ -500,7 +504,7 @@ Update a Discord channel | `channelId` | string | Yes | The Discord channel ID to update, e.g., 123456789012345678 | | `name` | string | No | The new name for the channel | | `topic` | string | No | The new topic for the channel | -| `serverId` | string | Yes | The Discord server ID \(guild ID\), e.g., 123456789012345678 | +| `serverId` | string | No | The Discord server ID \(guild ID\), e.g., 123456789012345678 | #### Output @@ -526,7 +530,7 @@ Delete a Discord channel | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `channelId` | string | Yes | The Discord channel ID to delete, e.g., 123456789012345678 | -| `serverId` | string | Yes | The Discord server ID \(guild ID\), e.g., 123456789012345678 | +| `serverId` | string | No | The Discord server ID \(guild ID\), e.g., 123456789012345678 | #### Output @@ -552,7 +556,7 @@ Get information about a Discord channel | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `channelId` | string | Yes | The Discord channel ID to retrieve, e.g., 123456789012345678 | -| `serverId` | string | Yes | The Discord server ID \(guild ID\), e.g., 123456789012345678 | +| `serverId` | string | No | The Discord server ID \(guild ID\), e.g., 123456789012345678 | #### Output @@ -884,7 +888,7 @@ Create an invite link for a Discord channel | `maxAge` | number | No | Duration of invite in seconds \(0 = never expires, default 86400\) | | `maxUses` | number | No | Max number of uses \(0 = unlimited, default 0\) | | `temporary` | boolean | No | Whether invite grants temporary membership | -| `serverId` | string | Yes | The Discord server ID \(guild ID\), e.g., 123456789012345678 | +| `serverId` | string | No | The Discord server ID \(guild ID\), e.g., 123456789012345678 | #### Output @@ -911,7 +915,7 @@ Get information about a Discord invite | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `inviteCode` | string | Yes | The invite code to retrieve | -| `serverId` | string | Yes | The Discord server ID \(guild ID\), e.g., 123456789012345678 | +| `serverId` | string | No | The Discord server ID \(guild ID\), e.g., 123456789012345678 | #### Output @@ -938,7 +942,7 @@ Delete a Discord invite | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `inviteCode` | string | Yes | The invite code to delete | -| `serverId` | string | Yes | The Discord server ID \(guild ID\), e.g., 123456789012345678 | +| `serverId` | string | No | The Discord server ID \(guild ID\), e.g., 123456789012345678 | #### Output @@ -960,7 +964,7 @@ Create a webhook in a Discord channel | --------- | ---- | -------- | ----------- | | `channelId` | string | Yes | The Discord channel ID to create the webhook in, e.g., 123456789012345678 | | `name` | string | Yes | Name of the webhook \(1-80 characters\) | -| `serverId` | string | Yes | The Discord server ID \(guild ID\), e.g., 123456789012345678 | +| `serverId` | string | No | The Discord server ID \(guild ID\), e.g., 123456789012345678 | #### Output @@ -990,7 +994,7 @@ Execute a Discord webhook to send a message | `webhookToken` | string | Yes | The webhook token | | `content` | string | Yes | The message content to send | | `username` | string | No | Override the default username of the webhook | -| `serverId` | string | Yes | The Discord server ID \(guild ID\), e.g., 123456789012345678 | +| `serverId` | string | No | The Discord server ID \(guild ID\), e.g., 123456789012345678 | #### Output @@ -1016,7 +1020,7 @@ Get information about a Discord webhook | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `webhookId` | string | Yes | The webhook ID to retrieve, e.g., 123456789012345678 | -| `serverId` | string | Yes | The Discord server ID \(guild ID\), e.g., 123456789012345678 | +| `serverId` | string | No | The Discord server ID \(guild ID\), e.g., 123456789012345678 | #### Output @@ -1043,7 +1047,7 @@ Delete a Discord webhook | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `webhookId` | string | Yes | The webhook ID to delete, e.g., 123456789012345678 | -| `serverId` | string | Yes | The Discord server ID \(guild ID\), e.g., 123456789012345678 | +| `serverId` | string | No | The Discord server ID \(guild ID\), e.g., 123456789012345678 | #### Output diff --git a/apps/docs/content/docs/integrations/github.mdx b/apps/docs/content/docs/integrations/github.mdx index 6d53cce14ca..9be5babec1a 100644 --- a/apps/docs/content/docs/integrations/github.mdx +++ b/apps/docs/content/docs/integrations/github.mdx @@ -113,6 +113,8 @@ Create comments on GitHub PRs | `path` | string | No | File path for review comment | | `commentType` | string | No | Type of comment \(pr_comment or file_comment\) | | `line` | number | No | Line number for review comment | +| `side` | string | No | Side of the diff \(LEFT or RIGHT\) | +| `commitId` | string | No | The SHA of the commit to comment on. Defaults to the pull request head commit. | #### Output @@ -208,6 +210,8 @@ Retrieve the latest commit from a GitHub repository | Parameter | Type | Description | | --------- | ---- | ----------- | +| `sha` | string | Commit SHA | +| `html_url` | string | GitHub web URL | | `commit` | object | Core commit data | | ↳ `url` | string | Commit API URL | | ↳ `message` | string | Commit message | @@ -246,8 +250,6 @@ Retrieve the latest commit from a GitHub repository | ↳ `html_url` | string | Profile page URL | | ↳ `type` | string | User or Organization | | ↳ `site_admin` | boolean | GitHub staff indicator | -| `sha` | string | Commit SHA | -| `html_url` | string | GitHub web URL | @@ -629,7 +631,7 @@ Get the list of files changed in a pull request | ↳ `contents_url` | string | Contents API URL | | ↳ `patch` | string | Diff patch | | ↳ `previous_filename` | string | Previous filename \(for renames\) | -| `count` | number | Total number of files | +| `count` | number | Number of files in this page | @@ -1383,7 +1385,7 @@ Close an issue in a GitHub repository | `owner` | string | Yes | Repository owner | | `repo` | string | Yes | Repository name | | `issue_number` | number | Yes | Issue number | -| `state_reason` | string | No | Reason for closing: completed or not_planned | +| `state_reason` | string | No | Reason for closing: completed, not_planned, or duplicate | #### Output @@ -1946,7 +1948,7 @@ List workflow runs for a repository, or for a single workflow when a workflow ID | `actor` | string | No | Filter by user who triggered the workflow | | `branch` | string | No | Filter by branch name | | `event` | string | No | Filter by event type \(e.g., push, pull_request, workflow_dispatch\) | -| `status` | string | No | Filter by status \(queued, in_progress, completed, waiting, requested, pending\) | +| `status` | string | No | Filter by check run status or conclusion: queued, in_progress, completed, waiting, requested, pending, success, failure, cancelled, skipped, timed_out, action_required, neutral, or stale. Omit \(or pass "all"\) for every run. | | `per_page` | number | No | Number of results per page \(default: 30, max: 100\) | | `page` | number | No | Page number of results to fetch \(default: 1\) | @@ -2217,8 +2219,8 @@ Search for code across GitHub repositories. Use qualifiers like repo:owner/name, | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `q` | string | Yes | Search query with optional qualifiers \(repo:, language:, path:, extension:, user:, org:\) | -| `sort` | string | No | Sort by indexed date \(default: best match\) | -| `order` | string | No | Sort order: asc or desc \(default: desc\) | +| `sort` | string | No | Sort by "indexed" \(how recently GitHub indexed the file\); default is best match. GitHub has deprecated this parameter and is closing it down. | +| `order` | string | No | Sort order: asc or desc \(default: desc\). Ignored unless sort is set; GitHub has deprecated this parameter and is closing it down. | | `per_page` | number | No | Results per page \(max 100, default: 30\) | | `page` | number | No | Page number \(default: 1\) | @@ -2627,7 +2629,7 @@ List commits in a repository with optional filtering by SHA, path, author, commi ### GitHub Get Commit -Get detailed information about a specific commit including files changed and stats +Get detailed information about a specific commit including files changed and stats. GitHub returns at most the first 300 changed files of a larger commit. @@ -2723,8 +2725,8 @@ Compare two commits or branches to see the diff, commits between them, and chang | `repo` | string | Yes | Repository name | | `base` | string | Yes | Base branch/tag/SHA for comparison | | `head` | string | Yes | Head branch/tag/SHA for comparison | -| `per_page` | number | No | Results per page for files \(max 100, default: 30\) | -| `page` | number | No | Page number for files \(default: 1\) | +| `per_page` | number | No | Commits per page \(max 100\). Setting per_page or page paginates the commit list, and changed files are returned only on page 1. Leave both unset to get up to 250 commits and every changed file in one response. | +| `page` | number | No | Page of the commit list. Changed files are returned only on page 1. Omit both page and per_page to get up to 250 commits in one response. | #### Output diff --git a/apps/docs/content/docs/integrations/gitlab.mdx b/apps/docs/content/docs/integrations/gitlab.mdx index 9256c2ac0e5..ae6c4564f99 100644 --- a/apps/docs/content/docs/integrations/gitlab.mdx +++ b/apps/docs/content/docs/integrations/gitlab.mdx @@ -420,6 +420,7 @@ Merge a merge request in a GitLab project | `squash` | boolean | No | Squash commits before merging | | `shouldRemoveSourceBranch` | boolean | No | Delete source branch after merge | | `mergeWhenPipelineSucceeds` | boolean | No | Merge when pipeline succeeds | +| `sha` | string | No | HEAD SHA of the source branch; the merge fails if it does not match. Required when the group or instance requires a commit SHA on the merge requests API. | #### Output @@ -1024,7 +1025,7 @@ Add an existing GitLab user to a project or group at a given access level | `resourceId` | string | Yes | Project or group ID or path \(e.g. mygroup/myproject\) | | `userId` | number | No | The ID of the user to add. Provide either userId or username. | | `username` | string | No | The username of the user to add. Provide either userId or username. | -| `accessLevel` | number | Yes | Access level: 0 \(No access\), 5 \(Minimal\), 10 \(Guest\), 15 \(Planner\), 20 \(Reporter\), 25 \(Security Manager\), 30 \(Developer\), 40 \(Maintainer\), 50 \(Owner\) | +| `accessLevel` | number | Yes | Access level: 10 \(Guest\), 15 \(Planner\), 20 \(Reporter\), 25 \(Security Manager\), 30 \(Developer\), 40 \(Maintainer\), 50 \(Owner\). 5 \(Minimal access\) is also valid for a top-level group on Premium and Ultimate. | | `expiresAt` | string | No | Access expiration date in YYYY-MM-DD format | | `memberRoleId` | number | No | Custom member role ID \(GitLab Ultimate only\) | @@ -1050,7 +1051,7 @@ Update a member's access level in a GitLab project or group | `resourceType` | string | Yes | Whether the resource is a 'project' or a 'group' | | `resourceId` | string | Yes | Project or group ID or path \(e.g. mygroup/myproject\) | | `userId` | number | Yes | The ID of the member to update | -| `accessLevel` | number | Yes | New access level: 0 \(No access\), 5 \(Minimal\), 10 \(Guest\), 15 \(Planner\), 20 \(Reporter\), 25 \(Security Manager\), 30 \(Developer\), 40 \(Maintainer\), 50 \(Owner\) | +| `accessLevel` | number | Yes | New access level: 10 \(Guest\), 15 \(Planner\), 20 \(Reporter\), 25 \(Security Manager\), 30 \(Developer\), 40 \(Maintainer\), 50 \(Owner\). 5 \(Minimal access\) is also valid for a top-level group on Premium and Ultimate. | | `expiresAt` | string | No | Access expiration date in YYYY-MM-DD format. Pass an empty string to clear an existing expiration. | | `memberRoleId` | number | No | Custom member role ID \(GitLab Ultimate only\). Warning: when omitted, GitLab removes any custom role the member currently holds. | @@ -1099,7 +1100,7 @@ Invite a person to a GitLab project or group by email address | `resourceType` | string | Yes | Whether the resource is a 'project' or a 'group' | | `resourceId` | string | Yes | Project or group ID or path \(e.g. mygroup/myproject\) | | `email` | string | Yes | Email address to invite \(comma-separated for multiple\) | -| `accessLevel` | number | Yes | Access level: 0 \(No access\), 5 \(Minimal\), 10 \(Guest\), 15 \(Planner\), 20 \(Reporter\), 25 \(Security Manager\), 30 \(Developer\), 40 \(Maintainer\), 50 \(Owner\) | +| `accessLevel` | number | Yes | Access level: 10 \(Guest\), 15 \(Planner\), 20 \(Reporter\), 25 \(Security Manager\), 30 \(Developer\), 40 \(Maintainer\), 50 \(Owner\). 5 \(Minimal access\) is also valid for a top-level group on Premium and Ultimate. | | `expiresAt` | string | No | Access expiration date in YYYY-MM-DD format | | `memberRoleId` | number | No | Custom member role ID \(GitLab Ultimate only\) | | `inviteSource` | string | No | Identifier recorded as the source of the invitation \(for attribution\) | @@ -2018,7 +2019,7 @@ Add a SAML group link that maps an identity-provider group to a GitLab group at | --------- | ---- | -------- | ----------- | | `groupId` | string | Yes | Group ID or path \(e.g. my-org/my-group\) | | `samlGroupName` | string | Yes | The name of the SAML group as sent by the identity provider | -| `accessLevel` | number | Yes | Access level granted to members of the SAML group: 10 \(Guest\), 15 \(Planner\), 20 \(Reporter\), 25 \(Security Manager\), 30 \(Developer\), 40 \(Maintainer\), 50 \(Owner\) | +| `accessLevel` | number | Yes | Access level granted to members of the SAML group: 10 \(Guest\), 15 \(Planner\), 20 \(Reporter\), 25 \(Security Manager\), 30 \(Developer\), 40 \(Maintainer\), 50 \(Owner\). 5 \(Minimal access\) is also valid for a top-level group. | | `memberRoleId` | number | No | Custom member role ID \(GitLab Ultimate only\) | | `provider` | string | No | Unique provider name that must match for this group link to be applied \(GitLab 18.2+\) | diff --git a/apps/docs/content/docs/integrations/incidentio.mdx b/apps/docs/content/docs/integrations/incidentio.mdx index b70b6bd9022..c106412033d 100644 --- a/apps/docs/content/docs/integrations/incidentio.mdx +++ b/apps/docs/content/docs/integrations/incidentio.mdx @@ -74,7 +74,7 @@ List incidents from incident.io. Returns a list of incidents with their details ### incident.io Incidents Create -Create a new incident in incident.io. Requires idempotency_key, severity_id, and visibility. Optionally accepts name, summary, type, and status. +Create a new incident in incident.io. Requires idempotency_key and visibility. Optionally accepts name, summary, severity_id, incident_type_id, and incident_status_id. @@ -85,7 +85,7 @@ Create a new incident in incident.io. Requires idempotency_key, severity_id, and | `idempotency_key` | string | Yes | Unique identifier to prevent duplicate incident creation. Use a UUID or unique string. | | `name` | string | No | Name of the incident \(e.g., "Database connection issues"\) | | `summary` | string | No | Brief summary of the incident \(e.g., "Intermittent connection failures to primary database"\) | -| `severity_id` | string | Yes | ID of the severity level \(e.g., "01FCNDV6P870EA6S7TK1DSYDG0"\) | +| `severity_id` | string | No | ID of the severity level \(e.g., "01FCNDV6P870EA6S7TK1DSYDG0"\) | | `incident_type_id` | string | No | ID of the incident type | | `incident_status_id` | string | No | ID of the initial incident status | | `visibility` | string | Yes | Visibility of the incident: "public" or "private" \(required\) | @@ -159,14 +159,14 @@ Retrieve detailed information about a specific incident from incident.io by its | ↳ `slack_channel_id` | string | Associated Slack channel ID | | ↳ `slack_channel_name` | string | Associated Slack channel name | | ↳ `visibility` | string | Incident visibility | -| ↳ `custom_field_entries` | array | Custom field values for the incident | +| ↳ `custom_field_entries` | array | Custom field values for the incident. Each value carries one of value_text, value_link, value_numeric, value_option \(\{id, value\}\), or value_catalog_entry \(\{id, name, external_id\}\). | | ↳ `incident_role_assignments` | array | Role assignments for the incident | ### incident.io Incidents Update -Update an existing incident in incident.io. Can update name, summary, severity, status, or type. +Update an existing incident in incident.io. Can update name, summary, severity, or status. @@ -179,7 +179,7 @@ Update an existing incident in incident.io. Can update name, summary, severity, | `summary` | string | No | Updated summary of the incident \(e.g., "Intermittent connection failures to primary database"\) | | `severity_id` | string | No | Updated severity ID for the incident \(e.g., "01FCNDV6P870EA6S7TK1DSYDG0"\) | | `incident_status_id` | string | No | Updated status ID for the incident \(e.g., "01FCNDV6P870EA6S7TK1DSYDG0"\) | -| `incident_type_id` | string | No | Updated incident type ID | +| `incident_type_id` | string | No | Not applied: incident.io does not support changing an incident's type after creation, so this value is ignored. | | `notify_incident_channel` | boolean | Yes | Whether to notify the incident channel about this update | #### Output @@ -214,7 +214,7 @@ Update an existing incident in incident.io. Can update name, summary, severity, ### incident.io Actions List -List actions from incident.io. Optionally filter by incident ID. +List actions from incident.io, optionally filtered by incident ID. Without page_size or after, follows pages automatically and returns up to 2,500 actions, oldest first; if more remain, pagination_meta.after is set. Pass page_size or after to fetch a single page. @@ -223,12 +223,17 @@ List actions from incident.io. Optionally filter by incident ID. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `incident_id` | string | No | Filter actions by incident ID \(e.g., "01FCNDV6P870EA6S7TK1DSYDG0"\) | -| `incident_mode` | string | No | Filter actions by incident mode \(standard, retrospective, test, tutorial, or stream\) | +| `incident_mode` | string | No | Filter actions by incident mode \(standard, retrospective, test, tutorial, or stream\). When omitted, actions from standard and retrospective incidents are returned. | +| `page_size` | number | No | Number of actions per page, 1-250. Setting it fetches a single page instead of following pages automatically | +| `after` | string | No | Pagination cursor from a previous page's pagination_meta.after \(e.g., "01FDAG4SAP5TYPT98WGR2N7W91"\) | #### Output | Parameter | Type | Description | | --------- | ---- | ----------- | +| `pagination_meta` | object | Pagination metadata. Pass `after` back to fetch the next page. | +| ↳ `after` | string | Cursor for the next page | +| ↳ `page_size` | number | Number of results per page | | `actions` | array | List of actions | | ↳ `id` | string | Action ID | | ↳ `description` | string | Action description | @@ -237,19 +242,30 @@ List actions from incident.io. Optionally filter by incident ID. | ↳ `name` | string | User name | | ↳ `email` | string | User email | | ↳ `status` | string | Action status | -| ↳ `due_at` | string | Due date/time | +| ↳ `due_at` | string | Deprecated: incident.io actions have no due date, so this is never set | | ↳ `created_at` | string | Creation timestamp | | ↳ `updated_at` | string | Last update timestamp | | ↳ `incident_id` | string | Associated incident ID | -| ↳ `creator` | object | User who created the action | -| ↳ `id` | string | User ID | -| ↳ `name` | string | User name | -| ↳ `email` | string | User email | +| ↳ `creator` | object | Who created the action | +| ↳ `user` | object | The user who caused this, if a person did | +| ↳ `id` | string | User ID | +| ↳ `name` | string | User display name | +| ↳ `email` | string | User email address | +| ↳ `role` | string | User role | +| ↳ `slack_user_id` | string | Slack user ID | +| ↳ `api_key` | object | The API key that caused this, if an integration did | +| ↳ `id` | string | API key ID | +| ↳ `name` | string | API key name | +| ↳ `workflow` | object | The incident.io workflow that caused this, if automation did | +| ↳ `id` | string | Workflow ID | +| ↳ `name` | string | Workflow name | +| ↳ `alert` | object | The alert that caused this, if an alert did | +| ↳ `id` | string | Alert ID | +| ↳ `title` | string | Alert title | +| ↳ `id` | string | ID of the user, API key, workflow, or alert | +| ↳ `name` | string | Name of the user, API key, or workflow \(or the alert title\) | +| ↳ `email` | string | User email, when a user created it | | ↳ `completed_at` | string | Completion timestamp | -| ↳ `external_issue_reference` | object | External issue tracking reference | -| ↳ `provider` | string | Issue tracking provider \(e.g., Jira, Linear\) | -| ↳ `issue_name` | string | Issue identifier | -| ↳ `issue_permalink` | string | URL to the external issue | @@ -277,25 +293,36 @@ Get detailed information about a specific action from incident.io. | ↳ `name` | string | User name | | ↳ `email` | string | User email | | ↳ `status` | string | Action status | -| ↳ `due_at` | string | Due date/time | +| ↳ `due_at` | string | Deprecated: incident.io actions have no due date, so this is never set | | ↳ `created_at` | string | Creation timestamp | | ↳ `updated_at` | string | Last update timestamp | | ↳ `incident_id` | string | Associated incident ID | -| ↳ `creator` | object | User who created the action | -| ↳ `id` | string | User ID | -| ↳ `name` | string | User name | -| ↳ `email` | string | User email | +| ↳ `creator` | object | Who created the action | +| ↳ `user` | object | The user who caused this, if a person did | +| ↳ `id` | string | User ID | +| ↳ `name` | string | User display name | +| ↳ `email` | string | User email address | +| ↳ `role` | string | User role | +| ↳ `slack_user_id` | string | Slack user ID | +| ↳ `api_key` | object | The API key that caused this, if an integration did | +| ↳ `id` | string | API key ID | +| ↳ `name` | string | API key name | +| ↳ `workflow` | object | The incident.io workflow that caused this, if automation did | +| ↳ `id` | string | Workflow ID | +| ↳ `name` | string | Workflow name | +| ↳ `alert` | object | The alert that caused this, if an alert did | +| ↳ `id` | string | Alert ID | +| ↳ `title` | string | Alert title | +| ↳ `id` | string | ID of the user, API key, workflow, or alert | +| ↳ `name` | string | Name of the user, API key, or workflow \(or the alert title\) | +| ↳ `email` | string | User email, when a user created it | | ↳ `completed_at` | string | Completion timestamp | -| ↳ `external_issue_reference` | object | External issue tracking reference | -| ↳ `provider` | string | Issue tracking provider \(e.g., Jira, Linear\) | -| ↳ `issue_name` | string | Issue identifier | -| ↳ `issue_permalink` | string | URL to the external issue | ### incident.io Follow-ups List -List follow-ups from incident.io. Optionally filter by incident ID. +List follow-ups from incident.io, optionally filtered by incident ID. Without page_size or after, follows pages automatically and returns up to 2,500 follow-ups, oldest first; if more remain, pagination_meta.after is set. Pass page_size or after to fetch a single page. @@ -304,12 +331,17 @@ List follow-ups from incident.io. Optionally filter by incident ID. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `incident_id` | string | No | Filter follow-ups by incident ID \(e.g., "01FCNDV6P870EA6S7TK1DSYDG0"\) | -| `incident_mode` | string | No | Filter follow-ups by incident mode \(standard, retrospective, test, tutorial, or stream\) | +| `incident_mode` | string | No | Filter follow-ups by incident mode \(standard, retrospective, test, tutorial, or stream\). When omitted, follow-ups from standard and retrospective incidents are returned. | +| `page_size` | number | No | Number of follow-ups per page, 1-250. Setting it fetches a single page instead of following pages automatically | +| `after` | string | No | Pagination cursor from a previous page's pagination_meta.after \(e.g., "01FDAG4SAP5TYPT98WGR2N7W91"\) | #### Output | Parameter | Type | Description | | --------- | ---- | ----------- | +| `pagination_meta` | object | Pagination metadata. Pass `after` back to fetch the next page. | +| ↳ `after` | string | Cursor for the next page | +| ↳ `page_size` | number | Number of results per page | | `follow_ups` | array | List of follow-ups | | ↳ `id` | string | Follow-up ID | | ↳ `title` | string | Follow-up title | @@ -318,25 +350,48 @@ List follow-ups from incident.io. Optionally filter by incident ID. | ↳ `id` | string | User ID | | ↳ `name` | string | User name | | ↳ `email` | string | User email | +| ↳ `assignee_team` | object | The team the follow-up is assigned to | +| ↳ `id` | string | Team ID | +| ↳ `name` | string | Team name | | ↳ `status` | string | Follow-up status | | ↳ `priority` | object | Follow-up priority | | ↳ `id` | string | Priority ID | | ↳ `name` | string | Priority name | | ↳ `description` | string | Priority description | | ↳ `rank` | number | Priority rank | +| ↳ `category` | object | Follow-up category | +| ↳ `id` | string | Category ID | +| ↳ `name` | string | Category name | +| ↳ `description` | string | Category description | +| ↳ `rank` | number | Category rank | | ↳ `created_at` | string | Creation timestamp | | ↳ `updated_at` | string | Last update timestamp | | ↳ `incident_id` | string | Associated incident ID | -| ↳ `creator` | object | User who created the follow-up | -| ↳ `id` | string | User ID | -| ↳ `name` | string | User name | -| ↳ `email` | string | User email | +| ↳ `creator` | object | Who created the follow-up | +| ↳ `user` | object | The user who caused this, if a person did | +| ↳ `id` | string | User ID | +| ↳ `name` | string | User display name | +| ↳ `email` | string | User email address | +| ↳ `role` | string | User role | +| ↳ `slack_user_id` | string | Slack user ID | +| ↳ `api_key` | object | The API key that caused this, if an integration did | +| ↳ `id` | string | API key ID | +| ↳ `name` | string | API key name | +| ↳ `workflow` | object | The incident.io workflow that caused this, if automation did | +| ↳ `id` | string | Workflow ID | +| ↳ `name` | string | Workflow name | +| ↳ `alert` | object | The alert that caused this, if an alert did | +| ↳ `id` | string | Alert ID | +| ↳ `title` | string | Alert title | +| ↳ `id` | string | ID of the user, API key, workflow, or alert | +| ↳ `name` | string | Name of the user, API key, or workflow \(or the alert title\) | +| ↳ `email` | string | User email, when a user created it | | ↳ `completed_at` | string | Completion timestamp | | ↳ `labels` | array | Labels associated with the follow-up | | ↳ `external_issue_reference` | object | External issue tracking reference | -| ↳ `provider` | string | External provider name | -| ↳ `issue_name` | string | External issue name or ID | -| ↳ `issue_permalink` | string | Permalink to external issue | +| ↳ `provider` | string | Issue tracking provider \(e.g., Jira, Linear\) | +| ↳ `issue_name` | string | Issue identifier | +| ↳ `issue_permalink` | string | URL to the external issue | @@ -364,25 +419,48 @@ Get detailed information about a specific follow-up from incident.io. | ↳ `id` | string | User ID | | ↳ `name` | string | User name | | ↳ `email` | string | User email | +| ↳ `assignee_team` | object | The team the follow-up is assigned to | +| ↳ `id` | string | Team ID | +| ↳ `name` | string | Team name | | ↳ `status` | string | Follow-up status | | ↳ `priority` | object | Follow-up priority | | ↳ `id` | string | Priority ID | | ↳ `name` | string | Priority name | | ↳ `description` | string | Priority description | | ↳ `rank` | number | Priority rank | +| ↳ `category` | object | Follow-up category | +| ↳ `id` | string | Category ID | +| ↳ `name` | string | Category name | +| ↳ `description` | string | Category description | +| ↳ `rank` | number | Category rank | | ↳ `created_at` | string | Creation timestamp | | ↳ `updated_at` | string | Last update timestamp | | ↳ `incident_id` | string | Associated incident ID | -| ↳ `creator` | object | User who created the follow-up | -| ↳ `id` | string | User ID | -| ↳ `name` | string | User name | -| ↳ `email` | string | User email | +| ↳ `creator` | object | Who created the follow-up | +| ↳ `user` | object | The user who caused this, if a person did | +| ↳ `id` | string | User ID | +| ↳ `name` | string | User display name | +| ↳ `email` | string | User email address | +| ↳ `role` | string | User role | +| ↳ `slack_user_id` | string | Slack user ID | +| ↳ `api_key` | object | The API key that caused this, if an integration did | +| ↳ `id` | string | API key ID | +| ↳ `name` | string | API key name | +| ↳ `workflow` | object | The incident.io workflow that caused this, if automation did | +| ↳ `id` | string | Workflow ID | +| ↳ `name` | string | Workflow name | +| ↳ `alert` | object | The alert that caused this, if an alert did | +| ↳ `id` | string | Alert ID | +| ↳ `title` | string | Alert title | +| ↳ `id` | string | ID of the user, API key, workflow, or alert | +| ↳ `name` | string | Name of the user, API key, or workflow \(or the alert title\) | +| ↳ `email` | string | User email, when a user created it | | ↳ `completed_at` | string | Completion timestamp | | ↳ `labels` | array | Labels associated with the follow-up | | ↳ `external_issue_reference` | object | External issue tracking reference | -| ↳ `provider` | string | External provider name | -| ↳ `issue_name` | string | External issue name or ID | -| ↳ `issue_permalink` | string | Permalink to external issue | +| ↳ `provider` | string | Issue tracking provider \(e.g., Jira, Linear\) | +| ↳ `issue_name` | string | Issue identifier | +| ↳ `issue_permalink` | string | URL to the external issue | @@ -400,6 +478,7 @@ List all users in your Incident.io workspace. Returns user details including id, | `after` | string | No | Pagination cursor to fetch the next page of results | | `email` | string | No | Filter users by email address | | `slack_user_id` | string | No | Filter users by Slack user ID | +| `include_inactive` | boolean | No | Include deactivated or not-yet-active users, for resolving people who have since been offboarded. Default: false | #### Output @@ -410,6 +489,8 @@ List all users in your Incident.io workspace. Returns user details including id, | ↳ `name` | string | Full name of the user | | ↳ `email` | string | Email address of the user | | ↳ `role` | string | Role of the user in the workspace | +| ↳ `slack_user_id` | string | Slack ID of the user | +| ↳ `is_active` | boolean | Whether the user is active \(false once deactivated\) | | `pagination_meta` | object | Pagination metadata | | ↳ `after` | string | Cursor for next page | | ↳ `page_size` | number | Number of items per page | @@ -438,6 +519,8 @@ Get detailed information about a specific user in your Incident.io workspace by | ↳ `name` | string | Full name of the user | | ↳ `email` | string | Email address of the user | | ↳ `role` | string | Role of the user in the workspace | +| ↳ `slack_user_id` | string | Slack ID of the user | +| ↳ `is_active` | boolean | Whether the user is active \(false once deactivated\) | @@ -682,6 +765,7 @@ List all schedules in incident.io | `pagination_meta` | object | Pagination metadata | | ↳ `after` | string | Cursor for next page | | ↳ `page_size` | number | Number of results per page | +| ↳ `total_record_count` | number | Total number of schedules | @@ -766,7 +850,7 @@ Update an existing schedule in incident.io | `id` | string | Yes | The ID of the schedule to update \(e.g., "01FCNDV6P870EA6S7TK1DSYDG0"\) | | `name` | string | No | New name for the schedule \(e.g., "Primary On-Call"\) | | `timezone` | string | No | New timezone for the schedule \(e.g., America/New_York\) | -| `config` | string | No | Schedule configuration as JSON string with rotations. Example: \{"rotations": \[\{"name": "Primary", "users": \[\{"id": "user_id"\}\], "handover_start_at": "2024-01-01T09:00:00Z", "handovers": \[\{"interval": 1, "interval_type": "weekly"\}\]\}\]\} | +| `config` | string | No | Schedule configuration as JSON with rotations. Sending it replaces the entire configuration, including any scheduled future versions of its rotations, so fetch the schedule first and include every version you want to keep. Example: \{"rotations": \[\{"name": "Primary", "users": \[\{"id": "user_id"\}\], "handover_start_at": "2024-01-01T09:00:00Z", "handovers": \[\{"interval": 1, "interval_type": "weekly"\}\]\}\]\} | #### Output @@ -803,7 +887,7 @@ Delete a schedule in incident.io ### List Escalations -List all escalation policies in incident.io +List escalations (pages sent to people) in incident.io. For escalation policies, use List Escalation Paths. @@ -811,7 +895,7 @@ List all escalation policies in incident.io | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `page_size` | number | No | Number of escalations to return per page | +| `page_size` | number | No | Number of escalations to return per page \(max 50\) | | `after` | string | No | Pagination cursor to fetch the next page of results | #### Output @@ -835,7 +919,7 @@ List all escalation policies in incident.io ### Create Escalation -Create a new escalation policy in incident.io +Page users or an escalation path (create an escalation) in incident.io. Provide either escalation_path_id or user_ids, not both. To create a reusable escalation policy, use Create Escalation Path instead. @@ -846,7 +930,9 @@ Create a new escalation policy in incident.io | `idempotency_key` | string | Yes | Unique identifier to prevent duplicate escalation creation. Use a UUID or unique string. | | `title` | string | Yes | Title of the escalation \(e.g., "Database Critical Alert"\) | | `escalation_path_id` | string | No | ID of the escalation path to use \(required if user_ids not provided\) | -| `user_ids` | string | No | Comma-separated list of user IDs to notify \(required if escalation_path_id not provided\) | +| `user_ids` | string | No | Comma-separated list of user IDs to page directly \(required if escalation_path_id not provided\) | +| `incident_id` | string | No | ID of an incident to link this escalation to; it appears in the escalation's related incidents \(e.g., "01H0J1EXE7AXZ2C93K61WBPYEH"\) | +| `description` | string | No | Additional details included with the page \(e.g., "Database CPU above 90%"\) | #### Output @@ -866,7 +952,7 @@ Create a new escalation policy in incident.io ### Show Escalation -Get details of a specific escalation policy in incident.io +Get an escalation (a page sent to people) in incident.io. For an escalation policy, use Show Escalation Path. @@ -874,7 +960,7 @@ Get details of a specific escalation policy in incident.io | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `id` | string | Yes | The ID of the escalation policy \(e.g., "01FCNDV6P870EA6S7TK1DSYDG0"\) | +| `id` | string | Yes | The ID of the escalation \(e.g., "01FCNDV6P870EA6S7TK1DSYDG0"\) | #### Output @@ -1110,7 +1196,7 @@ List all incident roles in incident.io | ↳ `instructions` | string | Instructions for the role | | ↳ `shortform` | string | Short form abbreviation of the role | | ↳ `role_type` | string | The type of role | -| ↳ `required` | boolean | Whether the role is required | +| ↳ `required` | boolean | Not returned by the incident.io API; always empty | | ↳ `created_at` | string | When the role was created | | ↳ `updated_at` | string | When the role was last updated | @@ -1142,7 +1228,7 @@ Create a new incident role in incident.io | ↳ `instructions` | string | Instructions for the role | | ↳ `shortform` | string | Short form abbreviation of the role | | ↳ `role_type` | string | The type of role | -| ↳ `required` | boolean | Whether the role is required | +| ↳ `required` | boolean | Not returned by the incident.io API; always empty | | ↳ `created_at` | string | When the role was created | | ↳ `updated_at` | string | When the role was last updated | @@ -1171,7 +1257,7 @@ Get details of a specific incident role in incident.io | ↳ `instructions` | string | Instructions for the role | | ↳ `shortform` | string | Short form abbreviation of the role | | ↳ `role_type` | string | The type of role | -| ↳ `required` | boolean | Whether the role is required | +| ↳ `required` | boolean | Not returned by the incident.io API; always empty | | ↳ `created_at` | string | When the role was created | | ↳ `updated_at` | string | When the role was last updated | @@ -1204,7 +1290,7 @@ Update an existing incident role in incident.io | ↳ `instructions` | string | Instructions for the role | | ↳ `shortform` | string | Short form abbreviation of the role | | ↳ `role_type` | string | The type of role | -| ↳ `required` | boolean | Whether the role is required | +| ↳ `required` | boolean | Not returned by the incident.io API; always empty | | ↳ `created_at` | string | When the role was created | | ↳ `updated_at` | string | When the role was last updated | @@ -1249,8 +1335,8 @@ List all incident timestamp definitions in incident.io | ↳ `id` | string | The timestamp ID | | ↳ `name` | string | The timestamp name | | ↳ `rank` | number | The rank/order of the timestamp | -| ↳ `created_at` | string | When the timestamp was created | -| ↳ `updated_at` | string | When the timestamp was last updated | +| ↳ `created_at` | string | Not returned by the incident.io API; always empty | +| ↳ `updated_at` | string | Not returned by the incident.io API; always empty | @@ -1274,8 +1360,8 @@ Get details of a specific incident timestamp definition in incident.io | ↳ `id` | string | The timestamp ID | | ↳ `name` | string | The timestamp name | | ↳ `rank` | number | The rank/order of the timestamp | -| ↳ `created_at` | string | When the timestamp was created | -| ↳ `updated_at` | string | When the timestamp was last updated | +| ↳ `created_at` | string | Not returned by the incident.io API; always empty | +| ↳ `updated_at` | string | Not returned by the incident.io API; always empty | @@ -1408,7 +1494,7 @@ List escalation paths in incident.io | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `page_size` | number | No | Number of escalation paths to return per page | +| `page_size` | number | No | Number of escalation paths to return per page \(max 25\) | | `after` | string | No | Pagination cursor to fetch the next page of results | #### Output @@ -1418,8 +1504,35 @@ List escalation paths in incident.io | `escalation_paths` | array | List of escalation paths | | ↳ `id` | string | The escalation path ID | | ↳ `name` | string | The escalation path name | -| ↳ `path` | array | Array of escalation levels | -| ↳ `working_hours` | array | Working hours configuration | +| ↳ `kind` | string | Path kind \(standalone, templated\) | +| ↳ `team_ids` | array | IDs of the teams that own this escalation path | +| ↳ `path` | array | Nodes that form the levels and branches of the path | +| ↳ `id` | string | Node ID, unique within the path | +| ↳ `type` | string | Node type \(level, notify_channel, delay, if_else, repeat, voicemail, escalation_path\) | +| ↳ `level` | object | For a level node: who to page and how long to wait for an ack | +| ↳ `targets` | array | Users, schedules, or channels to page | +| ↳ `id` | string | Target ID | +| ↳ `type` | string | Target type \(schedule, user, slack_channel, msteams_channel\) | +| ↳ `urgency` | string | Urgency \(high, low\) | +| ↳ `schedule_mode` | string | For schedule targets, which users to page | +| ↳ `time_to_ack_seconds` | number | Seconds to wait for an ack before moving on | +| ↳ `notify_channel` | json | For a notify_channel node | +| ↳ `delay` | json | For a delay node | +| ↳ `if_else` | json | For an if_else node | +| ↳ `repeat` | json | For a repeat node | +| ↳ `escalation_path` | json | For an escalation_path node | +| ↳ `working_hours` | array | Working-hours windows the path can refer to | +| ↳ `id` | string | Window ID | +| ↳ `name` | string | Window name | +| ↳ `timezone` | string | Timezone the intervals are in | +| ↳ `weekday_intervals` | array | Intervals, each \{weekday, start_time, end_time\} | +| ↳ `repeat_config` | json | How the path repeats | +| ↳ `current_responders` | array | Users currently on call for this path | +| ↳ `id` | string | User ID | +| ↳ `name` | string | User display name | +| ↳ `email` | string | User email address | +| ↳ `role` | string | User role | +| ↳ `slack_user_id` | string | Slack user ID | | `pagination_meta` | object | Pagination metadata | | ↳ `after` | string | Cursor for next page | | ↳ `page_size` | number | Number of results per page | @@ -1437,8 +1550,8 @@ Create a new escalation path in incident.io | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `name` | string | Yes | Name of the escalation path \(e.g., "Critical Incident Path"\) | -| `path` | json | Yes | Array of escalation levels with targets and time to acknowledge in seconds. Each level should have: targets \(array of \{id, type, schedule_id?, user_id?, urgency\}\) and time_to_ack_seconds \(number\) | -| `working_hours` | json | No | Optional working hours configuration. Array of \{weekday, start_time, end_time\} | +| `path` | json | Yes | Array of escalation path nodes. Each node needs a unique "id" and a "type" \(level, notify_channel, delay, if_else, repeat, voicemail, escalation_path\); a level node nests its targets under "level", e.g. \[\{"id":"lvl1","type":"level","level":\{"targets":\[\{"id":"<schedule id>","type":"schedule","schedule_mode":"currently_on_call","urgency":"high"\}\],"time_to_ack_seconds":300\}\}\]. Target type is schedule, user, slack_channel, or msteams_channel; urgency is high or low. | +| `working_hours` | json | No | Optional. Array of working-hours windows, each \{id, name, timezone, weekday_intervals: \[\{weekday, start_time, end_time\}\]\}, e.g. \[\{"id":"wh","name":"Business hours","timezone":"Europe/London","weekday_intervals":\[\{"weekday":"monday","start_time":"09:00","end_time":"17:00"\}\]\}\] | #### Output @@ -1447,18 +1560,35 @@ Create a new escalation path in incident.io | `escalation_path` | object | The created escalation path | | ↳ `id` | string | The escalation path ID | | ↳ `name` | string | The escalation path name | -| ↳ `path` | array | Array of escalation levels | -| ↳ `targets` | array | Targets for this level | -| ↳ `id` | string | Target ID | -| ↳ `type` | string | Target type | -| ↳ `schedule_id` | string | Schedule ID if type is schedule | -| ↳ `user_id` | string | User ID if type is user | -| ↳ `urgency` | string | Urgency level | -| ↳ `time_to_ack_seconds` | number | Time to acknowledge in seconds | -| ↳ `working_hours` | array | Working hours configuration | -| ↳ `weekday` | string | Day of week | -| ↳ `start_time` | string | Start time | -| ↳ `end_time` | string | End time | +| ↳ `kind` | string | Path kind \(standalone, templated\) | +| ↳ `team_ids` | array | IDs of the teams that own this escalation path | +| ↳ `path` | array | Nodes that form the levels and branches of the path | +| ↳ `id` | string | Node ID, unique within the path | +| ↳ `type` | string | Node type \(level, notify_channel, delay, if_else, repeat, voicemail, escalation_path\) | +| ↳ `level` | object | For a level node: who to page and how long to wait for an ack | +| ↳ `targets` | array | Users, schedules, or channels to page | +| ↳ `id` | string | Target ID | +| ↳ `type` | string | Target type \(schedule, user, slack_channel, msteams_channel\) | +| ↳ `urgency` | string | Urgency \(high, low\) | +| ↳ `schedule_mode` | string | For schedule targets, which users to page | +| ↳ `time_to_ack_seconds` | number | Seconds to wait for an ack before moving on | +| ↳ `notify_channel` | json | For a notify_channel node | +| ↳ `delay` | json | For a delay node | +| ↳ `if_else` | json | For an if_else node | +| ↳ `repeat` | json | For a repeat node | +| ↳ `escalation_path` | json | For an escalation_path node | +| ↳ `working_hours` | array | Working-hours windows the path can refer to | +| ↳ `id` | string | Window ID | +| ↳ `name` | string | Window name | +| ↳ `timezone` | string | Timezone the intervals are in | +| ↳ `weekday_intervals` | array | Intervals, each \{weekday, start_time, end_time\} | +| ↳ `repeat_config` | json | How the path repeats | +| ↳ `current_responders` | array | Users currently on call for this path | +| ↳ `id` | string | User ID | +| ↳ `name` | string | User display name | +| ↳ `email` | string | User email address | +| ↳ `role` | string | User role | +| ↳ `slack_user_id` | string | Slack user ID | @@ -1481,18 +1611,35 @@ Get details of a specific escalation path in incident.io | `escalation_path` | object | The escalation path details | | ↳ `id` | string | The escalation path ID | | ↳ `name` | string | The escalation path name | -| ↳ `path` | array | Array of escalation levels | -| ↳ `targets` | array | Targets for this level | -| ↳ `id` | string | Target ID | -| ↳ `type` | string | Target type | -| ↳ `schedule_id` | string | Schedule ID if type is schedule | -| ↳ `user_id` | string | User ID if type is user | -| ↳ `urgency` | string | Urgency level | -| ↳ `time_to_ack_seconds` | number | Time to acknowledge in seconds | -| ↳ `working_hours` | array | Working hours configuration | -| ↳ `weekday` | string | Day of week | -| ↳ `start_time` | string | Start time | -| ↳ `end_time` | string | End time | +| ↳ `kind` | string | Path kind \(standalone, templated\) | +| ↳ `team_ids` | array | IDs of the teams that own this escalation path | +| ↳ `path` | array | Nodes that form the levels and branches of the path | +| ↳ `id` | string | Node ID, unique within the path | +| ↳ `type` | string | Node type \(level, notify_channel, delay, if_else, repeat, voicemail, escalation_path\) | +| ↳ `level` | object | For a level node: who to page and how long to wait for an ack | +| ↳ `targets` | array | Users, schedules, or channels to page | +| ↳ `id` | string | Target ID | +| ↳ `type` | string | Target type \(schedule, user, slack_channel, msteams_channel\) | +| ↳ `urgency` | string | Urgency \(high, low\) | +| ↳ `schedule_mode` | string | For schedule targets, which users to page | +| ↳ `time_to_ack_seconds` | number | Seconds to wait for an ack before moving on | +| ↳ `notify_channel` | json | For a notify_channel node | +| ↳ `delay` | json | For a delay node | +| ↳ `if_else` | json | For an if_else node | +| ↳ `repeat` | json | For a repeat node | +| ↳ `escalation_path` | json | For an escalation_path node | +| ↳ `working_hours` | array | Working-hours windows the path can refer to | +| ↳ `id` | string | Window ID | +| ↳ `name` | string | Window name | +| ↳ `timezone` | string | Timezone the intervals are in | +| ↳ `weekday_intervals` | array | Intervals, each \{weekday, start_time, end_time\} | +| ↳ `repeat_config` | json | How the path repeats | +| ↳ `current_responders` | array | Users currently on call for this path | +| ↳ `id` | string | User ID | +| ↳ `name` | string | User display name | +| ↳ `email` | string | User email address | +| ↳ `role` | string | User role | +| ↳ `slack_user_id` | string | Slack user ID | @@ -1508,8 +1655,8 @@ Update an existing escalation path in incident.io | --------- | ---- | -------- | ----------- | | `id` | string | Yes | The ID of the escalation path to update \(e.g., "01FCNDV6P870EA6S7TK1DSYDG0"\) | | `name` | string | Yes | New name for the escalation path \(e.g., "Critical Incident Path"\) | -| `path` | json | Yes | New escalation path configuration. Array of escalation levels with targets and time_to_ack_seconds | -| `working_hours` | json | No | New working hours configuration. Array of \{weekday, start_time, end_time\} | +| `path` | json | Yes | New escalation path configuration. Array of escalation path nodes. Each node needs a unique "id" and a "type" \(level, notify_channel, delay, if_else, repeat, voicemail, escalation_path\); a level node nests its targets under "level", e.g. \[\{"id":"lvl1","type":"level","level":\{"targets":\[\{"id":"<schedule id>","type":"schedule","schedule_mode":"currently_on_call","urgency":"high"\}\],"time_to_ack_seconds":300\}\}\]. Target type is schedule, user, slack_channel, or msteams_channel; urgency is high or low. | +| `working_hours` | json | No | New working hours configuration. Array of working-hours windows, each \{id, name, timezone, weekday_intervals: \[\{weekday, start_time, end_time\}\]\}, e.g. \[\{"id":"wh","name":"Business hours","timezone":"Europe/London","weekday_intervals":\[\{"weekday":"monday","start_time":"09:00","end_time":"17:00"\}\]\}\] | #### Output @@ -1518,18 +1665,35 @@ Update an existing escalation path in incident.io | `escalation_path` | object | The updated escalation path | | ↳ `id` | string | The escalation path ID | | ↳ `name` | string | The escalation path name | -| ↳ `path` | array | Array of escalation levels | -| ↳ `targets` | array | Targets for this level | -| ↳ `id` | string | Target ID | -| ↳ `type` | string | Target type | -| ↳ `schedule_id` | string | Schedule ID if type is schedule | -| ↳ `user_id` | string | User ID if type is user | -| ↳ `urgency` | string | Urgency level | -| ↳ `time_to_ack_seconds` | number | Time to acknowledge in seconds | -| ↳ `working_hours` | array | Working hours configuration | -| ↳ `weekday` | string | Day of week | -| ↳ `start_time` | string | Start time | -| ↳ `end_time` | string | End time | +| ↳ `kind` | string | Path kind \(standalone, templated\) | +| ↳ `team_ids` | array | IDs of the teams that own this escalation path | +| ↳ `path` | array | Nodes that form the levels and branches of the path | +| ↳ `id` | string | Node ID, unique within the path | +| ↳ `type` | string | Node type \(level, notify_channel, delay, if_else, repeat, voicemail, escalation_path\) | +| ↳ `level` | object | For a level node: who to page and how long to wait for an ack | +| ↳ `targets` | array | Users, schedules, or channels to page | +| ↳ `id` | string | Target ID | +| ↳ `type` | string | Target type \(schedule, user, slack_channel, msteams_channel\) | +| ↳ `urgency` | string | Urgency \(high, low\) | +| ↳ `schedule_mode` | string | For schedule targets, which users to page | +| ↳ `time_to_ack_seconds` | number | Seconds to wait for an ack before moving on | +| ↳ `notify_channel` | json | For a notify_channel node | +| ↳ `delay` | json | For a delay node | +| ↳ `if_else` | json | For an if_else node | +| ↳ `repeat` | json | For a repeat node | +| ↳ `escalation_path` | json | For an escalation_path node | +| ↳ `working_hours` | array | Working-hours windows the path can refer to | +| ↳ `id` | string | Window ID | +| ↳ `name` | string | Window name | +| ↳ `timezone` | string | Timezone the intervals are in | +| ↳ `weekday_intervals` | array | Intervals, each \{weekday, start_time, end_time\} | +| ↳ `repeat_config` | json | How the path repeats | +| ↳ `current_responders` | array | Users currently on call for this path | +| ↳ `id` | string | User ID | +| ↳ `name` | string | User display name | +| ↳ `email` | string | User email address | +| ↳ `role` | string | User role | +| ↳ `slack_user_id` | string | Slack user ID | @@ -1631,7 +1795,7 @@ List alerts in incident.io, optionally filtered by status, source, or created da | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `page_size` | number | No | Number of results per page \(e.g., 10, 25, 50\). Default: 25 | +| `page_size` | number | No | Number of results per page \(e.g., 10, 25, 50; max 50\). Default: 25 | | `after` | string | No | Pagination cursor to fetch the next page of results \(e.g., "01FCNDV6P870EA6S7TK1DSYDG0"\) | | `status` | string | No | Filter by alert status: "firing" or "resolved" | | `status_operator` | string | No | How to apply the status filter: "one_of" to match it, "not_in" to exclude it. Default: one_of | @@ -1660,6 +1824,9 @@ List alerts in incident.io, optionally filtered by status, source, or created da | ↳ `updated_at` | string | When this alert was last updated | | ↳ `alert_group_ids` | array | IDs of every alert group this alert belongs to | | ↳ `attributes` | array | Attribute values parsed from the alert payload | +| ↳ `tags` | array | Tags someone has applied to this alert | +| ↳ `id` | string | Tag ID | +| ↳ `name` | string | Tag name | | `pagination_meta` | object | Pagination metadata | | ↳ `after` | string | Cursor for next page | | ↳ `page_size` | number | Number of results per page | @@ -1695,6 +1862,9 @@ Get a single alert by ID from incident.io | ↳ `updated_at` | string | When this alert was last updated | | ↳ `alert_group_ids` | array | IDs of every alert group this alert belongs to | | ↳ `attributes` | array | Attribute values parsed from the alert payload | +| ↳ `tags` | array | Tags someone has applied to this alert | +| ↳ `id` | string | Tag ID | +| ↳ `name` | string | Tag name | @@ -1727,6 +1897,9 @@ Resolve a currently firing alert in incident.io. Resolving an already-resolved a | ↳ `updated_at` | string | When this alert was last updated | | ↳ `alert_group_ids` | array | IDs of every alert group this alert belongs to | | ↳ `attributes` | array | Attribute values parsed from the alert payload | +| ↳ `tags` | array | Tags someone has applied to this alert | +| ↳ `id` | string | Tag ID | +| ↳ `name` | string | Tag name | @@ -1769,7 +1942,7 @@ List the connections between incidents and alerts in incident.io — which alert | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `page_size` | number | No | Number of results per page \(e.g., 10, 25, 50\). Default: 25 | +| `page_size` | number | No | Number of results per page \(e.g., 10, 25, 50; max 50\). Default: 25 | | `after` | string | No | Pagination cursor to fetch the next page of results \(e.g., "01FCNDV6P870EA6S7TK1DSYDG0"\) | | `incident_id` | string | No | Only return alerts attached to this incident \(e.g., "01FDAG4SAP5TYPT98WGR2N7W91"\) | | `alert_id` | string | No | Only return connections for this alert \(e.g., "01GW2G3V0S59R238FAHPDS1R66"\) | @@ -1878,7 +2051,7 @@ List the entries of a catalog type in incident.io — for example every service, | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `catalog_type_id` | string | Yes | The ID of the catalog type to list entries for \(e.g., "01FCNDV6P870EA6S7TK1DSYDG0"\) | -| `page_size` | number | No | Number of results per page \(e.g., 10, 25, 50\). Default: 25 | +| `page_size` | number | No | Number of results per page \(e.g., 10, 25, 50; max 250\). Default: 25 | | `after` | string | No | Pagination cursor to fetch the next page of results \(e.g., "01FCNDV6P870EA6S7TK1DSYDG0"\) | | `identifier` | string | No | Only return entries matching this identifier. Searches by ID, external ID, and alias. | diff --git a/apps/docs/content/docs/integrations/linear.mdx b/apps/docs/content/docs/integrations/linear.mdx index 53b4a019aae..6a538b56b57 100644 --- a/apps/docs/content/docs/integrations/linear.mdx +++ b/apps/docs/content/docs/integrations/linear.mdx @@ -582,7 +582,11 @@ List projects in Linear with optional filtering | ↳ `id` | string | Project ID | | ↳ `name` | string | Project name | | ↳ `description` | string | Project description | -| ↳ `state` | string | Project state \(planned, started, paused, completed, canceled\) | +| ↳ `state` | string | Deprecated project state \(planned, started, paused, completed, canceled\); prefer status | +| ↳ `status` | object | Current project status | +| ↳ `id` | string | Project status ID | +| ↳ `name` | string | Project status name | +| ↳ `type` | string | Status type \(backlog, planned, started, paused, completed, canceled\) | | ↳ `priority` | number | Project priority \(0-4\) | | ↳ `startDate` | string | Start date \(YYYY-MM-DD\) | | ↳ `targetDate` | string | Target date \(YYYY-MM-DD\) | @@ -594,6 +598,9 @@ List projects in Linear with optional filtering | ↳ `teams` | array | Associated teams | | ↳ `id` | string | Team ID | | ↳ `name` | string | Team name | +| ↳ `completedAt` | string | Completion timestamp \(ISO 8601\) | +| ↳ `canceledAt` | string | Cancellation timestamp \(ISO 8601\) | +| ↳ `archivedAt` | string | Archive timestamp \(ISO 8601\) | @@ -617,7 +624,11 @@ Get a single project by ID from Linear | ↳ `id` | string | Project ID | | ↳ `name` | string | Project name | | ↳ `description` | string | Project description | -| ↳ `state` | string | Project state \(planned, started, paused, completed, canceled\) | +| ↳ `state` | string | Deprecated project state \(planned, started, paused, completed, canceled\); prefer status | +| ↳ `status` | object | Current project status | +| ↳ `id` | string | Project status ID | +| ↳ `name` | string | Project status name | +| ↳ `type` | string | Status type \(backlog, planned, started, paused, completed, canceled\) | | ↳ `priority` | number | Project priority \(0-4\) | | ↳ `startDate` | string | Start date \(YYYY-MM-DD\) | | ↳ `targetDate` | string | Target date \(YYYY-MM-DD\) | @@ -629,6 +640,9 @@ Get a single project by ID from Linear | ↳ `teams` | array | Associated teams | | ↳ `id` | string | Team ID | | ↳ `name` | string | Team name | +| ↳ `completedAt` | string | Completion timestamp \(ISO 8601\) | +| ↳ `canceledAt` | string | Cancellation timestamp \(ISO 8601\) | +| ↳ `archivedAt` | string | Archive timestamp \(ISO 8601\) | @@ -658,7 +672,11 @@ Create a new project in Linear | ↳ `id` | string | Project ID | | ↳ `name` | string | Project name | | ↳ `description` | string | Project description | -| ↳ `state` | string | Project state \(planned, started, paused, completed, canceled\) | +| ↳ `state` | string | Deprecated project state \(planned, started, paused, completed, canceled\); prefer status | +| ↳ `status` | object | Current project status | +| ↳ `id` | string | Project status ID | +| ↳ `name` | string | Project status name | +| ↳ `type` | string | Status type \(backlog, planned, started, paused, completed, canceled\) | | ↳ `priority` | number | Project priority \(0-4\) | | ↳ `startDate` | string | Start date \(YYYY-MM-DD\) | | ↳ `targetDate` | string | Target date \(YYYY-MM-DD\) | @@ -686,7 +704,8 @@ Update an existing project in Linear | `projectId` | string | Yes | Project ID to update | | `name` | string | No | New project name | | `description` | string | No | New project description | -| `state` | string | No | Project state \(planned, started, completed, canceled\) | +| `state` | string | No | Deprecated: Linear no longer accepts a project state on update. Use statusId instead; a state given without statusId fails with an error. | +| `statusId` | string | No | Project status ID to move the project to \(see List Project Statuses\). Omit to keep the current status. | | `leadId` | string | No | User ID of the project lead | | `startDate` | string | No | Project start date \(ISO format: YYYY-MM-DD\) | | `targetDate` | string | No | Project target date \(ISO format: YYYY-MM-DD\) | @@ -700,7 +719,11 @@ Update an existing project in Linear | ↳ `id` | string | Project ID | | ↳ `name` | string | Project name | | ↳ `description` | string | Project description | -| ↳ `state` | string | Project state \(planned, started, paused, completed, canceled\) | +| ↳ `state` | string | Deprecated project state \(planned, started, paused, completed, canceled\); prefer status | +| ↳ `status` | object | Current project status | +| ↳ `id` | string | Project status ID | +| ↳ `name` | string | Project status name | +| ↳ `type` | string | Status type \(backlog, planned, started, paused, completed, canceled\) | | ↳ `priority` | number | Project priority \(0-4\) | | ↳ `startDate` | string | Start date \(YYYY-MM-DD\) | | ↳ `targetDate` | string | Target date \(YYYY-MM-DD\) | @@ -928,7 +951,7 @@ Update an existing label in Linear ### Linear Archive Label -Archive a label in Linear +Archive (retire) a label in Linear. A retired label can no longer be newly assigned but stays on issues that already use it. @@ -996,7 +1019,7 @@ Create a new workflow state (status) in Linear | --------- | ---- | -------- | ----------- | | `teamId` | string | Yes | Team ID to create the state in | | `name` | string | Yes | State name \(e.g., "In Review"\) | -| `color` | string | No | State color \(hex format\) | +| `color` | string | Yes | State color \(hex format, e.g. #5E6AD2\) | | `type` | string | Yes | State type: "backlog", "unstarted", "started", "completed", or "canceled" | | `description` | string | No | State description | | `position` | number | No | Position in the workflow | @@ -1126,7 +1149,7 @@ Get a single cycle by ID from Linear ### Linear Create Cycle -Create a new cycle (sprint/iteration) in Linear +Deprecated: Linear no longer supports creating cycles through its API (they are generated from the team cycle settings), so this always returns an error from Linear. @@ -1519,7 +1542,7 @@ Mark a notification as read or unread in Linear | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `notificationId` | string | Yes | Notification ID to update | -| `readAt` | string | No | Timestamp to mark as read \(ISO format\). Pass null or omit to mark as unread | +| `readAt` | string | No | ISO timestamp to mark the notification read at. Omit it to mark it read now; pass null to mark it unread. | #### Output @@ -1530,7 +1553,7 @@ Mark a notification as read or unread in Linear | ↳ `type` | string | Notification type | | ↳ `createdAt` | string | Creation timestamp | | ↳ `readAt` | string | Read timestamp | -| ↳ `issue` | object | Related issue | +| ↳ `issue` | object | Related issue \(only for issue notifications\) | @@ -1613,7 +1636,7 @@ List all customers in Linear ### Linear Create Customer Request -Create a customer request (need) in Linear. Assign to customer, set urgency (priority: 0 = Not important, 1 = Important), and optionally link to an issue. +Create a customer request (need) in Linear. Assign to customer, set urgency (priority: 0 = Not important, 1 = Important), and link it to an issue (required for API calls). @@ -1624,8 +1647,8 @@ Create a customer request (need) in Linear. Assign to customer, set urgency (pri | `customerId` | string | Yes | Customer ID to assign this request to | | `body` | string | No | Description of the customer request | | `priority` | number | No | Urgency level: 0 = Not important, 1 = Important \(default: 0\) | -| `issueId` | string | No | Issue ID to link this request to | -| `projectId` | string | No | Project ID to link this request to | +| `issueId` | string | Yes | Issue to link this request to \(UUID or identifier such as ENG-123\). Linear requires it for API calls. | +| `projectId` | string | No | Deprecated and ignored: Linear no longer accepts a project on customer requests. | #### Output @@ -1661,7 +1684,7 @@ Update a customer request (need) in Linear. Can change urgency, description, cus | `priority` | number | No | Updated urgency level: 0 = Not important, 1 = Important | | `customerId` | string | No | New customer ID to assign this request to | | `issueId` | string | No | New issue ID to link this request to | -| `projectId` | string | No | New project ID to link this request to | +| `projectId` | string | No | Deprecated and ignored: Linear no longer accepts a project on customer requests. | #### Output @@ -2371,7 +2394,7 @@ Create a new project status in Linear | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `name` | string | Yes | Project status name | -| `type` | string | Yes | Status type: "backlog", "planned", "started", "paused", "completed", or "canceled" | +| `type` | string | Yes | Status type: "backlog", "planned", "started", "completed", or "canceled" | | `color` | string | Yes | Status color \(hex code\) | | `position` | number | Yes | Position in status list \(e.g. 0, 1, 2...\) | | `description` | string | No | Status description | @@ -2432,7 +2455,7 @@ Update a project status in Linear ### Linear Delete Project Status -Delete a project status in Linear +Archive a project status in Linear (Linear does not support deleting one). The status must have no active projects and must not be the last status of its type. @@ -2440,13 +2463,13 @@ Delete a project status in Linear | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `statusId` | string | Yes | Project status ID to delete | +| `statusId` | string | Yes | Project status ID to archive | #### Output | Parameter | Type | Description | | --------- | ---- | ----------- | -| `success` | boolean | Whether the deletion was successful | +| `success` | boolean | Whether the archive was successful | diff --git a/apps/docs/content/docs/integrations/mailgun.mdx b/apps/docs/content/docs/integrations/mailgun.mdx index fb9d98f75e3..199f747e4fa 100644 --- a/apps/docs/content/docs/integrations/mailgun.mdx +++ b/apps/docs/content/docs/integrations/mailgun.mdx @@ -94,7 +94,7 @@ List events (logs) for messages sent through Mailgun | --------- | ---- | -------- | ----------- | | `domain` | string | Yes | Mailgun domain for listing events \(e.g., mg.example.com\) | | `event` | string | No | Filter by event type \(accepted, delivered, failed, opened, clicked, etc.\) | -| `limit` | number | No | Maximum number of events to return \(default: 100\) | +| `limit` | number | No | Maximum number of events to return \(default: 100, max: 300\) | #### Output diff --git a/apps/docs/content/docs/integrations/okta.mdx b/apps/docs/content/docs/integrations/okta.mdx index d5d2eeec9be..74d1372bac0 100644 --- a/apps/docs/content/docs/integrations/okta.mdx +++ b/apps/docs/content/docs/integrations/okta.mdx @@ -268,6 +268,28 @@ Unsuspend a previously suspended user in your Okta organization. Returns the use +### Unlock User in Okta + +Unlock a LOCKED_OUT user, or an ACTIVE user blocked from unknown devices, so they can sign in with their current password. Works only for Okta-sourced users, not directory-sourced accounts such as Active Directory. + + + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `userId` | string | Yes | User ID or login to unlock | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `userId` | string | Unlocked user ID | +| `unlocked` | boolean | Whether the user was unlocked | +| `success` | boolean | Operation success status | + + + ### Reset Password in Okta Generate a one-time token to reset a user password. Can email the reset link to the user or return it directly. Transitions the user to RECOVERY status. @@ -542,6 +564,39 @@ List all members of a specific group in your Okta organization +### List User Groups from Okta + +List the groups a user is a member of, one page at a time (pass nextCursor back as after while hasMore is true). Use it for access reviews and offboarding instead of scanning the members of each group. + + + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `userId` | string | Yes | User ID or login whose groups to list | +| `after` | string | No | Opaque pagination cursor returned as nextCursor by a previous call | +| `limit` | number | No | Maximum number of groups to return per page \(Okta default: 200\) | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `groups` | array | Array of groups the user belongs to | +| ↳ `id` | string | Group ID | +| ↳ `name` | string | Group name | +| ↳ `description` | string | Group description | +| ↳ `type` | string | Group type \(OKTA_GROUP, APP_GROUP, BUILT_IN\) | +| ↳ `created` | string | Creation timestamp | +| ↳ `lastUpdated` | string | Last update timestamp | +| ↳ `lastMembershipUpdated` | string | Last membership change timestamp | +| `count` | number | Number of groups returned | +| `nextCursor` | string | Cursor for the next page, or null on the last page | +| `hasMore` | boolean | Whether more groups are available | +| `success` | boolean | Operation success status | + + + ### List Group Rules from Okta List the group rules in your Okta organization. Each rule assigns users to groups automatically based on an expression over their profile, so this shows how group membership is being driven. diff --git a/apps/docs/content/docs/integrations/pagerduty.mdx b/apps/docs/content/docs/integrations/pagerduty.mdx index a2182e65860..ed808cb41e5 100644 --- a/apps/docs/content/docs/integrations/pagerduty.mdx +++ b/apps/docs/content/docs/integrations/pagerduty.mdx @@ -37,6 +37,7 @@ List incidents from PagerDuty with optional filters. | `sortBy` | string | No | Sort field \(e.g., created_at:desc\) | | `limit` | string | No | Maximum number of results \(max 100\) | | `offset` | string | No | Offset to start pagination search results | +| `includeTotal` | boolean | No | Populate the total result count in the response \(PagerDuty returns null for total unless requested; slower\) | #### Output @@ -254,6 +255,7 @@ List the individual alerts attached to a PagerDuty incident. | `statuses` | string | No | Comma-separated statuses to filter \(triggered, resolved\) | | `limit` | string | No | Maximum number of results \(max 100\) | | `offset` | string | No | Offset to start pagination search results | +| `includeTotal` | boolean | No | Populate the total result count in the response \(PagerDuty returns null for total unless requested; slower\) | #### Output @@ -288,6 +290,7 @@ List services from PagerDuty with optional name filter. | `query` | string | No | Filter services by name | | `limit` | string | No | Maximum number of results \(max 100\) | | `offset` | string | No | Offset to start pagination search results | +| `includeTotal` | boolean | No | Populate the total result count in the response \(PagerDuty returns null for total unless requested; slower\) | #### Output @@ -354,6 +357,7 @@ List current on-call entries from PagerDuty. | `until` | string | No | End time filter \(ISO 8601 format\) | | `limit` | string | No | Maximum number of results \(max 100\) | | `offset` | string | No | Offset to start pagination search results | +| `includeTotal` | boolean | No | Populate the total result count in the response \(PagerDuty returns null for total unless requested; slower\) | #### Output @@ -388,6 +392,7 @@ List escalation policies from PagerDuty with an optional name filter. | `query` | string | No | Filter escalation policies by name | | `limit` | string | No | Maximum number of results \(max 100\) | | `offset` | string | No | Offset to start pagination search results | +| `includeTotal` | boolean | No | Populate the total result count in the response \(PagerDuty returns null for total unless requested; slower\) | #### Output @@ -419,6 +424,7 @@ List on-call schedules from PagerDuty with an optional name filter. | `query` | string | No | Filter schedules by name | | `limit` | string | No | Maximum number of results \(max 100\) | | `offset` | string | No | Offset to start pagination search results | +| `includeTotal` | boolean | No | Populate the total result count in the response \(PagerDuty returns null for total unless requested; slower\) | #### Output @@ -449,6 +455,7 @@ List users from PagerDuty with an optional name/email filter. | `query` | string | No | Filter users by name or email | | `limit` | string | No | Maximum number of results \(max 100\) | | `offset` | string | No | Offset to start pagination search results | +| `includeTotal` | boolean | No | Populate the total result count in the response \(PagerDuty returns null for total unless requested; slower\) | #### Output @@ -487,6 +494,8 @@ Send a trigger, acknowledge, or resolve event to PagerDuty Events API v2 using a | `component` | string | No | Component of the source machine responsible for the event | | `group` | string | No | Logical grouping of components of a service | | `class` | string | No | The class/type of the event | +| `timestamp` | string | No | ISO 8601 time at which the monitoring tool detected or generated the event \(trigger only\) | +| `customDetails` | json | No | JSON object of additional details about the event and affected system \(trigger only\) | #### Output diff --git a/apps/docs/content/docs/integrations/resend.mdx b/apps/docs/content/docs/integrations/resend.mdx index cefddb4d4b3..72f5929cb7a 100644 --- a/apps/docs/content/docs/integrations/resend.mdx +++ b/apps/docs/content/docs/integrations/resend.mdx @@ -141,6 +141,8 @@ List all contacts in Resend | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | +| `limit` | number | No | Number of contacts to return, 1 to 100 \(Resend defaults to 20\) | +| `after` | string | No | Pagination cursor: the ID of the last contact from the previous page, to fetch the next page | #### Output @@ -315,7 +317,7 @@ Delete an audience from Resend by ID ### Create Broadcast -Create a broadcast email for an audience in Resend +Create a broadcast email for a segment (or legacy audience) in Resend @@ -323,7 +325,8 @@ Create a broadcast email for an audience in Resend | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `audienceId` | string | Yes | The ID of the audience to send the broadcast to | +| `segmentId` | string | No | The ID of the segment to send the broadcast to. Provide this or audienceId; segmentId takes precedence | +| `audienceId` | string | No | Deprecated by Resend in favor of segmentId: the ID of the audience to send the broadcast to | | `broadcastFrom` | string | Yes | Sender email address \(e.g., "sender@example.com" or "Sender Name <sender@example.com>"\) | | `broadcastSubject` | string | Yes | Broadcast email subject line | | `broadcastHtml` | string | No | HTML content of the broadcast | @@ -383,7 +386,7 @@ Retrieve details of a broadcast by ID | `segmentId` | string | Segment ID \(the current recipient field\) | | `from` | string | Sender email address | | `subject` | string | Broadcast subject | -| `replyTo` | string | Reply-to email address | +| `replyTo` | array | Reply-to email addresses | | `previewText` | string | Inbox preview text | | `status` | string | Broadcast status \(e.g., draft, sent\) | | `createdAt` | string | Broadcast creation timestamp | @@ -402,6 +405,8 @@ List all verified domains in your Resend account | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | +| `limit` | number | No | Number of domains to return, 1 to 100 \(Resend defaults to 20\) | +| `after` | string | No | Pagination cursor: the ID of the last domain from the previous page, to fetch the next page | #### Output diff --git a/apps/docs/content/docs/integrations/rippling.mdx b/apps/docs/content/docs/integrations/rippling.mdx index 39e4bc686b4..09414f62e7a 100644 --- a/apps/docs/content/docs/integrations/rippling.mdx +++ b/apps/docs/content/docs/integrations/rippling.mdx @@ -31,14 +31,29 @@ List all workers with optional filtering and pagination | --------- | ---- | -------- | ----------- | | `filter` | string | No | Filter expression | | `expand` | string | No | Comma-separated fields to expand | -| `orderBy` | string | No | Sort field. Prefix with - for descending | -| `cursor` | string | No | Pagination cursor from previous response | +| `orderBy` | string | No | Sort field\(s\), comma-separated; append " desc" for descending \(e.g. created_at desc\) | +| `cursor` | string | No | Pagination cursor: the nextCursor output of the previous page | #### Output | Parameter | Type | Description | | --------- | ---- | ----------- | | `workers` | array | List of workers | +| ↳ `job_function_id` | string | Job function ID | +| ↳ `pay_schedule_id` | string | Pay schedule ID | +| ↳ `original_start_date` | string | Original start date | +| ↳ `work_schedule` | json | Work schedule | +| ↳ `compensation_grade` | json | Compensation grade | +| ↳ `user` | json | Expanded user \(expand=user\) | +| ↳ `manager` | json | Expanded manager \(expand=manager\) | +| ↳ `legal_entity` | json | Expanded legal entity \(expand=legal_entity\) | +| ↳ `employment_type` | json | Expanded employment type \(expand=employment_type\) | +| ↳ `compensation` | json | Expanded compensation \(expand=compensation\) | +| ↳ `department` | json | Expanded department \(expand=department\) | +| ↳ `teams` | json | Expanded teams, when requested via expand | +| ↳ `level` | json | Expanded level, when requested via expand | +| ↳ `job_function` | json | Expanded job function, when requested via expand | +| ↳ `business_partners` | json | Expanded business partners, when requested via expand | | ↳ `id` | string | Worker ID | | ↳ `created_at` | string | Record creation date | | ↳ `updated_at` | string | Record update date | @@ -73,6 +88,7 @@ List all workers with optional filtering and pagination | ↳ `country_fields` | json | Country-specific fields | | `totalCount` | number | Number of items returned | | `nextLink` | string | Link to next page of results | +| `nextCursor` | string | Cursor for the next page; pass it back as the cursor param \(null on the last page\) | | `__meta` | json | Metadata including redacted_fields | @@ -126,6 +142,21 @@ Get a specific worker by ID | `termination_details` | json | Termination details | | `custom_fields` | json | Custom fields | | `country_fields` | json | Country-specific fields | +| `job_function_id` | string | Job function ID | +| `pay_schedule_id` | string | Pay schedule ID | +| `original_start_date` | string | Original start date | +| `work_schedule` | json | Work schedule | +| `compensation_grade` | json | Compensation grade | +| `user` | json | Expanded user \(expand=user\) | +| `manager` | json | Expanded manager \(expand=manager\) | +| `legal_entity` | json | Expanded legal entity \(expand=legal_entity\) | +| `employment_type` | json | Expanded employment type \(expand=employment_type\) | +| `compensation` | json | Expanded compensation \(expand=compensation\) | +| `department` | json | Expanded department \(expand=department\) | +| `teams` | json | Expanded teams, when requested via expand | +| `level` | json | Expanded level, when requested via expand | +| `job_function` | json | Expanded job function, when requested via expand | +| `business_partners` | json | Expanded business partners, when requested via expand | | `__meta` | json | Metadata including redacted_fields | @@ -140,8 +171,8 @@ List all users with optional pagination | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `orderBy` | string | No | Sort field. Prefix with - for descending | -| `cursor` | string | No | Pagination cursor from previous response | +| `orderBy` | string | No | Sort field\(s\), comma-separated; append " desc" for descending \(e.g. created_at desc\) | +| `cursor` | string | No | Pagination cursor: the nextCursor output of the previous page | #### Output @@ -165,6 +196,7 @@ List all users with optional pagination | ↳ `photos` | json | Array of photo objects | | `totalCount` | number | Number of items returned | | `nextLink` | string | Link to next page of results | +| `nextCursor` | string | Cursor for the next page; pass it back as the cursor param \(null on the last page\) | | `__meta` | json | Metadata including redacted_fields | @@ -215,8 +247,8 @@ List all companies | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `expand` | string | No | Comma-separated fields to expand | -| `orderBy` | string | No | Sort field. Prefix with - for descending | -| `cursor` | string | No | Pagination cursor from previous response | +| `orderBy` | string | No | Sort field\(s\), comma-separated; append " desc" for descending \(e.g. created_at desc\) | +| `cursor` | string | No | Pagination cursor: the nextCursor output of the previous page | #### Output @@ -234,8 +266,11 @@ List all companies | ↳ `parent_legal_entity_id` | string | Parent legal entity ID | | ↳ `legal_entities_id` | json | Array of legal entity IDs | | ↳ `physical_address` | json | Physical address of the holding entity | +| ↳ `parent_legal_entity` | json | Expanded parent legal entity \(expand=parent_legal_entity\) | +| ↳ `legal_entities` | json | Expanded legal entities \(expand=legal_entities\) | | `totalCount` | number | Number of items returned | | `nextLink` | string | Link to next page of results | +| `nextCursor` | string | Cursor for the next page; pass it back as the cursor param \(null on the last page\) | | `__meta` | json | Metadata including redacted_fields | @@ -301,8 +336,8 @@ List all departments | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `expand` | string | No | Comma-separated fields to expand | -| `orderBy` | string | No | Sort field. Prefix with - for descending | -| `cursor` | string | No | Pagination cursor from previous response | +| `orderBy` | string | No | Sort field\(s\), comma-separated; append " desc" for descending \(e.g. created_at desc\) | +| `cursor` | string | No | Pagination cursor: the nextCursor output of the previous page | #### Output @@ -320,6 +355,7 @@ List all departments | ↳ `department_hierarchy` | json | Expanded department hierarchy | | `totalCount` | number | Number of items returned | | `nextLink` | string | Link to next page of results | +| `nextCursor` | string | Cursor for the next page; pass it back as the cursor param \(null on the last page\) | | `__meta` | json | Metadata including redacted_fields | @@ -426,8 +462,8 @@ List all teams | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `expand` | string | No | Comma-separated fields to expand | -| `orderBy` | string | No | Sort field. Prefix with - for descending | -| `cursor` | string | No | Pagination cursor from previous response | +| `orderBy` | string | No | Sort field\(s\), comma-separated; append " desc" for descending \(e.g. created_at desc\) | +| `cursor` | string | No | Pagination cursor: the nextCursor output of the previous page | #### Output @@ -442,6 +478,7 @@ List all teams | ↳ `parent` | json | Expanded parent team | | `totalCount` | number | Number of items returned | | `nextLink` | string | Link to next page of results | +| `nextCursor` | string | Cursor for the next page; pass it back as the cursor param \(null on the last page\) | | `__meta` | json | Metadata including redacted_fields | @@ -483,8 +520,8 @@ List all employment types | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `orderBy` | string | No | Sort field. Prefix with - for descending | -| `cursor` | string | No | Pagination cursor from previous response | +| `orderBy` | string | No | Sort field\(s\), comma-separated; append " desc" for descending \(e.g. created_at desc\) | +| `cursor` | string | No | Pagination cursor: the nextCursor output of the previous page | #### Output @@ -501,6 +538,7 @@ List all employment types | ↳ `amount_worked` | string | Amount worked \(PART-TIME, FULL-TIME, TEMPORARY\) | | `totalCount` | number | Number of items returned | | `nextLink` | string | Link to next page of results | +| `nextCursor` | string | Cursor for the next page; pass it back as the cursor param \(null on the last page\) | | `__meta` | json | Metadata including redacted_fields | @@ -543,8 +581,8 @@ List all titles | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `orderBy` | string | No | Sort field. Prefix with - for descending | -| `cursor` | string | No | Pagination cursor from previous response | +| `orderBy` | string | No | Sort field\(s\), comma-separated; append " desc" for descending \(e.g. created_at desc\) | +| `cursor` | string | No | Pagination cursor: the nextCursor output of the previous page | #### Output @@ -557,6 +595,7 @@ List all titles | ↳ `name` | string | Title name | | `totalCount` | number | Number of items returned | | `nextLink` | string | Link to next page of results | +| `nextCursor` | string | Cursor for the next page; pass it back as the cursor param \(null on the last page\) | | `__meta` | json | Metadata including redacted_fields | @@ -662,8 +701,8 @@ List all custom fields | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `orderBy` | string | No | Sort field. Prefix with - for descending | -| `cursor` | string | No | Pagination cursor from previous response | +| `orderBy` | string | No | Sort field\(s\), comma-separated; append " desc" for descending \(e.g. created_at desc\) | +| `cursor` | string | No | Pagination cursor: the nextCursor output of the previous page | #### Output @@ -677,8 +716,10 @@ List all custom fields | ↳ `description` | string | Field description | | ↳ `required` | boolean | Whether the field is required | | ↳ `type` | string | Field type \(TEXT, DATE, NUMBER, CURRENCY, etc.\) | +| ↳ `options` | json | Choice values for SELECT and RADIO fields \(null for other types\) | | `totalCount` | number | Number of items returned | | `nextLink` | string | Link to next page of results | +| `nextCursor` | string | Cursor for the next page; pass it back as the cursor param \(null on the last page\) | | `__meta` | json | Metadata including redacted_fields | @@ -693,8 +734,8 @@ List all job functions | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `orderBy` | string | No | Sort field. Prefix with - for descending | -| `cursor` | string | No | Pagination cursor from previous response | +| `orderBy` | string | No | Sort field\(s\), comma-separated; append " desc" for descending \(e.g. created_at desc\) | +| `cursor` | string | No | Pagination cursor: the nextCursor output of the previous page | #### Output @@ -707,6 +748,7 @@ List all job functions | ↳ `name` | string | Job function name | | `totalCount` | number | Number of items returned | | `nextLink` | string | Link to next page of results | +| `nextCursor` | string | Cursor for the next page; pass it back as the cursor param \(null on the last page\) | | `__meta` | json | Metadata including redacted_fields | @@ -745,8 +787,8 @@ List all work locations | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `orderBy` | string | No | Sort field. Prefix with - for descending | -| `cursor` | string | No | Pagination cursor from previous response | +| `orderBy` | string | No | Sort field\(s\), comma-separated; append " desc" for descending \(e.g. created_at desc\) | +| `cursor` | string | No | Pagination cursor: the nextCursor output of the previous page | #### Output @@ -760,6 +802,7 @@ List all work locations | ↳ `address` | json | Address object | | `totalCount` | number | Number of items returned | | `nextLink` | string | Link to next page of results | +| `nextCursor` | string | Cursor for the next page; pass it back as the cursor param \(null on the last page\) | | `__meta` | json | Metadata including redacted_fields | @@ -882,14 +925,17 @@ List all business partners | --------- | ---- | -------- | ----------- | | `filter` | string | No | Filter expression | | `expand` | string | No | Comma-separated fields to expand | -| `orderBy` | string | No | Sort field. Prefix with - for descending | -| `cursor` | string | No | Pagination cursor from previous response | +| `orderBy` | string | No | Sort field\(s\), comma-separated; append " desc" for descending \(e.g. created_at desc\) | +| `cursor` | string | No | Pagination cursor: the nextCursor output of the previous page | #### Output | Parameter | Type | Description | | --------- | ---- | ----------- | | `businessPartners` | array | List of businessPartners | +| ↳ `business_partner_group` | json | Expanded business partner group \(expand=business_partner_group\) | +| ↳ `worker` | json | Expanded worker \(expand=worker\) | +| ↳ `client_group` | json | Expanded client group \(expand=client_group\) | | ↳ `id` | string | Business partner ID | | ↳ `created_at` | string | Record creation date | | ↳ `updated_at` | string | Record update date | @@ -899,6 +945,7 @@ List all business partners | ↳ `client_group_member_count` | number | Client group member count | | `totalCount` | number | Number of items returned | | `nextLink` | string | Link to next page of results | +| `nextCursor` | string | Cursor for the next page; pass it back as the cursor param \(null on the last page\) | | `__meta` | json | Metadata including redacted_fields | @@ -927,6 +974,9 @@ Get a specific business partner by ID | `worker_id` | string | Worker ID | | `client_group_id` | string | Client group ID | | `client_group_member_count` | number | Client group member count | +| `business_partner_group` | json | Expanded business partner group \(expand=business_partner_group\) | +| `worker` | json | Expanded worker \(expand=worker\) | +| `client_group` | json | Expanded client group \(expand=client_group\) | | `__meta` | json | Metadata including redacted_fields | @@ -989,14 +1039,15 @@ List all business partner groups | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `expand` | string | No | Comma-separated fields to expand | -| `orderBy` | string | No | Sort field. Prefix with - for descending | -| `cursor` | string | No | Pagination cursor from previous response | +| `orderBy` | string | No | Sort field\(s\), comma-separated; append " desc" for descending \(e.g. created_at desc\) | +| `cursor` | string | No | Pagination cursor: the nextCursor output of the previous page | #### Output | Parameter | Type | Description | | --------- | ---- | ----------- | | `businessPartnerGroups` | array | List of businessPartnerGroups | +| ↳ `default_business_partner` | json | Expanded default business partner \(expand=default_business_partner\) | | ↳ `id` | string | Business partner group ID | | ↳ `created_at` | string | Record creation date | | ↳ `updated_at` | string | Record update date | @@ -1005,6 +1056,7 @@ List all business partner groups | ↳ `default_business_partner_id` | string | Default business partner ID | | `totalCount` | number | Number of items returned | | `nextLink` | string | Link to next page of results | +| `nextCursor` | string | Cursor for the next page; pass it back as the cursor param \(null on the last page\) | | `__meta` | json | Metadata including redacted_fields | @@ -1032,6 +1084,7 @@ Get a specific business partner group by ID | `name` | string | Name | | `domain` | string | Domain | | `default_business_partner_id` | string | Default partner ID | +| `default_business_partner` | json | Expanded default business partner \(expand=default_business_partner\) | | `__meta` | json | Metadata including redacted_fields | @@ -1094,7 +1147,8 @@ List all supergroups | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `filter` | string | No | Filter expression \(filterable fields: app_owner_id, group_type\) | -| `orderBy` | string | No | Sort field. Prefix with - for descending | +| `orderBy` | string | No | Sort field\(s\), comma-separated; append " desc" for descending \(e.g. created_at desc\) | +| `cursor` | string | No | Pagination cursor: the nextCursor output of the previous page | #### Output @@ -1122,6 +1176,7 @@ List all supergroups | ↳ `ignore_prov_group_matching` | boolean | Whether to ignore provisioning group matching | | `totalCount` | number | Number of items returned | | `nextLink` | string | Link to next page of results | +| `nextCursor` | string | Cursor for the next page; pass it back as the cursor param \(null on the last page\) | | `__meta` | json | Metadata including redacted_fields | @@ -1177,7 +1232,8 @@ List members of a supergroup | --------- | ---- | -------- | ----------- | | `groupId` | string | Yes | Supergroup ID | | `expand` | string | No | Fields to expand \(e.g., worker\) | -| `orderBy` | string | No | Sort field | +| `orderBy` | string | No | Sort field\(s\), comma-separated; append " desc" for descending \(e.g. created_at desc\) | +| `cursor` | string | No | Pagination cursor: the nextCursor output of the previous page | #### Output @@ -1193,6 +1249,7 @@ List members of a supergroup | ↳ `worker` | json | Expanded worker object | | `totalCount` | number | Number of members returned | | `nextLink` | string | Next page link | +| `nextCursor` | string | Cursor for the next page; pass it back as the cursor param \(null on the last page\) | | `__meta` | json | Metadata including redacted_fields | @@ -1209,7 +1266,8 @@ List inclusion members of a supergroup | --------- | ---- | -------- | ----------- | | `groupId` | string | Yes | Supergroup ID | | `expand` | string | No | Fields to expand \(e.g., worker\) | -| `orderBy` | string | No | Sort field | +| `orderBy` | string | No | Sort field\(s\), comma-separated; append " desc" for descending \(e.g. created_at desc\) | +| `cursor` | string | No | Pagination cursor: the nextCursor output of the previous page | #### Output @@ -1225,6 +1283,7 @@ List inclusion members of a supergroup | ↳ `worker` | json | Expanded worker object | | `totalCount` | number | Number of members returned | | `nextLink` | string | Next page link | +| `nextCursor` | string | Cursor for the next page; pass it back as the cursor param \(null on the last page\) | | `__meta` | json | Metadata including redacted_fields | @@ -1241,7 +1300,8 @@ List exclusion members of a supergroup | --------- | ---- | -------- | ----------- | | `groupId` | string | Yes | Supergroup ID | | `expand` | string | No | Fields to expand \(e.g., worker\) | -| `orderBy` | string | No | Sort field | +| `orderBy` | string | No | Sort field\(s\), comma-separated; append " desc" for descending \(e.g. created_at desc\) | +| `cursor` | string | No | Pagination cursor: the nextCursor output of the previous page | #### Output @@ -1257,6 +1317,7 @@ List exclusion members of a supergroup | ↳ `worker` | json | Expanded worker object | | `totalCount` | number | Number of members returned | | `nextLink` | string | Next page link | +| `nextCursor` | string | Cursor for the next page; pass it back as the cursor param \(null on the last page\) | | `__meta` | json | Metadata including redacted_fields | @@ -1313,6 +1374,7 @@ List all custom objects | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | +| `cursor` | string | No | Pagination cursor: the nextCursor output of the previous page | #### Output @@ -1333,6 +1395,7 @@ List all custom objects | ↳ `enable_history` | boolean | Whether history is enabled | | `totalCount` | number | Number of items returned | | `nextLink` | string | Link to next page of results | +| `nextCursor` | string | Cursor for the next page; pass it back as the cursor param \(null on the last page\) | @@ -1467,6 +1530,7 @@ List all fields for a custom object | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `customObjectApiName` | string | Yes | Custom object API name | +| `cursor` | string | No | Pagination cursor: the nextCursor output of the previous page | #### Output @@ -1488,6 +1552,7 @@ List all fields for a custom object | ↳ `managed_package_install_id` | string | Package install ID | | `totalCount` | number | Number of fields returned | | `nextLink` | string | Next page link | +| `nextCursor` | string | Cursor for the next page; pass it back as the cursor param \(null on the last page\) | @@ -1643,6 +1708,7 @@ List all records for a custom object | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `customObjectApiName` | string | Yes | Custom object API name | +| `cursor` | string | No | Pagination cursor: the nextCursor output of the previous page | #### Output @@ -1661,6 +1727,7 @@ List all records for a custom object | ↳ `data` | json | Full record data including dynamic fields | | `totalCount` | number | Number of records returned | | `nextLink` | string | Next page link | +| `nextCursor` | string | Cursor for the next page; pass it back as the cursor param \(null on the last page\) | @@ -1737,7 +1804,9 @@ Query custom object records with filters | `customObjectApiName` | string | Yes | Custom object API name | | `query` | string | No | Query expression | | `limit` | number | No | Maximum number of records to return | -| `cursor` | string | No | Pagination cursor | +| `search` | string | No | Search record names or owners \(token/prefix match\); ANDed with query | +| `orderBy` | string | No | One field API name with optional asc or desc, e.g. name desc | +| `cursor` | string | No | Pagination cursor: the cursor output of the previous page | #### Output @@ -1771,7 +1840,7 @@ Create a custom object record | --------- | ---- | -------- | ----------- | | `customObjectApiName` | string | Yes | Custom object API name | | `externalId` | string | No | External ID for the record | -| `data` | json | Yes | Record data | +| `data` | json | Yes | Field values keyed by field API name \(e.g. \{"name": "License 4", "status__c": "ACTIVE"\}\) | #### Output @@ -1803,7 +1872,7 @@ Update a custom object record | `customObjectApiName` | string | Yes | Custom object API name | | `codrId` | string | Yes | Record ID | | `externalId` | string | No | External ID for the record | -| `data` | json | No | Updated record data | +| `data` | json | No | Field values to set, keyed by field API name \(e.g. \{"status__c": "FINAL"\}\) | #### Output @@ -1854,7 +1923,7 @@ Bulk create custom object records | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `customObjectApiName` | string | Yes | Custom object API name | -| `rowsToWrite` | json | Yes | Array of records to create \[\{external_id?, data\}\] | +| `rowsToWrite` | json | Yes | Array of flat records \[\{external_id?, <field_api_name>: value\}\] \(max 200\) | | `allOrNothing` | boolean | No | If true, fail entire batch on any error | #### Output @@ -1877,7 +1946,7 @@ Bulk update custom object records | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `customObjectApiName` | string | Yes | Custom object API name | -| `rowsToUpdate` | json | Yes | Array of records to update | +| `rowsToUpdate` | json | Yes | Array of flat records \[\{id, <field_api_name>: value\}\] \(max 200\) | | `allOrNothing` | boolean | No | If true, fail entire batch on any error | #### Output @@ -1900,14 +1969,15 @@ Bulk delete custom object records | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `customObjectApiName` | string | Yes | Custom object API name | -| `rowsToDelete` | json | Yes | Array of records to delete | +| `rowsToDelete` | json | Yes | Array of record ID strings to delete \(max 200\) | | `allOrNothing` | boolean | No | If true, fail entire batch on any error | #### Output | Parameter | Type | Description | | --------- | ---- | ----------- | -| `deleted` | boolean | Whether the bulk delete succeeded | +| `deleted` | boolean | Whether the bulk delete request succeeded | +| `deletedRecordIds` | array | IDs whose deletion was applied; may be partial or empty when records fail or await approval | @@ -2195,8 +2265,8 @@ List all custom settings | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `orderBy` | string | No | Sort field. Prefix with - for descending | -| `cursor` | string | No | Pagination cursor from previous response | +| `orderBy` | string | No | Sort field\(s\), comma-separated; append " desc" for descending \(e.g. created_at desc\) | +| `cursor` | string | No | Pagination cursor: the nextCursor output of the previous page | #### Output @@ -2209,12 +2279,13 @@ List all custom settings | ↳ `display_name` | string | Display name | | ↳ `api_name` | string | API name | | ↳ `data_type` | string | Data type | -| ↳ `secret_value` | string | Secret value | +| ↳ `secret_value` | string | Always null: Rippling never returns secret values | | ↳ `string_value` | string | String value | | ↳ `number_value` | number | Number value | | ↳ `boolean_value` | boolean | Boolean value | | `totalCount` | number | Number of items returned | | `nextLink` | string | Link to next page of results | +| `nextCursor` | string | Cursor for the next page; pass it back as the cursor param \(null on the last page\) | | `__meta` | json | Metadata including redacted_fields | @@ -2229,7 +2300,7 @@ Get a specific custom setting | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `id` | string | Yes | Resource ID | +| `id` | string | Yes | Custom setting API name \(api_name\) | #### Output @@ -2241,7 +2312,7 @@ Get a specific custom setting | `display_name` | string | Display name | | `api_name` | string | API name | | `data_type` | string | Data type | -| `secret_value` | string | Secret value | +| `secret_value` | string | Always null: Rippling never returns secret values | | `string_value` | string | String value | | `number_value` | number | Number value | | `boolean_value` | boolean | Boolean value | @@ -2277,7 +2348,7 @@ Create a new custom setting | `display_name` | string | Display name | | `api_name` | string | API name | | `data_type` | string | Data type | -| `secret_value` | string | Secret value | +| `secret_value` | string | Always null: Rippling never returns secret values | | `string_value` | string | String value | | `number_value` | number | Number value | | `boolean_value` | boolean | Boolean value | @@ -2294,7 +2365,7 @@ Update a custom setting | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `id` | string | Yes | Setting ID | +| `id` | string | Yes | Custom setting API name \(api_name\) | | `displayName` | string | No | Display name | | `apiName` | string | No | Unique API name | | `dataType` | string | No | Data type of the setting | @@ -2313,7 +2384,7 @@ Update a custom setting | `display_name` | string | Display name | | `api_name` | string | API name | | `data_type` | string | Data type | -| `secret_value` | string | Secret value | +| `secret_value` | string | Always null: Rippling never returns secret values | | `string_value` | string | String value | | `number_value` | number | Number value | | `boolean_value` | boolean | Boolean value | @@ -2330,7 +2401,7 @@ Delete a custom setting | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `id` | string | Yes | ID of the resource to delete | +| `id` | string | Yes | Custom setting API name \(api_name\) to delete | #### Output @@ -2350,6 +2421,7 @@ List all object categories | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | +| `cursor` | string | No | Pagination cursor: the nextCursor output of the previous page | #### Output @@ -2363,6 +2435,7 @@ List all object categories | ↳ `description` | string | Description | | `totalCount` | number | Number of items returned | | `nextLink` | string | Link to next page of results | +| `nextCursor` | string | Cursor for the next page; pass it back as the cursor param \(null on the last page\) | diff --git a/apps/docs/content/docs/integrations/sendgrid.mdx b/apps/docs/content/docs/integrations/sendgrid.mdx index 869ebd7997b..3114b13c0d1 100644 --- a/apps/docs/content/docs/integrations/sendgrid.mdx +++ b/apps/docs/content/docs/integrations/sendgrid.mdx @@ -331,7 +331,7 @@ Get a specific template by ID from SendGrid ### SendGrid List Templates -Get all email templates from SendGrid +List email templates from SendGrid. Returns legacy templates only unless generations includes dynamic @@ -339,7 +339,7 @@ Get all email templates from SendGrid | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `generations` | string | No | Filter by generation \(legacy, dynamic, or both\) | +| `generations` | string | No | Template generations to return: legacy, dynamic, or legacy,dynamic \(default when omitted: legacy only\) | | `pageSize` | number | No | Number of templates to return per page \(default: 20, max: 200\). When paginating with pageToken, pass the same pageSize used on the first request to keep page boundaries consistent. | | `pageToken` | string | No | Page token from a previous response \(nextPageToken\) to fetch the next page | diff --git a/apps/docs/content/docs/integrations/sentry.mdx b/apps/docs/content/docs/integrations/sentry.mdx index eb30a0e5a9a..c0c70bdeac2 100644 --- a/apps/docs/content/docs/integrations/sentry.mdx +++ b/apps/docs/content/docs/integrations/sentry.mdx @@ -30,9 +30,9 @@ List issues from Sentry for a specific organization and optionally a specific pr | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `organizationSlug` | string | Yes | The slug of the organization \(e.g., "my-org"\) | -| `projectSlug` | string | No | Filter issues by numeric project ID \(e.g., "4501234"\). This organization-scoped endpoint requires the numeric project ID, not the project slug. | +| `projectSlug` | string | No | Filter issues by project ID or slug \(e.g., "4501234" or "my-project"\) | | `query` | string | No | Search query to filter issues. Supports Sentry search syntax \(e.g., "is:unresolved", "level:error"\) | -| `statsPeriod` | string | No | Time window for the per-issue stats series \(e.g., "24h", "14d"\). Note: this controls the stats returned with each issue, not which issues are returned — use the query \(e.g., "age:-7d", "lastSeen:-24h"\) to filter results. | +| `statsPeriod` | string | No | Time window to search \(e.g., "24h", "14d"\); only issues with events in this window are returned. | | `cursor` | string | No | Pagination cursor for retrieving next page of results | | `limit` | number | No | Number of issues to return per page \(max: 100\) | | `status` | string | No | Filter by issue status: unresolved, resolved, or ignored. The legacy "ignored"/"muted" values map to Sentry's current "archived" search token. | @@ -84,6 +84,8 @@ List issues from Sentry for a specific organization and optionally a specific pr | `metadata` | object | Pagination metadata | | ↳ `nextCursor` | string | Cursor for the next page of results \(if available\) | | ↳ `hasMore` | boolean | Whether there are more results available | +| `nextCursor` | string | Cursor for the next page of results; pass it as the Pagination Cursor to fetch that page | +| `hasMore` | boolean | Whether there are more results available | @@ -159,6 +161,7 @@ Update a Sentry issue by changing its status, assignment, bookmark state, or oth | `organizationSlug` | string | Yes | The slug of the organization \(e.g., "my-org"\) | | `issueId` | string | Yes | The unique ID of the issue to update \(e.g., "12345"\) | | `status` | string | No | New status for the issue: resolved, unresolved, ignored, or resolvedInNextRelease | +| `priority` | string | No | New priority for the issue: low, medium, or high | | `assignedTo` | string | No | Actor to assign the issue to, in the form "user:<id>" or "team:<id>" \(a bare username or email is also accepted\). Use an empty string to unassign. | | `isBookmarked` | boolean | No | Whether to bookmark the issue | | `isSubscribed` | boolean | No | Whether to subscribe to issue updates | @@ -213,7 +216,7 @@ List all projects in a Sentry organization. Returns project details including na | ↳ `isBookmarked` | boolean | Whether the project is bookmarked | | ↳ `isMember` | boolean | Whether the user is a member of the project | | ↳ `features` | array | Enabled features for the project | -| ↳ `organization` | object | Organization information | +| ↳ `organization` | object | Organization information \(not returned by this endpoint; use Get Project\) | | ↳ `id` | string | Organization ID | | ↳ `slug` | string | Organization slug | | ↳ `name` | string | Organization name | @@ -221,11 +224,13 @@ List all projects in a Sentry organization. Returns project details including na | ↳ `id` | string | Team ID | | ↳ `name` | string | Team name | | ↳ `slug` | string | Team slug | -| ↳ `status` | string | Project status | -| ↳ `isPublic` | boolean | Whether the project is publicly visible | +| ↳ `status` | string | Project status \(not returned by this endpoint; use Get Project\) | +| ↳ `isPublic` | boolean | Whether the project is publicly visible \(not returned by this endpoint; use Get Project\) | | `metadata` | object | Pagination metadata | | ↳ `nextCursor` | string | Cursor for the next page of results \(if available\) | | ↳ `hasMore` | boolean | Whether there are more results available | +| `nextCursor` | string | Cursor for the next page of results; pass it as the Pagination Cursor to fetch that page | +| `hasMore` | boolean | Whether there are more results available | @@ -315,7 +320,7 @@ Create a new Sentry project in an organization. Requires a team to associate the | ↳ `hasAccess` | boolean | Whether the user has access | | ↳ `features` | array | Enabled features | | ↳ `firstEvent` | string | First event timestamp | -| ↳ `organization` | object | Organization information | +| ↳ `organization` | object | Organization information \(not returned by this endpoint; use Get Project\) | | ↳ `id` | string | Organization ID | | ↳ `slug` | string | Organization slug | | ↳ `name` | string | Organization name | @@ -327,9 +332,9 @@ Create a new Sentry project in an organization. Requires a team to associate the | ↳ `id` | string | Team ID | | ↳ `name` | string | Team name | | ↳ `slug` | string | Team slug | -| ↳ `status` | string | Project status | -| ↳ `color` | string | Project color code | -| ↳ `isPublic` | boolean | Whether the project is public | +| ↳ `status` | string | Project status \(not returned by this endpoint; use Get Project\) | +| ↳ `color` | string | Project color code \(not returned by this endpoint; use Get Project\) | +| ↳ `isPublic` | boolean | Whether the project is public \(not returned by this endpoint; use Get Project\) | @@ -388,7 +393,7 @@ List events from a Sentry project. Can be filtered by issue ID, query, or time p | `issueId` | string | No | Filter events by a specific issue ID \(e.g., "12345"\) | | `query` | string | No | Search query to filter events. Only applied when an Issue ID is provided \(the issue events endpoint\); the project events endpoint ignores it. Supports Sentry search syntax \(e.g., "user.email:*@example.com"\) | | `cursor` | string | No | Pagination cursor for retrieving next page of results | -| `limit` | number | No | Number of events to return per page \(max: 100\) | +| `limit` | number | No | Number of events to return per page \(max: 10, because full event bodies are requested\) | | `statsPeriod` | string | No | Time period to query \(e.g., "24h", "7d", "14d"\). Cannot be combined with absolute start/end. | #### Output @@ -434,6 +439,8 @@ List events from a Sentry project. Can be filtered by issue ID, query, or time p | `metadata` | object | Pagination metadata | | ↳ `nextCursor` | string | Cursor for the next page of results \(if available\) | | ↳ `hasMore` | boolean | Whether there are more results available | +| `nextCursor` | string | Cursor for the next page of results; pass it as the Pagination Cursor to fetch that page | +| `hasMore` | boolean | Whether there are more results available | @@ -505,7 +512,7 @@ List releases for a Sentry organization or project. Returns release details incl | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `organizationSlug` | string | Yes | The slug of the organization \(e.g., "my-org"\) | -| `projectSlug` | string | No | Filter releases by numeric project ID \(e.g., "4501234"\). This organization-scoped endpoint requires the numeric project ID, not the project slug. | +| `projectSlug` | string | No | Filter releases by project ID or slug \(e.g., "4501234" or "my-project"\) | | `query` | string | No | Search query to filter releases \(e.g., "1.0" to match version patterns\) | | `cursor` | string | No | Pagination cursor for retrieving next page of results | | `limit` | number | No | Number of releases to return per page \(default: 25, max: 100\) | @@ -558,6 +565,8 @@ List releases for a Sentry organization or project. Returns release details incl | `metadata` | object | Pagination metadata | | ↳ `nextCursor` | string | Cursor for the next page of results \(if available\) | | ↳ `hasMore` | boolean | Whether there are more results available | +| `nextCursor` | string | Cursor for the next page of results; pass it as the Pagination Cursor to fetch that page | +| `hasMore` | boolean | Whether there are more results available | @@ -696,6 +705,8 @@ List all teams in a Sentry organization. Useful for discovering the team slug re | `metadata` | object | Pagination metadata | | ↳ `nextCursor` | string | Cursor for the next page of results \(if available\) | | ↳ `hasMore` | boolean | Whether there are more results available | +| `nextCursor` | string | Cursor for the next page of results; pass it as the Pagination Cursor to fetch that page | +| `hasMore` | boolean | Whether there are more results available | diff --git a/apps/docs/content/docs/integrations/shopify.mdx b/apps/docs/content/docs/integrations/shopify.mdx index e110438e1f4..7d007722288 100644 --- a/apps/docs/content/docs/integrations/shopify.mdx +++ b/apps/docs/content/docs/integrations/shopify.mdx @@ -1388,7 +1388,7 @@ List inventory locations from your Shopify store. Use this to find location IDs | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `reverse` | boolean | No | Reverse the result sort order \(default false\) | -| `sortKey` | string | No | Sort results by ID, NAME, RELEVANCE \(default Shopify ordering\) | +| `sortKey` | string | No | Sort results by CREATED_AT, ID, NAME, RELEVANCE \(default Shopify ordering\) | | `query` | string | No | Shopify location search query, e.g. name:Warehouse | | `includeLegacy` | boolean | No | Include legacy fulfillment-service locations \(default false\) | | `shopDomain` | string | No | Your Shopify store domain \(e.g., mystore.myshopify.com\) | diff --git a/apps/docs/content/docs/integrations/slack.mdx b/apps/docs/content/docs/integrations/slack.mdx index ee31effedea..a7260e75879 100644 --- a/apps/docs/content/docs/integrations/slack.mdx +++ b/apps/docs/content/docs/integrations/slack.mdx @@ -616,7 +616,7 @@ Fetch every message in a Slack thread, automatically following pagination across | `inclusive` | boolean | No | Include messages with timestamps matching oldest or latest \(default: false\) | | `limit` | number | No | Messages to request per page \(default: 200, max: 999\) | | `cursor` | string | No | Pagination cursor from a previous response.nextCursor to resume from | -| `maxPages` | number | No | Maximum number of pages to fetch before stopping \(default: 10\) | +| `maxPages` | number | No | Maximum number of pages to fetch before stopping \(default: 10, max: 50\) | #### Output @@ -812,7 +812,7 @@ Fetch message history from a Slack channel, automatically following pagination. | `inclusive` | boolean | No | Include messages with timestamps matching oldest or latest \(default: false\) | | `limit` | number | No | Messages to request per page \(default: 200, max: 999\) | | `cursor` | string | No | Pagination cursor from a previous response.nextCursor to resume from | -| `maxPages` | number | No | Maximum number of pages to fetch before stopping \(default: 10\) | +| `maxPages` | number | No | Maximum number of pages to fetch before stopping \(default: 10, max: 50\) | #### Output @@ -960,7 +960,7 @@ Set the title of a Slack assistant thread (shown in the AI app thread header). ### Slack Set Suggested Prompts -Set the clickable suggested prompts shown in a Slack assistant thread (the prompt chips in an AI app). +Set the clickable suggested prompts shown in a Slack assistant thread (the prompt chips in an AI app). For apps on the legacy assistant experience (assistant_view) only. Slack silently fails this call for agent apps (agent_view); use Set Agent Suggested Prompts instead. @@ -1023,7 +1023,7 @@ Create or update the state of a Slack agent session associated with a thread. | `authMethod` | string | No | Slack authentication method | | `botToken` | string | No | Custom Slack bot token | | `channel` | string | Yes | Channel ID containing the agent session thread | -| `threadTs` | string | Yes | Timestamp of the thread associated with the agent session | +| `threadTs` | string | No | Timestamp of the thread root message the session is scoped to. Required for thread-based sessions in regular channels and DMs; omit for session channels. | | `status` | string | Yes | Agent session state: active, processing, suspended, or closed | | `title` | string | No | Title used when creating the agent session, up to 200 characters | | `initiatorUserId` | string | No | Slack user ID that initiated the session | @@ -1055,7 +1055,7 @@ Rename the Slack agent session associated with a thread. | `authMethod` | string | No | Slack authentication method | | `botToken` | string | No | Custom Slack bot token | | `channel` | string | Yes | Channel ID containing the agent session thread | -| `threadTs` | string | Yes | Timestamp of the thread associated with the agent session | +| `threadTs` | string | No | Timestamp of the thread root message the session is scoped to. Required for thread-based sessions in regular channels and DMs; omit for session channels. | | `title` | string | Yes | New agent session title, from 1 to 200 characters | #### Output @@ -2081,7 +2081,7 @@ Open a modal view in Slack using a trigger_id from an interaction payload. Used | --------- | ---- | -------- | ----------- | | `authMethod` | string | No | Authentication method: oauth or bot_token | | `botToken` | string | No | Bot token for Custom Bot | -| `triggerId` | string | Yes | Exchange a trigger to post to the user. Obtained from an interaction payload \(e.g., slash command, button click\) | +| `triggerId` | string | No | Exchange a trigger to post to the user. Obtained from an interaction payload \(e.g., slash command, button click\). Provide this or interactivityPointer. | | `interactivityPointer` | string | No | Alternative to trigger_id for posting to user | | `view` | json | Yes | A view payload object defining the modal. Must include type \("modal"\), title, and blocks array | @@ -2182,7 +2182,7 @@ Push a new view onto an existing modal stack in Slack. Limited to 2 additional v | --------- | ---- | -------- | ----------- | | `authMethod` | string | No | Authentication method: oauth or bot_token | | `botToken` | string | No | Bot token for Custom Bot | -| `triggerId` | string | Yes | Exchange a trigger to post to the user. Obtained from an interaction payload \(e.g., button click within an existing modal\) | +| `triggerId` | string | No | Exchange a trigger to post to the user. Obtained from an interaction payload \(e.g., button click within an existing modal\). Provide this or interactivityPointer. | | `interactivityPointer` | string | No | Alternative to trigger_id for posting to user | | `view` | json | Yes | A view payload object defining the modal to push. Must include type \("modal"\), title, and blocks array | @@ -2584,8 +2584,8 @@ Change access for users or regular channels on a standalone canvas. For sharing, | --------- | ---- | -------- | ----------- | | `canvas_id` | string | Yes | Canvas ID | | `access_level` | string | Yes | Access Level Options: read, write, owner. | -| `user_ids` | json | No | User IDs | -| `channel_ids` | json | No | Channel IDs | +| `user_ids` | json | No | Up to 20 Slack user IDs, as a JSON array or a comma-separated string. Omit channel_ids. | +| `channel_ids` | json | No | Up to 20 Slack channel IDs, as a JSON array or a comma-separated string. Omit user_ids. | #### Output @@ -2606,8 +2606,8 @@ Remove user or regular-channel access to a standalone canvas. Channel-granted ac | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `canvas_id` | string | Yes | Canvas ID | -| `user_ids` | json | No | User IDs | -| `channel_ids` | json | No | Channel IDs | +| `user_ids` | json | No | One Slack user ID to remove, as \["U123"\] or U123. | +| `channel_ids` | json | No | One Slack channel ID to remove, as \["C123"\] or C123. | #### Output @@ -2701,7 +2701,7 @@ Remove a user from a Slack conversation, subject to workspace permissions. ### Slack Unarchive Conversation -Restore an archived Slack channel. +Restore an archived Slack channel. Slack does not currently let bot tokens unarchive conversations, so this fails with the Sim app or a custom bot until Slack lifts that limit. @@ -2721,7 +2721,7 @@ Restore an archived Slack channel. ### Slack Close Conversation -Close a direct message or group direct message for the authenticated identity. +Close a direct message or group direct message for the authenticated identity. The Sim app can close 1:1 direct messages only; closing a group direct message needs a custom bot with the mpim:write scope. @@ -2770,7 +2770,7 @@ Open a DM or group DM with 1–8 user IDs, or resume a conversation by ID. Suppl | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `users` | json | No | User IDs | +| `users` | json | No | 1 to 8 Slack user IDs, as a JSON array or a comma-separated string. Omit channel. | | `channel` | string | No | Conversation ID | | `prevent_creation` | boolean | No | Only Resume Existing Conversation | | `return_im` | boolean | No | Include Conversation Details | @@ -3443,8 +3443,8 @@ Create a Slack user group with a mention handle and default channels. Requires a | `name` | string | Yes | Name | | `handle` | string | No | Mention Handle | | `description` | string | No | Description | -| `channels` | json | No | Default Channel IDs | -| `additional_channels` | json | No | Additional Channel IDs | +| `channels` | json | No | Default channel IDs for the group, as a JSON array \(\["C123"\]\) or a comma-separated string \(C123,C456\) | +| `additional_channels` | json | No | Channel IDs where members can add group members, as a JSON array or a comma-separated string | | `enable_section` | boolean | No | Show as Sidebar Section | | `include_count` | boolean | No | Include Member Count | | `team_id` | string | No | Workspace ID | @@ -3485,8 +3485,8 @@ Change a Slack user group’s name, handle, description, or default channels. Re | `name` | string | No | Name | | `handle` | string | No | Mention Handle | | `description` | string | No | Description | -| `channels` | json | No | Default Channel IDs | -| `additional_channels` | json | No | Additional Channel IDs | +| `channels` | json | No | Default channel IDs for the group, as a JSON array \(\["C123"\]\) or a comma-separated string \(C123,C456\) | +| `additional_channels` | json | No | Channel IDs where members can add group members, as a JSON array or a comma-separated string | | `enable_section` | boolean | No | Show as Sidebar Section | | `include_count` | boolean | No | Include Member Count | | `team_id` | string | No | Workspace ID | @@ -3656,7 +3656,7 @@ Replace all members of a Slack user group with the supplied user IDs. An empty l | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `usergroup` | string | Yes | User Group ID | -| `users` | json | Yes | User IDs | +| `users` | json | Yes | The complete member list as Slack user IDs, in a JSON array or a comma-separated string | | `additional_channels` | json | No | Additional Channel IDs | | `is_shared` | boolean | No | Shared Section | | `include_count` | boolean | No | Include Member Count | @@ -3722,7 +3722,7 @@ Read Do Not Disturb settings for the supplied user IDs. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `users` | json | Yes | User IDs | +| `users` | json | Yes | Slack user IDs to read, up to 50, as a JSON array \(\["U123","W456"\]\) or a comma-separated string \(U123,W456\) | | `team_id` | string | No | Workspace ID | #### Output diff --git a/apps/docs/content/docs/integrations/snowflake.mdx b/apps/docs/content/docs/integrations/snowflake.mdx index fbbbde187e7..bbb8877af4f 100644 --- a/apps/docs/content/docs/integrations/snowflake.mdx +++ b/apps/docs/content/docs/integrations/snowflake.mdx @@ -72,7 +72,7 @@ Execute one parameterized SQL statement through the Snowflake SQL API. | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -117,7 +117,7 @@ Check a running or completed statement and retrieve exactly one result partition | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -160,7 +160,7 @@ Cancel a running Snowflake SQL API statement. | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -209,7 +209,7 @@ Insert structured JSON rows using bound values. | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -259,7 +259,7 @@ Update matching rows with a bound MERGE statement without inserting new rows. | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -309,7 +309,7 @@ Update matching rows and insert unmatched rows with a bound MERGE statement. | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -358,7 +358,7 @@ Delete rows matching a required set of bound column filters. | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -414,7 +414,7 @@ Load files from an existing Snowflake stage with COPY INTO. | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -469,7 +469,7 @@ Export a Snowflake table to files in a stage with COPY INTO. | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -515,7 +515,7 @@ List the databases the credential can access. | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -562,7 +562,7 @@ List the schemas in a Snowflake database. | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -610,7 +610,7 @@ List the tables in a Snowflake schema. | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -656,7 +656,7 @@ List warehouses visible to the active Snowflake role. | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -701,7 +701,7 @@ Get the full details for a Snowflake virtual warehouse. | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -746,7 +746,7 @@ Resume a Snowflake virtual warehouse if it is suspended. | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -791,7 +791,7 @@ Suspend a Snowflake virtual warehouse. | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -839,7 +839,7 @@ Resize a Snowflake warehouse or change its auto-suspend and auto-resume settings | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -887,7 +887,7 @@ List tasks in a Snowflake schema. | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -934,7 +934,7 @@ Describe a Snowflake task. | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -982,7 +982,7 @@ Run a Snowflake task immediately, optionally retrying its last failed graph. | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -1029,7 +1029,7 @@ Resume a suspended Snowflake task so its schedule runs again. | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -1076,7 +1076,7 @@ Suspend a Snowflake task so its schedule stops triggering runs. | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -1126,7 +1126,7 @@ Query up to seven days of Snowflake task history, capped at 10000 rows. | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -1175,7 +1175,7 @@ Find one task history record by query ID within Snowflake’s seven-day window a | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -1221,7 +1221,7 @@ Cancel one running task query by query ID with SYSTEM$CANCEL_QUERY. Task runs al | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -1268,7 +1268,7 @@ Read a task query result with RESULT_SCAN during Snowflake’s 24-hour retention | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -1280,7 +1280,7 @@ Read a task query result with RESULT_SCAN during Snowflake’s 24-hour retention ### Snowflake List Query History -List queries that completed in the last seven days, optionally filtered. +List queries from the last seven days, optionally filtered. Queries still running are included unless an end time is set. @@ -1319,7 +1319,7 @@ List queries that completed in the last seven days, optionally filtered. | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -1370,7 +1370,7 @@ List staged-file load results for a table over the last fourteen days. | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -1420,7 +1420,7 @@ Inspect table and column metadata through Snowflake INFORMATION_SCHEMA views. | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -1470,7 +1470,7 @@ Call a stored procedure with explicitly typed Snowflake bindings. | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | @@ -1546,7 +1546,7 @@ Ask Snowflake Cortex Analyst a question in natural language against a semantic v | ↳ `currentPartition` | number | Zero-based partition returned | | ↳ `partitionCount` | number | Total partitions in the result set. Snowflake reports this only on the first partition, so pass it back to Get Statement when fetching later partitions | | ↳ `nextPartition` | number | Next partition to request with Get Statement, if one exists | -| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | +| ↳ `truncated` | boolean | Whether more result partitions remain to fetch with Get Statement, or null when Snowflake returned a metadata-less partition response and partitionCount was not supplied. Also true, with nextPartition null, when Snowflake returned code 391908 \(result set too large to return in full\); narrow the query or lower the row limit instead of fetching more partitions. Snowflake does not report when the requested row limit capped the result set, so that cap is never reflected here | | ↳ `dml` | object | Completed DML statistics, or null when the statement has no DML statistics | | ↳ `rowsInserted` | number | Rows inserted by the statement | | ↳ `rowsUpdated` | number | Rows updated by the statement | diff --git a/apps/docs/content/docs/integrations/telegram.mdx b/apps/docs/content/docs/integrations/telegram.mdx index 0701da3bf4f..25b20f19e5f 100644 --- a/apps/docs/content/docs/integrations/telegram.mdx +++ b/apps/docs/content/docs/integrations/telegram.mdx @@ -85,7 +85,7 @@ Delete messages in Telegram channels or chats through the Telegram Bot API. Requ | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `chatId` | string | Yes | Telegram chat ID \(numeric, can be negative for groups\) | -| `messageId` | string | Yes | Telegram message ID \(numeric identifier of the message to delete\) | +| `messageId` | number | Yes | Telegram message ID \(numeric identifier of the message to delete\) | #### Output @@ -119,16 +119,16 @@ Send photos to Telegram channels or users through the Telegram Bot API. | `message` | string | Success or error message | | `data` | object | Telegram message data including optional photo\(s\) | | ↳ `message_id` | number | Unique Telegram message identifier | -| ↳ `from` | object | Chat information | -| ↳ `id` | number | Chat ID | -| ↳ `is_bot` | boolean | Whether the chat is a bot or not | -| ↳ `first_name` | string | Chat username \(if available\) | -| ↳ `username` | string | Chat title \(for groups and channels\) | -| ↳ `chat` | object | Information about the bot that sent the message | -| ↳ `id` | number | Bot user ID | -| ↳ `first_name` | string | Bot first name | -| ↳ `username` | string | Bot username | -| ↳ `type` | string | Chat type \(private, group, supergroup, channel\) | +| ↳ `from` | object | Sender information | +| ↳ `id` | number | Sender user ID | +| ↳ `is_bot` | boolean | Whether the sender is a bot | +| ↳ `first_name` | string | Sender first name | +| ↳ `username` | string | Sender username, when available | +| ↳ `chat` | object | Recipient chat information | +| ↳ `id` | number | Recipient chat ID | +| ↳ `first_name` | string | Chat first name, for private chats | +| ↳ `username` | string | Chat username, when available | +| ↳ `type` | string | Chat type: private, group, supergroup, or channel | | ↳ `date` | number | Unix timestamp when message was sent | | ↳ `text` | string | Text content of the sent message \(if applicable\) | | ↳ `photo` | array | List of photos included in the message | @@ -173,7 +173,22 @@ Send videos to Telegram channels or users through the Telegram Bot API. | ↳ `type` | string | Type of chat \(private, group, supergroup, or channel\) | | ↳ `date` | number | Unix timestamp when the message was sent | | ↳ `text` | string | Text content of the sent message \(if applicable\) | -| ↳ `format` | object | Media format information \(for videos, GIFs, etc.\) | +| ↳ `video` | object | Video sent in the message | +| ↳ `file_id` | string | Video file ID, reusable to resend the file | +| ↳ `file_unique_id` | string | Unique video file identifier | +| ↳ `width` | number | Video width in pixels | +| ↳ `height` | number | Video height in pixels | +| ↳ `duration` | number | Duration of the video in seconds | +| ↳ `thumbnail` | object | Video thumbnail details | +| ↳ `file_id` | string | Thumbnail file ID | +| ↳ `file_unique_id` | string | Unique thumbnail file identifier | +| ↳ `file_size` | number | Thumbnail file size in bytes | +| ↳ `width` | number | Thumbnail width in pixels | +| ↳ `height` | number | Thumbnail height in pixels | +| ↳ `file_name` | string | Original video file name | +| ↳ `mime_type` | string | Video MIME type | +| ↳ `file_size` | number | Video file size in bytes | +| ↳ `format` | object | Legacy key: Telegram returns no format object, so this is never populated. Read video instead. | | ↳ `file_name` | string | Media file name | | ↳ `mime_type` | string | Media MIME type | | ↳ `duration` | number | Duration of media in seconds | @@ -293,7 +308,22 @@ Send animations (GIFs) to Telegram channels or users through the Telegram Bot AP | ↳ `type` | string | Type of chat \(private, group, supergroup, or channel\) | | ↳ `date` | number | Unix timestamp when the message was sent | | ↳ `text` | string | Text content of the sent message \(if applicable\) | -| ↳ `format` | object | Media format information \(for videos, GIFs, etc.\) | +| ↳ `animation` | object | Animation sent in the message | +| ↳ `file_id` | string | Animation file ID, reusable to resend the file | +| ↳ `file_unique_id` | string | Unique animation file identifier | +| ↳ `width` | number | Animation width in pixels | +| ↳ `height` | number | Animation height in pixels | +| ↳ `duration` | number | Duration of the animation in seconds | +| ↳ `thumbnail` | object | Animation thumbnail details | +| ↳ `file_id` | string | Thumbnail file ID | +| ↳ `file_unique_id` | string | Unique thumbnail file identifier | +| ↳ `file_size` | number | Thumbnail file size in bytes | +| ↳ `width` | number | Thumbnail width in pixels | +| ↳ `height` | number | Thumbnail height in pixels | +| ↳ `file_name` | string | Original animation file name | +| ↳ `mime_type` | string | Animation MIME type | +| ↳ `file_size` | number | Animation file size in bytes | +| ↳ `format` | object | Legacy key: Telegram returns no format object, so this is never populated. Read animation instead. | | ↳ `file_name` | string | Media file name | | ↳ `mime_type` | string | Media MIME type | | ↳ `duration` | number | Duration of media in seconds | @@ -518,7 +548,7 @@ Send a native poll to a Telegram chat through the Telegram Bot API. | --------- | ---- | -------- | ----------- | | `chatId` | string | Yes | Telegram chat ID \(numeric, can be negative for groups\) | | `question` | string | Yes | Poll question \(1-300 characters\) | -| `options` | json | Yes | List of 2-10 answer options as text strings | +| `options` | json | Yes | List of 1-12 answer options as text strings | | `isAnonymous` | boolean | No | Whether the poll needs to be anonymous \(defaults to true\) | | `allowsMultipleAnswers` | boolean | No | Whether the poll allows multiple answers | diff --git a/apps/docs/content/docs/integrations/twilio_sms.mdx b/apps/docs/content/docs/integrations/twilio_sms.mdx index ee940ea75b2..2014aa93ece 100644 --- a/apps/docs/content/docs/integrations/twilio_sms.mdx +++ b/apps/docs/content/docs/integrations/twilio_sms.mdx @@ -23,7 +23,7 @@ Send SMS messages. ### Twilio Send SMS -Send text messages to single or multiple recipients using the Twilio API. +Send a text message to one recipient using the Twilio API. Call once per recipient to reach several numbers. @@ -31,9 +31,10 @@ Send text messages to single or multiple recipients using the Twilio API. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `phoneNumbers` | string | Yes | Phone numbers to send the message to in E.164 format \(e.g., +15551234567\), separated by newlines | +| `phoneNumbers` | string | Yes | Recipient phone number in E.164 format \(e.g., +15551234567\) or a channel address \(e.g., whatsapp:+15551234567\). Only the first line is used. | | `message` | string | Yes | Message to send | -| `fromNumber` | string | Yes | Twilio phone number to send the message from in E.164 format \(e.g., +15551234567\) | +| `fromNumber` | string | No | Sender: a Twilio phone number in E.164 format \(e.g., +15551234567\), alphanumeric sender ID, short code, or channel address. Required unless a Messaging Service SID is given. | +| `messagingServiceSid` | string | No | Messaging Service SID \(MG...\). When set without a From number, Twilio picks the sender from the service sender pool. | #### Output diff --git a/apps/docs/content/docs/integrations/twilio_voice.mdx b/apps/docs/content/docs/integrations/twilio_voice.mdx index cc8d55d5ef8..acabacca60d 100644 --- a/apps/docs/content/docs/integrations/twilio_voice.mdx +++ b/apps/docs/content/docs/integrations/twilio_voice.mdx @@ -72,9 +72,10 @@ Retrieve a list of calls made to and from an account. | `to` | string | No | Filter by calls to this phone number in E.164 format \(e.g., +14155551234\) | | `from` | string | No | Filter by calls from this phone number in E.164 format \(e.g., +14155559876\) | | `status` | string | No | Filter by call status \(e.g., queued, ringing, in-progress, completed, busy, failed, no-answer, canceled\) | -| `startTimeAfter` | string | No | Filter calls that started on or after this date \(YYYY-MM-DD\) | -| `startTimeBefore` | string | No | Filter calls that started on or before this date \(YYYY-MM-DD\) | +| `startTimeAfter` | string | No | Filter calls that started on or after this date \(YYYY-MM-DD, UTC; inclusive\) | +| `startTimeBefore` | string | No | Filter calls that started before this date \(YYYY-MM-DD, UTC; exclusive\) | | `pageSize` | number | No | Number of records to return \(max 1000, default 50\) | +| `pageToken` | string | No | Page token from a previous result \(nextPageToken\) to fetch the next page | #### Output @@ -82,9 +83,10 @@ Retrieve a list of calls made to and from an account. | --------- | ---- | ----------- | | `success` | boolean | Whether the calls were successfully retrieved | | `calls` | array | Array of call objects | -| `total` | number | Total number of calls returned | +| `total` | number | Number of calls returned on this page | | `page` | number | Current page number | | `pageSize` | number | Number of calls per page | +| `nextPageToken` | string | Pass as pageToken to fetch the next page; null on the last page | | `error` | string | Error message if retrieval failed | diff --git a/apps/docs/content/docs/integrations/typeform.mdx b/apps/docs/content/docs/integrations/typeform.mdx index c7840979332..d1d5e7788f7 100644 --- a/apps/docs/content/docs/integrations/typeform.mdx +++ b/apps/docs/content/docs/integrations/typeform.mdx @@ -33,9 +33,10 @@ Retrieve form responses from Typeform | `pageSize` | number | No | Number of responses to retrieve \(e.g., 10, 25, 50\) | | `before` | string | No | Cursor token for fetching the next page of older responses | | `after` | string | No | Cursor token for fetching the next page of newer responses | -| `since` | string | No | Retrieve responses submitted after this date \(e.g., "2024-01-01T00:00:00Z"\) | -| `until` | string | No | Retrieve responses submitted before this date \(e.g., "2024-12-31T23:59:59Z"\) | -| `completed` | string | No | Filter by completion status \(e.g., "true", "false", "all"\) | +| `since` | string | No | Retrieve responses submitted on or after this date \(e.g., "2024-01-01T00:00:00Z"\) | +| `until` | string | No | Retrieve responses submitted on or before this date \(e.g., "2024-12-31T23:59:59Z"\) | +| `completed` | string | No | Filter by completion status: "true" \(submitted only\), "false" \(started but not submitted\), or "all" \(no filter sent, so Typeform returns submitted responses only\). Ignored when responseType is set | +| `responseType` | string | No | Comma-separated response types to return \(e.g., "partial,completed"\). Typeform returns only "completed" when omitted. Takes precedence over completed | #### Output @@ -183,7 +184,7 @@ Create a new form with fields and settings | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `title` | string | Yes | Form title | -| `type` | string | No | Form type \(default: "form"\). Options: "form", "quiz" | +| `type` | string | No | Form type: "quiz", "classification", "score", "branching", "classification_branching", or "score_branching" \(Typeform default: "quiz"\) | | `workspaceId` | string | No | Workspace ID to create the form in \(e.g., "ws_abc123"\) | | `fields` | json | No | Array of field objects defining the form structure. Each field needs: type, title, and optional properties/validations | | `settings` | json | No | Form settings object \(language, progress_bar, etc.\) | @@ -217,7 +218,7 @@ Update an existing form using JSON Patch operations | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `formId` | string | Yes | Form unique identifier to update \(e.g., "abc123XYZ"\) | -| `operations` | json | Yes | Array of JSON Patch operations \(RFC 6902\). Each operation needs: op \(add/remove/replace\), path, and value \(for add/replace\) | +| `operations` | json | Yes | Array of JSON Patch operations \(RFC 6902\), each with op, path, and value. Typeform accepts only these paths: /title, /settings/is_public, /settings/meta, /settings/google_analytics, /settings/google_tag_manager, /settings/facebook_pixel, /settings/enrichment_in_renderer, /settings/email_consent_notifications_config, /theme, /workspace | #### Output diff --git a/apps/docs/content/docs/integrations/webflow.mdx b/apps/docs/content/docs/integrations/webflow.mdx index f557bf5a8b2..af64967c48b 100644 --- a/apps/docs/content/docs/integrations/webflow.mdx +++ b/apps/docs/content/docs/integrations/webflow.mdx @@ -48,10 +48,10 @@ List items from a Webflow CMS collection | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `siteId` | string | Yes | ID of the Webflow site \(e.g., "580e63e98c9a982ac9b8b741"\) | +| `siteId` | string | No | ID of the Webflow site \(e.g., "580e63e98c9a982ac9b8b741"\). Not sent to Webflow; item requests are scoped by collection. | | `collectionId` | string | Yes | ID of the collection \(e.g., "580e63fc8c9a982ac9b8b745"\) | | `offset` | number | No | Offset for pagination \(e.g., 0, 100, 200\) | -| `limit` | number | No | Maximum number of items to return \(e.g., 10, 50, 100; default: 100\) | +| `limit` | number | No | Maximum number of items to return, max 100 \(e.g., 10, 50, 100; default: 100\) | #### Output @@ -84,7 +84,7 @@ Get a single item from a Webflow CMS collection | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `siteId` | string | Yes | ID of the Webflow site \(e.g., "580e63e98c9a982ac9b8b741"\) | +| `siteId` | string | No | ID of the Webflow site \(e.g., "580e63e98c9a982ac9b8b741"\). Not sent to Webflow; item requests are scoped by collection. | | `collectionId` | string | Yes | ID of the collection \(e.g., "580e63fc8c9a982ac9b8b745"\) | | `itemId` | string | Yes | ID of the item to retrieve \(e.g., "580e64008c9a982ac9b8b754"\) | @@ -92,8 +92,17 @@ Get a single item from a Webflow CMS collection | Parameter | Type | Description | | --------- | ---- | ----------- | -| `item` | json | The retrieved item object | -| `metadata` | json | Metadata about the retrieved item | +| `item` | object | The retrieved item object | +| ↳ `id` | string | Unique item ID | +| ↳ `cmsLocaleId` | string | CMS locale ID | +| ↳ `lastPublished` | string | Last published date \(ISO 8601\) | +| ↳ `lastUpdated` | string | Last updated date \(ISO 8601\) | +| ↳ `createdOn` | string | Creation date \(ISO 8601\) | +| ↳ `isArchived` | boolean | Whether the item is archived | +| ↳ `isDraft` | boolean | Whether the item is a draft | +| ↳ `fieldData` | object | Collection-specific field data \(varies by collection schema\) | +| `metadata` | object | Metadata about the retrieved item | +| ↳ `itemId` | string | ID of the retrieved item | @@ -107,7 +116,7 @@ Create a new item in a Webflow CMS collection | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `siteId` | string | Yes | ID of the Webflow site \(e.g., "580e63e98c9a982ac9b8b741"\) | +| `siteId` | string | No | ID of the Webflow site \(e.g., "580e63e98c9a982ac9b8b741"\). Not sent to Webflow; item requests are scoped by collection. | | `collectionId` | string | Yes | ID of the collection \(e.g., "580e63fc8c9a982ac9b8b745"\) | | `fieldData` | json | Yes | Field data for the new item as a JSON object. Keys should match collection field names. | @@ -115,8 +124,17 @@ Create a new item in a Webflow CMS collection | Parameter | Type | Description | | --------- | ---- | ----------- | -| `item` | json | The created item object | -| `metadata` | json | Metadata about the created item | +| `item` | object | The created item object | +| ↳ `id` | string | Unique item ID | +| ↳ `cmsLocaleId` | string | CMS locale ID | +| ↳ `lastPublished` | string | Last published date \(ISO 8601\) | +| ↳ `lastUpdated` | string | Last updated date \(ISO 8601\) | +| ↳ `createdOn` | string | Creation date \(ISO 8601\) | +| ↳ `isArchived` | boolean | Whether the item is archived | +| ↳ `isDraft` | boolean | Whether the item is a draft | +| ↳ `fieldData` | object | Collection-specific field data \(varies by collection schema\) | +| `metadata` | object | Metadata about the created item | +| ↳ `itemId` | string | ID of the created item | @@ -130,7 +148,7 @@ Update an existing item in a Webflow CMS collection | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `siteId` | string | Yes | ID of the Webflow site \(e.g., "580e63e98c9a982ac9b8b741"\) | +| `siteId` | string | No | ID of the Webflow site \(e.g., "580e63e98c9a982ac9b8b741"\). Not sent to Webflow; item requests are scoped by collection. | | `collectionId` | string | Yes | ID of the collection \(e.g., "580e63fc8c9a982ac9b8b745"\) | | `itemId` | string | Yes | ID of the item to update \(e.g., "580e64008c9a982ac9b8b754"\) | | `fieldData` | json | Yes | Field data to update as a JSON object. Only include fields you want to change. | @@ -139,8 +157,17 @@ Update an existing item in a Webflow CMS collection | Parameter | Type | Description | | --------- | ---- | ----------- | -| `item` | json | The updated item object | -| `metadata` | json | Metadata about the updated item | +| `item` | object | The updated item object | +| ↳ `id` | string | Unique item ID | +| ↳ `cmsLocaleId` | string | CMS locale ID | +| ↳ `lastPublished` | string | Last published date \(ISO 8601\) | +| ↳ `lastUpdated` | string | Last updated date \(ISO 8601\) | +| ↳ `createdOn` | string | Creation date \(ISO 8601\) | +| ↳ `isArchived` | boolean | Whether the item is archived | +| ↳ `isDraft` | boolean | Whether the item is a draft | +| ↳ `fieldData` | object | Collection-specific field data \(varies by collection schema\) | +| `metadata` | object | Metadata about the updated item | +| ↳ `itemId` | string | ID of the updated item | @@ -154,7 +181,7 @@ Delete an item from a Webflow CMS collection | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `siteId` | string | Yes | ID of the Webflow site \(e.g., "580e63e98c9a982ac9b8b741"\) | +| `siteId` | string | No | ID of the Webflow site \(e.g., "580e63e98c9a982ac9b8b741"\). Not sent to Webflow; item requests are scoped by collection. | | `collectionId` | string | Yes | ID of the collection \(e.g., "580e63fc8c9a982ac9b8b745"\) | | `itemId` | string | Yes | ID of the item to delete \(e.g., "580e64008c9a982ac9b8b754"\) | @@ -163,7 +190,8 @@ Delete an item from a Webflow CMS collection | Parameter | Type | Description | | --------- | ---- | ----------- | | `success` | boolean | Whether the deletion was successful | -| `metadata` | json | Metadata about the deletion | +| `metadata` | object | Metadata about the deletion | +| ↳ `deleted` | boolean | Whether the item was deleted | diff --git a/apps/docs/content/docs/integrations/whatsapp.mdx b/apps/docs/content/docs/integrations/whatsapp.mdx index 73c43736eb5..7dc39c57741 100644 --- a/apps/docs/content/docs/integrations/whatsapp.mdx +++ b/apps/docs/content/docs/integrations/whatsapp.mdx @@ -153,39 +153,16 @@ Send an image, document, video, audio, or sticker message. Accepts an uploaded f | Parameter | Type | Description | | --------- | ---- | ----------- | -| `success` | boolean | Send success status | -| `messageId` | string | WhatsApp message identifier | -| `messageStatus` | string | Pacing status from the send API: accepted, held_for_quality_assessment, or paused. Acceptance is not delivery — use the webhook trigger for delivery status. | -| `messagingProduct` | string | Messaging product returned by the send API | -| `inputPhoneNumber` | string | Recipient phone number echoed by the send API | -| `whatsappUserId` | string | Resolved WhatsApp user ID for the recipient | -| `contacts` | array | Recipient contacts returned by the send API \(each item includes input and wa_id\) | -| `mediaId` | string | Media asset ID from Upload Media, or the ID downloaded by Download Media | -| `file` | file | Media downloaded by Download Media, stored as a workflow file | -| `fileName` | string | Name of the file uploaded by Upload Media | -| `mimeType` | string | MIME type of the uploaded or downloaded media | -| `size` | number | Size in bytes of the file uploaded by Upload Media | -| `fileSize` | number | Size in bytes of the downloaded media | -| `sha256` | string | SHA-256 hash WhatsApp reported for the downloaded media | -| `eventType` | string | Webhook classification such as incoming_message, message_status, or mixed | -| `from` | string | Sender phone number from the first incoming message | -| `recipientId` | string | Recipient phone number from the first status update in the batch | -| `phoneNumberId` | string | Business phone number ID from the first message or status item in the batch | -| `displayPhoneNumber` | string | Business display phone number from the first message or status item in the batch | -| `text` | string | Text body from the first incoming text message | -| `timestamp` | string | Timestamp from the first message or status item in the batch | -| `messageType` | string | Type of the first incoming message in the batch, such as text, image, or system | -| `mediaMimeType` | string | MIME type of the first incoming media message in the webhook batch | -| `caption` | string | Caption on the first incoming image, video, or document message | -| `status` | string | First outgoing message status in the batch, such as sent, delivered, or read | -| `contact` | json | First sender contact in the webhook batch \(wa_id, profile.name\) | -| `messages` | json | All incoming message objects from the webhook batch, flattened across entries/changes | -| `statuses` | json | All message status objects from the webhook batch, flattened across entries/changes | -| `webhookContacts` | json | All sender contact profiles from the webhook batch | -| `conversation` | json | Conversation metadata from the first status update in the batch \(id, expiration_timestamp, origin.type\) | -| `pricing` | json | Pricing metadata from the first status update in the batch \(billable, pricing_model, category\) | -| `raw` | json | Full structured WhatsApp webhook payload | -| `error` | string | Error information if sending fails | +| `success` | boolean | WhatsApp message send success status | +| `messageId` | string | Unique WhatsApp message identifier | +| `messageStatus` | string | Message pacing status when WhatsApp returns one: accepted, held_for_quality_assessment, or paused. Acceptance is not delivery — subscribe to the webhook trigger for delivery status. | +| `messagingProduct` | string | Messaging product returned by the API | +| `inputPhoneNumber` | string | Recipient phone number echoed back by WhatsApp | +| `whatsappUserId` | string | WhatsApp user ID resolved for the recipient | +| `contacts` | array | Recipient contact records returned by WhatsApp | +| ↳ `input` | string | Input phone number sent to the API | +| ↳ `wa_id` | string | WhatsApp user ID associated with the recipient | +| `mediaId` | string | Media ID WhatsApp assigned when a file was uploaded for this send \(reusable for 30 days\) | diff --git a/apps/docs/content/docs/integrations/wordpress.mdx b/apps/docs/content/docs/integrations/wordpress.mdx index 4c7213c1740..d6b75d6d359 100644 --- a/apps/docs/content/docs/integrations/wordpress.mdx +++ b/apps/docs/content/docs/integrations/wordpress.mdx @@ -51,6 +51,7 @@ Create a new blog post in WordPress.com | `tags` | string | No | Comma-separated tag IDs | | `featuredMedia` | number | No | Featured image media ID | | `slug` | string | No | URL slug for the post | +| `date` | string | No | Publish date in the site timezone, ISO 8601 \(e.g., 2026-12-01T09:00:00\). A future date with status publish schedules the post | #### Output @@ -94,6 +95,7 @@ Update an existing blog post in WordPress.com | `tags` | string | No | Comma-separated tag IDs | | `featuredMedia` | number | No | Featured image media ID | | `slug` | string | No | URL slug for the post | +| `date` | string | No | Publish date in the site timezone, ISO 8601 \(e.g., 2026-12-01T09:00:00\). A future date with status publish schedules the post | #### Output @@ -247,12 +249,13 @@ Create a new page in WordPress.com | `siteId` | string | Yes | WordPress.com site ID or domain \(e.g., 12345678 or mysite.wordpress.com\) | | `title` | string | Yes | Page title | | `content` | string | No | Page content \(HTML or plain text\) | -| `status` | string | No | Page status: publish, draft, pending, private | +| `status` | string | No | Page status: publish, draft, pending, private, or future | | `excerpt` | string | No | Page excerpt | | `parent` | number | No | Parent page ID for hierarchical pages | | `menuOrder` | number | No | Order in page menu | | `featuredMedia` | number | No | Featured image media ID | | `slug` | string | No | URL slug for the page | +| `date` | string | No | Publish date in the site timezone, ISO 8601 \(e.g., 2026-12-01T09:00:00\). A future date with status publish schedules the page | #### Output @@ -290,12 +293,13 @@ Update an existing page in WordPress.com | `pageId` | number | Yes | The ID of the page to update | | `title` | string | No | Page title | | `content` | string | No | Page content \(HTML or plain text\) | -| `status` | string | No | Page status: publish, draft, pending, private | +| `status` | string | No | Page status: publish, draft, pending, private, or future | | `excerpt` | string | No | Page excerpt | | `parent` | number | No | Parent page ID for hierarchical pages | | `menuOrder` | number | No | Order in page menu | | `featuredMedia` | number | No | Featured image media ID | | `slug` | string | No | URL slug for the page | +| `date` | string | No | Publish date in the site timezone, ISO 8601 \(e.g., 2026-12-01T09:00:00\). A future date with status publish schedules the page | #### Output @@ -631,10 +635,11 @@ List comments from WordPress.com with optional filters | `perPage` | number | No | Number of comments per request \(e.g., 10, 25, 50\). Default: 10, max: 100 | | `page` | number | No | Page number for pagination \(e.g., 1, 2, 3\) | | `postId` | number | No | Filter by post ID \(e.g., 123, 456\) | -| `status` | string | No | Filter by comment status: approved, hold, spam, trash | +| `status` | string | No | Filter by comment status: approve, hold, spam, trash, all | | `search` | string | No | Search term to filter comments \(e.g., "question", "feedback"\) | | `orderBy` | string | No | Order by field: date, id, parent | | `order` | string | No | Order direction: asc or desc | +| `context` | string | No | Response context: view \(default\) or edit. edit returns author_email but requires the moderate_comments capability | #### Output @@ -646,7 +651,7 @@ List comments from WordPress.com with optional filters | ↳ `parent` | number | Parent comment ID | | ↳ `author` | number | Author user ID | | ↳ `author_name` | string | Author display name | -| ↳ `author_email` | string | Author email | +| ↳ `author_email` | string | Author email \(edit context only\) | | ↳ `author_url` | string | Author URL | | ↳ `date` | string | Comment date | | ↳ `content` | object | Comment content object | @@ -1082,6 +1087,7 @@ List users from WordPress.com (requires admin privileges) | `search` | string | No | Search term to filter users \(e.g., "john", "admin"\) | | `roles` | string | No | Comma-separated role names to filter by \(e.g., "administrator,editor"\) | | `order` | string | No | Order direction: asc or desc | +| `context` | string | No | Response context: view \(default\) or edit. edit returns username, first_name, last_name, email and roles but requires the list_users capability | #### Output @@ -1089,16 +1095,16 @@ List users from WordPress.com (requires admin privileges) | --------- | ---- | ----------- | | `users` | array | List of users | | ↳ `id` | number | User ID | -| ↳ `username` | string | Username | +| ↳ `username` | string | Username \(edit context only\) | | ↳ `name` | string | Display name | -| ↳ `first_name` | string | First name | -| ↳ `last_name` | string | Last name | -| ↳ `email` | string | Email address | +| ↳ `first_name` | string | First name \(edit context only\) | +| ↳ `last_name` | string | Last name \(edit context only\) | +| ↳ `email` | string | Email address \(edit context only\) | | ↳ `url` | string | User website URL | | ↳ `description` | string | User bio | | ↳ `link` | string | Author archive URL | | ↳ `slug` | string | User slug | -| ↳ `roles` | array | User roles | +| ↳ `roles` | array | User roles \(edit context only\) | | ↳ `avatar_urls` | object | Avatar URLs at different sizes | | `total` | number | Total number of users | | `totalPages` | number | Total number of result pages | @@ -1124,16 +1130,16 @@ Get a specific user from WordPress.com by ID | --------- | ---- | ----------- | | `user` | object | The retrieved user | | ↳ `id` | number | User ID | -| ↳ `username` | string | Username | +| ↳ `username` | string | Username \(edit context only\) | | ↳ `name` | string | Display name | -| ↳ `first_name` | string | First name | -| ↳ `last_name` | string | Last name | -| ↳ `email` | string | Email address | +| ↳ `first_name` | string | First name \(edit context only\) | +| ↳ `last_name` | string | Last name \(edit context only\) | +| ↳ `email` | string | Email address \(edit context only\) | | ↳ `url` | string | User website URL | | ↳ `description` | string | User bio | | ↳ `link` | string | Author archive URL | | ↳ `slug` | string | User slug | -| ↳ `roles` | array | User roles | +| ↳ `roles` | array | User roles \(edit context only\) | | ↳ `avatar_urls` | object | Avatar URLs at different sizes | @@ -1160,7 +1166,7 @@ Search across all content types in WordPress.com (posts, pages, media) | Parameter | Type | Description | | --------- | ---- | ----------- | | `results` | array | Search results | -| ↳ `id` | number | Content ID | +| ↳ `id` | number | Content ID \(a string slug for post-format results\) | | ↳ `title` | string | Content title | | ↳ `url` | string | Content URL | | ↳ `type` | string | Content type \(post, term, or post-format\) | diff --git a/apps/docs/content/docs/integrations/zoho_desk.mdx b/apps/docs/content/docs/integrations/zoho_desk.mdx index 260d52aaad7..1611239c25c 100644 --- a/apps/docs/content/docs/integrations/zoho_desk.mdx +++ b/apps/docs/content/docs/integrations/zoho_desk.mdx @@ -212,7 +212,7 @@ Update fields on an existing Zoho Desk ticket. | `language` | string | No | Ticket language | | `channel` | string | No | Ticket origin channel | | `webUrl` | string | No | URL to access the ticket | -| `sharedDepartments` | array | No | JSON array of shared departments and access privileges | +| `sharedDepartments` | array | No | Departments to share the ticket with, each as \{"id": departmentId, "type": "READ_ONLY" \| "READ_WRITE" \| "RESTRICTED_ACCESS"\}. JSON array. | | `teamId` | string | No | Team ID | | `secondaryContacts` | array | No | JSON array of secondary contact IDs | | `entitySkills` | array | No | JSON array of skill IDs in priority order; at most 10 | @@ -353,7 +353,7 @@ Add a comment to a Zoho Desk ticket. ### Zoho Desk List Threads -List conversation threads on a Zoho Desk ticket, newest first (Zoho sorts by sendDateTime descending by default). Returns a list projection: message bodies (content, summary, to/cc/bcc) come back only from Get Thread. +List conversation threads on a Zoho Desk ticket, newest first (Zoho sorts by sendDateTime descending by default). Returns a list projection: message bodies (content) come back only from Get Thread. @@ -588,7 +588,7 @@ Create Ticket in Zoho Desk. | `uploads` | array | No | File attachments in the ticket. For more information, refer to the Uploads section JSON array. | | `resolution` | string | No | Resolution notes of the ticket | | `webUrl` | string | No | URL to access the resource | -| `sharedDepartments` | array | No | List of departments to which the ticket could be shared, along with the access privileges for each department JSON array. | +| `sharedDepartments` | array | No | Departments to share the ticket with, each as \{"id": departmentId, "type": "READ_ONLY" \| "READ_WRITE" \| "RESTRICTED_ACCESS"\}. JSON array. | | `teamId` | string | No | ID of the team to assign the ticket | | `secondaryContacts` | array | No | List of Secondary contacts JSON array. | | `entitySkills` | array | No | JSON array of up to 10 skill IDs, ordered from highest to lowest assignment priority. | diff --git a/apps/docs/content/docs/integrations/zoom.mdx b/apps/docs/content/docs/integrations/zoom.mdx index 316e6e41fb3..6e571bd6852 100644 --- a/apps/docs/content/docs/integrations/zoom.mdx +++ b/apps/docs/content/docs/integrations/zoom.mdx @@ -267,7 +267,7 @@ Update an existing Zoom meeting | `joinBeforeHost` | boolean | No | Allow participants to join before host | | `muteUponEntry` | boolean | No | Mute participants upon entry | | `waitingRoom` | boolean | No | Enable waiting room | -| `autoRecording` | string | No | Auto recording setting: local, cloud, or none | +| `autoRecording` | string | No | Auto recording setting: local or cloud. Omit to leave unchanged; turning auto recording off is not supported on update. | #### Output @@ -289,8 +289,8 @@ Delete or cancel a Zoom meeting | --------- | ---- | -------- | ----------- | | `meetingId` | string | Yes | The meeting ID to delete \(e.g., "1234567890" or "85746065432"\) | | `occurrenceId` | string | No | Occurrence ID for deleting a specific occurrence of a recurring meeting | -| `scheduleForReminder` | boolean | No | Send cancellation reminder email to registrants | -| `cancelMeetingReminder` | boolean | No | Send cancellation email to registrants and alternative hosts | +| `scheduleForReminder` | boolean | No | Email the host and alternative hosts about the cancellation | +| `cancelMeetingReminder` | boolean | No | Email the meeting registrants about the cancellation | #### Output @@ -331,8 +331,8 @@ List all cloud recordings for a Zoom user | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `userId` | string | Yes | The user ID or email address \(e.g., "me", "user@example.com", or "AbcDefGHi"\). Use "me" for the authenticated user with OAuth credentials. With a Zoom server-to-server service account, "me" is not supported — provide the target user ID or email address. | -| `from` | string | No | Start date in yyyy-mm-dd format \(within last 6 months\) | -| `to` | string | No | End date in yyyy-mm-dd format | +| `from` | string | No | Start date in yyyy-mm-dd format \(UTC\). Zoom allows at most a one-month range and defaults to today when omitted | +| `to` | string | No | End date in yyyy-mm-dd format \(UTC\) | | `pageSize` | number | No | Number of records per page, 1-300 \(e.g., 30, 50, 100\) | | `nextPageToken` | string | No | Token for pagination to get next page of results | | `trash` | boolean | No | Set to true to list recordings from trash | @@ -432,7 +432,7 @@ Delete cloud recordings for a Zoom meeting | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `meetingId` | string | Yes | The meeting ID or meeting UUID \(e.g., "1234567890" or "4444AAABBBccccc12345=="\) | -| `recordingId` | string | No | Specific recording file ID to delete. If not provided, deletes all recordings. | +| `recordingId` | string | No | Specific recording file ID to delete. If not provided, deletes all recordings of the meeting, which needs the cloud_recording:delete:meeting_recording scope. | | `action` | string | No | Delete action: "trash" \(move to trash\) or "delete" \(permanently delete\) | #### Output diff --git a/apps/docs/scripts/compile-content.ts b/apps/docs/scripts/compile-content.ts index 7081d373098..1aa1b7b7cfd 100644 --- a/apps/docs/scripts/compile-content.ts +++ b/apps/docs/scripts/compile-content.ts @@ -211,7 +211,8 @@ async function generate() { const dates = lastModified() let compiled = 0 for (const file of await filesIn(CONTENT_ROOT)) { - const relative = path.relative(CONTENT_ROOT, file) + // Navigation keys and page URLs below assume `/`; on Windows path.relative returns `\`. + const relative = path.relative(CONTENT_ROOT, file).split(path.sep).join('/') if (relative.endsWith('meta.json')) { const parsed = metadataSchema.safeParse(JSON.parse(await readFile(file, 'utf8'))) if (!parsed.success) throw new Error(`${relative}: ${parsed.error.message}`) diff --git a/apps/pii/server.py b/apps/pii/server.py index 405d96e13bc..3f39210010a 100644 --- a/apps/pii/server.py +++ b/apps/pii/server.py @@ -8,9 +8,10 @@ import json import logging +import threading import time from collections.abc import AsyncIterator -from contextlib import asynccontextmanager +from contextlib import asynccontextmanager, nullcontext from typing import Any import regex as regex_module @@ -184,7 +185,6 @@ def build_analyzer() -> AnalyzerEngine: anonymizer: AnonymizerEngine NER_ENTITIES: frozenset _BLANK_ARTIFACTS: dict -_NLP_MAX_LENGTH: dict # Every entity the spaCy NER recognizers can actually produce. A request touching # any of these must run spaCy; a request naming only non-NER (regex/checksum) @@ -228,19 +228,22 @@ def _regex_only(entities: list[str] | None, score_threshold: float | None) -> bo ) -# spaCy refuses (error E088) any text longer than its model's `max_length`, so a -# longer text runs NER in windows of this many characters, following spaCy's -# guidance to segment long documents (it sizes NER memory at roughly 1GB per -# 100,000 characters of one text). +# A text longer than this runs NER in windows of this many characters, following +# spaCy's guidance to segment long documents. One NER pass costs memory that grows +# with the text's length (about 3GB for 900,000 characters), enough to get a worker +# OOM-killed, so no pass sees more than one window. That also keeps every pass under +# spaCy's `max_length`, which it refuses with error E088. NER_WINDOW_CHARS = 100_000 # How much of the previous window each window repeats. Far longer than any entity # spaCy tags, so an entity cut by one window's edge lies whole inside the next. NER_WINDOW_OVERLAP = 1_000 - -def _exceeds_nlp_length(text: str, language: str) -> bool: - limit = _NLP_MAX_LENGTH.get(language) - return limit is not None and len(text) > limit +# One NER pass (a batch, a short text, or one window) at a time per worker. FastAPI +# runs these sync endpoints on a threadpool, so without it a worker runs one pass per +# request in flight and their memory adds up until it is OOM-killed. A long text +# takes it per window, so it interleaves with other requests. Regex-only requests +# never take it. +_NER_SLOT = threading.Lock() def _window_entities( @@ -265,7 +268,7 @@ def _analyze_long( return_decision_process: bool = False, ad_hoc_recognizers: list[PatternRecognizer] | None = None, ) -> list[RecognizerResult]: - """Analyze a text longer than spaCy's `max_length`. + """Analyze a text longer than NER_WINDOW_CHARS. Pattern, checksum, and custom recognizers have no length limit, so they run once over the whole text (against blank NLP artifacts, as the regex-only path @@ -291,13 +294,15 @@ def _analyze_long( return results step = NER_WINDOW_CHARS - NER_WINDOW_OVERLAP for start in range(0, len(text), step): - for result in analyzer.analyze( - text=text[start : start + NER_WINDOW_CHARS], - language=language, - entities=window_entities, - score_threshold=score_threshold, - return_decision_process=return_decision_process, - ): + with _NER_SLOT: + window_results = analyzer.analyze( + text=text[start : start + NER_WINDOW_CHARS], + language=language, + entities=window_entities, + score_threshold=score_threshold, + return_decision_process=return_decision_process, + ) + for result in window_results: results.append( RecognizerResult( result.entity_type, @@ -327,7 +332,7 @@ def _analyze_one( ad_hoc_recognizers: list[PatternRecognizer] | None = None, ): regex_only = _regex_only(entities, score_threshold) - if not regex_only and _exceeds_nlp_length(text, language): + if not regex_only and len(text) > NER_WINDOW_CHARS: return _analyze_long( text, language, entities, score_threshold, return_decision_process, ad_hoc_recognizers ) @@ -335,15 +340,16 @@ def _analyze_one( # otherwise analyze() computes artifacts (runs spaCy) as usual. Custom-pattern # recognizers are regex-based, so they run fine against the blank artifacts. nlp_artifacts = _BLANK_ARTIFACTS.get(language) if regex_only else None - return analyzer.analyze( - text=text, - language=language, - entities=entities or None, - score_threshold=score_threshold, - return_decision_process=return_decision_process, - nlp_artifacts=nlp_artifacts, - ad_hoc_recognizers=ad_hoc_recognizers or None, - ) + with nullcontext() if regex_only else _NER_SLOT: + return analyzer.analyze( + text=text, + language=language, + entities=entities or None, + score_threshold=score_threshold, + return_decision_process=return_decision_process, + nlp_artifacts=nlp_artifacts, + ad_hoc_recognizers=ad_hoc_recognizers or None, + ) # Presidio's BatchAnalyzerEngine defaults nlp.pipe to batch_size=1, so a 2000-text @@ -358,9 +364,10 @@ def _analyze_many( score_threshold: float | None, ad_hoc_recognizers: list[PatternRecognizer] | None = None, ): - """Analyze many texts, skipping the spaCy pass for regex-only requests and - analyzing any text longer than spaCy's `max_length` on its own (see - `_analyze_long`).""" + """Analyze many texts, skipping the spaCy pass for regex-only requests. A text + longer than NER_WINDOW_CHARS is analyzed on its own (see `_analyze_long`); the + rest share NER passes of at most NER_WINDOW_CHARS in total, since a batched pass + costs memory for every character in it, like one long text.""" if _regex_only(entities, score_threshold): blank = _BLANK_ARTIFACTS.get(language) return [ @@ -374,20 +381,32 @@ def _analyze_many( ) for text in texts ] - long_indices = {i for i, text in enumerate(texts) if _exceeds_nlp_length(text, language)} - short_indices = [i for i in range(len(texts)) if i not in long_indices] + long_indices: list[int] = [] + batches: list[list[int]] = [] + batch_chars = 0 + for i, text in enumerate(texts): + if len(text) > NER_WINDOW_CHARS: + long_indices.append(i) + continue + if not batches or batch_chars + len(text) > NER_WINDOW_CHARS: + batches.append([]) + batch_chars = 0 + batches[-1].append(i) + batch_chars += len(text) results: list[list[RecognizerResult]] = [[] for _ in texts] - short_results = batch_analyzer.analyze_iterator( - texts=[texts[i] for i in short_indices], - language=language, - batch_size=NLP_BATCH_SIZE, - entities=entities or None, - score_threshold=score_threshold, - ad_hoc_recognizers=ad_hoc_recognizers or None, - ) - for i, per_text in zip(short_indices, short_results): - results[i] = list(per_text) - for i in sorted(long_indices): + for batch in batches: + with _NER_SLOT: + batch_results = batch_analyzer.analyze_iterator( + texts=[texts[i] for i in batch], + language=language, + batch_size=NLP_BATCH_SIZE, + entities=entities or None, + score_threshold=score_threshold, + ad_hoc_recognizers=ad_hoc_recognizers or None, + ) + for i, per_text in zip(batch, batch_results): + results[i] = list(per_text) + for i in long_indices: results[i] = _analyze_long( texts[i], language, entities, score_threshold, ad_hoc_recognizers=ad_hoc_recognizers ) @@ -396,7 +415,7 @@ def _analyze_many( @asynccontextmanager async def lifespan(_app: FastAPI) -> AsyncIterator[None]: - global analyzer, batch_analyzer, anonymizer, NER_ENTITIES, _BLANK_ARTIFACTS, _NLP_MAX_LENGTH + global analyzer, batch_analyzer, anonymizer, NER_ENTITIES, _BLANK_ARTIFACTS logger.info("building analyzer (spacy)") analyzer = build_analyzer() batch_analyzer = BatchAnalyzerEngine(analyzer_engine=analyzer) @@ -423,10 +442,6 @@ async def lifespan(_app: FastAPI) -> AsyncIterator[None]: language: analyzer.nlp_engine.process_text("", language) for language in SUPPORTED_LANGUAGES } - _NLP_MAX_LENGTH = { - language: nlp.max_length - for language, nlp in getattr(analyzer.nlp_engine, "nlp", {}).items() - } yield @@ -686,8 +701,10 @@ def run_anonymize( ) +# Async so it answers on the event loop: requests queued on _NER_SLOT hold +# threadpool threads, and the load balancer's health check must not wait behind them. @app.get("/health") -def health() -> dict[str, str]: +async def health() -> dict[str, str]: return {"status": "ok"} diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/param-dependents.ts b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/param-dependents.ts index 5751d69b74c..145f9bb42ac 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/param-dependents.ts +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/param-dependents.ts @@ -1,4 +1,5 @@ import { getTransitiveSubBlockDependents } from '@/lib/workflows/subblocks/dependencies' +import { omitConditionHiddenParams } from '@/lib/workflows/tool-input/hidden-params' import type { StoredTool } from '@/lib/workflows/tool-input/types' import { getBlock } from '@/blocks/registry' import type { ToolMetadata } from '@/tools/metadata' @@ -27,10 +28,14 @@ export function clearDependentToolParams( return next ?? params } -/** Keeps user-configured inputs that the newly selected operation accepts. */ +/** + * Keeps user-configured inputs that the newly selected operation accepts and still shows: a + * value whose fields the operation hides would otherwise linger out of sight and still run. + */ export function getParamsForToolOperation( tool: Pick, - nextTool: ToolMetadata + nextTool: ToolMetadata, + operation: string ): Record { const newParamIds = new Set( Object.entries(nextTool.params ?? {}) @@ -64,5 +69,6 @@ export function getParamsForToolOperation( Object.entries(tool.params || {}).forEach(([paramId, value]) => { if (newParamIds.has(paramId) && value) preservedParams[paramId] = value }) - return clearDependentToolParams(tool.type, preservedParams, 'operation') + const visibleParams = omitConditionHiddenParams(subBlocks, preservedParams, operation) + return clearDependentToolParams(tool.type, visibleParams, 'operation') } diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.tsx index bd584693029..6d2c81d98ae 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.tsx @@ -981,7 +981,7 @@ export const ToolInput = memo(function ToolInput({ return } - const preservedParams = getParamsForToolOperation(tool, newToolConfig) + const preservedParams = getParamsForToolOperation(tool, newToolConfig, operation) if (tool.type === 'jira') { const subBlockStore = useSubBlockStore.getState() diff --git a/apps/sim/blocks/blocks/affinity.test.ts b/apps/sim/blocks/blocks/affinity.test.ts new file mode 100644 index 00000000000..19b372a3933 --- /dev/null +++ b/apps/sim/blocks/blocks/affinity.test.ts @@ -0,0 +1,79 @@ +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@/lib/internal/workflows/read-tool-enrichment', () => ({ + readWorkflowInputFieldsForTool: vi.fn(), + readWorkflowMetadataForTool: vi.fn(), +})) + +import { AffinityBlock } from '@/blocks/blocks/affinity' +import { ToolCallParamsError } from '@/providers/tool-params-error' +import { prepareToolExecution, transformBlockTool } from '@/providers/utils' +import { affinityCreateListFieldDropdownOptionTool } from '@/tools/affinity/create_list_field_dropdown_option' + +/** Runs the mapper the way an Agent tool call does: its result is spread over the merged args. */ +function toolCall(args: Record, operation: string) { + const mapParams = AffinityBlock.tools.config?.params + if (!mapParams) throw new Error('Affinity block has no params mapper') + return { ...args, ...mapParams(args, { operation }) } +} + +describe('AffinityBlock agent tool calls', () => { + it('maps block-field keys and keeps model args instead of dropping them', () => { + const result = toolCall( + { apiKey: 'key', noteEntityType: 'company', entityId: '42', limit: '10' }, + 'list_entity_notes' + ) + expect(result).toMatchObject({ entityType: 'company', entityId: '42', limit: 10 }) + expect(result.noteEntityType).toBeUndefined() + + expect( + toolCall({ apiKey: 'key', name: 'Deals', type: 'company', isPublic: true }, 'create_list') + ).toMatchObject({ name: 'Deals', type: 'company', isPublic: true }) + }) +}) + +describe('AffinityBlock dropdown option rank and win rate on a tool call', () => { + const operation = 'create_list_field_dropdown_option' + + async function prepare(stored: Record, modelArgs: Record) { + const providerTool = await transformBlockTool( + { type: AffinityBlock.type, operation, params: { apiKey: 'key', ...stored } }, + { + selectedOperation: operation, + getAllBlocks: () => [AffinityBlock], + getTool: () => affinityCreateListFieldDropdownOptionTool, + } + ) + if (!providerTool) throw new Error('Affinity agent tool was not created') + return prepareToolExecution(providerTool, modelArgs, {}, undefined).executionParams + } + + const pinnedStatusOption = { + listId: 'l1', + fieldId: 'f1', + optionType: 'status-dropdown', + optionText: 'Won', + optionColor: 'green', + optionStatusCategory: 'won', + } + + it('fails the call instead of sending the model fields over the pinned option', async () => { + await expect( + prepare(pinnedStatusOption, { rank: 2, winRate: 150, type: 'ranked-dropdown', text: 'X' }) + ).rejects.toThrow(ToolCallParamsError) + }) + + it.each([ + ['Option Rank', { optionRank: ' ' }, { rank: 2.5 }], + ['Win Rate', { optionWinRate: ' ' }, { rank: 1, winRate: 250 }], + ])('validates the model value behind a blank %s', async (_label, stored, modelArgs) => { + await expect(prepare({ ...pinnedStatusOption, ...stored }, modelArgs)).rejects.toThrow( + ToolCallParamsError + ) + }) + + it('sends a valid model rank behind a blank Option Rank', async () => { + const params = await prepare({ ...pinnedStatusOption, optionRank: ' ' }, { rank: 3 }) + expect(params).toMatchObject({ type: 'status-dropdown', text: 'Won', rank: 3 }) + }) +}) diff --git a/apps/sim/blocks/blocks/affinity.ts b/apps/sim/blocks/blocks/affinity.ts index 6bc3c72ed38..dadff8f1d3c 100644 --- a/apps/sim/blocks/blocks/affinity.ts +++ b/apps/sim/blocks/blocks/affinity.ts @@ -2,8 +2,12 @@ import { AffinityIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' import { + failToolCallOnError, + isToolCall, + mapperOperation, parseOptionalBooleanInput, parseOptionalNumberInput, + toolCallArg, withSavedCredential, } from '@/blocks/utils' @@ -1337,176 +1341,196 @@ export const AffinityBlock: BlockConfig = { * omitting a key leaves the previous operation's value on the wire — an * advanced field is serialized on non-emptiness alone, even while the UI * hides it. `undefined` is what actually drops one. + * + * On a tool call the model's args arrive under the tool's own param names, + * so a tool param the selected operation does not fill from a block field + * keeps the model's value instead of being dropped. */ - params: (params) => { - const operation = String(params.operation ?? '') - const isIn = (group: readonly string[]) => group.includes(operation) + params: (params, context) => + failToolCallOnError(context, () => { + const operation = mapperOperation(params, context) + const isIn = (group: readonly string[]) => group.includes(operation) + + const isKeywordSearch = isIn(KEYWORD_SEARCH_OPERATIONS) + const isDropdownWrite = isIn(DROPDOWN_OPTION_WRITE_OPERATIONS) + const isEntitySearch = isIn(ENTITY_SEARCH_OPERATIONS) + const isFieldValueSelection = isIn(FIELD_VALUE_SELECTION_OPERATIONS) + const isNoteWrite = isIn(NOTE_WRITE_OPERATIONS) + const isCreateNote = operation === 'create_note' + const isCreateList = operation === 'create_list' + const isCreateReminder = operation === 'create_reminder' - const isKeywordSearch = isIn(KEYWORD_SEARCH_OPERATIONS) - const isDropdownWrite = isIn(DROPDOWN_OPTION_WRITE_OPERATIONS) - const isEntitySearch = isIn(ENTITY_SEARCH_OPERATIONS) - const isFieldValueSelection = isIn(FIELD_VALUE_SELECTION_OPERATIONS) - const isNoteWrite = isIn(NOTE_WRITE_OPERATIONS) - const isCreateNote = operation === 'create_note' - const isCreateList = operation === 'create_list' - const isCreateReminder = operation === 'create_reminder' + let entityType: unknown + if (isIn(FIELD_ENTITY_OPERATIONS)) entityType = params.fieldEntityType + else if (operation === 'list_entity_notes') entityType = params.noteEntityType + else if (isIn(MERGE_OPERATIONS)) entityType = params.mergeEntityType + else if (isCreateReminder) entityType = params.reminderEntityType - let entityType: unknown - if (isIn(FIELD_ENTITY_OPERATIONS)) entityType = params.fieldEntityType - else if (operation === 'list_entity_notes') entityType = params.noteEntityType - else if (isIn(MERGE_OPERATIONS)) entityType = params.mergeEntityType - else if (isCreateReminder) entityType = params.reminderEntityType + let type: unknown + if (isCreateList) type = params.listType + else if (operation === 'create_list_field_dropdown_option') type = params.optionType + else if (isCreateNote) type = params.noteType + else if (isCreateReminder) type = params.reminderType - let type: unknown - if (isCreateList) type = params.listType - else if (operation === 'create_list_field_dropdown_option') type = params.optionType - else if (isCreateNote) type = params.noteType - else if (isCreateReminder) type = params.reminderType + let filter: unknown + if (isIn(CONNECTION_OPERATIONS)) filter = params.connectionFilter + else if (isIn(FILTER_OPERATIONS)) filter = params.filter - let filter: unknown - if (isIn(CONNECTION_OPERATIONS)) filter = params.connectionFilter - else if (isIn(FILTER_OPERATIONS)) filter = params.filter + let orderBy: unknown + if (operation === 'list_entity_relationships') orderBy = params.relationshipOrderBy + else if (operation === 'list_field_value_changes') orderBy = params.changeOrderBy - let orderBy: unknown - if (operation === 'list_entity_relationships') orderBy = params.relationshipOrderBy - else if (operation === 'list_field_value_changes') orderBy = params.changeOrderBy + let includes: unknown + if (isIn(NOTE_INCLUDES_OPERATIONS)) includes = params.noteIncludes + else if (isIn(FIELD_INCLUDES_OPERATIONS)) includes = params.fieldIncludes - let includes: unknown - if (isIn(NOTE_INCLUDES_OPERATIONS)) includes = params.noteIncludes - else if (isIn(FIELD_INCLUDES_OPERATIONS)) includes = params.fieldIncludes + let ids: unknown + if (isIn(ID_FILTER_OPERATIONS)) ids = params.entityIds + else if (isKeywordSearch) ids = params.searchIds + else if (isFieldValueSelection) ids = params.valueFieldIds - let ids: unknown - if (isIn(ID_FILTER_OPERATIONS)) ids = params.entityIds - else if (isKeywordSearch) ids = params.searchIds - else if (isFieldValueSelection) ids = params.valueFieldIds + /** A blank block field falls through to the model's value, which is validated too. */ + const parseOptionRank = (value: unknown) => + parseOptionalNumberInput(value, 'Option Rank', { integer: true, min: 0 }) + const parseWinRate = (value: unknown) => + parseOptionalNumberInput(value, 'Win Rate', { integer: true, min: 0, max: 100 }) - return { - apiKey: params.apiKey, - entityType, - type, - filter, - orderBy, - includes, - ids, - entityId: isIn(ENTITY_ID_OPERATIONS) ? params.entityId : undefined, - companyId: - operation === 'get_company' - ? params.companyId - : isKeywordSearch - ? params.scopeCompanyId + const toolParams: Record = { + apiKey: params.apiKey, + entityType, + type, + filter, + orderBy, + includes, + ids, + entityId: isIn(ENTITY_ID_OPERATIONS) ? params.entityId : undefined, + companyId: + operation === 'get_company' + ? params.companyId + : isKeywordSearch + ? params.scopeCompanyId + : undefined, + personId: operation === 'get_person' ? params.personId : undefined, + opportunityId: operation === 'get_opportunity' ? params.opportunityId : undefined, + listId: isIn(LIST_ID_OPERATIONS) ? params.listId : undefined, + listEntryId: isIn(LIST_ENTRY_ID_OPERATIONS) ? params.listEntryId : undefined, + viewId: + operation === 'get_saved_view' || operation === 'list_saved_view_entries' + ? params.viewId + : undefined, + fieldId: isIn(FIELD_ID_OPERATIONS) ? params.fieldId : undefined, + dropdownOptionId: isIn(DROPDOWN_OPTION_ID_OPERATIONS) + ? params.dropdownOptionId + : undefined, + noteId: isIn(NOTE_ID_OPERATIONS) ? params.noteId : undefined, + transcriptId: + operation === 'get_transcript' || operation === 'list_transcript_fragments' + ? params.transcriptId : undefined, - personId: operation === 'get_person' ? params.personId : undefined, - opportunityId: operation === 'get_opportunity' ? params.opportunityId : undefined, - listId: isIn(LIST_ID_OPERATIONS) ? params.listId : undefined, - listEntryId: isIn(LIST_ENTRY_ID_OPERATIONS) ? params.listEntryId : undefined, - viewId: - operation === 'get_saved_view' || operation === 'list_saved_view_entries' - ? params.viewId + userId: operation === 'get_user' ? params.userId : undefined, + mergeId: operation === 'get_merge' ? params.mergeId : undefined, + taskId: operation === 'get_merge_task' ? params.taskId : undefined, + types: isFieldValueSelection ? params.valueFieldTypes : undefined, + fieldIds: isIn(FIELD_SELECTION_OPERATIONS) ? params.fieldIds : undefined, + fieldTypes: isIn(FIELD_SELECTION_OPERATIONS) ? params.fieldTypes : undefined, + filters: isEntitySearch ? params.searchFilters : undefined, + sorts: isEntitySearch ? params.searchSorts : undefined, + searchTerm: isEntitySearch ? params.searchTerm : undefined, + searchFieldIds: isEntitySearch ? params.searchTermFieldIds : undefined, + prompt: isIn(PROMPT_OPERATIONS) ? params.prompt : undefined, + listIds: operation === 'semantic_search' ? params.listIds : undefined, + term: + operation === 'list_lists' || operation === 'list_users' ? params.term : undefined, + name: isCreateList ? params.listName : undefined, + isPublic: isCreateList ? parseOptionalBooleanInput(params.isPublic) : undefined, + text: isDropdownWrite ? params.optionText : undefined, + rank: isDropdownWrite + ? (parseOptionRank(params.optionRank) ?? + parseOptionRank(toolCallArg(context, params.rank))) : undefined, - fieldId: isIn(FIELD_ID_OPERATIONS) ? params.fieldId : undefined, - dropdownOptionId: isIn(DROPDOWN_OPTION_ID_OPERATIONS) - ? params.dropdownOptionId - : undefined, - noteId: isIn(NOTE_ID_OPERATIONS) ? params.noteId : undefined, - transcriptId: - operation === 'get_transcript' || operation === 'list_transcript_fragments' - ? params.transcriptId + color: isDropdownWrite ? params.optionColor : undefined, + statusCategory: isDropdownWrite ? params.optionStatusCategory : undefined, + winRate: isDropdownWrite + ? (parseWinRate(params.optionWinRate) ?? + parseWinRate(toolCallArg(context, params.winRate))) : undefined, - userId: operation === 'get_user' ? params.userId : undefined, - mergeId: operation === 'get_merge' ? params.mergeId : undefined, - taskId: operation === 'get_merge_task' ? params.taskId : undefined, - types: isFieldValueSelection ? params.valueFieldTypes : undefined, - fieldIds: isIn(FIELD_SELECTION_OPERATIONS) ? params.fieldIds : undefined, - fieldTypes: isIn(FIELD_SELECTION_OPERATIONS) ? params.fieldTypes : undefined, - filters: isEntitySearch ? params.searchFilters : undefined, - sorts: isEntitySearch ? params.searchSorts : undefined, - searchTerm: isEntitySearch ? params.searchTerm : undefined, - searchFieldIds: isEntitySearch ? params.searchTermFieldIds : undefined, - prompt: isIn(PROMPT_OPERATIONS) ? params.prompt : undefined, - listIds: operation === 'semantic_search' ? params.listIds : undefined, - term: operation === 'list_lists' || operation === 'list_users' ? params.term : undefined, - name: isCreateList ? params.listName : undefined, - isPublic: isCreateList ? parseOptionalBooleanInput(params.isPublic) : undefined, - text: isDropdownWrite ? params.optionText : undefined, - rank: isDropdownWrite - ? parseOptionalNumberInput(params.optionRank, 'Option Rank', { integer: true, min: 0 }) - : undefined, - color: isDropdownWrite ? params.optionColor : undefined, - statusCategory: isDropdownWrite ? params.optionStatusCategory : undefined, - winRate: isDropdownWrite - ? parseOptionalNumberInput(params.optionWinRate, 'Win Rate', { - integer: true, - min: 0, - max: 100, - }) - : undefined, - value: isIn(FIELD_VALUE_WRITE_OPERATIONS) ? params.fieldValue : undefined, - updates: isIn(FIELD_BATCH_WRITE_OPERATIONS) ? params.fieldUpdates : undefined, - html: isNoteWrite ? params.noteHtml : undefined, - companyIds: isNoteWrite ? params.noteCompanyIds : undefined, - personIds: isNoteWrite ? params.notePersonIds : undefined, - opportunityIds: isNoteWrite ? params.noteOpportunityIds : undefined, - interactionId: isCreateNote ? params.interactionId : undefined, - interactionType: isCreateNote ? params.interactionType : undefined, - parentId: isCreateNote ? params.parentId : undefined, - creatorId: isCreateNote ? params.creatorId : undefined, - createdAt: isCreateNote ? params.noteCreatedAt : undefined, - primaryId: operation === 'create_merge' ? params.primaryId : undefined, - duplicateId: operation === 'create_merge' ? params.duplicateId : undefined, - dueDate: isCreateReminder ? params.dueDate : undefined, - content: isCreateReminder ? params.reminderContent : undefined, - ownerId: isCreateReminder ? params.ownerId : undefined, - resetTrigger: isCreateReminder ? params.resetTrigger : undefined, - periodDays: isCreateReminder - ? parseOptionalNumberInput(params.periodDays, 'Period In Days', { - integer: true, - min: 1, - }) - : undefined, - cursor: isIn(CURSOR_OPERATIONS) ? params.cursor : undefined, - limit: isIn(LIMIT_OPERATIONS) - ? parseOptionalNumberInput(params.limit, 'Limit', { integer: true, min: 1 }) - : undefined, - totalCount: isIn(TOTAL_COUNT_OPERATIONS) - ? parseOptionalBooleanInput(params.totalCount) - : undefined, - fieldEntityType: undefined, - noteEntityType: undefined, - mergeEntityType: undefined, - reminderEntityType: undefined, - listName: undefined, - listType: undefined, - optionType: undefined, - optionText: undefined, - optionRank: undefined, - optionColor: undefined, - optionStatusCategory: undefined, - optionWinRate: undefined, - fieldValue: undefined, - fieldUpdates: undefined, - searchFilters: undefined, - searchSorts: undefined, - searchTermFieldIds: undefined, - searchIds: undefined, - scopeCompanyId: undefined, - entityIds: undefined, - valueFieldIds: undefined, - valueFieldTypes: undefined, - noteType: undefined, - noteHtml: undefined, - noteCompanyIds: undefined, - notePersonIds: undefined, - noteOpportunityIds: undefined, - noteCreatedAt: undefined, - reminderType: undefined, - reminderContent: undefined, - connectionFilter: undefined, - relationshipOrderBy: undefined, - changeOrderBy: undefined, - noteIncludes: undefined, - fieldIncludes: undefined, - } - }, + value: isIn(FIELD_VALUE_WRITE_OPERATIONS) ? params.fieldValue : undefined, + updates: isIn(FIELD_BATCH_WRITE_OPERATIONS) ? params.fieldUpdates : undefined, + html: isNoteWrite ? params.noteHtml : undefined, + companyIds: isNoteWrite ? params.noteCompanyIds : undefined, + personIds: isNoteWrite ? params.notePersonIds : undefined, + opportunityIds: isNoteWrite ? params.noteOpportunityIds : undefined, + interactionId: isCreateNote ? params.interactionId : undefined, + interactionType: isCreateNote ? params.interactionType : undefined, + parentId: isCreateNote ? params.parentId : undefined, + creatorId: isCreateNote ? params.creatorId : undefined, + createdAt: isCreateNote ? params.noteCreatedAt : undefined, + primaryId: operation === 'create_merge' ? params.primaryId : undefined, + duplicateId: operation === 'create_merge' ? params.duplicateId : undefined, + dueDate: isCreateReminder ? params.dueDate : undefined, + content: isCreateReminder ? params.reminderContent : undefined, + ownerId: isCreateReminder ? params.ownerId : undefined, + resetTrigger: isCreateReminder ? params.resetTrigger : undefined, + periodDays: isCreateReminder + ? parseOptionalNumberInput(params.periodDays, 'Period In Days', { + integer: true, + min: 1, + }) + : undefined, + cursor: isIn(CURSOR_OPERATIONS) ? params.cursor : undefined, + limit: isIn(LIMIT_OPERATIONS) + ? parseOptionalNumberInput(params.limit, 'Limit', { integer: true, min: 1 }) + : undefined, + totalCount: isIn(TOTAL_COUNT_OPERATIONS) + ? parseOptionalBooleanInput(params.totalCount) + : undefined, + } + + if (isToolCall(context)) { + for (const [key, value] of Object.entries(toolParams)) { + if (value === undefined) toolParams[key] = params[key] + } + } + + return { + ...toolParams, + fieldEntityType: undefined, + noteEntityType: undefined, + mergeEntityType: undefined, + reminderEntityType: undefined, + listName: undefined, + listType: undefined, + optionType: undefined, + optionText: undefined, + optionRank: undefined, + optionColor: undefined, + optionStatusCategory: undefined, + optionWinRate: undefined, + fieldValue: undefined, + fieldUpdates: undefined, + searchFilters: undefined, + searchSorts: undefined, + searchTermFieldIds: undefined, + searchIds: undefined, + scopeCompanyId: undefined, + entityIds: undefined, + valueFieldIds: undefined, + valueFieldTypes: undefined, + noteType: undefined, + noteHtml: undefined, + noteCompanyIds: undefined, + notePersonIds: undefined, + noteOpportunityIds: undefined, + noteCreatedAt: undefined, + reminderType: undefined, + reminderContent: undefined, + connectionFilter: undefined, + relationshipOrderBy: undefined, + changeOrderBy: undefined, + noteIncludes: undefined, + fieldIncludes: undefined, + } + }), }, }, diff --git a/apps/sim/blocks/blocks/agentmail.test.ts b/apps/sim/blocks/blocks/agentmail.test.ts new file mode 100644 index 00000000000..5959ce72671 --- /dev/null +++ b/apps/sim/blocks/blocks/agentmail.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from 'vitest' +import { AgentMailBlock } from '@/blocks/blocks/agentmail' + +/** Runs the mapper the way an Agent tool call does: its result is spread over the merged args. */ +function toolCall(args: Record, operation: string) { + const mapParams = AgentMailBlock.tools.config?.params + if (!mapParams) throw new Error('AgentMail block has no params mapper') + return { ...args, ...mapParams(args, { operation }) } +} + +describe('AgentMailBlock agent tool calls', () => { + it('maps the block-field reply message key and keeps the model recipients and flags', () => { + expect( + toolCall( + { inboxId: 'inbox', replyMessageId: 'msg-1', to: 'a@example.com', replyAll: true }, + 'reply_message' + ) + ).toMatchObject({ messageId: 'msg-1', to: 'a@example.com', replyAll: true }) + }) + + it('keeps a boolean permanent flag from the model', () => { + expect( + toolCall({ inboxId: 'inbox', threadId: 't-1', permanent: true }, 'delete_thread') + ).toMatchObject({ permanent: true }) + }) + + it('treats a stored "false" permanent dropdown as a trash move, not a permanent delete', () => { + expect( + toolCall({ inboxId: 'inbox', threadId: 't-1', permanent: 'false' }, 'delete_thread') + ).toMatchObject({ permanent: false }) + }) + + it('treats a stored "false" reply-all dropdown as a reply to the sender only', () => { + expect( + toolCall({ inboxId: 'inbox', replyMessageId: 'msg-1', replyAll: 'false' }, 'reply_message') + ).toMatchObject({ replyAll: false }) + }) +}) diff --git a/apps/sim/blocks/blocks/agentmail.ts b/apps/sim/blocks/blocks/agentmail.ts index db6048ac1d3..d2f79653304 100644 --- a/apps/sim/blocks/blocks/agentmail.ts +++ b/apps/sim/blocks/blocks/agentmail.ts @@ -1,7 +1,7 @@ import { AgentMailIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' export const AgentMailBlock: BlockConfig = { type: 'agentmail', @@ -567,9 +567,9 @@ export const AgentMailBlock: BlockConfig = { ], config: { tool: (params) => `agentmail_${params.operation || 'send_message'}`, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { - operation, inboxIdParam, permanent, replyMessageId, @@ -590,11 +590,11 @@ export const AgentMailBlock: BlockConfig = { } if (operation === 'delete_thread' && permanent !== undefined) { - rest.permanent = permanent === 'true' + rest.permanent = permanent === true || permanent === 'true' } if (operation === 'reply_message' && replyAll !== undefined) { - rest.replyAll = replyAll === 'true' + rest.replyAll = replyAll === true || replyAll === 'true' } if (operation === 'reply_message' && replyMessageId) { @@ -604,7 +604,7 @@ export const AgentMailBlock: BlockConfig = { if (operation === 'reply_message' && replyTo) { rest.to = replyTo } else if (operation === 'reply_message') { - rest.to = undefined + rest.to = toolCallArg(context, rest.to) } if (operation === 'forward_message' && forwardMessageId) { diff --git a/apps/sim/blocks/blocks/agentphone.test.ts b/apps/sim/blocks/blocks/agentphone.test.ts new file mode 100644 index 00000000000..987946d1a89 --- /dev/null +++ b/apps/sim/blocks/blocks/agentphone.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from 'vitest' +import { AgentPhoneBlock } from '@/blocks/blocks/agentphone' + +/** Runs the mapper the way an Agent tool call does: its result is spread over the merged args. */ +function toolCall(args: Record, operation: string) { + const mapParams = AgentPhoneBlock.tools.config?.params + if (!mapParams) throw new Error('AgentPhone block has no params mapper') + return { ...args, ...mapParams(args, { operation }) } +} + +describe('AgentPhoneBlock agent tool calls', () => { + it('maps block-field filters and coerces limits for an operation passed only in context', () => { + expect( + toolCall({ apiKey: 'key', callsStatus: 'completed', limit: '25' }, 'list_calls') + ).toMatchObject({ status: 'completed', limit: 25 }) + }) +}) diff --git a/apps/sim/blocks/blocks/agentphone.ts b/apps/sim/blocks/blocks/agentphone.ts index 2212123f5dc..0159154666d 100644 --- a/apps/sim/blocks/blocks/agentphone.ts +++ b/apps/sim/blocks/blocks/agentphone.ts @@ -2,7 +2,7 @@ import { toError } from '@sim/utils/errors' import { AgentPhoneIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, withSavedCredential } from '@/blocks/utils' const CONVERSATION_OPS = [ 'get_conversation', @@ -588,9 +588,9 @@ export const AgentPhoneBlock: BlockConfig = { ], config: { tool: (params) => `agentphone_${params.operation || 'create_number'}`, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { - operation, attachAgentId, callAgentId, toNumberCall, @@ -633,7 +633,7 @@ export const AgentPhoneBlock: BlockConfig = { if (messageBody !== undefined) rest.body = messageBody } - if (['create_contact', 'update_contact'].includes(operation as string)) { + if (['create_contact', 'update_contact'].includes(operation)) { if (contactPhoneNumber) rest.phoneNumber = contactPhoneNumber if (contactName) rest.name = contactName if (contactEmail) rest.email = contactEmail diff --git a/apps/sim/blocks/blocks/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/algolia.test.ts b/apps/sim/blocks/blocks/algolia.test.ts new file mode 100644 index 00000000000..c5c3c4e9d44 --- /dev/null +++ b/apps/sim/blocks/blocks/algolia.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from 'vitest' +import { AlgoliaBlock } from '@/blocks/blocks/algolia' + +/** Runs the mapper the way an Agent tool call does: its result is spread over the merged args. */ +function toolCall(args: Record, operation: string) { + const mapParams = AlgoliaBlock.tools.config?.params + if (!mapParams) throw new Error('Algolia block has no params mapper') + return { ...args, ...mapParams(args, { operation }) } +} + +describe('AlgoliaBlock agent tool calls', () => { + it('maps the block-field requests key on a tool call', () => { + expect( + toolCall({ indexName: 'products', getRecordsRequests: '[{"objectID":"1"}]' }, 'get_records') + ).toMatchObject({ requests: '[{"objectID":"1"}]' }) + }) + + it('keeps the model filters, requests, and copy-or-move operation', () => { + expect(toolCall({ indexName: 'p', filters: 'brand:x' }, 'delete_by_filter')).toMatchObject({ + filters: 'brand:x', + }) + expect( + toolCall({ indexName: 'p', requests: [{ objectID: '1' }] }, 'get_records') + ).toMatchObject({ requests: [{ objectID: '1' }] }) + expect( + toolCall({ indexName: 'p', destination: 'q', operation: 'move' }, 'copy_move_index') + ).toMatchObject({ operation: 'move' }) + }) +}) diff --git a/apps/sim/blocks/blocks/algolia.ts b/apps/sim/blocks/blocks/algolia.ts index fbcbe319e9e..077b1164aa5 100644 --- a/apps/sim/blocks/blocks/algolia.ts +++ b/apps/sim/blocks/blocks/algolia.ts @@ -1,7 +1,7 @@ import { AlgoliaIcon } from '@/components/icons' -import type { BlockConfig, BlockMeta } from '@/blocks/types' +import type { BlockConfig, BlockMeta, BlockToolParamsContext } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { isToolCall, mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' export const AlgoliaBlock: BlockConfig = { type: 'algolia', @@ -593,11 +593,11 @@ Return ONLY the JSON array.`, ], config: { tool: (params: Record) => `algolia_${params.operation}`, - params: (params: Record) => { - const { operation, ...rest } = params + params: (params: Record, context?: BlockToolParamsContext) => { + const operation = mapperOperation(params, context) const result: Record = {} - for (const [key, value] of Object.entries(rest)) { + for (const [key, value] of Object.entries(params)) { if (value === undefined || value === null || value === '') continue result[key] = value } @@ -618,15 +618,18 @@ Return ONLY the JSON array.`, result.getRankingInfo = toBool(result.getRankingInfo, false) } if (operation === 'copy_move_index') { - result.operation = result.copyMoveOperation + // A tool call carries the tool's own copy-or-move `operation` as a model arg. + if (!isToolCall(context) || result.copyMoveOperation !== undefined) { + result.operation = result.copyMoveOperation + } result.copyMoveOperation = undefined } if (operation === 'delete_by_filter') { - result.filters = result.deleteFilters + result.filters = result.deleteFilters ?? toolCallArg(context, result.filters) result.deleteFilters = undefined } if (operation === 'get_records') { - result.requests = result.getRecordsRequests + result.requests = result.getRecordsRequests ?? toolCallArg(context, result.requests) result.getRecordsRequests = undefined } diff --git a/apps/sim/blocks/blocks/amplitude.test.ts b/apps/sim/blocks/blocks/amplitude.test.ts new file mode 100644 index 00000000000..3c4cbc212b2 --- /dev/null +++ b/apps/sim/blocks/blocks/amplitude.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest' +import { AmplitudeBlock } from '@/blocks/blocks/amplitude' + +/** Runs the mapper the way an Agent tool call does: its result is spread over the merged args. */ +function toolCall(args: Record, operation: string) { + const mapParams = AmplitudeBlock.tools.config?.params + if (!mapParams) throw new Error('Amplitude block has no params mapper') + return { ...args, ...mapParams(args, { operation }) } +} + +describe('AmplitudeBlock agent tool calls', () => { + it('maps the block-field event key for an operation passed only in context', () => { + expect( + toolCall( + { apiKey: 'k', secretKey: 's', segmentationEventType: 'signup', start: '20260101' }, + 'event_segmentation' + ) + ).toMatchObject({ eventType: 'signup', start: '20260101' }) + }) +}) diff --git a/apps/sim/blocks/blocks/amplitude.ts b/apps/sim/blocks/blocks/amplitude.ts index 22ff60e1c80..f2975f113e0 100644 --- a/apps/sim/blocks/blocks/amplitude.ts +++ b/apps/sim/blocks/blocks/amplitude.ts @@ -1,6 +1,6 @@ import { AmplitudeIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, withSavedCredential } from '@/blocks/utils' /* * Amplitude identifies a person by user id or device id — either one alone is @@ -1012,10 +1012,10 @@ export const AmplitudeBlock: BlockConfig = { ], config: { tool: (params) => `amplitude_${params.operation}`, - params: (params) => { + params: (params, context) => { const result: Record = {} - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'send_event': if (params.sendEventUserProperties) result.userProperties = params.sendEventUserProperties diff --git a/apps/sim/blocks/blocks/apollo.test.ts b/apps/sim/blocks/blocks/apollo.test.ts new file mode 100644 index 00000000000..3af28753040 --- /dev/null +++ b/apps/sim/blocks/blocks/apollo.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from 'vitest' +import { ApolloBlock } from '@/blocks/blocks/apollo' +import type { BlockToolParamsContext } from '@/blocks/types' + +/** The block's `tools.config.params` mapper; `context` is set on a tool call, absent on the canvas. */ +const buildParams = ( + inputs: Record, + context?: BlockToolParamsContext +): Record => ApolloBlock.tools.config?.params?.(inputs, context) ?? {} + +/** + * On an agent call the stored row params merge with the model args (keyed by the tool's param + * names), the operation reaches the mapper only on `context`, and the handler forwards + * `{ ...merged, ...mapped }`. + */ +describe('ApolloBlock agent tool calls', () => { + const agentCall = ( + operation: string, + merged: Record + ): Record => { + return { ...merged, ...buildParams(merged, { operation }) } + } + + it('forwards the row acting user and label names to sequence_add_contacts', () => { + const mapped = agentCall('sequence_add', { + apiKey: 'key', + sequence_id: 'seq_1', + contact_ids: ['c_1'], + send_email_from_email_account_id: 'ea_1', + sequence_user_id: 'user_1', + sequence_add_label_names: '["outbound"]', + }) + expect(mapped).toMatchObject({ user_id: 'user_1', label_names: ['outbound'] }) + expect(mapped.sequence_user_id).toBeUndefined() + expect(mapped.sequence_add_label_names).toBeUndefined() + }) + + it('sends the row initial status over a stale task status carried from another operation', () => { + const mapped = agentCall('sequence_add', { + apiKey: 'key', + sequence_id: 'seq_1', + contact_ids: ['c_1'], + send_email_from_email_account_id: 'ea_1', + sequence_status: 'paused', + status: 'scheduled', + }) + expect(mapped.status).toBe('paused') + }) + + it('keeps the row initial status on the canvas', () => { + const mapped = buildParams({ + operation: 'sequence_add', + apiKey: 'key', + sequence_status: 'paused', + status: 'active', + }) + expect(mapped.status).toBe('paused') + }) +}) diff --git a/apps/sim/blocks/blocks/apollo.ts b/apps/sim/blocks/blocks/apollo.ts index aba5a2b5a8a..7a851822308 100644 --- a/apps/sim/blocks/blocks/apollo.ts +++ b/apps/sim/blocks/blocks/apollo.ts @@ -3,7 +3,7 @@ import { getErrorMessage } from '@sim/utils/errors' import { ApolloIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, withSavedCredential } from '@/blocks/utils' /** Identifies a person by email when available, otherwise by given name. */ const PERSON_IDENTITY_FIELD = ['email', 'first_name'] as const @@ -1112,7 +1112,8 @@ Return ONLY the timestamp string in ISO 8601 format - no explanations, no quotes throw new Error(`Invalid Apollo operation: ${params.operation}`) } }, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { apiKey, ...rest } = params const parsedParams: Record = { apiKey, ...rest } @@ -1190,7 +1191,7 @@ Return ONLY the timestamp string in ISO 8601 format - no explanations, no quotes } } - if (params.operation === 'organization_bulk_enrich') { + if (operation === 'organization_bulk_enrich') { // Back-compat: workflows saved before the `organizations` → `domains` rename stored an // array of { name, domain? } objects (or plain strings) under `organizations`. Derive // `domains` from it so those workflows keep running without manual migration. @@ -1213,7 +1214,7 @@ Return ONLY the timestamp string in ISO 8601 format - no explanations, no quotes parsedParams.organizations = undefined } - if (params.operation === 'contact_bulk_update') { + if (operation === 'contact_bulk_update') { const { ids, attributes } = splitBulkUpdateInput(parsedParams.contacts) if (attributes) { if (parsedParams.contact_attributes === undefined) { @@ -1225,7 +1226,7 @@ Return ONLY the timestamp string in ISO 8601 format - no explanations, no quotes parsedParams.contacts = undefined } - if (params.operation === 'account_bulk_update') { + if (operation === 'account_bulk_update') { const { ids, attributes } = splitBulkUpdateInput(parsedParams.accounts) if (attributes) { if (parsedParams.account_attributes === undefined) { @@ -1249,23 +1250,23 @@ Return ONLY the timestamp string in ISO 8601 format - no explanations, no quotes parsedParams.account_bulk_update_account_stage_id = undefined } - if (params.operation === 'contact_create') { + if (operation === 'contact_create') { if (rest.contact_run_dedupe !== undefined) { parsedParams.run_dedupe = rest.contact_run_dedupe } parsedParams.contact_run_dedupe = undefined } - if (params.operation === 'account_create' || params.operation === 'account_update') { + if (operation === 'account_create' || operation === 'account_update') { if (rest.account_name) parsedParams.name = rest.account_name parsedParams.account_name = undefined } - if (params.operation === 'account_update') { + if (operation === 'account_update') { parsedParams.account_id = rest.account_id } - if (params.operation === 'sequence_add') { + if (operation === 'sequence_add') { if (parsedParams.sequence_add_label_names !== undefined) { parsedParams.label_names = parsedParams.sequence_add_label_names } @@ -1280,17 +1281,14 @@ Return ONLY the timestamp string in ISO 8601 format - no explanations, no quotes parsedParams.sequence_status = undefined } - if (params.operation === 'task_create') { + if (operation === 'task_create') { if (rest.task_notes !== undefined) { parsedParams.note = rest.task_notes } parsedParams.task_notes = undefined } - if ( - params.operation === 'opportunity_create' || - params.operation === 'opportunity_update' - ) { + if (operation === 'opportunity_create' || operation === 'opportunity_update') { if (rest.opportunity_name) parsedParams.name = rest.opportunity_name parsedParams.opportunity_name = undefined } diff --git a/apps/sim/blocks/blocks/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/ashby.test.ts b/apps/sim/blocks/blocks/ashby.test.ts index 4678e846694..f4211b5dc1b 100644 --- a/apps/sim/blocks/blocks/ashby.test.ts +++ b/apps/sim/blocks/blocks/ashby.test.ts @@ -1,6 +1,9 @@ import { describe, expect, it } from 'vitest' import { AshbyBlock } from './ashby' +const blockParams = AshbyBlock.tools.config?.params +if (!blockParams) throw new Error('AshbyBlock has no params mapper') + describe('AshbyBlock', () => { const buildParams = (operation: string, extra: Record) => ({ operation, @@ -9,7 +12,7 @@ describe('AshbyBlock', () => { describe('alternateEmailAddresses parsing (create_candidate)', () => { it('parses a comma-separated string into an array', () => { - const result = AshbyBlock.tools.config.params!( + const result = blockParams( buildParams('create_candidate', { alternateEmailAddresses: 'a@x.com, b@x.com', }) @@ -20,9 +23,7 @@ describe('AshbyBlock', () => { describe('socialLinks parsing (update_candidate)', () => { it('preserves an empty JSON array so users can clear all social links', () => { - const result = AshbyBlock.tools.config.params!( - buildParams('update_candidate', { socialLinks: '[]' }) - ) + const result = blockParams(buildParams('update_candidate', { socialLinks: '[]' })) expect(result.socialLinks).toEqual([]) }) @@ -30,24 +31,20 @@ describe('AshbyBlock', () => { // A silent [] here would let the Ashby update proceed without applying // the requested links and with no error shown to the workflow author. expect(() => - AshbyBlock.tools.config.params!( - buildParams('update_candidate', { socialLinks: 'not json' }) - ) + blockParams(buildParams('update_candidate', { socialLinks: 'not json' })) ).toThrow(/Invalid JSON in Ashby social links/) }) it('throws when the parsed JSON is not an array', () => { expect(() => - AshbyBlock.tools.config.params!( - buildParams('update_candidate', { socialLinks: '{"type":"Twitter"}' }) - ) + blockParams(buildParams('update_candidate', { socialLinks: '{"type":"Twitter"}' })) ).toThrow(/expected a JSON array/) }) }) describe('nullable candidate updates', () => { it('preserves nulls from dynamic references for aliased update fields', () => { - const result = AshbyBlock.tools.config.params!( + const result = blockParams( buildParams('update_candidate', { updateName: null, candidateLocation: null, @@ -63,17 +60,14 @@ describe('AshbyBlock', () => { describe('archiveEmail parsing (change_application_stage)', () => { it('rejects non-object archive email input', () => { expect(() => - AshbyBlock.tools.config.params!( - buildParams('change_application_stage', { archiveEmail: 'true' }) - ) + blockParams(buildParams('change_application_stage', { archiveEmail: 'true' })) ).toThrow(/expected a JSON object/) }) }) describe('fieldValue parsing (set_custom_field_value)', () => { const parse = (fieldValue: unknown) => - AshbyBlock.tools.config.params!(buildParams('set_custom_field_value', { fieldValue })) - .fieldValue + blockParams(buildParams('set_custom_field_value', { fieldValue })).fieldValue it('decodes null so the annotation can be cleared', () => { // Ashby clears a custom field when it receives an explicit null, which is @@ -106,17 +100,13 @@ describe('AshbyBlock', () => { describe('fieldValues parsing (set_custom_field_values)', () => { it('throws instead of silently dropping the writes when the JSON is malformed', () => { expect(() => - AshbyBlock.tools.config.params!( - buildParams('set_custom_field_values', { fieldValues: 'not json' }) - ) + blockParams(buildParams('set_custom_field_values', { fieldValues: 'not json' })) ).toThrow(/Invalid JSON in Ashby custom field values/) }) it('throws when the parsed JSON is not an array', () => { expect(() => - AshbyBlock.tools.config.params!( - buildParams('set_custom_field_values', { fieldValues: '{"fieldId":"abc"}' }) - ) + blockParams(buildParams('set_custom_field_values', { fieldValues: '{"fieldId":"abc"}' })) ).toThrow(/expected a JSON array/) }) }) @@ -126,7 +116,7 @@ describe('AshbyBlock', () => { // The Source ID field is hidden once the clear switch is on, but a value // typed beforehand is still stored. Sending both would trip the tool's // exclusivity guard and surface as an error the user cannot see the cause of. - const result = AshbyBlock.tools.config.params!( + const result = blockParams( buildParams('change_application_source', { changeSourceId: 'src-left-over', unsetSource: 'true', @@ -146,7 +136,7 @@ describe('AshbyBlock', () => { // result, not just the mapping, since that gap is where the bug lived. const merge = (inputs: Record) => ({ ...inputs, - ...AshbyBlock.tools.config.params!(inputs), + ...blockParams(inputs), }) const cleared = merge( @@ -179,4 +169,33 @@ describe('AshbyBlock', () => { expect(explicit.sourceId).toBe('src-intended') }) }) + describe('agent tool calls (operation only in context)', () => { + const toolCall = (operation: string, args: Record) => ({ + ...args, + ...blockParams(args, { operation }), + }) + + it('maps block-only fields saved on the tool row to the tool params', () => { + const result = toolCall('create_application', { + appCandidateId: 'cand-1', + appCreatedAt: '2026-01-01T00:00:00Z', + jobId: 'job-1', + }) + expect(result.candidateId).toBe('cand-1') + expect(result.createdAt).toBe('2026-01-01T00:00:00Z') + }) + + it('keeps model args keyed by the tool param names', () => { + const values = [{ fieldId: 'f-1', fieldValue: 'High' }] + expect( + toolCall('set_custom_field_values', { objectType: 'Candidate', objectId: 'c-1', values }) + .values + ).toEqual(values) + expect( + toolCall('change_application_source', { applicationId: 'app-1', sourceId: 'src-1' }) + .sourceId + ).toBe('src-1') + expect(toolCall('search_candidates', { name: 'Ada', limit: 5 }).limit).toBe(5) + }) + }) }) diff --git a/apps/sim/blocks/blocks/ashby.ts b/apps/sim/blocks/blocks/ashby.ts index 7c3d6af7950..b04c6993f08 100644 --- a/apps/sim/blocks/blocks/ashby.ts +++ b/apps/sim/blocks/blocks/ashby.ts @@ -1,7 +1,12 @@ import { getErrorMessage } from '@sim/utils/errors' import { AshbyIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' -import { normalizeFileInput, withSavedCredential } from '@/blocks/utils' +import { + mapperOperation, + normalizeFileInput, + toolCallArg, + withSavedCredential, +} from '@/blocks/utils' import { getTrigger } from '@/triggers' function parseStringListInput(value: unknown): string[] { @@ -1420,7 +1425,8 @@ Output only the JSON array.`, ], config: { tool: (params) => `ashby_${params.operation}`, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const result: Record = {} if (params.perPage) result.perPage = Number(params.perPage) if (params.searchName) result.name = params.searchName @@ -1466,7 +1472,7 @@ Output only the JSON array.`, params.includeUnpublishedJobPostingIds === 'true' || params.includeUnpublishedJobPostingIds === true ) { - if (params.operation === 'list_jobs') result.includeUnpublishedJobPostingsIds = true + if (operation === 'list_jobs') result.includeUnpublishedJobPostingsIds = true else result.includeUnpublishedJobPostingIds = true } if (params.excludeFormDefinition === 'true' || params.excludeFormDefinition === true) { @@ -1486,7 +1492,7 @@ Output only the JSON array.`, if (applicationHistory.length > 0) result.applicationHistory = applicationHistory } if ( - (params.operation === 'create_candidate' || params.operation === 'update_candidate') && + (operation === 'create_candidate' || operation === 'update_candidate') && params.candidateLocation !== undefined && params.candidateLocation !== '' ) { @@ -1507,28 +1513,30 @@ Output only the JSON array.`, ) { result.startAutomaticActivities = true } - if (params.operation === 'search_jobs' || params.operation === 'search_candidates') { - result.limit = params.perPage ? Number(params.perPage) : undefined + if (operation === 'search_jobs' || operation === 'search_candidates') { + result.limit = params.perPage + ? Number(params.perPage) + : toolCallArg(context, params.limit) } - if (params.operation === 'upload_resume' || params.operation === 'upload_candidate_file') { + if (operation === 'upload_resume' || operation === 'upload_candidate_file') { const file = normalizeFileInput(params.file, { single: true }) if (!file) throw new Error('A candidate file is required.') result.file = file } - if (params.operation === 'create_application' && params.appCandidateId) { + if (operation === 'create_application' && params.appCandidateId) { result.candidateId = params.appCandidateId } - if (params.operation === 'create_application' && params.appCreatedAt) { + if (operation === 'create_application' && params.appCreatedAt) { result.createdAt = params.appCreatedAt } if ( - (params.operation === 'create_candidate' || params.operation === 'update_candidate') && + (operation === 'create_candidate' || operation === 'update_candidate') && params.candidateCreatedAt !== undefined && params.candidateCreatedAt !== '' ) { result.createdAt = params.candidateCreatedAt } - if (params.operation === 'create_note' && params.noteCreatedAt) { + if (operation === 'create_note' && params.noteCreatedAt) { result.createdAt = params.noteCreatedAt } if (params.updateName !== undefined && params.updateName !== '') { @@ -1544,7 +1552,7 @@ Output only the JSON array.`, ) { result.includeLocationHierarchy = true } - if (params.operation === 'list_offers' && params.offerApplicationId) { + if (operation === 'list_offers' && params.offerApplicationId) { result.applicationId = params.offerApplicationId } if (params.alternateEmailAddresses) { @@ -1559,13 +1567,15 @@ Output only the JSON array.`, result.socialLinks = parseSocialLinksInput(socialLinksValue) } } - if (params.operation === 'set_custom_field_value') { + if (operation === 'set_custom_field_value') { result.fieldValue = parseCustomFieldValueInput(params.fieldValue) } - if (params.operation === 'set_custom_field_values') { - result.values = parseCustomFieldValuesInput(params.fieldValues) + if (operation === 'set_custom_field_values') { + result.values = parseCustomFieldValuesInput( + params.fieldValues || toolCallArg(context, params.values) + ) } - if (params.operation === 'change_application_source') { + if (operation === 'change_application_source') { // sourceId is always assigned, never conditionally, because the executor // merges `{ ...inputs, ...transformedParams }` and a key this mapping // leaves unset simply inherits whatever was in inputs. The create-path @@ -1576,8 +1586,9 @@ Output only the JSON array.`, // Inheriting it would attribute a source nobody asked for, or collide // with a clear request and fail with no visible cause. const unsetSource = params.unsetSource === 'true' || params.unsetSource === true + const requestedSourceId = params.changeSourceId || toolCallArg(context, params.sourceId) const changeSourceId = - typeof params.changeSourceId === 'string' ? params.changeSourceId.trim() : '' + typeof requestedSourceId === 'string' ? requestedSourceId.trim() : '' result.sourceId = unsetSource || !changeSourceId ? undefined : changeSourceId if (unsetSource) result.unsetSource = true } diff --git a/apps/sim/blocks/blocks/athena.test.ts b/apps/sim/blocks/blocks/athena.test.ts new file mode 100644 index 00000000000..cdbee96774b --- /dev/null +++ b/apps/sim/blocks/blocks/athena.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, it } from 'vitest' +import { AthenaBlock } from '@/blocks/blocks/athena' + +/** + * An agent tool call sends model args under the tool's param names (`workGroup`, `queryStatement`, + * `name`) with the operation only on `context`; the handler forwards `{ ...args, ...mapped }`. + */ +const agentCall = (operation: string, args: Record): Record => ({ + ...args, + ...(AthenaBlock.tools.config?.params?.(args, { operation }) ?? {}), +}) + +const CREDENTIALS = { awsRegion: 'us-east-1', awsAccessKeyId: 'AKIA', awsSecretAccessKey: 'secret' } + +describe('AthenaBlock agent tool calls', () => { + it('keeps the model prepared statement workgroup and statement instead of throwing', () => { + expect( + agentCall('create_prepared_statement', { + ...CREDENTIALS, + statementName: 'by_day', + workGroup: 'primary', + queryStatement: 'SELECT * FROM t WHERE d = ?', + description: 'Daily rows', + }) + ).toMatchObject({ + statementName: 'by_day', + workGroup: 'primary', + queryStatement: 'SELECT * FROM t WHERE d = ?', + description: 'Daily rows', + }) + }) + + it('keeps the model catalog name and coerces maxResults on list calls', () => { + expect(agentCall('get_data_catalog', { ...CREDENTIALS, name: 'AwsDataCatalog' })).toMatchObject( + { name: 'AwsDataCatalog' } + ) + expect(agentCall('list_named_queries', { ...CREDENTIALS, maxResults: '5' })).toMatchObject({ + maxResults: 5, + }) + }) +}) diff --git a/apps/sim/blocks/blocks/athena.ts b/apps/sim/blocks/blocks/athena.ts index eb99711a3ca..a3b2d4580c2 100644 --- a/apps/sim/blocks/blocks/athena.ts +++ b/apps/sim/blocks/blocks/athena.ts @@ -1,7 +1,7 @@ import { AthenaIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' /** * Normalizes a switch value that may arrive as a boolean or as the strings 'true' / 'false'. @@ -681,8 +681,9 @@ Return ONLY a JSON array of strings — no explanations, no markdown code blocks throw new Error(`Invalid Athena operation: ${params.operation}`) } }, - params: (params) => { - const { operation, maxResults, ...rest } = params + params: (params, context) => { + const { maxResults, ...rest } = params + const operation = mapperOperation(params, context) const awsRegion = rest.awsRegion const awsAccessKeyId = rest.awsAccessKeyId @@ -696,6 +697,9 @@ Return ONLY a JSON array of strings — no explanations, no markdown code blocks rest.resultReuseMaxAgeInMinutes !== '' ? Number.parseInt(String(rest.resultReuseMaxAgeInMinutes), 10) : undefined + const queryName = rest.queryName || toolCallArg(context, rest.name) + const queryDescription = rest.queryDescription || toolCallArg(context, rest.description) + const workGroupName = rest.workGroupName || toolCallArg(context, rest.workGroup) switch (operation) { case 'start_query': @@ -766,7 +770,7 @@ Return ONLY a JSON array of strings — no explanations, no markdown code blocks } case 'create_named_query': { - if (!rest.queryName) { + if (!queryName) { throw new Error('Query name is required') } if (!rest.database) { @@ -779,10 +783,10 @@ Return ONLY a JSON array of strings — no explanations, no markdown code blocks awsRegion, awsAccessKeyId, awsSecretAccessKey, - name: rest.queryName, + name: queryName, database: rest.database, queryString: rest.queryString, - ...(rest.queryDescription && { description: rest.queryDescription }), + ...(queryDescription && { description: queryDescription }), ...(rest.workGroup && { workGroup: rest.workGroup }), } } @@ -879,7 +883,7 @@ Return ONLY a JSON array of strings — no explanations, no markdown code blocks if (!rest.namedQueryId) { throw new Error('Named query ID is required') } - if (!rest.queryName) { + if (!queryName) { throw new Error('Query name is required') } if (!rest.queryString) { @@ -888,64 +892,66 @@ Return ONLY a JSON array of strings — no explanations, no markdown code blocks return { ...connection, namedQueryId: rest.namedQueryId, - name: rest.queryName, + name: queryName, queryString: rest.queryString, - ...(rest.queryDescription && { description: rest.queryDescription }), + ...(queryDescription && { description: queryDescription }), } case 'create_prepared_statement': - case 'update_prepared_statement': + case 'update_prepared_statement': { + const queryStatement = rest.queryString || toolCallArg(context, rest.queryStatement) if (!rest.statementName) { throw new Error('Statement name is required') } - if (!rest.workGroupName) { + if (!workGroupName) { throw new Error('Workgroup is required') } - if (!rest.queryString) { + if (!queryStatement) { throw new Error('SQL query statement is required') } return { ...connection, statementName: rest.statementName, - workGroup: rest.workGroupName, - queryStatement: rest.queryString, - ...(rest.queryDescription && { description: rest.queryDescription }), + workGroup: workGroupName, + queryStatement, + ...(queryDescription && { description: queryDescription }), } + } case 'get_prepared_statement': case 'delete_prepared_statement': if (!rest.statementName) { throw new Error('Statement name is required') } - if (!rest.workGroupName) { + if (!workGroupName) { throw new Error('Workgroup is required') } return { ...connection, statementName: rest.statementName, - workGroup: rest.workGroupName, + workGroup: workGroupName, } case 'batch_get_prepared_statement': if (!rest.preparedStatementNames) { throw new Error('Statement names are required') } - if (!rest.workGroupName) { + if (!workGroupName) { throw new Error('Workgroup is required') } return { ...connection, preparedStatementNames: rest.preparedStatementNames, - workGroup: rest.workGroupName, + workGroup: workGroupName, } case 'list_prepared_statements': - if (!rest.workGroupName) { + if (!workGroupName) { throw new Error('Workgroup is required') } return { ...connection, - workGroup: rest.workGroupName, + workGroup: workGroupName, ...(parsedMaxResults !== undefined && { maxResults: parsedMaxResults }), ...(rest.nextToken && { nextToken: rest.nextToken }), } @@ -958,15 +964,17 @@ Return ONLY a JSON array of strings — no explanations, no markdown code blocks ...(rest.nextToken && { nextToken: rest.nextToken }), } - case 'get_data_catalog': - if (!rest.catalogName) { + case 'get_data_catalog': { + const catalogName = rest.catalogName || toolCallArg(context, rest.name) + if (!catalogName) { throw new Error('Data catalog name is required') } return { ...connection, - name: rest.catalogName, + name: catalogName, ...(rest.workGroup && { workGroup: rest.workGroup }), } + } case 'get_database': if (!rest.catalogName) { @@ -1008,10 +1016,10 @@ Return ONLY a JSON array of strings — no explanations, no markdown code blocks } case 'get_work_group': - if (!rest.workGroupName) { + if (!workGroupName) { throw new Error('Workgroup is required') } - return { ...connection, workGroup: rest.workGroupName } + return { ...connection, workGroup: workGroupName } default: throw new Error(`Invalid Athena operation: ${operation}`) diff --git a/apps/sim/blocks/blocks/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/azure_data_explorer.ts b/apps/sim/blocks/blocks/azure_data_explorer.ts index 8327179942c..a4955d44ce4 100644 --- a/apps/sim/blocks/blocks/azure_data_explorer.ts +++ b/apps/sim/blocks/blocks/azure_data_explorer.ts @@ -1,7 +1,7 @@ import { AzureDataExplorerIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' /** Every operation except the cluster-level database listing runs in a database. */ const DATABASE_SCOPED_OPERATIONS = [ @@ -423,7 +423,7 @@ export const AzureDataExplorerBlock: BlockConfig = { ], config: { tool: (params) => params.operation, - params: (params) => { + params: (params, context) => { const auth = { clusterUri: params.clusterUri, tenantId: params.tenantId, @@ -432,7 +432,7 @@ export const AzureDataExplorerBlock: BlockConfig = { resource: params.resource || undefined, } - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'azure_data_explorer_query': return { ...auth, @@ -467,9 +467,13 @@ export const AzureDataExplorerBlock: BlockConfig = { ...auth, database: params.database, table: params.table, - mode: params.ingestMode || undefined, + mode: params.ingestMode || toolCallArg(context, params.mode) || undefined, sourceQuery: params.sourceQuery, - async: toBoolean(params.ingestAsync), + async: + params.ingestAsync === false || params.ingestAsync === 'false' + ? undefined + : (toBoolean(params.ingestAsync) ?? + toBoolean(toolCallArg(context, params.async))), ingestionProperties: params.ingestionProperties || undefined, } case 'azure_data_explorer_create_table': diff --git a/apps/sim/blocks/blocks/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/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/brex.test.ts b/apps/sim/blocks/blocks/brex.test.ts new file mode 100644 index 00000000000..8cf7fd36f0f --- /dev/null +++ b/apps/sim/blocks/blocks/brex.test.ts @@ -0,0 +1,107 @@ +import { describe, expect, it } from 'vitest' +import { BrexBlock } from '@/blocks/blocks/brex' +import type { BlockToolParamsContext } from '@/blocks/types' + +/** Runs the mapper the way each executor path merges it over the incoming params. */ +function runMapper(params: Record, context?: BlockToolParamsContext) { + const mapper = BrexBlock.tools.config?.params + if (!mapper) throw new Error('Brex block has no params mapper') + return { ...params, ...mapper(params, context) } +} + +describe('Brex tool-call mapping', () => { + it('prefers the block cash account field over the model cash account', () => { + const sent = runMapper( + { + apiKey: 'token', + accountId: 'acct_block', + cashAccountId: 'acct_model', + vendorPaymentInstrumentId: 'pi_1', + amount: 5000, + description: 'Invoice 42', + externalMemo: 'Thanks', + }, + { operation: 'create_transfer' } + ) + expect(sent.cashAccountId).toBe('acct_block') + expect(sent.amount).toBe(5000) + }) + + it('keeps the model cash account on a tool call when the block field is blank', () => { + const sent = runMapper( + { + apiKey: 'token', + cashAccountId: 'acct_model', + vendorPaymentInstrumentId: 'pi_1', + amount: 5000, + description: 'Invoice 42', + externalMemo: 'Thanks', + }, + { operation: 'create_transfer' } + ) + expect(sent.cashAccountId).toBe('acct_model') + }) + + it('prefers the block spend limit name, period and members over the model args', () => { + const sent = runMapper( + { + apiKey: 'token', + resourceName: 'Travel', + name: 'Model name', + spendLimitPeriodRecurrenceType: 'PER_MONTH', + periodRecurrenceType: 'PER_YEAR', + spendLimitMemberUserIds: 'u1,u2', + memberUserIds: 'u9', + baseLimitAmount: 1000, + }, + { operation: 'create_spend_limit' } + ) + expect(sent).toMatchObject({ + name: 'Travel', + periodRecurrenceType: 'PER_MONTH', + memberUserIds: 'u1,u2', + baseLimitAmount: 1000, + }) + }) + + it('prefers the block vendor email and phone fields over the model args', () => { + const sent = runMapper( + { apiKey: 'token', vendorId: 'v1', vendorEmail: 'ap@vendor.com', vendorPhone: '555' }, + { operation: 'update_vendor' } + ) + expect(sent).toMatchObject({ email: 'ap@vendor.com', phone: '555' }) + }) + + it('keeps the model vendor email on a tool call when the block field is blank', () => { + const sent = runMapper( + { apiKey: 'token', companyName: 'Acme', email: 'model@vendor.com' }, + { operation: 'create_vendor' } + ) + expect(sent.email).toBe('model@vendor.com') + }) +}) + +describe('Brex canvas list filters never reach writes', () => { + it('drops a saved List Users email filter from a vendor write', () => { + const sent = runMapper({ + operation: 'update_vendor', + apiKey: 'token', + vendorId: 'v1', + companyName: 'Acme', + email: 'alice@corp.com', + }) + expect(sent.email).toBeUndefined() + }) + + it('drops a saved List Spend Limits member filter from a new spend limit', () => { + const sent = runMapper({ + operation: 'create_spend_limit', + apiKey: 'token', + resourceName: 'Travel', + spendLimitPeriodRecurrenceType: 'PER_MONTH', + baseLimitAmount: '1000', + memberUserIds: 'u1,u2', + }) + expect(sent.memberUserIds).toBeUndefined() + }) +}) diff --git a/apps/sim/blocks/blocks/brex.ts b/apps/sim/blocks/blocks/brex.ts index 51e119edd6e..81339f966f3 100644 --- a/apps/sim/blocks/blocks/brex.ts +++ b/apps/sim/blocks/blocks/brex.ts @@ -1,7 +1,12 @@ import { BrexIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput, withSavedCredential } from '@/blocks/utils' +import { + mapperOperation, + normalizeFileInput, + toolCallArg, + withSavedCredential, +} from '@/blocks/utils' /** Coerces a required money-amount field to a finite number, throwing on blank/non-numeric input rather than silently sending 0 or NaN to Brex. */ function toRequiredAmount(value: unknown, fieldLabel: string): number { @@ -640,7 +645,7 @@ export const BrexBlock: BlockConfig = { id: 'limitBufferPercentage', title: 'Limit Buffer Percentage', type: 'short-input', - placeholder: 'Flexible buffer on the limit as a 0-100 percentage', + placeholder: 'Flexible buffer on the limit as a whole-number percentage from 0 to 100', mode: 'advanced', condition: { field: 'operation', value: 'create_spend_limit' }, }, @@ -723,7 +728,7 @@ export const BrexBlock: BlockConfig = { wandConfig: { enabled: true, prompt: - 'Generate a comma-separated list of Brex expense payment statuses to filter by.\n\nValid statuses: NOT_STARTED, PROCESSING, CANCELED, DECLINED, CLEARED, REFUNDING, REFUNDED, CASH_ADVANCE, CREDITED, AWAITING_PAYMENT, SCHEDULED\n\nExamples:\n- "only cleared payments" -> CLEARED\n- "refunded or refunding" -> REFUNDED,REFUNDING\n\nReturn ONLY the comma-separated status values - no explanations, no extra text.', + 'Generate a comma-separated list of Brex expense payment statuses to filter by.\n\nValid statuses: NOT_STARTED, PROCESSING, CANCELED, DECLINED, CLEARED, REFUNDING, REFUNDED, CASH_ADVANCE, CREDITED, AWAITING_PAYMENT, SCHEDULED, HELD\n\nExamples:\n- "only cleared payments" -> CLEARED\n- "refunded or refunding" -> REFUNDED,REFUNDING\n\nReturn ONLY the comma-separated status values - no explanations, no extra text.', placeholder: 'Describe which payment statuses to include...', }, }, @@ -880,8 +885,9 @@ export const BrexBlock: BlockConfig = { ], config: { tool: (params) => `brex_${params.operation}`, - params: (params) => { - const { operation, apiKey } = params + params: (params, context) => { + const operation = mapperOperation(params, context) + const { apiKey } = params const result: Record = { apiKey } switch (operation) { @@ -943,7 +949,7 @@ export const BrexBlock: BlockConfig = { result.budgetId = params.budgetId break case 'create_budget': { - result.name = params.resourceName + result.name = params.resourceName || toolCallArg(context, params.name) result.description = params.description result.parentBudgetId = params.parentBudgetId result.periodRecurrenceType = params.periodRecurrenceType @@ -961,8 +967,10 @@ export const BrexBlock: BlockConfig = { result.spendLimitId = params.spendLimitId break case 'create_spend_limit': { - result.name = params.resourceName - result.periodRecurrenceType = params.spendLimitPeriodRecurrenceType + result.name = params.resourceName || toolCallArg(context, params.name) + result.periodRecurrenceType = + params.spendLimitPeriodRecurrenceType || + toolCallArg(context, params.periodRecurrenceType) result.spendType = params.spendType result.expenseVisibility = params.expenseVisibility result.authorizationVisibility = params.authorizationVisibility @@ -991,8 +999,8 @@ export const BrexBlock: BlockConfig = { if (transactionLimitAmount !== undefined) result.transactionLimitAmount = transactionLimitAmount if (params.ownerUserIds) result.ownerUserIds = params.ownerUserIds - if (params.spendLimitMemberUserIds) - result.memberUserIds = params.spendLimitMemberUserIds + result.memberUserIds = + params.spendLimitMemberUserIds || toolCallArg(context, params.memberUserIds) break } case 'get_vendor': @@ -1000,20 +1008,20 @@ export const BrexBlock: BlockConfig = { break case 'create_vendor': result.companyName = params.companyName - if (params.vendorEmail) result.email = params.vendorEmail - if (params.vendorPhone) result.phone = params.vendorPhone + result.email = params.vendorEmail || toolCallArg(context, params.email) + result.phone = params.vendorPhone || toolCallArg(context, params.phone) break case 'update_vendor': result.vendorId = params.vendorId if (params.companyName) result.companyName = params.companyName - if (params.vendorEmail) result.email = params.vendorEmail - if (params.vendorPhone) result.phone = params.vendorPhone + result.email = params.vendorEmail || toolCallArg(context, params.email) + result.phone = params.vendorPhone || toolCallArg(context, params.phone) break case 'get_transfer': result.transferId = params.transferId break case 'create_transfer': { - result.cashAccountId = params.accountId + result.cashAccountId = params.accountId || toolCallArg(context, params.cashAccountId) result.vendorPaymentInstrumentId = params.vendorPaymentInstrumentId result.amount = toRequiredAmount(params.amount, 'Amount') if (params.currency) result.currency = params.currency diff --git a/apps/sim/blocks/blocks/brightdata.test.ts b/apps/sim/blocks/blocks/brightdata.test.ts new file mode 100644 index 00000000000..db28714d8a9 --- /dev/null +++ b/apps/sim/blocks/blocks/brightdata.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from 'vitest' +import { BrightDataBlock } from '@/blocks/blocks/brightdata' + +const mapper = BrightDataBlock.tools.config?.params +if (!mapper) throw new Error('BrightDataBlock has no params mapper') +const mapToolParams = mapper + +/** + * Agent tool calls carry the operation only in `context` and key model args by the tool's + * param names; the result is spread over the merged params, as `buildBlockToolParamsTransform` does. + */ +const toolCall = (operation: string, merged: Record) => ({ + ...merged, + ...mapToolParams(merged, { operation }), +}) + +describe('BrightDataBlock tool calls', () => { + it('maps stored block fields and keeps the model dataset and URLs for sync scrape', () => { + const params = toolCall('sync_scrape', { + apiKey: 'key', + datasetId: 'gd_model', + urls: '[{"url":"https://example.com"}]', + syncFormat: 'csv', + }) + + expect(params.datasetId).toBe('gd_model') + expect(params.urls).toBe('[{"url":"https://example.com"}]') + expect(params.format).toBe('csv') + }) +}) diff --git a/apps/sim/blocks/blocks/brightdata.ts b/apps/sim/blocks/blocks/brightdata.ts index ea9ee0d21d9..60bc40eb46f 100644 --- a/apps/sim/blocks/blocks/brightdata.ts +++ b/apps/sim/blocks/blocks/brightdata.ts @@ -1,7 +1,7 @@ import { BrightDataIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' export const BrightDataBlock: BlockConfig = { type: 'brightdata', @@ -341,10 +341,10 @@ export const BrightDataBlock: BlockConfig = { ], config: { tool: (params) => `brightdata_${params.operation}`, - params: (params) => { + params: (params, context) => { const result: Record = { apiKey: params.apiKey } - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'scrape_url': result.zone = params.zone result.url = params.url @@ -363,7 +363,7 @@ export const BrightDataBlock: BlockConfig = { break case 'discover': - result.query = params.discoverQuery + result.query = params.discoverQuery ?? toolCallArg(context, params.query) if (params.numResults) result.numResults = Number(params.numResults) if (params.mode) result.mode = params.mode if (params.intent) result.intent = params.intent @@ -374,8 +374,8 @@ export const BrightDataBlock: BlockConfig = { break case 'sync_scrape': - result.datasetId = params.syncDatasetId - result.urls = params.syncUrls + result.datasetId = params.syncDatasetId ?? toolCallArg(context, params.datasetId) + result.urls = params.syncUrls ?? toolCallArg(context, params.urls) if (params.syncFormat) result.format = params.syncFormat if (params.syncIncludeErrors != null) result.includeErrors = params.syncIncludeErrors break diff --git a/apps/sim/blocks/blocks/buffer.test.ts b/apps/sim/blocks/blocks/buffer.test.ts new file mode 100644 index 00000000000..0e371573abb --- /dev/null +++ b/apps/sim/blocks/blocks/buffer.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from 'vitest' +import { BufferBlock } from '@/blocks/blocks/buffer' + +const mapper = BufferBlock.tools.config?.params +if (!mapper) throw new Error('BufferBlock has no params mapper') +const mapToolParams = mapper + +describe('BufferBlock tool calls', () => { + it('turns the default share mode into addToQueue when creating a post', () => { + const merged = { apiKey: 'key', channelId: 'ch_1', text: 'Hello', mode: 'default' } + const params: Record = { + ...merged, + ...mapToolParams(merged, { operation: 'create_post' }), + } + + expect(params.mode).toBe('addToQueue') + expect(params.schedulingType).toBeUndefined() + }) +}) diff --git a/apps/sim/blocks/blocks/buffer.ts b/apps/sim/blocks/blocks/buffer.ts index b1704172957..9a275f5a3be 100644 --- a/apps/sim/blocks/blocks/buffer.ts +++ b/apps/sim/blocks/blocks/buffer.ts @@ -1,7 +1,7 @@ import { BufferIcon } from '@/components/icons' import type { BlockConfig, BlockMeta, SubBlockConfig } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput, withSavedCredential } from '@/blocks/utils' +import { mapperOperation, normalizeFileInput, withSavedCredential } from '@/blocks/utils' import { getToolMetadata } from '@/tools/metadata' const POST_EDIT_OPS = ['create_post', 'edit_post'] @@ -658,7 +658,8 @@ export const BufferBlock: BlockConfig = { ], config: { tool: (params) => `buffer_${params.operation}`, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const result: Record = {} for (const [key, value] of Object.entries(params)) { if ( @@ -674,7 +675,7 @@ export const BufferBlock: BlockConfig = { } if ((key === 'mode' || key === 'schedulingType') && value === 'default') { result[key] = - params.operation === 'create_post' + operation === 'create_post' ? key === 'mode' ? 'addToQueue' : 'automatic' @@ -699,7 +700,7 @@ export const BufferBlock: BlockConfig = { throw new Error('Choose one media input: uploaded/reference file or public URL') if (params.assets && (normalizedMedia || mediaUrl)) throw new Error('Choose assets or a single media input') - if (params.operation === 'edit_post' && params.clearText === true) result.text = null + if (operation === 'edit_post' && params.clearText === true) result.text = null if (normalizedMedia) { result.media = normalizedMedia } else if (mediaUrl) { diff --git a/apps/sim/blocks/blocks/calcom.test.ts b/apps/sim/blocks/blocks/calcom.test.ts new file mode 100644 index 00000000000..1f8f272b866 --- /dev/null +++ b/apps/sim/blocks/blocks/calcom.test.ts @@ -0,0 +1,110 @@ +import { describe, expect, it } from 'vitest' +import { CalComBlock } from '@/blocks/blocks/calcom' +import type { BlockToolParamsContext } from '@/blocks/types' + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = CalComBlock.tools.config?.params + if (!mapper) throw new Error('Cal.com block has no params mapper') + return mapper(params, context) +} + +/** What the tool receives: the mapper output spread over the params it was given. */ +function sentParams(params: Record, context?: BlockToolParamsContext) { + return { ...params, ...mapParams(params, context) } +} + +describe('Cal.com create booking on a tool call', () => { + it('lets pinned attendee fields win over the model attendee and keeps the rest', () => { + const sent = sentParams( + { + attendeeName: 'Pinned Name', + attendeeTimeZone: 'Europe/London', + attendee: { name: 'Model Name', email: 'model@x.com', timeZone: 'UTC' }, + eventTypeId: 123, + start: '2026-01-15T10:00:00Z', + }, + { operation: 'calcom_create_booking' } + ) + + expect(sent.attendee).toEqual({ + name: 'Pinned Name', + email: 'model@x.com', + timeZone: 'Europe/London', + }) + expect(sent.eventTypeId).toBe(123) + }) + + it('splits pinned comma-separated guests into an array', () => { + const sent = sentParams( + { guests: 'a@x.com, b@y.com', attendee: { name: 'A', timeZone: 'UTC' } }, + { operation: 'calcom_create_booking' } + ) + expect(sent.guests).toEqual(['a@x.com', 'b@y.com']) + }) +}) + +describe('Cal.com create booking on the canvas', () => { + it('accepts guests that already resolved to an array', () => { + const sent = sentParams({ + operation: 'calcom_create_booking', + attendeeName: 'A', + attendeeTimeZone: 'UTC', + guests: ['a@x.com'], + }) + expect(sent.guests).toEqual(['a@x.com']) + }) +}) + +describe('Cal.com list bookings', () => { + it('sends the pinned status instead of the model status on a tool call', () => { + const sent = sentParams( + { bookingStatus: 'past', status: 'upcoming' }, + { operation: 'calcom_list_bookings' } + ) + expect(sent.status).toBe('past') + }) + + it('keeps the model status and attendee filter when nothing is pinned', () => { + const sent = sentParams( + { status: 'upcoming', attendeeEmail: 'a@x.com', take: 5 }, + { operation: 'calcom_list_bookings' } + ) + expect(sent.status).toBe('upcoming') + expect(sent.attendeeEmail).toBe('a@x.com') + expect(sent.take).toBe(5) + }) + + it('does not filter by an attendee email left over from Create Booking on the canvas', () => { + const sent = sentParams({ + operation: 'calcom_list_bookings', + attendeeEmail: 'stale@x.com', + take: '10', + }) + expect(sent.attendeeEmail).toBeUndefined() + expect(sent.take).toBe(10) + }) + + it.each([null, ''])('drops blank advanced limit and offset (%j) on the canvas', (blank) => { + const sent = sentParams({ operation: 'calcom_list_bookings', take: blank, skip: blank }) + expect(sent.take).toBeUndefined() + expect(sent.skip).toBeUndefined() + }) +}) + +describe('Cal.com event type id on a tool call', () => { + it('uses the event type picked in the tool row', () => { + const sent = sentParams( + { eventTypeIdParam: '42', eventTypeId: 7 }, + { operation: 'calcom_get_event_type' } + ) + expect(sent.eventTypeId).toBe(42) + }) + + it('keeps the model event type id and fields on an update with nothing pinned', () => { + const sent = sentParams( + { eventTypeId: 7, lengthInMinutes: 45, scheduleId: 3 }, + { operation: 'calcom_update_event_type' } + ) + expect(sent).toMatchObject({ eventTypeId: 7, lengthInMinutes: 45, scheduleId: 3 }) + }) +}) diff --git a/apps/sim/blocks/blocks/calcom.ts b/apps/sim/blocks/blocks/calcom.ts index 3f7d0b4f09d..41233d0a1de 100644 --- a/apps/sim/blocks/blocks/calcom.ts +++ b/apps/sim/blocks/blocks/calcom.ts @@ -1,6 +1,8 @@ +import { isPlainRecord } from '@sim/utils/object' import { CalComIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' import { getTrigger } from '@/triggers' const EVENT_TYPE_FIELD = ['eventTypeSelector', 'eventTypeId'] as const @@ -350,6 +352,58 @@ Return ONLY the IANA timezone string - no explanations or quotes.`, ], condition: { field: 'operation', value: 'calcom_list_bookings' }, }, + { + id: 'filterAttendeeEmail', + title: 'Attendee Email', + type: 'short-input', + placeholder: 'Only bookings with this attendee', + condition: { field: 'operation', value: 'calcom_list_bookings' }, + mode: 'advanced', + }, + { + id: 'afterStart', + title: 'Starts After', + type: 'short-input', + placeholder: 'ISO 8601 (e.g., 2024-01-15T00:00:00Z)', + condition: { field: 'operation', value: 'calcom_list_bookings' }, + mode: 'advanced', + }, + { + id: 'beforeEnd', + title: 'Ends Before', + type: 'short-input', + placeholder: 'ISO 8601 (e.g., 2024-01-22T00:00:00Z)', + condition: { field: 'operation', value: 'calcom_list_bookings' }, + mode: 'advanced', + }, + { + id: 'sortStart', + title: 'Sort by Start', + type: 'dropdown', + options: [ + { label: 'None', id: '' }, + { label: 'Ascending', id: 'asc' }, + { label: 'Descending', id: 'desc' }, + ], + condition: { field: 'operation', value: 'calcom_list_bookings' }, + mode: 'advanced', + }, + { + id: 'take', + title: 'Limit', + type: 'short-input', + placeholder: 'Bookings to return (default 100)', + condition: { field: 'operation', value: 'calcom_list_bookings' }, + mode: 'advanced', + }, + { + id: 'skip', + title: 'Offset', + type: 'short-input', + placeholder: 'Bookings to skip (default 0)', + condition: { field: 'operation', value: 'calcom_list_bookings' }, + mode: 'advanced', + }, // Event Type fields { @@ -712,9 +766,9 @@ Return ONLY valid JSON - no explanations.`, ], config: { tool: (params) => params.operation || 'calcom_list_bookings', - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { - operation, oauthCredential, attendeeName, attendeeEmail, @@ -745,6 +799,11 @@ Return ONLY valid JSON - no explanations.`, duration, metadata, availability, + attendee, + status, + filterAttendeeEmail, + take, + skip, ...rest } = params @@ -759,12 +818,23 @@ Return ONLY valid JSON - no explanations.`, } switch (operation) { - case 'calcom_create_booking': - result.attendee = { - name: attendeeName, - ...(attendeeEmail && { email: attendeeEmail }), - timeZone: attendeeTimeZone, - ...(attendeePhone && { phoneNumber: attendeePhone }), + case 'calcom_create_booking': { + const modelAttendee = toolCallArg(context, attendee) + if (isPlainRecord(modelAttendee)) { + const pinned = Object.entries({ + name: attendeeName, + email: attendeeEmail, + timeZone: attendeeTimeZone, + phoneNumber: attendeePhone, + }).filter(([, value]) => value !== undefined && value !== null && value !== '') + result.attendee = { ...modelAttendee, ...Object.fromEntries(pinned) } + } else if (modelAttendee === undefined || attendeeName || attendeeTimeZone) { + result.attendee = { + name: attendeeName, + ...(attendeeEmail && { email: attendeeEmail }), + timeZone: attendeeTimeZone, + ...(attendeePhone && { phoneNumber: attendeePhone }), + } } { const eventTypeIdNum = toNumber(eventTypeId) @@ -772,7 +842,13 @@ Return ONLY valid JSON - no explanations.`, } if (start) result.start = start if (end) result.end = end - if (guests) result.guests = guests.split(',').map((g: string) => g.trim()) + if (guests) { + result.guests = Array.isArray(guests) + ? guests + : String(guests) + .split(',') + .map((g: string) => g.trim()) + } { const lengthNum = toNumber(lengthInMinutes) if (lengthNum !== undefined) result.lengthInMinutes = lengthNum @@ -785,6 +861,7 @@ Return ONLY valid JSON - no explanations.`, } } break + } case 'calcom_cancel_booking': if (bookingUid) result.bookingUid = bookingUid @@ -797,20 +874,28 @@ Return ONLY valid JSON - no explanations.`, if (reschedulingReason) result.reschedulingReason = reschedulingReason break - case 'calcom_list_bookings': - if (bookingStatus) result.status = bookingStatus + case 'calcom_list_bookings': { + const statusFilter = bookingStatus || toolCallArg(context, status) + if (statusFilter) result.status = statusFilter + result.attendeeEmail = filterAttendeeEmail || toolCallArg(context, attendeeEmail) + result.take = toNumber(take) + result.skip = toNumber(skip) break + } case 'calcom_create_event_type': case 'calcom_update_event_type': { if (operation === 'calcom_update_event_type') { - const eventTypeIdNum = toNumber(eventTypeIdParam) + const eventTypeIdNum = + toNumber(eventTypeIdParam) ?? toolCallArg(context, toNumber(eventTypeId)) if (eventTypeIdNum !== undefined) result.eventTypeId = eventTypeIdNum } - const lengthNum = toNumber(eventLength) + const lengthNum = + toNumber(eventLength) ?? toolCallArg(context, toNumber(lengthInMinutes)) if (lengthNum !== undefined) result.lengthInMinutes = lengthNum - const scheduleIdNum = toNumber(eventTypeScheduleId) + const scheduleIdNum = + toNumber(eventTypeScheduleId) ?? toolCallArg(context, toNumber(scheduleId)) if (scheduleIdNum !== undefined) result.scheduleId = scheduleIdNum const slotIntervalNum = toNumber(slotInterval) if (slotIntervalNum !== undefined) result.slotInterval = slotIntervalNum @@ -829,7 +914,8 @@ Return ONLY valid JSON - no explanations.`, case 'calcom_get_event_type': case 'calcom_delete_event_type': { - const eventTypeIdNum = toNumber(eventTypeIdParam) + const eventTypeIdNum = + toNumber(eventTypeIdParam) ?? toolCallArg(context, toNumber(eventTypeId)) if (eventTypeIdNum !== undefined) result.eventTypeId = eventTypeIdNum } break @@ -943,9 +1029,24 @@ Return ONLY valid JSON - no explanations.`, eventTypeSlug: { type: 'string', description: 'Event type slug' }, username: { type: 'string', description: 'Cal.com username' }, duration: { type: 'number', description: 'Slot duration in minutes' }, + filterAttendeeEmail: { type: 'string', description: 'List Bookings attendee email filter' }, + afterStart: { type: 'string', description: 'List bookings starting after this time' }, + beforeEnd: { type: 'string', description: 'List bookings ending before this time' }, + sortStart: { type: 'string', description: 'Sort bookings by start time (asc or desc)' }, + take: { type: 'number', description: 'Number of bookings to return' }, + skip: { type: 'number', description: 'Number of bookings to skip' }, }, outputs: { success: { type: 'boolean', description: 'Whether operation succeeded' }, + data: { + type: 'json', + description: + 'Cal.com response data: a booking, event type, or schedule object, an array of them for list operations, or the slots map keyed by date (YYYY-MM-DD) for Get Available Slots', + }, + pagination: { + type: 'json', + description: 'List Bookings pagination (totalItems, remainingItems, hasNextPage, ...)', + }, bookingUid: { type: 'string', description: 'Booking unique identifier' }, bookingId: { type: 'number', description: 'Booking ID' }, status: { type: 'string', description: 'Booking or event status' }, diff --git a/apps/sim/blocks/blocks/calendly.test.ts b/apps/sim/blocks/blocks/calendly.test.ts new file mode 100644 index 00000000000..ae78571412d --- /dev/null +++ b/apps/sim/blocks/blocks/calendly.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from 'vitest' +import { CalendlyBlock } from '@/blocks/blocks/calendly' +import type { BlockToolParamsContext } from '@/blocks/types' +import { listEventTypesTool } from '@/tools/calendly/list_event_types' +import type { ToolConfig } from '@/tools/types' + +/** + * Assertions run against `{ ...inputs, ...mapper(inputs, context) }`, the shape both the canvas + * handler and the tool-call transform forward: a key the mapper leaves out keeps its raw value. + */ +describe('CalendlyBlock params mapper', () => { + const mapper = CalendlyBlock.tools.config?.params + if (!mapper) throw new Error('CalendlyBlock is missing its params mapper') + + const resolve = (inputs: Record, context?: BlockToolParamsContext) => ({ + ...inputs, + ...mapper(inputs, context), + }) + + const eventTypesUrl = (params: Record) => { + const tool: ToolConfig = listEventTypesTool + const url = tool.request.url + if (typeof url !== 'function') throw new Error('Expected a url builder') + return url(params) + } + + it('lists all event types on the canvas when the Active Only switch was turned off', () => { + const params = resolve({ + operation: 'calendly_list_event_types', + apiKey: 'k', + user: 'user-1', + active: false, + }) + + expect(eventTypesUrl(params)).not.toContain('active=') + }) + + it('lists all event types on a tool call whose stored row has the switch off', () => { + const params = resolve( + { apiKey: 'k', user: 'user-1', active: false }, + { operation: 'calendly_list_event_types' } + ) + + expect(eventTypesUrl(params)).not.toContain('active=') + }) + + it('still filters to active event types when the switch is on', () => { + const params = resolve({ + operation: 'calendly_list_event_types', + apiKey: 'k', + user: 'user-1', + active: true, + }) + + expect(eventTypesUrl(params)).toContain('active=true') + }) +}) diff --git a/apps/sim/blocks/blocks/calendly.ts b/apps/sim/blocks/blocks/calendly.ts index 2f4a57f06c4..8187514d98e 100644 --- a/apps/sim/blocks/blocks/calendly.ts +++ b/apps/sim/blocks/blocks/calendly.ts @@ -34,7 +34,7 @@ export const CalendlyBlock: BlockConfig = { authMode: AuthMode.ApiKey, triggerAllowed: true, longDescription: - 'Manage event types, scheduled events, invitees, and webhooks. Trigger workflows based on Calendly webhook events (invitee scheduled, invitee canceled, routing form submitted). Requires Personal Access Token.', + 'Manage event types, scheduled events, invitees, bookings, availability, and routing forms. Trigger workflows based on Calendly webhook events (invitee scheduled, invitee canceled, routing form submitted). Requires Personal Access Token.', docsLink: 'https://docs.sim.ai/integrations/calendly', category: 'tools', integrationType: IntegrationType.Productivity, @@ -445,9 +445,43 @@ Return ONLY the timestamp string in ISO 8601 format - no explanations, no quotes prompt: 'Generate a JSON array of guest email address strings, for example ["guest@example.com"]. Return ONLY the JSON array - no explanations, no extra text.', placeholder: 'Describe the guests to copy on the invite...', + generationType: 'json-array', + }, + }, + { + id: 'location', + title: 'Location', + type: 'long-input', + placeholder: '{"kind": "outbound_call", "location": "+14155551234"}', + description: + 'Must match a location on the event type. Leave empty for round robin event types.', + mode: 'advanced', + condition: { field: 'operation', value: 'calendly_create_event_invitee' }, + wandConfig: { + enabled: true, + prompt: + 'Generate a Calendly invitee location JSON object with a "kind" (physical, inbound_call, outbound_call, zoom_conference, google_conference, gotomeeting_conference, microsoft_teams_conference, webex_conference, ask_invitee, or custom) and, for physical, outbound_call, ask_invitee, and custom, a "location" string. Return ONLY the JSON object - no explanations, no extra text.', + placeholder: 'Describe where the meeting takes place...', generationType: 'json-object', }, }, + { + id: 'questionsAndAnswers', + title: 'Questions and Answers', + type: 'long-input', + placeholder: '[{"question": "Company", "answer": "Acme", "position": 0}]', + description: + "Answers to the event type's booking questions. Questions must match exactly; required ones must be answered.", + mode: 'advanced', + condition: { field: 'operation', value: 'calendly_create_event_invitee' }, + wandConfig: { + enabled: true, + prompt: + 'Generate a JSON array of Calendly booking answers, each an object with "question" (the exact question text), "answer", and "position" (the question\'s zero-based order). Return ONLY the JSON array - no explanations, no extra text.', + placeholder: 'Describe the answers to the booking questions...', + generationType: 'json-array', + }, + }, { id: 'inviteeUri', title: 'Invitee URI', @@ -583,8 +617,8 @@ Return ONLY the timestamp string in ISO 8601 format - no explanations, no quotes return { ...rest, - // The switch cannot express "inactive only", so off means unfiltered, not `active=false`. - ...(active === true && { active: true }), + // Off means unfiltered, not `active=false`; always written so it overrides the raw input. + active: active === true ? true : undefined, ...(events !== undefined && { events: parseJsonArray(events, 'events') }), ...(eventGuests !== undefined && { eventGuests: parseJsonArray(eventGuests, 'eventGuests'), @@ -621,6 +655,11 @@ Return ONLY the timestamp string in ISO 8601 format - no explanations, no quotes inviteeTimezone: { type: 'string', description: 'Timezone of the invitee' }, textReminderNumber: { type: 'string', description: 'Phone number for SMS reminders' }, eventGuests: { type: 'json', description: 'Array of additional guest email addresses' }, + location: { type: 'json', description: 'Meeting location ({kind, location})' }, + questionsAndAnswers: { + type: 'json', + description: 'Answers to booking questions ([{question, answer, position}])', + }, role: { type: 'string', description: 'Filter memberships by role' }, formUri: { type: 'string', description: 'Routing form UUID or URI' }, count: { type: 'number', description: 'Results per page' }, @@ -803,7 +842,7 @@ export const CalendlyV2Block: BlockConfig = { hideFromToolbar: false, sunset: undefined, longDescription: - 'Manage event types, scheduled events, invitees, and webhooks. Trigger workflows based on Calendly webhook events (invitee scheduled, invitee canceled, routing form submitted).', + 'Manage event types, scheduled events, invitees, bookings, availability, and routing forms. Trigger workflows based on Calendly webhook events (invitee scheduled, invitee canceled, routing form submitted).', ...withSavedCredential(CalendlyBlock, { id: 'credential', type: 'oauth-input', diff --git a/apps/sim/blocks/blocks/cbinsights.test.ts b/apps/sim/blocks/blocks/cbinsights.test.ts index d581a6c0f34..2713ade0fcd 100644 --- a/apps/sim/blocks/blocks/cbinsights.test.ts +++ b/apps/sim/blocks/blocks/cbinsights.test.ts @@ -101,4 +101,12 @@ describe('CbInsightsBlock', () => { expect(maturity.startDate).toBe('2025-01-01') expect(maturity.endDate).toBe('2025-06-01') }) + + it('keeps model filters on a firmographics tool call, which carries no operation in params', () => { + const merged = { clientId: 'id', clientSecret: 'secret', keyword: 'fintech', orgIds: [1, 2] } + const params = { ...merged, ...buildParams(merged, { operation: 'search_firmographics' }) } + + expect(params.keyword).toBe('fintech') + expect(params.orgIds).toEqual([1, 2]) + }) }) diff --git a/apps/sim/blocks/blocks/cbinsights.ts b/apps/sim/blocks/blocks/cbinsights.ts index d7d73cbaaf1..1eaea4770b3 100644 --- a/apps/sim/blocks/blocks/cbinsights.ts +++ b/apps/sim/blocks/blocks/cbinsights.ts @@ -2,7 +2,7 @@ import { Building, ListChecks, Search, Sparkles, Sprout, Users } from '@sim/emcn import { CbInsightsIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' /** Operations that take a single organization ID on the path. */ const ORG_OPERATIONS = [ @@ -654,8 +654,8 @@ export const CbInsightsBlock: BlockConfig = { * advanced field is serialized on non-emptiness alone, even while the UI * hides it. `undefined` is what actually drops one. */ - params: (params) => { - const operation = String(params.operation ?? '') + params: (params, context) => { + const operation = mapperOperation(params, context) const isOrg = (ORG_OPERATIONS as readonly string[]).includes(operation) const isOrgList = (ORG_LIST_OPERATIONS as readonly string[]).includes(operation) const isFirmographics = operation === 'search_firmographics' @@ -670,11 +670,15 @@ export const CbInsightsBlock: BlockConfig = { clientId: params.clientId, clientSecret: params.clientSecret, orgId: isOrg ? params.orgId : undefined, - orgIds: isOrgList ? params.orgIds : firmographic(params.orgIdFilter), + orgIds: isOrgList + ? params.orgIds + : firmographic(params.orgIdFilter ?? toolCallArg(context, params.orgIds)), message: isAi ? params.message : undefined, chatId: isChat ? params.chatId : undefined, names: isLookup ? params.names : undefined, - urls: isLookup ? params.urls : firmographic(params.firmographicsUrls), + urls: isLookup + ? params.urls + : firmographic(params.firmographicsUrls ?? toolCallArg(context, params.urls)), profileUrl: isLookup ? params.profileUrl : undefined, keyword: firmographic(params.keyword), orgNames: firmographic(params.orgNames), diff --git a/apps/sim/blocks/blocks/checkr.test.ts b/apps/sim/blocks/blocks/checkr.test.ts new file mode 100644 index 00000000000..4a7444ceb54 --- /dev/null +++ b/apps/sim/blocks/blocks/checkr.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from 'vitest' +import { CheckrBlock } from '@/blocks/blocks/checkr' + +const mapper = CheckrBlock.tools.config?.params +if (!mapper) throw new Error('CheckrBlock has no params mapper') +const mapToolParams = mapper + +/** + * Agent tool calls carry the operation only in `context` and key model args by the tool's + * param names; the result is spread over the merged params, as `buildBlockToolParamsTransform` does. + */ +const toolCall = (operation: string, merged: Record) => ({ + ...merged, + ...mapToolParams(merged, { operation }), +}) + +describe('CheckrBlock tool calls', () => { + it('sends the stored report tags when ordering a report', () => { + const params = toolCall('create_report', { + apiKey: 'key', + candidateId: 'cand_1', + package: 'basic', + reportTags: 'urgent, onsite', + }) + + expect(params.tags).toEqual(['urgent', 'onsite']) + }) + + it('keeps the model node and work locations when updating a continuous check', () => { + const params = toolCall('update_continuous_check', { + apiKey: 'key', + continuousCheckId: 'cc_1', + node: 'node_1', + workLocations: [{ country: 'US', state: 'CA' }], + }) + + expect(params.node).toBe('node_1') + expect(params.workLocations).toEqual([{ country: 'US', state: 'CA' }]) + }) +}) diff --git a/apps/sim/blocks/blocks/checkr.ts b/apps/sim/blocks/blocks/checkr.ts index 5fad3954ed3..3c97794fa9a 100644 --- a/apps/sim/blocks/blocks/checkr.ts +++ b/apps/sim/blocks/blocks/checkr.ts @@ -1,6 +1,6 @@ import { CheckrIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' import { getTrigger } from '@/triggers' const CANDIDATE_ID_REQUIRED_OPS = [ @@ -1271,7 +1271,8 @@ export const CheckrBlock: BlockConfig = { ], config: { tool: (params) => `checkr_${params.operation}`, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { candidateAdjudication, reportAdjudication, @@ -1293,18 +1294,21 @@ export const CheckrBlock: BlockConfig = { } = params const result: Record = { ...rest } - if (params.operation === 'create_invitation' || params.operation === 'create_report') { - result.tags = toStringList(reportTags) + if (operation === 'create_invitation' || operation === 'create_report') { + result.tags = toStringList(reportTags ?? toolCallArg(context, rest.tags)) } else { result.tags = toStringList(rest.tags) } - if (params.operation === 'list_candidates') { - result.geoId = filterGeoId || undefined - result.programId = filterProgramId || undefined + if (operation === 'list_candidates') { + result.geoId = filterGeoId || toolCallArg(context, rest.geoId) || undefined + result.programId = filterProgramId || toolCallArg(context, rest.programId) || undefined } - if (params.operation === 'update_continuous_check') { - result.node = continuousCheckNode || undefined - result.workLocations = toJsonArray(continuousCheckWorkLocations, 'work locations') + if (operation === 'update_continuous_check') { + result.node = continuousCheckNode || toolCallArg(context, rest.node) || undefined + result.workLocations = toJsonArray( + continuousCheckWorkLocations ?? toolCallArg(context, rest.workLocations), + 'work locations' + ) } else { result.workLocations = toJsonArray(rest.workLocations, 'work locations') } @@ -1314,10 +1318,9 @@ export const CheckrBlock: BlockConfig = { result.selfDisclosures = toJsonArray(rest.selfDisclosures, 'self disclosures') const adjudication = - params.operation === 'update_report' ? reportAdjudication : candidateAdjudication + operation === 'update_report' ? reportAdjudication : candidateAdjudication if (adjudication) result.adjudication = adjudication - const status = - params.operation === 'list_subscriptions' ? subscriptionStatus : invitationStatus + const status = operation === 'list_subscriptions' ? subscriptionStatus : invitationStatus if (status) result.status = status const noMiddle = toOptionalBoolean(noMiddleName) diff --git a/apps/sim/blocks/blocks/circleback.test.ts b/apps/sim/blocks/blocks/circleback.test.ts new file mode 100644 index 00000000000..69eb152b182 --- /dev/null +++ b/apps/sim/blocks/blocks/circleback.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest' +import { CirclebackBlock } from '@/blocks/blocks/circleback' + +/** + * A tool call merges the stored row with the model's args (keyed by tool param names) and spreads + * the mapper result over them; the operation arrives only in `context`. + */ +const toolCall = (args: Record, operation: string) => ({ + ...args, + ...CirclebackBlock.tools.config?.params?.(args, { operation }), +}) + +describe('CirclebackBlock tool calls', () => { + it('sends the stored action-item filters under the tool param names', () => { + const params = toolCall( + { statusFilter: 'DONE', assigneeFilterProfileId: 'profile-1' }, + 'list_action_items' + ) + expect(params.status).toBe('DONE') + expect(params.assigneeProfileId).toBe('profile-1') + }) +}) diff --git a/apps/sim/blocks/blocks/circleback.ts b/apps/sim/blocks/blocks/circleback.ts index 40a8007ddda..58c24542757 100644 --- a/apps/sim/blocks/blocks/circleback.ts +++ b/apps/sim/blocks/blocks/circleback.ts @@ -1,7 +1,7 @@ import { ClipboardList, Table } from '@sim/emcn/icons' import { CirclebackIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, withSavedCredential } from '@/blocks/utils' import { getTrigger } from '@/triggers' export const CirclebackBlock: BlockConfig = { @@ -452,18 +452,19 @@ export const CirclebackBlock: BlockConfig = { ], config: { tool: (params) => `circleback_${params.operation}`, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) /* Filter variants live on their own subBlocks so an operation switch cannot leak a mutation input into a list filter; remap them onto the tool param names here. */ const result: Record = {} - if (params.operation === 'list_action_items') { + if (operation === 'list_action_items') { if (params.statusFilter) result.status = params.statusFilter if (params.assigneeFilterProfileId) { result.assigneeProfileId = params.assigneeFilterProfileId } } - if (params.operation === 'search_meetings' && params.searchMeetingIds) { + if (operation === 'search_meetings' && params.searchMeetingIds) { result.meetingIds = params.searchMeetingIds } return result diff --git a/apps/sim/blocks/blocks/clerk.test.ts b/apps/sim/blocks/blocks/clerk.test.ts new file mode 100644 index 00000000000..02cff4fc4d3 --- /dev/null +++ b/apps/sim/blocks/blocks/clerk.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest' +import { ClerkBlock } from '@/blocks/blocks/clerk' + +/** + * A tool call merges the stored row with the model's args (keyed by tool param names) and spreads + * the mapper result over them; the operation arrives only in `context`. + */ +const toolCall = (args: Record, operation: string) => ({ + ...args, + ...ClerkBlock.tools.config?.params?.(args, { operation }), +}) + +describe('ClerkBlock tool calls', () => { + it('parses metadata the model sends as a JSON string', () => { + const params = toolCall( + { secretKey: 'sk', emailAddress: ['a@example.com'], publicMetadata: '{"plan":"pro"}' }, + 'clerk_create_user' + ) + expect(params.publicMetadata).toEqual({ plan: 'pro' }) + expect(params.emailAddress).toEqual(['a@example.com']) + }) +}) diff --git a/apps/sim/blocks/blocks/clerk.ts b/apps/sim/blocks/blocks/clerk.ts index f0cd40bec9b..be1ad8d9917 100644 --- a/apps/sim/blocks/blocks/clerk.ts +++ b/apps/sim/blocks/blocks/clerk.ts @@ -1,7 +1,7 @@ import { ClerkIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, withSavedCredential } from '@/blocks/utils' import { getTrigger } from '@/triggers' /** @@ -820,9 +820,9 @@ export const ClerkBlock: BlockConfig = { ], config: { tool: (params) => params.operation as string, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { - operation, secretKey, emailAddressFilter, usernameFilter, diff --git a/apps/sim/blocks/blocks/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/cloudflare.test.ts b/apps/sim/blocks/blocks/cloudflare.test.ts index 320d41cb2dc..ac1de8b7123 100644 --- a/apps/sim/blocks/blocks/cloudflare.test.ts +++ b/apps/sim/blocks/blocks/cloudflare.test.ts @@ -233,3 +233,40 @@ describe('Cloudflare migration convergence', () => { expect(second.blocks['block-1'].subBlocks.recordProxied?.value).toBe('true') }) }) + +/** + * An agent tool call sends model args under the tool's param names (`type`, `files`) with the + * operation only on `context`; the handler forwards `{ ...args, ...mapped }`. + */ +describe('Cloudflare agent tool calls', () => { + const agentCall = ( + operation: string, + args: Record + ): Record => ({ + ...args, + ...CloudflareBlock.tools.config?.params?.(args, { operation }), + }) + + it('keeps the model record type that the canvas reads from an alias subBlock', () => { + expect( + agentCall('create_dns_record', { + ...CREDENTIALS, + zoneId: 'zone-1', + type: 'CNAME', + name: 'app.example.com', + content: 'origin.example.com', + }) + ).toMatchObject({ type: 'CNAME' }) + }) + + it('drops file targets when the model purges everything', () => { + expect( + agentCall('purge_cache', { + ...CREDENTIALS, + zoneId: 'zone-1', + purge_everything: true, + files: 'https://example.com/a.css', + }).files + ).toBeUndefined() + }) +}) diff --git a/apps/sim/blocks/blocks/cloudflare.ts b/apps/sim/blocks/blocks/cloudflare.ts index b1b6ce473b2..fe3a894c7df 100644 --- a/apps/sim/blocks/blocks/cloudflare.ts +++ b/apps/sim/blocks/blocks/cloudflare.ts @@ -1,6 +1,6 @@ import { CloudflareIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { isToolCall, mapperOperation, withSavedCredential } from '@/blocks/utils' /** Advanced inputs serialize before conditions; separate aliases prevent hidden values crossing operations. */ const SUBBLOCK_ALIASES: Record> = { @@ -4521,11 +4521,16 @@ export const CloudflareBlock: BlockConfig = { ], config: { tool: (params) => `cloudflare_${params.operation}`, - params: (params) => { + params: (params, context) => { const result = { ...params } - const operation = typeof result.operation === 'string' ? result.operation : '' - for (const [toolParam, aliasId] of Object.entries(SUBBLOCK_ALIASES[operation] ?? {})) - result[toolParam] = result[aliasId] + const operation = mapperOperation(params, context) + const toolCall = isToolCall(context) + for (const [toolParam, aliasId] of Object.entries(SUBBLOCK_ALIASES[operation] ?? {})) { + const aliasValue = result[aliasId] + const aliasBlank = aliasValue === undefined || aliasValue === null || aliasValue === '' + // A tool call carries the model's value under the tool's own param name. + if (!(toolCall && aliasBlank)) result[toolParam] = aliasValue + } for (const aliasId of ALIASED_SUBBLOCK_IDS) result[aliasId] = void 0 if (result.proxied === 'true') result.proxied = !0 else if (result.proxied === 'false') result.proxied = !1 @@ -4545,7 +4550,7 @@ export const CloudflareBlock: BlockConfig = { if (result.match === '') result.match = void 0 if (result.tag_match === '') result.tag_match = void 0 if (result.deploy === '') result.deploy = void 0 - if (result.operation === 'update_dns_record') { + if (operation === 'update_dns_record') { if (result.content === '') result.content = void 0 if (result.name === '') result.name = void 0 if (result.comment === '') result.comment = void 0 diff --git a/apps/sim/blocks/blocks/cloudformation.test.ts b/apps/sim/blocks/blocks/cloudformation.test.ts new file mode 100644 index 00000000000..5b6165f6f86 --- /dev/null +++ b/apps/sim/blocks/blocks/cloudformation.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest' +import { CloudFormationBlock } from '@/blocks/blocks/cloudformation' + +/** + * An agent tool call sends model args under the tool's param names (`description`, `tags`) with + * the operation only on `context`; the handler forwards `{ ...args, ...mapped }`. + */ +const agentCall = (operation: string, args: Record): Record => ({ + ...args, + ...(CloudFormationBlock.tools.config?.params?.(args, { operation }) ?? {}), +}) + +describe('CloudFormationBlock agent tool calls', () => { + it('keeps the model change set description and tags', () => { + expect( + agentCall('create_change_set', { + awsRegion: 'us-east-1', + awsAccessKeyId: 'AKIA', + awsSecretAccessKey: 'secret', + stackName: 'app', + changeSetName: 'cs-1', + usePreviousTemplate: true, + description: 'Bump instance size', + tags: [{ Key: 'team', Value: 'infra' }], + }) + ).toMatchObject({ + usePreviousTemplate: true, + description: 'Bump instance size', + tags: [{ Key: 'team', Value: 'infra' }], + }) + }) +}) diff --git a/apps/sim/blocks/blocks/cloudformation.ts b/apps/sim/blocks/blocks/cloudformation.ts index 75eb9753de0..443c84f62dc 100644 --- a/apps/sim/blocks/blocks/cloudformation.ts +++ b/apps/sim/blocks/blocks/cloudformation.ts @@ -2,7 +2,7 @@ import { getErrorMessage } from '@sim/utils/errors' import { CloudFormationIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { isToolCall, mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' export const CloudFormationBlock: BlockConfig = { type: 'cloudformation', @@ -420,16 +420,9 @@ Return ONLY valid JSON - no explanations, no markdown code blocks.`, throw new Error(`Invalid CloudFormation operation: ${params.operation}`) } }, - params: (params) => { - const { - operation, - limit, - usePreviousTemplate, - parameters, - tags, - timeoutInMinutes, - ...rest - } = params + params: (params, context) => { + const { limit, usePreviousTemplate, parameters, tags, timeoutInMinutes, ...rest } = params + const operation = mapperOperation(params, context) const awsRegion = rest.awsRegion const awsAccessKeyId = rest.awsAccessKeyId @@ -530,6 +523,7 @@ Return ONLY valid JSON - no explanations, no markdown code blocks.`, } case 'create_change_set': { + const description = rest.changeSetDescription || toolCallArg(context, rest.description) if (!rest.stackName) throw new Error('Stack name is required') if (!rest.changeSetName) throw new Error('Change set name is required') if (!rest.templateBody && !parsedUsePreviousTemplate) { @@ -548,8 +542,12 @@ Return ONLY valid JSON - no explanations, no markdown code blocks.`, ...(parameters && { parameters: parseJson(parameters, 'parameters') }), ...(rest.capabilities && { capabilities: rest.capabilities }), ...(rest.changeSetType && { changeSetType: rest.changeSetType }), - ...(rest.changeSetDescription && { description: rest.changeSetDescription }), - tags: rest.changeSetTags ? parseJson(rest.changeSetTags, 'tags') : undefined, + ...(description && { description }), + tags: rest.changeSetTags + ? parseJson(rest.changeSetTags, 'tags') + : isToolCall(context) + ? parseJson(tags, 'tags') + : undefined, ...(rest.roleArn && { roleArn: rest.roleArn }), } } diff --git a/apps/sim/blocks/blocks/cloudtrail.test.ts b/apps/sim/blocks/blocks/cloudtrail.test.ts index 71f7bd44062..bcc734a9ace 100644 --- a/apps/sim/blocks/blocks/cloudtrail.test.ts +++ b/apps/sim/blocks/blocks/cloudtrail.test.ts @@ -50,3 +50,22 @@ describe('CloudTrail block defaults', () => { expect(() => CloudTrailBlock.tools.config?.params?.(params)).toThrow(/filter/i) }) }) + +/** + * An agent tool call sends model args under the tool's param names (`name` for a trail) with the + * operation only on `context`; the handler forwards `{ ...args, ...mapped }`. + */ +describe('CloudTrail agent tool calls', () => { + it('keeps the model trail name for get_trail', () => { + const args = { + awsRegion: 'us-east-1', + awsAccessKeyId: 'AKIA', + awsSecretAccessKey: 'secret', + name: 'org-trail', + } + expect({ + ...args, + ...CloudTrailBlock.tools.config?.params?.(args, { operation: 'get_trail' }), + }).toMatchObject({ name: 'org-trail' }) + }) +}) diff --git a/apps/sim/blocks/blocks/cloudtrail.ts b/apps/sim/blocks/blocks/cloudtrail.ts index 75d437d0530..03be182c6dd 100644 --- a/apps/sim/blocks/blocks/cloudtrail.ts +++ b/apps/sim/blocks/blocks/cloudtrail.ts @@ -1,7 +1,7 @@ import { CloudTrailIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' /** Operations that accept an opaque AWS pagination token. */ const PAGINATED_OPERATIONS = [ @@ -427,155 +427,157 @@ Return ONLY the SQL query — no explanations, no markdown code blocks.`, throw new Error(`Invalid CloudTrail operation: ${params.operation}`) } }, - params: (params) => { - const { operation, ...rest } = params + params: (params, context) => { + const operation = mapperOperation(params, context) - const awsRegion = rest.awsRegion - const awsAccessKeyId = rest.awsAccessKeyId - const awsSecretAccessKey = rest.awsSecretAccessKey + const awsRegion = params.awsRegion + const awsAccessKeyId = params.awsAccessKeyId + const awsSecretAccessKey = params.awsSecretAccessKey const credentials = { awsRegion, awsAccessKeyId, awsSecretAccessKey } switch (operation) { case 'lookup_events': { - const maxResults = parseBoundedInt(rest.lookupMaxResults) - if (Boolean(rest.attributeKey) !== Boolean(rest.attributeValue)) { + const maxResults = parseBoundedInt(params.lookupMaxResults) + if (Boolean(params.attributeKey) !== Boolean(params.attributeValue)) { throw new Error('Provide both a filter attribute and a filter value, or neither') } return { ...credentials, - ...(rest.attributeKey && { - attributeKey: rest.attributeKey, - attributeValue: rest.attributeValue, + ...(params.attributeKey && { + attributeKey: params.attributeKey, + attributeValue: params.attributeValue, }), - ...(rest.startTime && { startTime: rest.startTime }), - ...(rest.endTime && { endTime: rest.endTime }), - ...(rest.eventCategory === 'insight' && { eventCategory: 'insight' }), + ...(params.startTime && { startTime: params.startTime }), + ...(params.endTime && { endTime: params.endTime }), + ...(params.eventCategory === 'insight' && { eventCategory: 'insight' }), ...(maxResults !== undefined && { maxResults }), - ...(rest.nextToken && { nextToken: rest.nextToken }), + ...(params.nextToken && { nextToken: params.nextToken }), } } case 'describe_trails': return { ...credentials, - ...(rest.trailNameList && { trailNameList: rest.trailNameList }), - ...(rest.includeShadowTrails !== undefined && - rest.includeShadowTrails !== '' && { - includeShadowTrails: String(rest.includeShadowTrails) !== 'false', + ...(params.trailNameList && { trailNameList: params.trailNameList }), + ...(params.includeShadowTrails !== undefined && + params.includeShadowTrails !== '' && { + includeShadowTrails: String(params.includeShadowTrails) !== 'false', }), } case 'get_trail': - case 'get_trail_status': - if (!rest.trailName) { + case 'get_trail_status': { + const name = params.trailName || toolCallArg(context, params.name) + if (!name) { throw new Error('Trail name or ARN is required') } - return { ...credentials, name: rest.trailName } + return { ...credentials, name } + } case 'list_trails': return { ...credentials, - ...(rest.nextToken && { nextToken: rest.nextToken }), + ...(params.nextToken && { nextToken: params.nextToken }), } case 'get_event_selectors': - if (!rest.trailName) { + if (!params.trailName) { throw new Error('Trail name or ARN is required') } - return { ...credentials, trailName: rest.trailName } + return { ...credentials, trailName: params.trailName } case 'get_insight_selectors': - if (Boolean(rest.trailName) === Boolean(rest.eventDataStore)) { + if (Boolean(params.trailName) === Boolean(params.eventDataStore)) { throw new Error( 'Specify exactly one of trail name or event data store for Insights selectors' ) } return { ...credentials, - ...(rest.trailName && { trailName: rest.trailName }), - ...(rest.eventDataStore && { eventDataStore: rest.eventDataStore }), + ...(params.trailName && { trailName: params.trailName }), + ...(params.eventDataStore && { eventDataStore: params.eventDataStore }), } case 'start_query': - if (Boolean(rest.queryStatement) === Boolean(rest.queryAlias)) { + if (Boolean(params.queryStatement) === Boolean(params.queryAlias)) { throw new Error('Specify exactly one of Lake SQL query or query template alias') } return { ...credentials, - ...(rest.queryStatement && { queryStatement: rest.queryStatement }), - ...(rest.queryAlias && { queryAlias: rest.queryAlias }), - ...(rest.queryParameters && { queryParameters: rest.queryParameters }), - ...(rest.deliveryS3Uri && { deliveryS3Uri: rest.deliveryS3Uri }), - ...(rest.eventDataStoreOwnerAccountId && { - eventDataStoreOwnerAccountId: rest.eventDataStoreOwnerAccountId, + ...(params.queryStatement && { queryStatement: params.queryStatement }), + ...(params.queryAlias && { queryAlias: params.queryAlias }), + ...(params.queryParameters && { queryParameters: params.queryParameters }), + ...(params.deliveryS3Uri && { deliveryS3Uri: params.deliveryS3Uri }), + ...(params.eventDataStoreOwnerAccountId && { + eventDataStoreOwnerAccountId: params.eventDataStoreOwnerAccountId, }), } case 'describe_query': - if (Boolean(rest.queryId) === Boolean(rest.queryAlias)) { + if (Boolean(params.queryId) === Boolean(params.queryAlias)) { throw new Error('Specify exactly one of query ID or query template alias') } return { ...credentials, - ...(rest.queryId && { queryId: rest.queryId }), - ...(rest.queryAlias && { queryAlias: rest.queryAlias }), - ...(rest.refreshId && { refreshId: rest.refreshId }), - ...(rest.eventDataStoreOwnerAccountId && { - eventDataStoreOwnerAccountId: rest.eventDataStoreOwnerAccountId, + ...(params.queryId && { queryId: params.queryId }), + ...(params.queryAlias && { queryAlias: params.queryAlias }), + ...(params.refreshId && { refreshId: params.refreshId }), + ...(params.eventDataStoreOwnerAccountId && { + eventDataStoreOwnerAccountId: params.eventDataStoreOwnerAccountId, }), } case 'get_query_results': { - if (!rest.queryId) { + if (!params.queryId) { throw new Error('Query ID is required') } - const maxQueryResults = parseBoundedInt(rest.maxQueryResults) + const maxQueryResults = parseBoundedInt(params.maxQueryResults) return { ...credentials, - queryId: rest.queryId, + queryId: params.queryId, ...(maxQueryResults !== undefined && { maxQueryResults }), - ...(rest.nextToken && { nextToken: rest.nextToken }), - ...(rest.eventDataStoreOwnerAccountId && { - eventDataStoreOwnerAccountId: rest.eventDataStoreOwnerAccountId, + ...(params.nextToken && { nextToken: params.nextToken }), + ...(params.eventDataStoreOwnerAccountId && { + eventDataStoreOwnerAccountId: params.eventDataStoreOwnerAccountId, }), } } case 'cancel_query': - if (!rest.queryId) { + if (!params.queryId) { throw new Error('Query ID is required') } return { ...credentials, - queryId: rest.queryId, - ...(rest.eventDataStoreOwnerAccountId && { - eventDataStoreOwnerAccountId: rest.eventDataStoreOwnerAccountId, + queryId: params.queryId, + ...(params.eventDataStoreOwnerAccountId && { + eventDataStoreOwnerAccountId: params.eventDataStoreOwnerAccountId, }), } case 'list_event_data_stores': { - const maxResults = parseBoundedInt(rest.eventDataStoreMaxResults) + const maxResults = parseBoundedInt(params.eventDataStoreMaxResults) return { ...credentials, ...(maxResults !== undefined && { maxResults }), - ...(rest.nextToken && { nextToken: rest.nextToken }), + ...(params.nextToken && { nextToken: params.nextToken }), } } case 'get_event_data_store': - if (!rest.eventDataStore) { + if (!params.eventDataStore) { throw new Error('Event data store ARN or ID is required') } - return { ...credentials, eventDataStore: rest.eventDataStore } + return { ...credentials, eventDataStore: params.eventDataStore } case 'list_tags': - if (!rest.resourceIdList) { + if (!params.resourceIdList) { throw new Error('At least one resource ARN is required') } return { ...credentials, - resourceIdList: rest.resourceIdList, - ...(rest.nextToken && { nextToken: rest.nextToken }), + resourceIdList: params.resourceIdList, + ...(params.nextToken && { nextToken: params.nextToken }), } default: diff --git a/apps/sim/blocks/blocks/cloudwatch.test.ts b/apps/sim/blocks/blocks/cloudwatch.test.ts new file mode 100644 index 00000000000..e174f1aa0f5 --- /dev/null +++ b/apps/sim/blocks/blocks/cloudwatch.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it } from 'vitest' +import { CloudWatchV2Block } from '@/blocks/blocks/cloudwatch' +import type { BlockToolParamsContext } from '@/blocks/types' + +const configuredParams = CloudWatchV2Block.tools.config?.params +if (!configuredParams) { + throw new Error('CloudWatch block must define tools.config.params') +} +const mapParams = configuredParams + +/** The tool-call merge: the mapped params land over the model's args (`{ ...args, ...mapped }`). */ +function merge(args: Record, context?: BlockToolParamsContext) { + return { ...args, ...mapParams(args, context) } +} + +describe('CloudWatch block params', () => { + it('publishes a metric from model args named by the tool when the operation is only in the context', () => { + const merged = merge( + { namespace: 'Custom/App', metricName: 'Hits', value: 3 }, + { operation: 'put_metric_data' } + ) + + expect(merged.namespace).toBe('Custom/App') + expect(merged.metricName).toBe('Hits') + expect(merged.value).toBe(3) + }) + it('splits a comma-separated extendedStatistics the model sent without statistics', () => { + const merged = merge( + { + namespace: 'AWS/EC2', + metricName: 'CPUUtilization', + startTime: 1700000000, + endTime: 1700003600, + period: 300, + extendedStatistics: 'p99, p95', + }, + { operation: 'get_metric_statistics' } + ) + + expect(merged.extendedStatistics).toEqual(['p99', 'p95']) + expect(merged.statistics).toBeUndefined() + }) +}) diff --git a/apps/sim/blocks/blocks/cloudwatch.ts b/apps/sim/blocks/blocks/cloudwatch.ts index 83445492d2e..31e439ff7de 100644 --- a/apps/sim/blocks/blocks/cloudwatch.ts +++ b/apps/sim/blocks/blocks/cloudwatch.ts @@ -1,7 +1,7 @@ import { CloudWatchIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' /* * Canonical basic/advanced pairs, shared by the card sentences below. Listing @@ -761,8 +761,9 @@ Return ONLY the numeric timestamp - no explanations, no quotes, no extra text.`, throw new Error(`Invalid CloudWatch operation: ${params.operation}`) } }, - params: (params) => { - const { operation, startTime, endTime, limit, ...rest } = params + params: (params, context) => { + const operation = mapperOperation(params, context) + const { startTime, endTime, limit, ...rest } = params const awsRegion = rest.awsRegion const awsAccessKeyId = rest.awsAccessKeyId @@ -903,7 +904,8 @@ Return ONLY the numeric timestamp - no explanations, no quotes, no extra text.`, } case 'get_metric_statistics': { - if (!rest.metricNamespace) { + const namespace = rest.metricNamespace || toolCallArg(context, rest.namespace) + if (!namespace) { throw new Error('Namespace is required') } if (!rest.metricName) { @@ -915,12 +917,15 @@ Return ONLY the numeric timestamp - no explanations, no quotes, no extra text.`, if (!endTime) { throw new Error('End time is required') } - if (!rest.metricPeriod) { + const period = rest.metricPeriod || toolCallArg(context, rest.period) + if (!period) { throw new Error('Period is required') } - const stat = rest.metricStatistics - if (!stat) { + const stat = rest.metricStatistics || toolCallArg(context, rest.statistics) + const extendedStat = + rest.metricExtendedStatistics || toolCallArg(context, rest.extendedStatistics) + if (!stat && !extendedStat) { throw new Error('Statistics is required') } @@ -928,16 +933,16 @@ Return ONLY the numeric timestamp - no explanations, no quotes, no extra text.`, awsRegion, awsAccessKeyId, awsSecretAccessKey, - namespace: rest.metricNamespace, + namespace, metricName: rest.metricName, startTime: Number(startTime), endTime: Number(endTime), - period: Number(rest.metricPeriod), - statistics: Array.isArray(stat) ? stat : [stat], - ...(rest.metricExtendedStatistics && { - extendedStatistics: Array.isArray(rest.metricExtendedStatistics) - ? rest.metricExtendedStatistics - : String(rest.metricExtendedStatistics) + period: Number(period), + ...(stat && { statistics: Array.isArray(stat) ? stat : [stat] }), + ...(extendedStat && { + extendedStatistics: Array.isArray(extendedStat) + ? extendedStat + : String(extendedStat) .split(',') .map((s: string) => s.trim()) .filter(Boolean), @@ -963,16 +968,21 @@ Return ONLY the numeric timestamp - no explanations, no quotes, no extra text.`, } case 'put_metric_data': { - if (!rest.metricNamespace) { + const namespace = rest.metricNamespace || toolCallArg(context, rest.namespace) + if (!namespace) { throw new Error('Namespace is required') } if (!rest.metricName) { throw new Error('Metric name is required') } - if (rest.metricValue === undefined || rest.metricValue === '') { + const metricValue = + rest.metricValue === undefined || rest.metricValue === '' + ? toolCallArg(context, rest.value) + : rest.metricValue + if (metricValue === undefined || metricValue === '') { throw new Error('Metric value is required') } - const numericValue = Number(rest.metricValue) + const numericValue = Number(metricValue) if (!Number.isFinite(numericValue)) { throw new Error('Metric value must be a finite number') } @@ -981,7 +991,7 @@ Return ONLY the numeric timestamp - no explanations, no quotes, no extra text.`, awsRegion, awsAccessKeyId, awsSecretAccessKey, - namespace: rest.metricNamespace, + namespace, metricName: rest.metricName, value: numericValue, ...(rest.metricUnit && rest.metricUnit !== 'None' && { unit: rest.metricUnit }), diff --git a/apps/sim/blocks/blocks/coda.test.ts b/apps/sim/blocks/blocks/coda.test.ts new file mode 100644 index 00000000000..1e9773cee31 --- /dev/null +++ b/apps/sim/blocks/blocks/coda.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from 'vitest' +import { CodaBlock } from '@/blocks/blocks/coda' + +const mapParams = CodaBlock.tools.config?.params + +/** + * A tool call merges the stored row with the model's args (keyed by tool param names) and spreads + * the mapper result over them; the operation arrives only in `context`. + */ +const toolCall = (args: Record, operation: string) => ({ + ...args, + ...mapParams?.(args, { operation }), +}) + +describe('CodaBlock', () => { + it('keeps the model args a tool call sends under the tool param names', () => { + const params = toolCall( + { docId: 'doc-1', tableId: 'grid-1', query: 'Status:"Done"', sortBy: 'natural', limit: 5 }, + 'list_rows' + ) + expect(params.query).toBe('Status:"Done"') + expect(params.sortBy).toBe('natural') + expect(params.limit).toBe(5) + }) + + it('does not restore a sentinel or off switch the coercion dropped on a tool call', () => { + const params = toolCall( + { docId: 'd', tableTypes: 'all', isPublished: false, visibleOnly: 'false' }, + 'list_tables' + ) + expect(params.tableTypes).toBeUndefined() + expect(params.isPublished).toBeUndefined() + expect(params.visibleOnly).toBeUndefined() + }) + + it('keeps the array form of table types a tool call sends', () => { + const params = toolCall({ docId: 'd', tableTypes: ['table'] }, 'list_tables') + expect(params.tableTypes).toEqual(['table']) + }) + + it('still drops a stale raw input on the canvas', () => { + const inputs = { operation: 'list_docs', query: 'stale', docSearch: 'roadmap', title: 'old' } + const params = { ...inputs, ...mapParams?.(inputs) } + expect(params.query).toBe('roadmap') + expect(params.title).toBeUndefined() + }) +}) diff --git a/apps/sim/blocks/blocks/coda.ts b/apps/sim/blocks/blocks/coda.ts index 25137f72fee..7f5334e64fc 100644 --- a/apps/sim/blocks/blocks/coda.ts +++ b/apps/sim/blocks/blocks/coda.ts @@ -1,5 +1,6 @@ import { CodaIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' const DOC_FIELD = ['docSelector', 'manualDocId'] const PAGE_FIELD = ['pageSelector', 'manualPageId'] @@ -110,6 +111,30 @@ const PAGE_TOKEN_OPERATIONS = [...LIMIT_OPERATIONS, 'list_workspace_members'] const LIST_SORT_OPERATIONS = ['list_tables', 'list_formulas', 'list_controls'] +/** + * Tool params the mapper reads from the same-named field, so a tool call's own value was + * already coerced; the tool-call fallback must not restore a value the coercion rejected + * (the `'all'` table-type sentinel, an off switch). + */ +const SELF_MAPPED_PARAMS = new Set([ + 'tableTypes', + 'limit', + 'discoverable', + 'allowEditorsToChangePermissions', + 'allowCopying', + 'allowViewersToRequestEditing', + 'includeSubpages', + 'isOwner', + 'isPublished', + 'inGallery', + 'useColumnNames', + 'useUpdatedTableLayouts', + 'visibleOnly', + 'disableParsing', + 'suppressEmail', + 'degradeGracefully', +]) + /** Switches only send `true`; an off switch leaves the Coda filter unset. */ function trueOrUndefined(value: unknown): true | undefined { return value === true || value === 'true' ? true : undefined @@ -1534,11 +1559,11 @@ Return ONLY the JSON object.`, ], config: { tool: (params) => `coda_${params.operation || 'list_rows'}`, - params: (params) => { - const operation = params.operation + params: (params, context) => { + const operation = mapperOperation(params, context) const isFolderWrite = operation === 'create_folder' || operation === 'update_folder' const pageVisibility = params.pageVisibility - return { + const mapped: Record = { query: operation === 'list_rows' ? params.rowFilter @@ -1571,7 +1596,9 @@ Return ONLY the JSON object.`, : params.listSortBy === 'name' ? 'name' : undefined, - tableTypes: unlessDefault(params.tableTypes, 'all'), + tableTypes: Array.isArray(params.tableTypes) + ? params.tableTypes + : unlessDefault(params.tableTypes, 'all'), mode: unlessDefault(params.publishMode, 'unchanged'), discoverable: triState(params.discoverable), allowEditorsToChangePermissions: triState(params.allowEditorsToChangePermissions), @@ -1593,6 +1620,14 @@ Return ONLY the JSON object.`, suppressEmail: trueOrUndefined(params.suppressEmail), degradeGracefully: trueOrUndefined(params.degradeGracefully), } + /* A tool call keeps each model arg this mapping leaves unset instead of wiping it; + {@link SELF_MAPPED_PARAMS} lists the keys whose drop must stand. */ + for (const [key, value] of Object.entries(mapped)) { + if (value === undefined && !SELF_MAPPED_PARAMS.has(key)) { + mapped[key] = toolCallArg(context, params[key]) + } + } + return mapped }, }, }, diff --git a/apps/sim/blocks/blocks/codepipeline.test.ts b/apps/sim/blocks/blocks/codepipeline.test.ts new file mode 100644 index 00000000000..d3c5ff370c1 --- /dev/null +++ b/apps/sim/blocks/blocks/codepipeline.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from 'vitest' +import { CodePipelineV2Block } from '@/blocks/blocks/codepipeline' +import type { BlockToolParamsContext } from '@/blocks/types' + +const configuredParams = CodePipelineV2Block.tools.config?.params +if (!configuredParams) { + throw new Error('CodePipeline block must define tools.config.params') +} +const mapParams = configuredParams + +/** The tool-call merge: the mapped params land over the model's args (`{ ...args, ...mapped }`). */ +function merge(args: Record, context?: BlockToolParamsContext) { + return { ...args, ...mapParams(args, context) } +} + +describe('CodePipeline block params', () => { + it('keeps the model approval decision on a tool call, where the operation is only in the context', () => { + const merged = merge( + { + pipelineName: 'deploy', + stageName: 'Prod', + actionName: 'ManualApproval', + token: 'tok-1', + status: 'Rejected', + summary: 'Failing canary', + }, + { operation: 'put_approval_result' } + ) + + expect(merged.token).toBe('tok-1') + expect(merged.status).toBe('Rejected') + expect(merged.summary).toBe('Failing canary') + }) +}) diff --git a/apps/sim/blocks/blocks/codepipeline.ts b/apps/sim/blocks/blocks/codepipeline.ts index 1a67d1dcced..53774759002 100644 --- a/apps/sim/blocks/blocks/codepipeline.ts +++ b/apps/sim/blocks/blocks/codepipeline.ts @@ -2,9 +2,11 @@ import { CodePipelineIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' import { + mapperOperation, parseOptionalBooleanInput, parseOptionalJsonInput, parseOptionalNumberInput, + toolCallArg, withSavedCredential, } from '@/blocks/utils' @@ -397,8 +399,14 @@ export const CodePipelineBlock: BlockConfig = { throw new Error(`Invalid CodePipeline operation: ${params.operation}`) } }, - params: (params) => { - const { operation, maxResults, getPipelineVersion, ...rest } = params + params: (params, context) => { + const operation = mapperOperation(params, context) + const { maxResults, getPipelineVersion, ...rest } = params + /** A blank block-only field yields, on a tool call, the model's arg under the tool's name. */ + const orToolArg = (blockValue: unknown, toolValue: unknown) => + blockValue === undefined || blockValue === '' + ? (toolCallArg(context, toolValue) ?? blockValue) + : blockValue const awsRegion = rest.awsRegion const awsAccessKeyId = rest.awsAccessKeyId @@ -530,9 +538,9 @@ export const CodePipelineBlock: BlockConfig = { pipelineName: rest.pipelineName, stageName: rest.stageName, actionName: rest.actionName, - token: rest.approvalToken, - status: rest.approvalStatus, - summary: rest.approvalSummary, + token: orToolArg(rest.approvalToken, rest.token), + status: orToolArg(rest.approvalStatus, rest.status), + summary: orToolArg(rest.approvalSummary, rest.summary), } case 'disable_stage_transition': @@ -543,7 +551,7 @@ export const CodePipelineBlock: BlockConfig = { pipelineName: rest.pipelineName, stageName: rest.stageName, transitionType: rest.transitionType, - reason: rest.transitionReason, + reason: orToolArg(rest.transitionReason, rest.reason), } case 'enable_stage_transition': diff --git a/apps/sim/blocks/blocks/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/context_dev.test.ts b/apps/sim/blocks/blocks/context_dev.test.ts new file mode 100644 index 00000000000..62e6bcd215d --- /dev/null +++ b/apps/sim/blocks/blocks/context_dev.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest' +import { ContextDevBlock } from '@/blocks/blocks/context_dev' + +/** + * A tool call merges the stored row with the model's args (keyed by tool param names) and spreads + * the mapper result over them; the operation arrives only in `context`. + */ +const toolCall = (args: Record, operation: string) => ({ + ...args, + ...ContextDevBlock.tools.config?.params?.(args, { operation }), +}) + +describe('ContextDevBlock tool calls', () => { + it('parses an extraction schema the model sends as a JSON string', () => { + const params = toolCall( + { apiKey: 'key', url: 'https://example.com', schema: '{"type":"object"}', maxPages: 3 }, + 'extract' + ) + expect(params.schema).toEqual({ type: 'object' }) + expect(params.maxPages).toBe(3) + }) +}) diff --git a/apps/sim/blocks/blocks/context_dev.ts b/apps/sim/blocks/blocks/context_dev.ts index cc8eaadfb7e..98ff5574718 100644 --- a/apps/sim/blocks/blocks/context_dev.ts +++ b/apps/sim/blocks/blocks/context_dev.ts @@ -1,6 +1,7 @@ import { ContextDevIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation } from '@/blocks/utils' /** Operations whose primary input is a full page URL. */ const URL_OPS = [ @@ -628,9 +629,9 @@ Do not include any explanations, markdown formatting, or other text outside the config: { tool: (params) => params.operation ? `context_dev_${params.operation}` : 'context_dev_scrape_markdown', - params: (params) => { - const { operation, apiKey } = params - const result: Record = { apiKey } + params: (params, context) => { + const operation = mapperOperation(params, context) + const result: Record = { apiKey: params.apiKey } const setBool = (key: string) => { if (params[key] != null) result[key] = params[key] diff --git a/apps/sim/blocks/blocks/crowdstrike.test.ts b/apps/sim/blocks/blocks/crowdstrike.test.ts index 646c499a851..488a41da81c 100644 --- a/apps/sim/blocks/blocks/crowdstrike.test.ts +++ b/apps/sim/blocks/blocks/crowdstrike.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest' import { CrowdStrikeBlock } from '@/blocks/blocks/crowdstrike' +import type { BlockToolParamsContext } from '@/blocks/types' const mapParams = CrowdStrikeBlock.tools.config?.params if (!mapParams) { @@ -18,8 +19,8 @@ const credentials = { * subBlock value. Every assertion here runs against the merged result, because a * mapper-only assertion passes even when the raw value survives onto the wire. */ -function merge(inputs: Record) { - return { ...inputs, ...mapParams(inputs) } +function merge(inputs: Record, context?: BlockToolParamsContext) { + return { ...inputs, ...mapParams(inputs, context) } } describe('CrowdStrike block params', () => { @@ -146,4 +147,14 @@ describe('CrowdStrike block params', () => { expect(merged.includeHidden).toBe(false) }) + + it('keeps the model host action and hosts on a tool call, where the operation is only in the context', () => { + const merged = merge( + { ...credentials, actionName: 'lift_containment', deviceIds: ['aid-1'] }, + { operation: 'crowdstrike_perform_host_action' } + ) + + expect(merged.actionName).toBe('lift_containment') + expect(merged.deviceIds).toEqual(['aid-1']) + }) }) diff --git a/apps/sim/blocks/blocks/crowdstrike.ts b/apps/sim/blocks/blocks/crowdstrike.ts index 0e713d6bec7..a9e7d5a1415 100644 --- a/apps/sim/blocks/blocks/crowdstrike.ts +++ b/apps/sim/blocks/blocks/crowdstrike.ts @@ -2,9 +2,11 @@ import { CrowdStrikeIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' import { + mapperOperation, parseOptionalBooleanInput, parseOptionalJsonInput, parseOptionalNumberInput, + toolCallArg, withSavedCredential, } from '@/blocks/utils' @@ -840,8 +842,8 @@ export const CrowdStrikeBlock: BlockConfig = { config: { tool: (params) => typeof params.operation === 'string' ? params.operation : 'crowdstrike_query_alerts', - params: (params) => { - const operation = typeof params.operation === 'string' ? params.operation : '' + params: (params, context) => { + const operation = mapperOperation(params, context) /** * The executor merges this result over the raw block inputs, so a key this @@ -928,14 +930,20 @@ export const CrowdStrikeBlock: BlockConfig = { setJson('actionParameters', params.actionParameters, 'action parameters') break case 'crowdstrike_perform_host_action': - setString('actionName', params.hostActionName) + setString( + 'actionName', + params.hostActionName || toolCallArg(context, params.actionName) + ) setJson('deviceIds', params.deviceIds, 'host agent IDs') break case 'crowdstrike_get_host_group_details': setJson('hostGroupIds', params.hostGroupIds, 'host group IDs') break case 'crowdstrike_perform_host_group_action': - setString('actionName', params.hostGroupActionName) + setString( + 'actionName', + params.hostGroupActionName || toolCallArg(context, params.actionName) + ) setString('hostGroupId', params.hostGroupId) setJson('deviceIds', params.deviceIds, 'host agent IDs') break @@ -951,7 +959,7 @@ export const CrowdStrikeBlock: BlockConfig = { break case 'crowdstrike_delete_indicators': setJson('indicatorIds', params.indicatorIds, 'indicator IDs') - setString('filter', params.deleteFilter) + setString('filter', params.deleteFilter || toolCallArg(context, params.filter)) setString('comment', params.comment) break case 'crowdstrike_get_vulnerability_details': diff --git a/apps/sim/blocks/blocks/crunchbase.test.ts b/apps/sim/blocks/blocks/crunchbase.test.ts index 45f6c67c5ff..ed4c8805d6f 100644 --- a/apps/sim/blocks/blocks/crunchbase.test.ts +++ b/apps/sim/blocks/blocks/crunchbase.test.ts @@ -87,4 +87,23 @@ describe('CrunchbaseBlock', () => { expect(deleted.collection).toBe('people') expect(deleted.deletedCollection).toBeUndefined() }) + + /* + * A tool call merges the stored row with the model's args, keyed by the tool's + * param names, and carries the operation only in `context`. + */ + it('keeps the model args a tool call sends under the tool param names', () => { + const args = { + apiKey: 'key', + collection: 'organizations', + query: [{ type: 'predicate', field_id: 'num_employees_enum' }], + fieldIds: ['identifier'], + limit: 10, + } + const params = { ...args, ...buildParams(args, { operation: 'search_entities' }) } + expect(params.collection).toBe('organizations') + expect(params.query).toEqual(args.query) + expect(params.fieldIds).toEqual(['identifier']) + expect(params.limit).toBe(10) + }) }) diff --git a/apps/sim/blocks/blocks/crunchbase.ts b/apps/sim/blocks/blocks/crunchbase.ts index 0ed7810ed62..8d78ff352b9 100644 --- a/apps/sim/blocks/blocks/crunchbase.ts +++ b/apps/sim/blocks/blocks/crunchbase.ts @@ -2,7 +2,7 @@ import { Building, ListChecks, Search, Sprout, Trash, Users } from '@sim/emcn/ic import { CrunchbaseIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' import { CRUNCHBASE_CARD_COLLECTIONS, CRUNCHBASE_COLLECTIONS, @@ -394,8 +394,8 @@ export const CrunchbaseBlock: BlockConfig = { * advanced field is serialized on non-emptiness alone, even while the UI * hides it. `undefined` is what actually drops one. */ - params: (params) => { - const operation = String(params.operation ?? '') + params: (params, context) => { + const operation = mapperOperation(params, context) const isSearch = (SEARCH_OPERATIONS as readonly string[]).includes(operation) const isLookup = (LOOKUP_OPERATIONS as readonly string[]).includes(operation) const isCollectionScoped = (COLLECTION_OPERATIONS as readonly string[]).includes(operation) @@ -406,13 +406,16 @@ export const CrunchbaseBlock: BlockConfig = { const paginates = isSearch || isCard || isDeleted let query: unknown - if (isSearch) query = params.searchQuery - else if (isAutocomplete) query = params.autocompleteQuery + if (isSearch) query = params.searchQuery ?? toolCallArg(context, params.query) + else if (isAutocomplete) + query = params.autocompleteQuery ?? toolCallArg(context, params.query) let collection: unknown if (isCollectionScoped) collection = params.collection - else if (isCard) collection = params.cardCollection - else if (isDeleted) collection = params.deletedCollection + else if (isCard) + collection = params.cardCollection ?? toolCallArg(context, params.collection) + else if (isDeleted) + collection = params.deletedCollection ?? toolCallArg(context, params.collection) return { apiKey: params.apiKey, @@ -422,7 +425,7 @@ export const CrunchbaseBlock: BlockConfig = { cardId: isCard ? params.cardId : undefined, fieldIds: operation === 'search_entities' - ? params.searchFieldIds + ? (params.searchFieldIds ?? toolCallArg(context, params.fieldIds)) : isSearch || isLookup ? params.fieldIds : undefined, diff --git a/apps/sim/blocks/blocks/dagster.test.ts b/apps/sim/blocks/blocks/dagster.test.ts new file mode 100644 index 00000000000..de353d98bed --- /dev/null +++ b/apps/sim/blocks/blocks/dagster.test.ts @@ -0,0 +1,60 @@ +/** + * An Agent tool call runs the block mapper over `{ ...storedRowParams, ...modelArgs }` with the + * operation only in `context`; the tool then receives `{ ...merged, ...mapped }`. + */ +import { describe, expect, it } from 'vitest' +import { DagsterBlock } from '@/blocks/blocks/dagster' +import { materializeAssetsTool } from '@/tools/dagster/materialize_assets' +import { reportAssetMaterializationTool } from '@/tools/dagster/report_asset_materialization' + +function materializeVariables(args: Record) { + const mapped = + DagsterBlock.tools.config?.params?.(args, { operation: 'materialize_assets' }) ?? {} + const body = materializeAssetsTool.request.body + if (typeof body !== 'function') throw new Error('materialize_assets has no body builder') + return (body({ ...args, ...mapped } as never) as { variables: Record }).variables +} + +const BASE_ARGS = { + host: 'https://dagster.example.com', + repositoryLocationName: 'loc', + repositoryName: 'repo', + assetSelection: 'orders', +} + +describe('Dagster materialize assets on an Agent tool call', () => { + it('sends the job name stored on the tool row', () => { + expect(materializeVariables({ ...BASE_ARGS, assetJobName: 'stored_job' }).jobName).toBe( + 'stored_job' + ) + }) + + it('keeps the job name the model supplied', () => { + expect(materializeVariables({ ...BASE_ARGS, jobName: 'model_job' }).jobName).toBe('model_job') + }) +}) + +function reportedEventType(args: Record) { + const mapped = + DagsterBlock.tools.config?.params?.(args, { operation: 'report_asset_materialization' }) ?? {} + const body = reportAssetMaterializationTool.request.body + if (typeof body !== 'function') + throw new Error('report_asset_materialization has no body builder') + const { variables } = body({ ...args, ...mapped } as never) as { + variables: { eventParams: { eventType: unknown } } + } + return variables.eventParams.eventType +} + +describe('Dagster report asset event on an Agent tool call', () => { + it('keeps the event type the model supplied over the seeded dropdown default', () => { + expect( + reportedEventType({ + host: 'https://dagster.example.com', + assetKey: 'orders', + reportEventType: 'ASSET_MATERIALIZATION', + eventType: 'ASSET_OBSERVATION', + }) + ).toBe('ASSET_OBSERVATION') + }) +}) diff --git a/apps/sim/blocks/blocks/dagster.ts b/apps/sim/blocks/blocks/dagster.ts index deb79ba2013..a445401dcce 100644 --- a/apps/sim/blocks/blocks/dagster.ts +++ b/apps/sim/blocks/blocks/dagster.ts @@ -1,6 +1,7 @@ import { DagsterIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { IntegrationType } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' /** Coerces a subBlock value to a finite number, returning undefined for empty or non-numeric input. */ function toFiniteNumber(value: unknown): number | undefined { @@ -548,46 +549,56 @@ Return ONLY the comma-separated asset keys - no explanations, no extra text.`, ], config: { tool: (params) => `dagster_${params.operation}`, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const result: Record = {} - if (params.operation === 'list_runs') { + if (operation === 'list_runs') { result.limit = toFiniteNumber(params.limit) - result.jobName = params.listRunsJobName || undefined + result.jobName = + params.listRunsJobName || toolCallArg(context, params.jobName) || undefined result.createdAfter = toFiniteNumber(params.createdAfter) result.createdBefore = toFiniteNumber(params.createdBefore) - result.cursor = params.runsCursor || undefined + result.cursor = params.runsCursor || toolCallArg(context, params.cursor) || undefined } - if (params.operation === 'get_run_logs') { - result.limit = toFiniteNumber(params.logsLimit) + if (operation === 'get_run_logs') { + result.limit = + toFiniteNumber(params.logsLimit) ?? toolCallArg(context, toFiniteNumber(params.limit)) } - if (params.operation === 'reexecute_run') { + if (operation === 'reexecute_run') { if (params.runId) result.parentRunId = params.runId } - if (params.operation === 'list_schedules' && !params.scheduleStatus) { + if (operation === 'list_schedules' && !params.scheduleStatus) { result.scheduleStatus = undefined } - if (params.operation === 'list_sensors' && !params.sensorStatus) { + if (operation === 'list_sensors' && !params.sensorStatus) { result.sensorStatus = undefined } - if (params.operation === 'list_assets') { - result.prefix = params.assetPrefix || undefined - result.limit = toFiniteNumber(params.assetsLimit) - result.cursor = params.assetsCursor || undefined + if (operation === 'list_assets') { + result.prefix = params.assetPrefix || toolCallArg(context, params.prefix) || undefined + result.limit = + toFiniteNumber(params.assetsLimit) ?? toolCallArg(context, toFiniteNumber(params.limit)) + result.cursor = params.assetsCursor || toolCallArg(context, params.cursor) || undefined } - if (params.operation === 'materialize_assets') { - result.jobName = params.assetJobName + if (operation === 'materialize_assets') { + result.jobName = + params.assetJobName || toolCallArg(context, params.jobName) || params.assetJobName } - if (params.operation === 'report_asset_materialization') { - result.eventType = params.reportEventType || 'ASSET_MATERIALIZATION' - result.partitionKeys = params.reportPartitionKeys || undefined - result.description = params.reportDescription || undefined + if (operation === 'report_asset_materialization') { + result.eventType = + toolCallArg(context, params.eventType) || + params.reportEventType || + 'ASSET_MATERIALIZATION' + result.partitionKeys = + params.reportPartitionKeys || toolCallArg(context, params.partitionKeys) || undefined + result.description = + params.reportDescription || toolCallArg(context, params.description) || undefined } return result diff --git a/apps/sim/blocks/blocks/datadog.test.ts b/apps/sim/blocks/blocks/datadog.test.ts index 53a1794df82..57c4c18702a 100644 --- a/apps/sim/blocks/blocks/datadog.test.ts +++ b/apps/sim/blocks/blocks/datadog.test.ts @@ -99,3 +99,48 @@ describe('datadog numeric coercion', () => { expect(params[key]).toBe(0) }) }) + +/** + * On a tool call (Agent tool row, Pi, Human-in-the-loop) the operation arrives only in + * `context`, and the model's args are keyed by the tool's param names. The mapper's result is + * spread over those args, so a branch that renames a block field onto a tool param must keep + * the model's value when the block field is blank. + */ +function toolCallParams( + operation: string, + modelArgs: Record +): Record { + const params = { ...baseInputs, ...modelArgs } + return { ...params, ...(mapParams?.(params, { operation }) as Record) } +} + +describe('datadog tool-call params', () => { + it.each([ + ['datadog_create_monitor', { query: 'avg:cpu{*} > 90', tags: 'team:a', priority: 2 }], + ['datadog_mute_monitor', { monitorId: '123' }], + ['datadog_query_logs', { query: 'status:error', from: 'now-1h', to: 'now', limit: 20 }], + ['datadog_create_incident', { title: 'DB down', customerImpacted: true }], + ['datadog_update_security_signal_state', { signalId: 's1', state: 'archived' }], + ['datadog_trigger_synthetics_tests', { publicIds: 'abc-def-ghi' }], + ['datadog_list_monitors', { name: 'cpu', monitorTags: 'env:prod', page: 0 }], + ])('keeps the model args for %s', (operation, modelArgs) => { + const params = toolCallParams(operation, modelArgs) + + expect(params).toMatchObject(modelArgs) + }) + + it('drops a non-numeric model page size instead of sending it to Datadog', () => { + const params = toolCallParams('datadog_list_monitors', { pageSize: 'fifty' }) + + expect(params.pageSize).toBeUndefined() + }) + + it('reads a model switch value sent as a string', () => { + const params = toolCallParams('datadog_unmute_monitor', { + monitorId: '123', + allScopes: 'false', + }) + + expect(params.allScopes).toBe(false) + }) +}) diff --git a/apps/sim/blocks/blocks/datadog.ts b/apps/sim/blocks/blocks/datadog.ts index e9f6fae27c2..29b78e12fa6 100644 --- a/apps/sim/blocks/blocks/datadog.ts +++ b/apps/sim/blocks/blocks/datadog.ts @@ -1,7 +1,7 @@ import { DatadogIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' import { DATADOG_SITE_LABELS, DATADOG_SITES } from '@/tools/datadog/types' /** @@ -1961,14 +1961,31 @@ Return ONLY the search query string - no explanations.`, ], config: { tool: (params) => params.operation, - params: (params) => { + params: (params, context) => { const baseParams: { apiKey: string; applicationKey: string; site: string } = { apiKey: params.apiKey, applicationKey: params.applicationKey, site: params.site, } - - switch (params.operation) { + /** + * A block field, or on a tool call where it is blank, the model's arg under the tool's + * param name. On the canvas the field is returned unchanged. + */ + const field = (blockValue: unknown, toolParam: string) => + blockValue != null && blockValue !== '' + ? blockValue + : (toolCallArg(context, params[toolParam]) ?? blockValue) + /** Like {@link field} for numeric fields, coercing both values. */ + const numberField = (blockValue: unknown, toolParam: string) => + datadogNumber(blockValue) ?? toolCallArg(context, datadogNumber(params[toolParam])) + /** Like {@link field} for switches, coercing both values. */ + const switchField = (blockValue: unknown, toolParam: string) => + toSwitchBoolean(blockValue) ?? toolCallArg(context, toSwitchBoolean(params[toolParam])) + /** Like {@link field} for optional fields whose blank value is omitted. */ + const optionalField = (blockValue: unknown, toolParam: string) => + blockValue || toolCallArg(context, params[toolParam]) || undefined + + switch (mapperOperation(params, context)) { case 'datadog_submit_metrics': return { ...baseParams, series: params.series } @@ -1995,10 +2012,10 @@ Return ONLY the search query string - no explanations.`, ...baseParams, name: params.name, type: params.type, - query: params.monitorQuery, + query: field(params.monitorQuery, 'query'), message: params.message, - tags: params.monitorTags, - priority: datadogNumber(params.monitorPriority), + tags: field(params.monitorTags, 'tags'), + priority: numberField(params.monitorPriority, 'priority'), options: params.options, } @@ -2008,22 +2025,23 @@ Return ONLY the search query string - no explanations.`, case 'datadog_list_monitors': return { ...baseParams, - name: params.listMonitorName || undefined, - tags: params.listMonitorTags || undefined, + name: optionalField(params.listMonitorName, 'name'), + tags: optionalField(params.listMonitorTags, 'tags'), /** * `monitorTags` belongs to Create Monitor but serializes for every operation, and * the block merges these params over the raw inputs. Without an explicit clear, a - * leftover value would filter this list while presenting it as complete. + * leftover value would filter this list while presenting it as complete. A tool + * call carries only this tool's args, so there it is the model's filter. */ - monitorTags: undefined, - pageSize: datadogNumber(params.listMonitorPageSize), - page: datadogNumber(params.listMonitorPage), + monitorTags: toolCallArg(context, params.monitorTags), + pageSize: numberField(params.listMonitorPageSize, 'pageSize'), + page: numberField(params.listMonitorPage, 'page'), } case 'datadog_mute_monitor': return { ...baseParams, - monitorId: params.muteMonitorId, + monitorId: field(params.muteMonitorId, 'monitorId'), scope: params.scope || undefined, end: datadogNumber(params.end), } @@ -2031,19 +2049,19 @@ Return ONLY the search query string - no explanations.`, case 'datadog_unmute_monitor': return { ...baseParams, - monitorId: params.muteMonitorId, + monitorId: field(params.muteMonitorId, 'monitorId'), scope: params.scope || undefined, - allScopes: toSwitchBoolean(params.unmuteAllScopes), + allScopes: switchField(params.unmuteAllScopes, 'allScopes'), } case 'datadog_query_logs': return { ...baseParams, - query: params.logQuery, - from: params.logFrom, - to: params.logTo, - limit: datadogNumber(params.logLimit), - cursor: params.logCursor || undefined, + query: field(params.logQuery, 'query'), + from: field(params.logFrom, 'from'), + to: field(params.logTo, 'to'), + limit: numberField(params.logLimit, 'limit'), + cursor: optionalField(params.logCursor, 'cursor'), } case 'datadog_send_logs': @@ -2052,22 +2070,25 @@ Return ONLY the search query string - no explanations.`, case 'datadog_create_downtime': return { ...baseParams, - scope: params.downtimeScope, - message: params.downtimeMessage, - start: datadogNumber(params.downtimeStart), - end: datadogNumber(params.downtimeEnd), - monitorId: params.downtimeMonitorId, - monitorTags: params.downtimeMonitorTags || undefined, - timezone: params.downtimeTimezone || undefined, - muteFirstRecoveryNotification: toSwitchBoolean(params.downtimeMuteFirstRecovery), + scope: field(params.downtimeScope, 'scope'), + message: field(params.downtimeMessage, 'message'), + start: numberField(params.downtimeStart, 'start'), + end: numberField(params.downtimeEnd, 'end'), + monitorId: field(params.downtimeMonitorId, 'monitorId'), + monitorTags: optionalField(params.downtimeMonitorTags, 'monitorTags'), + timezone: optionalField(params.downtimeTimezone, 'timezone'), + muteFirstRecoveryNotification: switchField( + params.downtimeMuteFirstRecovery, + 'muteFirstRecoveryNotification' + ), } case 'datadog_list_downtimes': return { ...baseParams, currentOnly: toSwitchBoolean(params.currentOnly), - limit: datadogNumber(params.downtimeLimit), - offset: datadogNumber(params.downtimeOffset), + limit: numberField(params.downtimeLimit, 'limit'), + offset: numberField(params.downtimeOffset, 'offset'), } case 'datadog_cancel_downtime': @@ -2076,130 +2097,152 @@ Return ONLY the search query string - no explanations.`, case 'datadog_list_incidents': return { ...baseParams, - include: params.incidentInclude || undefined, - pageSize: datadogNumber(params.incidentPageSize), - pageOffset: datadogNumber(params.incidentPageOffset), + include: optionalField(params.incidentInclude, 'include'), + pageSize: numberField(params.incidentPageSize, 'pageSize'), + pageOffset: numberField(params.incidentPageOffset, 'pageOffset'), } case 'datadog_get_incident': return { ...baseParams, incidentId: params.incidentId, - include: params.incidentInclude || undefined, + include: optionalField(params.incidentInclude, 'include'), } case 'datadog_create_incident': return { ...baseParams, - title: params.incidentTitle, - customerImpacted: toSwitchBoolean(params.incidentCustomerImpacted) ?? false, - severity: params.incidentSeverity || undefined, - customerImpactScope: params.incidentCustomerImpactScope || undefined, + title: field(params.incidentTitle, 'title'), + customerImpacted: + switchField(params.incidentCustomerImpacted, 'customerImpacted') ?? false, + severity: optionalField(params.incidentSeverity, 'severity'), + customerImpactScope: optionalField( + params.incidentCustomerImpactScope, + 'customerImpactScope' + ), incidentTypeUuid: params.incidentTypeUuid || undefined, - isTest: toSwitchBoolean(params.incidentIsTest), - fields: params.incidentFields || undefined, - notificationHandles: params.incidentNotificationHandles || undefined, + isTest: switchField(params.incidentIsTest, 'isTest'), + fields: optionalField(params.incidentFields, 'fields'), + notificationHandles: optionalField( + params.incidentNotificationHandles, + 'notificationHandles' + ), } case 'datadog_update_incident': return { ...baseParams, incidentId: params.incidentId, - title: params.incidentTitle || undefined, - severity: params.incidentSeverity || undefined, - customerImpacted: toSwitchBoolean(params.incidentCustomerImpacted), - customerImpactScope: params.incidentCustomerImpactScope || undefined, - customerImpactStart: params.incidentCustomerImpactStart || undefined, - customerImpactEnd: params.incidentCustomerImpactEnd || undefined, - detected: params.incidentDetected || undefined, - fields: params.incidentFields || undefined, - notificationHandles: params.incidentNotificationHandles || undefined, + title: optionalField(params.incidentTitle, 'title'), + severity: optionalField(params.incidentSeverity, 'severity'), + customerImpacted: switchField(params.incidentCustomerImpacted, 'customerImpacted'), + customerImpactScope: optionalField( + params.incidentCustomerImpactScope, + 'customerImpactScope' + ), + customerImpactStart: optionalField( + params.incidentCustomerImpactStart, + 'customerImpactStart' + ), + customerImpactEnd: optionalField( + params.incidentCustomerImpactEnd, + 'customerImpactEnd' + ), + detected: optionalField(params.incidentDetected, 'detected'), + fields: optionalField(params.incidentFields, 'fields'), + notificationHandles: optionalField( + params.incidentNotificationHandles, + 'notificationHandles' + ), } case 'datadog_add_incident_todo': return { ...baseParams, incidentId: params.incidentId, - content: params.todoContent, - assignees: params.todoAssignees, - dueDate: params.todoDueDate || undefined, + content: field(params.todoContent, 'content'), + assignees: field(params.todoAssignees, 'assignees'), + dueDate: optionalField(params.todoDueDate, 'dueDate'), } case 'datadog_list_slos': return { ...baseParams, - ids: params.sloIds || undefined, - query: params.sloQuery || undefined, - tagsQuery: params.sloTagsQuery || undefined, - metricsQuery: params.sloMetricsQuery || undefined, - limit: datadogNumber(params.sloLimit), - offset: datadogNumber(params.sloOffset), + ids: optionalField(params.sloIds, 'ids'), + query: optionalField(params.sloQuery, 'query'), + tagsQuery: optionalField(params.sloTagsQuery, 'tagsQuery'), + metricsQuery: optionalField(params.sloMetricsQuery, 'metricsQuery'), + limit: numberField(params.sloLimit, 'limit'), + offset: numberField(params.sloOffset, 'offset'), } case 'datadog_get_slo': return { ...baseParams, sloId: params.sloId, - withConfiguredAlertIds: toSwitchBoolean(params.sloWithConfiguredAlertIds), + withConfiguredAlertIds: switchField( + params.sloWithConfiguredAlertIds, + 'withConfiguredAlertIds' + ), } case 'datadog_create_slo': return { ...baseParams, - name: params.sloName, - type: params.sloType, - thresholds: params.sloThresholds, - description: params.sloDescription || undefined, - tags: params.sloTags || undefined, - query: params.sloMetricQuery || undefined, - monitorIds: params.sloMonitorIds || undefined, - groups: params.sloGroups || undefined, - targetThreshold: datadogNumber(params.sloTargetThreshold), - warningThreshold: datadogNumber(params.sloWarningThreshold), - timeframe: params.sloTimeframe || undefined, + name: field(params.sloName, 'name'), + type: field(params.sloType, 'type'), + thresholds: field(params.sloThresholds, 'thresholds'), + description: optionalField(params.sloDescription, 'description'), + tags: optionalField(params.sloTags, 'tags'), + query: optionalField(params.sloMetricQuery, 'query'), + monitorIds: optionalField(params.sloMonitorIds, 'monitorIds'), + groups: optionalField(params.sloGroups, 'groups'), + targetThreshold: numberField(params.sloTargetThreshold, 'targetThreshold'), + warningThreshold: numberField(params.sloWarningThreshold, 'warningThreshold'), + timeframe: optionalField(params.sloTimeframe, 'timeframe'), } case 'datadog_update_slo': return { ...baseParams, sloId: params.sloId, - name: params.sloName || undefined, - type: params.sloUpdateType || undefined, - thresholds: params.sloThresholds || undefined, - description: params.sloDescription || undefined, - tags: params.sloTags || undefined, - query: params.sloMetricQuery || undefined, - monitorIds: params.sloMonitorIds || undefined, - groups: params.sloGroups || undefined, - targetThreshold: datadogNumber(params.sloTargetThreshold), - warningThreshold: datadogNumber(params.sloWarningThreshold), - timeframe: params.sloTimeframe || undefined, + name: optionalField(params.sloName, 'name'), + type: optionalField(params.sloUpdateType, 'type'), + thresholds: optionalField(params.sloThresholds, 'thresholds'), + description: optionalField(params.sloDescription, 'description'), + tags: optionalField(params.sloTags, 'tags'), + query: optionalField(params.sloMetricQuery, 'query'), + monitorIds: optionalField(params.sloMonitorIds, 'monitorIds'), + groups: optionalField(params.sloGroups, 'groups'), + targetThreshold: numberField(params.sloTargetThreshold, 'targetThreshold'), + warningThreshold: numberField(params.sloWarningThreshold, 'warningThreshold'), + timeframe: optionalField(params.sloTimeframe, 'timeframe'), } case 'datadog_delete_slo': return { ...baseParams, sloId: params.sloId, - force: toSwitchBoolean(params.sloForce), + force: switchField(params.sloForce, 'force'), } case 'datadog_get_slo_history': return { ...baseParams, sloId: params.sloId, - fromTs: datadogNumber(params.sloFromTs), - toTs: datadogNumber(params.sloToTs), - target: datadogNumber(params.sloTarget), - applyCorrection: toSwitchBoolean(params.sloApplyCorrection), + fromTs: numberField(params.sloFromTs, 'fromTs'), + toTs: numberField(params.sloToTs, 'toTs'), + target: numberField(params.sloTarget, 'target'), + applyCorrection: switchField(params.sloApplyCorrection, 'applyCorrection'), } case 'datadog_list_dashboards': return { ...baseParams, - filterShared: toSwitchBoolean(params.dashboardFilterShared), - filterDeleted: toSwitchBoolean(params.dashboardFilterDeleted), - count: datadogNumber(params.dashboardCount), - start: datadogNumber(params.dashboardStart), + filterShared: switchField(params.dashboardFilterShared, 'filterShared'), + filterDeleted: switchField(params.dashboardFilterDeleted, 'filterDeleted'), + count: numberField(params.dashboardCount, 'count'), + start: numberField(params.dashboardStart, 'start'), } case 'datadog_get_dashboard': @@ -2208,14 +2251,17 @@ Return ONLY the search query string - no explanations.`, case 'datadog_create_dashboard': return { ...baseParams, - title: params.dashboardTitle, - layoutType: params.dashboardLayoutType, - widgets: params.dashboardWidgets, - description: params.dashboardDescription || undefined, - notifyList: params.dashboardNotifyList || undefined, - templateVariables: params.dashboardTemplateVariables || undefined, - tags: params.dashboardTags || undefined, - reflowType: params.dashboardReflowType || undefined, + title: field(params.dashboardTitle, 'title'), + layoutType: field(params.dashboardLayoutType, 'layoutType'), + widgets: field(params.dashboardWidgets, 'widgets'), + description: optionalField(params.dashboardDescription, 'description'), + notifyList: optionalField(params.dashboardNotifyList, 'notifyList'), + templateVariables: optionalField( + params.dashboardTemplateVariables, + 'templateVariables' + ), + tags: optionalField(params.dashboardTags, 'tags'), + reflowType: optionalField(params.dashboardReflowType, 'reflowType'), } case 'datadog_delete_dashboard': @@ -2224,42 +2270,42 @@ Return ONLY the search query string - no explanations.`, case 'datadog_list_synthetics_tests': return { ...baseParams, - pageSize: datadogNumber(params.syntheticsPageSize), - pageNumber: datadogNumber(params.syntheticsPageNumber), + pageSize: numberField(params.syntheticsPageSize, 'pageSize'), + pageNumber: numberField(params.syntheticsPageNumber, 'pageNumber'), } case 'datadog_get_synthetics_test': - return { ...baseParams, publicId: params.syntheticsPublicId } + return { ...baseParams, publicId: field(params.syntheticsPublicId, 'publicId') } case 'datadog_get_synthetics_results': case 'datadog_get_browser_synthetics_results': return { ...baseParams, - publicId: params.syntheticsPublicId, - fromTs: datadogNumber(params.syntheticsFromTs), - toTs: datadogNumber(params.syntheticsToTs), - probeDc: params.syntheticsProbeDc || undefined, + publicId: field(params.syntheticsPublicId, 'publicId'), + fromTs: numberField(params.syntheticsFromTs, 'fromTs'), + toTs: numberField(params.syntheticsToTs, 'toTs'), + probeDc: optionalField(params.syntheticsProbeDc, 'probeDc'), } case 'datadog_trigger_synthetics_tests': - return { ...baseParams, publicIds: params.syntheticsPublicIds } + return { ...baseParams, publicIds: field(params.syntheticsPublicIds, 'publicIds') } case 'datadog_update_synthetics_status': return { ...baseParams, - publicId: params.syntheticsPublicId, - newStatus: params.syntheticsNewStatus, + publicId: field(params.syntheticsPublicId, 'publicId'), + newStatus: field(params.syntheticsNewStatus, 'newStatus'), } case 'datadog_list_security_signals': return { ...baseParams, - query: params.signalQuery || undefined, - from: params.signalFrom || undefined, - to: params.signalTo || undefined, - sort: params.signalSort || undefined, - cursor: params.signalCursor || undefined, - limit: datadogNumber(params.signalLimit), + query: optionalField(params.signalQuery, 'query'), + from: optionalField(params.signalFrom, 'from'), + to: optionalField(params.signalTo, 'to'), + sort: optionalField(params.signalSort, 'sort'), + cursor: optionalField(params.signalCursor, 'cursor'), + limit: numberField(params.signalLimit, 'limit'), } case 'datadog_get_security_signal': @@ -2269,44 +2315,44 @@ Return ONLY the search query string - no explanations.`, return { ...baseParams, signalId: params.signalId, - state: params.signalState, - archiveReason: params.signalArchiveReason || undefined, - archiveComment: params.signalArchiveComment || undefined, + state: field(params.signalState, 'state'), + archiveReason: optionalField(params.signalArchiveReason, 'archiveReason'), + archiveComment: optionalField(params.signalArchiveComment, 'archiveComment'), } case 'datadog_update_security_signal_assignee': return { ...baseParams, signalId: params.signalId, - assigneeUuid: params.signalAssigneeUuid, + assigneeUuid: field(params.signalAssigneeUuid, 'assigneeUuid'), } case 'datadog_list_security_rules': return { ...baseParams, - query: params.ruleQuery || undefined, - sort: params.ruleSort || undefined, - pageSize: datadogNumber(params.rulePageSize), - pageNumber: datadogNumber(params.rulePageNumber), + query: optionalField(params.ruleQuery, 'query'), + sort: optionalField(params.ruleSort, 'sort'), + pageSize: numberField(params.rulePageSize, 'pageSize'), + pageNumber: numberField(params.rulePageNumber, 'pageNumber'), } case 'datadog_search_spans': return { ...baseParams, - query: params.spanQuery || undefined, - from: params.spanFrom || undefined, - to: params.spanTo || undefined, - sort: params.spanSort || undefined, - cursor: params.spanCursor || undefined, - limit: datadogNumber(params.spanLimit), + query: optionalField(params.spanQuery, 'query'), + from: optionalField(params.spanFrom, 'from'), + to: optionalField(params.spanTo, 'to'), + sort: optionalField(params.spanSort, 'sort'), + cursor: optionalField(params.spanCursor, 'cursor'), + limit: numberField(params.spanLimit, 'limit'), } case 'datadog_list_services': return { ...baseParams, - pageSize: datadogNumber(params.servicePageSize), - pageNumber: datadogNumber(params.servicePageNumber), - schemaVersion: params.serviceSchemaVersion || undefined, + pageSize: numberField(params.servicePageSize, 'pageSize'), + pageNumber: numberField(params.servicePageNumber, 'pageNumber'), + schemaVersion: optionalField(params.serviceSchemaVersion, 'schemaVersion'), } default: @@ -2473,7 +2519,10 @@ Return ONLY the search query string - no explanations.`, success: { type: 'boolean', description: 'Whether the operation succeeded' }, series: { type: 'json', description: 'Timeseries data' }, status: { type: 'string', description: 'Query status' }, - errors: { type: 'json', description: 'Metric series rejected during submission' }, + errors: { + type: 'json', + description: 'Metric series rejected during submission, or SLO history query errors', + }, event: { type: 'json', description: 'Event data' }, monitor: { type: 'json', description: 'Monitor data' }, monitors: { type: 'json', description: 'List of monitors' }, @@ -2486,6 +2535,7 @@ Return ONLY the search query string - no explanations.`, downtimes: { type: 'json', description: 'List of downtimes' }, totalCount: { type: 'number', description: 'Total downtimes matching the filter' }, incident: { type: 'json', description: 'Incident data' }, + included: { type: 'json', description: 'Related incident resources requested via include' }, incidents: { type: 'json', description: 'List of incidents' }, nextOffset: { type: 'number', description: 'Offset for the next page of incidents' }, todo: { type: 'json', description: 'Incident follow-up task' }, diff --git a/apps/sim/blocks/blocks/daytona.test.ts b/apps/sim/blocks/blocks/daytona.test.ts new file mode 100644 index 00000000000..8529767cac1 --- /dev/null +++ b/apps/sim/blocks/blocks/daytona.test.ts @@ -0,0 +1,38 @@ +/** + * An Agent tool call runs the block mapper over `{ ...storedRowParams, ...modelArgs }` with the + * operation only in `context`; the tool then receives `{ ...merged, ...mapped }`. + */ +import { describe, expect, it } from 'vitest' +import { DaytonaBlock } from '@/blocks/blocks/daytona' +import { daytonaGitCloneTool } from '@/tools/daytona/git_clone' + +function gitCloneBody(args: Record) { + const mapped = DaytonaBlock.tools.config?.params?.(args, { operation: 'git_clone' }) ?? {} + const body = daytonaGitCloneTool.request.body + if (typeof body !== 'function') throw new Error('git_clone has no body builder') + return body({ ...args, ...mapped } as never) +} + +describe('Daytona git clone on an Agent tool call', () => { + it('sends the repository and path stored on the tool row', () => { + expect( + gitCloneBody({ + apiKey: 'key', + sandboxId: 'sb-1', + repoUrl: 'https://github.com/acme/app.git', + clonePath: '/home/daytona/app', + }) + ).toMatchObject({ url: 'https://github.com/acme/app.git', path: '/home/daytona/app' }) + }) + + it('keeps the repository and path the model supplied', () => { + expect( + gitCloneBody({ + apiKey: 'key', + sandboxId: 'sb-1', + url: 'https://github.com/acme/model.git', + path: '/home/daytona/model', + }) + ).toMatchObject({ url: 'https://github.com/acme/model.git', path: '/home/daytona/model' }) + }) +}) diff --git a/apps/sim/blocks/blocks/daytona.ts b/apps/sim/blocks/blocks/daytona.ts index 46ca0fc2eed..b75d0c6dca3 100644 --- a/apps/sim/blocks/blocks/daytona.ts +++ b/apps/sim/blocks/blocks/daytona.ts @@ -1,7 +1,12 @@ import { DaytonaIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput, withSavedCredential } from '@/blocks/utils' +import { + mapperOperation, + normalizeFileInput, + toolCallArg, + withSavedCredential, +} from '@/blocks/utils' const SANDBOX_SCOPED_OPERATIONS = [ 'execute_command', @@ -452,8 +457,9 @@ export const DaytonaBlock: BlockConfig = { ], config: { tool: (params) => `daytona_${params.operation}`, - params: (params) => { - const { operation, apiKey, ...rest } = params + params: (params, context) => { + const { apiKey, ...rest } = params + const operation = mapperOperation(params, context) const baseParams: Record = { apiKey } @@ -515,8 +521,8 @@ export const DaytonaBlock: BlockConfig = { if (rest.directoryPath) baseParams.path = rest.directoryPath break case 'git_clone': - baseParams.url = rest.repoUrl - baseParams.path = rest.clonePath + baseParams.url = rest.repoUrl || toolCallArg(context, rest.url) || rest.repoUrl + baseParams.path = rest.clonePath || toolCallArg(context, rest.path) || rest.clonePath if (rest.gitBranch) baseParams.branch = rest.gitBranch if (rest.gitCommitId) baseParams.commitId = rest.gitCommitId if (rest.gitUsername) baseParams.username = rest.gitUsername diff --git a/apps/sim/blocks/blocks/deployments.test.ts b/apps/sim/blocks/blocks/deployments.test.ts new file mode 100644 index 00000000000..6c6c2330a21 --- /dev/null +++ b/apps/sim/blocks/blocks/deployments.test.ts @@ -0,0 +1,13 @@ +import { describe, expect, it } from 'vitest' +import { DeploymentsBlock } from '@/blocks/blocks/deployments' + +describe('DeploymentsBlock params on a tool call', () => { + it('keeps the model version label and description for deploy', () => { + expect( + DeploymentsBlock.tools.config?.params?.( + { workflowId: 'wf-1', name: 'Release 4', description: 'Adds retries' }, + { operation: 'deployments_deploy' } + ) + ).toEqual({ workflowId: 'wf-1', name: 'Release 4', description: 'Adds retries' }) + }) +}) diff --git a/apps/sim/blocks/blocks/deployments.ts b/apps/sim/blocks/blocks/deployments.ts index b9e419a7ea6..187db8b7b37 100644 --- a/apps/sim/blocks/blocks/deployments.ts +++ b/apps/sim/blocks/blocks/deployments.ts @@ -1,5 +1,6 @@ import { Rocket } from '@sim/emcn/icons' import type { BlockConfig } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' const WORKFLOW_FIELD = ['workflowSelector', 'manualWorkflowId'] as const @@ -117,8 +118,8 @@ export const DeploymentsBlock: BlockConfig = { ], config: { tool: (params: Record) => params.operation || 'deployments_deploy', - params: (params: Record) => { - const operation = params.operation || 'deployments_deploy' + params: (params: Record, context) => { + const operation = mapperOperation(params, context) || 'deployments_deploy' const workflowId = typeof params.workflowId === 'string' ? params.workflowId.trim() : '' if (!workflowId) { throw new Error('Deployments Block Error: Workflow is required') @@ -127,8 +128,11 @@ export const DeploymentsBlock: BlockConfig = { if (operation === 'deployments_deploy') { return { workflowId, - name: params.versionName?.trim() || undefined, - description: params.versionDescription?.trim() || undefined, + name: params.versionName?.trim() || toolCallArg(context, params.name) || undefined, + description: + params.versionDescription?.trim() || + toolCallArg(context, params.description) || + undefined, } } diff --git a/apps/sim/blocks/blocks/discord.test.ts b/apps/sim/blocks/blocks/discord.test.ts new file mode 100644 index 00000000000..b5e04077270 --- /dev/null +++ b/apps/sim/blocks/blocks/discord.test.ts @@ -0,0 +1,189 @@ +/** + * Agent tool calls pass the operation only in context and supply arguments under the tool's param + * names, so the Discord mapping must run there; canvas "No change" flags must stay unsent. + */ +import { describe, expect, it } from 'vitest' +import { DiscordV2Block } from '@/blocks/blocks/discord' +import { discordAddReactionTool } from '@/tools/discord/add_reaction' +import { discordArchiveThreadTool } from '@/tools/discord/archive_thread' +import { discordBanMemberTool } from '@/tools/discord/ban_member' +import { discordBulkDeleteMessagesTool } from '@/tools/discord/bulk_delete_messages' +import { discordCreateChannelTool } from '@/tools/discord/create_channel' +import { discordGetMessagesTool } from '@/tools/discord/get_messages' +import { discordSendMessageTool } from '@/tools/discord/send_message' +import { discordUpdateMemberTool } from '@/tools/discord/update_member' +import { discordUpdateRoleTool } from '@/tools/discord/update_role' +import type { ToolConfig } from '@/tools/types' + +function sentParams( + inputs: Record, + context?: { operation: string } +): Record { + const mapper = DiscordV2Block.tools.config?.params + if (!mapper) throw new Error('Discord block has no params mapper') + return { ...inputs, ...mapper(inputs, context) } +} + +function requestUrl(tool: ToolConfig, params: Record): string { + const url = tool.request.url + return typeof url === 'function' ? url(params) : url +} + +function requestBody(tool: ToolConfig, params: Record): unknown { + const build = tool.request.body + if (typeof build !== 'function') throw new Error(`${tool.id} has no request body`) + return build(params) +} + +describe('Discord agent tool calls', () => { + it.each([ + ['a comma list from the tool row', '111, 222'], + ['an array from the model', ['111', '222']], + ])('bulk deletes the message IDs given as %s', (_label, messageIds) => { + const params = sentParams( + { botToken: 'bot', serverId: '1', channelId: '9', messageIds }, + { operation: 'discord_bulk_delete_messages' } + ) + expect(requestBody(discordBulkDeleteMessagesTool, params)).toEqual({ + messages: ['111', '222'], + }) + }) + + it.each([ + [true, true], + ['false', false], + ])('sends archived %j to Discord as the boolean %j', (archived, expected) => { + const params = sentParams( + { botToken: 'bot', serverId: '1', threadId: '7', archived }, + { operation: 'discord_archive_thread' } + ) + expect(requestBody(discordArchiveThreadTool, params)).toEqual({ archived: expected }) + }) + + it('runs a channel operation without a server ID, but not a guild operation', () => { + const params = sentParams( + { botToken: 'bot', channelId: '9', messageId: '8', emoji: '👍' }, + { operation: 'discord_add_reaction' } + ) + expect(requestUrl(discordAddReactionTool, params)).toBe( + 'https://discord.com/api/v10/channels/9/messages/8/reactions/%F0%9F%91%8D/@me' + ) + expect(() => + sentParams({ botToken: 'bot', userId: '5' }, { operation: 'discord_get_member' }) + ).toThrow('Server ID is required') + }) + + it("pages messages from the model's cursor, never from a stale pinned-messages timestamp", () => { + const agent = sentParams( + { botToken: 'bot', serverId: '1', channelId: '9', before: '123' }, + { operation: 'discord_get_messages' } + ) + expect(requestUrl(discordGetMessagesTool, agent)).toBe( + 'https://discord.com/api/v10/channels/9/messages?limit=10&before=123' + ) + + const canvas = sentParams({ + operation: 'discord_get_messages', + botToken: 'bot', + serverId: '1', + channelId: '9', + before: '2026-01-01T00:00:00Z', + }) + expect(requestUrl(discordGetMessagesTool, canvas)).toBe( + 'https://discord.com/api/v10/channels/9/messages?limit=10' + ) + }) + + it("creates the model's channel type over the tool row's seeded text-channel option", () => { + const agent = sentParams( + { botToken: 'bot', serverId: '1', name: 'vc', channelType: '0', type: 2 }, + { operation: 'discord_create_channel' } + ) + expect(requestBody(discordCreateChannelTool, agent)).toEqual({ name: 'vc', type: 2 }) + + const canvas = sentParams({ + operation: 'discord_create_channel', + botToken: 'bot', + serverId: '1', + name: 'vc', + channelType: '2', + }) + expect(requestBody(discordCreateChannelTool, canvas)).toEqual({ name: 'vc', type: 2 }) + }) + + it("bans with the model's message purge window over the tool row's seeded zero days", () => { + const agent = sentParams( + { + botToken: 'bot', + serverId: '1', + userId: '5', + deleteMessageDays: '0', + deleteMessageSeconds: 604800, + }, + { operation: 'discord_ban_member' } + ) + expect(requestBody(discordBanMemberTool, agent)).toEqual({ delete_message_seconds: 604800 }) + + const canvas = sentParams({ + operation: 'discord_ban_member', + botToken: 'bot', + serverId: '1', + userId: '5', + deleteMessageDays: '7', + }) + expect(requestBody(discordBanMemberTool, canvas)).toEqual({ delete_message_seconds: 604800 }) + }) +}) + +describe('Discord canvas "No change" flags', () => { + it('renames a member without touching their voice mute or deafen state', () => { + const params = sentParams({ + operation: 'discord_update_member', + botToken: 'bot', + serverId: '1', + userId: '5', + nick: 'Ada', + mute: '', + deaf: '', + }) + expect(requestBody(discordUpdateMemberTool, params)).toEqual({ nick: 'Ada' }) + }) + + it('renames a role without changing whether it is hoisted or mentionable', () => { + const params = sentParams({ + operation: 'discord_update_role', + botToken: 'bot', + serverId: '1', + roleId: '3', + name: 'Mods', + hoist: '', + mentionable: '', + }) + expect(requestBody(discordUpdateRoleTool, params)).toEqual({ name: 'Mods' }) + }) +}) + +describe('Discord request paths', () => { + it('rejects an ID that would steer the bot request to another endpoint', () => { + expect(() => + requestUrl(discordAddReactionTool, { + botToken: 'bot', + channelId: '9/../../guilds/1', + messageId: '8', + emoji: 'x', + }) + ).toThrow('channelId cannot contain a path separator') + }) +}) + +describe('Discord send message', () => { + it('posts a file-only message without placeholder text', () => { + const input = discordSendMessageTool.operation.input({ + botToken: 'bot', + serverId: '1', + channelId: '9', + files: [{ id: 'f', name: 'a.png', url: 'u', size: 1, type: 'image/png', key: 'k' }], + } as never) as { content?: string } + expect(input.content).toBeUndefined() + }) +}) diff --git a/apps/sim/blocks/blocks/discord.ts b/apps/sim/blocks/blocks/discord.ts index 13042e581a0..7675061cd43 100644 --- a/apps/sim/blocks/blocks/discord.ts +++ b/apps/sim/blocks/blocks/discord.ts @@ -1,7 +1,19 @@ import { DiscordIcon } from '@/components/icons' -import type { BlockConfig, BlockMeta, BlockToolParams } from '@/blocks/types' +import type { + BlockConfig, + BlockMeta, + BlockToolParams, + BlockToolParamsContext, +} from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput, withSavedCredential } from '@/blocks/utils' +import { + mapperOperation, + normalizeFileInput, + parseOptionalBooleanInput, + toolCallArg, + withSavedCredential, +} from '@/blocks/utils' +import { parseMessageIds } from '@/tools/discord/bulk_delete_messages' /** * Canonical basic/advanced pair, shared by the card sentences below. Listing @@ -10,16 +22,51 @@ import { normalizeFileInput, withSavedCredential } from '@/blocks/utils' */ const ATTACHMENTS_FIELD = ['attachmentFiles', 'files'] as const -function discordToolParams(params: BlockToolParams, requireBotToken: boolean) { - const commonParams: Record = { +/** Operations whose endpoint is addressed by the guild, so they cannot run without a server ID. */ +const GUILD_SCOPED_OPERATIONS = [ + 'discord_get_server', + 'discord_list_channels', + 'discord_create_channel', + 'discord_create_role', + 'discord_update_role', + 'discord_delete_role', + 'discord_assign_role', + 'discord_remove_role', + 'discord_list_roles', + 'discord_kick_member', + 'discord_ban_member', + 'discord_unban_member', + 'discord_get_member', + 'discord_update_member', +] + +/** + * Leaves a voice or role flag as it is on an update. Listed first so an update, and an Agent tool + * row (which seeds the first option), never overwrite the flag unless one is chosen. + */ +const NO_CHANGE_OPTION = { label: 'No change', id: '' } +const HOIST_YES = { label: 'Yes - Display role members separately', id: 'true' } +const HOIST_NO = { label: "No - Don't display separately", id: 'false' } +const MENTIONABLE_YES = { label: 'Yes - Role can be mentioned', id: 'true' } +const MENTIONABLE_NO = { label: 'No - Role cannot be mentioned', id: 'false' } + +function discordToolParams( + params: BlockToolParams, + requireBotToken: boolean, + context?: BlockToolParamsContext +) { + const operation = mapperOperation(params, context) + const commonParams: Record = { botToken: params.botToken, serverId: params.serverId, } if (requireBotToken && !params.botToken) throw new Error('Bot token is required') - if (!params.serverId) throw new Error('Server ID is required') + if (GUILD_SCOPED_OPERATIONS.includes(operation) && !params.serverId) { + throw new Error('Server ID is required') + } - switch (params.operation) { + switch (operation) { case 'discord_send_message': { return { ...commonParams, @@ -33,6 +80,7 @@ function discordToolParams(params: BlockToolParams, requireBotToken: boolean) { ...commonParams, channelId: params.channelId, limit: params.limit ? Math.min(Math.max(1, Number(params.limit)), 100) : 10, + before: toolCallArg(context, params.before), } case 'discord_get_server': return commonParams @@ -55,10 +103,7 @@ function discordToolParams(params: BlockToolParams, requireBotToken: boolean) { return { ...commonParams, channelId: params.channelId, - messageIds: String(params.messageIds || '') - .split(',') - .map((id: string) => id.trim()) - .filter(Boolean), + messageIds: parseMessageIds(params.messageIds), } case 'discord_get_pinned_messages': return { @@ -83,7 +128,10 @@ function discordToolParams(params: BlockToolParams, requireBotToken: boolean) { channelId: params.channelId, messageId: params.messageId, } - case 'discord_create_thread': + case 'discord_create_thread': { + const isPublic = + toolCallArg(context, parseOptionalBooleanInput(params.isPublic)) ?? + (params.threadVisibility !== undefined ? params.threadVisibility !== 'private' : undefined) return { ...commonParams, channelId: params.channelId, @@ -92,10 +140,9 @@ function discordToolParams(params: BlockToolParams, requireBotToken: boolean) { ...(params.autoArchiveDuration && { autoArchiveDuration: Number(params.autoArchiveDuration), }), - ...(params.threadVisibility !== undefined && { - isPublic: params.threadVisibility !== 'private', - }), + ...(isPublic !== undefined && { isPublic }), } + } case 'discord_join_thread': case 'discord_leave_thread': return { ...commonParams, threadId: params.threadId } @@ -103,16 +150,20 @@ function discordToolParams(params: BlockToolParams, requireBotToken: boolean) { return { ...commonParams, threadId: params.threadId, - archived: params.archived === 'true', + archived: parseOptionalBooleanInput(params.archived) ?? false, } - case 'discord_create_channel': + case 'discord_create_channel': { + const type = + toolCallArg(context, params.type) ?? + (params.channelType ? Number(params.channelType) : undefined) return { ...commonParams, name: params.name, ...(params.topic && { topic: params.topic }), - ...(params.channelType && { type: Number(params.channelType) }), + ...(type !== undefined && { type }), ...(params.parentId && { parentId: params.parentId }), } + } case 'discord_update_channel': return { ...commonParams, @@ -126,26 +177,19 @@ function discordToolParams(params: BlockToolParams, requireBotToken: boolean) { case 'discord_list_channels': return commonParams case 'discord_create_role': + case 'discord_update_role': { + const hoist = parseOptionalBooleanInput(params.hoist) + const mentionable = parseOptionalBooleanInput(params.mentionable) return { ...commonParams, - name: params.name, + ...(operation === 'discord_create_role' + ? { name: params.name } + : { roleId: params.roleId, ...(params.name && { name: params.name }) }), ...(params.color && { color: Number(params.color) }), - ...(params.hoist !== undefined && { hoist: params.hoist === 'true' }), - ...(params.mentionable !== undefined && { - mentionable: params.mentionable === 'true', - }), - } - case 'discord_update_role': - return { - ...commonParams, - roleId: params.roleId, - ...(params.name && { name: params.name }), - ...(params.color && { color: Number(params.color) }), - ...(params.hoist !== undefined && { hoist: params.hoist === 'true' }), - ...(params.mentionable !== undefined && { - mentionable: params.mentionable === 'true', - }), + ...(hoist !== undefined && { hoist }), + ...(mentionable !== undefined && { mentionable }), } + } case 'discord_delete_role': return { ...commonParams, roleId: params.roleId } case 'discord_assign_role': @@ -164,33 +208,40 @@ function discordToolParams(params: BlockToolParams, requireBotToken: boolean) { userId: params.userId, ...(params.reason && { reason: params.reason }), } - case 'discord_ban_member': + case 'discord_ban_member': { + const deleteMessageSeconds = + toolCallArg(context, params.deleteMessageSeconds) ?? + (params.deleteMessageDays ? Number(params.deleteMessageDays) * 86400 : undefined) return { ...commonParams, userId: params.userId, ...(params.reason && { reason: params.reason }), - ...(params.deleteMessageDays && { - deleteMessageSeconds: Number(params.deleteMessageDays) * 86400, - }), + ...(deleteMessageSeconds !== undefined && { deleteMessageSeconds }), } + } case 'discord_get_member': return { ...commonParams, userId: params.userId } - case 'discord_update_member': + case 'discord_update_member': { + const mute = parseOptionalBooleanInput(params.mute) + const deaf = parseOptionalBooleanInput(params.deaf) return { ...commonParams, userId: params.userId, ...(params.nick !== undefined && { nick: params.nick }), - ...(params.mute !== undefined && { mute: params.mute === 'true' }), - ...(params.deaf !== undefined && { deaf: params.deaf === 'true' }), + ...(mute !== undefined && { mute }), + ...(deaf !== undefined && { deaf }), } - case 'discord_create_invite': + } + case 'discord_create_invite': { + const temporary = parseOptionalBooleanInput(params.temporary) return { ...commonParams, channelId: params.channelId, ...(params.maxAge !== undefined && { maxAge: Number(params.maxAge) }), ...(params.maxUses !== undefined && { maxUses: Number(params.maxUses) }), - ...(params.temporary !== undefined && { temporary: params.temporary === 'true' }), + ...(temporary !== undefined && { temporary }), } + } case 'discord_get_invite': case 'discord_delete_invite': return { ...commonParams, inviteCode: params.inviteCode } @@ -434,7 +485,7 @@ export const DiscordBlock: BlockConfig = { title: 'Server ID', type: 'short-input', placeholder: 'Enter Discord server ID', - required: true, + required: { field: 'operation', value: GUILD_SCOPED_OPERATIONS }, serviceId: 'discord', }, // Channel ID - for operations that need it @@ -827,11 +878,17 @@ export const DiscordBlock: BlockConfig = { id: 'hoist', title: 'Display Separately', type: 'dropdown', - options: [ - { label: 'Yes - Display role members separately', id: 'true' }, - { label: "No - Don't display separately", id: 'false' }, - ], - value: () => 'false', + options: ({ values } = { values: {} }) => + values?.operation === 'discord_create_role' + ? [HOIST_NO, HOIST_YES] + : [NO_CHANGE_OPTION, HOIST_YES, HOIST_NO], + value: (p) => + p?.operation === 'discord_create_role' + ? 'false' + : p?.operation === 'discord_update_role' + ? '' + : undefined, + dependsOn: ['operation'], condition: { field: 'operation', value: ['discord_create_role', 'discord_update_role'], @@ -842,11 +899,17 @@ export const DiscordBlock: BlockConfig = { id: 'mentionable', title: 'Mentionable', type: 'dropdown', - options: [ - { label: 'Yes - Role can be mentioned', id: 'true' }, - { label: 'No - Role cannot be mentioned', id: 'false' }, - ], - value: () => 'true', + options: ({ values } = { values: {} }) => + values?.operation === 'discord_create_role' + ? [MENTIONABLE_YES, MENTIONABLE_NO] + : [NO_CHANGE_OPTION, MENTIONABLE_YES, MENTIONABLE_NO], + value: (p) => + p?.operation === 'discord_create_role' + ? 'true' + : p?.operation === 'discord_update_role' + ? '' + : undefined, + dependsOn: ['operation'], condition: { field: 'operation', value: ['discord_create_role', 'discord_update_role'], @@ -874,9 +937,11 @@ export const DiscordBlock: BlockConfig = { title: 'Server Mute', type: 'dropdown', options: [ + NO_CHANGE_OPTION, { label: 'Mute member', id: 'true' }, { label: 'Unmute member', id: 'false' }, ], + value: () => '', condition: { field: 'operation', value: ['discord_update_member'], @@ -888,9 +953,11 @@ export const DiscordBlock: BlockConfig = { title: 'Server Deafen', type: 'dropdown', options: [ + NO_CHANGE_OPTION, { label: 'Deafen member', id: 'true' }, { label: 'Undeafen member', id: 'false' }, ], + value: () => '', condition: { field: 'operation', value: ['discord_update_member'], @@ -1022,7 +1089,7 @@ export const DiscordBlock: BlockConfig = { tool: (params) => { return params.operation || 'discord_send_message' }, - params: (params) => discordToolParams(params, true), + params: (params, context) => discordToolParams(params, true, context), }, }, inputs: { @@ -1190,7 +1257,7 @@ export const DiscordV2Block: BlockConfig = { DiscordBlock, { id: 'credential', type: 'oauth-input', serviceId: 'discord', title: 'Discord Credential' }, { - params: (params) => discordToolParams(params, false), + params: (params, context) => discordToolParams(params, false, context), condition: { field: 'operation', value: 'discord_execute_webhook', not: true }, } ), diff --git a/apps/sim/blocks/blocks/docusign.test.ts b/apps/sim/blocks/blocks/docusign.test.ts index 75a3f62e05c..7176cd0b835 100644 --- a/apps/sim/blocks/blocks/docusign.test.ts +++ b/apps/sim/blocks/blocks/docusign.test.ts @@ -28,3 +28,17 @@ describe('DocuSign List Envelopes status filter', () => { expect(merged.envelopeStatus).toBe('completed') }) }) + +describe('DocuSign agent tool calls', () => { + it('sends the tool row Status setting for Send Envelope', () => { + const mapper = DocuSignBlock.tools.config?.params + if (!mapper) throw new Error('DocuSign block has no params mapper') + + const result = mapper( + { envelopeStatus: 'created', emailSubject: 'Sign', signerEmail: 'a@b.co', signerName: 'A' }, + { operation: 'send_envelope' } + ) + + expect(result.status).toBe('created') + }) +}) diff --git a/apps/sim/blocks/blocks/docusign.ts b/apps/sim/blocks/blocks/docusign.ts index 9efc2329b38..2f854966e70 100644 --- a/apps/sim/blocks/blocks/docusign.ts +++ b/apps/sim/blocks/blocks/docusign.ts @@ -2,7 +2,7 @@ import { DocuSignIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput, toolCallArg } from '@/blocks/utils' +import { mapperOperation, normalizeFileInput, toolCallArg } from '@/blocks/utils' const DOCUMENT_FIELD = ['uploadDocument', 'documentRef'] as const @@ -315,7 +315,8 @@ export const DocuSignBlock: BlockConfig = { config: { tool: (params) => `docusign_${params.operation}`, params: (params, context) => { - const { oauthCredential, operation, documentFile, listEnvelopeStatus, ...rest } = params + const { oauthCredential, documentFile, listEnvelopeStatus, ...rest } = params + const operation = mapperOperation(params, context) const cleanParams: Record = { oauthCredential, @@ -331,14 +332,13 @@ export const DocuSignBlock: BlockConfig = { * merges raw inputs under this result, so the list filter is always assigned explicitly: * otherwise that stored `sent` reached List Envelopes and "All" listed only sent envelopes. */ - if ((operation ?? context?.operation) === 'list_envelopes') { + if (operation === 'list_envelopes') { cleanParams.envelopeStatus = listEnvelopeStatus || toolCallArg(context, rest.envelopeStatus) || undefined } - if (operation === 'create_from_template') { - cleanParams.status = rest.envelopeStatus - } else if (operation === 'send_envelope') { + // A model-supplied `status` is copied over this by the loop below. + if (operation === 'create_from_template' || operation === 'send_envelope') { cleanParams.status = rest.envelopeStatus } diff --git a/apps/sim/blocks/blocks/downdetector.test.ts b/apps/sim/blocks/blocks/downdetector.test.ts new file mode 100644 index 00000000000..eac35c6b617 --- /dev/null +++ b/apps/sim/blocks/blocks/downdetector.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from 'vitest' +import { DowndetectorBlock } from '@/blocks/blocks/downdetector' + +describe('Downdetector agent tool calls', () => { + it('forwards the model page token for Get Site Companies', () => { + const mapper = DowndetectorBlock.tools.config?.params + if (!mapper) throw new Error('Downdetector block has no params mapper') + + const result = mapper( + { siteId: '12', page: 'opaque-token' }, + { operation: 'downdetector_get_site_companies' } + ) + + expect(result.page).toBe('opaque-token') + }) +}) diff --git a/apps/sim/blocks/blocks/downdetector.ts b/apps/sim/blocks/blocks/downdetector.ts index 68a9f570ec1..7d0e8411eb4 100644 --- a/apps/sim/blocks/blocks/downdetector.ts +++ b/apps/sim/blocks/blocks/downdetector.ts @@ -1,6 +1,7 @@ import { DowndetectorIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' const COMPANY_ID_OPERATIONS = [ 'downdetector_get_company', @@ -348,7 +349,7 @@ export const DowndetectorBlock: BlockConfig = { ], config: { tool: (params) => params.operation, - params: (params) => { + params: (params, context) => { const result: Record = {} if (params.categoryId) result.categoryId = Number(params.categoryId) if (params.pageSize) result.pageSize = Number(params.pageSize) @@ -359,8 +360,8 @@ export const DowndetectorBlock: BlockConfig = { // operation uses an integer page number. Always overwrite `page` (with the // token, a number, or undefined) so a stale value from a now-hidden field // can never leak into the wrong endpoint via the merged inputs. - if (params.operation === 'downdetector_get_site_companies') { - result.page = params.pageToken || undefined + if (mapperOperation(params, context) === 'downdetector_get_site_companies') { + result.page = params.pageToken || toolCallArg(context, params.page) || undefined } else { result.page = params.page ? Number(params.page) : undefined } diff --git a/apps/sim/blocks/blocks/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/dub.test.ts b/apps/sim/blocks/blocks/dub.test.ts new file mode 100644 index 00000000000..f67b3f5fa3f --- /dev/null +++ b/apps/sim/blocks/blocks/dub.test.ts @@ -0,0 +1,64 @@ +/** + * Workflow runs hand a tool `{ ...rawInputs, ...mappedParams }`, so the mapper must clear values + * another operation left in a shared subBlock. Agent tool calls pass the operation in context and + * supply arguments under the tool's param names, which the mapper must keep. + */ +import { describe, expect, it } from 'vitest' +import { DubBlock } from '@/blocks/blocks/dub' +import { createLinkTool } from '@/tools/dub/create_link' +import { getAnalyticsTool } from '@/tools/dub/get_analytics' +import type { ToolConfig } from '@/tools/types' + +function workflowParams(inputs: Record): Record { + return { ...inputs, ...(DubBlock.tools.config.params?.(inputs) ?? {}) } +} + +function agentParams(operation: string, args: Record): Record { + return { ...args, ...(DubBlock.tools.config.params?.(args, { operation }) ?? {}) } +} + +function requestUrl(tool: ToolConfig, params: Record): URL { + const url = tool.request.url + return new URL(typeof url === 'function' ? url(params) : url) +} + +function requestBody(tool: ToolConfig, params: Record) { + const body = tool.request.body + if (typeof body !== 'function') throw new Error(`${tool.id} has no request body`) + return body(params) +} + +describe('Dub block parameter mapping', () => { + it('keeps the destination, slug, and conversion flag an agent passes to Create Link', () => { + const params = agentParams('create_link', { + apiKey: 'dub_test', + url: 'https://sim.ai', + domain: 'go.sim.ai', + key: 'launch', + trackConversion: true, + }) + expect(requestBody(createLinkTool, params)).toEqual({ + url: 'https://sim.ai', + domain: 'go.sim.ai', + key: 'launch', + trackConversion: true, + }) + }) + + it('keeps the link and domain filters an agent passes to Get Analytics', () => { + const url = requestUrl( + getAnalyticsTool, + agentParams('get_analytics', { apiKey: 'dub_test', linkId: 'link_1', domain: 'go.sim.ai' }) + ) + expect(url.searchParams.get('linkId')).toBe('link_1') + expect(url.searchParams.get('domain')).toBe('go.sim.ai') + }) + + it('drops a create-link domain left behind when a workflow switches to Get Analytics', () => { + const url = requestUrl( + getAnalyticsTool, + workflowParams({ operation: 'get_analytics', apiKey: 'dub_test', domain: 'stale.sh' }) + ) + expect(url.searchParams.get('domain')).toBeNull() + }) +}) diff --git a/apps/sim/blocks/blocks/dub.ts b/apps/sim/blocks/blocks/dub.ts index 21fa25a17fb..4393a76784c 100644 --- a/apps/sim/blocks/blocks/dub.ts +++ b/apps/sim/blocks/blocks/dub.ts @@ -1,8 +1,8 @@ import { omit } from '@sim/utils/object' import { DubIcon } from '@/components/icons' -import type { BlockConfig, BlockMeta } from '@/blocks/types' +import type { BlockConfig, BlockMeta, BlockToolParamsContext } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { isToolCall, mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' const GET_LINK_FIELD = ['linkId', 'getLinkExternalId', 'getLinkKey'] as const const BULK_UPDATE_TARGET_FIELD = ['bulkUpdateLinkIds', 'bulkUpdateExternalIds'] as const @@ -1032,44 +1032,46 @@ export const DubBlock = { ], config: { tool: (params) => `dub_${params.operation}`, - params: (params) => { + params: (params, context?: BlockToolParamsContext) => { + const operation = mapperOperation(params, context) const result: Record = {} const isLinkMutation = - params.operation === 'create_link' || - params.operation === 'upsert_link' || - params.operation === 'update_link' + operation === 'create_link' || operation === 'upsert_link' || operation === 'update_link' - // The executor merges { ...inputs, ...transformedParams }, so a raw subBlock - // id that shares its name with a tool param (e.g. 'domain', 'linkId') passes - // through untouched unless explicitly cleared here. These fields are only - // shown for the operations below; every other operation must null them out - // so a value left over from a previous operation selection can't leak in. - if (!isLinkMutation) { - result.domain = undefined - result.key = undefined - result.title = undefined - result.description = undefined - result.externalId = undefined - result.tagIds = undefined - result.tenantId = undefined - result.folderId = undefined - result.trackConversion = undefined - } - if (params.operation !== 'create_link' && params.operation !== 'upsert_link') { - result.url = undefined - } - if ( - params.operation !== 'get_link' && - params.operation !== 'update_link' && - params.operation !== 'delete_link' - ) { - result.linkId = undefined - } - if (params.operation !== 'list_links') { - result.search = undefined - result.showArchived = undefined - result.page = undefined - result.pageSize = undefined + /** + * The canvas merges `{ ...inputs, ...mapped }`, so a raw subBlock id that shares its name + * with a tool param (e.g. `domain`, `linkId`) passes through unless cleared here, and a + * value left by another operation would leak in. A tool call carries the model's args + * under those same names for the selected tool, so nothing is cleared there. + */ + if (!isToolCall(context)) { + if (!isLinkMutation) { + result.domain = undefined + result.key = undefined + result.title = undefined + result.description = undefined + result.externalId = undefined + result.tagIds = undefined + result.tenantId = undefined + result.folderId = undefined + result.trackConversion = undefined + } + if (operation !== 'create_link' && operation !== 'upsert_link') { + result.url = undefined + } + if ( + operation !== 'get_link' && + operation !== 'update_link' && + operation !== 'delete_link' + ) { + result.linkId = undefined + } + if (operation !== 'list_links') { + result.search = undefined + result.showArchived = undefined + result.page = undefined + result.pageSize = undefined + } } if (isLinkMutation) { @@ -1077,20 +1079,26 @@ export const DubBlock = { if (params.linkArchived === 'true') result.archived = true if (params.tenantId) result.tenantId = params.tenantId if (params.folderId) result.folderId = params.folderId - // Only ever send `true` or omit — an explicit `false` on update_link would - // silently disable conversion tracking on links that already had it enabled, - // since Dub's update is a partial PATCH (matches linkRewrite/linkArchived). - result.trackConversion = params.trackConversion === 'true' ? true : undefined + // The dropdown only ever sends `true` or omits: a stored `false` on update_link would + // disable tracking on links that had it, since Dub's update is a partial PATCH. A tool + // call keeps the model's own boolean. + result.trackConversion = + params.trackConversion === 'true' + ? true + : toolCallArg( + context, + typeof params.trackConversion === 'boolean' ? params.trackConversion : undefined + ) } - if (params.operation === 'get_link') { + if (operation === 'get_link') { if (params.getLinkExternalId) result.externalId = params.getLinkExternalId if (params.getLinkDomain) result.domain = params.getLinkDomain if (params.getLinkKey) result.key = params.getLinkKey } - if (params.operation === 'update_link' && params.updateUrl) { + if (operation === 'update_link' && params.updateUrl) { result.url = params.updateUrl } - if (params.operation === 'list_links') { + if (operation === 'list_links') { if (params.listDomain) result.domain = params.listDomain if (params.listTagIds) result.tagIds = params.listTagIds if (params.listTenantId) result.tenantId = params.listTenantId @@ -1101,7 +1109,7 @@ export const DubBlock = { if (params.startingAfter) result.startingAfter = params.startingAfter if (params.endingBefore) result.endingBefore = params.endingBefore } - if (params.operation === 'get_analytics') { + if (operation === 'get_analytics') { if (params.analyticsEvent) result.event = params.analyticsEvent if (params.analyticsGroupBy) result.groupBy = params.analyticsGroupBy if (params.analyticsLinkId) result.linkId = params.analyticsLinkId @@ -1113,7 +1121,7 @@ export const DubBlock = { if (params.analyticsCountry) result.country = params.analyticsCountry if (params.analyticsTimezone) result.timezone = params.analyticsTimezone } - if (params.operation === 'get_links_count') { + if (operation === 'get_links_count') { if (params.countSearch) result.search = params.countSearch if (params.countDomain) result.domain = params.countDomain if (params.countTagIds) result.tagIds = params.countTagIds @@ -1122,18 +1130,18 @@ export const DubBlock = { if (params.countShowArchived === 'true') result.showArchived = true if (params.countGroupBy) result.groupBy = params.countGroupBy } - if (params.operation === 'bulk_create_links') { + if (operation === 'bulk_create_links') { if (params.bulkLinks) result.links = params.bulkLinks } - if (params.operation === 'bulk_update_links') { + if (operation === 'bulk_update_links') { if (params.bulkUpdateLinkIds) result.linkIds = params.bulkUpdateLinkIds if (params.bulkUpdateExternalIds) result.externalIds = params.bulkUpdateExternalIds if (params.bulkUpdateData) result.data = params.bulkUpdateData } - if (params.operation === 'bulk_delete_links') { + if (operation === 'bulk_delete_links') { if (params.bulkDeleteLinkIds) result.linkIds = params.bulkDeleteLinkIds } - if (params.operation === 'get_events') { + if (operation === 'get_events') { if (params.eventsEvent) result.event = params.eventsEvent if (params.eventsLinkId) result.linkId = params.eventsLinkId if (params.eventsExternalId) result.externalId = params.eventsExternalId @@ -1147,7 +1155,7 @@ export const DubBlock = { if (params.eventsPage) result.page = Number(params.eventsPage) if (params.eventsLimit) result.limit = Number(params.eventsLimit) } - if (params.operation === 'get_qr_code') { + if (operation === 'get_qr_code') { if (params.qrUrl) result.url = params.qrUrl if (params.qrLogo) result.logo = params.qrLogo if (params.qrSize) result.size = Number(params.qrSize) @@ -1157,24 +1165,24 @@ export const DubBlock = { if (params.qrHideLogo === 'true') result.hideLogo = true if (params.qrMargin) result.margin = Number(params.qrMargin) } - if (params.operation === 'list_domains') { + if (operation === 'list_domains') { if (params.domainsSearch) result.search = params.domainsSearch if (params.domainsArchived === 'true') result.archived = true if (params.domainsPage) result.page = Number(params.domainsPage) if (params.domainsPageSize) result.pageSize = Number(params.domainsPageSize) } - if (params.operation === 'list_tags') { + if (operation === 'list_tags') { if (params.tagsSearch) result.search = params.tagsSearch if (params.tagsSortBy) result.sortBy = params.tagsSortBy if (params.tagsSortOrder) result.sortOrder = params.tagsSortOrder if (params.tagsPage) result.page = Number(params.tagsPage) if (params.tagsPageSize) result.pageSize = Number(params.tagsPageSize) } - if (params.operation === 'create_tag') { + if (operation === 'create_tag') { if (params.tagName) result.name = params.tagName if (params.tagColor) result.color = params.tagColor } - if (params.operation === 'list_folders') { + if (operation === 'list_folders') { if (params.foldersSearch) result.search = params.foldersSearch if (params.foldersPage) result.page = Number(params.foldersPage) if (params.foldersPageSize) result.pageSize = Number(params.foldersPageSize) diff --git a/apps/sim/blocks/blocks/dynamodb.test.ts b/apps/sim/blocks/blocks/dynamodb.test.ts new file mode 100644 index 00000000000..0c12275b26a --- /dev/null +++ b/apps/sim/blocks/blocks/dynamodb.test.ts @@ -0,0 +1,50 @@ +/** + * An Agent tool call runs the block mapper over `{ ...storedRowParams, ...modelArgs }` with the + * operation only in `context`; the internal tool then receives `{ ...merged, ...mapped }`. + */ +import { describe, expect, it } from 'vitest' +import { DynamoDBBlock } from '@/blocks/blocks/dynamodb' + +function toolParams(operation: string, args: Record) { + return { ...args, ...DynamoDBBlock.tools.config?.params?.(args, { operation }) } +} + +const AWS_ARGS = { + region: 'us-east-1', + accessKeyId: 'AKIA', + secretAccessKey: 'secret', + tableName: 'orders', +} + +describe('DynamoDB on an Agent tool call', () => { + it('get sends the primary key stored on the tool row', () => { + expect(toolParams('get', { ...AWS_ARGS, getKey: '{"id":"1"}' }).key).toEqual({ id: '1' }) + }) + + it('scan keeps the index, projection, and consistent read the model supplied', () => { + expect( + toolParams('scan', { + ...AWS_ARGS, + indexName: 'by-status', + projectionExpression: 'id, status', + consistentRead: true, + }) + ).toMatchObject({ + indexName: 'by-status', + projectionExpression: 'id, status', + consistentRead: true, + }) + }) + + it('update keeps the return values the model supplied over the seeded dropdown default', () => { + expect( + toolParams('update', { + ...AWS_ARGS, + updateKey: '{"id":"1"}', + updateExpression: 'SET #s = :s', + updateReturnValues: 'ALL_NEW', + returnValues: 'UPDATED_OLD', + }).returnValues + ).toBe('UPDATED_OLD') + }) +}) diff --git a/apps/sim/blocks/blocks/dynamodb.ts b/apps/sim/blocks/blocks/dynamodb.ts index 1a67c12ad29..a819a1b7486 100644 --- a/apps/sim/blocks/blocks/dynamodb.ts +++ b/apps/sim/blocks/blocks/dynamodb.ts @@ -2,7 +2,7 @@ import { toError } from '@sim/utils/errors' import { DynamoDBIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' export const DynamoDBBlock: BlockConfig = { type: 'dynamodb', @@ -731,7 +731,7 @@ Return ONLY the expression - no explanations.`, throw new Error(`Invalid DynamoDB operation: ${params.operation}`) } }, - params: (params) => { + params: (params, context) => { const parseJson = (value: unknown, fieldName: string) => { if (!value) return undefined if (typeof value === 'object') return value @@ -745,7 +745,7 @@ Return ONLY the expression - no explanations.`, return undefined } - const op = params.operation as string + const op = mapperOperation(params, context) const result: Record = { region: params.region, accessKeyId: params.accessKeyId, @@ -772,7 +772,10 @@ Return ONLY the expression - no explanations.`, if (params.consistentRead === 'true' || params.consistentRead === true) { result.consistentRead = true } - result.projectionExpression = params.getProjectionExpression || undefined + result.projectionExpression = + params.getProjectionExpression || + toolCallArg(context, params.projectionExpression) || + undefined const getNames = parseJson(params.getExpressionAttributeNames, 'expressionAttributeNames') if (getNames !== undefined) result.expressionAttributeNames = getNames } @@ -817,11 +820,14 @@ Return ONLY the expression - no explanations.`, params.scanIndexForward === 'false' || params.scanIndexForward === false ? false : undefined - result.projectionExpression = params.queryProjectionExpression || undefined + result.projectionExpression = + params.queryProjectionExpression || + toolCallArg(context, params.projectionExpression) || + undefined result.consistentRead = params.queryConsistentRead === 'true' || params.queryConsistentRead === true ? true - : undefined + : toolCallArg(context, params.consistentRead) } if (op === 'scan') { @@ -846,11 +852,12 @@ Return ONLY the expression - no explanations.`, if (lim) result.limit = Number.parseInt(String(lim), 10) const esk = parseJson(params.scanExclusiveStartKey, 'exclusiveStartKey') if (esk !== undefined) result.exclusiveStartKey = esk - result.indexName = params.scanIndexName || undefined + result.indexName = + params.scanIndexName || toolCallArg(context, params.indexName) || undefined result.consistentRead = params.scanConsistentRead === 'true' || params.scanConsistentRead === true ? true - : undefined + : toolCallArg(context, params.consistentRead) if ( params.scanSegment !== undefined && params.scanSegment !== null && @@ -882,7 +889,9 @@ Return ONLY the expression - no explanations.`, if (values !== undefined) result.expressionAttributeValues = values if (params.updateConditionExpression) result.conditionExpression = params.updateConditionExpression - if (params.updateReturnValues) result.returnValues = params.updateReturnValues + const returnValues = + toolCallArg(context, params.returnValues) || params.updateReturnValues + if (returnValues) result.returnValues = returnValues } if (op === 'delete') { diff --git a/apps/sim/blocks/blocks/dynatrace.test.ts b/apps/sim/blocks/blocks/dynatrace.test.ts new file mode 100644 index 00000000000..d641f71917b --- /dev/null +++ b/apps/sim/blocks/blocks/dynatrace.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from 'vitest' +import { DynatraceBlock } from '@/blocks/blocks/dynatrace' + +/** + * An agent tool call: the stored row's values and the model's args (keyed by the tool's param + * names) arrive merged, the operation only on `context`, and the executor forwards + * `{ ...params, ...mapped }`. + */ +const agentCall = ( + operation: string, + params: Record +): Record => ({ + ...params, + ...(DynatraceBlock.tools.config?.params?.(params, { operation }) ?? {}), +}) + +describe('DynatraceBlock agent tool calls', () => { + it('forwards the tag key and value set on the tool row to delete_tag', () => { + const mapped = agentCall('dynatrace_delete_tag', { + entitySelector: 'type(HOST)', + tagKey: 'env', + tagValue: 'prod', + }) + expect(mapped).toMatchObject({ key: 'env', value: 'prod' }) + }) + + it('keeps model args named after the tool params when the row fields are blank', () => { + const mapped = agentCall('dynatrace_delete_tag', { + entitySelector: 'type(HOST)', + tagKey: '', + tagValue: '', + key: 'team', + value: 'payments', + }) + expect(mapped).toMatchObject({ key: 'team', value: 'payments' }) + + const monitors = agentCall('dynatrace_list_synthetic_monitors', { + monitorEnabled: '', + enabled: false, + managementZone: 42, + }) + expect(monitors).toMatchObject({ enabled: false, managementZone: 42 }) + }) +}) diff --git a/apps/sim/blocks/blocks/dynatrace.ts b/apps/sim/blocks/blocks/dynatrace.ts index 7d22d6a2153..9cf4edf147f 100644 --- a/apps/sim/blocks/blocks/dynatrace.ts +++ b/apps/sim/blocks/blocks/dynatrace.ts @@ -1,7 +1,7 @@ import { DynatraceIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' /** Operations that accept the shared `from` timeframe parameter. */ const FROM_OPERATIONS = [ @@ -1560,7 +1560,8 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, ], config: { tool: (params) => params.operation, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const baseParams: Record = { environmentUrl: params.environmentUrl, apiToken: params.apiToken, @@ -1581,6 +1582,22 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, return undefined } + /** + * A dedicated block field, else on a tool call the model's arg under the + * tool's own param name. Blank strings fall through to `undefined`. + */ + const pick = (dedicated: unknown, toolParam: string) => + dedicated || toolCallArg(context, params[toolParam]) || undefined + + /** + * A required tool param fed by a differently named block field: the field's + * value, else on a tool call the model's arg when the field is blank. + */ + const orModelArg = (dedicated: unknown, toolParam: string) => + dedicated === undefined || dedicated === null || dedicated === '' + ? (toolCallArg(context, params[toolParam]) ?? dedicated) + : dedicated + const pagination = { pageSize: toNumber(params.pageSize), nextPageKey: params.nextPageKey || undefined, @@ -1588,21 +1605,21 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, // Create and update SLO take the identical definition. const sloWriteParams = { - name: params.sloName, - target: toNumber(params.sloTarget), - warning: toNumber(params.sloWarning), - timeframe: params.sloTimeframe, - evaluationType: params.sloEvaluationType || 'AGGREGATE', - description: params.sloDescription || undefined, - enabled: params.sloEnabled, - filter: params.sloFilter || undefined, - metricExpression: params.sloMetricExpression || undefined, - metricName: params.sloMetricName || undefined, + name: orModelArg(params.sloName, 'name'), + target: toNumber(orModelArg(params.sloTarget, 'target')), + warning: toNumber(orModelArg(params.sloWarning, 'warning')), + timeframe: orModelArg(params.sloTimeframe, 'timeframe'), + evaluationType: pick(params.sloEvaluationType, 'evaluationType') || 'AGGREGATE', + description: pick(params.sloDescription, 'description'), + enabled: orModelArg(params.sloEnabled, 'enabled'), + filter: pick(params.sloFilter, 'filter'), + metricExpression: pick(params.sloMetricExpression, 'metricExpression'), + metricName: pick(params.sloMetricName, 'metricName'), burnRateVisualizationEnabled: params.burnRateVisualizationEnabled, fastBurnThreshold: toNumber(params.fastBurnThreshold), } - switch (params.operation) { + switch (operation) { case 'dynatrace_list_problems': return { ...baseParams, @@ -1611,15 +1628,15 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, to: params.to || undefined, problemSelector: params.problemSelector || undefined, entitySelector: params.entitySelector || undefined, - sort: params.problemSort || undefined, - fields: params.problemFields || undefined, + sort: pick(params.problemSort, 'sort'), + fields: pick(params.problemFields, 'fields'), } case 'dynatrace_get_problem': return { ...baseParams, problemId: params.problemId, - fields: params.problemFields || undefined, + fields: pick(params.problemFields, 'fields'), } case 'dynatrace_close_problem': @@ -1633,7 +1650,7 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, ...baseParams, problemId: params.problemId, message: params.message, - context: params.commentContext || undefined, + context: pick(params.commentContext, 'context'), } case 'dynatrace_query_metrics': @@ -1653,7 +1670,7 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, ...pagination, metricSelector: params.metricSelector || undefined, text: params.text || undefined, - fields: params.metricFields || undefined, + fields: pick(params.metricFields, 'fields'), writtenSince: params.writtenSince || undefined, writtenSinceMode: params.writtenSinceMode || undefined, metadataSelector: params.metadataSelector || undefined, @@ -1663,7 +1680,7 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, return { ...baseParams, metricKey: params.metricKey } case 'dynatrace_ingest_metrics': - return { ...baseParams, payload: params.metricPayload } + return { ...baseParams, payload: orModelArg(params.metricPayload, 'payload') } case 'dynatrace_list_entities': return { @@ -1672,8 +1689,8 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, entitySelector: params.entitySelector, from: params.from || undefined, to: params.to || undefined, - fields: params.entityFields || undefined, - sort: params.entitySort || undefined, + fields: pick(params.entityFields, 'fields'), + sort: pick(params.entitySort, 'sort'), } case 'dynatrace_get_entity': @@ -1682,7 +1699,7 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, entityId: params.entityId, from: params.from || undefined, to: params.to || undefined, - fields: params.entityFields || undefined, + fields: pick(params.entityFields, 'fields'), } case 'dynatrace_list_entity_types': @@ -1710,16 +1727,16 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, startTime: toNumber(params.startTime), endTime: toNumber(params.endTime), eventTimeout: toNumber(params.eventTimeout), - properties: params.eventProperties || undefined, + properties: pick(params.eventProperties, 'properties'), } case 'dynatrace_search_logs': return { ...baseParams, - query: params.logQuery || undefined, + query: pick(params.logQuery, 'query'), from: params.from || undefined, to: params.to || undefined, - sort: params.logSort || undefined, + sort: pick(params.logSort, 'sort'), limit: toNumber(params.limit), nextSliceKey: params.nextSliceKey || undefined, } @@ -1735,7 +1752,7 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, from: params.from || undefined, to: params.to || undefined, timeFrame: params.timeFrame || undefined, - sort: params.sloSort || undefined, + sort: pick(params.sloSort, 'sort'), enabledSlos: params.enabledSlos || undefined, evaluate: params.evaluate, showGlobalSlos: params.showGlobalSlos, @@ -1757,15 +1774,15 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, securityProblemSelector: params.securityProblemSelector || undefined, from: params.from || undefined, to: params.to || undefined, - fields: params.securityFields || undefined, - sort: params.securitySort || undefined, + fields: pick(params.securityFields, 'fields'), + sort: pick(params.securitySort, 'sort'), } case 'dynatrace_get_security_problem': return { ...baseParams, securityProblemId: params.securityProblemId, - fields: params.securityFields || undefined, + fields: pick(params.securityFields, 'fields'), managementZoneFilter: params.managementZoneFilter || undefined, from: params.from || undefined, } @@ -1774,18 +1791,18 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, return { ...baseParams, ...pagination, - filter: params.auditFilter || undefined, + filter: pick(params.auditFilter, 'filter'), from: params.from || undefined, to: params.to || undefined, - sort: params.auditSort || undefined, + sort: pick(params.auditSort, 'sort'), } case 'dynatrace_mute_security_problem': return { ...baseParams, securityProblemId: params.securityProblemId, - reason: params.muteReason, - comment: params.muteComment || undefined, + reason: orModelArg(params.muteReason, 'reason'), + comment: pick(params.muteComment, 'comment'), } case 'dynatrace_unmute_security_problem': @@ -1793,15 +1810,15 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, ...baseParams, securityProblemId: params.securityProblemId, reason: UNMUTE_REASON, - comment: params.muteComment || undefined, + comment: pick(params.muteComment, 'comment'), } case 'dynatrace_mute_security_problems': return { ...baseParams, securityProblemIds: params.securityProblemIds, - reason: params.muteReason, - comment: params.muteComment || undefined, + reason: orModelArg(params.muteReason, 'reason'), + comment: pick(params.muteComment, 'comment'), } case 'dynatrace_unmute_security_problems': @@ -1809,7 +1826,7 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, ...baseParams, securityProblemIds: params.securityProblemIds, reason: UNMUTE_REASON, - comment: params.muteComment || undefined, + comment: pick(params.muteComment, 'comment'), } case 'dynatrace_list_remediation_items': @@ -1826,15 +1843,15 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, attackSelector: params.attackSelector || undefined, from: params.from || undefined, to: params.to || undefined, - fields: params.attackFields || undefined, - sort: params.attackSort || undefined, + fields: pick(params.attackFields, 'fields'), + sort: pick(params.attackSort, 'sort'), } case 'dynatrace_get_attack': return { ...baseParams, attackId: params.attackId, - fields: params.attackFields || undefined, + fields: pick(params.attackFields, 'fields'), } case 'dynatrace_list_tags': @@ -1858,15 +1875,15 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, return { ...baseParams, entitySelector: params.entitySelector, - key: params.tagKey, - value: params.tagValue || undefined, + key: orModelArg(params.tagKey, 'key'), + value: pick(params.tagValue, 'value'), deleteAllWithKey: params.deleteAllWithKey, from: params.from || undefined, to: params.to || undefined, } case 'dynatrace_list_settings_schemas': - return { ...baseParams, fields: params.schemaFields || undefined } + return { ...baseParams, fields: pick(params.schemaFields, 'fields') } case 'dynatrace_list_settings_objects': return { @@ -1875,9 +1892,9 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, schemaIds: params.schemaIds || undefined, scopes: params.scopes || undefined, externalIds: params.externalIds || undefined, - fields: params.settingsFields || undefined, - filter: params.settingsFilter || undefined, - sort: params.settingsSort || undefined, + fields: pick(params.settingsFields, 'fields'), + filter: pick(params.settingsFilter, 'filter'), + sort: pick(params.settingsSort, 'sort'), } case 'dynatrace_get_settings_object': @@ -1888,9 +1905,9 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, ...baseParams, schemaId: params.schemaId, scope: params.scope, - value: params.settingsValue, + value: orModelArg(params.settingsValue, 'value'), schemaVersion: params.schemaVersion || undefined, - externalId: params.settingsExternalId || undefined, + externalId: pick(params.settingsExternalId, 'externalId'), validateOnly: params.validateOnly, } @@ -1898,7 +1915,7 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, return { ...baseParams, objectId: params.objectId, - value: params.settingsValue, + value: orModelArg(params.settingsValue, 'value'), schemaVersion: params.schemaVersion || undefined, updateToken: params.updateToken || undefined, validateOnly: params.validateOnly, @@ -1914,13 +1931,17 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, case 'dynatrace_list_synthetic_monitors': return { ...baseParams, - type: params.monitorType || undefined, + type: pick(params.monitorType, 'type'), // "Any" must send no filter — enabled=false would return only the // disabled monitors, the opposite of what was asked for. - enabled: toOptionalBoolean(params.monitorEnabled), - location: params.monitorLocation || undefined, - tag: params.monitorTag || undefined, - managementZone: toNumber(params.monitorManagementZone), + enabled: + toOptionalBoolean(params.monitorEnabled) ?? + toOptionalBoolean(toolCallArg(context, params.enabled)), + location: pick(params.monitorLocation, 'location'), + tag: pick(params.monitorTag, 'tag'), + managementZone: + toNumber(params.monitorManagementZone) ?? + toNumber(toolCallArg(context, params.managementZone)), } case 'dynatrace_execute_synthetic_monitors': @@ -1931,7 +1952,7 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, failOnPerformanceIssue: params.failOnPerformanceIssue, stopOnProblem: params.stopOnProblem, takeScreenshotsOnSuccess: params.takeScreenshotsOnSuccess, - metadata: params.batchMetadata || undefined, + metadata: pick(params.batchMetadata, 'metadata'), } case 'dynatrace_get_synthetic_batch': @@ -1951,7 +1972,7 @@ Return ONLY the selector string - no explanations, no surrounding quotes.`, problemId: params.problemId, commentId: params.commentId, message: params.message, - context: params.commentContext || undefined, + context: pick(params.commentContext, 'context'), } case 'dynatrace_create_slo': diff --git a/apps/sim/blocks/blocks/elevenlabs.test.ts b/apps/sim/blocks/blocks/elevenlabs.test.ts new file mode 100644 index 00000000000..c228cb5f503 --- /dev/null +++ b/apps/sim/blocks/blocks/elevenlabs.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from 'vitest' +import { ElevenLabsBlock } from '@/blocks/blocks/elevenlabs' + +describe('ElevenLabs agent tool calls', () => { + it('keeps the model voice settings for Edit Voice Settings', () => { + const mapper = ElevenLabsBlock.tools.config?.params + if (!mapper) throw new Error('ElevenLabs block has no params mapper') + + const result = mapper( + { apiKey: 'key', voiceId: 'voice-1', stability: 0.4, style: 0.2, speed: 1.1 }, + { operation: 'edit_voice_settings' } + ) + + expect(result).toMatchObject({ stability: 0.4, style: 0.2, speed: 1.1 }) + }) +}) diff --git a/apps/sim/blocks/blocks/elevenlabs.ts b/apps/sim/blocks/blocks/elevenlabs.ts index 070fc7bc67f..577f3aff755 100644 --- a/apps/sim/blocks/blocks/elevenlabs.ts +++ b/apps/sim/blocks/blocks/elevenlabs.ts @@ -1,6 +1,11 @@ import { ElevenLabsIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' -import { normalizeFileInput, withSavedCredential } from '@/blocks/utils' +import { + mapperOperation, + normalizeFileInput, + toolCallArg, + withSavedCredential, +} from '@/blocks/utils' const VOICE_OPERATIONS = [ 'tts', @@ -331,8 +336,9 @@ export const ElevenLabsBlock: BlockConfig = { ], config: { tool: (params) => `elevenlabs_${params.operation || 'tts'}`, - params: (params) => { + params: (params, context) => { const audioFile = normalizeFileInput(params.audioFile, { single: true }) + const isEditVoiceSettings = mapperOperation(params, context) === 'edit_voice_settings' return { apiKey: params.apiKey, text: params.text, @@ -343,17 +349,18 @@ export const ElevenLabsBlock: BlockConfig = { category: params.category || undefined, nextPageToken: params.nextPageToken || undefined, pageSize: toNumber(params.pageSize), - stability: toNumber( - params.operation === 'edit_voice_settings' ? params.editStability : params.stability - ), - similarityBoost: toNumber( - params.operation === 'edit_voice_settings' - ? params.editSimilarityBoost - : params.similarityBoost - ), - style: toNumber(params.editStyle), - speed: toNumber(params.editSpeed), - useSpeakerBoost: toBoolean(params.editUseSpeakerBoost), + stability: isEditVoiceSettings + ? (toNumber(params.editStability) ?? toNumber(toolCallArg(context, params.stability))) + : toNumber(params.stability), + similarityBoost: isEditVoiceSettings + ? (toNumber(params.editSimilarityBoost) ?? + toNumber(toolCallArg(context, params.similarityBoost))) + : toNumber(params.similarityBoost), + style: toNumber(params.editStyle) ?? toNumber(toolCallArg(context, params.style)), + speed: toNumber(params.editSpeed) ?? toNumber(toolCallArg(context, params.speed)), + useSpeakerBoost: + toBoolean(params.editUseSpeakerBoost) ?? + toBoolean(toolCallArg(context, params.useSpeakerBoost)), durationSeconds: toNumber(params.durationSeconds), promptInfluence: toNumber(params.promptInfluence), loop: toBoolean(params.loop), diff --git a/apps/sim/blocks/blocks/emailbison.test.ts b/apps/sim/blocks/blocks/emailbison.test.ts new file mode 100644 index 00000000000..b55dd5d991a --- /dev/null +++ b/apps/sim/blocks/blocks/emailbison.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from 'vitest' +import { EmailBisonBlock } from '@/blocks/blocks/emailbison' + +describe('Email Bison agent tool calls', () => { + it('keeps the model reply filters for List Replies', () => { + const mapper = EmailBisonBlock.tools.config?.params + if (!mapper) throw new Error('Email Bison block has no params mapper') + + const result = mapper( + { apiKey: 'key', status: 'interested', leadId: 7, tagIds: [3, 4] }, + { operation: 'list_replies' } + ) + + expect(result).toMatchObject({ status: 'interested', leadId: 7, tagIds: [3, 4] }) + }) + + it('keeps the model tag name for Create Tag', () => { + const mapper = EmailBisonBlock.tools.config?.params + if (!mapper) throw new Error('Email Bison block has no params mapper') + + const result = mapper({ apiKey: 'key', name: 'VIP' }, { operation: 'create_tag' }) + + expect(result.name).toBe('VIP') + }) +}) diff --git a/apps/sim/blocks/blocks/emailbison.ts b/apps/sim/blocks/blocks/emailbison.ts index 906fe981a87..2deaaf76726 100644 --- a/apps/sim/blocks/blocks/emailbison.ts +++ b/apps/sim/blocks/blocks/emailbison.ts @@ -1,7 +1,7 @@ import { EmailBisonIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { isToolCall, mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' import { getTrigger } from '@/triggers' const LEAD_MUTATION_OPERATIONS = ['create_lead', 'update_lead'] as const @@ -524,42 +524,58 @@ export const EmailBisonBlock: BlockConfig = { ], config: { tool: (params) => `emailbison_${params.operation}`, - params: (params) => ({ - apiBaseUrl: params.apiBaseUrl, - leadId: - params.operation === 'list_replies' ? toNumberParam(params.replyLeadId) : params.leadId, - leadIds: parseNumberList(params.leadIds), - tagIds: parseNumberList( - params.operation === 'attach_tags_to_leads' ? params.tagIds : params.filterTagIds - ), - excludedTagIds: parseNumberList(params.excludedTagIds), - customVariables: parseJsonArray(params.customVariables), - campaignId: toNumberParam(params.campaignId), - campaignType: emptyToUndefined(params.campaignType), - name: - params.operation === 'create_tag' || params.operation === 'create_campaign' - ? params.operation === 'create_tag' - ? params.tagName - : params.campaignName - : emptyToUndefined(params.campaignName), - action: params.action, - maxEmailsPerDay: toNumberParam(params.maxEmailsPerDay), - maxNewLeadsPerDay: toNumberParam(params.maxNewLeadsPerDay), - sequencePrioritization: emptyToUndefined(params.sequencePrioritization), - plainText: toBooleanParam(params.plainText), - openTracking: toBooleanParam(params.openTracking), - reputationBuilding: toBooleanParam(params.reputationBuilding), - canUnsubscribe: toBooleanParam(params.canUnsubscribe), - includeAutoRepliesInStats: toBooleanParam(params.includeAutoRepliesInStats), - allowParallelSending: toBooleanParam(params.allowParallelSending), - skipWebhooks: toBooleanParam(params.skipWebhooks), - withoutTags: toBooleanParam(params.withoutTags), - read: toBooleanParam(params.read), - senderEmailId: toNumberParam(params.senderEmailId), - campaignStatus: emptyToUndefined(params.campaignStatus), - status: - params.operation === 'list_replies' ? emptyToUndefined(params.replyStatus) : undefined, - }), + params: (params, context) => { + const operation = mapperOperation(params, context) + const toolCall = isToolCall(context) + /** A block-only field; on a tool call a blank one yields to the model's arg under the tool's param name. */ + const blockFieldOr = (blockValue: unknown, modelArg: unknown) => + toolCall ? (emptyToUndefined(blockValue) ?? modelArg) : blockValue + return { + apiBaseUrl: params.apiBaseUrl, + leadId: + operation === 'list_replies' + ? (toNumberParam(params.replyLeadId) ?? + toNumberParam(toolCallArg(context, params.leadId))) + : params.leadId, + leadIds: parseNumberList(params.leadIds), + tagIds: + operation === 'attach_tags_to_leads' + ? parseNumberList(params.tagIds) + : (parseNumberList(params.filterTagIds) ?? + parseNumberList(toolCallArg(context, params.tagIds))), + excludedTagIds: parseNumberList(params.excludedTagIds), + customVariables: parseJsonArray(params.customVariables), + campaignId: toNumberParam(params.campaignId), + campaignType: emptyToUndefined(params.campaignType), + name: + operation === 'create_tag' + ? blockFieldOr(params.tagName, params.name) + : operation === 'create_campaign' + ? blockFieldOr(params.campaignName, params.name) + : (emptyToUndefined(params.campaignName) ?? + emptyToUndefined(toolCallArg(context, params.name))), + action: params.action, + maxEmailsPerDay: toNumberParam(params.maxEmailsPerDay), + maxNewLeadsPerDay: toNumberParam(params.maxNewLeadsPerDay), + sequencePrioritization: emptyToUndefined(params.sequencePrioritization), + plainText: toBooleanParam(params.plainText), + openTracking: toBooleanParam(params.openTracking), + reputationBuilding: toBooleanParam(params.reputationBuilding), + canUnsubscribe: toBooleanParam(params.canUnsubscribe), + includeAutoRepliesInStats: toBooleanParam(params.includeAutoRepliesInStats), + allowParallelSending: toBooleanParam(params.allowParallelSending), + skipWebhooks: toBooleanParam(params.skipWebhooks), + withoutTags: toBooleanParam(params.withoutTags), + read: toBooleanParam(params.read), + senderEmailId: toNumberParam(params.senderEmailId), + campaignStatus: emptyToUndefined(params.campaignStatus), + status: + operation === 'list_replies' + ? (emptyToUndefined(params.replyStatus) ?? + emptyToUndefined(toolCallArg(context, params.status))) + : undefined, + } + }, }, }, inputs: { diff --git a/apps/sim/blocks/blocks/enrich.test.ts b/apps/sim/blocks/blocks/enrich.test.ts new file mode 100644 index 00000000000..7a50b724e4f --- /dev/null +++ b/apps/sim/blocks/blocks/enrich.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from 'vitest' +import { EnrichBlock } from '@/blocks/blocks/enrich' + +describe('Enrich agent tool calls', () => { + it('forwards the model company ID list and location for Search Jobs', () => { + const mapper = EnrichBlock.tools.config?.params + if (!mapper) throw new Error('Enrich block has no params mapper') + + const result = mapper( + { apiKey: 'key', keywords: 'engineer', companyIds: '2048, 3050', location: 'London' }, + { operation: 'search_jobs' } + ) + + expect(result).toMatchObject({ companyIds: '2048, 3050', location: 'London' }) + }) +}) diff --git a/apps/sim/blocks/blocks/enrich.ts b/apps/sim/blocks/blocks/enrich.ts index bc241787cb9..afa0a9a9c80 100644 --- a/apps/sim/blocks/blocks/enrich.ts +++ b/apps/sim/blocks/blocks/enrich.ts @@ -1,7 +1,7 @@ import { EnrichSoIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { isToolCall, mapperOperation, withSavedCredential } from '@/blocks/utils' /** * City and country are independent filters rather than a canonical pair, so the @@ -755,41 +755,51 @@ export const EnrichBlock: BlockConfig = { ], config: { tool: (params) => `enrich_${params.operation}`, - params: (params) => { - const { operation, ...rest } = params - const parsedParams: Record = { ...rest } + params: (params, context) => { + const operation = mapperOperation(params, context) + const toolCall = isToolCall(context) + /** A block-only field; on a tool call a blank one yields to the model's arg under the tool's param name. */ + const blockFieldOr = (blockValue: unknown, modelArg: unknown) => + toolCall && (blockValue === undefined || blockValue === null || blockValue === '') + ? modelArg + : blockValue + const parsedParams: Record = { ...params } try { - if (rest.currentJobTitles && typeof rest.currentJobTitles === 'string') { - parsedParams.currentJobTitles = JSON.parse(rest.currentJobTitles) + if (params.currentJobTitles && typeof params.currentJobTitles === 'string') { + parsedParams.currentJobTitles = JSON.parse(params.currentJobTitles) } - if (rest.skills && typeof rest.skills === 'string') { - parsedParams.skills = JSON.parse(rest.skills) + if (params.skills && typeof params.skills === 'string') { + parsedParams.skills = JSON.parse(params.skills) } - if (rest.industries && typeof rest.industries === 'string') { - parsedParams.industries = JSON.parse(rest.industries) + if (params.industries && typeof params.industries === 'string') { + parsedParams.industries = JSON.parse(params.industries) } - if (rest.companyIds && typeof rest.companyIds === 'string') { - parsedParams.companyIds = JSON.parse(rest.companyIds) + if ( + operation !== 'search_jobs' && + params.companyIds && + typeof params.companyIds === 'string' + ) { + parsedParams.companyIds = JSON.parse(params.companyIds) } - if (rest.jobTitles && typeof rest.jobTitles === 'string') { - parsedParams.jobTitles = JSON.parse(rest.jobTitles) + if (params.jobTitles && typeof params.jobTitles === 'string') { + parsedParams.jobTitles = JSON.parse(params.jobTitles) } - if (rest.accountLocation && typeof rest.accountLocation === 'string') { - parsedParams.accountLocation = JSON.parse(rest.accountLocation) + if (params.accountLocation && typeof params.accountLocation === 'string') { + parsedParams.accountLocation = JSON.parse(params.accountLocation) } - if (rest.employeeSizeRange && typeof rest.employeeSizeRange === 'string') { - parsedParams.employeeSizeRange = JSON.parse(rest.employeeSizeRange) + if (params.employeeSizeRange && typeof params.employeeSizeRange === 'string') { + parsedParams.employeeSizeRange = JSON.parse(params.employeeSizeRange) } - if (rest.filters && typeof rest.filters === 'string') { - parsedParams.filters = JSON.parse(rest.filters) + if (params.filters && typeof params.filters === 'string') { + parsedParams.filters = JSON.parse(params.filters) } } catch (error: any) { throw new Error(`Invalid JSON input: ${error.message}`) } if (operation === 'linkedin_profile') { - parsedParams.url = rest.linkedinUrl + parsedParams.url = blockFieldOr(params.linkedinUrl, params.url) parsedParams.linkedinUrl = undefined } if ( @@ -797,32 +807,32 @@ export const EnrichBlock: BlockConfig = { operation === 'linkedin_to_personal_email' || operation === 'phone_finder' ) { - parsedParams.linkedinProfile = rest.linkedinUrl + parsedParams.linkedinProfile = blockFieldOr(params.linkedinUrl, params.linkedinProfile) parsedParams.linkedinUrl = undefined } if (operation === 'company_lookup') { - parsedParams.name = rest.companyName + parsedParams.name = blockFieldOr(params.companyName, params.name) parsedParams.companyName = undefined } if (operation === 'search_company') { - parsedParams.name = rest.searchCompanyName + parsedParams.name = blockFieldOr(params.searchCompanyName, params.name) parsedParams.searchCompanyName = undefined } if (operation === 'search_similar_companies') { - parsedParams.url = rest.linkedinCompanyUrl + parsedParams.url = blockFieldOr(params.linkedinCompanyUrl, params.url) parsedParams.linkedinCompanyUrl = undefined } if (operation === 'get_post_details') { - parsedParams.url = rest.postUrl + parsedParams.url = blockFieldOr(params.postUrl, params.url) parsedParams.postUrl = undefined } if (operation === 'search_logo') { - parsedParams.url = rest.domain + parsedParams.url = blockFieldOr(params.domain, params.url) } if (operation === 'search_jobs') { - parsedParams.location = rest.jobLocation + parsedParams.location = blockFieldOr(params.jobLocation, params.location) parsedParams.jobLocation = undefined - parsedParams.companyIds = rest.jobCompanyIds + parsedParams.companyIds = blockFieldOr(params.jobCompanyIds, params.companyIds) parsedParams.jobCompanyIds = undefined } diff --git a/apps/sim/blocks/blocks/enrichment.test.ts b/apps/sim/blocks/blocks/enrichment.test.ts new file mode 100644 index 00000000000..c2e0c52ebe5 --- /dev/null +++ b/apps/sim/blocks/blocks/enrichment.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest' +import { EnrichmentBlock } from '@/blocks/blocks/enrichment' +import type { BlockToolParamsContext } from '@/blocks/types' + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = EnrichmentBlock.tools.config?.params + if (!mapper) throw new Error('Enrichment block has no params mapper') + return mapper(params, context) +} + +describe('Enrichment tool calls', () => { + it('runs the row enrichment with the model inputs when the operation arrives only in the context', () => { + expect(mapParams({ inputs: { domain: 'acme.com' } }, { operation: 'company-info' })).toEqual({ + enrichmentId: 'company-info', + inputs: { domain: 'acme.com' }, + }) + }) + + it('lets a value filled on the tool row override the model input', () => { + const mapped = mapParams( + { 'company-info__domain': 'stored.com', inputs: '{"domain":"model.com"}' }, + { operation: 'company-info' } + ) + expect(mapped.inputs).toEqual({ domain: 'stored.com' }) + }) + + it('keeps the model enrichment id when the tool row carries no operation', () => { + expect(mapParams({ enrichmentId: 'company-info' }, { operation: undefined }).enrichmentId).toBe( + 'company-info' + ) + }) +}) diff --git a/apps/sim/blocks/blocks/enrichment.ts b/apps/sim/blocks/blocks/enrichment.ts index 14e6f4f207d..b24c68a75f5 100644 --- a/apps/sim/blocks/blocks/enrichment.ts +++ b/apps/sim/blocks/blocks/enrichment.ts @@ -1,6 +1,8 @@ +import { isPlainRecord } from '@sim/utils/object' import { EnrichmentIcon } from '@/components/icons' import type { BlockConfig, BlockMeta, OutputFieldDefinition, ParamType } from '@/blocks/types' import { IntegrationType } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' import { ALL_ENRICHMENTS, getEnrichment } from '@/enrichments' import { mapFieldType } from '@/enrichments/providers' import type { EnrichmentOutputField } from '@/enrichments/types' @@ -8,6 +10,22 @@ import type { EnrichmentOutputField } from '@/enrichments/types' /** Stable subBlock id for an enrichment input (unique across enrichments). */ const inputFieldId = (enrichmentId: string, inputId: string) => `${enrichmentId}__${inputId}` +/** + * The `inputs` map a model passed on a tool call, as an object or its JSON text. Fields filled on + * the tool row override its entries. + */ +function parseModelInputs(value: unknown): Record { + if (typeof value === 'string') { + try { + const parsed: unknown = JSON.parse(value) + return isPlainRecord(parsed) ? parsed : {} + } catch { + return {} + } + } + return isPlainRecord(value) ? value : {} +} + // One input field per (enrichment, input), shown only for its enrichment. const inputSubBlocks = ALL_ENRICHMENTS.flatMap((enrichment) => enrichment.inputs.map((input) => ({ @@ -141,16 +159,19 @@ export const EnrichmentBlock: BlockConfig = { access: ['enrichment_run'], config: { tool: () => 'enrichment_run', - params: (params) => { - const enrichment = getEnrichment(params.operation) - const inputs: Record = {} + params: (params, context) => { + const operation = mapperOperation(params, context) + const enrichment = getEnrichment(operation) + const inputs: Record = { + ...parseModelInputs(toolCallArg(context, params.inputs)), + } if (enrichment) { for (const input of enrichment.inputs) { const value = params[inputFieldId(enrichment.id, input.id)] if (value !== undefined && value !== '') inputs[input.id] = value } } - return { enrichmentId: params.operation, inputs } + return { enrichmentId: operation || params.enrichmentId, inputs } }, }, }, diff --git a/apps/sim/blocks/blocks/exa.test.ts b/apps/sim/blocks/blocks/exa.test.ts new file mode 100644 index 00000000000..a828ea1ba38 --- /dev/null +++ b/apps/sim/blocks/blocks/exa.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from 'vitest' +import { ExaBlock } from '@/blocks/blocks/exa' +import type { BlockToolParamsContext } from '@/blocks/types' + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = ExaBlock.tools.config?.params + if (!mapper) throw new Error('Exa block has no params mapper') + return mapper(params, context) +} + +describe('Exa legacy Research tool rows', () => { + it('maps the stored research model to an Agent effort when the operation arrives only in the context', () => { + expect( + mapParams({ query: 'q', model: 'exa-research-pro' }, { operation: 'exa_research' }).effort + ).toBe('high') + }) +}) diff --git a/apps/sim/blocks/blocks/exa.ts b/apps/sim/blocks/blocks/exa.ts index 91909da489d..f650d0b5c1a 100644 --- a/apps/sim/blocks/blocks/exa.ts +++ b/apps/sim/blocks/blocks/exa.ts @@ -1,6 +1,7 @@ import { ExaAIIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation } from '@/blocks/utils' /** Categories Exa currently supports. Shared by Search and Find Similar Links. */ const CATEGORY_OPTIONS = [ @@ -588,7 +589,7 @@ export const ExaBlock: BlockConfig = { return 'exa_search' } }, - params: (params) => { + params: (params, context) => { const result: Record = {} if (params.numResults) { result.numResults = Number(params.numResults) @@ -614,7 +615,7 @@ export const ExaBlock: BlockConfig = { * unset value maps to the same depth rather than falling through to * the Agent default of `auto`. */ - if (params.operation === LEGACY_RESEARCH_OPERATION) { + if (mapperOperation(params, context) === LEGACY_RESEARCH_OPERATION) { result.effort = RESEARCH_MODEL_TO_EFFORT[params.model as string] ?? 'medium' } return result diff --git a/apps/sim/blocks/blocks/file.test.ts b/apps/sim/blocks/blocks/file.test.ts index 4355c17297e..1dfa1a1cc32 100644 --- a/apps/sim/blocks/blocks/file.test.ts +++ b/apps/sim/blocks/blocks/file.test.ts @@ -186,4 +186,89 @@ describe('FileV5Block', () => { }) ).toThrow('Manage Sharing accepts a single file at a time') }) + + describe('on a tool call, where the operation arrives only in context', () => { + it('sends the file picked on a Get Content row', () => { + expect( + FileV5Block.tools.config?.params?.( + { getContentInput: 'file-1', offset: 5 }, + { operation: 'file_get_content' } + ) + ).toEqual({ fileId: ['file-1'], workspaceId: undefined }) + }) + + it('keeps the model folder the canonical pass republished as folderRef on write', () => { + expect( + FileV5Block.tools.config?.params?.( + { fileName: 'notes.md', content: 'hi', folderRef: '/Reports' }, + { operation: 'file_write' } + ) + ).toMatchObject({ fileName: 'notes.md', folderPath: '/Reports', content: 'hi' }) + }) + + it('moves the model-named folder under the destination parent the row pins', () => { + expect( + FileV5Block.tools.config?.params?.( + { destinationParentRef: '/Archive', path: '/Reports/Q1', destinationPath: '/Other/Q1' }, + { operation: 'file_update_folder' } + ) + ).toMatchObject({ path: '/Reports/Q1', destinationPath: '/Archive/Q1' }) + }) + + it('creates the model-named folder under the parent the row pins', () => { + expect( + FileV5Block.tools.config?.params?.( + { createParentRef: '/Reports', path: '/Other/New' }, + { operation: 'file_create_folder' } + ) + ).toMatchObject({ path: '/Reports/New' }) + }) + + it('keeps the model path for Create Folder when the row pins no parent', () => { + expect( + FileV5Block.tools.config?.params?.( + { path: '/Other/New' }, + { operation: 'file_create_folder' } + ) + ).toMatchObject({ path: '/Other/New' }) + }) + + /** The tool-call executor spreads the mapper result over the merged row and model params. */ + const toolCallRequest = (params: Record, operation: string) => ({ + ...params, + ...FileV5Block.tools.config?.params?.(params, { operation }), + }) + + it('sends only the row folder on Append when the model also names folderPaths', () => { + const request = toolCallRequest( + { + folderScopeRef: '/Reports', + fileName: 'notes.md', + content: 'x', + folderPaths: ['/Reports'], + }, + 'file_append' + ) + expect(request).toMatchObject({ fileName: 'notes.md', folderPath: '/Reports', content: 'x' }) + expect(request.folderPaths).toBeUndefined() + }) + + it('sends only the model folderPath on Edit when the model names both folder args', () => { + const request = toolCallRequest( + { fileName: 'notes.md', content: 'x', folderRef: '/Reports', folderPaths: ['/Other'] }, + 'file_edit' + ) + expect(request).toMatchObject({ fileName: 'notes.md', folderPath: '/Reports' }) + expect(request.folderPaths).toBeUndefined() + }) + + it('keeps the model folderPaths on Append when the row pins no folder', () => { + const request = toolCallRequest( + { fileName: 'notes.md', content: 'x', folderPaths: ['/Reports', '/Archive'] }, + 'file_append' + ) + expect(request.folderPaths).toEqual(['/Reports', '/Archive']) + expect(request.folderPath).toBeUndefined() + }) + }) }) diff --git a/apps/sim/blocks/blocks/file.ts b/apps/sim/blocks/blocks/file.ts index 628f34a5170..4f54fcd88f3 100644 --- a/apps/sim/blocks/blocks/file.ts +++ b/apps/sim/blocks/blocks/file.ts @@ -8,12 +8,15 @@ import { } from '@/lib/folders/paths' import { readFolderPaths } from '@/lib/folders/selection' import { inferContextFromKey } from '@/lib/uploads/utils/file' -import type { BlockConfig, SubBlockType } from '@/blocks/types' +import type { BlockConfig, BlockToolParamsContext, SubBlockType } from '@/blocks/types' import { IntegrationType } from '@/blocks/types' import { createVersionedToolSelector, + isToolCall, + mapperOperation, normalizeFileInput, parseOptionalNumberInput, + toolCallArg, } from '@/blocks/utils' const logger = createLogger('FileBlock') @@ -184,7 +187,8 @@ interface FileFamilyParams { function fileFamilyInput( params: FileFamilyParams, label: string, - pickerValue: unknown + pickerValue: unknown, + context?: BlockToolParamsContext ): Record { const workspaceId = params._context?.workspaceId const fileIds = pickerValue ? parseReadFileIds(pickerValue) : null @@ -195,6 +199,9 @@ function fileFamilyInput( const folderPaths = folderScopePaths(params.folderScopeRef) if (!folderPaths) { + /* A tool call names its target in the tool's own `fileId` / `folderPaths` args, + which the merged params already carry. */ + if (isToolCall(context)) return { workspaceId } throw new Error(`File or folder is required for ${label}`) } return { @@ -275,6 +282,34 @@ function namedFileTarget( } } +/** + * {@link namedFileTarget} for a mapper that also runs on tool calls, where the stored picker may + * be empty and the model names the file with the tool's own `fileName` and `folderPath` args. The + * model's folder applies only to the model's name, and never beside a scope the row already pins. + * + * The result is spread over the merged row and model params, so a folder arg the model sent stays + * in the request unless it is cleared here; the tool refuses `folderPath` and `folderPaths` together. + */ +function namedFileTargetWithModelFolder( + params: FileFamilyParams & { fileName?: unknown }, + pickerValue: unknown, + label: string, + context: BlockToolParamsContext | undefined, + modelFolderPath: string | undefined +): ReturnType { + const target = namedFileTarget( + params, + pickerValue || toolCallArg(context, params.fileName), + label + ) + if (!isToolCall(context)) return target + if (pickerValue || target.folderPath || target.folderPaths) { + return { folderPath: undefined, folderPaths: undefined, ...target } + } + if (!modelFolderPath) return target + return { ...target, folderPath: modelFolderPath, folderPaths: undefined } +} + /** * A whole number above zero, or nothing. * @@ -663,8 +698,8 @@ export const FileV3Block: BlockConfig = { access: ['file_parser_v3', 'file_get', 'file_write', 'file_append'], config: { tool: (params) => params.operation || 'file_parser_v3', - params: (params) => { - const operation = params.operation || 'file_parser_v3' + params: (params, context) => { + const operation = mapperOperation(params, context) || 'file_parser_v3' if (operation === 'file_write') { return { @@ -676,7 +711,7 @@ export const FileV3Block: BlockConfig = { } if (operation === 'file_append') { - const appendInput = params.appendFileInput + const appendInput = params.appendFileInput || toolCallArg(context, params.fileName) if (!appendInput) { throw new Error('File is required for append') } @@ -696,13 +731,13 @@ export const FileV3Block: BlockConfig = { return { fileName, - content: params.appendContent, + content: params.appendContent ?? toolCallArg(context, params.content), workspaceId: params._context?.workspaceId, } } if (operation === 'file_get') { - const getInput = params.getFileInput + const getInput = params.getFileInput || toolCallArg(context, params.fileId) if (!getInput) { throw new Error('File is required for get') } @@ -974,8 +1009,8 @@ export const FileV4Block: BlockConfig = { if (operation === 'file_fetch') return 'file_fetch' return operation }, - params: (params) => { - const operation = params.operation || 'file_read' + params: (params, context) => { + const operation = mapperOperation(params, context) || 'file_read' if (operation === 'file_write') { return { @@ -987,7 +1022,7 @@ export const FileV4Block: BlockConfig = { } if (operation === 'file_append') { - const appendInput = params.appendFileInput + const appendInput = params.appendFileInput || toolCallArg(context, params.fileName) if (!appendInput) { throw new Error('File is required for append') } @@ -1007,13 +1042,13 @@ export const FileV4Block: BlockConfig = { return { fileName, - content: params.appendContent, + content: params.appendContent ?? toolCallArg(context, params.content), workspaceId: params._context?.workspaceId, } } if (operation === 'file_read') { - const readInput = params.readFileInput + const readInput = params.readFileInput || toolCallArg(context, params.fileId) if (!readInput) { throw new Error('File is required for read') } @@ -1930,8 +1965,13 @@ export const FileV5Block: BlockConfig = { ], config: { tool: (params) => params.operation || 'file_read', - params: (params) => { - const operation = params.operation || 'file_read' + params: (params, context) => { + const operation = mapperOperation(params, context) || 'file_read' + /** + * A tool call's `folderPath` arg shares its name with the basic half of the `folderRef` + * pair, so the canonical pass republishes it as `folderRef`. Read on tool calls only. + */ + const modelFolderPath = toolCallArg(context, optionalText(params.folderRef)) if (operation === 'file_search') { const maxResultsInput = @@ -1968,7 +2008,7 @@ export const FileV5Block: BlockConfig = { Boolean(fileInput) && (params.content == null || params.content === '') return { fileName: params.fileName, - folderPath: optionalText(params.writeFolderRef), + folderPath: optionalText(params.writeFolderRef) ?? modelFolderPath, content: omitContent ? undefined : params.content, ...(fileInput ? { fileInput } : {}), contentType: params.contentType ?? undefined, @@ -1979,21 +2019,26 @@ export const FileV5Block: BlockConfig = { if (operation === 'file_list') { return { - path: optionalText(params.folderRef), - recursive: switchValue(params.folderRecursive), + path: optionalText(params.folderRef) ?? toolCallArg(context, params.path), + recursive: switchValue( + params.folderRecursive, + switchValue(toolCallArg(context, params.recursive)) + ), /* Bounded here as well as at the contract, so a typo fails while configuring rather than on the first run. */ - depth: parseOptionalNumberInput(params.folderDepth, 'Max Depth', { - integer: true, - min: 1, - max: MAX_FOLDER_PATH_SEGMENTS, - }), - search: optionalText(params.folderSearch), - limit: parseOptionalNumberInput(params.folderLimit, 'Limit', { - integer: true, - min: 1, - max: MAX_FILE_LIST_LIMIT, - }), + depth: + parseOptionalNumberInput(params.folderDepth, 'Max Depth', { + integer: true, + min: 1, + max: MAX_FOLDER_PATH_SEGMENTS, + }) ?? toolCallArg(context, params.depth), + search: optionalText(params.folderSearch) ?? toolCallArg(context, params.search), + limit: + parseOptionalNumberInput(params.folderLimit, 'Limit', { + integer: true, + min: 1, + max: MAX_FILE_LIST_LIMIT, + }) ?? toolCallArg(context, params.limit), workspaceId: params._context?.workspaceId, } } @@ -2006,9 +2051,17 @@ export const FileV5Block: BlockConfig = { * tool takes a canonical path. */ const name = optionalText(params.folderName) - const parentPrefix = folderPathPrefix(optionalText(params.createParentRef)) + const createParent = optionalText(params.createParentRef) + const parentPrefix = folderPathPrefix(createParent) + /* A model-supplied path keeps only its last segment when the row pins a parent. */ + const modelPath = toolCallArg(context, optionalText(params.path)) + const modelSegment = modelPath?.split('/').filter(Boolean).pop() return { - path: name ? `${parentPrefix}/${encodeFolderPathSegment(name)}` : undefined, + path: name + ? `${parentPrefix}/${encodeFolderPathSegment(name)}` + : createParent && modelSegment + ? `${parentPrefix}/${modelSegment}` + : modelPath, workspaceId: params._context?.workspaceId, } } @@ -2021,80 +2074,106 @@ export const FileV5Block: BlockConfig = { * carried from the source path's last segment. An unset parent means * the workspace root. Renaming is not a move and is not offered here. */ - const sourcePath = optionalText(params.folderRef) + const sourcePath = + optionalText(params.folderRef) ?? toolCallArg(context, optionalText(params.path)) const segment = sourcePath?.split('/').pop() - const parentPrefix = folderPathPrefix(optionalText(params.destinationParentRef)) + const destinationParent = optionalText(params.destinationParentRef) + const parentPrefix = folderPathPrefix(destinationParent) + /* A model-supplied full destination applies unless the row pins a destination parent. */ + const modelDestination = destinationParent + ? undefined + : toolCallArg(context, optionalText(params.destinationPath)) return { path: sourcePath, - destinationPath: segment ? `${parentPrefix}/${segment}` : undefined, + destinationPath: + modelDestination ?? (segment ? `${parentPrefix}/${segment}` : undefined), workspaceId: params._context?.workspaceId, } } if (operation === 'file_delete_folder') { return { - path: optionalText(params.folderRef), - recursive: switchValue(params.deleteFolderRecursive), + path: optionalText(params.folderRef) ?? toolCallArg(context, params.path), + recursive: switchValue( + params.deleteFolderRecursive, + switchValue(toolCallArg(context, params.recursive)) + ), workspaceId: params._context?.workspaceId, } } if (operation === 'file_move') { return { - fileId: optionalText(params.moveFileId), - folderPath: optionalText(params.moveTargetRef), + fileId: optionalText(params.moveFileId) ?? toolCallArg(context, params.fileId), + folderPath: optionalText(params.moveTargetRef) ?? modelFolderPath, workspaceId: params._context?.workspaceId, } } if (operation === 'file_restore_folder') { return { - folderId: optionalText(params.restoreFolderId), + folderId: optionalText(params.restoreFolderId) ?? toolCallArg(context, params.folderId), workspaceId: params._context?.workspaceId, } } if (operation === 'file_append') { return { - ...namedFileTarget(params, params.appendFileInput, 'append'), - content: params.appendContent, + ...namedFileTargetWithModelFolder( + params, + params.appendFileInput, + 'append', + context, + modelFolderPath + ), + content: params.appendContent ?? toolCallArg(context, params.content), workspaceId: params._context?.workspaceId, } } if (operation === 'file_edit') { - const mode = optionalText(params.editMode) ?? 'search_replace' + const mode = + optionalText(params.editMode) ?? + toolCallArg(context, optionalText(params.mode)) ?? + 'search_replace' if (!FILE_EDIT_MODES.has(mode)) throw new Error('Edit Type is invalid') return { - ...namedFileTarget(params, params.editFileInput, 'edit'), + ...namedFileTargetWithModelFolder( + params, + params.editFileInput, + 'edit', + context, + modelFolderPath + ), mode, - search: params.editSearch, - content: params.editContent ?? '', + search: params.editSearch ?? toolCallArg(context, params.search), + content: params.editContent ?? toolCallArg(context, params.content) ?? '', replaceAll: switchValue(params.replaceAll), beforeAnchor: params.beforeAnchor, afterAnchor: params.afterAnchor, anchor: params.anchor, startAnchor: params.startAnchor, endAnchor: params.endAnchor, - occurrence: parseOptionalNumberInput(params.editOccurrence, 'Anchor Occurrence', { - integer: true, - min: 1, - }), + occurrence: + parseOptionalNumberInput(params.editOccurrence, 'Anchor Occurrence', { + integer: true, + min: 1, + }) ?? toolCallArg(context, params.occurrence), workspaceId: params._context?.workspaceId, } } if (operation === 'file_compress') { return { - ...fileFamilyInput(params, 'compress', params.compressInput), + ...fileFamilyInput(params, 'compress', params.compressInput, context), archiveName: optionalText(params.archiveName), } } if (operation === 'file_decompress') { - const decompressInput = params.decompressInput + const decompressInput = params.decompressInput || toolCallArg(context, params.fileId) if (!decompressInput) { throw new Error('File is required for decompress') } @@ -2126,26 +2205,34 @@ export const FileV5Block: BlockConfig = { } if (operation === 'file_manage_sharing') { - const shareInput = params.shareInput + const shareInput = params.shareInput || toolCallArg(context, params.fileId) if (!shareInput) { throw new Error('File is required to manage sharing') } - const allowedEmails = + const rowEmails = typeof params.shareAllowedEmails === 'string' ? params.shareAllowedEmails .split(/[\n,]/) .map((email) => email.trim()) .filter(Boolean) : undefined + const allowedEmails = rowEmails?.length + ? rowEmails + : (toolCallArg(context, params.allowedEmails) ?? rowEmails) + /* A tool row has no visibility dropdown, so a tool call states the link + with the tool's own `isActive` / `authType` args. */ + const modelSharing = !params.shareVisibility && isToolCall(context) const visibility = (params.shareVisibility as string) || 'public' - const isActive = visibility !== 'private' + const isActive = modelSharing + ? switchValue(params.isActive, true) + : visibility !== 'private' const shareParams = { isActive, // When disabling, leave authType unset so the stored access mode is preserved. - authType: isActive ? visibility : undefined, - password: params.sharePassword, + authType: isActive ? (modelSharing ? params.authType : visibility) : undefined, + password: params.sharePassword ?? toolCallArg(context, params.password), allowedEmails, workspaceId: params._context?.workspaceId, } @@ -2189,13 +2276,13 @@ export const FileV5Block: BlockConfig = { const range = optionalPositiveInt(params.contentOffset, 'Start Line') const count = optionalPositiveInt(params.contentLimit, 'Line Count') return { - ...fileFamilyInput(params, 'get content', params.getContentInput), + ...fileFamilyInput(params, 'get content', params.getContentInput, context), ...(range === undefined ? {} : { offset: range }), ...(count === undefined ? {} : { limit: count }), } } - return fileFamilyInput(params, 'read', params.readFileInput) + return fileFamilyInput(params, 'read', params.readFileInput, context) }, }, }, diff --git a/apps/sim/blocks/blocks/firecrawl.test.ts b/apps/sim/blocks/blocks/firecrawl.test.ts new file mode 100644 index 00000000000..fd3dab6b31a --- /dev/null +++ b/apps/sim/blocks/blocks/firecrawl.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from 'vitest' +import { FirecrawlBlock } from '@/blocks/blocks/firecrawl' +import type { BlockToolParamsContext } from '@/blocks/types' + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = FirecrawlBlock.tools.config?.params + if (!mapper) throw new Error('Firecrawl block has no params mapper') + return mapper(params, context) +} + +describe('Firecrawl tool calls', () => { + it('sends Parse a single document when the model passes it in a list', () => { + const file = { id: 'file-1' } + expect(mapParams({ file: [file] }, { operation: 'parse' }).file).toEqual(file) + }) +}) diff --git a/apps/sim/blocks/blocks/firecrawl.ts b/apps/sim/blocks/blocks/firecrawl.ts index 323f3b8a4b3..128bb994734 100644 --- a/apps/sim/blocks/blocks/firecrawl.ts +++ b/apps/sim/blocks/blocks/firecrawl.ts @@ -1,7 +1,7 @@ import { FirecrawlIcon } from '@/components/icons' import type { BlockConfig, BlockMeta, SubBlockType } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput } from '@/blocks/utils' +import { mapperOperation, normalizeFileInput } from '@/blocks/utils' /** The document being parsed, whether it was uploaded or passed in by reference. */ const DOCUMENT_FIELD = ['fileUpload', 'fileReference'] as const @@ -592,9 +592,9 @@ Example 2 - Product Data: return 'firecrawl_scrape' } }, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { - operation, limit, urls, formats, diff --git a/apps/sim/blocks/blocks/fireflies.test.ts b/apps/sim/blocks/blocks/fireflies.test.ts new file mode 100644 index 00000000000..06ee181af64 --- /dev/null +++ b/apps/sim/blocks/blocks/fireflies.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from 'vitest' +import { FirefliesBlock, FirefliesV2Block } from '@/blocks/blocks/fireflies' +import type { BlockConfig, BlockToolParamsContext } from '@/blocks/types' + +function mapParams( + block: BlockConfig, + params: Record, + context?: BlockToolParamsContext +) { + const mapper = block.tools.config?.params + if (!mapper) throw new Error('Fireflies block has no params mapper') + return mapper(params, context) +} + +describe('Fireflies tool calls', () => { + it('uploads a picked file by its https URL when the operation arrives only in the context', () => { + const mapped = mapParams( + FirefliesV2Block, + { audioFile: { name: 'call.mp3', url: 'https://files.example.com/call.mp3' } }, + { operation: 'fireflies_upload_audio' } + ) + expect(mapped.audioUrl).toBe('https://files.example.com/call.mp3') + expect(mapped.audioFile).toBeUndefined() + }) + + it('keeps the model bite name and a zero start time', () => { + const mapped = mapParams( + FirefliesBlock, + { transcriptId: 't1', startTime: 0, endTime: 30, name: 'Intro', summary: 'Opening' }, + { operation: 'fireflies_create_bite' } + ) + expect(mapped).toMatchObject({ startTime: 0, endTime: 30, name: 'Intro', summary: 'Opening' }) + }) +}) diff --git a/apps/sim/blocks/blocks/fireflies.ts b/apps/sim/blocks/blocks/fireflies.ts index f2da0288c59..cf971fff653 100644 --- a/apps/sim/blocks/blocks/fireflies.ts +++ b/apps/sim/blocks/blocks/fireflies.ts @@ -3,11 +3,21 @@ import { FirefliesIcon } from '@/components/icons' import { resolveHttpsUrlFromFileInput } from '@/lib/uploads/utils/file' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput, withSavedCredential } from '@/blocks/utils' +import { + mapperOperation, + normalizeFileInput, + toolCallArg, + withSavedCredential, +} from '@/blocks/utils' import { getTrigger } from '@/triggers' const AUDIO_FILE_FIELD = ['audioFile', 'audioFileReference'] as const +/** A bite boundary the caller never set; `0` is a valid start time. */ +function isBlankTime(value: unknown): boolean { + return value === undefined || value === null || value === '' +} + export const FirefliesBlock: BlockConfig = { type: 'fireflies', name: 'Fireflies (Legacy)', @@ -523,12 +533,12 @@ Return ONLY the summary text - no quotes, no labels.`, tool: (params) => { return params.operation || 'fireflies_list_transcripts' }, - params: (params) => { + params: (params, context) => { const baseParams: Record = { apiKey: params.apiKey, } - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'fireflies_list_transcripts': return { ...baseParams, @@ -605,7 +615,7 @@ Return ONLY the summary text - no quotes, no labels.`, if (!params.transcriptId?.trim()) { throw new Error('Transcript ID is required.') } - if (!params.startTime || !params.endTime) { + if (isBlankTime(params.startTime) || isBlankTime(params.endTime)) { throw new Error('Start time and end time are required.') } return { @@ -613,16 +623,17 @@ Return ONLY the summary text - no quotes, no labels.`, transcriptId: params.transcriptId.trim(), startTime: Number(params.startTime), endTime: Number(params.endTime), - name: params.biteName?.trim() || undefined, + name: params.biteName?.trim() || toolCallArg(context, params.name) || undefined, mediaType: params.mediaType?.trim() || undefined, - summary: params.biteSummary?.trim() || undefined, + summary: + params.biteSummary?.trim() || toolCallArg(context, params.summary) || undefined, } case 'fireflies_list_bites': return { ...baseParams, transcriptId: params.transcriptId?.trim() || undefined, - mine: true, + mine: toolCallArg(context, params.mine) ?? true, limit: params.limit ? Number(params.limit) : undefined, skip: params.skip ? Number(params.skip) : undefined, } @@ -717,16 +728,18 @@ export const FirefliesV2Block: BlockConfig = { FirefliesBlock.tools?.config?.tool ? FirefliesBlock.tools.config.tool(params) : params.operation || 'fireflies_list_transcripts', - params: (params) => { + params: (params, context) => { const baseParams = FirefliesBlock.tools?.config?.params if (!baseParams) { return params } - if (params.operation === 'fireflies_upload_audio') { - // Use canonical 'audioFile' param directly + if (mapperOperation(params, context) === 'fireflies_upload_audio') { const audioFile = normalizeFileInput(params.audioFile, { single: true }) if (!audioFile) { + if (toolCallArg(context, params.audioUrl?.trim())) { + return baseParams(params, context) + } throw new Error('Audio file is required.') } const audioUrl = resolveHttpsUrlFromFileInput(audioFile) @@ -734,14 +747,17 @@ export const FirefliesV2Block: BlockConfig = { throw new Error('Audio file must include a https URL.') } - return baseParams({ - ...params, - audioUrl, - audioFile: undefined, - }) + return baseParams( + { + ...params, + audioUrl, + audioFile: undefined, + }, + context + ) } - return baseParams(params) + return baseParams(params, context) }, }, }, diff --git a/apps/sim/blocks/blocks/fivetran.test.ts b/apps/sim/blocks/blocks/fivetran.test.ts new file mode 100644 index 00000000000..8ff9bd4e83f --- /dev/null +++ b/apps/sim/blocks/blocks/fivetran.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from 'vitest' +import { FivetranBlock } from '@/blocks/blocks/fivetran' +import type { BlockToolParamsContext } from '@/blocks/types' + +/** Mirrors the tool-call path: the mapper result is spread over the merged params. */ +function toolCallParams(args: Record, context: BlockToolParamsContext) { + const mapper = FivetranBlock.tools.config?.params + if (!mapper) throw new Error('Fivetran block has no params mapper') + return { ...args, ...mapper(args, context) } +} + +describe('Fivetran agent tool calls', () => { + it('pauses the connection when the operation arrives only in the context', () => { + const sent = toolCallParams( + { connectionId: 'c1', syncFrequency: 60 }, + { operation: 'pause_connection' } + ) + expect(sent.paused).toBe(true) + expect(sent.syncFrequency).toBeUndefined() + }) + + it.each([ + ['create_group', { name: 'Analytics' }], + ['create_destination', { groupId: 'g1', service: 'snowflake', config: { host: 'h' } }], + ['update_schema_config', { connectionId: 'c1', schemas: { public: { enabled: true } } }], + [ + 'update_connection_schema', + { connectionId: 'c1', schemaName: 'public', enabled: false, tables: { t: {} } }, + ], + [ + 'update_connection_table', + { connectionId: 'c1', schemaName: 'public', tableName: 't', enabled: true }, + ], + ])('keeps the model arguments for %s', (operation, args) => { + expect(toolCallParams(args, { operation })).toMatchObject(args) + }) +}) diff --git a/apps/sim/blocks/blocks/fivetran.ts b/apps/sim/blocks/blocks/fivetran.ts index 49eb01fe8a5..8eb1d6833a9 100644 --- a/apps/sim/blocks/blocks/fivetran.ts +++ b/apps/sim/blocks/blocks/fivetran.ts @@ -1,5 +1,6 @@ import { FivetranIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' import { getTrigger } from '@/triggers' const CONNECTION_ID_OPS = [ @@ -1058,16 +1059,17 @@ export const FivetranBlock: BlockConfig = { } return `fivetran_${params.operation}` }, - params: (params) => { + params: (params, context) => { const result: Record = {} + const operation = mapperOperation(params, context) const isConnectionSettings = (CONNECTION_SETTINGS_OPS as readonly string[]).includes( - params.operation + operation ) - if (params.operation === 'pause_connection' || params.operation === 'resume_connection') { + if (operation === 'pause_connection' || operation === 'resume_connection') { return { ...PAUSE_ONLY_UPDATE, - paused: params.operation === 'pause_connection', + paused: operation === 'pause_connection', } } @@ -1077,43 +1079,51 @@ export const FivetranBlock: BlockConfig = { result.pauseAfterTrial = toOptionalBoolean(params.pauseAfterTrial) result.dataDelayThreshold = toOptionalNumber(params.dataDelayThreshold) } - if (isConnectionSettings || params.operation === 'create_destination') { + if (isConnectionSettings || operation === 'create_destination') { result.runSetupTests = toOptionalBoolean(params.runSetupTests) } - if (params.operation === 'create_destination') { - result.service = params.destinationService - result.config = params.destinationConfig + if (operation === 'create_destination') { + result.service = params.destinationService ?? toolCallArg(context, params.service) + result.config = params.destinationConfig ?? toolCallArg(context, params.config) result.daylightSavingTimeEnabled = toOptionalBoolean(params.daylightSavingTimeEnabled) } - if (params.operation === 'create_group') result.name = params.groupName - if (params.operation === 'update_schema_config') result.schemas = params.schemasConfig - if (params.operation === 'update_connection_schema') { - result.enabled = toOptionalBoolean(params.schemaEnabled) - result.tables = params.schemaTables + if (operation === 'create_group') { + result.name = params.groupName ?? toolCallArg(context, params.name) + } + if (operation === 'update_schema_config') { + result.schemas = params.schemasConfig ?? toolCallArg(context, params.schemas) + } + if (operation === 'update_connection_schema') { + result.enabled = + toOptionalBoolean(params.schemaEnabled) ?? + toOptionalBoolean(toolCallArg(context, params.enabled)) + result.tables = params.schemaTables ?? toolCallArg(context, params.tables) } - if (params.operation === 'update_connection') { + if (operation === 'update_connection') { result.isHistoricalSync = toOptionalBoolean(params.isHistoricalSync) } - if ((SETUP_TEST_OPS as readonly string[]).includes(params.operation)) { + if ((SETUP_TEST_OPS as readonly string[]).includes(operation)) { result.trustCertificates = toOptionalBoolean(params.trustCertificates) result.trustFingerprints = toOptionalBoolean(params.trustFingerprints) } - if (params.operation === 'sync_connection') result.force = toOptionalBoolean(params.force) - if (params.operation === 'update_connection_table') { - result.enabled = toOptionalBoolean(params.tableEnabled) + if (operation === 'sync_connection') result.force = toOptionalBoolean(params.force) + if (operation === 'update_connection_table') { + result.enabled = + toOptionalBoolean(params.tableEnabled) ?? + toOptionalBoolean(toolCallArg(context, params.enabled)) } - if (params.operation === 'create_connect_card') { + if (operation === 'create_connect_card') { result.hideSetupGuide = toOptionalBoolean(params.hideSetupGuide) result.allFields = toOptionalBoolean(params.allFields) } - if (params.operation === 'run_transformation') { + if (operation === 'run_transformation') { result.fullRefresh = toOptionalBoolean(params.fullRefresh) } - if (params.operation === 'list_users') { + if (operation === 'list_users') { result.active = toOptionalBoolean(params.active) result.hasApiKey = toOptionalBoolean(params.hasApiKey) } - if ((PAGINATED_OPS as readonly string[]).includes(params.operation)) { + if ((PAGINATED_OPS as readonly string[]).includes(operation)) { result.limit = toOptionalNumber(params.limit) } return result diff --git a/apps/sim/blocks/blocks/flint.ts b/apps/sim/blocks/blocks/flint.ts index 02be8b453c4..2ce183ee4f6 100644 --- a/apps/sim/blocks/blocks/flint.ts +++ b/apps/sim/blocks/blocks/flint.ts @@ -1,7 +1,7 @@ import { FlintIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, withSavedCredential } from '@/blocks/utils' /** * Coerces the publish switch value to an explicit boolean, preserving an @@ -155,10 +155,10 @@ Return ONLY the raw JSON array starting with [ and ending with ] - no explanatio access: ['flint_create_task', 'flint_generate_pages', 'flint_get_task'], config: { tool: (params) => params.operation || 'flint_create_task', - params: (params) => { + params: (params, context) => { const base: Record = { apiKey: params.apiKey } - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'flint_generate_pages': return { ...base, diff --git a/apps/sim/blocks/blocks/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/github.ts b/apps/sim/blocks/blocks/github.ts index a40fcf32d95..24e589f502a 100644 --- a/apps/sim/blocks/blocks/github.ts +++ b/apps/sim/blocks/blocks/github.ts @@ -2,7 +2,7 @@ import { Calendar } from '@sim/emcn/icons' import { GithubIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { createVersionedToolSelector, withSavedCredential } from '@/blocks/utils' +import { createVersionedToolSelector, mapperOperation, withSavedCredential } from '@/blocks/utils' import { getTrigger } from '@/triggers' /** Reviewers can be named individually or by team slug; either identifies the request. */ @@ -16,7 +16,9 @@ const REVIEWER_FIELD = ['reviewers', 'team_reviewers'] as const * * `toBoolean` marks a dropdown feeding a boolean tool param: a dropdown stores * its option id, so the value arrives as the string 'true'/'false' and the - * generic handler only JSON-parses `json`/`array` inputs. + * generic handler only JSON-parses `json`/`array` inputs. An entry whose + * `from` equals `to` only coerces; scoping it to the operation whose subBlock + * owns the field keeps a stale value left from another operation raw. */ const GITHUB_PARAM_ALIASES: ReadonlyArray<{ from: string @@ -44,6 +46,44 @@ const GITHUB_PARAM_ALIASES: ReadonlyArray<{ { from: 'fork_name', to: 'name', operations: ['github_fork_repo'] }, { from: 'fork_sort', to: 'sort', operations: ['github_list_forks'] }, { from: 'gist_public', to: 'public', operations: ['github_create_gist'], toBoolean: true }, + { + from: 'draft', + to: 'draft', + operations: ['github_create_pr', 'github_create_release'], + toBoolean: true, + }, + { from: 'prerelease', to: 'prerelease', operations: ['github_create_release'], toBoolean: true }, + { + from: 'default_branch_only', + to: 'default_branch_only', + operations: ['github_fork_repo'], + toBoolean: true, + }, +] + +/** + * Operations whose tools take no `owner`/`repo`: projects are addressed by owner + * login or node ID, gists by gist ID, and searches by query alone. + */ +const OPERATIONS_WITHOUT_REPOSITORY = [ + 'github_list_projects', + 'github_get_project', + 'github_create_project', + 'github_update_project', + 'github_delete_project', + 'github_search_code', + 'github_search_commits', + 'github_search_issues', + 'github_search_repos', + 'github_search_users', + 'github_create_gist', + 'github_get_gist', + 'github_list_gists', + 'github_update_gist', + 'github_delete_gist', + 'github_fork_gist', + 'github_star_gist', + 'github_unstar_gist', ] export const GitHubBlock: BlockConfig = { @@ -472,6 +512,7 @@ export const GitHubBlock: BlockConfig = { type: 'short-input', placeholder: 'e.g., microsoft', required: true, + condition: { field: 'operation', value: OPERATIONS_WITHOUT_REPOSITORY, not: true }, }, { id: 'repo', @@ -479,6 +520,7 @@ export const GitHubBlock: BlockConfig = { type: 'short-input', placeholder: 'e.g., vscode', required: true, + condition: { field: 'operation', value: OPERATIONS_WITHOUT_REPOSITORY, not: true }, }, { id: 'pullNumber', @@ -656,6 +698,7 @@ export const GitHubBlock: BlockConfig = { title: 'State', type: 'dropdown', options: [ + { label: 'No change', id: '' }, { label: 'Open', id: 'open' }, { label: 'Closed', id: 'closed' }, ], @@ -740,7 +783,6 @@ export const GitHubBlock: BlockConfig = { type: 'short-input', placeholder: 'Comma-separated: user1,user2', condition: { field: 'operation', value: 'github_request_reviewers' }, - mode: 'advanced', }, { id: 'team_reviewers', @@ -1042,6 +1084,7 @@ export const GitHubBlock: BlockConfig = { title: 'State', type: 'dropdown', options: [ + { label: 'No change', id: '' }, { label: 'Open', id: 'open' }, { label: 'Closed', id: 'closed' }, ], @@ -1410,6 +1453,7 @@ export const GitHubBlock: BlockConfig = { title: 'Public', type: 'dropdown', options: [ + { label: 'No change', id: '' }, { label: 'Private', id: 'false' }, { label: 'Public', id: 'true' }, ], @@ -1867,6 +1911,8 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, 'github_list_forks', 'github_list_milestones', 'github_list_stargazers', + 'github_list_branches', + 'github_get_pr_files', ], }, mode: 'advanced', @@ -1987,7 +2033,31 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, title: 'Page Number', type: 'short-input', placeholder: 'e.g., 1', - condition: { field: 'operation', value: 'github_list_tags' }, + condition: { + field: 'operation', + value: [ + 'github_list_tags', + 'github_list_branches', + 'github_list_commits', + 'github_list_forks', + 'github_list_gists', + 'github_list_issue_comments', + 'github_list_issues', + 'github_list_milestones', + 'github_list_pr_comments', + 'github_list_prs', + 'github_list_releases', + 'github_list_stargazers', + 'github_list_workflow_runs', + 'github_list_workflows', + 'github_get_pr_files', + 'github_search_code', + 'github_search_commits', + 'github_search_issues', + 'github_search_repos', + 'github_search_users', + ], + }, mode: 'advanced', }, ], @@ -2289,19 +2359,14 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, * block did not supply would clobber a model-supplied value on the agent * path. * - * On the agent tool-calling path `operation` is not part of the params - * this receives: `providers/utils.ts` spreads it in for the tool-selection - * call (`:736-739`) but builds the transform's input from `block.params` - * alone (`:776`). Every alias therefore skips there, which is the same - * behaviour as before this mapper existed - the agent path already works - * because a model supplies `content`/`title`/`sort` by their real names. - * That gap is shared by every block whose mapper branches on - * `params.operation`, so closing it belongs in the provider layer rather - * than here. + * On a tool call (Agent tool row, Pi, Human-in-the-loop) the operation + * arrives only in `context`, so it is read through `mapperOperation`. A + * value the user stored under a block-only id then reaches its tool param, + * and an unset one emits nothing, leaving the model's own argument intact. */ - params: (params) => { + params: (params, context) => { const result: Record = {} - const operation = typeof params.operation === 'string' ? params.operation : '' + const operation = mapperOperation(params, context) const isSet = (value: unknown) => value !== undefined && value !== null && value !== '' diff --git a/apps/sim/blocks/blocks/gitlab.test.ts b/apps/sim/blocks/blocks/gitlab.test.ts index 1d64a625926..ec08815ce2a 100644 --- a/apps/sim/blocks/blocks/gitlab.test.ts +++ b/apps/sim/blocks/blocks/gitlab.test.ts @@ -94,3 +94,219 @@ describe('GitLabBlock access operations', () => { expect(untouched?.admin).toBeUndefined() }) }) + +const blockParams = block.tools.config?.params +if (!blockParams) throw new Error('GitLab block has no params mapper') +const mapParams = blockParams + +/** Runs the mapper the way a tool call does: model/stored args with no operation, which arrives in context. */ +function mapToolCall(operation: string, args: Record) { + return mapParams({ accessToken: 'pat', ...args }, { operation }) +} + +describe('GitLabBlock mapper on tool calls', () => { + it('maps values a tool row stored under block-only fields to the tool params', () => { + expect( + mapToolCall('gitlab_compare_branches', { + projectId: 'g/p', + compareFrom: 'main', + compareTo: 'dev', + }) + ).toMatchObject({ from: 'main', to: 'dev' }) + expect(mapToolCall('gitlab_search_users', { userSearch: 'jdoe' })).toMatchObject({ + search: 'jdoe', + }) + expect( + mapToolCall('gitlab_update_member', { + resourceId: '42', + userId: 7, + memberAccessLevel: 'Maintainer', + }) + ).toMatchObject({ accessLevel: 40, userId: 7 }) + }) + + it("keeps the model's tool-named args when no block field is stored", () => { + expect( + mapToolCall('gitlab_compare_branches', { projectId: 42, from: 'v1', to: 'v2' }) + ).toMatchObject({ projectId: '42', from: 'v1', to: 'v2' }) + expect( + mapToolCall('gitlab_create_user', { + email: 'a@b.com', + username: 'ab', + name: 'A B', + resetPassword: true, + }) + ).toMatchObject({ email: 'a@b.com', username: 'ab', name: 'A B' }) + expect( + mapToolCall('gitlab_update_member', { resourceId: '42', userId: 7, accessLevel: 30 }) + ).toMatchObject({ accessLevel: 30 }) + expect( + mapToolCall('gitlab_list_issues', { projectId: '1', issueState: 'all', state: 'closed' }) + ).toMatchObject({ state: 'closed' }) + }) + + it('accepts the typed arrays and booleans a model sends', () => { + expect( + mapToolCall('gitlab_create_issue', { projectId: '1', title: 'Bug', assigneeIds: [3, 4] }) + ).toMatchObject({ assigneeIds: [3, 4] }) + expect( + mapToolCall('gitlab_create_release', { + projectId: '1', + tagName: 'v1', + milestones: ['M1', 'M2'], + }) + ).toMatchObject({ milestones: ['M1', 'M2'] }) + expect( + mapToolCall('gitlab_create_pipeline', { + projectId: '1', + ref: 'main', + variables: { FOO: 1 }, + }) + ).toMatchObject({ variables: [{ key: 'FOO', value: '1' }] }) + expect( + mapToolCall('gitlab_create_merge_request', { + projectId: '1', + title: 'T', + sourceBranch: 'a', + targetBranch: 'b', + squash: false, + })?.squash + ).toBe(false) + }) + + it('does not apply tool-named fallbacks on the canvas', () => { + const canvas = mapParams({ + accessToken: 'pat', + operation: 'gitlab_list_merge_requests', + projectId: '1', + sourceBranch: 'stale-create-mr-value', + }) + expect(canvas?.sourceBranch).toBeUndefined() + }) + + it('keeps create-only advanced values saved under another operation off update and merge requests', () => { + const canvas = (operation: string, extra: Record) => + mapParams({ + accessToken: 'pat', + operation, + projectId: '1', + issueIid: '2', + mergeRequestIid: '3', + ...extra, + }) + const updateIssue = canvas('gitlab_update_issue', { confidential: true, dueDate: '2026-12-31' }) + expect(updateIssue).toHaveProperty('confidential', undefined) + expect(updateIssue).toHaveProperty('dueDate', undefined) + expect(canvas('gitlab_update_merge_request', { draft: false })).toHaveProperty( + 'draft', + undefined + ) + expect(canvas('gitlab_merge_merge_request', { sha: 'stale-approve-sha' })).toHaveProperty( + 'sha', + undefined + ) + expect(canvas('gitlab_merge_merge_request', { mergeSha: 'abc123' })).toMatchObject({ + sha: 'abc123', + }) + }) + + it("passes the model's update and merge values through on tool calls", () => { + expect( + mapToolCall('gitlab_update_issue', { + projectId: '1', + issueIid: 2, + confidential: false, + dueDate: '2026-12-31', + }) + ).toMatchObject({ confidential: false, dueDate: '2026-12-31' }) + expect( + mapToolCall('gitlab_update_merge_request', { + projectId: '1', + mergeRequestIid: 3, + draft: true, + }) + ).toMatchObject({ draft: true }) + expect( + mapToolCall('gitlab_merge_merge_request', { projectId: '1', mergeRequestIid: 3, sha: 'abc' }) + ).toMatchObject({ sha: 'abc' }) + }) + + it("keeps the model's explicit opt-outs and milestone unassign on tool calls", () => { + expect( + mapToolCall('gitlab_merge_merge_request', { + projectId: '1', + mergeRequestIid: 3, + squash: false, + shouldRemoveSourceBranch: false, + }) + ).toMatchObject({ squash: false, shouldRemoveSourceBranch: false }) + expect( + mapToolCall('gitlab_update_issue', { projectId: '1', issueIid: 2, milestoneId: 0 }) + ).toMatchObject({ milestoneId: 0 }) + expect( + mapToolCall('gitlab_update_merge_request', { + projectId: '1', + mergeRequestIid: 3, + milestoneId: 0, + }) + ).toMatchObject({ milestoneId: 0 }) + expect(mapToolCall('gitlab_list_groups', { allAvailable: false })).toMatchObject({ + allAvailable: false, + }) + }) + + it("keeps the model's empty string that clears a field on tool calls", () => { + expect( + mapToolCall('gitlab_update_issue', { + projectId: '1', + issueIid: 2, + labels: '', + description: '', + }) + ).toMatchObject({ labels: '', description: '' }) + expect( + mapToolCall('gitlab_update_merge_request', { + projectId: '1', + mergeRequestIid: 3, + labels: '', + assigneeIds: '', + }) + ).toMatchObject({ labels: '', assigneeIds: '' }) + expect( + mapToolCall('gitlab_update_member', { + resourceId: '1', + userId: 7, + accessLevel: 30, + expiresAt: '', + }) + ).toMatchObject({ expiresAt: '' }) + expect( + mapToolCall('gitlab_update_invitation', { + resourceId: '1', + email: 'a@b.c', + accessLevel: 30, + expiresAt: '', + }) + ).toMatchObject({ accessLevel: 30, expiresAt: '' }) + expect( + mapToolCall('gitlab_update_invitation', { + resourceId: '1', + email: 'a@b.c', + expiresAt: '', + }) + ).toMatchObject({ expiresAt: '' }) + }) + + it('leaves a blank canvas field unsent on update operations', () => { + const result = mapParams({ + accessToken: 'pat', + operation: 'gitlab_update_issue', + projectId: '1', + issueIid: 2, + labels: '', + description: '', + }) + expect(result?.labels).toBeUndefined() + expect(result?.description).toBeUndefined() + }) +}) diff --git a/apps/sim/blocks/blocks/gitlab.ts b/apps/sim/blocks/blocks/gitlab.ts index a2f5520eb2d..2e87ff0b8d7 100644 --- a/apps/sim/blocks/blocks/gitlab.ts +++ b/apps/sim/blocks/blocks/gitlab.ts @@ -1,7 +1,7 @@ import { GitLabIcon } from '@/components/icons' -import type { BlockConfig, BlockMeta } from '@/blocks/types' +import type { BlockConfig, BlockMeta, BlockToolParamsContext } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' import { coerceGitLabAccessLevel, GITLAB_ACCESS_LEVEL_OPTIONS, @@ -104,11 +104,15 @@ const USER_ID_REQUIRED_OPS = USER_ID_OPS.filter((op) => op !== 'gitlab_add_membe /** * Parses an optional JSON text field at execution time. Returns undefined for - * blank input and throws a field-specific error for malformed JSON. + * blank input and throws a field-specific error for malformed JSON. A tool call + * may already carry the parsed object or array, which passes through. */ -function parseJsonParam(raw: unknown, label: string): any { +function parseJsonParam( + raw: unknown, + label: string +): Record | unknown[] | undefined { if (raw === undefined || raw === null || raw === '') return undefined - let parsed = raw + let parsed: unknown = raw if (typeof raw === 'string') { try { parsed = JSON.parse(raw) @@ -120,7 +124,18 @@ function parseJsonParam(raw: unknown, label: string): any { if (typeof parsed !== 'object') { throw new Error(`${label} must be a JSON object or array.`) } - return parsed + return Array.isArray(parsed) ? parsed : (parsed as Record) +} + +/** + * Parses CI variables (pipeline or job) and normalizes the `{KEY: value}` + * shorthand to GitLab's `[{ key, value }]` array form. + */ +function parseCiVariables(raw: unknown, label: string): unknown[] | undefined { + const parsed = parseJsonParam(raw, label) + if (parsed === undefined) return undefined + if (Array.isArray(parsed)) return parsed + return Object.entries(parsed).map(([key, value]) => ({ key, value: String(value) })) } /** Maps a "Leave unchanged / Yes / No" dropdown value to true, false, or undefined. */ @@ -130,6 +145,62 @@ function parseTriState(raw: unknown): boolean | undefined { return undefined } +/** + * Trimmed text of a string or finite-number input, `''` for anything else. The + * canvas sends text, while a tool call can carry a numeric id (`projectId: 42`). + */ +function inputText(value: unknown): string { + if (typeof value === 'string') return value.trim() + if (typeof value === 'number' && Number.isFinite(value)) return String(value) + return '' +} + +/** {@link inputText}, or `undefined` when blank. */ +function optionalText(value: unknown): string | undefined { + return inputText(value) || undefined +} + +/** + * A model's explicit `''` on a tool call, which GitLab update endpoints read as + * "clear this field". The canvas never forwards a blank field, so this is + * `undefined` there. + */ +function toolCallClear( + value: unknown, + context: BlockToolParamsContext | undefined +): '' | undefined { + return toolCallArg(context, value === '' ? '' : undefined) +} + +/** + * Numeric ids from a comma-separated string (canvas) or the array or number a + * tool call sends. + */ +function parseIdList(value: unknown): number[] | undefined { + if (Array.isArray(value)) return value.map((id) => Number(id)) + if (typeof value === 'number') return [value] + if (typeof value !== 'string' || !value) return undefined + return value.split(',').map((id) => Number(id.trim())) +} + +/** Titles from a comma-separated string (canvas) or the array a tool call sends. */ +function parseTitleList(value: unknown): string[] | undefined { + const items = Array.isArray(value) + ? value.map((title) => String(title)) + : typeof value === 'string' && value + ? value.split(',') + : undefined + return items?.map((title) => title.trim()).filter(Boolean) +} + +/** + * A switch input: the canvas drops an off switch as before, while a tool call + * keeps the model's explicit `false`. + */ +function switchInput(value: unknown, context: BlockToolParamsContext | undefined): unknown { + return value || toolCallArg(context, value === false ? false : undefined) +} + export const GitLabBlock: BlockConfig = { type: 'gitlab', hideFromToolbar: true, @@ -605,6 +676,16 @@ Return ONLY the title - no explanations, no extra text.`, placeholder: 'Describe the issue or merge request...', }, }, + { + id: 'updateTitle', + title: 'Title', + type: 'short-input', + placeholder: 'New title (leave blank to keep the current title)', + condition: { + field: 'operation', + value: ['gitlab_update_issue', 'gitlab_update_merge_request'], + }, + }, { id: 'description', title: 'Description', @@ -975,13 +1056,24 @@ Return ONLY the timestamp string - no explanations, no extra text.`, id: 'sha', title: 'Commit SHA', type: 'short-input', - placeholder: 'Optional HEAD SHA to approve', + placeholder: 'Optional HEAD SHA of the source branch', mode: 'advanced', condition: { field: 'operation', value: ['gitlab_approve_merge_request'], }, }, + { + id: 'mergeSha', + title: 'Commit SHA', + type: 'short-input', + placeholder: 'Optional HEAD SHA of the source branch', + mode: 'advanced', + condition: { + field: 'operation', + value: ['gitlab_merge_merge_request'], + }, + }, { id: 'labels', title: 'Labels', @@ -1032,6 +1124,34 @@ Return ONLY the timestamp string - no explanations, no extra text.`, ], }, }, + { + id: 'dueDate', + title: 'Due Date', + type: 'short-input', + placeholder: 'YYYY-MM-DD (optional)', + mode: 'advanced', + condition: { + field: 'operation', + value: ['gitlab_create_issue'], + }, + wandConfig: { + enabled: true, + prompt: `Generate a due date in YYYY-MM-DD format based on the user's description. + +Return ONLY the date string - no explanations, no extra text.`, + placeholder: 'Describe the due date (e.g., "next Friday")...', + }, + }, + { + id: 'confidential', + title: 'Confidential', + type: 'switch', + mode: 'advanced', + condition: { + field: 'operation', + value: ['gitlab_create_issue'], + }, + }, { id: 'issueState', title: 'State', @@ -1117,6 +1237,38 @@ Return ONLY the timestamp string - no explanations, no extra text.`, value: ['gitlab_create_merge_request', 'gitlab_merge_merge_request'], }, }, + { + id: 'draft', + title: 'Draft', + type: 'switch', + mode: 'advanced', + condition: { + field: 'operation', + value: ['gitlab_create_merge_request'], + }, + }, + { + id: 'mergeWhenPipelineSucceeds', + title: 'Merge When Checks Pass', + type: 'switch', + mode: 'advanced', + description: 'Set the merge request to auto-merge once its checks pass', + condition: { + field: 'operation', + value: ['gitlab_merge_merge_request'], + }, + }, + { + id: 'squashCommitMessage', + title: 'Squash Commit Message', + type: 'long-input', + placeholder: 'Custom squash commit message (optional)', + mode: 'advanced', + condition: { + field: 'operation', + value: ['gitlab_merge_merge_request'], + }, + }, // Tri-state variants for Update MR: a switch cannot express "turn this // off" without also clobbering the setting on every unrelated update. { @@ -2170,59 +2322,70 @@ Return ONLY the JSON array - no explanations, no extra text.`, tool: (params) => { return params.operation || 'gitlab_list_projects' }, - params: (params) => { - const baseParams: Record = { + params: (params, context) => { + const operation = mapperOperation(params, context) + const baseParams: Record = { accessToken: params.accessToken, - host: params.host?.trim() || undefined, + host: optionalText(params.host), } + const projectId = inputText(params.projectId) + const groupId = inputText(params.groupId) + const resourceId = inputText(params.resourceId) + const pagination = { + perPage: params.perPage ? Number(params.perPage) : undefined, + page: params.page ? Number(params.page) : undefined, + } + const sort = params.sortOrder || toolCallArg(context, params.sort) || undefined + /** A block text field, or on a tool call the model's arg under the tool's param name. */ + const textOrToolArg = (blockValue: unknown, toolValue: unknown) => + inputText(blockValue) || inputText(toolCallArg(context, toolValue)) - switch (params.operation) { + switch (operation) { case 'gitlab_list_projects': return { ...baseParams, owned: params.owned || undefined, membership: params.membership || undefined, - search: params.searchQuery?.trim() || undefined, + search: optionalText(params.searchQuery) || toolCallArg(context, params.search), visibility: params.visibility || undefined, - orderBy: params.projectOrderBy || undefined, - sort: params.sortOrder || undefined, - perPage: params.perPage ? Number(params.perPage) : undefined, - page: params.page ? Number(params.page) : undefined, + orderBy: params.projectOrderBy || toolCallArg(context, params.orderBy) || undefined, + sort, + ...pagination, } case 'gitlab_get_project': - if (!params.projectId?.trim()) { + if (!projectId) { throw new Error('Project ID is required.') } return { ...baseParams, - projectId: params.projectId.trim(), + projectId, } case 'gitlab_list_groups': return { ...baseParams, owned: params.owned || undefined, - search: params.searchQuery?.trim() || undefined, - topLevelOnly: params.groupsTopLevelOnly || undefined, + search: optionalText(params.searchQuery) || toolCallArg(context, params.search), + topLevelOnly: + params.groupsTopLevelOnly || toolCallArg(context, params.topLevelOnly) || undefined, visibility: params.visibility || undefined, minAccessLevel: params.groupMinAccessLevel ? Number(params.groupMinAccessLevel) - : undefined, - allAvailable: params.groupAllAvailable || undefined, - orderBy: params.groupOrderBy || undefined, - sort: params.sortOrder || undefined, - perPage: params.perPage ? Number(params.perPage) : undefined, - page: params.page ? Number(params.page) : undefined, + : toolCallArg(context, params.minAccessLevel), + allAvailable: params.groupAllAvailable || toolCallArg(context, params.allAvailable), + orderBy: params.groupOrderBy || toolCallArg(context, params.orderBy) || undefined, + sort, + ...pagination, } case 'gitlab_get_group': - if (!params.groupId?.trim()) { + if (!groupId) { throw new Error('Group ID is required.') } return { ...baseParams, - groupId: params.groupId.trim(), + groupId, } case 'gitlab_list_user_memberships': { @@ -2234,21 +2397,22 @@ Return ONLY the JSON array - no explanations, no extra text.`, ...baseParams, userId: membershipUserId, membershipType: params.membershipType || undefined, - perPage: params.perPage ? Number(params.perPage) : undefined, - page: params.page ? Number(params.page) : undefined, + ...pagination, } } case 'gitlab_list_issues': - if (!params.projectId?.trim()) { + if (!projectId) { throw new Error('Project ID is required.') } return { ...baseParams, - projectId: params.projectId.trim(), - state: params.issueState !== 'all' ? params.issueState : undefined, - labels: params.labels?.trim() || undefined, - search: params.searchQuery?.trim() || undefined, + projectId, + state: + (params.issueState !== 'all' ? params.issueState : undefined) || + toolCallArg(context, params.state), + labels: optionalText(params.labels), + search: optionalText(params.searchQuery) || toolCallArg(context, params.search), assigneeId: (() => { const raw = String(params.assigneeId ?? '').trim() if (!raw) return undefined @@ -2256,479 +2420,483 @@ Return ONLY the JSON array - no explanations, no extra text.`, if (Number.isNaN(parsed)) throw new Error('Assignee ID must be a number.') return parsed })(), - milestoneTitle: params.milestoneTitle?.trim() || undefined, - orderBy: params.issueOrderBy || undefined, - sort: params.sortOrder || undefined, - perPage: params.perPage ? Number(params.perPage) : undefined, - page: params.page ? Number(params.page) : undefined, + milestoneTitle: optionalText(params.milestoneTitle), + orderBy: params.issueOrderBy || toolCallArg(context, params.orderBy) || undefined, + sort, + ...pagination, } case 'gitlab_get_issue': - if (!params.projectId?.trim() || !params.issueIid) { + if (!projectId || !params.issueIid) { throw new Error('Project ID and Issue Number are required.') } return { ...baseParams, - projectId: params.projectId.trim(), + projectId, issueIid: Number(params.issueIid), } - case 'gitlab_create_issue': - if (!params.projectId?.trim() || !params.title?.trim()) { + case 'gitlab_create_issue': { + const title = inputText(params.title) + if (!projectId || !title) { throw new Error('Project ID and title are required.') } return { ...baseParams, - projectId: params.projectId.trim(), - title: params.title.trim(), - description: params.description?.trim() || undefined, - labels: params.labels?.trim() || undefined, - assigneeIds: params.assigneeIds - ? params.assigneeIds.split(',').map((id: string) => Number(id.trim())) - : undefined, + projectId, + title, + description: optionalText(params.description), + labels: optionalText(params.labels), + assigneeIds: parseIdList(params.assigneeIds), milestoneId: params.milestoneId ? Number(params.milestoneId) : undefined, + dueDate: optionalText(params.dueDate), + confidential: switchInput(params.confidential, context), } + } case 'gitlab_update_issue': - if (!params.projectId?.trim() || !params.issueIid) { + if (!projectId || !params.issueIid) { throw new Error('Project ID and Issue IID are required.') } return { ...baseParams, - projectId: params.projectId.trim(), + projectId, issueIid: Number(params.issueIid), - title: params.title?.trim() || undefined, - description: params.description?.trim() || undefined, - labels: params.labels?.trim() || undefined, - assigneeIds: params.assigneeIds - ? params.assigneeIds.split(',').map((id: string) => Number(id.trim())) - : undefined, - milestoneId: params.milestoneId ? Number(params.milestoneId) : undefined, + title: optionalText(params.updateTitle) || optionalText(params.title), + description: + optionalText(params.description) ?? toolCallClear(params.description, context), + labels: optionalText(params.labels) ?? toolCallClear(params.labels, context), + assigneeIds: parseIdList(params.assigneeIds), + milestoneId: params.milestoneId + ? Number(params.milestoneId) + : toolCallArg(context, params.milestoneId === 0 ? 0 : undefined), stateEvent: params.stateEvent || undefined, + dueDate: toolCallArg(context, params.dueDate), + confidential: toolCallArg(context, params.confidential), } case 'gitlab_delete_issue': - if (!params.projectId?.trim() || !params.issueIid) { + if (!projectId || !params.issueIid) { throw new Error('Project ID and Issue IID are required.') } return { ...baseParams, - projectId: params.projectId.trim(), + projectId, issueIid: Number(params.issueIid), } - case 'gitlab_create_issue_note': - if (!params.projectId?.trim() || !params.issueIid || !params.body?.trim()) { + case 'gitlab_create_issue_note': { + const body = inputText(params.body) + if (!projectId || !params.issueIid || !body) { throw new Error('Project ID, Issue IID, and comment body are required.') } return { ...baseParams, - projectId: params.projectId.trim(), + projectId, issueIid: Number(params.issueIid), - body: params.body.trim(), - internal: params.internalNote || undefined, + body, + internal: params.internalNote || toolCallArg(context, params.internal) || undefined, } + } case 'gitlab_list_merge_requests': - if (!params.projectId?.trim()) { + if (!projectId) { throw new Error('Project ID is required.') } return { ...baseParams, - projectId: params.projectId.trim(), - state: params.mrState !== 'all' ? params.mrState : undefined, - labels: params.labels?.trim() || undefined, - sourceBranch: params.sourceBranchFilter?.trim() || undefined, - targetBranch: params.targetBranchFilter?.trim() || undefined, - orderBy: params.mrOrderBy || undefined, - sort: params.sortOrder || undefined, - perPage: params.perPage ? Number(params.perPage) : undefined, - page: params.page ? Number(params.page) : undefined, + projectId, + state: + (params.mrState !== 'all' ? params.mrState : undefined) || + toolCallArg(context, params.state), + labels: optionalText(params.labels), + sourceBranch: + textOrToolArg(params.sourceBranchFilter, params.sourceBranch) || undefined, + targetBranch: + textOrToolArg(params.targetBranchFilter, params.targetBranch) || undefined, + orderBy: params.mrOrderBy || toolCallArg(context, params.orderBy) || undefined, + sort, + ...pagination, } case 'gitlab_get_merge_request': - if (!params.projectId?.trim() || !params.mergeRequestIid) { + if (!projectId || !params.mergeRequestIid) { throw new Error('Project ID and Merge Request IID are required.') } return { ...baseParams, - projectId: params.projectId.trim(), + projectId, mergeRequestIid: Number(params.mergeRequestIid), } - case 'gitlab_create_merge_request': - if ( - !params.projectId?.trim() || - !params.title?.trim() || - !params.sourceBranch?.trim() || - !params.targetBranch?.trim() - ) { + case 'gitlab_create_merge_request': { + const title = inputText(params.title) + const sourceBranch = inputText(params.sourceBranch) + const targetBranch = inputText(params.targetBranch) + if (!projectId || !title || !sourceBranch || !targetBranch) { throw new Error('Project ID, title, source branch, and target branch are required.') } return { ...baseParams, - projectId: params.projectId.trim(), - title: params.title.trim(), - sourceBranch: params.sourceBranch.trim(), - targetBranch: params.targetBranch.trim(), - description: params.description?.trim() || undefined, - labels: params.labels?.trim() || undefined, - assigneeIds: params.assigneeIds - ? params.assigneeIds.split(',').map((id: string) => Number(id.trim())) - : undefined, + projectId, + title, + sourceBranch, + targetBranch, + description: optionalText(params.description), + labels: optionalText(params.labels), + assigneeIds: parseIdList(params.assigneeIds), milestoneId: params.milestoneId ? Number(params.milestoneId) : undefined, - removeSourceBranch: params.removeSourceBranch || undefined, - squash: params.squash || undefined, + removeSourceBranch: switchInput(params.removeSourceBranch, context), + squash: switchInput(params.squash, context), + draft: switchInput(params.draft, context), } + } case 'gitlab_update_merge_request': - if (!params.projectId?.trim() || !params.mergeRequestIid) { + if (!projectId || !params.mergeRequestIid) { throw new Error('Project ID and Merge Request IID are required.') } return { ...baseParams, - projectId: params.projectId.trim(), + projectId, mergeRequestIid: Number(params.mergeRequestIid), - title: params.title?.trim() || undefined, - description: params.description?.trim() || undefined, - labels: params.labels?.trim() || undefined, - assigneeIds: params.assigneeIds - ? params.assigneeIds.split(',').map((id: string) => Number(id.trim())) - : undefined, - milestoneId: params.milestoneId ? Number(params.milestoneId) : undefined, + title: optionalText(params.updateTitle) || optionalText(params.title), + description: + optionalText(params.description) ?? toolCallClear(params.description, context), + labels: optionalText(params.labels) ?? toolCallClear(params.labels, context), + assigneeIds: + parseIdList(params.assigneeIds) ?? toolCallClear(params.assigneeIds, context), + milestoneId: params.milestoneId + ? Number(params.milestoneId) + : toolCallArg(context, params.milestoneId === 0 ? 0 : undefined), stateEvent: params.stateEvent || undefined, - removeSourceBranch: parseTriState(params.updateRemoveSourceBranch), - squash: parseTriState(params.updateSquash), + removeSourceBranch: + parseTriState(params.updateRemoveSourceBranch) ?? + parseTriState(toolCallArg(context, params.removeSourceBranch)), + squash: + parseTriState(params.updateSquash) ?? + parseTriState(toolCallArg(context, params.squash)), + draft: toolCallArg(context, params.draft), } case 'gitlab_merge_merge_request': - if (!params.projectId?.trim() || !params.mergeRequestIid) { + if (!projectId || !params.mergeRequestIid) { throw new Error('Project ID and Merge Request IID are required.') } return { ...baseParams, - projectId: params.projectId.trim(), + projectId, mergeRequestIid: Number(params.mergeRequestIid), - mergeCommitMessage: params.mergeCommitMessage?.trim() || undefined, - squash: params.squash || undefined, - shouldRemoveSourceBranch: params.removeSourceBranch || undefined, - } - - case 'gitlab_create_merge_request_note': - if (!params.projectId?.trim() || !params.mergeRequestIid || !params.body?.trim()) { + mergeCommitMessage: optionalText(params.mergeCommitMessage), + squashCommitMessage: optionalText(params.squashCommitMessage), + squash: switchInput(params.squash, context), + shouldRemoveSourceBranch: + params.removeSourceBranch || toolCallArg(context, params.shouldRemoveSourceBranch), + mergeWhenPipelineSucceeds: switchInput(params.mergeWhenPipelineSucceeds, context), + sha: textOrToolArg(params.mergeSha, params.sha) || undefined, + } + + case 'gitlab_create_merge_request_note': { + const body = inputText(params.body) + if (!projectId || !params.mergeRequestIid || !body) { throw new Error('Project ID, Merge Request IID, and comment body are required.') } return { ...baseParams, - projectId: params.projectId.trim(), + projectId, mergeRequestIid: Number(params.mergeRequestIid), - body: params.body.trim(), - internal: params.internalNote || undefined, + body, + internal: params.internalNote || toolCallArg(context, params.internal) || undefined, } + } case 'gitlab_list_pipelines': - if (!params.projectId?.trim()) { + if (!projectId) { throw new Error('Project ID is required.') } return { ...baseParams, - projectId: params.projectId.trim(), - status: params.pipelineStatus || undefined, - ref: params.ref?.trim() || undefined, - orderBy: params.pipelineOrderBy || undefined, - sort: params.sortOrder || undefined, - perPage: params.perPage ? Number(params.perPage) : undefined, - page: params.page ? Number(params.page) : undefined, + projectId, + status: params.pipelineStatus || toolCallArg(context, params.status) || undefined, + ref: optionalText(params.ref), + orderBy: params.pipelineOrderBy || toolCallArg(context, params.orderBy) || undefined, + sort, + ...pagination, } case 'gitlab_get_pipeline': - if (!params.projectId?.trim() || !params.pipelineId) { + if (!projectId || !params.pipelineId) { throw new Error('Project ID and Pipeline ID are required.') } return { ...baseParams, - projectId: params.projectId.trim(), + projectId, pipelineId: Number(params.pipelineId), } - case 'gitlab_create_pipeline': - if (!params.projectId?.trim() || !params.ref?.trim()) { + case 'gitlab_create_pipeline': { + const ref = inputText(params.ref) + if (!projectId || !ref) { throw new Error('Project ID and branch/tag ref are required.') } return { ...baseParams, - projectId: params.projectId.trim(), - ref: params.ref.trim(), - variables: (() => { - const parsed = parseJsonParam(params.pipelineVariables, 'Pipeline Variables') - if (parsed === undefined) return undefined - // Accept {KEY: value} shorthand and normalize to GitLab's array form. - if (!Array.isArray(parsed) && typeof parsed === 'object') { - return Object.entries(parsed).map(([key, value]) => ({ - key, - value: String(value), - })) - } - return parsed - })(), - inputs: parseJsonParam(params.pipelineInputs, 'Pipeline Inputs'), + projectId, + ref, + variables: + parseCiVariables(params.pipelineVariables, 'Pipeline Variables') ?? + parseCiVariables(toolCallArg(context, params.variables), 'Pipeline Variables'), + inputs: + parseJsonParam(params.pipelineInputs, 'Pipeline Inputs') ?? + parseJsonParam(toolCallArg(context, params.inputs), 'Pipeline Inputs'), } + } case 'gitlab_retry_pipeline': case 'gitlab_cancel_pipeline': - if (!params.projectId?.trim() || !params.pipelineId) { + if (!projectId || !params.pipelineId) { throw new Error('Project ID and Pipeline ID are required.') } return { ...baseParams, - projectId: params.projectId.trim(), + projectId, pipelineId: Number(params.pipelineId), } case 'gitlab_list_repository_tree': - if (!params.projectId?.trim()) { + if (!projectId) { throw new Error('Project ID is required.') } return { ...baseParams, - projectId: params.projectId.trim(), - path: params.path?.trim() || undefined, - ref: params.ref?.trim() || undefined, + projectId, + path: optionalText(params.path), + ref: optionalText(params.ref), recursive: params.recursive || undefined, - perPage: params.perPage ? Number(params.perPage) : undefined, - page: params.page ? Number(params.page) : undefined, + ...pagination, } - case 'gitlab_get_file': - if (!params.projectId?.trim() || !params.filePath?.trim() || !params.ref?.trim()) { + case 'gitlab_get_file': { + const filePath = inputText(params.filePath) + const ref = inputText(params.ref) + if (!projectId || !filePath || !ref) { throw new Error('Project ID, file path, and ref are required.') } return { ...baseParams, - projectId: params.projectId.trim(), - filePath: params.filePath.trim(), - ref: params.ref.trim(), + projectId, + filePath, + ref, } + } case 'gitlab_create_file': - case 'gitlab_update_file': - if ( - !params.projectId?.trim() || - !params.filePath?.trim() || - !params.branch?.trim() || - !params.content || - !params.commitMessage?.trim() - ) { + case 'gitlab_update_file': { + const filePath = inputText(params.filePath) + const branch = inputText(params.branch) + const commitMessage = inputText(params.commitMessage) + if (!projectId || !filePath || !branch || !params.content || !commitMessage) { throw new Error( 'Project ID, file path, branch, content, and commit message are required.' ) } return { ...baseParams, - projectId: params.projectId.trim(), - filePath: params.filePath.trim(), - branch: params.branch.trim(), + projectId, + filePath, + branch, content: params.content, - commitMessage: params.commitMessage.trim(), - startBranch: params.startBranch?.trim() || undefined, - authorName: params.authorName?.trim() || undefined, - authorEmail: params.authorEmail?.trim() || undefined, + commitMessage, + startBranch: optionalText(params.startBranch), + authorName: optionalText(params.authorName), + authorEmail: optionalText(params.authorEmail), executeFilemode: parseTriState(params.executeFilemode), - ...(params.operation === 'gitlab_update_file' - ? { lastCommitId: params.lastCommitId?.trim() || undefined } + ...(operation === 'gitlab_update_file' + ? { lastCommitId: optionalText(params.lastCommitId) } : {}), } + } - case 'gitlab_create_branch': - if (!params.projectId?.trim() || !params.branch?.trim() || !params.ref?.trim()) { + case 'gitlab_create_branch': { + const branch = inputText(params.branch) + const ref = inputText(params.ref) + if (!projectId || !branch || !ref) { throw new Error('Project ID, branch name, and source ref are required.') } return { ...baseParams, - projectId: params.projectId.trim(), - branch: params.branch.trim(), - ref: params.ref.trim(), + projectId, + branch, + ref, } + } case 'gitlab_list_branches': - if (!params.projectId?.trim()) { + if (!projectId) { throw new Error('Project ID is required.') } return { ...baseParams, - projectId: params.projectId.trim(), - search: params.query?.trim() || undefined, - perPage: params.perPage ? Number(params.perPage) : undefined, - page: params.page ? Number(params.page) : undefined, + projectId, + search: optionalText(params.query) || toolCallArg(context, params.search), + ...pagination, } - case 'gitlab_delete_branch': - if (!params.projectId?.trim() || !params.branch?.trim()) { + case 'gitlab_delete_branch': { + const branch = inputText(params.branch) + if (!projectId || !branch) { throw new Error('Project ID and branch name are required.') } return { ...baseParams, - projectId: params.projectId.trim(), - branch: params.branch.trim(), + projectId, + branch, } + } - case 'gitlab_compare_branches': - if ( - !params.projectId?.trim() || - !params.compareFrom?.trim() || - !params.compareTo?.trim() - ) { + case 'gitlab_compare_branches': { + const from = textOrToolArg(params.compareFrom, params.from) + const to = textOrToolArg(params.compareTo, params.to) + if (!projectId || !from || !to) { throw new Error('Project ID, from ref, and to ref are required.') } return { ...baseParams, - projectId: params.projectId.trim(), - from: params.compareFrom.trim(), - to: params.compareTo.trim(), + projectId, + from, + to, straight: params.straight || undefined, - fromProjectId: params.fromProjectId?.trim() || undefined, + fromProjectId: optionalText(params.fromProjectId), unidiff: params.unidiff || undefined, } + } case 'gitlab_list_commits': - if (!params.projectId?.trim()) { + if (!projectId) { throw new Error('Project ID is required.') } return { ...baseParams, - projectId: params.projectId.trim(), - refName: params.refName?.trim() || undefined, - since: params.since?.trim() || undefined, - until: params.until?.trim() || undefined, - path: params.path?.trim() || undefined, - author: params.author?.trim() || undefined, - perPage: params.perPage ? Number(params.perPage) : undefined, - page: params.page ? Number(params.page) : undefined, + projectId, + refName: optionalText(params.refName), + since: optionalText(params.since), + until: optionalText(params.until), + path: optionalText(params.path), + author: optionalText(params.author), + ...pagination, } case 'gitlab_get_merge_request_changes': - if (!params.projectId?.trim() || !params.mergeRequestIid) { + if (!projectId || !params.mergeRequestIid) { throw new Error('Project ID and Merge Request IID are required.') } return { ...baseParams, - projectId: params.projectId.trim(), + projectId, mergeRequestIid: Number(params.mergeRequestIid), } case 'gitlab_approve_merge_request': - if (!params.projectId?.trim() || !params.mergeRequestIid) { + if (!projectId || !params.mergeRequestIid) { throw new Error('Project ID and Merge Request IID are required.') } return { ...baseParams, - projectId: params.projectId.trim(), + projectId, mergeRequestIid: Number(params.mergeRequestIid), - sha: params.sha?.trim() || undefined, + sha: optionalText(params.sha), } case 'gitlab_list_pipeline_jobs': - if (!params.projectId?.trim() || !params.pipelineId) { + if (!projectId || !params.pipelineId) { throw new Error('Project ID and Pipeline ID are required.') } return { ...baseParams, - projectId: params.projectId.trim(), + projectId, pipelineId: Number(params.pipelineId), scope: params.scope || undefined, includeRetried: params.includeRetried || undefined, - perPage: params.perPage ? Number(params.perPage) : undefined, - page: params.page ? Number(params.page) : undefined, + ...pagination, } case 'gitlab_get_job_log': - if (!params.projectId?.trim() || !params.jobId) { + if (!projectId || !params.jobId) { throw new Error('Project ID and Job ID are required.') } return { ...baseParams, - projectId: params.projectId.trim(), + projectId, jobId: Number(params.jobId), } case 'gitlab_play_job': - if (!params.projectId?.trim() || !params.jobId) { + if (!projectId || !params.jobId) { throw new Error('Project ID and Job ID are required.') } return { ...baseParams, - projectId: params.projectId.trim(), + projectId, jobId: Number(params.jobId), - jobVariables: (() => { - const parsed = parseJsonParam(params.jobVariables, 'Job Variables') - if (parsed === undefined) return undefined - if (!Array.isArray(parsed) && typeof parsed === 'object') { - return Object.entries(parsed).map(([key, value]) => ({ - key, - value: String(value), - })) - } - return parsed - })(), + jobVariables: parseCiVariables(params.jobVariables, 'Job Variables'), } case 'gitlab_list_releases': - if (!params.projectId?.trim()) { + if (!projectId) { throw new Error('Project ID is required.') } return { ...baseParams, - projectId: params.projectId.trim(), - orderBy: params.releaseOrderBy || undefined, - sort: params.sortOrder || undefined, - perPage: params.perPage ? Number(params.perPage) : undefined, - page: params.page ? Number(params.page) : undefined, + projectId, + orderBy: params.releaseOrderBy || toolCallArg(context, params.orderBy) || undefined, + sort, + ...pagination, } - case 'gitlab_create_release': - if (!params.projectId?.trim() || !params.tagName?.trim()) { + case 'gitlab_create_release': { + const tagName = inputText(params.tagName) + if (!projectId || !tagName) { throw new Error('Project ID and tag name are required.') } return { ...baseParams, - projectId: params.projectId.trim(), - tagName: params.tagName.trim(), - name: params.releaseName?.trim() || undefined, - description: params.description?.trim() || undefined, - ref: params.ref?.trim() || undefined, - releasedAt: params.releasedAt?.trim() || undefined, - tagMessage: params.tagMessage?.trim() || undefined, + projectId, + tagName, + name: textOrToolArg(params.releaseName, params.name) || undefined, + description: optionalText(params.description), + ref: optionalText(params.ref), + releasedAt: optionalText(params.releasedAt), + tagMessage: optionalText(params.tagMessage), assetLinks: parseJsonParam(params.assetLinks, 'Asset Links'), - milestones: params.releaseMilestones - ? params.releaseMilestones - .split(',') - .map((title: string) => title.trim()) - .filter(Boolean) - : undefined, + milestones: + parseTitleList(params.releaseMilestones) ?? + parseTitleList(toolCallArg(context, params.milestones)), } + } case 'gitlab_list_members': - if (!params.resourceId?.trim()) { + if (!resourceId) { throw new Error('Project / Group ID is required.') } return { ...baseParams, resourceType: params.resourceType || 'project', - resourceId: params.resourceId.trim(), - directOnly: params.directMembersOnly || undefined, - query: params.query?.trim() || undefined, - userIds: params.memberUserIds?.trim() || undefined, - state: params.memberState || undefined, + resourceId, + directOnly: + params.directMembersOnly || toolCallArg(context, params.directOnly) || undefined, + query: optionalText(params.query), + userIds: textOrToolArg(params.memberUserIds, params.userIds) || undefined, + state: params.memberState || toolCallArg(context, params.state) || undefined, showSeatInfo: params.showSeatInfo || undefined, - perPage: params.perPage ? Number(params.perPage) : undefined, - page: params.page ? Number(params.page) : undefined, + ...pagination, } case 'gitlab_add_member': { const addMemberUserId = String(params.userId ?? '').trim() + const username = inputText(params.username) if ( - !params.resourceId?.trim() || - (!addMemberUserId && !params.username?.trim()) || + !resourceId || + (!addMemberUserId && !username) || !hasGitLabAccessLevel(params.accessLevel) ) { throw new Error( @@ -2738,85 +2906,89 @@ Return ONLY the JSON array - no explanations, no extra text.`, return { ...baseParams, resourceType: params.resourceType || 'project', - resourceId: params.resourceId.trim(), + resourceId, userId: addMemberUserId ? Number(addMemberUserId) : undefined, - username: params.username?.trim() || undefined, + username: username || undefined, accessLevel: coerceGitLabAccessLevel(params.accessLevel), - expiresAt: params.expiresAt?.trim() || undefined, + expiresAt: optionalText(params.expiresAt), memberRoleId: params.memberRoleId ? Number(params.memberRoleId) : undefined, } } - case 'gitlab_update_member': - if ( - !params.resourceId?.trim() || - !params.userId || - !hasGitLabAccessLevel(params.memberAccessLevel) - ) { + case 'gitlab_update_member': { + const level = hasGitLabAccessLevel(params.memberAccessLevel) + ? params.memberAccessLevel + : toolCallArg(context, params.accessLevel) + if (!resourceId || !params.userId || !hasGitLabAccessLevel(level)) { throw new Error('Project / Group ID, User ID, and Access Level are required.') } return { ...baseParams, resourceType: params.resourceType || 'project', - resourceId: params.resourceId.trim(), + resourceId, userId: Number(params.userId), - accessLevel: coerceGitLabAccessLevel(params.memberAccessLevel), - expiresAt: params.clearExpiresAt ? '' : params.expiresAt?.trim() || undefined, + accessLevel: coerceGitLabAccessLevel(level), + expiresAt: params.clearExpiresAt + ? '' + : (optionalText(params.expiresAt) ?? toolCallClear(params.expiresAt, context)), memberRoleId: params.memberRoleId ? Number(params.memberRoleId) : undefined, } + } case 'gitlab_remove_member': - if (!params.resourceId?.trim() || !params.userId) { + if (!resourceId || !params.userId) { throw new Error('Project / Group ID and User ID are required.') } return { ...baseParams, resourceType: params.resourceType || 'project', - resourceId: params.resourceId.trim(), + resourceId, userId: Number(params.userId), skipSubresources: params.skipSubresources || undefined, unassignIssuables: params.unassignIssuables || undefined, } - case 'gitlab_invite_member': - if ( - !params.resourceId?.trim() || - !params.email?.trim() || - !hasGitLabAccessLevel(params.accessLevel) - ) { + case 'gitlab_invite_member': { + const email = inputText(params.email) + if (!resourceId || !email || !hasGitLabAccessLevel(params.accessLevel)) { throw new Error('Project / Group ID, Email, and Access Level are required.') } return { ...baseParams, resourceType: params.resourceType || 'project', - resourceId: params.resourceId.trim(), - email: params.email.trim(), + resourceId, + email, accessLevel: coerceGitLabAccessLevel(params.accessLevel), - expiresAt: params.expiresAt?.trim() || undefined, + expiresAt: optionalText(params.expiresAt), memberRoleId: params.memberRoleId ? Number(params.memberRoleId) : undefined, - inviteSource: params.inviteSource?.trim() || undefined, + inviteSource: optionalText(params.inviteSource), } + } case 'gitlab_list_invitations': - if (!params.resourceId?.trim()) { + if (!resourceId) { throw new Error('Project / Group ID is required.') } return { ...baseParams, resourceType: params.resourceType || 'project', - resourceId: params.resourceId.trim(), - query: params.query?.trim() || undefined, - perPage: params.perPage ? Number(params.perPage) : undefined, - page: params.page ? Number(params.page) : undefined, + resourceId, + query: optionalText(params.query), + ...pagination, } - case 'gitlab_update_invitation': - if (!params.resourceId?.trim() || !params.email?.trim()) { + case 'gitlab_update_invitation': { + const email = inputText(params.email) + if (!resourceId || !email) { throw new Error('Project / Group ID and Email are required.') } + const level = hasGitLabAccessLevel(params.invitationAccessLevel) + ? params.invitationAccessLevel + : toolCallArg(context, params.accessLevel) if ( - !hasGitLabAccessLevel(params.invitationAccessLevel) && - !params.expiresAt?.trim() && + !hasGitLabAccessLevel(level) && + !inputText(params.expiresAt) && + toolCallClear(params.expiresAt, context) === undefined && !params.clearExpiresAt ) { throw new Error( @@ -2826,47 +2998,49 @@ Return ONLY the JSON array - no explanations, no extra text.`, return { ...baseParams, resourceType: params.resourceType || 'project', - resourceId: params.resourceId.trim(), - email: params.email.trim(), + resourceId, + email, // Only send access_level when a level is chosen; "Leave unchanged" // ('') keeps the invitation's current level instead of resetting it. - accessLevel: hasGitLabAccessLevel(params.invitationAccessLevel) - ? coerceGitLabAccessLevel(params.invitationAccessLevel) - : undefined, - expiresAt: params.clearExpiresAt ? '' : params.expiresAt?.trim() || undefined, + accessLevel: hasGitLabAccessLevel(level) ? coerceGitLabAccessLevel(level) : undefined, + expiresAt: params.clearExpiresAt + ? '' + : (optionalText(params.expiresAt) ?? toolCallClear(params.expiresAt, context)), } + } - case 'gitlab_revoke_invitation': - if (!params.resourceId?.trim() || !params.email?.trim()) { + case 'gitlab_revoke_invitation': { + const email = inputText(params.email) + if (!resourceId || !email) { throw new Error('Project / Group ID and Email are required.') } return { ...baseParams, resourceType: params.resourceType || 'project', - resourceId: params.resourceId.trim(), - email: params.email.trim(), + resourceId, + email, } + } case 'gitlab_list_access_requests': - if (!params.resourceId?.trim()) { + if (!resourceId) { throw new Error('Project / Group ID is required.') } return { ...baseParams, resourceType: params.resourceType || 'project', - resourceId: params.resourceId.trim(), - perPage: params.perPage ? Number(params.perPage) : undefined, - page: params.page ? Number(params.page) : undefined, + resourceId, + ...pagination, } case 'gitlab_approve_access_request': - if (!params.resourceId?.trim() || !params.userId) { + if (!resourceId || !params.userId) { throw new Error('Project / Group ID and User ID are required.') } return { ...baseParams, resourceType: params.resourceType || 'project', - resourceId: params.resourceId.trim(), + resourceId, userId: Number(params.userId), accessLevel: hasGitLabAccessLevel(params.accessLevel) ? coerceGitLabAccessLevel(params.accessLevel) @@ -2874,92 +3048,90 @@ Return ONLY the JSON array - no explanations, no extra text.`, } case 'gitlab_deny_access_request': - if (!params.resourceId?.trim() || !params.userId) { + if (!resourceId || !params.userId) { throw new Error('Project / Group ID and User ID are required.') } return { ...baseParams, resourceType: params.resourceType || 'project', - resourceId: params.resourceId.trim(), + resourceId, userId: Number(params.userId), } case 'gitlab_list_saml_group_links': - if (!params.groupId?.trim()) { + if (!groupId) { throw new Error('Group ID is required.') } return { ...baseParams, - groupId: params.groupId.trim(), + groupId, } - case 'gitlab_add_saml_group_link': - if ( - !params.groupId?.trim() || - !params.samlGroupName?.trim() || - !hasGitLabAccessLevel(params.accessLevel) - ) { + case 'gitlab_add_saml_group_link': { + const samlGroupName = inputText(params.samlGroupName) + if (!groupId || !samlGroupName || !hasGitLabAccessLevel(params.accessLevel)) { throw new Error('Group ID, SAML Group Name, and Access Level are required.') } return { ...baseParams, - groupId: params.groupId.trim(), - samlGroupName: params.samlGroupName.trim(), + groupId, + samlGroupName, accessLevel: coerceGitLabAccessLevel(params.accessLevel), memberRoleId: params.memberRoleId ? Number(params.memberRoleId) : undefined, - provider: params.samlProvider?.trim() || undefined, + provider: textOrToolArg(params.samlProvider, params.provider) || undefined, } + } - case 'gitlab_delete_saml_group_link': - if (!params.groupId?.trim() || !params.samlGroupName?.trim()) { + case 'gitlab_delete_saml_group_link': { + const samlGroupName = inputText(params.samlGroupName) + if (!groupId || !samlGroupName) { throw new Error('Group ID and SAML Group Name are required.') } return { ...baseParams, - groupId: params.groupId.trim(), - samlGroupName: params.samlGroupName.trim(), - provider: params.samlProvider?.trim() || undefined, + groupId, + samlGroupName, + provider: textOrToolArg(params.samlProvider, params.provider) || undefined, } + } - case 'gitlab_search_users': - if (!params.userSearch?.trim()) { + case 'gitlab_search_users': { + const search = textOrToolArg(params.userSearch, params.search) + if (!search) { throw new Error('Search query is required.') } return { ...baseParams, - search: params.userSearch.trim(), - perPage: params.perPage ? Number(params.perPage) : undefined, - page: params.page ? Number(params.page) : undefined, + search, + ...pagination, } + } - case 'gitlab_create_user': - if ( - !params.userAdminEmail?.trim() || - !params.userAdminUsername?.trim() || - !params.userAdminName?.trim() - ) { + case 'gitlab_create_user': { + const email = textOrToolArg(params.userAdminEmail, params.email) + const username = textOrToolArg(params.userAdminUsername, params.username) + const name = textOrToolArg(params.userAdminName, params.name) + const password = textOrToolArg(params.userAdminPassword, params.password) + if (!email || !username || !name) { throw new Error('Email, Username, and Full Name are required.') } - if ( - !params.userAdminPassword?.trim() && - !params.resetPassword && - !params.forceRandomPassword - ) { + if (!password && !params.resetPassword && !params.forceRandomPassword) { throw new Error( 'One of Password, Send Password Reset Link, or Force Random Password is required.' ) } return { ...baseParams, - email: params.userAdminEmail.trim(), - username: params.userAdminUsername.trim(), - name: params.userAdminName.trim(), - password: params.userAdminPassword?.trim() || undefined, + email, + username, + name, + password: password || undefined, resetPassword: params.resetPassword || undefined, forceRandomPassword: params.forceRandomPassword || undefined, - admin: params.userAdminIsAdmin || undefined, + admin: params.userAdminIsAdmin || toolCallArg(context, params.admin) || undefined, skipConfirmation: params.skipConfirmation || undefined, } + } case 'gitlab_update_user': if (!params.userId) { @@ -2968,14 +3140,19 @@ Return ONLY the JSON array - no explanations, no extra text.`, return { ...baseParams, userId: Number(params.userId), - email: params.userAdminEmail?.trim() || undefined, - username: params.userAdminUsername?.trim() || undefined, - name: params.userAdminName?.trim() || undefined, + email: textOrToolArg(params.userAdminEmail, params.email) || undefined, + username: textOrToolArg(params.userAdminUsername, params.username) || undefined, + name: textOrToolArg(params.userAdminName, params.name) || undefined, // Only pass a real boolean: an explicit `false` demotes the user, // while an untouched switch serializes as `null` and must be // dropped so an unrelated update never touches the admin flag. admin: - typeof params.userAdminIsAdmin === 'boolean' ? params.userAdminIsAdmin : undefined, + typeof params.userAdminIsAdmin === 'boolean' + ? params.userAdminIsAdmin + : toolCallArg( + context, + typeof params.admin === 'boolean' ? params.admin : undefined + ), } case 'gitlab_delete_user': @@ -3004,15 +3181,17 @@ Return ONLY the JSON array - no explanations, no extra text.`, userId: Number(params.userId), } - case 'gitlab_delete_user_identity': - if (!params.userId || !params.provider?.trim()) { + case 'gitlab_delete_user_identity': { + const provider = inputText(params.provider) + if (!params.userId || !provider) { throw new Error('User ID and Identity Provider are required.') } return { ...baseParams, userId: Number(params.userId), - provider: params.provider.trim(), + provider, } + } default: return baseParams @@ -3029,6 +3208,18 @@ Return ONLY the JSON array - no explanations, no extra text.`, mergeRequestIid: { type: 'number', description: 'Merge request internal ID' }, pipelineId: { type: 'number', description: 'Pipeline ID' }, title: { type: 'string', description: 'Title for issue or merge request' }, + updateTitle: { + type: 'string', + description: 'New title when updating an issue or merge request', + }, + dueDate: { type: 'string', description: 'Issue due date (YYYY-MM-DD)' }, + confidential: { type: 'boolean', description: 'Create the issue as confidential' }, + draft: { type: 'boolean', description: 'Create the merge request as a draft' }, + mergeWhenPipelineSucceeds: { + type: 'boolean', + description: 'Auto-merge the merge request once its checks pass', + }, + squashCommitMessage: { type: 'string', description: 'Custom squash commit message' }, description: { type: 'string', description: 'Description (Markdown supported)' }, body: { type: 'string', description: 'Comment body' }, sourceBranch: { type: 'string', description: 'Source branch for merge request' }, @@ -3115,6 +3306,7 @@ Return ONLY the JSON array - no explanations, no extra text.`, scope: { type: 'string', description: 'Job scope filter' }, includeRetried: { type: 'boolean', description: 'Include retried jobs in the listing' }, sha: { type: 'string', description: 'Commit SHA' }, + mergeSha: { type: 'string', description: 'Source branch HEAD SHA required to merge' }, compareFrom: { type: 'string', description: 'Branch, tag, or commit SHA to compare from' }, compareTo: { type: 'string', description: 'Branch, tag, or commit SHA to compare to' }, straight: { type: 'boolean', description: 'Compare directly instead of using the merge base' }, 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/gong.test.ts b/apps/sim/blocks/blocks/gong.test.ts new file mode 100644 index 00000000000..5d13dd8b9f7 --- /dev/null +++ b/apps/sim/blocks/blocks/gong.test.ts @@ -0,0 +1,20 @@ +/** + * Agent tool calls pass the operation in context and supply arguments under the tool's param + * names, which the mapper spreads over and must keep. + */ +import { describe, expect, it } from 'vitest' +import { GongBlock } from '@/blocks/blocks/gong' + +function agentParams(operation: string, args: Record): Record { + return { ...args, ...(GongBlock.tools.config?.params?.(args, { operation }) ?? {}) } +} + +describe('GongBlock agent tool calls', () => { + it('keeps the model flowId when unassigning flow prospects', () => { + const params = agentParams('unassign_flow_prospects', { + crmProspectId: 'lead-1', + flowId: 'flow-9', + }) + expect(params.flowId).toBe('flow-9') + }) +}) diff --git a/apps/sim/blocks/blocks/gong.ts b/apps/sim/blocks/blocks/gong.ts index 7599830cc87..938bf3b09f5 100644 --- a/apps/sim/blocks/blocks/gong.ts +++ b/apps/sim/blocks/blocks/gong.ts @@ -1,6 +1,6 @@ import { GongIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' import { getTrigger } from '@/triggers' export const GongBlock: BlockConfig = { @@ -1088,11 +1088,11 @@ Return ONLY the timestamp string in ISO 8601 format - no explanations, no quotes ], config: { tool: (params) => `gong_${params.operation}`, - params: (params) => { + params: (params, context) => { const result: Record = {} // Map operation-specific subBlock IDs to tool param names, gated by the // selected operation so stale values from other operations never leak in - const operation = params.operation as string + const operation = mapperOperation(params, context) if (operation === 'get_call_transcript' || operation === 'get_extensive_calls') { if (params.transcriptFromDateTime) result.fromDateTime = params.transcriptFromDateTime if (params.transcriptToDateTime) result.toDateTime = params.transcriptToDateTime @@ -1123,7 +1123,7 @@ Return ONLY the timestamp string in ISO 8601 format - no explanations, no quotes if (params.logsToDateTime) result.toDateTime = params.logsToDateTime } if (operation === 'unassign_flow_prospects') { - result.flowId = params.unassignFlowId || undefined + result.flowId = params.unassignFlowId || toolCallArg(context, params.flowId) || undefined } return result }, diff --git a/apps/sim/blocks/blocks/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_bigquery.ts b/apps/sim/blocks/blocks/google_bigquery.ts index 5c9844d06b2..bc8354f531a 100644 --- a/apps/sim/blocks/blocks/google_bigquery.ts +++ b/apps/sim/blocks/blocks/google_bigquery.ts @@ -2,6 +2,7 @@ import { GoogleBigQueryIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation } from '@/blocks/utils' const EXISTING_DATASET_OPS = [ 'list_tables', @@ -420,7 +421,7 @@ Return ONLY the JSON array - no explanations, no wrapping, no extra text.`, throw new Error(`Invalid Google BigQuery operation: ${params.operation}`) } }, - params: (params) => { + params: (params, context) => { const { oauthCredential, rows, @@ -435,7 +436,7 @@ Return ONLY the JSON array - no explanations, no wrapping, no extra text.`, tableId, ...rest } = params - const operation = String(params.operation) + const operation = mapperOperation(params, context) return { ...rest, oauthCredential, diff --git a/apps/sim/blocks/blocks/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..db62f9cfbad --- /dev/null +++ b/apps/sim/blocks/blocks/google_forms.test.ts @@ -0,0 +1,34 @@ +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 }) + }) + + it.each([ + { operation: 'create_form', inputs: { documentTitle: 'd' }, missing: 'title' }, + { operation: 'create_watch', inputs: { formId: 'f', topicName: 't' }, missing: 'eventType' }, + { + operation: 'create_watch', + inputs: { formId: 'f', eventType: 'RESPONSES' }, + missing: 'topicName', + }, + { operation: 'delete_watch', inputs: { formId: 'f' }, missing: 'watchId' }, + { operation: 'renew_watch', inputs: { formId: 'f' }, missing: 'watchId' }, + ])( + 'leaves a $missing the model omitted on $operation for the required-param check', + ({ operation, inputs, missing }) => { + const mapped = GoogleFormsBlock.tools.config?.params?.( + { oauthCredential: 'cred-1', ...inputs }, + { operation } + ) + expect(mapped?.[missing]).toBeUndefined() + } + ) +}) diff --git a/apps/sim/blocks/blocks/google_forms.ts b/apps/sim/blocks/blocks/google_forms.ts index 4ee9fe1a337..8761fed0e0f 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 @@ -355,7 +355,7 @@ Example for "Add a required multiple choice question about favorite color": case 'create_form': return { ...baseParams, - title: String(title).trim(), + title: title == null ? undefined : String(title).trim(), documentTitle: documentTitle ? String(documentTitle).trim() : undefined, unpublished: unpublished ?? false, } @@ -377,8 +377,8 @@ Example for "Add a required multiple choice question about favorite color": return { ...baseParams, formId: effectiveFormId, - eventType: String(eventType), - topicName: String(topicName).trim(), + eventType: eventType == null ? undefined : String(eventType), + topicName: topicName == null ? undefined : String(topicName).trim(), watchId: watchId ? String(watchId).trim() : undefined, } case 'delete_watch': @@ -386,7 +386,7 @@ Example for "Add a required multiple choice question about favorite color": return { ...baseParams, formId: effectiveFormId, - watchId: String(watchId).trim(), + watchId: watchId == null ? undefined : String(watchId).trim(), } default: throw new Error(`Invalid Google Forms operation: ${operation}`) 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/grafana.test.ts b/apps/sim/blocks/blocks/grafana.test.ts new file mode 100644 index 00000000000..eac82d598dd --- /dev/null +++ b/apps/sim/blocks/blocks/grafana.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from 'vitest' +import { GrafanaBlock } from '@/blocks/blocks/grafana' +import type { BlockToolParamsContext } from '@/blocks/types' + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = GrafanaBlock.tools.config?.params + if (!mapper) throw new Error('Grafana block has no params mapper') + return mapper(params, context) +} + +describe('Grafana tool calls', () => { + it('keeps the model folder UID and parent UID when moving a folder', () => { + const mapped = mapParams( + { folderUid: 'child', parentUid: 'parent' }, + { operation: 'grafana_move_folder' } + ) + + expect(mapped).toMatchObject({ folderUid: 'child', parentUid: 'parent' }) + }) + + it('keeps the model folder UID and rule group when reading an alert rule group', () => { + const mapped = mapParams( + { folderUid: 'folder-1', ruleGroup: 'cpu' }, + { operation: 'grafana_get_alert_rule_group' } + ) + + expect(mapped).toMatchObject({ folderUid: 'folder-1', ruleGroup: 'cpu' }) + }) +}) diff --git a/apps/sim/blocks/blocks/grafana.ts b/apps/sim/blocks/blocks/grafana.ts index e5811970090..cfb95065be8 100644 --- a/apps/sim/blocks/blocks/grafana.ts +++ b/apps/sim/blocks/blocks/grafana.ts @@ -1,7 +1,7 @@ import { GrafanaIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' export const GrafanaBlock: BlockConfig = { type: 'grafana', @@ -1110,9 +1110,9 @@ Return ONLY the JSON object - no explanations, no markdown, no extra text.`, ], config: { tool: (params) => params.operation, - params: (params) => { + params: (params, context) => { const result: Record = {} - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'grafana_list_dashboards': if (params.page) result.page = Number(params.page) if (params.limit) result.limit = Number(params.limit) @@ -1144,17 +1144,17 @@ Return ONLY the JSON object - no explanations, no markdown, no extra text.`, if (params.contactPointSettings) result.settings = params.contactPointSettings break case 'grafana_query_data_source': - result.queries = params.dataSourceQueries + result.queries = params.dataSourceQueries ?? toolCallArg(context, params.queries) if (params.queryFrom) result.from = params.queryFrom if (params.queryTo) result.to = params.queryTo break case 'grafana_move_folder': - result.folderUid = params.manageFolderUid - result.parentUid = params.newParentUid ?? '' + result.folderUid = params.manageFolderUid ?? toolCallArg(context, params.folderUid) + result.parentUid = params.newParentUid ?? toolCallArg(context, params.parentUid) ?? '' break case 'grafana_get_alert_rule_group': - result.folderUid = params.manageFolderUid - result.ruleGroup = params.ruleGroupName + result.folderUid = params.manageFolderUid ?? toolCallArg(context, params.folderUid) + result.ruleGroup = params.ruleGroupName ?? toolCallArg(context, params.ruleGroup) break case 'grafana_create_annotation': if (params.annotationTags) result.tags = params.annotationTags diff --git a/apps/sim/blocks/blocks/grain.test.ts b/apps/sim/blocks/blocks/grain.test.ts new file mode 100644 index 00000000000..8d93892d126 --- /dev/null +++ b/apps/sim/blocks/blocks/grain.test.ts @@ -0,0 +1,29 @@ +/** + * Agent tool calls pass the operation in context and supply arguments under the tool's param + * names, which the mapper spreads over and must keep. + */ +import { describe, expect, it } from 'vitest' +import { GrainV2Block } from '@/blocks/blocks/grain' + +function agentParams(operation: string, args: Record): Record { + return { ...args, ...(GrainV2Block.tools.config?.params?.(args, { operation }) ?? {}) } +} + +describe('GrainV2Block agent tool calls', () => { + it('keeps the model include options when creating a webhook', () => { + const params = agentParams('grain_create_hook_v2', { + hookUrl: 'https://example.com/hook', + hookType: 'recording_added', + include: { participants: true }, + }) + expect(params.include).toEqual({ participants: true }) + }) + + it('keeps the model event type and state filters when listing webhooks', () => { + const params = agentParams('grain_list_hooks_v2', { + hookType: 'highlight_added', + state: 'enabled', + }) + expect(params).toMatchObject({ hookType: 'highlight_added', state: 'enabled' }) + }) +}) diff --git a/apps/sim/blocks/blocks/grain.ts b/apps/sim/blocks/blocks/grain.ts index 4c5181114b4..fbcd860c004 100644 --- a/apps/sim/blocks/blocks/grain.ts +++ b/apps/sim/blocks/blocks/grain.ts @@ -2,7 +2,7 @@ import { omit } from '@sim/utils/object' import { GrainIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' import { getTrigger } from '@/triggers' import { GRAIN_HOOK_TYPE_OPTIONS, grainTriggerOptions } from '@/triggers/grain/utils' @@ -368,12 +368,12 @@ Return ONLY the search term - no explanations, no quotes, no extra text.`, tool: (params) => { return params.operation || 'grain_list_recordings' }, - params: (params) => { + params: (params, context) => { const baseParams: Record = { apiKey: params.apiKey, } - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'grain_list_recordings': return { ...baseParams, @@ -705,12 +705,12 @@ export const GrainV2Block: BlockConfig = { tool: (params) => { return params.operation || 'grain_list_recordings' }, - params: (params) => { + params: (params, context) => { const baseParams: Record = { apiKey: params.apiKey, } - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'grain_create_hook_v2': { if (!params.hookUrl?.trim()) { throw new Error('Webhook URL is required.') @@ -719,12 +719,10 @@ export const GrainV2Block: BlockConfig = { throw new Error('Event type is required.') } let include: unknown - if (params.hookInclude) { + const rawInclude = params.hookInclude || toolCallArg(context, params.include) + if (rawInclude) { try { - include = - typeof params.hookInclude === 'string' - ? JSON.parse(params.hookInclude) - : params.hookInclude + include = typeof rawInclude === 'string' ? JSON.parse(rawInclude) : rawInclude } catch { throw new Error('Invalid JSON for include options') } @@ -740,8 +738,8 @@ export const GrainV2Block: BlockConfig = { case 'grain_list_hooks_v2': return { ...baseParams, - hookType: params.hookTypeFilter || undefined, - state: params.hookState || undefined, + hookType: params.hookTypeFilter || toolCallArg(context, params.hookType) || undefined, + state: params.hookState || toolCallArg(context, params.state) || undefined, } case 'grain_delete_hook_v2': @@ -754,7 +752,7 @@ export const GrainV2Block: BlockConfig = { } default: - return GrainBlock.tools!.config!.params!(params) + return GrainBlock.tools!.config!.params!(params, context) } }, }, diff --git a/apps/sim/blocks/blocks/greenhouse.ts b/apps/sim/blocks/blocks/greenhouse.ts index cf4ba4c1fd3..acae12ce0c0 100644 --- a/apps/sim/blocks/blocks/greenhouse.ts +++ b/apps/sim/blocks/blocks/greenhouse.ts @@ -1,6 +1,7 @@ import { GreenhouseIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' +import { mapperOperation } from '@/blocks/utils' import { getTrigger } from '@/triggers' export const GreenhouseBlock: BlockConfig = { @@ -362,16 +363,17 @@ Return ONLY the ISO 8601 timestamp - no explanations, no extra text.`, ], config: { tool: (params) => `${params.operation}`, - params: (params) => { + params: (params, context) => { const result: Record = {} + const operation = mapperOperation(params, context) if (params.per_page) result.per_page = Number(params.per_page) if (params.page) result.page = Number(params.page) - if (params.operation === 'greenhouse_list_applications' && params.applicationStatus) { + if (operation === 'greenhouse_list_applications' && params.applicationStatus) { result.status = params.applicationStatus } - if (params.operation === 'greenhouse_list_jobs' && params.status === '') { + if (operation === 'greenhouse_list_jobs' && params.status === '') { result.status = undefined } diff --git a/apps/sim/blocks/blocks/harmonic.test.ts b/apps/sim/blocks/blocks/harmonic.test.ts index 78f3f0a8b4f..37b08bd04eb 100644 --- a/apps/sim/blocks/blocks/harmonic.test.ts +++ b/apps/sim/blocks/blocks/harmonic.test.ts @@ -55,6 +55,12 @@ describe('HarmonicBlock', () => { expect(direct.personUrns).toEqual(['urn:harmonic:person:44']) }) + it('keeps model arguments on agent tool calls, where the operation arrives in context', () => { + const args = { oauthCredential: 'credential-id', personId: '22', companyContextUrns: ['urn:c'] } + const params = { ...args, ...buildParams(args, { operation: 'harmonic_get_person' }) } + expect(params).toMatchObject({ personId: '22', companyContextUrns: ['urn:c'] }) + }) + it('does not parse malformed batch JSON before the secret-safe tool boundary', () => { expect( resolve({ diff --git a/apps/sim/blocks/blocks/harmonic.ts b/apps/sim/blocks/blocks/harmonic.ts index f20b4ceee54..e46e94dbf98 100644 --- a/apps/sim/blocks/blocks/harmonic.ts +++ b/apps/sim/blocks/blocks/harmonic.ts @@ -1,6 +1,7 @@ import { HarmonicIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation } from '@/blocks/utils' const HARMONIC_OPERATIONS = [ 'harmonic_search_people_scout', @@ -497,8 +498,8 @@ export const HarmonicBlock: BlockConfig = { * operation-specific key is therefore assigned explicitly; `undefined` * is what removes a stale value after the operation changes. */ - params: (params) => { - const operation = String(params.operation ?? '') + params: (params, context) => { + const operation = mapperOperation(params, context) const isPaged = (PAGED_OPERATIONS as readonly string[]).includes(operation) const usesSavedSearch = (SAVED_SEARCH_OPERATIONS as readonly string[]).includes(operation) const usesPersonUrns = (PERSON_URN_OPERATIONS as readonly string[]).includes(operation) diff --git a/apps/sim/blocks/blocks/helpscout.test.ts b/apps/sim/blocks/blocks/helpscout.test.ts new file mode 100644 index 00000000000..06f06eda6a6 --- /dev/null +++ b/apps/sim/blocks/blocks/helpscout.test.ts @@ -0,0 +1,35 @@ +/** + * Agent tool calls pass the operation in context and supply arguments under the tool's param + * names (`status`, `type`, `sortField`), which the mapper spreads over and must keep. + */ +import { describe, expect, it } from 'vitest' +import { HelpScoutBlock } from '@/blocks/blocks/helpscout' + +function agentParams(operation: string, args: Record): Record { + return { ...args, ...(HelpScoutBlock.tools.config?.params?.(args, { operation }) ?? {}) } +} + +describe('HelpScoutBlock agent tool calls', () => { + it('keeps the model status when updating a conversation status', () => { + const params = agentParams('update_conversation_status', { + conversationId: '123', + status: 'closed', + }) + expect(params.status).toBe('closed') + }) + + it('keeps the model type and status when creating a conversation', () => { + const params = agentParams('create_conversation', { + mailboxId: '1', + subject: 'Hi', + type: 'chat', + status: 'pending', + }) + expect(params).toMatchObject({ type: 'chat', status: 'pending' }) + }) + + it('keeps the model sort field when listing customers', () => { + const params = agentParams('list_customers', { sortField: 'lastName' }) + expect(params.sortField).toBe('lastName') + }) +}) diff --git a/apps/sim/blocks/blocks/helpscout.ts b/apps/sim/blocks/blocks/helpscout.ts index 167c47364d3..7d5bb29f707 100644 --- a/apps/sim/blocks/blocks/helpscout.ts +++ b/apps/sim/blocks/blocks/helpscout.ts @@ -2,6 +2,7 @@ import { HelpScoutIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' import { getTrigger } from '@/triggers' const CONVERSATION_OPERATIONS = [ @@ -71,8 +72,8 @@ const TIMESTAMP_WAND = { } as const /** The status dropdown the active operation shows, collapsed onto the tools' shared `status` param. */ -function resolveStatus(params: Record): unknown { - switch (params.operation) { +function resolveStatus(params: Record, operation: string): unknown { + switch (operation) { case 'list_conversations': return params.listStatus case 'update_conversation_status': @@ -934,21 +935,29 @@ export const HelpScoutBlock: BlockConfig = { ], config: { tool: (params) => `helpscout_${params.operation || 'list_conversations'}`, - params: (params) => ({ - status: optionalString(resolveStatus(params)), - type: optionalString(params.conversationType), - sortField: optionalString( - params.operation === 'list_customers' - ? params.customerSortField - : params.conversationSortField - ), - sortOrder: optionalString(params.sortOrder), - gender: optionalString(params.gender), - workflowType: optionalString(params.workflowType), - organizationSort: optionalString(params.organizationSort), - page: optionalNumber(params.page), - number: optionalNumber(params.number), - }), + params: (params, context) => { + const operation = mapperOperation(params, context) + return { + status: + optionalString(resolveStatus(params, operation)) ?? + optionalString(toolCallArg(context, params.status)), + type: + optionalString(params.conversationType) ?? + optionalString(toolCallArg(context, params.type)), + sortField: + optionalString( + operation === 'list_customers' + ? params.customerSortField + : params.conversationSortField + ) ?? optionalString(toolCallArg(context, params.sortField)), + sortOrder: optionalString(params.sortOrder), + gender: optionalString(params.gender), + workflowType: optionalString(params.workflowType), + organizationSort: optionalString(params.organizationSort), + page: optionalNumber(params.page), + number: optionalNumber(params.number), + } + }, }, }, inputs: { diff --git a/apps/sim/blocks/blocks/hex.test.ts b/apps/sim/blocks/blocks/hex.test.ts index 5e632ff4f64..8e71341a5e2 100644 --- a/apps/sim/blocks/blocks/hex.test.ts +++ b/apps/sim/blocks/blocks/hex.test.ts @@ -6,6 +6,7 @@ import { describe, expect, it } from 'vitest' import { HexBlock } from '@/blocks/blocks/hex' import type { BlockToolParamsContext } from '@/blocks/types' +import { getGroupTool } from '@/tools/hex/get_group' import { getProjectRunsTool } from '@/tools/hex/get_project_runs' import { getQueriedTablesTool } from '@/tools/hex/get_queried_tables' import { listGroupsTool } from '@/tools/hex/list_groups' @@ -77,13 +78,13 @@ describe('Hex block keeps stale subBlock values out of tool requests', () => { }) it('get project runs keeps a run status an agent passes directly', () => { - const args = { operation: 'get_project_runs', projectId: PROJECT_ID, statusFilter: 'errored' } + const args = { projectId: PROJECT_ID, statusFilter: 'errored' } const built = requestUrl(getProjectRunsTool, args, { operation: 'get_project_runs' }) expect(built.searchParams.get('statusFilter')).toBe('errored') }) it('list groups keeps a user id an agent passes directly', () => { - const args = { operation: 'list_groups', userId: PROJECT_ID } + const args = { userId: PROJECT_ID } const built = requestUrl(listGroupsTool, args, { operation: 'list_groups' }) expect(built.searchParams.get('userId')).toBe(PROJECT_ID) }) @@ -94,8 +95,13 @@ describe('Hex block keeps stale subBlock values out of tool requests', () => { }) it('get queried tables keeps a cursor an agent passes directly', () => { - const args = { operation: 'get_queried_tables', projectId: PROJECT_ID, after: 'tables-cursor' } + const args = { projectId: PROJECT_ID, after: 'tables-cursor' } const built = requestUrl(getQueriedTablesTool, args, { operation: 'get_queried_tables' }) expect(built.searchParams.get('after')).toBe('tables-cursor') }) + + it('get group sends the Group ID stored on an agent tool row', () => { + const built = requestUrl(getGroupTool, { groupIdInput: PROJECT_ID }, { operation: 'get_group' }) + expect(built.pathname).toBe(`/api/v1/groups/${PROJECT_ID}`) + }) }) diff --git a/apps/sim/blocks/blocks/hex.ts b/apps/sim/blocks/blocks/hex.ts index 9d23f46547d..7c6950cf67a 100644 --- a/apps/sim/blocks/blocks/hex.ts +++ b/apps/sim/blocks/blocks/hex.ts @@ -1,7 +1,7 @@ import { HexIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { isToolCall, toolCallArg, withSavedCredential } from '@/blocks/utils' +import { isToolCall, mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' /** * Sort fields each list endpoint accepts. The only Sort By field is the List Projects one, so a @@ -711,7 +711,7 @@ Do not include any explanations, markdown formatting, or other text outside the }, params: (params, context) => { const result: Record = {} - const op = params.operation + const op = mapperOperation(params, context) const fieldOrToolArg = (field: unknown, arg: unknown) => emptyToUndefined(field) ?? emptyToUndefined(toolCallArg(context, arg)) diff --git a/apps/sim/blocks/blocks/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.test.ts b/apps/sim/blocks/blocks/hubspot.test.ts new file mode 100644 index 00000000000..bbf335e25f2 --- /dev/null +++ b/apps/sim/blocks/blocks/hubspot.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest' +import { HubSpotBlock } from '@/blocks/blocks/hubspot' + +function mapParams(params: Record, operation: string) { + const mapper = HubSpotBlock.tools.config?.params + if (!mapper) throw new Error('HubSpot block has no params mapper') + return mapper(params, { operation }) +} + +describe('HubSpot create_list name on a tool call', () => { + const list = { oauthCredential: 'cred-1', objectTypeId: '0-1', processingType: 'MANUAL' } + + it('keeps the List Name pinned on the tool row over the model name', () => { + expect( + mapParams({ ...list, listName: 'My List', name: 'Model Name' }, 'create_list').name + ).toBe('My List') + }) + + it('uses the model name when the row leaves List Name empty', () => { + expect(mapParams({ ...list, name: 'Model Name' }, 'create_list').name).toBe('Model Name') + }) +}) diff --git a/apps/sim/blocks/blocks/hubspot.ts b/apps/sim/blocks/blocks/hubspot.ts index 4909c3b0516..b689e2b430b 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, @@ -1727,10 +1726,6 @@ Return ONLY the JSON array of property names - no explanations, no markdown, no cleanParams.associations = associations } - if (listName && operation === 'create_list') { - cleanParams.name = listName - } - if ( operation === 'create_association' && associationTypeId !== undefined && @@ -1769,6 +1764,11 @@ Return ONLY the JSON array of property names - no explanations, no markdown, no } }) + // After the copy so the row's List Name beats a model `name` on a tool call. + if (listName && operation === 'create_list') { + cleanParams.name = listName + } + return cleanParams }, }, diff --git a/apps/sim/blocks/blocks/iam.test.ts b/apps/sim/blocks/blocks/iam.test.ts index 6fbaaa58c5f..1f2a6a6b0f7 100644 --- a/apps/sim/blocks/blocks/iam.test.ts +++ b/apps/sim/blocks/blocks/iam.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest' import { IAMBlock } from '@/blocks/blocks/iam' +import type { BlockToolParamsContext } from '@/blocks/types' const SHAPE_ERROR = 'Condition Context Keys must be a JSON array of { contextKeyName, contextKeyValues, contextKeyType }' @@ -48,3 +49,32 @@ describe('IAMBlock contextEntries parsing', () => { expect(result.contextEntries).toBeUndefined() }) }) + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = IAMBlock.tools.config?.params + if (!mapper) throw new Error('IAM block has no params mapper') + return mapper(params, context) +} + +describe('IAMBlock tool calls', () => { + it('parses stored context entries when the operation arrives only in the context', () => { + const result = mapParams( + { + region: 'us-east-1', + policySourceArn: 'arn:aws:iam::000000000000:role/example', + actionNames: 's3:GetObject', + contextEntries: JSON.stringify([CONTEXT_ENTRY]), + }, + { operation: 'simulate_principal_policy' } + ) + expect(result.contextEntries).toEqual([CONTEXT_ENTRY]) + }) + + it('keeps the model access key status on update_access_key', () => { + const result = mapParams( + { region: 'us-east-1', accessKeyIdToUpdate: 'AKIAEXAMPLE', status: 'Active' }, + { operation: 'update_access_key' } + ) + expect(result.status).toBe('Active') + }) +}) diff --git a/apps/sim/blocks/blocks/iam.ts b/apps/sim/blocks/blocks/iam.ts index ce502858d6a..ea5e898b984 100644 --- a/apps/sim/blocks/blocks/iam.ts +++ b/apps/sim/blocks/blocks/iam.ts @@ -2,7 +2,7 @@ import { isRecordLike } from '@sim/utils/object' import { IAMIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' /** * Converts the Tags table, a `[{ key, value }]` list (or its JSON string), a plain @@ -632,9 +632,8 @@ export const IAMBlock: BlockConfig = { throw new Error(`Invalid IAM operation: ${params.operation}`) } }, - params: (params) => { + params: (params, context) => { const { - operation, maxItems, maxSessionDuration, onlyAttached, @@ -651,7 +650,7 @@ export const IAMBlock: BlockConfig = { const result: Record = { ...connectionConfig } - switch (operation) { + switch (mapperOperation(params, context)) { case 'list_users': case 'list_roles': case 'list_groups': @@ -737,7 +736,7 @@ export const IAMBlock: BlockConfig = { break case 'update_access_key': result.accessKeyIdToUpdate = rest.accessKeyIdToUpdate - result.status = rest.accessKeyStatus + result.status = rest.accessKeyStatus ?? toolCallArg(context, rest.status) if (rest.userName) result.userName = rest.userName break case 'add_user_to_group': diff --git a/apps/sim/blocks/blocks/identity_center.test.ts b/apps/sim/blocks/blocks/identity_center.test.ts new file mode 100644 index 00000000000..d38760d42be --- /dev/null +++ b/apps/sim/blocks/blocks/identity_center.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest' +import { IdentityCenterBlock } from '@/blocks/blocks/identity_center' +import type { BlockToolParamsContext } from '@/blocks/types' + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = IdentityCenterBlock.tools.config?.params + if (!mapper) throw new Error('Identity Center block has no params mapper') + return mapper(params, context) +} + +describe('Identity Center list_account_assignments tool calls', () => { + it('keeps the model accountId when no account filter is stored', () => { + const mapped = mapParams( + { instanceArn: 'arn:i', principalId: 'u1', principalType: 'USER', accountId: '222' }, + { operation: 'list_account_assignments' } + ) + + expect(mapped.accountId).toBe('222') + }) +}) diff --git a/apps/sim/blocks/blocks/identity_center.ts b/apps/sim/blocks/blocks/identity_center.ts index a9b885903ac..a46a9c2ff58 100644 --- a/apps/sim/blocks/blocks/identity_center.ts +++ b/apps/sim/blocks/blocks/identity_center.ts @@ -1,7 +1,7 @@ import { IdentityCenterIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' export const IdentityCenterBlock: BlockConfig = { type: 'identity_center', @@ -418,8 +418,8 @@ export const IdentityCenterBlock: BlockConfig = { throw new Error(`Invalid Identity Center operation: ${params.operation}`) } }, - params: (params) => { - const { operation, maxResults, ...rest } = params + params: (params, context) => { + const { maxResults, ...rest } = params const connectionConfig = { region: rest.region, @@ -429,7 +429,7 @@ export const IdentityCenterBlock: BlockConfig = { const result: Record = { ...connectionConfig } - switch (operation) { + switch (mapperOperation(params, context)) { case 'list_instances': if (maxResults) { const parsed = Number.parseInt(String(maxResults), 10) @@ -505,7 +505,8 @@ export const IdentityCenterBlock: BlockConfig = { result.instanceArn = rest.instanceArn result.principalId = rest.principalId result.principalType = rest.principalType - result.accountId = rest.filterAccountId || undefined + result.accountId = + rest.filterAccountId || toolCallArg(context, rest.accountId) || undefined if (maxResults) { const parsed = Number.parseInt(String(maxResults), 10) if (!Number.isNaN(parsed)) result.maxResults = parsed diff --git a/apps/sim/blocks/blocks/incidentio.test.ts b/apps/sim/blocks/blocks/incidentio.test.ts new file mode 100644 index 00000000000..df618b729da --- /dev/null +++ b/apps/sim/blocks/blocks/incidentio.test.ts @@ -0,0 +1,108 @@ +import { describe, expect, it } from 'vitest' +import { IncidentioBlock } from '@/blocks/blocks/incidentio' + +/** + * On a tool call (Agent tool row, Pi, Human-in-the-loop v2) the mapper receives the stored row's + * params merged with the model's args, without `operation`; the operation arrives only in + * `context`. The executor spreads the mapper output over those merged params. + */ +function runToolCall(operation: string, merged: Record) { + const mapper = IncidentioBlock.tools.config?.params + if (!mapper) throw new Error('incidentio block has no params mapper') + return { ...merged, ...mapper(merged, { operation }) } +} + +describe('incidentio mapper on tool calls', () => { + it('applies block-only fields stored on the tool row', () => { + expect(runToolCall('incidentio_users_list', { apiKey: 'k', user_email: 'a@b.com' }).email).toBe( + 'a@b.com' + ) + const alert = runToolCall('incidentio_alert_events_create', { + alert_title: 'Checkout latency', + alert_status: 'firing', + }) + expect(alert.title).toBe('Checkout latency') + expect(alert.status).toBe('firing') + }) + + it("keeps the model's status over the seeded status dropdown", () => { + const resolved = runToolCall('incidentio_actions_update', { + id: 'act_1', + description: 'Fail over', + item_status: 'outstanding', + status: 'completed', + }) + expect(resolved.status).toBe('completed') + }) + + it('uses the status dropdown on the canvas', () => { + const mapper = IncidentioBlock.tools.config?.params + if (!mapper) throw new Error('incidentio block has no params mapper') + const canvas = mapper({ + operation: 'incidentio_follow_ups_update', + item_status: 'not_doing', + follow_up_title: 'Add alerting', + }) + expect(canvas.status).toBe('not_doing') + expect(canvas.title).toBe('Add alerting') + }) + + it("doesn't filter a tool-call alert list by the tool row's seeded status", () => { + const listed = runToolCall('incidentio_alerts_list', { apiKey: 'k', alert_status: 'firing' }) + expect(listed.status).toBeUndefined() + const mapper = IncidentioBlock.tools.config?.params + if (!mapper) throw new Error('incidentio block has no params mapper') + expect(mapper({ alert_status: 'firing' }, { operation: 'incidentio_alerts_list' }).status).toBe( + undefined + ) + expect( + runToolCall('incidentio_alerts_list', { alert_status: 'firing', status: 'resolved' }).status + ).toBe('resolved') + }) + + it("leaves a workflow created without a state to the tool's draft default", () => { + expect(runToolCall('incidentio_workflows_create', { name: 'Notify' }).state).toBeUndefined() + expect( + runToolCall('incidentio_workflows_create', { name: 'Notify', state: 'active' }).state + ).toBe('active') + }) +}) + +describe('incidentio mapper on a block newly added in the editor', () => { + /** The editor seeds dropdowns with `value({})`, so create operations start on the '' option. */ + const runCanvas = (params: Record) => { + const mapper = IncidentioBlock.tools.config?.params + if (!mapper) throw new Error('incidentio block has no params mapper') + return { ...params, ...mapper(params) } + } + + it('creates a firing alert event', () => { + const alert = runCanvas({ + operation: 'incidentio_alert_events_create', + alert_status: '', + alert_title: 'Disk full', + }) + expect(alert.status).toBe('firing') + }) + + it('creates a schedule in UTC', () => { + expect(runCanvas({ operation: 'incidentio_schedules_create', timezone: '' }).timezone).toBe( + 'UTC' + ) + expect( + runCanvas({ operation: 'incidentio_schedules_create', timezone: 'Europe/London' }).timezone + ).toBe('Europe/London') + }) + + it('creates an active workflow', () => { + expect(runCanvas({ operation: 'incidentio_workflows_create', state: '' }).state).toBe('active') + expect(runCanvas({ operation: 'incidentio_workflows_create', state: 'draft' }).state).toBe( + 'draft' + ) + }) + + it("leaves an update's 'No change' options unset", () => { + expect(runCanvas({ operation: 'incidentio_schedules_update', timezone: '' }).timezone).toBe('') + expect(runCanvas({ operation: 'incidentio_workflows_update', state: '' }).state).toBe('') + }) +}) diff --git a/apps/sim/blocks/blocks/incidentio.ts b/apps/sim/blocks/blocks/incidentio.ts index d7f18519767..1d3fc6b5131 100644 --- a/apps/sim/blocks/blocks/incidentio.ts +++ b/apps/sim/blocks/blocks/incidentio.ts @@ -1,7 +1,7 @@ import { IncidentioIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { isToolCall, mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' import { getTrigger } from '@/triggers' /** Identifiers a user can be looked up by, whichever one is filled. */ @@ -319,6 +319,8 @@ export const IncidentioBlock: BlockConfig = { 'incidentio_incident_alerts_list', 'incidentio_catalog_entries_list', 'incidentio_teams_list', + 'incidentio_actions_list', + 'incidentio_follow_ups_list', ], }, mode: 'advanced', @@ -343,6 +345,8 @@ export const IncidentioBlock: BlockConfig = { 'incidentio_incident_alerts_list', 'incidentio_catalog_entries_list', 'incidentio_teams_list', + 'incidentio_actions_list', + 'incidentio_follow_ups_list', ], }, mode: 'advanced', @@ -401,17 +405,13 @@ Return ONLY the summary text - no explanations.`, field: 'operation', value: ['incidentio_incidents_create', 'incidentio_incidents_update'], }, - required: { field: 'operation', value: 'incidentio_incidents_create' }, }, { id: 'incident_type_id', title: 'Incident Type ID', type: 'short-input', placeholder: 'Enter incident type ID...', - condition: { - field: 'operation', - value: ['incidentio_incidents_create', 'incidentio_incidents_update'], - }, + condition: { field: 'operation', value: 'incidentio_incidents_create' }, }, { id: 'incident_status_id', @@ -578,6 +578,21 @@ Return ONLY the title - no explanations.`, placeholder: 'Enter user IDs, comma-separated (required if no path ID)...', condition: { field: 'operation', value: 'incidentio_escalations_create' }, }, + { + id: 'escalation_description', + title: 'Description', + type: 'long-input', + placeholder: 'Additional details included with the page...', + condition: { field: 'operation', value: 'incidentio_escalations_create' }, + }, + { + id: 'escalation_incident_id', + title: 'Incident ID', + type: 'short-input', + placeholder: 'Link the escalation to an incident (optional)...', + condition: { field: 'operation', value: 'incidentio_escalations_create' }, + mode: 'advanced', + }, { id: 'incident_id', title: 'Incident ID', @@ -613,6 +628,7 @@ Return ONLY the title - no explanations.`, title: 'Incident Mode', type: 'dropdown', options: [ + { label: 'Standard and Retrospective', id: '' }, { label: 'Standard', id: 'standard' }, { label: 'Retrospective', id: 'retrospective' }, { label: 'Test', id: 'test' }, @@ -648,11 +664,18 @@ Return ONLY the title - no explanations.`, title: 'State', type: 'dropdown', options: [ + { label: 'No change', id: '' }, { label: 'Active', id: 'active' }, { label: 'Draft', id: 'draft' }, { label: 'Disabled', id: 'disabled' }, ], - value: () => 'active', + value: (params) => + params?.operation === 'incidentio_workflows_create' + ? 'active' + : params?.operation === 'incidentio_workflows_update' + ? '' + : undefined, + dependsOn: ['operation'], condition: { field: 'operation', value: ['incidentio_workflows_create', 'incidentio_workflows_update'], @@ -823,6 +846,7 @@ Return ONLY the title - no explanations.`, title: 'Timezone', type: 'dropdown', options: [ + { label: 'No change', id: '' }, { label: 'America/New_York (Eastern)', id: 'America/New_York' }, { label: 'America/Chicago (Central)', id: 'America/Chicago' }, { label: 'America/Denver (Mountain)', id: 'America/Denver' }, @@ -847,12 +871,17 @@ Return ONLY the title - no explanations.`, { label: 'Pacific/Auckland (New Zealand)', id: 'Pacific/Auckland' }, { label: 'UTC', id: 'UTC' }, ], - value: () => 'UTC', + value: (params) => + params?.operation === 'incidentio_schedules_create' + ? 'UTC' + : params?.operation === 'incidentio_schedules_update' + ? '' + : undefined, + dependsOn: ['operation'], condition: { field: 'operation', value: ['incidentio_schedules_create', 'incidentio_schedules_update'], }, - required: { field: 'operation', value: 'incidentio_schedules_create' }, }, { id: 'config', @@ -872,7 +901,7 @@ The configuration must follow this structure: "name": "Rotation Name", "users": [{"id": "user_id"}], "handover_start_at": "ISO8601 timestamp", - "handovers": [{"interval": number, "interval_type": "daily|weekly|monthly"}] + "handovers": [{"interval": number, "interval_type": "hourly|daily|weekly"}] } ] } @@ -1132,7 +1161,7 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, title: 'Path Configuration', type: 'long-input', placeholder: - 'JSON array of escalation levels: [{"targets": [{"id": "...", "type": "...", "urgency": "..."}], "time_to_ack_seconds": 300}]', + 'JSON array of nodes: [{"id": "lvl1", "type": "level", "level": {"targets": [{"id": "", "type": "schedule", "schedule_mode": "currently_on_call", "urgency": "high"}], "time_to_ack_seconds": 300}}]', condition: { field: 'operation', value: ['incidentio_escalation_paths_create', 'incidentio_escalation_paths_update'], @@ -1140,16 +1169,22 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, required: true, wandConfig: { enabled: true, - prompt: `Generate a JSON array for escalation path configuration based on the user's description. -The array must follow this structure: + prompt: `Generate a JSON array of incident.io escalation path nodes based on the user's description. +Each node needs a unique "id" and a "type". A "level" node pages its targets and waits for an acknowledgment: [ { - "targets": [{"id": "target_id", "type": "user|schedule", "urgency": "high|low"}], - "time_to_ack_seconds": number + "id": "lvl1", + "type": "level", + "level": { + "targets": [ + {"id": "schedule_or_user_id", "type": "schedule|user", "schedule_mode": "currently_on_call", "urgency": "high|low"} + ], + "time_to_ack_seconds": number + } } ] -Each level represents an escalation step with acknowledgment timeout. +Use one level node per escalation step, in order. Only set "schedule_mode" on schedule targets. Return ONLY the JSON array - no explanations or markdown formatting.`, placeholder: @@ -1162,7 +1197,7 @@ Return ONLY the JSON array - no explanations or markdown formatting.`, title: 'Working Hours', type: 'long-input', placeholder: - 'Optional JSON array: [{"weekday": "monday", "start_time": "09:00", "end_time": "17:00"}]', + 'Optional JSON array: [{"id": "wh", "name": "Business hours", "timezone": "Europe/London", "weekday_intervals": [{"weekday": "monday", "start_time": "09:00", "end_time": "17:00"}]}]', condition: { field: 'operation', value: ['incidentio_escalation_paths_create', 'incidentio_escalation_paths_update'], @@ -1172,7 +1207,14 @@ Return ONLY the JSON array - no explanations or markdown formatting.`, prompt: `Generate a JSON array for working hours configuration based on the user's description. The array must follow this structure: [ - {"weekday": "monday|tuesday|wednesday|thursday|friday|saturday|sunday", "start_time": "HH:MM", "end_time": "HH:MM"} + { + "id": "unique_id", + "name": "Business hours", + "timezone": "IANA timezone, e.g. Europe/London", + "weekday_intervals": [ + {"weekday": "monday|tuesday|wednesday|thursday|friday|saturday|sunday", "start_time": "HH:MM", "end_time": "HH:MM"} + ] + } ] Return ONLY the JSON array - no explanations or markdown formatting.`, @@ -1185,14 +1227,16 @@ Return ONLY the JSON array - no explanations or markdown formatting.`, title: 'Alert Status', type: 'dropdown', options: [ + { label: 'Any', id: '' }, { label: 'Firing', id: 'firing' }, { label: 'Resolved', id: 'resolved' }, ], + value: (params) => (params?.operation === 'incidentio_alert_events_create' ? 'firing' : ''), + dependsOn: ['operation'], condition: { field: 'operation', value: ['incidentio_alerts_list', 'incidentio_alert_events_create'], }, - required: { field: 'operation', value: 'incidentio_alert_events_create' }, }, { id: 'status_operator', @@ -1740,7 +1784,8 @@ Return ONLY the description - no explanations.`, return 'incidentio_incidents_list' } }, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const result: Record = {} const toBoolean = (value: unknown) => value === true || value === 'true' if (params.page_size) result.page_size = Number(params.page_size) @@ -1756,38 +1801,57 @@ Return ONLY the description - no explanations.`, if (params.skip_step_upgrades !== undefined) { result.skip_step_upgrades = toBoolean(params.skip_step_upgrades) } - if (params.operation === 'incidentio_users_list') { + // Status dropdowns are always seeded, so on a tool call the model's `status` must win. + const pickStatus = (dropdownValue: unknown) => { + const status = toolCallArg(context, params.status) || dropdownValue + if (status) result.status = status + } + if (operation === 'incidentio_users_list') { if (params.user_email) result.email = params.user_email if (params.user_slack_id) result.slack_user_id = params.user_slack_id } - if (params.operation === 'incidentio_alerts_list') { - if (params.alert_status) result.status = params.alert_status + if (operation === 'incidentio_alerts_list') { + // A tool row can't show this dropdown, so its stored value is only the seeded default. + pickStatus(isToolCall(context) ? undefined : params.alert_status) result.has_notes = toTriState(params.has_notes) result.include_maintenance_window = toTriState(params.include_maintenance_window) } - if (params.operation === 'incidentio_alert_events_create') { - if (params.alert_status) result.status = params.alert_status + // The editor seeds these dropdowns without an operation, so a new create block holds ''. + if (operation === 'incidentio_alert_events_create') { + pickStatus(params.alert_status || 'firing') if (params.alert_title) result.title = params.alert_title if (params.alert_description) result.description = params.alert_description } + if (operation === 'incidentio_schedules_create' && !params.timezone) { + result.timezone = 'UTC' + } + // On a tool call a missing state keeps the tool's 'draft' default, so an agent never + // creates a live workflow by omission. + if (operation === 'incidentio_workflows_create' && !params.state && !isToolCall(context)) { + result.state = 'active' + } + if (operation === 'incidentio_escalations_create') { + if (params.escalation_description) result.description = params.escalation_description + if (params.escalation_incident_id) result.incident_id = params.escalation_incident_id + } if ( - params.operation === 'incidentio_follow_ups_create' || - params.operation === 'incidentio_follow_ups_update' + operation === 'incidentio_follow_ups_create' || + operation === 'incidentio_follow_ups_update' ) { if (params.follow_up_title) result.title = params.follow_up_title if (params.follow_up_description) result.description = params.follow_up_description } if ( - params.operation === 'incidentio_actions_create' || - params.operation === 'incidentio_actions_update' + operation === 'incidentio_actions_create' || + operation === 'incidentio_actions_update' ) { if (params.action_description) result.description = params.action_description } if ( - params.operation === 'incidentio_follow_ups_update' || - params.operation === 'incidentio_actions_update' + operation === 'incidentio_follow_ups_update' || + operation === 'incidentio_actions_update' ) { - if (params.item_status) result.status = params.item_status + pickStatus(params.item_status) } return result }, @@ -1890,6 +1954,8 @@ Return ONLY the description - no explanations.`, follow_up_priority_option_id: { type: 'string', description: 'Follow-up priority option ID' }, external_issue_reference_id: { type: 'string', description: 'External issue reference ID' }, labels: { type: 'string', description: 'Comma-separated follow-up labels' }, + escalation_description: { type: 'string', description: 'Escalation description' }, + escalation_incident_id: { type: 'string', description: 'Incident to link an escalation to' }, }, outputs: { incidents: { type: 'json', description: 'List of incidents' }, diff --git a/apps/sim/blocks/blocks/infisical.ts b/apps/sim/blocks/blocks/infisical.ts index b233d6f3744..71a40032a63 100644 --- a/apps/sim/blocks/blocks/infisical.ts +++ b/apps/sim/blocks/blocks/infisical.ts @@ -1,7 +1,7 @@ import { InfisicalIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, withSavedCredential } from '@/blocks/utils' export const InfisicalBlock: BlockConfig = { type: 'infisical', @@ -192,7 +192,7 @@ export const InfisicalBlock: BlockConfig = { ], config: { tool: (params) => `infisical_${params.operation}`, - params: (params) => { + params: (params, context) => { const result: Record = { apiKey: params.apiKey, projectId: params.projectId, @@ -202,7 +202,7 @@ export const InfisicalBlock: BlockConfig = { if (params.baseUrl) result.baseUrl = params.baseUrl if (params.secretPath) result.secretPath = params.secretPath - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'list_secrets': if (params.recursive != null) result.recursive = params.recursive if (params.includeImports != null) result.includeImports = params.includeImports diff --git a/apps/sim/blocks/blocks/instagram.test.ts b/apps/sim/blocks/blocks/instagram.test.ts index d1948b9a428..917c1a82c88 100644 --- a/apps/sim/blocks/blocks/instagram.test.ts +++ b/apps/sim/blocks/blocks/instagram.test.ts @@ -76,4 +76,26 @@ describe('InstagramBlock', () => { buildParams({ operation: 'instagram_get_account_insights', period: 'week' }) ).toThrow('Instagram account insights period must be day or lifetime') }) + + it('forwards the media and metrics an agent passes under the tool param names', () => { + const file = { + id: 'file-1', + key: 'execution/workflow/execution/photo.jpg', + name: 'photo.jpg', + size: 1024, + type: 'image/jpeg', + } + const carousel = buildParams( + { oauthCredential: 'credential-1', media: [file, { ...file, id: 'file-2' }], caption: 'hi' }, + { operation: 'instagram_publish_carousel' } + ) + expect(carousel).toMatchObject({ caption: 'hi' }) + expect(carousel.media).toHaveLength(2) + + const insights = buildParams( + { oauthCredential: 'credential-1', mediaId: 'media-1', metrics: 'reach,views' }, + { operation: 'instagram_get_media_insights' } + ) + expect(insights).toMatchObject({ mediaId: 'media-1', metrics: 'reach,views' }) + }) }) diff --git a/apps/sim/blocks/blocks/instagram.ts b/apps/sim/blocks/blocks/instagram.ts index 6862204a45b..da0749eede4 100644 --- a/apps/sim/blocks/blocks/instagram.ts +++ b/apps/sim/blocks/blocks/instagram.ts @@ -2,7 +2,7 @@ import { InstagramIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput } from '@/blocks/utils' +import { mapperOperation, normalizeFileInput, toolCallArg } from '@/blocks/utils' const IG_USER_ID_OPS = [ 'instagram_list_media', @@ -780,8 +780,8 @@ Return ONLY the timestamp or date - no explanations, no extra text.`, } return operation }, - params: (params) => { - const operation = typeof params.operation === 'string' ? params.operation : '' + params: (params, context) => { + const operation = mapperOperation(params, context) const result: Record = { credential: params.oauthCredential, } @@ -805,12 +805,17 @@ Return ONLY the timestamp or date - no explanations, no extra text.`, const resolved = normalizeFileInput(params.media, { single: true }) if (resolved) result.media = resolved } else if (operation === 'instagram_publish_carousel') { - const resolved = normalizeFileInput(params.carouselMedia) + const resolved = + normalizeFileInput(params.carouselMedia) ?? + normalizeFileInput(toolCallArg(context, params.media)) if (resolved) result.media = resolved } for (const key of OPERATION_PARAM_KEYS[operation] ?? []) { - const value = params[key] + const value = + key === 'insightMetrics' + ? params.insightMetrics || toolCallArg(context, params.metrics) + : params[key] if (value === undefined || value === null || value === '') continue if (key === 'insightMetrics') { diff --git a/apps/sim/blocks/blocks/instantly.test.ts b/apps/sim/blocks/blocks/instantly.test.ts new file mode 100644 index 00000000000..a616b454f7f --- /dev/null +++ b/apps/sim/blocks/blocks/instantly.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from 'vitest' +import { InstantlyV2Block } from '@/blocks/blocks/instantly' +import type { BlockToolParamsContext } from '@/blocks/types' + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = InstantlyV2Block.tools.config?.params + if (!mapper) throw new Error('Instantly block has no params mapper') + return { ...params, ...mapper(params, context) } +} + +describe('Instantly agent tool calls', () => { + it('keeps the model interest value so the update does not fail as missing', () => { + const merged = mapParams( + { lead_email: 'ann@example.com', interest_value: 1, campaign_id: 'camp-1' }, + { operation: 'update_lead_interest_status' } + ) + + expect(merged.interest_value).toBe(1) + expect(merged.campaign_id).toBe('camp-1') + }) + + it('keeps model lead fields named by the tool instead of wiping them', () => { + const merged = mapParams( + { email: 'ann@example.com', first_name: 'Ann', campaign: 'camp-1', skip_if_in_list: true }, + { operation: 'create_lead' } + ) + + expect(merged).toMatchObject({ first_name: 'Ann', campaign: 'camp-1', skip_if_in_list: true }) + }) + + it('keeps the model reply body when the block body fields are empty', () => { + const merged = mapParams( + { reply_to_uuid: 'email-1', eaccount: 'me@example.com', subject: 'Re', body: { text: 'Hi' } }, + { operation: 'reply_to_email' } + ) + + expect(merged.body).toEqual({ text: 'Hi' }) + }) +}) diff --git a/apps/sim/blocks/blocks/instantly.ts b/apps/sim/blocks/blocks/instantly.ts index 08c22aecefe..9484186e167 100644 --- a/apps/sim/blocks/blocks/instantly.ts +++ b/apps/sim/blocks/blocks/instantly.ts @@ -2,7 +2,7 @@ import { isRecordLike } from '@sim/utils/object' import { InstantlyIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { isToolCall, mapperOperation, withSavedCredential } from '@/blocks/utils' import { getTrigger } from '@/triggers' const LEAD_LIST_OPERATIONS = ['list_leads'] as const @@ -932,81 +932,198 @@ export const InstantlyBlock: BlockConfig = { ], config: { tool: (params) => `instantly_${params.operation}`, - params: (params) => ({ - campaign: mapCampaignParam(params), - list_id: mapListIdParam(params), - campaign_id: mapCampaignIdParam(params), - leadId: params.leadId, - email: emptyToUndefined(params.email), - first_name: emptyToUndefined(params.firstName), - last_name: emptyToUndefined(params.lastName), - company_name: emptyToUndefined(params.companyName), - job_title: emptyToUndefined(params.jobTitle), - phone: emptyToUndefined(params.phone), - website: emptyToUndefined(params.website), - personalization: emptyToUndefined(params.personalization), - custom_variables: parseJsonObject(params.customVariables), - lt_interest_status: toNumberParam(params.leadInterestStatus), - pl_value_lead: emptyToUndefined(params.potentialLeadValue), - assigned_to: optionalIdParam(params.assignedTo), - blocklist_id: optionalIdParam(params.blocklistId), - skip_if_in_workspace: toBooleanParam(params.skipIfInWorkspace), - skip_if_in_campaign: toBooleanParam(params.skipIfInCampaign), - skip_if_in_list: toBooleanParam(params.skipIfInList), - verify_leads_for_lead_finder: toBooleanParam(params.verifyLeadsForLeadFinder), - verify_leads_on_import: toBooleanParam(params.verifyLeadsOnImport), - filter: emptyToUndefined(params.leadFilter), - ids: mapIdsParam(params), - excluded_ids: parseStringList(params.excludedLeadIds), - contacts: parseStringList(params.contacts), - organization_user_ids: parseStringList(params.organizationUserIds), - smart_view_id: optionalIdParam(params.smartViewId), - is_website_visitor: toBooleanParam(params.websiteVisitor), - distinct_contacts: toBooleanParam(params.distinctContacts), - enrichment_status: toNumberParam(params.enrichmentStatus), - esg_code: emptyToUndefined(params.esgCode), - in_campaign: toBooleanParam(params.inCampaign), - in_list: toBooleanParam(params.inList), - status: mapStatusParam(params), - limit: mapLimitParam(params), - starting_after: mapStartingAfterParam(params), - lead_email: emptyToUndefined(params.leadEmail), - interest_value: - params.operation === 'update_lead_interest_status' - ? toNullableNumberParam(params.interestValue, true) - : undefined, - ai_interest_value: toNumberParam(params.aiInterestValue), - disable_auto_interest: toBooleanParam(params.disableAutoInterest), - name: mapNameParam(params), - campaign_schedule: parseJsonObject(params.campaignSchedule), - sequences: parseJsonArray(params.sequences), - email_list: parseStringList(params.emailList), - daily_limit: toNumberParam(params.dailyLimit), - daily_max_leads: toNumberParam(params.dailyMaxLeads), - open_tracking: toBooleanParam(params.openTracking), - stop_on_reply: toBooleanParam(params.stopOnReply), - pl_value: toNumberParam(params.positiveLeadValue), - email_gap: toNumberParam(params.emailGap), - link_tracking: toBooleanParam(params.linkTracking), - text_only: toBooleanParam(params.textOnly), - tag_ids: emptyToUndefined(params.tagIds), - ai_sales_agent_id: optionalIdParam(params.aiSalesAgentId), - search: mapSearchParam(params), - eaccount: emptyToUndefined(params.emailAccount), - i_status: toNumberParam(params.emailStatus), - lead: emptyToUndefined(params.emailLead), - is_unread: toBooleanParam(params.emailIsUnread), - reply_to_uuid: emptyToUndefined(params.replyToUuid), - subject: emptyToUndefined(params.subject), - body: { - text: emptyToUndefined(params.bodyText), - html: emptyToUndefined(params.bodyHtml), - }, - cc_address_email_list: emptyToUndefined(params.ccRecipients), - bcc_address_email_list: emptyToUndefined(params.bccRecipients), - has_enrichment_task: toBooleanParam(params.hasEnrichmentTask), - owned_by: optionalIdParam(params.ownedBy), - }), + params: (params, context) => { + const operation = mapperOperation(params, context) + const toolCall = isToolCall(context) + /** + * The block field's value, else on a tool call the model's arg under the tool's own param + * name: the result is spread over the merged params, so an `undefined` here wipes that arg. + */ + const orArg = ( + blockValue: T | undefined, + toolKey: string, + coerce: (value: unknown) => T | undefined + ): T | undefined => + blockValue !== undefined || !toolCall ? blockValue : coerce(params[toolKey]) + + return { + campaign: orArg(mapCampaignParam(params, operation), 'campaign', optionalIdParam), + list_id: orArg(mapListIdParam(params, operation), 'list_id', optionalIdParam), + campaign_id: orArg(mapCampaignIdParam(params, operation), 'campaign_id', optionalIdParam), + leadId: params.leadId, + email: emptyToUndefined(params.email), + first_name: orArg(emptyToUndefined(params.firstName), 'first_name', emptyToUndefined), + last_name: orArg(emptyToUndefined(params.lastName), 'last_name', emptyToUndefined), + company_name: orArg( + emptyToUndefined(params.companyName), + 'company_name', + emptyToUndefined + ), + job_title: orArg(emptyToUndefined(params.jobTitle), 'job_title', emptyToUndefined), + phone: emptyToUndefined(params.phone), + website: emptyToUndefined(params.website), + personalization: emptyToUndefined(params.personalization), + custom_variables: orArg( + parseJsonObject(params.customVariables), + 'custom_variables', + parseJsonObject + ), + lt_interest_status: orArg( + toNumberParam(params.leadInterestStatus), + 'lt_interest_status', + toNumberParam + ), + pl_value_lead: orArg( + emptyToUndefined(params.potentialLeadValue), + 'pl_value_lead', + emptyToUndefined + ), + assigned_to: orArg(optionalIdParam(params.assignedTo), 'assigned_to', optionalIdParam), + blocklist_id: orArg(optionalIdParam(params.blocklistId), 'blocklist_id', optionalIdParam), + skip_if_in_workspace: orArg( + toBooleanParam(params.skipIfInWorkspace), + 'skip_if_in_workspace', + toBooleanParam + ), + skip_if_in_campaign: orArg( + toBooleanParam(params.skipIfInCampaign), + 'skip_if_in_campaign', + toBooleanParam + ), + skip_if_in_list: orArg( + toBooleanParam(params.skipIfInList), + 'skip_if_in_list', + toBooleanParam + ), + verify_leads_for_lead_finder: orArg( + toBooleanParam(params.verifyLeadsForLeadFinder), + 'verify_leads_for_lead_finder', + toBooleanParam + ), + verify_leads_on_import: orArg( + toBooleanParam(params.verifyLeadsOnImport), + 'verify_leads_on_import', + toBooleanParam + ), + filter: orArg(emptyToUndefined(params.leadFilter), 'filter', emptyToUndefined), + ids: orArg(mapIdsParam(params, operation), 'ids', parseStringList), + excluded_ids: orArg( + parseStringList(params.excludedLeadIds), + 'excluded_ids', + parseStringList + ), + contacts: parseStringList(params.contacts), + organization_user_ids: orArg( + parseStringList(params.organizationUserIds), + 'organization_user_ids', + parseStringList + ), + smart_view_id: orArg( + optionalIdParam(params.smartViewId), + 'smart_view_id', + optionalIdParam + ), + is_website_visitor: orArg( + toBooleanParam(params.websiteVisitor), + 'is_website_visitor', + toBooleanParam + ), + distinct_contacts: orArg( + toBooleanParam(params.distinctContacts), + 'distinct_contacts', + toBooleanParam + ), + enrichment_status: orArg( + toNumberParam(params.enrichmentStatus), + 'enrichment_status', + toNumberParam + ), + esg_code: orArg(emptyToUndefined(params.esgCode), 'esg_code', emptyToUndefined), + in_campaign: orArg(toBooleanParam(params.inCampaign), 'in_campaign', toBooleanParam), + in_list: orArg(toBooleanParam(params.inList), 'in_list', toBooleanParam), + status: orArg(mapStatusParam(params, operation), 'status', toNumberParam), + limit: orArg(mapLimitParam(params, operation), 'limit', toNumberParam), + starting_after: orArg( + mapStartingAfterParam(params, operation), + 'starting_after', + emptyToUndefined + ), + lead_email: orArg(emptyToUndefined(params.leadEmail), 'lead_email', emptyToUndefined), + interest_value: mapInterestValueParam(params, operation, toolCall), + ai_interest_value: orArg( + toNumberParam(params.aiInterestValue), + 'ai_interest_value', + toNumberParam + ), + disable_auto_interest: orArg( + toBooleanParam(params.disableAutoInterest), + 'disable_auto_interest', + toBooleanParam + ), + name: orArg(mapNameParam(params, operation), 'name', emptyToUndefined), + campaign_schedule: orArg( + parseJsonObject(params.campaignSchedule), + 'campaign_schedule', + parseJsonObject + ), + sequences: parseJsonArray(params.sequences), + email_list: orArg(parseStringList(params.emailList), 'email_list', parseStringList), + daily_limit: orArg(toNumberParam(params.dailyLimit), 'daily_limit', toNumberParam), + daily_max_leads: orArg( + toNumberParam(params.dailyMaxLeads), + 'daily_max_leads', + toNumberParam + ), + open_tracking: orArg( + toBooleanParam(params.openTracking), + 'open_tracking', + toBooleanParam + ), + stop_on_reply: orArg(toBooleanParam(params.stopOnReply), 'stop_on_reply', toBooleanParam), + pl_value: orArg(toNumberParam(params.positiveLeadValue), 'pl_value', toNumberParam), + email_gap: orArg(toNumberParam(params.emailGap), 'email_gap', toNumberParam), + link_tracking: orArg( + toBooleanParam(params.linkTracking), + 'link_tracking', + toBooleanParam + ), + text_only: orArg(toBooleanParam(params.textOnly), 'text_only', toBooleanParam), + tag_ids: orArg(emptyToUndefined(params.tagIds), 'tag_ids', emptyToUndefined), + ai_sales_agent_id: orArg( + optionalIdParam(params.aiSalesAgentId), + 'ai_sales_agent_id', + optionalIdParam + ), + search: orArg(mapSearchParam(params, operation), 'search', emptyToUndefined), + eaccount: orArg(emptyToUndefined(params.emailAccount), 'eaccount', emptyToUndefined), + i_status: orArg(toNumberParam(params.emailStatus), 'i_status', toNumberParam), + lead: orArg(emptyToUndefined(params.emailLead), 'lead', emptyToUndefined), + is_unread: orArg(toBooleanParam(params.emailIsUnread), 'is_unread', toBooleanParam), + reply_to_uuid: orArg( + emptyToUndefined(params.replyToUuid), + 'reply_to_uuid', + emptyToUndefined + ), + subject: emptyToUndefined(params.subject), + body: mapBodyParam(params, toolCall), + cc_address_email_list: orArg( + emptyToUndefined(params.ccRecipients), + 'cc_address_email_list', + emptyToUndefined + ), + bcc_address_email_list: orArg( + emptyToUndefined(params.bccRecipients), + 'bcc_address_email_list', + emptyToUndefined + ), + has_enrichment_task: orArg( + toBooleanParam(params.hasEnrichmentTask), + 'has_enrichment_task', + toBooleanParam + ), + owned_by: orArg(optionalIdParam(params.ownedBy), 'owned_by', optionalIdParam), + } + }, }, }, inputs: { @@ -1232,14 +1349,14 @@ function emptyToUndefined(value: unknown): unknown { return trimmed === '' || trimmed === '-' ? undefined : trimmed } -function mapCampaignParam(params: Record): string | undefined { - if (params.operation === 'list_leads') return optionalIdParam(params.campaignId) - if (params.operation !== 'create_lead' || params.leadDestination !== 'campaign') return undefined +function mapCampaignParam(params: Record, operation: string): string | undefined { + if (operation === 'list_leads') return optionalIdParam(params.campaignId) + if (operation !== 'create_lead' || params.leadDestination !== 'campaign') return undefined return optionalIdParam(params.leadDestinationId) } -function mapListIdParam(params: Record): string | undefined { - switch (params.operation) { +function mapListIdParam(params: Record, operation: string): string | undefined { + switch (operation) { case 'delete_leads': return params.deleteSource === 'list' ? optionalIdParam(params.deleteSourceId) : undefined case 'create_lead': @@ -1255,42 +1372,45 @@ function mapListIdParam(params: Record): string | undefined { } } -function mapCampaignIdParam(params: Record): string | undefined { - if (params.operation === 'delete_leads') { +function mapCampaignIdParam( + params: Record, + operation: string +): string | undefined { + if (operation === 'delete_leads') { return params.deleteSource === 'campaign' ? optionalIdParam(params.deleteSourceId) : undefined } - if (params.operation === 'update_lead_interest_status' || params.operation === 'list_emails') { + if (operation === 'update_lead_interest_status' || operation === 'list_emails') { return optionalIdParam(params.campaignId) } return undefined } -function mapIdsParam(params: Record): string[] | undefined { - if (params.operation === 'delete_leads') return parseStringList(params.deleteLeadIds) - if (params.operation === 'list_leads') return parseStringList(params.leadIds) +function mapIdsParam(params: Record, operation: string): string[] | undefined { + if (operation === 'delete_leads') return parseStringList(params.deleteLeadIds) + if (operation === 'list_leads') return parseStringList(params.leadIds) return undefined } -function mapStatusParam(params: Record): number | undefined { - if (params.operation === 'delete_leads') return toNumberParam(params.deleteStatus) - if (params.operation === 'list_campaigns') return toNumberParam(params.campaignStatus) +function mapStatusParam(params: Record, operation: string): number | undefined { + if (operation === 'delete_leads') return toNumberParam(params.deleteStatus) + if (operation === 'list_campaigns') return toNumberParam(params.campaignStatus) return undefined } -function mapLimitParam(params: Record): number | undefined { - if (params.operation === 'delete_leads') return toNumberParam(params.deleteLimit) - if (isPaginatedOperation(params.operation)) return toNumberParam(params.limit) +function mapLimitParam(params: Record, operation: string): number | undefined { + if (operation === 'delete_leads') return toNumberParam(params.deleteLimit) + if (isPaginatedOperation(operation)) return toNumberParam(params.limit) return undefined } -function mapStartingAfterParam(params: Record): unknown { - return isPaginatedOperation(params.operation) ? emptyToUndefined(params.startingAfter) : undefined +function mapStartingAfterParam(params: Record, operation: string): unknown { + return isPaginatedOperation(operation) ? emptyToUndefined(params.startingAfter) : undefined } -function mapNameParam(params: Record): unknown { - switch (params.operation) { +function mapNameParam(params: Record, operation: string): unknown { + switch (operation) { case 'create_lead_list': return emptyToUndefined(params.leadListName) case 'create_campaign': @@ -1301,12 +1421,34 @@ function mapNameParam(params: Record): unknown { } } -function mapSearchParam(params: Record): unknown { - if (params.operation === 'list_emails') return emptyToUndefined(params.emailSearch) - if (isSearchOperation(params.operation)) return emptyToUndefined(params.search) +function mapSearchParam(params: Record, operation: string): unknown { + if (operation === 'list_emails') return emptyToUndefined(params.emailSearch) + if (isSearchOperation(operation)) return emptyToUndefined(params.search) return undefined } +function mapInterestValueParam( + params: Record, + operation: string, + toolCall: boolean +): number | null | undefined { + if (operation !== 'update_lead_interest_status') return undefined + const blockValueEmpty = + params.interestValue === undefined || + (typeof params.interestValue === 'string' && params.interestValue.trim() === '') + if (toolCall && blockValueEmpty) return toNullableNumberParam(params.interest_value) + return toNullableNumberParam(params.interestValue, true) +} + +function mapBodyParam(params: Record, toolCall: boolean): unknown { + const text = emptyToUndefined(params.bodyText) + const html = emptyToUndefined(params.bodyHtml) + if (toolCall && text === undefined && html === undefined) { + return parseJsonObject(params.body) ?? emptyToUndefined(params.body) + } + return { text, html } +} + function isPaginatedOperation(value: unknown): boolean { return ( value === 'list_leads' || diff --git a/apps/sim/blocks/blocks/intercom.test.ts b/apps/sim/blocks/blocks/intercom.test.ts index 8e761a8c81a..077c4c2a58a 100644 --- a/apps/sim/blocks/blocks/intercom.test.ts +++ b/apps/sim/blocks/blocks/intercom.test.ts @@ -74,3 +74,35 @@ describe('Intercom role defaults', () => { expect(options()[0]?.id).toBe('lead') }) }) + +describe('Intercom tool-row fields on a tool call', () => { + it.each([ + { operation: 'update_ticket', field: 'ticket_assignee_id', param: 'assignee_id' }, + { operation: 'create_contact', field: 'contact_company_id', param: 'company_id' }, + { operation: 'close_conversation', field: 'close_body', param: 'body' }, + { operation: 'assign_conversation', field: 'assign_body', param: 'body' }, + { operation: 'create_note', field: 'note_body', param: 'body' }, + { operation: 'create_note', field: 'tag_contact_id', param: 'contactId' }, + { operation: 'attach_contact_to_company', field: 'attach_company_id', param: 'companyId' }, + { operation: 'create_tag', field: 'tag_name', param: 'name' }, + { operation: 'create_tag', field: 'tag_id_update', param: 'id' }, + { operation: 'create_event', field: 'event_user_id', param: 'user_id' }, + { operation: 'create_event', field: 'event_email', param: 'email' }, + { operation: 'create_event', field: 'event_contact_id', param: 'id' }, + { operation: 'create_event', field: 'event_metadata', param: 'metadata' }, + { operation: 'create_message', field: 'message_type_msg', param: 'message_type' }, + { operation: 'create_company', field: 'company_name', param: 'name' }, + ])( + 'keeps the pinned $field over the model $param on $operation', + ({ operation, field, param }) => { + const mapped = mapParams({ [field]: 'pinned', [param]: 'model' }, { operation }) + expect(mapped[param]).toBe('pinned') + } + ) + + it('fills a param from the model when the row leaves its field empty', () => { + expect(mapParams({ assignee_id: 'model' }, { operation: 'update_ticket' }).assignee_id).toBe( + 'model' + ) + }) +}) diff --git a/apps/sim/blocks/blocks/intercom.ts b/apps/sim/blocks/blocks/intercom.ts index 6121c2c4e32..7f92408daac 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) { @@ -169,8 +173,9 @@ const mapIntercomParams: IntercomParamsMapper = (params, context) => { if (event_created_at) cleanParams.created_at = Number(event_created_at) } + // A block field mapped above (pinned on a tool row) beats the model's arg under the tool's name. Object.entries(rest).forEach(([key, value]) => { - if (value !== undefined && value !== null && value !== '') { + if (hasInput(value) && cleanParams[key] === undefined) { cleanParams[key] = value } }) 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/jotform.test.ts b/apps/sim/blocks/blocks/jotform.test.ts index e3279e61ebb..da3a395a959 100644 --- a/apps/sim/blocks/blocks/jotform.test.ts +++ b/apps/sim/blocks/blocks/jotform.test.ts @@ -25,4 +25,14 @@ describe('JotformBlock', () => { expect({ ...inputs, ...buildParams(inputs) }.questions).toBe(inputs.bulkQuestions) }) + + /** + * An agent tool call passes the operation only in `context`; a report title filled + * on the tool row must still reach the tool's `title` param. + */ + it('maps tool-row fields on an agent tool call', () => { + const args: Record = { apiKey: 'key', formId: '2315', reportTitle: 'Weekly' } + + expect({ ...args, ...buildParams(args, { operation: 'create_report' }) }.title).toBe('Weekly') + }) }) diff --git a/apps/sim/blocks/blocks/jotform.ts b/apps/sim/blocks/blocks/jotform.ts index 7157680f467..d4b4d2cf8dd 100644 --- a/apps/sim/blocks/blocks/jotform.ts +++ b/apps/sim/blocks/blocks/jotform.ts @@ -1,6 +1,6 @@ import { JotformIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, withSavedCredential } from '@/blocks/utils' import { getTrigger } from '@/triggers' /** @@ -730,10 +730,10 @@ export const JotformBlock: BlockConfig = { * Everything else — formId, submissionId, answers, the pagination fields — is * named after its param and reaches the tool unchanged. */ - params: (params) => { + params: (params, context) => { const result: Record = {} - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'create_form': if (params.newFormQuestions) result.questions = params.newFormQuestions if (params.newFormProperties) result.properties = params.newFormProperties diff --git a/apps/sim/blocks/blocks/jupyter.ts b/apps/sim/blocks/blocks/jupyter.ts index 12f41d9f88e..891d4c3dffc 100644 --- a/apps/sim/blocks/blocks/jupyter.ts +++ b/apps/sim/blocks/blocks/jupyter.ts @@ -3,6 +3,7 @@ import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' import { createVersionedToolSelector, + mapperOperation, normalizeFileInput, withSavedCredential, } from '@/blocks/utils' @@ -292,61 +293,59 @@ export const JupyterBlock = { ], config: { tool: (params) => params.operation as string, - params: (params) => { + params: (params, context) => { const normalizedFile = normalizeFileInput(params.file, { single: true }) if (normalizedFile) { params.file = normalizedFile } - const { operation, ...rest } = params - const baseParams: Record = { - serverUrl: rest.serverUrl, - token: rest.token, + serverUrl: params.serverUrl, + token: params.token, } - switch (operation) { + switch (mapperOperation(params, context)) { case 'jupyter_list_contents': - if (rest.path) baseParams.path = rest.path + if (params.path) baseParams.path = params.path break case 'jupyter_get_content': case 'jupyter_delete_content': - baseParams.path = rest.path + baseParams.path = params.path break case 'jupyter_create_file': - baseParams.path = rest.path - baseParams.type = rest.type - if (rest.content) baseParams.content = rest.content + baseParams.path = params.path + baseParams.type = params.type + if (params.content) baseParams.content = params.content break case 'jupyter_upload_file': - if (rest.directory) baseParams.directory = rest.directory - baseParams.file = rest.file - if (rest.uploadFileName) baseParams.fileName = rest.uploadFileName + if (params.directory) baseParams.directory = params.directory + baseParams.file = params.file + if (params.uploadFileName) baseParams.fileName = params.uploadFileName break case 'jupyter_rename_content': - baseParams.path = rest.path - baseParams.newPath = rest.newPath + baseParams.path = params.path + baseParams.newPath = params.newPath break case 'jupyter_copy_content': - baseParams.path = rest.path - baseParams.copyFromPath = rest.copyFromPath + baseParams.path = params.path + baseParams.copyFromPath = params.copyFromPath break case 'jupyter_start_kernel': - if (rest.kernelName) baseParams.kernelName = rest.kernelName + if (params.kernelName) baseParams.kernelName = params.kernelName break case 'jupyter_stop_kernel': case 'jupyter_restart_kernel': case 'jupyter_interrupt_kernel': - baseParams.kernelId = rest.kernelId + baseParams.kernelId = params.kernelId break case 'jupyter_create_session': - baseParams.path = rest.path - if (rest.kernelName) baseParams.kernelName = rest.kernelName - if (rest.sessionName) baseParams.name = rest.sessionName - if (rest.sessionType) baseParams.type = rest.sessionType + baseParams.path = params.path + if (params.kernelName) baseParams.kernelName = params.kernelName + if (params.sessionName) baseParams.name = params.sessionName + if (params.sessionType) baseParams.type = params.sessionType break case 'jupyter_delete_session': - baseParams.sessionId = rest.sessionId + baseParams.sessionId = params.sessionId break } diff --git a/apps/sim/blocks/blocks/kalshi.test.ts b/apps/sim/blocks/blocks/kalshi.test.ts new file mode 100644 index 00000000000..0ba5bb8ef46 --- /dev/null +++ b/apps/sim/blocks/blocks/kalshi.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it } from 'vitest' +import { KalshiBlock } from '@/blocks/blocks/kalshi' + +const buildParams = KalshiBlock.tools.config?.params +if (!buildParams) throw new Error('KalshiBlock has no params mapper') + +describe('KalshiBlock', () => { + /** + * An agent tool call passes the operation only in `context`; the order ID filled + * on the tool row must still reach the tool's `orderId` param. + */ + it('maps the order ID field on an agent tool call', () => { + const args: Record = { keyId: 'key', privateKey: 'pem', orderIdParam: 'ord-1' } + + expect({ ...args, ...buildParams(args, { operation: 'cancel_order' }) }.orderId).toBe('ord-1') + }) + + it.each([ + { operation: 'cancel_order', stale: { orderId: 'O-STALE' }, field: { orderIdParam: 'O-NEW' } }, + { operation: 'get_order', stale: { orderId: 'O-STALE' }, field: { orderIdParam: 'O-NEW' } }, + { + operation: 'amend_order', + stale: { clientOrderId: 'C-STALE' }, + field: { clientOrderIdAmend: 'C-NEW' }, + }, + { operation: 'get_orders', stale: { status: 'open' }, field: { orderStatus: 'resting' } }, + ])( + 'sends the $operation field over a stale canvas value under the tool param name', + ({ operation, stale, field }) => { + const canvas: Record = { + operation, + keyId: 'key', + privateKey: 'pem', + ...stale, + ...field, + } + const sent: Record = { ...canvas, ...buildParams(canvas) } + expect(sent[Object.keys(stale)[0]]).toBe(Object.values(field)[0]) + } + ) + + it('drops a stale canvas order ID when the operation field is empty', () => { + const canvas = { operation: 'get_order', orderId: 'O-STALE', orderIdParam: '' } + expect({ ...canvas, ...buildParams(canvas) }.orderId).toBeUndefined() + }) + + it.each([ + { operation: 'cancel_order', param: 'orderId', field: 'orderIdParam' }, + { operation: 'get_orders', param: 'status', field: 'orderStatus' }, + { operation: 'create_order', param: 'type', field: 'orderType' }, + { operation: 'create_order', param: 'ticker', field: 'tickerOrder' }, + ])( + 'keeps the row-pinned $field over the model $param on a $operation tool call', + ({ operation, param, field }) => { + const args = { [field]: 'pinned', [param]: 'model' } + expect({ ...args, ...buildParams(args, { operation }) }[param]).toBe('pinned') + } + ) + + it('keeps the model order ID on a tool call when the row leaves the field empty', () => { + const args = { orderId: 'model' } + expect({ ...args, ...buildParams(args, { operation: 'cancel_order' }) }.orderId).toBe('model') + }) +}) diff --git a/apps/sim/blocks/blocks/kalshi.ts b/apps/sim/blocks/blocks/kalshi.ts index 280e6eebed4..500fc67e0da 100644 --- a/apps/sim/blocks/blocks/kalshi.ts +++ b/apps/sim/blocks/blocks/kalshi.ts @@ -1,7 +1,12 @@ import { KalshiIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { createVersionedToolSelector, withSavedCredential } from '@/blocks/utils' +import { + createVersionedToolSelector, + mapperOperation, + toolCallArg, + withSavedCredential, +} from '@/blocks/utils' /* * Mutually exclusive alternates, not canonical pairs — an order carries either @@ -695,9 +700,9 @@ Return ONLY the numeric timestamp (seconds since Unix epoch) - no explanations, return 'kalshi_get_markets' } }, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { - operation, orderStatus, tickerFilter, tickerFills, @@ -712,69 +717,72 @@ Return ONLY the numeric timestamp (seconds since Unix epoch) - no explanations, ...rest } = params const cleanParams: Record = {} + Object.entries(rest).forEach(([key, value]) => { + if (value !== undefined && value !== null && value !== '') { + cleanParams[key] = value + } + }) + + /** + * The operation's own field wins over a value under the tool's param name: on the canvas + * that value is stale from another operation, and on a tool call the row's field is pinned. + * The model's value fills the param only on a tool call with the field empty. + */ + const mapField = (key: string, field: unknown) => { + cleanParams[key] = field || toolCallArg(context, cleanParams[key]) + } - if (operation === 'get_orders' && orderStatus) { - cleanParams.status = orderStatus + if (operation === 'get_orders') { + mapField('status', orderStatus) } if ( - (operation === 'get_orders' || - operation === 'get_positions' || - operation === 'get_settlements') && - tickerFilter + operation === 'get_orders' || + operation === 'get_positions' || + operation === 'get_settlements' ) { - cleanParams.ticker = tickerFilter + mapField('ticker', tickerFilter) } - if (operation === 'get_fills' && tickerFills) { - cleanParams.ticker = tickerFills + if (operation === 'get_fills') { + mapField('ticker', tickerFills) } if (operation === 'get_candlesticks') { - if (seriesTickerCandlesticks) cleanParams.seriesTicker = seriesTickerCandlesticks - if (tickerCandlesticks) cleanParams.ticker = tickerCandlesticks + mapField('seriesTicker', seriesTickerCandlesticks) + mapField('ticker', tickerCandlesticks) } - // Map series ticker for get_event_candlesticks (event ticker flows through eventTicker) - if (operation === 'get_event_candlesticks' && seriesTickerCandlesticks) { - cleanParams.seriesTicker = seriesTickerCandlesticks + // Event candlesticks take the event ticker through eventTicker + if (operation === 'get_event_candlesticks') { + mapField('seriesTicker', seriesTickerCandlesticks) } - if (operation === 'get_series_by_ticker' && seriesTickerGet) { - cleanParams.seriesTicker = seriesTickerGet + if (operation === 'get_series_by_ticker') { + mapField('seriesTicker', seriesTickerGet) } if ( - (operation === 'get_order' || - operation === 'cancel_order' || - operation === 'amend_order') && - orderIdParam + operation === 'get_order' || + operation === 'cancel_order' || + operation === 'amend_order' ) { - cleanParams.orderId = orderIdParam + mapField('orderId', orderIdParam) } - if ((operation === 'create_order' || operation === 'amend_order') && tickerOrder) { - cleanParams.ticker = tickerOrder + if (operation === 'create_order' || operation === 'amend_order') { + mapField('ticker', tickerOrder) } - if (operation === 'create_order' && orderType) { - cleanParams.type = orderType + if (operation === 'create_order') { + mapField('type', orderType) } - if (operation === 'amend_order' && countAmend) { - cleanParams.count = countAmend + if (operation === 'amend_order') { + mapField('count', countAmend) + mapField('clientOrderId', clientOrderIdAmend) } - if (operation === 'amend_order' && clientOrderIdAmend) { - cleanParams.clientOrderId = clientOrderIdAmend - } - - Object.entries(rest).forEach(([key, value]) => { - if (value !== undefined && value !== null && value !== '') { - cleanParams[key] = value - } - }) - return cleanParams }, }, diff --git a/apps/sim/blocks/blocks/ketch.test.ts b/apps/sim/blocks/blocks/ketch.test.ts new file mode 100644 index 00000000000..03c6dbaae40 --- /dev/null +++ b/apps/sim/blocks/blocks/ketch.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from 'vitest' +import { KetchBlock } from '@/blocks/blocks/ketch' + +const buildParams = KetchBlock.tools.config?.params +if (!buildParams) throw new Error('KetchBlock has no params mapper') + +describe('KetchBlock', () => { + /** + * An agent tool call passes the operation only in `context`; a purposes map the + * model sends as JSON text must reach the tool as an object, like the canvas sends it. + */ + it('parses a JSON-text purposes map on an agent tool call', () => { + const args = { + organizationCode: 'org', + propertyCode: 'web', + environmentCode: 'production', + identities: { email: 'a@example.com' }, + purposes: '{"analytics":{"allowed":"granted"}}', + } + + expect({ ...args, ...buildParams(args, { operation: 'set_consent' }) }.purposes).toEqual({ + analytics: { allowed: 'granted' }, + }) + }) +}) diff --git a/apps/sim/blocks/blocks/ketch.ts b/apps/sim/blocks/blocks/ketch.ts index 47baebd7da1..6601d23589d 100644 --- a/apps/sim/blocks/blocks/ketch.ts +++ b/apps/sim/blocks/blocks/ketch.ts @@ -1,6 +1,7 @@ import { KetchIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { IntegrationType } from '@/blocks/types' +import { mapperOperation } from '@/blocks/utils' export const KetchBlock: BlockConfig = { type: 'ketch', @@ -186,7 +187,8 @@ export const KetchBlock: BlockConfig = { ], config: { tool: (params) => `ketch_${params.operation}`, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const result: Record = { organizationCode: params.organizationCode, propertyCode: params.propertyCode, @@ -203,20 +205,20 @@ export const KetchBlock: BlockConfig = { : params.identities } - if (params.operation === 'get_consent' && params.purposesFilter) { + if (operation === 'get_consent' && params.purposesFilter) { result.purposes = typeof params.purposesFilter === 'string' ? JSON.parse(params.purposesFilter) : params.purposesFilter } - if (params.operation === 'set_consent' && params.purposes) { + if (operation === 'set_consent' && params.purposes) { result.purposes = typeof params.purposes === 'string' ? JSON.parse(params.purposes) : params.purposes if (params.collectedAt) result.collectedAt = Number(params.collectedAt) } - if (params.operation === 'set_subscriptions') { + if (operation === 'set_subscriptions') { if (params.topics) { result.topics = typeof params.topics === 'string' ? JSON.parse(params.topics) : params.topics @@ -227,7 +229,7 @@ export const KetchBlock: BlockConfig = { } } - if (params.operation === 'invoke_right') { + if (operation === 'invoke_right') { if (params.rightCode) result.rightCode = params.rightCode if (params.userData) { result.userData = diff --git a/apps/sim/blocks/blocks/knowledge.test.ts b/apps/sim/blocks/blocks/knowledge.test.ts new file mode 100644 index 00000000000..280384bffb9 --- /dev/null +++ b/apps/sim/blocks/blocks/knowledge.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from 'vitest' +import { KnowledgeBlock } from '@/blocks/blocks/knowledge' + +function mapToolCall(params: Record, operation: string) { + const mapper = KnowledgeBlock.tools.config?.params + if (!mapper) throw new Error('Knowledge block has no params mapper') + return mapper(params, { operation }) +} + +describe('Knowledge mapper on tool calls (operation only in context)', () => { + it('coerces a model-sent "false" to a boolean for update_chunk', () => { + const mapped = mapToolCall( + { knowledgeBaseId: 'kb-1', documentId: 'doc-1', chunkId: 'chunk-1', enabled: 'false' }, + 'update_chunk' + ) + + expect(mapped.enabled).toBe(false) + }) + + it('forwards the stored status filter and search for list_chunks', () => { + const mapped = mapToolCall( + { + knowledgeBaseId: 'kb-1', + documentId: 'doc-1', + chunkSearch: 'pricing', + chunkEnabledFilter: 'false', + }, + 'list_chunks' + ) + + expect(mapped).toMatchObject({ search: 'pricing', enabled: 'false' }) + }) + + it('keeps the model status filter when the stored row holds the default "all"', () => { + const mapped = mapToolCall( + { knowledgeBaseId: 'kb-1', documentId: 'doc-1', chunkEnabledFilter: 'all', enabled: 'true' }, + 'list_chunks' + ) + + expect(mapped.enabled).toBe('true') + }) + + it('sends the stored upsert document id as documentId', () => { + const mapped = mapToolCall( + { knowledgeBaseId: 'kb-1', upsertDocumentId: ' doc-9 ', name: 'Doc', content: 'Body' }, + 'upsert_document' + ) + + expect(mapped.documentId).toBe('doc-9') + }) +}) diff --git a/apps/sim/blocks/blocks/knowledge.ts b/apps/sim/blocks/blocks/knowledge.ts index 1c89a28c419..291988eddee 100644 --- a/apps/sim/blocks/blocks/knowledge.ts +++ b/apps/sim/blocks/blocks/knowledge.ts @@ -2,7 +2,7 @@ import { isPlainRecord } from '@sim/utils/object' import { PackageSearchIcon } from '@/components/icons' import { DEFAULT_RERANKER_MODEL, SUPPORTED_RERANKER_MODELS } from '@/lib/knowledge/reranker-models' import type { BlockConfig } from '@/blocks/types' -import { getCohereRerankerApiKeyCondition } from '@/blocks/utils' +import { getCohereRerankerApiKeyCondition, mapperOperation, toolCallArg } from '@/blocks/utils' /* * Canonical basic/advanced pairs, shared by the card sentences below. Listing @@ -448,8 +448,9 @@ export const KnowledgeBlock: BlockConfig = { return 'knowledge_search' } }, - params: (params) => { + params: (params, context) => { params = { ...params } + const operation = mapperOperation(params, context) const knowledgeBaseId = params.knowledgeBaseId ? String(params.knowledgeBaseId).trim() : '' if (!knowledgeBaseId) { throw new Error('Knowledge base ID is required') @@ -464,45 +465,53 @@ export const KnowledgeBlock: BlockConfig = { 'update_chunk', 'delete_chunk', ] - if (docOps.includes(params.operation)) { + if (docOps.includes(operation)) { const documentId = params.documentId ? String(params.documentId).trim() : '' if (!documentId) { - throw new Error(`Document ID is required for ${params.operation} operation`) + throw new Error(`Document ID is required for ${operation} operation`) } params.documentId = documentId } const chunkOps = ['update_chunk', 'delete_chunk'] - if (chunkOps.includes(params.operation)) { + if (chunkOps.includes(operation)) { const chunkId = params.chunkId ? String(params.chunkId).trim() : '' if (!chunkId) { - throw new Error(`Chunk ID is required for ${params.operation} operation`) + throw new Error(`Chunk ID is required for ${operation} operation`) } params.chunkId = chunkId } const connectorOps = ['get_connector', 'trigger_sync'] - if (connectorOps.includes(params.operation)) { + if (connectorOps.includes(operation)) { const connectorId = params.connectorId ? String(params.connectorId).trim() : '' if (!connectorId) { - throw new Error(`Connector ID is required for ${params.operation} operation`) + throw new Error(`Connector ID is required for ${operation} operation`) } params.connectorId = connectorId } // Map list_chunks sub-block fields to tool params - if (params.operation === 'list_chunks') { + if (operation === 'list_chunks') { if (params.chunkSearch) params.search = params.chunkSearch - if (params.chunkEnabledFilter) params.enabled = params.chunkEnabledFilter + if (params.chunkEnabledFilter) { + const modelEnabled = + params.chunkEnabledFilter === 'all' ? toolCallArg(context, params.enabled) : undefined + /* The tool takes a string; a model may send the boolean `false`, which must survive. */ + params.enabled = + modelEnabled === undefined || modelEnabled === null || modelEnabled === '' + ? params.chunkEnabledFilter + : String(modelEnabled) + } } // Map upsert sub-block field to tool param - if (params.operation === 'upsert_document' && params.upsertDocumentId) { + if (operation === 'upsert_document' && params.upsertDocumentId) { params.documentId = String(params.upsertDocumentId).trim() } if ( - (params.operation === 'create_document' || params.operation === 'upsert_document') && + (operation === 'create_document' || operation === 'upsert_document') && typeof params.documentTags === 'string' && params.documentTags.trim().length > 0 ) { @@ -515,7 +524,7 @@ export const KnowledgeBlock: BlockConfig = { } // Convert enabled dropdown string to boolean for update_chunk - if (params.operation === 'update_chunk' && typeof params.enabled === 'string') { + if (operation === 'update_chunk' && typeof params.enabled === 'string') { params.enabled = params.enabled === 'true' } diff --git a/apps/sim/blocks/blocks/lambda.test.ts b/apps/sim/blocks/blocks/lambda.test.ts index 2b6558ebb63..7ecf979d872 100644 --- a/apps/sim/blocks/blocks/lambda.test.ts +++ b/apps/sim/blocks/blocks/lambda.test.ts @@ -168,4 +168,22 @@ describe('LambdaBlock params mapping', () => { }) ).toThrow('filterPatterns must be a JSON array') }) + + it('maps an agent tool call, where the operation arrives only in the context', () => { + const modelArgs = { + ...CONNECTION, + functionName: 'alpha', + eventSourceArn: 'arn:aws:sqs:us-east-1:1:queue', + batchSize: '10', + filterPatterns: [{ body: { status: ['open'] } }], + } + + const mapped = toolConfig?.params?.(modelArgs, { + operation: 'create_event_source_mapping', + }) as Record + + expect(mapped.batchSize).toBe(10) + expect(mapped.filterPatterns).toEqual(['{"body":{"status":["open"]}}']) + expect(mapped.functionName).toBe('alpha') + }) }) diff --git a/apps/sim/blocks/blocks/lambda.ts b/apps/sim/blocks/blocks/lambda.ts index 1bebcaf688b..b5cadb0a155 100644 --- a/apps/sim/blocks/blocks/lambda.ts +++ b/apps/sim/blocks/blocks/lambda.ts @@ -2,7 +2,7 @@ import { getErrorMessage } from '@sim/utils/errors' import { LambdaIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, withSavedCredential } from '@/blocks/utils' type ParamKind = 'string' | 'number' | 'boolean' | 'json' | 'array' | 'jsonArray' @@ -1957,11 +1957,11 @@ export const LambdaBlock: BlockConfig = { } return `lambda_${operation}` }, - params: (params) => { - const operation = String(params.operation ?? '') + params: (params, context) => { + const operation = mapperOperation(params, context) const owned = OPERATION_PARAMS[operation] if (!owned) { - throw new Error(`Invalid Lambda operation: ${params.operation}`) + throw new Error(`Invalid Lambda operation: ${operation}`) } const ownedNames = new Set(owned) diff --git a/apps/sim/blocks/blocks/langsmith.test.ts b/apps/sim/blocks/blocks/langsmith.test.ts new file mode 100644 index 00000000000..9ae7ff9d66e --- /dev/null +++ b/apps/sim/blocks/blocks/langsmith.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from 'vitest' +import { LangsmithBlock } from '@/blocks/blocks/langsmith' + +const buildParams = LangsmithBlock.tools.config?.params +if (!buildParams) throw new Error('LangsmithBlock has no params mapper') + +describe('LangsmithBlock', () => { + /** + * The model names the create-run outputs after the tool's `run_outputs` param, not the + * block's `outputs` field; the mapper must not overwrite them with the empty field. + */ + it('keeps model run outputs on an agent create-run call', () => { + const args = { apiKey: 'key', name: 'run', run_type: 'chain', run_outputs: { answer: 42 } } + + expect( + { ...args, ...buildParams(args, { operation: 'langsmith_create_run' }) }.run_outputs + ).toEqual({ answer: 42 }) + }) +}) diff --git a/apps/sim/blocks/blocks/langsmith.ts b/apps/sim/blocks/blocks/langsmith.ts index ac7b3bbc4f9..2602e11e7e8 100644 --- a/apps/sim/blocks/blocks/langsmith.ts +++ b/apps/sim/blocks/blocks/langsmith.ts @@ -1,7 +1,7 @@ import { toError } from '@sim/utils/errors' import { LangsmithIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' export const LangsmithBlock: BlockConfig = { type: 'langsmith', @@ -315,7 +315,8 @@ Common patch fields: outputs, end_time, status, error`, ], config: { tool: (params) => params.operation, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const parseJsonValue = (value: unknown, label: string) => { if (value === undefined || value === null || value === '') { return undefined @@ -332,7 +333,7 @@ Common patch fields: outputs, end_time, status, error`, const emptyToUndefined = (value: unknown) => (value === '' ? undefined : value) - if (params.operation === 'langsmith_create_runs_batch') { + if (operation === 'langsmith_create_runs_batch') { const post = parseJsonValue(params.post, 'post runs') const patch = parseJsonValue(params.patch, 'patch runs') @@ -347,7 +348,7 @@ Common patch fields: outputs, end_time, status, error`, } } - if (params.operation === 'langsmith_update_run') { + if (operation === 'langsmith_update_run') { const name = emptyToUndefined(params.name) const end_time = emptyToUndefined(params.end_time) const outputs = parseJsonValue(params.outputs, 'outputs') @@ -379,14 +380,14 @@ Common patch fields: outputs, end_time, status, error`, } } - if (params.operation === 'langsmith_get_run') { + if (operation === 'langsmith_get_run') { return { apiKey: params.apiKey, runId: params.runId, } } - if (params.operation === 'langsmith_create_feedback') { + if (operation === 'langsmith_create_feedback') { const parseScore = (value: unknown) => { if (value === undefined || value === null || value === '') { return undefined @@ -418,7 +419,10 @@ Common patch fields: outputs, end_time, status, error`, start_time: params.start_time, end_time: params.end_time, inputs: parseJsonValue(params.inputs, 'inputs'), - run_outputs: parseJsonValue(params.outputs, 'outputs'), + run_outputs: parseJsonValue( + params.outputs || toolCallArg(context, params.run_outputs), + 'outputs' + ), extra: parseJsonValue(params.extra, 'metadata'), tags: parseJsonValue(params.tags, 'tags'), parent_run_id: params.parent_run_id, diff --git a/apps/sim/blocks/blocks/latex.test.ts b/apps/sim/blocks/blocks/latex.test.ts new file mode 100644 index 00000000000..19a05f57653 --- /dev/null +++ b/apps/sim/blocks/blocks/latex.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest' +import { LatexBlock } from '@/blocks/blocks/latex' + +const mapParams = LatexBlock.tools.config?.params +if (!mapParams) throw new Error('LatexBlock has no params mapper') + +describe('LatexBlock agent tool calls', () => { + it('forwards a search query typed into the tool row, which carries no operation in its params', () => { + expect( + mapParams({ packageQuery: 'chemistry' }, { operation: 'latex_search_packages' }) + ).toEqual({ query: 'chemistry' }) + }) + + it('keeps the model query and name when the tool row leaves the block fields blank', () => { + expect( + mapParams({ packageQuery: '', query: 'tikz' }, { operation: 'latex_search_packages' }) + ).toEqual({ query: 'tikz' }) + expect(mapParams({ name: ' amsmath ' }, { operation: 'latex_get_package' })).toEqual({ + name: 'amsmath', + }) + }) +}) diff --git a/apps/sim/blocks/blocks/latex.ts b/apps/sim/blocks/blocks/latex.ts index f47c343128a..323e29a92e3 100644 --- a/apps/sim/blocks/blocks/latex.ts +++ b/apps/sim/blocks/blocks/latex.ts @@ -1,6 +1,7 @@ import { LatexIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { IntegrationType } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' export const LatexBlock: BlockConfig = { type: 'latex', @@ -158,9 +159,9 @@ Return ONLY the JSON array - no explanations, no markdown, no extra text.`, return 'latex_compile' } }, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { - operation, compiler, fileName, resources, @@ -179,13 +180,14 @@ Return ONLY the JSON array - no explanations, no markdown, no extra text.`, if (operation === 'latex_search_packages') { return { - query: packageQuery, + query: toolCallArg(context, packageQuery || params.query) ?? packageQuery, ...maxResultsParam, } } if (operation === 'latex_get_package') { - const effectivePackageName = typeof packageName === 'string' ? packageName.trim() : '' + const requestedName = toolCallArg(context, packageName || params.name) ?? packageName + const effectivePackageName = typeof requestedName === 'string' ? requestedName.trim() : '' if (!effectivePackageName) { throw new Error('Package name is required.') } diff --git a/apps/sim/blocks/blocks/launchdarkly.test.ts b/apps/sim/blocks/blocks/launchdarkly.test.ts new file mode 100644 index 00000000000..ed3237145e0 --- /dev/null +++ b/apps/sim/blocks/blocks/launchdarkly.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest' +import { LaunchDarklyBlock } from '@/blocks/blocks/launchdarkly' + +type Params = Record + +const toolCall = (args: Params, operation: string): Params => + LaunchDarklyBlock.tools.config?.params?.(args as never, { operation }) as Params + +describe('LaunchDarkly agent tool calls', () => { + it('keeps the model name, key and boolean temporary flag on create_flag', () => { + const mapped = toolCall( + { projectKey: 'default', name: 'New checkout', key: 'new-checkout', temporary: true }, + 'create_flag' + ) + expect(mapped).toMatchObject({ name: 'New checkout', key: 'new-checkout', temporary: true }) + }) + + it('keeps a boolean archive on update_flag', () => { + expect( + toolCall({ projectKey: 'default', flagKey: 'old-flag', archive: true }, 'update_flag').archive + ).toBe(true) + }) +}) diff --git a/apps/sim/blocks/blocks/launchdarkly.ts b/apps/sim/blocks/blocks/launchdarkly.ts index 4c07a164470..30a888ad1f8 100644 --- a/apps/sim/blocks/blocks/launchdarkly.ts +++ b/apps/sim/blocks/blocks/launchdarkly.ts @@ -1,7 +1,7 @@ import { LaunchDarklyIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' export const LaunchDarklyBlock: BlockConfig = { type: 'launchdarkly', @@ -329,23 +329,24 @@ Return ONLY the resource specifier string - no explanations, no extra text.`, const operation = params.operation || 'list_flags' return `launchdarkly_${operation}` }, - params: (params) => { - const { operation, flagName, newFlagKey, ...rest } = params + params: (params, context) => { + const operation = mapperOperation(params, context) + const { flagName, newFlagKey, ...rest } = params if (operation === 'create_flag') { - rest.name = flagName - rest.key = newFlagKey + rest.name = flagName ?? toolCallArg(context, params.name) + rest.key = newFlagKey ?? toolCallArg(context, params.key) } if (operation === 'toggle_flag') { - rest.enabled = rest.enabled === 'true' + rest.enabled = rest.enabled === true || rest.enabled === 'true' } if (rest.temporary !== undefined) { - rest.temporary = rest.temporary === 'true' + rest.temporary = rest.temporary === true || rest.temporary === 'true' } - if (rest.archive !== undefined) { + if (rest.archive !== undefined && typeof rest.archive !== 'boolean') { if (rest.archive === 'true') rest.archive = true else if (rest.archive === 'false') rest.archive = false else rest.archive = undefined diff --git a/apps/sim/blocks/blocks/linear.test.ts b/apps/sim/blocks/blocks/linear.test.ts new file mode 100644 index 00000000000..69358e9834f --- /dev/null +++ b/apps/sim/blocks/blocks/linear.test.ts @@ -0,0 +1,138 @@ +import { describe, expect, it } from 'vitest' +import { LinearV2Block } from '@/blocks/blocks/linear' +import type { BlockToolParamsContext } from '@/blocks/types' + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = LinearV2Block.tools.config?.params + if (!mapper) throw new Error('Linear block has no params mapper') + return mapper(params, context) +} + +/** What the tool receives: the mapper's result spread over the params it was given. */ +function sent(params: Record, context?: BlockToolParamsContext) { + return { ...params, ...mapParams(params, context) } +} + +describe('Linear agent tool calls', () => { + it('uses the Customer ID filled in the tool row', () => { + const toolParams = sent({ customerIdTarget: 'cust-1' }, { operation: 'linear_get_customer' }) + expect(toolParams.customerId).toBe('cust-1') + }) + + it('keeps the model customer fields when no block field is filled', () => { + const toolParams = sent( + { name: 'Acme', domains: ['acme.com'], revenue: 5000, size: 40 }, + { operation: 'linear_create_customer' } + ) + expect(toolParams).toMatchObject({ + name: 'Acme', + domains: ['acme.com'], + revenue: 5000, + size: 40, + }) + }) + + it('keeps the model project and label ids for Add Label to Project', () => { + const toolParams = sent( + { projectId: 'proj-1', labelId: 'plabel-1' }, + { operation: 'linear_add_label_to_project' } + ) + expect(toolParams).toMatchObject({ projectId: 'proj-1', labelId: 'plabel-1' }) + }) + + it('keeps the model attachment title on Update Attachment', () => { + const toolParams = sent( + { attachmentId: 'att-1', title: 'Spec' }, + { operation: 'linear_update_attachment' } + ) + expect(toolParams.title).toBe('Spec') + }) + + it('keeps a model priority of 0 on Update Issue', () => { + const toolParams = sent({ issueId: 'ENG-1', priority: 0 }, { operation: 'linear_update_issue' }) + expect(toolParams.priority).toBe(0) + }) + + it('keeps the model readAt when the tool row leaves Mark as Read unset', () => { + const readAt = '2026-11-01T00:00:00.000Z' + const toolParams = sent( + { notificationId: 'n1', readAt }, + { operation: 'linear_update_notification' } + ) + expect(toolParams.readAt).toBe(readAt) + }) + + it('keeps the model includeArchived on List Customers', () => { + const toolParams = sent({ includeArchived: true }, { operation: 'linear_list_customers' }) + expect(toolParams.includeArchived).toBe(true) + }) +}) + +describe('Linear canvas requests', () => { + it('sends Blocked by as the related issue blocking this one', () => { + const inputs = { + operation: 'linear_create_issue_relation', + issueId: 'ENG-1', + relatedIssueId: 'ENG-2', + relationType: 'blocked', + } + expect(sent(inputs)).toMatchObject({ + issueId: 'ENG-2', + relatedIssueId: 'ENG-1', + type: 'blocks', + }) + }) + + it('sends the customer details filled on Create Customer', () => { + const inputs = { + operation: 'linear_create_customer', + customerName: 'Acme', + customerExternalIds: 'crm-1, crm-2', + customerOwnerId: ' user-1 ', + customerRevenue: '100000', + customerSize: '25', + customerLogoUrl: 'https://acme.test/logo.png', + } + expect(sent(inputs)).toMatchObject({ + name: 'Acme', + externalIds: ['crm-1', 'crm-2'], + ownerId: 'user-1', + revenue: 100000, + size: 25, + logoUrl: 'https://acme.test/logo.png', + }) + }) + + it('leaves the urgency unchanged when Update Customer Request picks No change', () => { + const inputs = { + operation: 'linear_update_customer_request', + customerNeedId: 'need-1', + customerRequestPriority: '', + } + expect(sent(inputs).priority).toBeUndefined() + }) + + it('sends Label IDs typed as a comma-separated list as an array', () => { + const inputs = { operation: 'linear_read_issues', labelIds: 'lbl-1, lbl-2' } + expect(sent(inputs).labelIds).toEqual(['lbl-1', 'lbl-2']) + }) + + it('moves an updated project to the chosen project status', () => { + const inputs = { + operation: 'linear_update_project', + projectId: 'proj-1', + projectUpdateStatusId: ' status-1 ', + } + expect(sent(inputs).statusId).toBe('status-1') + }) + + it('does not move an updated project to a Status ID left over from a project status operation', () => { + const inputs = { + operation: 'linear_update_project', + projectId: 'proj-1', + name: 'Renamed', + projectStatusId: 'ps-old', + } + expect(sent(inputs).statusId).toBeUndefined() + }) +}) diff --git a/apps/sim/blocks/blocks/linear.ts b/apps/sim/blocks/blocks/linear.ts index f4ba420bb27..731b5380c2a 100644 --- a/apps/sim/blocks/blocks/linear.ts +++ b/apps/sim/blocks/blocks/linear.ts @@ -2,7 +2,13 @@ import { DevinIcon, LinearIcon } 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, + parseOptionalBooleanInput, + toolCallArg, +} from '@/blocks/utils' import { getTrigger } from '@/triggers' /** @@ -13,6 +19,46 @@ import { getTrigger } from '@/triggers' const TEAM_FIELD = ['teamId', 'manualTeamId'] as const const PROJECT_FIELD = ['projectId', 'manualProjectId'] as const +/** True for a value a block field holds when nobody filled it. */ +function isBlank(value: unknown): boolean { + return value === undefined || value === null || (typeof value === 'string' && !value.trim()) +} + +/** A trimmed string from a block string or a model number; blank is `undefined`. */ +function trimmedText(value: unknown): string | undefined { + if (typeof value === 'string') return value.trim() || undefined + if (typeof value === 'number' && Number.isFinite(value)) return String(value) + return undefined +} + +/** A number from a block string or a model number; blank is `undefined`, so `0` survives. */ +function optionalNumber(value: unknown): number | undefined { + if (typeof value === 'number') return Number.isFinite(value) ? value : undefined + if (typeof value === 'string' && value.trim()) return Number(value) + return undefined +} + +/** Trimmed ids from a model array, a JSON array string, or a comma-separated block string. */ +function idList(value: unknown): string[] | undefined { + let items: unknown[] + if (Array.isArray(value)) { + items = value + } else if (typeof value === 'string' && value.trim()) { + const text = value.trim() + items = text.split(',') + if (text.startsWith('[')) { + try { + const parsed: unknown = JSON.parse(text) + if (Array.isArray(parsed)) items = parsed + } catch {} + } + } else { + return undefined + } + const ids = items.map(trimmedText).filter((id): id is string => id !== undefined) + return ids.length > 0 ? ids : undefined +} + export const LinearBlock: BlockConfig = { type: 'linear', name: 'Linear (Legacy)', @@ -318,7 +364,7 @@ export const LinearBlock: BlockConfig = { { text: 'Update project status', field: 'projectStatusId', core: true }, ], linear_delete_project_status: [ - { text: 'Delete project status', field: 'projectStatusId', core: true }, + { text: 'Archive project status', field: 'projectStatusId', core: true }, ], linear_list_project_statuses: [ 'List project statuses', @@ -364,7 +410,7 @@ export const LinearBlock: BlockConfig = { { label: 'Update Workflow State', id: 'linear_update_workflow_state' }, { label: 'List Cycles', id: 'linear_list_cycles' }, { label: 'Get Cycle', id: 'linear_get_cycle' }, - { label: 'Create Cycle', id: 'linear_create_cycle' }, + { label: 'Create Cycle', id: 'linear_create_cycle', hidden: true }, { label: 'Get Active Cycle', id: 'linear_get_active_cycle' }, { label: 'Create Attachment', id: 'linear_create_attachment' }, { label: 'List Attachments', id: 'linear_list_attachments' }, @@ -409,7 +455,7 @@ export const LinearBlock: BlockConfig = { { label: 'List Project Milestones', id: 'linear_list_project_milestones' }, { label: 'Create Project Status', id: 'linear_create_project_status' }, { label: 'Update Project Status', id: 'linear_update_project_status' }, - { label: 'Delete Project Status', id: 'linear_delete_project_status' }, + { label: 'Archive Project Status', id: 'linear_delete_project_status' }, { label: 'List Project Statuses', id: 'linear_list_project_statuses' }, ], value: () => 'linear_read_issues', @@ -610,7 +656,7 @@ export const LinearBlock: BlockConfig = { title: 'Title', type: 'short-input', placeholder: 'Enter issue title', - required: true, + required: { field: 'operation', value: 'linear_create_issue' }, condition: { field: 'operation', value: ['linear_create_issue', 'linear_update_issue'], @@ -733,6 +779,7 @@ Return ONLY the comment text - no explanations.`, title: 'Color (hex)', type: 'short-input', placeholder: '#5E6AD2', + required: { field: 'operation', value: 'linear_create_workflow_state' }, condition: { field: 'operation', value: [ @@ -767,14 +814,20 @@ Return ONLY the comment text - no explanations.`, id: 'priority', title: 'Priority', type: 'dropdown', - options: [ + options: (params) => [ + { + label: params?.values.operation === 'linear_update_issue' ? 'No change' : 'Default', + id: '', + }, { label: 'No Priority', id: '0' }, { label: 'Urgent', id: '1' }, { label: 'High', id: '2' }, { label: 'Normal', id: '3' }, { label: 'Low', id: '4' }, ], - value: () => '0', + value: (params) => + params?.operation === 'linear_update_issue' ? '' : params?.operation ? '0' : undefined, + dependsOn: ['operation'], condition: { field: 'operation', value: ['linear_create_issue', 'linear_update_issue', 'linear_create_project'], @@ -819,7 +872,13 @@ Return ONLY the search query - no explanations.`, type: 'switch', condition: { field: 'operation', - value: ['linear_read_issues', 'linear_search_issues', 'linear_list_projects'], + value: [ + 'linear_read_issues', + 'linear_search_issues', + 'linear_list_projects', + 'linear_list_customers', + 'linear_list_customer_requests', + ], }, }, { @@ -1216,7 +1275,7 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n title: 'Customer Name', type: 'short-input', placeholder: 'Enter customer name', - required: true, + required: { field: 'operation', value: 'linear_create_customer' }, condition: { field: 'operation', value: ['linear_create_customer', 'linear_update_customer'], @@ -1330,11 +1389,22 @@ Return ONLY the description text - no explanations.`, id: 'customerRequestPriority', title: 'Urgency', type: 'dropdown', - options: [ + options: (params) => [ + { + label: + params?.values.operation === 'linear_update_customer_request' ? 'No change' : 'Default', + id: '', + }, { label: 'Not Important (0)', id: '0' }, { label: 'Important (1)', id: '1' }, ], - value: () => '0', + value: (params) => + params?.operation === 'linear_update_customer_request' + ? '' + : params?.operation + ? '0' + : undefined, + dependsOn: ['operation'], condition: { field: 'operation', value: ['linear_create_customer_request', 'linear_update_customer_request'], @@ -1345,6 +1415,7 @@ Return ONLY the description text - no explanations.`, title: 'Link to Issue', type: 'short-input', placeholder: 'Enter issue ID to link', + required: { field: 'operation', value: 'linear_create_customer_request' }, condition: { field: 'operation', value: ['linear_create_customer_request', 'linear_update_customer_request'], @@ -1399,7 +1470,14 @@ Return ONLY the description text - no explanations.`, title: 'Status Color', type: 'short-input', placeholder: 'Enter hex color (e.g., #FF0000)', - required: true, + required: { + field: 'operation', + value: [ + 'linear_create_customer_status', + 'linear_create_customer_tier', + 'linear_create_project_status', + ], + }, condition: { field: 'operation', value: [ @@ -1578,7 +1656,7 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n { label: 'Backlog', id: 'backlog' }, { label: 'Planned', id: 'planned' }, { label: 'Started', id: 'started' }, - { label: 'Paused', id: 'paused' }, + { label: 'Paused (deprecated)', id: 'paused', hidden: true }, { label: 'Completed', id: 'completed' }, { label: 'Canceled', id: 'canceled' }, ], @@ -1611,6 +1689,16 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n value: ['linear_update_project_status', 'linear_delete_project_status'], }, }, + { + id: 'projectUpdateStatusId', + title: 'Status ID', + type: 'short-input', + placeholder: 'Enter project status ID to move the project to', + condition: { + field: 'operation', + value: 'linear_update_project', + }, + }, { id: 'projectStatusIndefinite', title: 'Can Stay Indefinitely', @@ -1742,22 +1830,41 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n tool: (params) => { return params.operation || 'linear_read_issues' }, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) // Use canonical param IDs (raw subBlock IDs are deleted after serialization) const effectiveTeamId = params.teamId ? String(params.teamId).trim() : '' const effectiveProjectId = params.projectId ? String(params.projectId).trim() : '' + /** + * The block-only field when it is filled. On a tool call the model fills the tool's own + * param instead, so a blank block field falls back to it; the canvas keeps the field as is. + */ + const fieldOr = (blockValue: unknown, toolValue: unknown): unknown => + isBlank(blockValue) && isToolCall(context) ? toolValue : blockValue + const baseParams: Record = { oauthCredential: params.oauthCredential, } - switch (params.operation) { + const customerDetails = () => ({ + domains: idList(params.customerDomains) ?? toolCallArg(context, idList(params.domains)), + externalIds: + idList(params.customerExternalIds) ?? toolCallArg(context, idList(params.externalIds)), + logoUrl: trimmedText(fieldOr(params.customerLogoUrl, params.logoUrl)), + ownerId: trimmedText(fieldOr(params.customerOwnerId, params.ownerId)), + revenue: optionalNumber(fieldOr(params.customerRevenue, params.revenue)), + size: optionalNumber(fieldOr(params.customerSize, params.size)), + }) + + switch (operation) { case 'linear_read_issues': return { ...baseParams, teamId: effectiveTeamId || undefined, projectId: effectiveProjectId || undefined, includeArchived: params.includeArchived, + labelIds: idList(params.labelIds), first: params.first ? Number(params.first) : undefined, after: params.after?.trim() || undefined, } @@ -1786,8 +1893,8 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n description: params.description, stateId: params.stateId, assigneeId: params.assigneeId, - priority: params.priority ? Number(params.priority) : undefined, - estimate: params.estimate ? Number(params.estimate) : undefined, + priority: optionalNumber(params.priority), + estimate: optionalNumber(params.estimate), } case 'linear_update_issue': @@ -1801,8 +1908,8 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n description: params.description, stateId: params.stateId, assigneeId: params.assigneeId, - priority: params.priority ? Number(params.priority) : undefined, - estimate: params.estimate ? Number(params.estimate) : undefined, + priority: optionalNumber(params.priority), + estimate: optionalNumber(params.estimate), } case 'linear_archive_issue': @@ -1910,7 +2017,7 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n leadId: params.leadId, startDate: params.startDate, targetDate: params.targetDate, - priority: params.priority ? Number(params.priority) : undefined, + priority: optionalNumber(params.priority), } case 'linear_update_project': @@ -1922,7 +2029,8 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n projectId: effectiveProjectId, name: params.name, description: params.description, - state: params.projectState, + state: fieldOr(params.projectState, params.state), + statusId: trimmedText(fieldOr(params.projectUpdateStatusId, params.statusId)), leadId: params.leadId, targetDate: params.targetDate, } @@ -1994,17 +2102,19 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n after: params.after?.trim() || undefined, } - case 'linear_create_workflow_state': - if (!effectiveTeamId || !params.name?.trim() || !params.workflowType) { + case 'linear_create_workflow_state': { + const workflowType = fieldOr(params.workflowType, params.type) + if (!effectiveTeamId || !params.name?.trim() || !workflowType) { throw new Error('Team ID, name, and workflow type are required.') } return { ...baseParams, teamId: effectiveTeamId, name: params.name.trim(), - type: params.workflowType, + type: workflowType, color: params.color?.trim() || undefined, } + } case 'linear_update_workflow_state': if (!params.stateId?.trim()) { @@ -2034,17 +2144,20 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n cycleId: params.cycleId.trim(), } - case 'linear_create_cycle': - if (!effectiveTeamId || !params.startDate?.trim() || !params.endDate?.trim()) { + case 'linear_create_cycle': { + const startsAt = trimmedText(fieldOr(params.startDate, params.startsAt)) + const endsAt = trimmedText(fieldOr(params.endDate, params.endsAt)) + if (!effectiveTeamId || !startsAt || !endsAt) { throw new Error('Team ID, start date, and end date are required.') } return { ...baseParams, teamId: effectiveTeamId, name: params.name?.trim() || undefined, - startsAt: params.startDate.trim(), - endsAt: params.endDate.trim(), + startsAt, + endsAt, } + } case 'linear_get_active_cycle': if (!effectiveTeamId) { @@ -2067,7 +2180,8 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n const attachmentUrl = params.url?.trim() || (attachmentFile ? (attachmentFile as { url?: string }).url : undefined) - if (!attachmentUrl) { + // A tool call hands over a file reference the executor resolves to a URL later. + if (!attachmentUrl && !(isToolCall(context) && attachmentFile)) { throw new Error('URL or file is required.') } return { @@ -2075,7 +2189,7 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n issueId: params.issueId.trim(), url: attachmentUrl, file: attachmentFile, - title: params.attachmentTitle, + title: fieldOr(params.attachmentTitle, params.title), } } @@ -2097,7 +2211,7 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n return { ...baseParams, attachmentId: params.attachmentId.trim(), - title: params.attachmentTitle, + title: fieldOr(params.attachmentTitle, params.title), } case 'linear_delete_attachment': @@ -2109,16 +2223,29 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n attachmentId: params.attachmentId.trim(), } - case 'linear_create_issue_relation': - if (!params.issueId?.trim() || !params.relatedIssueId?.trim() || !params.relationType) { + case 'linear_create_issue_relation': { + const relationType = fieldOr(params.relationType, params.type) + if (!params.issueId?.trim() || !params.relatedIssueId?.trim() || !relationType) { throw new Error('Issue ID, related issue ID, and relation type are required.') } + const issueId = params.issueId.trim() + const relatedIssueId = params.relatedIssueId.trim() + // Linear has no "blocked by" type: A blocked by B is stored as B blocks A. + if (relationType === 'blocked') { + return { + ...baseParams, + issueId: relatedIssueId, + relatedIssueId: issueId, + type: 'blocks', + } + } return { ...baseParams, - issueId: params.issueId.trim(), - relatedIssueId: params.relatedIssueId.trim(), - type: params.relationType, + issueId, + relatedIssueId, + type: relationType, } + } case 'linear_list_issue_relations': if (!params.issueId?.trim()) { @@ -2142,6 +2269,8 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n case 'linear_create_favorite': if (!params.favoriteTargetId?.trim() || !params.favoriteType) { + // A tool call names the target with the tool's own issueId/projectId/cycleId/labelId. + if (isToolCall(context)) return baseParams throw new Error('Target ID and favorite type are required.') } return { @@ -2190,50 +2319,55 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n if (!params.notificationId?.trim()) { throw new Error('Notification ID is required.') } + // On a tool call with no Mark as Read setting, the model's readAt decides. + if (isToolCall(context) && isBlank(params.markAsRead)) { + return { ...baseParams, notificationId: params.notificationId.trim() } + } return { ...baseParams, notificationId: params.notificationId.trim(), readAt: params.markAsRead ? new Date().toISOString() : null, } - case 'linear_create_customer': - if (!params.customerName?.trim()) { + case 'linear_create_customer': { + const name = trimmedText(fieldOr(params.customerName, params.name)) + if (!name) { throw new Error('Customer name is required.') } return { ...baseParams, - name: params.customerName.trim(), - domains: params.customerDomains - ? params.customerDomains - .split(',') - .map((d: string) => d.trim()) - .filter(Boolean) - : undefined, + name, + ...customerDetails(), } + } case 'linear_list_customers': return { ...baseParams, first: params.first ? Number(params.first) : undefined, after: params.after?.trim() || undefined, - includeArchived: false, + includeArchived: params.includeArchived ?? false, } - case 'linear_create_customer_request': + case 'linear_create_customer_request': { + const issueId = trimmedText(fieldOr(params.linkedIssueId, params.issueId)) if (!params.customerId?.trim()) { throw new Error('Customer ID is required.') } + if (!issueId) { + throw new Error( + 'Link to Issue is required: Linear needs an issue for every customer request created through its API.' + ) + } return { ...baseParams, customerId: params.customerId.trim(), - body: params.requestBody?.trim(), + body: trimmedText(fieldOr(params.requestBody, params.body)), priority: - params.customerRequestPriority !== undefined - ? Number(params.customerRequestPriority) - : 0, - issueId: params.linkedIssueId?.trim(), - projectId: effectiveProjectId || undefined, + optionalNumber(fieldOr(params.customerRequestPriority, params.priority)) ?? 0, + issueId, } + } case 'linear_update_customer_request': if (!params.customerNeedId?.trim()) { @@ -2243,13 +2377,9 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n ...baseParams, customerNeedId: params.customerNeedId.trim(), customerId: params.customerId?.trim(), - body: params.requestBody?.trim(), - priority: - params.customerRequestPriority !== undefined - ? Number(params.customerRequestPriority) - : undefined, - issueId: params.linkedIssueId?.trim(), - projectId: effectiveProjectId || undefined, + body: trimmedText(fieldOr(params.requestBody, params.body)), + priority: optionalNumber(fieldOr(params.customerRequestPriority, params.priority)), + issueId: trimmedText(fieldOr(params.linkedIssueId, params.issueId)), } case 'linear_list_customer_requests': @@ -2257,48 +2387,35 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n ...baseParams, first: params.first ? Number(params.first) : undefined, after: params.after?.trim() || undefined, - includeArchived: false, + includeArchived: params.includeArchived ?? false, } case 'linear_get_customer': - if (!params.customerIdTarget?.trim()) { + case 'linear_delete_customer': { + const customerId = trimmedText(fieldOr(params.customerIdTarget, params.customerId)) + if (!customerId) { throw new Error('Customer ID is required.') } return { ...baseParams, - customerId: params.customerIdTarget.trim(), + customerId, } + } - case 'linear_update_customer': - if (!params.customerIdTarget?.trim()) { + case 'linear_update_customer': { + const customerId = trimmedText(fieldOr(params.customerIdTarget, params.customerId)) + if (!customerId) { throw new Error('Customer ID is required.') } return { ...baseParams, - customerId: params.customerIdTarget.trim(), - name: params.customerName?.trim() || undefined, - domains: params.customerDomains?.trim() - ? params.customerDomains.split(',').map((d: string) => d.trim()) - : undefined, - externalIds: params.customerExternalIds?.trim() - ? params.customerExternalIds.split(',').map((id: string) => id.trim()) - : undefined, - logoUrl: params.customerLogoUrl?.trim() || undefined, - ownerId: params.customerOwnerId?.trim() || undefined, - revenue: params.customerRevenue ? Number(params.customerRevenue) : undefined, - size: params.customerSize ? Number(params.customerSize) : undefined, + customerId, + name: trimmedText(fieldOr(params.customerName, params.name)), + ...customerDetails(), statusId: params.statusId?.trim() || undefined, tierId: params.tierId?.trim() || undefined, } - - case 'linear_delete_customer': - if (!params.customerIdTarget?.trim()) { - throw new Error('Customer ID is required.') - } - return { - ...baseParams, - customerId: params.customerIdTarget.trim(), - } + } case 'linear_merge_customers': if (!params.sourceCustomerId?.trim() || !params.targetCustomerId?.trim()) { @@ -2310,17 +2427,20 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n targetCustomerId: params.targetCustomerId.trim(), } - case 'linear_create_customer_status': - if (!params.statusName?.trim() || !params.statusColor?.trim()) { + case 'linear_create_customer_status': { + const name = trimmedText(fieldOr(params.statusName, params.name)) + const color = trimmedText(fieldOr(params.statusColor, params.color)) + if (!name || !color) { throw new Error('Status name and color are required.') } return { ...baseParams, - name: params.statusName.trim(), - color: params.statusColor.trim(), - description: params.statusDescription?.trim() || undefined, - displayName: params.statusDisplayName?.trim() || undefined, + name, + color, + description: trimmedText(fieldOr(params.statusDescription, params.description)), + displayName: trimmedText(fieldOr(params.statusDisplayName, params.displayName)), } + } case 'linear_update_customer_status': if (!params.statusId?.trim()) { @@ -2329,10 +2449,10 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n return { ...baseParams, statusId: params.statusId.trim(), - name: params.statusName?.trim() || undefined, - color: params.statusColor?.trim() || undefined, - description: params.statusDescription?.trim() || undefined, - displayName: params.statusDisplayName?.trim() || undefined, + name: trimmedText(fieldOr(params.statusName, params.name)), + color: trimmedText(fieldOr(params.statusColor, params.color)), + description: trimmedText(fieldOr(params.statusDescription, params.description)), + displayName: trimmedText(fieldOr(params.statusDisplayName, params.displayName)), } case 'linear_delete_customer_status': @@ -2351,17 +2471,20 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n after: params.after?.trim() || undefined, } - case 'linear_create_customer_tier': - if (!params.tierName?.trim() || !params.statusColor?.trim()) { + case 'linear_create_customer_tier': { + const name = trimmedText(fieldOr(params.tierName, params.name)) + const color = trimmedText(fieldOr(params.statusColor, params.color)) + if (!name || !color) { throw new Error('Tier name and color are required.') } return { ...baseParams, - name: params.tierName.trim(), - displayName: params.tierDisplayName?.trim() || params.tierName.trim(), - color: params.statusColor.trim(), - description: params.tierDescription?.trim() || undefined, + name, + displayName: trimmedText(fieldOr(params.tierDisplayName, params.displayName)) || name, + color, + description: trimmedText(fieldOr(params.tierDescription, params.description)), } + } case 'linear_update_customer_tier': if (!params.tierId?.trim()) { @@ -2370,10 +2493,10 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n return { ...baseParams, tierId: params.tierId.trim(), - name: params.tierName?.trim() || undefined, - displayName: params.tierDisplayName?.trim() || undefined, - color: params.statusColor?.trim() || undefined, - description: params.tierDescription?.trim() || undefined, + name: trimmedText(fieldOr(params.tierName, params.name)), + displayName: trimmedText(fieldOr(params.tierDisplayName, params.displayName)), + color: trimmedText(fieldOr(params.statusColor, params.color)), + description: trimmedText(fieldOr(params.tierDescription, params.description)), } case 'linear_delete_customer_tier': @@ -2401,39 +2524,47 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n projectId: effectiveProjectId, } - case 'linear_create_project_label': - if (!params.projectLabelName?.trim()) { + case 'linear_create_project_label': { + const name = trimmedText(fieldOr(params.projectLabelName, params.name)) + if (!name) { throw new Error('Project label name is required.') } return { ...baseParams, - name: params.projectLabelName.trim(), - description: params.projectLabelDescription?.trim() || undefined, - color: params.statusColor?.trim() || undefined, - isGroup: params.projectLabelIsGroup === 'true', - parentId: params.projectLabelParentId?.trim() || undefined, + name, + description: trimmedText(fieldOr(params.projectLabelDescription, params.description)), + color: trimmedText(fieldOr(params.statusColor, params.color)), + isGroup: isBlank(params.projectLabelIsGroup) + ? (parseOptionalBooleanInput(toolCallArg(context, params.isGroup)) ?? false) + : params.projectLabelIsGroup === 'true', + parentId: trimmedText(fieldOr(params.projectLabelParentId, params.parentId)), } + } - case 'linear_update_project_label': - if (!params.projectLabelId?.trim()) { + case 'linear_update_project_label': { + const labelId = trimmedText(fieldOr(params.projectLabelId, params.labelId)) + if (!labelId) { throw new Error('Project label ID is required.') } return { ...baseParams, - labelId: params.projectLabelId.trim(), - name: params.projectLabelName?.trim() || undefined, - description: params.projectLabelDescription?.trim() || undefined, - color: params.statusColor?.trim() || undefined, + labelId, + name: trimmedText(fieldOr(params.projectLabelName, params.name)), + description: trimmedText(fieldOr(params.projectLabelDescription, params.description)), + color: trimmedText(fieldOr(params.statusColor, params.color)), } + } - case 'linear_delete_project_label': - if (!params.projectLabelId?.trim()) { + case 'linear_delete_project_label': { + const labelId = trimmedText(fieldOr(params.projectLabelId, params.labelId)) + if (!labelId) { throw new Error('Project label ID is required.') } return { ...baseParams, - labelId: params.projectLabelId.trim(), + labelId, } + } case 'linear_list_project_labels': return { @@ -2444,36 +2575,33 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n } case 'linear_add_label_to_project': - if (!params.projectIdForMilestone?.trim() || !params.projectLabelId?.trim()) { - throw new Error('Project ID and label ID are required.') - } - return { - ...baseParams, - projectId: params.projectIdForMilestone.trim(), - labelId: params.projectLabelId.trim(), - } - - case 'linear_remove_label_from_project': - if (!params.projectIdForMilestone?.trim() || !params.projectLabelId?.trim()) { + case 'linear_remove_label_from_project': { + const projectId = trimmedText(fieldOr(params.projectIdForMilestone, params.projectId)) + const labelId = trimmedText(fieldOr(params.projectLabelId, params.labelId)) + if (!projectId || !labelId) { throw new Error('Project ID and label ID are required.') } return { ...baseParams, - projectId: params.projectIdForMilestone.trim(), - labelId: params.projectLabelId.trim(), + projectId, + labelId, } + } - case 'linear_create_project_milestone': - if (!params.projectIdForMilestone?.trim() || !params.milestoneName?.trim()) { + case 'linear_create_project_milestone': { + const projectId = trimmedText(fieldOr(params.projectIdForMilestone, params.projectId)) + const name = trimmedText(fieldOr(params.milestoneName, params.name)) + if (!projectId || !name) { throw new Error('Project ID and milestone name are required.') } return { ...baseParams, - projectId: params.projectIdForMilestone.trim(), - name: params.milestoneName.trim(), - description: params.milestoneDescription?.trim() || undefined, - targetDate: params.milestoneTargetDate?.trim() || undefined, + projectId, + name, + description: trimmedText(fieldOr(params.milestoneDescription, params.description)), + targetDate: trimmedText(fieldOr(params.milestoneTargetDate, params.targetDate)), } + } case 'linear_update_project_milestone': if (!params.milestoneId?.trim()) { @@ -2482,9 +2610,9 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n return { ...baseParams, milestoneId: params.milestoneId.trim(), - name: params.milestoneName?.trim() || undefined, - description: params.milestoneDescription?.trim() || undefined, - targetDate: params.milestoneTargetDate?.trim() || undefined, + name: trimmedText(fieldOr(params.milestoneName, params.name)), + description: trimmedText(fieldOr(params.milestoneDescription, params.description)), + targetDate: trimmedText(fieldOr(params.milestoneTargetDate, params.targetDate)), } case 'linear_delete_project_milestone': @@ -2496,59 +2624,77 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n milestoneId: params.milestoneId.trim(), } - case 'linear_list_project_milestones': - if (!params.projectIdForMilestone?.trim()) { + case 'linear_list_project_milestones': { + const projectId = trimmedText(fieldOr(params.projectIdForMilestone, params.projectId)) + if (!projectId) { throw new Error('Project ID is required.') } return { ...baseParams, - projectId: params.projectIdForMilestone.trim(), + projectId, first: params.first ? Number(params.first) : undefined, after: params.after?.trim() || undefined, } + } - case 'linear_create_project_status': - if ( - !params.projectStatusName?.trim() || - !params.projectStatusType?.trim() || - !params.statusColor?.trim() || - !params.projectStatusPosition?.trim() - ) { + case 'linear_create_project_status': { + const name = trimmedText(fieldOr(params.projectStatusName, params.name)) + const type = trimmedText(fieldOr(params.projectStatusType, params.type)) + const color = trimmedText(fieldOr(params.statusColor, params.color)) + const positionInput = fieldOr(params.projectStatusPosition, params.position) + const position = + typeof positionInput === 'number' + ? positionInput + : typeof positionInput === 'string' && positionInput.trim() + ? Number.parseFloat(positionInput.trim()) + : undefined + if (!name || !type || !color || position === undefined) { throw new Error('Project status name, type, color, and position are required.') } return { ...baseParams, - name: params.projectStatusName.trim(), - type: params.projectStatusType.trim(), - color: params.statusColor.trim(), - position: Number.parseFloat(params.projectStatusPosition.trim()), - description: params.projectStatusDescription?.trim() || undefined, - indefinite: params.projectStatusIndefinite === 'true', + name, + type, + color, + position, + description: trimmedText( + fieldOr(params.projectStatusDescription, params.description) + ), + indefinite: isBlank(params.projectStatusIndefinite) + ? (parseOptionalBooleanInput(toolCallArg(context, params.indefinite)) ?? false) + : params.projectStatusIndefinite === 'true', } + } - case 'linear_update_project_status': - if (!params.projectStatusId?.trim()) { + case 'linear_update_project_status': { + const statusId = trimmedText(fieldOr(params.projectStatusId, params.statusId)) + if (!statusId) { throw new Error('Project status ID is required.') } return { ...baseParams, - statusId: params.projectStatusId.trim(), - name: params.projectStatusName?.trim() || undefined, - color: params.statusColor?.trim() || undefined, - description: params.projectStatusDescription?.trim() || undefined, + statusId, + name: trimmedText(fieldOr(params.projectStatusName, params.name)), + color: trimmedText(fieldOr(params.statusColor, params.color)), + description: trimmedText( + fieldOr(params.projectStatusDescription, params.description) + ), indefinite: params.projectStatusIndefinite ? params.projectStatusIndefinite === 'true' - : undefined, + : parseOptionalBooleanInput(toolCallArg(context, params.indefinite)), } + } - case 'linear_delete_project_status': - if (!params.projectStatusId?.trim()) { + case 'linear_delete_project_status': { + const statusId = trimmedText(fieldOr(params.projectStatusId, params.statusId)) + if (!statusId) { throw new Error('Project status ID is required.') } return { ...baseParams, - statusId: params.projectStatusId.trim(), + statusId, } + } case 'linear_list_project_statuses': return { @@ -2651,6 +2797,10 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n milestoneDescription: { type: 'string', description: 'Milestone description' }, milestoneTargetDate: { type: 'string', description: 'Milestone target date (YYYY-MM-DD)' }, projectStatusId: { type: 'string', description: 'Project status identifier' }, + projectUpdateStatusId: { + type: 'string', + description: 'Project status ID to move the project to on Update Project', + }, projectStatusName: { type: 'string', description: 'Project status name' }, projectStatusDescription: { type: 'string', description: 'Project status description' }, projectStatusIndefinite: { diff --git a/apps/sim/blocks/blocks/linkedin.ts b/apps/sim/blocks/blocks/linkedin.ts index 55ea31c45a0..5d0498b3bf4 100644 --- a/apps/sim/blocks/blocks/linkedin.ts +++ b/apps/sim/blocks/blocks/linkedin.ts @@ -2,6 +2,7 @@ import { LinkedInIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation } from '@/blocks/utils' export const LinkedInBlock: BlockConfig = { type: 'linkedin', @@ -103,8 +104,8 @@ export const LinkedInBlock: BlockConfig = { return 'linkedin_share_post' }, - params: (inputs) => { - const operation = inputs.operation || 'share_post' + params: (inputs, context) => { + const operation = mapperOperation(inputs, context) || 'share_post' const { oauthCredential, ...rest } = inputs if (operation === 'get_profile') { diff --git a/apps/sim/blocks/blocks/linq.test.ts b/apps/sim/blocks/blocks/linq.test.ts new file mode 100644 index 00000000000..42604b97870 --- /dev/null +++ b/apps/sim/blocks/blocks/linq.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest' +import { LinqBlock } from '@/blocks/blocks/linq' + +type Params = Record + +const toolCall = (args: Params, operation: string): Params => + LinqBlock.tools.config?.params?.(args as never, { operation }) as Params + +describe('Linq agent tool calls', () => { + it('unwraps a single picked file on create_attachment', () => { + const file = { + id: 'f1', + name: 'card.png', + key: 'workspace/ws/card.png', + size: 10, + type: 'image/png', + } + expect(toolCall({ file: [file] }, 'create_attachment').file).toEqual(file) + }) +}) diff --git a/apps/sim/blocks/blocks/linq.ts b/apps/sim/blocks/blocks/linq.ts index 50f58eaf7ba..b9072c5d099 100644 --- a/apps/sim/blocks/blocks/linq.ts +++ b/apps/sim/blocks/blocks/linq.ts @@ -1,7 +1,7 @@ import { LinqIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput, withSavedCredential } from '@/blocks/utils' +import { mapperOperation, normalizeFileInput, withSavedCredential } from '@/blocks/utils' import { getTrigger } from '@/triggers' const CHAT_ID_OPS = [ @@ -781,9 +781,9 @@ export const LinqBlock: BlockConfig = { ], config: { tool: (params) => `linq_${params.operation || 'send_message'}`, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { - operation, senderFrom, recipients, messageText, @@ -881,7 +881,6 @@ export const LinqBlock: BlockConfig = { } if (operation === 'react_to_message') { - if (reactionOperation) rest.operation = reactionOperation if (reactionType) rest.type = reactionType if (reactionCustomEmoji) rest.customEmoji = reactionCustomEmoji if (reactionPartIndex !== undefined && reactionPartIndex !== '') { @@ -940,6 +939,11 @@ export const LinqBlock: BlockConfig = { rest.limit = toFiniteNumber(limit, 'Limit') } + // The react tool declares its own `operation` param: add or remove. + if (operation === 'react_to_message' && reactionOperation) { + return { ...rest, operation: reactionOperation } + } + return rest }, }, diff --git a/apps/sim/blocks/blocks/logfire.ts b/apps/sim/blocks/blocks/logfire.ts index 7c651b997ab..afe1544209a 100644 --- a/apps/sim/blocks/blocks/logfire.ts +++ b/apps/sim/blocks/blocks/logfire.ts @@ -2,7 +2,7 @@ import { Bug, ClipboardList, Clock, Database, File, Search, Server } from '@sim/ import { LogfireIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, withSavedCredential } from '@/blocks/utils' const toBoolean = (value: unknown): boolean | undefined => { if (value === true || value === 'true') return true @@ -311,7 +311,7 @@ Return ONLY the IANA timezone string - no explanations or quotes.`, ], config: { tool: (params) => String(params.operation || 'logfire_search_records'), - params: (params) => { + params: (params, context) => { const baseParams = { apiKey: params.apiKey, region: params.region || 'auto', @@ -324,7 +324,7 @@ Return ONLY the IANA timezone string - no explanations or quotes.`, limit: toNumber(params.limit), } - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'logfire_query': return { ...baseParams, diff --git a/apps/sim/blocks/blocks/logrocket.ts b/apps/sim/blocks/blocks/logrocket.ts index 462782e64c5..1f48f274aef 100644 --- a/apps/sim/blocks/blocks/logrocket.ts +++ b/apps/sim/blocks/blocks/logrocket.ts @@ -1,5 +1,6 @@ import { LogRocketIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' +import { mapperOperation } from '@/blocks/utils' /** * A highlights request identifies its subject by email or user ID — either one @@ -286,10 +287,10 @@ export const LogRocketBlock: BlockConfig = { ], config: { tool: (params) => `logrocket_${params.operation}`, - params: (params) => { + params: (params, context) => { const result: Record = {} - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'request_highlights': if (params.highlightsUserEmail) result.userEmail = params.highlightsUserEmail if (params.highlightsUserId) result.userID = params.highlightsUserId diff --git a/apps/sim/blocks/blocks/logs.test.ts b/apps/sim/blocks/blocks/logs.test.ts index 3ecfb864333..44b0c1cf5a9 100644 --- a/apps/sim/blocks/blocks/logs.test.ts +++ b/apps/sim/blocks/blocks/logs.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { LogsV2Block } from '@/blocks/blocks/logs' +import { LogsBlock, LogsV2Block } from '@/blocks/blocks/logs' function buildQueryParams(params: Record) { return LogsV2Block.tools.config!.params!({ operation: 'query', ...params }) @@ -77,3 +77,25 @@ describe('LogsV2Block backwards compatibility', () => { expect(JSON.stringify(params)).not.toContain('triggers') }) }) + +describe('LogsBlock agent tool calls', () => { + const mapParams = LogsBlock.tools.config?.params + if (!mapParams) throw new Error('LogsBlock has no params mapper') + + it('sends the log id typed into the tool row instead of query filters', () => { + expect(mapParams({ logId: 'log-1' }, { operation: 'get_log' })).toEqual({ id: 'log-1' }) + }) + + it('sends the execution id typed into the tool row instead of query filters', () => { + expect(mapParams({ executionIdLookup: 'exec-1' }, { operation: 'get_execution' })).toEqual({ + executionId: 'exec-1', + }) + }) + + it('keeps the model-supplied id when the tool row leaves the block field blank', () => { + expect(mapParams({ id: 'log-2' }, { operation: 'get_log' })).toEqual({ id: 'log-2' }) + expect(mapParams({ executionId: 'exec-2' }, { operation: 'get_execution' })).toEqual({ + executionId: 'exec-2', + }) + }) +}) diff --git a/apps/sim/blocks/blocks/logs.ts b/apps/sim/blocks/blocks/logs.ts index 7970a8b0d03..8050abf9fac 100644 --- a/apps/sim/blocks/blocks/logs.ts +++ b/apps/sim/blocks/blocks/logs.ts @@ -1,5 +1,6 @@ import { Library } from '@sim/emcn/icons' import type { BlockConfig } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' export const LogsBlock: BlockConfig = { type: 'logs', @@ -191,23 +192,25 @@ export const LogsBlock: BlockConfig = { if (operation === 'get_execution') return 'logs_get_execution' return 'logs_query' }, - params: (params: Record) => { - const operation = params.operation || 'query' + params: (params: Record, context) => { + const operation = mapperOperation(params, context) || 'query' if (operation === 'get_log') { - if (!params.logId) { + const logId = params.logId || toolCallArg(context, params.id) + if (!logId) { throw new Error('Logs Block Error: Log ID is required for get_log operation') } - return { id: params.logId } + return { id: logId } } if (operation === 'get_execution') { - if (!params.executionIdLookup) { + const executionId = params.executionIdLookup || toolCallArg(context, params.executionId) + if (!executionId) { throw new Error( 'Logs Block Error: Execution ID is required for get_execution operation' ) } - return { executionId: params.executionIdLookup } + return { executionId } } const rawLimit = @@ -551,8 +554,8 @@ export const LogsV2Block: BlockConfig = { if (operation === 'get_run_details') return 'logs_get_run_details' return 'logs_query_runs' }, - params: (params: Record) => { - const operation = params.operation || 'query' + params: (params: Record, context) => { + const operation = mapperOperation(params, context) || 'query' if (operation === 'get_run_details') { if (!params.runId) { diff --git a/apps/sim/blocks/blocks/loops.ts b/apps/sim/blocks/blocks/loops.ts index a957b6a8401..ec1fe28eff0 100644 --- a/apps/sim/blocks/blocks/loops.ts +++ b/apps/sim/blocks/blocks/loops.ts @@ -1,7 +1,7 @@ import { LoopsIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' import { getTrigger } from '@/triggers' /** How a contact is identified — email or user id, whichever the user filled. */ @@ -510,8 +510,9 @@ Return ONLY the JSON object - no explanations, no extra text.`, ], config: { tool: (params) => `loops_${params.operation}`, - params: (params) => { - const { operation, apiKey } = params + params: (params, context) => { + const operation = mapperOperation(params, context) + const { apiKey } = params const result: Record = { apiKey } switch (operation) { @@ -571,8 +572,8 @@ Return ONLY the JSON object - no explanations, no extra text.`, break case 'create_contact_property': - result.name = params.propertyName - result.type = params.propertyType + result.name = params.propertyName ?? toolCallArg(context, params.name) + result.type = params.propertyType ?? toolCallArg(context, params.type) break case 'list_contact_properties': diff --git a/apps/sim/blocks/blocks/mailgun.test.ts b/apps/sim/blocks/blocks/mailgun.test.ts new file mode 100644 index 00000000000..93f46b9ed03 --- /dev/null +++ b/apps/sim/blocks/blocks/mailgun.test.ts @@ -0,0 +1,131 @@ +/** + * Tool calls pass the operation only in context and supply model arguments under the tool's param + * names, so the add-member mapping must run there without overwriting what the model sent. An Agent + * tool row never stores Member Email or Member Name (no tool param matches them); the block-field + * case covers surfaces that pass raw block params with a context operation. + */ +import { describe, expect, it } from 'vitest' +import { MailgunV2Block } from '@/blocks/blocks/mailgun' +import type { BlockToolParamsContext } from '@/blocks/types' +import { mailgunAddListMemberTool } from '@/tools/mailgun/add_list_member' +import { mailgunGetMailingListTool } from '@/tools/mailgun/get_mailing_list' +import type { ToolConfig } from '@/tools/types' +import { validateRequiredParametersAfterMerge } from '@/tools/utils' + +function mapParams( + inputs: Record, + context?: BlockToolParamsContext +): Record { + const mapped = MailgunV2Block.tools.config?.params?.(inputs, context) ?? {} + return { ...inputs, ...mapped } +} + +function requestUrl(tool: ToolConfig, params: Record): string { + const url = tool.request.url + return typeof url === 'function' ? url(params) : url +} + +function formFields( + params: Record, + tool: ToolConfig = mailgunAddListMemberTool +): Record { + const build = tool.request.body + if (typeof build !== 'function') throw new Error('add_list_member has no request body') + const { body } = build(params) as { body: FormData } + return Object.fromEntries(body.entries()) +} + +describe('Mailgun block add_list_member mapping', () => { + it('adds the member the model named to the list the model named', () => { + const params = mapParams( + { apiKey: 'key', listAddress: 'news@mg.example.com', address: 'alice@example.com' }, + { operation: 'add_list_member' } + ) + expect(requestUrl(mailgunAddListMemberTool, params)).toBe( + 'https://api.mailgun.net/v3/lists/news@mg.example.com/members' + ) + expect(formFields(params).address).toBe('alice@example.com') + }) + + it('sends block-field Member Email and Name instead of the list address on a tool call', () => { + const params = mapParams( + { + apiKey: 'key', + listAddress: 'news@mg.example.com', + address: 'news@mg.example.com', + memberAddress: 'bob@example.com', + memberName: 'Bob', + }, + { operation: 'add_list_member' } + ) + expect(formFields(params)).toMatchObject({ address: 'bob@example.com', name: 'Bob' }) + }) + + it('adds the member even when the model names the list address as the member', () => { + const params = mapParams( + { apiKey: 'key', listAddress: 'news@mg.example.com', address: 'news@mg.example.com' }, + { operation: 'add_list_member', pinnedParams: new Set(['apiKey']) } + ) + expect(formFields(params).address).toBe('news@mg.example.com') + }) + + it('never adds the row-saved List Address to its own list as a member', () => { + const params = mapParams( + { apiKey: 'key', address: 'news@mg.example.com' }, + { operation: 'add_list_member', pinnedParams: new Set(['apiKey', 'address']) } + ) + expect(requestUrl(mailgunAddListMemberTool, params)).toBe( + 'https://api.mailgun.net/v3/lists/news@mg.example.com/members' + ) + expect(() => + validateRequiredParametersAfterMerge( + 'mailgun_add_list_member', + mailgunAddListMemberTool, + params + ) + ).toThrow('Address is required') + }) + + it.each([ + ['a stored string', 'false', 'no'], + ['a model boolean', false, 'no'], + ['a model boolean', true, 'yes'], + ])('honors subscribed given as %s (%j) on a tool call', (_label, subscribed, expected) => { + const params = mapParams( + { apiKey: 'key', listAddress: 'l@mg.example.com', address: 'a@x.com', subscribed }, + { operation: 'add_list_member' } + ) + expect(formFields(params).subscribed).toBe(expected) + }) + + it('maps the canvas List Address and Member Email as before', () => { + const params = mapParams({ + apiKey: 'key', + operation: 'add_list_member', + address: 'news@mg.example.com', + memberAddress: 'carol@example.com', + subscribed: 'false', + }) + expect(requestUrl(mailgunAddListMemberTool, params)).toBe( + 'https://api.mailgun.net/v3/lists/news@mg.example.com/members' + ) + expect(formFields(params)).toMatchObject({ address: 'carol@example.com', subscribed: 'no' }) + }) +}) + +describe('Mailgun list address path segment', () => { + it('rejects a list address that would escape its path segment', () => { + expect(() => + requestUrl(mailgunGetMailingListTool, { + apiKey: 'key', + address: 'x@mg.example.com/../../domains', + }) + ).toThrow(/path separator/) + }) + + it('keeps a query delimiter inside the segment', () => { + expect( + requestUrl(mailgunGetMailingListTool, { apiKey: 'key', address: 'news+a@mg.example.com?x=1' }) + ).toBe('https://api.mailgun.net/v3/lists/news+a@mg.example.com%3Fx=1') + }) +}) diff --git a/apps/sim/blocks/blocks/mailgun.ts b/apps/sim/blocks/blocks/mailgun.ts index 58f90b9cb72..7c4f64ea5f7 100644 --- a/apps/sim/blocks/blocks/mailgun.ts +++ b/apps/sim/blocks/blocks/mailgun.ts @@ -1,7 +1,13 @@ import { MailgunIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { + isToolCall, + mapperOperation, + parseOptionalBooleanInput, + toolCallArg, + withSavedCredential, +} from '@/blocks/utils' export const MailgunBlock: BlockConfig = { type: 'mailgun', @@ -395,17 +401,25 @@ Return ONLY the JSON object - no explanations or markdown.`, ], config: { tool: (params) => `mailgun_${params.operation}`, - params: (params) => { - const { operation, memberAddress, memberName, ...rest } = params + params: (params, context) => { + const { memberAddress, memberName, ...rest } = params - // Handle special field mappings for add_list_member - if (operation === 'add_list_member') { + if (mapperOperation(params, context) === 'add_list_member') { + /** + * The block's List Address field is stored under `address`, the tool's member param. + * On the canvas, and on a tool call whose row saved that field, `address` is the list; + * otherwise it is the member the model named. + */ + const addressIsList = + !isToolCall(context) || Boolean(context?.pinnedParams?.has('address')) return { ...rest, - listAddress: params.address, - address: memberAddress, - name: memberName, - subscribed: params.subscribed === 'true', + listAddress: addressIsList ? params.address : params.listAddress, + address: memberAddress || (addressIsList ? undefined : params.address), + name: memberName || toolCallArg(context, params.name), + subscribed: isToolCall(context) + ? parseOptionalBooleanInput(params.subscribed) + : params.subscribed === 'true', } } @@ -518,7 +532,7 @@ export const MailgunBlockMeta = { icon: MailgunIcon, title: 'Mailgun domain verification monitor', prompt: - 'Create a scheduled workflow that checks the status of each Mailgun sending domain, flags any domain whose SPF, DKIM, or tracking records fall out of verification, and pages the on-call engineer in Slack with the exact records that need fixing.', + 'Create a scheduled workflow that checks the state of each Mailgun sending domain, flags any domain that is no longer active, and pages the on-call engineer in Slack with the domain name and its current state.', modules: ['scheduled', 'agent', 'workflows'], category: 'operations', tags: ['monitoring', 'automation', 'enterprise'], @@ -531,7 +545,7 @@ export const MailgunBlockMeta = { description: 'Send a transactional email through a Mailgun sending domain to one or more recipients.', content: - '# Send Transactional Email\n\nDeliver an email through Mailgun.\n\n## Steps\n1. Confirm the verified sending domain to use, listing domains first if unsure.\n2. Compose the message with from, to, subject, and an HTML or text body.\n3. Send Message with those fields, adding CC, BCC, or attachments as needed.\n\n## Output\nConfirmation of acceptance with the Mailgun message ID and the recipients it was queued to.', + '# Send Transactional Email\n\nDeliver an email through Mailgun.\n\n## Steps\n1. Confirm the verified sending domain to use, listing domains first if unsure.\n2. Compose the message with from, to, subject, and an HTML or text body.\n3. Send Message with those fields, adding CC or BCC recipients and tags as needed.\n\n## Output\nConfirmation of acceptance with the Mailgun message ID and the recipients it was queued to.', }, { name: 'track-delivery-events', diff --git a/apps/sim/blocks/blocks/manageengine-sdp.ts b/apps/sim/blocks/blocks/manageengine-sdp.ts index d95924575f8..35f485fbf60 100644 --- a/apps/sim/blocks/blocks/manageengine-sdp.ts +++ b/apps/sim/blocks/blocks/manageengine-sdp.ts @@ -2,6 +2,7 @@ import { ManageEngineIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { isToolCall, mapperOperation } from '@/blocks/utils' import { SDP_DATA_CENTER_BASES } from '@/tools/manageengine_sdp/data-centers' /** @@ -1055,14 +1056,12 @@ export const ManageEngineSdpBlock: BlockConfig = { ], config: { tool: (params) => `manageengine_sdp_${params.operation}`, - params: (params) => { - // The agent-tool path does not carry `operation` inside params - it is a - // sibling of the tool call, used only to pick the tool - and there the - // model addresses tool params by their real names. The tool is already - // selected, so there is no cross-operation leak to guard against, while - // running the scoping below WOULD overwrite the model's own values with - // `undefined`. - if (typeof params.operation !== 'string') return params + params: (params, context) => { + // On a tool call the model addresses tool params by their real names and + // the tool is already selected, so there is no cross-operation leak to + // guard against, while running the scoping below WOULD overwrite the + // model's own values with `undefined`. + if (isToolCall(context)) return params // IMPORTANT: leaving a key out of the result does NOT keep it from the // tool. Both call sites merge this return value on top of the original @@ -1075,7 +1074,7 @@ export const ManageEngineSdpBlock: BlockConfig = { // under an unrelated operation. Every module-prefixed subBlock below is // therefore funnelled into the shared tool param name and every // inactive module's value is explicitly cleared. - const operation = params.operation + const operation = mapperOperation(params, context) const { // The five entity ids are destructured out and republished scoped // below. Passing them through would send a problem id typed earlier to diff --git a/apps/sim/blocks/blocks/mem0.test.ts b/apps/sim/blocks/blocks/mem0.test.ts index 7620aba09fa..9757a8e62e7 100644 --- a/apps/sim/blocks/blocks/mem0.test.ts +++ b/apps/sim/blocks/blocks/mem0.test.ts @@ -29,4 +29,18 @@ describe('Mem0Block', () => { }) ).toThrow('Each message must have role user or assistant and non-empty content') }) + + it('maps an agent search call, whose operation arrives only in context', () => { + const params = buildParams( + { apiKey: 'test-key', userId: 'alice', query: 'favorite tools', limit: 5 }, + { operation: 'search' } + ) + + expect(params).toEqual({ + apiKey: 'test-key', + userId: 'alice', + query: 'favorite tools', + limit: 5, + }) + }) }) diff --git a/apps/sim/blocks/blocks/mem0.ts b/apps/sim/blocks/blocks/mem0.ts index a50dabebff2..c321621cf4a 100644 --- a/apps/sim/blocks/blocks/mem0.ts +++ b/apps/sim/blocks/blocks/mem0.ts @@ -1,12 +1,22 @@ import { toError } from '@sim/utils/errors' import { Mem0Icon } from '@/components/icons' -import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { + AuthMode, + type BlockConfig, + type BlockMeta, + type BlockToolParamsContext, + IntegrationType, +} from '@/blocks/types' +import { mapperOperation, withSavedCredential } from '@/blocks/utils' import { parseMem0Messages } from '@/tools/mem0/utils' -function mem0ToolParams(params: Record, requireApiKey: boolean) { +function mem0ToolParams( + params: Record, + requireApiKey: boolean, + context?: BlockToolParamsContext +) { const errors: string[] = [] - const operation = params.operation || 'add' + const operation = mapperOperation(params, context) || 'add' if (requireApiKey && !params.apiKey) { errors.push('API Key is required') @@ -269,7 +279,7 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n return 'mem0_add_memories' } }, - params: (params) => mem0ToolParams(params, true), + params: (params, context) => mem0ToolParams(params, true, context), }, }, inputs: { @@ -403,6 +413,6 @@ export const Mem0V2Block: BlockConfig = { ...withSavedCredential( Mem0Block, { id: 'credential', type: 'oauth-input', serviceId: 'mem0', title: 'Mem0 Credential' }, - { params: (params) => mem0ToolParams(params, false) } + { params: (params, context) => mem0ToolParams(params, false, context) } ), } diff --git a/apps/sim/blocks/blocks/memory.ts b/apps/sim/blocks/blocks/memory.ts index 8858883156d..463d3bb0a9d 100644 --- a/apps/sim/blocks/blocks/memory.ts +++ b/apps/sim/blocks/blocks/memory.ts @@ -1,5 +1,6 @@ import { BrainIcon } from '@/components/icons' import type { BlockConfig } from '@/blocks/types' +import { mapperOperation } from '@/blocks/utils' export const MemoryBlock: BlockConfig = { type: 'memory', @@ -121,24 +122,25 @@ export const MemoryBlock: BlockConfig = { return 'memory_add' } }, - params: (params: Record) => { + params: (params: Record, context) => { + const operation = mapperOperation(params, context) const errors: string[] = [] - if (!params.operation) { + if (!operation) { errors.push('Operation is required') } const conversationId = params.id || params.conversationId - if (params.operation === 'add') { + if (operation === 'add') { if (!conversationId) { errors.push('Conversation ID is required for add operation') } } - if (params.operation === 'get' || params.operation === 'delete') { + if (operation === 'get' || operation === 'delete') { if (!conversationId) { - errors.push(`Conversation ID is required for ${params.operation} operation`) + errors.push(`Conversation ID is required for ${operation} operation`) } } @@ -148,7 +150,7 @@ export const MemoryBlock: BlockConfig = { const baseResult: Record = {} - if (params.operation === 'add') { + if (operation === 'add') { return { ...baseResult, conversationId: conversationId, @@ -157,14 +159,14 @@ export const MemoryBlock: BlockConfig = { } } - if (params.operation === 'get') { + if (operation === 'get') { return { ...baseResult, conversationId: conversationId, } } - if (params.operation === 'delete') { + if (operation === 'delete') { return { ...baseResult, conversationId: conversationId, diff --git a/apps/sim/blocks/blocks/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_dynamics_365.test.ts b/apps/sim/blocks/blocks/microsoft_dynamics_365.test.ts index 620abf93464..ac0577a9b2e 100644 --- a/apps/sim/blocks/blocks/microsoft_dynamics_365.test.ts +++ b/apps/sim/blocks/blocks/microsoft_dynamics_365.test.ts @@ -1,5 +1,9 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { MicrosoftDynamics365Block } from '@/blocks/blocks/microsoft_dynamics_365' +import { getToolMetadata } from '@/tools/metadata' +import { microsoftDynamics365ListRecordsTool } from '@/tools/microsoft_dynamics_365/list_records' +import { microsoftDynamics365UpdateRecordTool } from '@/tools/microsoft_dynamics_365/update_record' +import { getSubBlocksForToolInput } from '@/tools/params' const BASE_PARAMS = { credential: 'credential-1', @@ -330,6 +334,16 @@ describe('MicrosoftDynamics365Block', () => { ).toThrow('Time spent must be at most 2147483647') }) + it('refuses to close an opportunity whose canvas Outcome is blank instead of assuming won', () => { + expect(() => + mapParams({ + operation: 'close_opportunity', + closeOpportunityId: '11111111-1111-4111-8111-111111111111', + opportunityOutcome: '', + }) + ).toThrow('Outcome') + }) + it('supports an optional opportunity subject and enforces close-description limits', () => { expect( mapParams({ @@ -378,3 +392,153 @@ describe('MicrosoftDynamics365Block', () => { ).toBeUndefined() }) }) + +/** + * Agent tool rows, Pi, and Human v2 pass the operation only in the mapper context. Params hold the + * stored row values merged with the model's args, which are keyed by the selected tool's param + * names. A tool row stores only fields tool-input renders, so block-only dropdowns such as + * `recordType` and `ownerType` are absent. + */ +describe('MicrosoftDynamics365Block tool-call mapping', () => { + const RECORD_ID = '11111111-1111-4111-8111-111111111111' + const OWNER_ID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' + + function mapToolCall(operation: string, params: Record) { + const mapper = MicrosoftDynamics365Block.tools.config?.params + if (!mapper) throw new Error('Dynamics 365 CRM block is missing its params mapper') + return mapper({ ...BASE_PARAMS, ...params }, { operation }) + } + + it('renders Owner Type and Owner ID on the List Owners and Assign Record tool rows', () => { + const rowTools = [microsoftDynamics365ListRecordsTool, microsoftDynamics365UpdateRecordTool] + vi.mocked(getToolMetadata).mockImplementationOnce(lookup).mockImplementationOnce(lookup) + function lookup(toolId: string) { + const tool = rowTools.find((candidate) => candidate.id === toolId) + return tool && { id: tool.id, params: tool.params } + } + const rowFields = (toolId: string, operation: string) => + getSubBlocksForToolInput( + toolId, + 'microsoft_dynamics_365', + { operation }, + {}, + MicrosoftDynamics365Block + )?.subBlocks.map((subBlock) => subBlock.id) + + expect(rowFields('microsoft_dynamics_365_list_records', 'list_owners')).toContain('ownerType') + expect(rowFields('microsoft_dynamics_365_update_record', 'assign_record')).toEqual( + expect.arrayContaining(['ownerType', 'ownerId']) + ) + }) + + it('lists owners from the row-stored owner type on a tool call', () => { + expect( + mapToolCall('list_owners', { ownerType: 'team', entitySetName: 'accounts' }) + ).toMatchObject({ entitySetName: 'teams' }) + }) + + it('assigns the record the model names to the row-stored owner on a tool call', () => { + expect( + mapToolCall('assign_record', { + ownerType: 'team', + ownerId: OWNER_ID, + entitySetName: 'contacts', + recordId: RECORD_ID, + }) + ).toEqual({ + ...BASE_PARAMS, + entitySetName: 'contacts', + recordId: RECORD_ID, + data: { 'ownerid@odata.bind': `/teams(${OWNER_ID})` }, + }) + }) + + it('applies the stored resolution subject when the model sends only the case ID', () => { + expect( + mapToolCall('close_case', { caseSubject: 'Resolved by agent', caseId: RECORD_ID }) + ).toEqual({ ...BASE_PARAMS, caseId: RECORD_ID, subject: 'Resolved by agent' }) + expect( + mapToolCall('close_case', { caseId: RECORD_ID, subject: 'Model subject', timeSpent: 15 }) + ).toEqual({ ...BASE_PARAMS, caseId: RECORD_ID, subject: 'Model subject', timeSpent: 15 }) + }) + + it('keeps typed model list args over the stored count switch', () => { + expect( + mapToolCall('list_records', { + includeCount: false, + entitySetName: 'contacts', + select: 'fullname', + pageSize: 10, + count: true, + }) + ).toEqual({ + ...BASE_PARAMS, + entitySetName: 'contacts', + select: 'fullname', + pageSize: 10, + count: 'true', + }) + }) + + it('closes the opportunity the model names with the outcome it chose', () => { + expect( + mapToolCall('close_opportunity', { + opportunityId: RECORD_ID, + outcome: 'lost', + statusReason: 4, + }) + ).toEqual({ ...BASE_PARAMS, opportunityId: RECORD_ID, outcome: 'lost', statusReason: 4 }) + }) + + it('refuses to close an opportunity when the model omits the outcome', () => { + expect(() => mapToolCall('close_opportunity', { opportunityId: RECORD_ID })).toThrow( + 'Outcome is required' + ) + }) + + it('searches the model entities and numeric paging, else every CRM table', () => { + const entityList = [{ name: 'contact' }, { name: 'lead' }] + const entities = JSON.stringify(entityList) + expect( + mapToolCall('search_records', { searchTerm: 'Contoso', entities, top: 10, skip: 20 }) + ).toMatchObject({ entities, top: 10, skip: 20, searchMode: 'any', searchType: 'simple' }) + expect( + mapToolCall('search_records', { searchTerm: 'Contoso', entities: entityList }) + ).toMatchObject({ entities }) + const omitted = mapToolCall('search_records', { searchTerm: 'Contoso' }) + expect(omitted).toMatchObject({ searchTerm: 'Contoso', top: 100 }) + expect(omitted).not.toHaveProperty('entities') + }) + + it('leaves qualification switches the model omits for the tool to reject', () => { + const mapped = mapToolCall('qualify_lead', { leadId: RECORD_ID }) + expect(mapped).toEqual({ ...BASE_PARAMS, leadId: RECORD_ID }) + expect(mapped).not.toHaveProperty('createAccount') + expect(mapped).not.toHaveProperty('createContact') + expect(mapped).not.toHaveProperty('createOpportunity') + }) + + it('passes model qualification references when no stored values exist', () => { + expect( + mapToolCall('qualify_lead', { + leadId: RECORD_ID, + createAccount: false, + createContact: false, + createOpportunity: true, + statusReason: 3, + opportunityCustomerId: OWNER_ID, + opportunityCustomerType: 'contact', + qualifyOpportunityCustomerType: 'account', + }) + ).toEqual({ + ...BASE_PARAMS, + leadId: RECORD_ID, + createAccount: false, + createContact: false, + createOpportunity: true, + statusReason: 3, + opportunityCustomerId: OWNER_ID, + opportunityCustomerType: 'contact', + }) + }) +}) diff --git a/apps/sim/blocks/blocks/microsoft_dynamics_365.ts b/apps/sim/blocks/blocks/microsoft_dynamics_365.ts index ded79b02066..c9ae70ad8b1 100644 --- a/apps/sim/blocks/blocks/microsoft_dynamics_365.ts +++ b/apps/sim/blocks/blocks/microsoft_dynamics_365.ts @@ -1,11 +1,14 @@ import { MicrosoftDataverseIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' -import type { BlockConfig, BlockMeta } from '@/blocks/types' +import type { BlockConfig, BlockMeta, BlockToolParamsContext } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' import { + isToolCall, + mapperOperation, parseOptionalBooleanInput, parseOptionalJsonInput, parseOptionalNumberInput, + toolCallArg, } from '@/blocks/utils' const DATAVERSE_GUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i @@ -86,8 +89,20 @@ function optionalBoundedString( return normalized } -function getListPaginationParams(params: Record) { - const pageSize = parseOptionalNumberInput(params.maxResults, 'Max results', { +function isUnset(value: unknown): boolean { + return value === undefined || value === null || value === '' +} + +function firstSet(primary: unknown, fallback: unknown): unknown { + return isUnset(primary) ? fallback : primary +} + +function getListPaginationParams( + params: Record, + context: BlockToolParamsContext | undefined +) { + const pageSizeInput = firstSet(params.maxResults, toolCallArg(context, params.pageSize)) + const pageSize = parseOptionalNumberInput(pageSizeInput, 'Max results', { integer: true, min: 1, max: 100, @@ -153,6 +168,37 @@ function getOwnerType(value: unknown) { return OWNER_TYPES[ownerType as OwnerType] } +/** + * The entity set a record operation targets. On a tool call the model's required `entitySetName` + * wins (the tool validates it): `recordType` is not a tool param, so a tool row never shows it + * and any stored value is not the model's choice. The canvas reads only `recordType`. + */ +function getRecordEntitySetName( + params: Record, + context: BlockToolParamsContext | undefined +): string { + return ( + optionalString(toolCallArg(context, params.entitySetName)) ?? + getRecordType(params.recordType).entitySetName + ) +} + +/** + * The tables a search covers. The canvas searches its selected `recordType`. A tool call sends the + * model's `entities` (a JSON string, or an array it typed directly), else leaves it unset so the + * tool searches every supported CRM table, matching the tool's documented default. + */ +function getSearchEntities( + params: Record, + context: BlockToolParamsContext | undefined +): string | undefined { + if (!isToolCall(context)) { + return JSON.stringify([{ name: getRecordType(params.recordType).logicalName }]) + } + if (Array.isArray(params.entities)) return JSON.stringify(params.entities) + return optionalString(params.entities) +} + function getCommonParams(params: Record) { return { credential: requiredString(params.credential, 'Microsoft account'), @@ -501,6 +547,7 @@ export const MicrosoftDynamics365Block: BlockConfig = { { label: 'Team', id: 'team' }, ], value: () => 'user', + paramVisibility: 'user-only', condition: { field: 'operation', value: ['list_owners', 'assign_record'] }, required: { field: 'operation', value: ['list_owners', 'assign_record'] }, }, @@ -509,6 +556,7 @@ export const MicrosoftDynamics365Block: BlockConfig = { title: 'Owner ID', type: 'short-input', placeholder: 'User or team GUID', + paramVisibility: 'user-only', condition: { field: 'operation', value: 'assign_record' }, required: { field: 'operation', value: 'assign_record' }, }, @@ -748,69 +796,72 @@ export const MicrosoftDynamics365Block: BlockConfig = { throw new Error(`Unsupported Dynamics 365 CRM operation: ${params.operation}`) } }, - params: (params) => { + params: (params, context) => { const common = getCommonParams(params) + const operation = mapperOperation(params, context) - switch (params.operation) { + switch (operation) { case 'list_records': { - const recordType = getRecordType(params.recordType) const includeCount = parseBooleanWithDefault( - params.includeCount, + firstSet(toolCallArg(context, params.count), params.includeCount), 'Include total count', false ) + const select = optionalString( + firstSet(params.listSelect, toolCallArg(context, params.select)) + ) + const filter = optionalString( + firstSet(params.listFilter, toolCallArg(context, params.filter)) + ) + const orderBy = optionalString( + firstSet(params.listOrderBy, toolCallArg(context, params.orderBy)) + ) + const expand = optionalString( + firstSet(params.recordExpand, toolCallArg(context, params.expand)) + ) return { ...common, - entitySetName: recordType.entitySetName, - ...(optionalString(params.listSelect) && { - select: optionalString(params.listSelect), - }), - ...(optionalString(params.listFilter) && { - filter: optionalString(params.listFilter), - }), - ...(optionalString(params.listOrderBy) && { - orderBy: optionalString(params.listOrderBy), - }), - ...(optionalString(params.recordExpand) && { - expand: optionalString(params.recordExpand), - }), - ...getListPaginationParams(params), + entitySetName: getRecordEntitySetName(params, context), + ...(select && { select }), + ...(filter && { filter }), + ...(orderBy && { orderBy }), + ...(expand && { expand }), + ...getListPaginationParams(params, context), count: includeCount ? 'true' : 'false', } } case 'get_record': { - const recordType = getRecordType(params.recordType) + const select = optionalString( + firstSet(params.listSelect, toolCallArg(context, params.select)) + ) + const expand = optionalString( + firstSet(params.recordExpand, toolCallArg(context, params.expand)) + ) return { ...common, - entitySetName: recordType.entitySetName, + entitySetName: getRecordEntitySetName(params, context), recordId: normalizeDataverseGuid( requiredString(params.recordId, 'Record ID'), 'Record ID' ), - ...(optionalString(params.listSelect) && { - select: optionalString(params.listSelect), - }), - ...(optionalString(params.recordExpand) && { - expand: optionalString(params.recordExpand), - }), + ...(select && { select }), + ...(expand && { expand }), } } case 'create_record': { - const recordType = getRecordType(params.recordType) return { ...common, - entitySetName: recordType.entitySetName, + entitySetName: getRecordEntitySetName(params, context), data: parseRequiredRecord(params.data), } } case 'update_record': { - const recordType = getRecordType(params.recordType) return { ...common, - entitySetName: recordType.entitySetName, + entitySetName: getRecordEntitySetName(params, context), recordId: normalizeDataverseGuid( requiredString(params.recordId, 'Record ID'), 'Record ID' @@ -820,35 +871,38 @@ export const MicrosoftDynamics365Block: BlockConfig = { } case 'search_records': { - const recordType = getRecordType(params.recordType) + const entities = getSearchEntities(params, context) const top = - parseOptionalNumberInput(params.maxResults, 'Max results', { - integer: true, - min: 1, - max: 100, - }) ?? 100 - const skip = parseOptionalNumberInput(params.searchSkip, 'Search offset', { - integer: true, - min: 0, - max: 2_147_483_647, - }) + parseOptionalNumberInput( + firstSet(params.maxResults, toolCallArg(context, params.top)), + 'Max results', + { integer: true, min: 1, max: 100 } + ) ?? 100 + const skip = parseOptionalNumberInput( + firstSet(params.searchSkip, toolCallArg(context, params.skip)), + 'Search offset', + { integer: true, min: 0, max: 2_147_483_647 } + ) + const filter = optionalString( + firstSet(params.searchFilter, toolCallArg(context, params.filter)) + ) + const facets = optionalString( + firstSet(params.searchFacets, toolCallArg(context, params.facets)) + ) + const orderBy = optionalString( + firstSet(params.searchOrderBy, toolCallArg(context, params.orderBy)) + ) return { ...common, searchTerm: requiredString(params.searchTerm, 'Search term', 100), - entities: JSON.stringify([{ name: recordType.logicalName }]), + ...(entities && { entities }), top, ...(skip !== undefined && { skip }), - ...(optionalString(params.searchFilter) && { - filter: optionalString(params.searchFilter), - }), - ...(optionalString(params.searchFacets) && { - facets: optionalString(params.searchFacets), - }), - ...(optionalString(params.searchOrderBy) && { - orderBy: optionalString(params.searchOrderBy), - }), - searchMode: requiredString(params.searchMode ?? 'any', 'Search mode'), - searchType: requiredString(params.searchType ?? 'simple', 'Query type'), + ...(filter && { filter }), + ...(facets && { facets }), + ...(orderBy && { orderBy }), + searchMode: requiredString(params.searchMode || 'any', 'Search mode'), + searchType: requiredString(params.searchType || 'simple', 'Query type'), } } @@ -859,12 +913,11 @@ export const MicrosoftDynamics365Block: BlockConfig = { entitySetName: ownerType.entitySetName, select: ownerType.select, filter: ownerType.filter, - ...getListPaginationParams(params), + ...getListPaginationParams(params, context), } } case 'assign_record': { - const recordType = getRecordType(params.recordType) const ownerType = getOwnerType(params.ownerType) const ownerId = normalizeDataverseGuid( requiredString(params.ownerId, 'Owner ID'), @@ -872,7 +925,7 @@ export const MicrosoftDynamics365Block: BlockConfig = { ) return { ...common, - entitySetName: recordType.entitySetName, + entitySetName: getRecordEntitySetName(params, context), recordId: normalizeDataverseGuid( requiredString(params.recordId, 'Record ID'), 'Record ID' @@ -884,45 +937,68 @@ export const MicrosoftDynamics365Block: BlockConfig = { } case 'qualify_lead': { - const createOpportunity = parseBooleanWithDefault( + const qualifySwitch = (value: unknown, label: string, defaultValue: boolean) => + isToolCall(context) && isUnset(value) + ? undefined + : parseBooleanWithDefault(value, label, defaultValue) + const createAccount = qualifySwitch(params.createAccount, 'Create account', true) + const createContact = qualifySwitch(params.createContact, 'Create contact', true) + const createOpportunity = qualifySwitch( params.createOpportunity, 'Create opportunity', false ) const statusReason = parseOptionalNumberInput( - params.qualifyStatusReason, + firstSet(params.qualifyStatusReason, toolCallArg(context, params.statusReason)), 'Qualified status reason', { integer: true, min: -2_147_483_648, max: 2_147_483_647 } ) - const opportunityCurrencyId = createOpportunity - ? optionalString(params.qualifyOpportunityCurrencyId) - : undefined - const opportunityCustomerId = createOpportunity - ? optionalString(params.qualifyOpportunityCustomerId) - : undefined - const sourceCampaignId = createOpportunity - ? optionalString(params.qualifySourceCampaignId) - : undefined - const processInstanceId = createOpportunity - ? optionalString(params.qualifyProcessInstanceId) - : undefined - const processInstanceEntityType = createOpportunity - ? optionalString(params.qualifyProcessInstanceEntityType) - : undefined + const opportunityField = (dedicated: unknown, toolParam: unknown) => + createOpportunity + ? optionalString(firstSet(dedicated, toolCallArg(context, toolParam))) + : undefined + const opportunityCurrencyId = opportunityField( + params.qualifyOpportunityCurrencyId, + params.opportunityCurrencyId + ) + const opportunityCustomerId = opportunityField( + params.qualifyOpportunityCustomerId, + params.opportunityCustomerId + ) + const sourceCampaignId = opportunityField( + params.qualifySourceCampaignId, + params.sourceCampaignId + ) + const processInstanceId = opportunityField( + params.qualifyProcessInstanceId, + params.processInstanceId + ) + const processInstanceEntityType = opportunityField( + params.qualifyProcessInstanceEntityType, + params.processInstanceEntityType + ) if (Boolean(processInstanceId) !== Boolean(processInstanceEntityType)) { throw new Error( 'Process instance ID and process instance table must be provided together' ) } const opportunityCustomerType = opportunityCustomerId - ? requiredString(params.qualifyOpportunityCustomerType, 'Opportunity customer type') + ? requiredString( + optionalString(params.qualifyOpportunityCustomerId) + ? params.qualifyOpportunityCustomerType + : firstSet( + toolCallArg(context, params.opportunityCustomerType), + params.qualifyOpportunityCustomerType + ), + 'Opportunity customer type' + ) : undefined return { ...common, leadId: requiredString(params.leadId, 'Lead ID'), - createAccount: parseBooleanWithDefault(params.createAccount, 'Create account', true), - createContact: parseBooleanWithDefault(params.createContact, 'Create contact', true), - createOpportunity, + ...(createAccount !== undefined && { createAccount }), + ...(createContact !== undefined && { createContact }), + ...(createOpportunity !== undefined && { createOpportunity }), ...(statusReason !== undefined && { statusReason }), ...(opportunityCurrencyId && { opportunityCurrencyId }), ...(opportunityCustomerId && { @@ -939,20 +1015,30 @@ export const MicrosoftDynamics365Block: BlockConfig = { case 'close_opportunity': { const statusReason = parseOptionalNumberInput( - params.opportunityStatusReason, + firstSet(params.opportunityStatusReason, toolCallArg(context, params.statusReason)), 'Opportunity status reason', { integer: true, min: -2_147_483_648, max: 2_147_483_647 } ) - const subject = optionalBoundedString(params.opportunitySubject, 'Close subject', 200) + const subject = optionalBoundedString( + firstSet(params.opportunitySubject, toolCallArg(context, params.subject)), + 'Close subject', + 200 + ) const description = optionalBoundedString( - params.opportunityDescription, + firstSet(params.opportunityDescription, toolCallArg(context, params.description)), 'Close notes', 2_000 ) return { ...common, - opportunityId: requiredString(params.closeOpportunityId, 'Opportunity ID'), - outcome: requiredString(params.opportunityOutcome ?? 'won', 'Outcome'), + opportunityId: requiredString( + firstSet(params.closeOpportunityId, toolCallArg(context, params.opportunityId)), + 'Opportunity ID' + ), + outcome: requiredString( + isToolCall(context) ? params.outcome : (params.opportunityOutcome ?? 'won'), + 'Outcome' + ), ...(subject && { subject }), ...(description && { description }), ...(statusReason !== undefined && { statusReason }), @@ -960,25 +1046,29 @@ export const MicrosoftDynamics365Block: BlockConfig = { } case 'close_case': { - const timeSpent = parseOptionalNumberInput(params.caseTimeSpent, 'Time spent', { - integer: true, - min: 0, - max: 2_147_483_647, - }) + const timeSpent = parseOptionalNumberInput( + firstSet(params.caseTimeSpent, toolCallArg(context, params.timeSpent)), + 'Time spent', + { integer: true, min: 0, max: 2_147_483_647 } + ) const statusReason = parseOptionalNumberInput( - params.caseStatusReason, + firstSet(params.caseStatusReason, toolCallArg(context, params.statusReason)), 'Case status reason', { integer: true, min: -2_147_483_648, max: 2_147_483_647 } ) const description = optionalBoundedString( - params.caseDescription, + firstSet(params.caseDescription, toolCallArg(context, params.description)), 'Resolution notes', 100_000 ) return { ...common, caseId: requiredString(params.caseId, 'Case ID'), - subject: requiredString(params.caseSubject, 'Resolution subject', 200), + subject: requiredString( + firstSet(params.caseSubject, toolCallArg(context, params.subject)), + 'Resolution subject', + 200 + ), ...(description && { description }), ...(timeSpent !== undefined && { timeSpent }), ...(statusReason !== undefined && { statusReason }), @@ -986,7 +1076,7 @@ export const MicrosoftDynamics365Block: BlockConfig = { } default: - throw new Error(`Unsupported Dynamics 365 CRM operation: ${params.operation}`) + throw new Error(`Unsupported Dynamics 365 CRM operation: ${operation}`) } }, }, 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/mintlify.test.ts b/apps/sim/blocks/blocks/mintlify.test.ts index 95ac6a5a0ad..4d6eefaf63c 100644 --- a/apps/sim/blocks/blocks/mintlify.test.ts +++ b/apps/sim/blocks/blocks/mintlify.test.ts @@ -1,13 +1,17 @@ import { describe, expect, it } from 'vitest' import { MintlifyBlock } from '@/blocks/blocks/mintlify' +const mapper = MintlifyBlock.tools.config?.params +if (!mapper) throw new Error('MintlifyBlock has no params mapper') +const blockParams = mapper + /** * The executor merges `tools.config.params` on top of the raw inputs, so every * assertion runs against the merged result rather than the transform's return * value alone. */ function resolveParams(inputs: Record) { - return { ...inputs, ...MintlifyBlock.tools.config.params!(inputs) } + return { ...inputs, ...blockParams(inputs) } } describe('MintlifyBlock', () => { @@ -50,4 +54,21 @@ describe('MintlifyBlock', () => { expect(result.limit).toBeUndefined() }) }) + + describe('agent tool calls', () => { + it('coerces numbers and keeps tool-named args when the operation arrives only in context', () => { + const args = { projectId: 'proj_1', source: 'contextual', status: 'pending', limit: '50' } + const result = { + ...args, + ...blockParams(args, { operation: 'get_feedback' }), + } + + expect(result).toEqual({ + projectId: 'proj_1', + source: 'contextual', + status: 'pending', + limit: 50, + }) + }) + }) }) diff --git a/apps/sim/blocks/blocks/mintlify.ts b/apps/sim/blocks/blocks/mintlify.ts index 646e9c75019..9f5ba6d655b 100644 --- a/apps/sim/blocks/blocks/mintlify.ts +++ b/apps/sim/blocks/blocks/mintlify.ts @@ -1,12 +1,15 @@ import { MintlifyIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { isToolCall, mapperOperation } from '@/blocks/utils' /** - * SubBlock IDs each operation may forward to its tool. Anything outside the - * selected operation's list is explicitly cleared, because the executor merges - * `tools.config.params` on top of the raw inputs and a retained advanced-mode - * value would otherwise leak across operations. + * SubBlock IDs each operation may forward to its tool. On the canvas anything + * outside the selected operation's list is explicitly cleared, because the + * executor merges `tools.config.params` on top of the raw inputs and a retained + * advanced-mode value would otherwise leak across operations. A tool call's + * params are the stored row plus the model's arguments, keyed by the tool's own + * param names (`path`, `source`, `status`), so nothing is cleared there. */ const OPERATION_PARAMS: Record = { trigger_update: ['projectId'], @@ -566,20 +569,16 @@ Return ONLY the JSON array.`, ], config: { tool: (params: Record) => `mintlify_${params.operation}`, - params: (params: Record) => { - const { operation } = params - // On the agent-tool path `operation` is a sibling of the tool call rather - // than a member of params, so clearing anything here would erase the - // model's own arguments. - if (typeof operation !== 'string') return {} - - const allowed = OPERATION_PARAMS[operation] + params: (params: Record, context) => { + const allowed = OPERATION_PARAMS[mapperOperation(params, context)] if (!allowed) return {} const result: Record = {} - for (const key of Object.keys(params)) { - if (key === 'operation' || key === 'apiKey') continue - result[key] = undefined + if (!isToolCall(context)) { + for (const key of Object.keys(params)) { + if (key === 'operation' || key === 'apiKey') continue + result[key] = undefined + } } for (const key of allowed) { @@ -588,8 +587,7 @@ Return ONLY the JSON array.`, if (NUMERIC_PARAMS.has(key)) { const numeric = Number(value) - if (!Number.isFinite(numeric)) continue - result[key] = numeric + result[key] = Number.isFinite(numeric) ? numeric : undefined continue } diff --git a/apps/sim/blocks/blocks/modal.test.ts b/apps/sim/blocks/blocks/modal.test.ts index 5ef7fcfad21..d8fea6a8268 100644 --- a/apps/sim/blocks/blocks/modal.test.ts +++ b/apps/sim/blocks/blocks/modal.test.ts @@ -50,4 +50,21 @@ describe('ModalBlock', () => { expect(params).not.toHaveProperty('temperature') expect(params).not.toHaveProperty('topP') }) + + it('coerces sampling controls on an agent tool call, where the operation arrives only in the context', () => { + const params = buildParams( + { model: 'Qwen/Qwen3.5-4B', content: 'hello', maxTokens: '256', temperature: 0.2 }, + { operation: 'chat_completion' } + ) + + expect(params).toMatchObject({ maxTokens: 256, temperature: 0.2 }) + }) + + it("keeps the model's function URL on an agent tool call", () => { + const modelArgs = { url: 'https://ws--app-fn.modal.run', method: 'GET' } + + const params = { ...modelArgs, ...buildParams(modelArgs, { operation: 'call_function' }) } + + expect(params.url).toBe('https://ws--app-fn.modal.run') + }) }) diff --git a/apps/sim/blocks/blocks/modal.ts b/apps/sim/blocks/blocks/modal.ts index 507c7996f95..c1a917aeed3 100644 --- a/apps/sim/blocks/blocks/modal.ts +++ b/apps/sim/blocks/blocks/modal.ts @@ -1,6 +1,7 @@ import { ModalIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' import { MODAL_SHARED_INFERENCE_URL } from '@/tools/modal/utils' /** Operations that talk to a Modal Endpoint's OpenAI-compatible `/v1` API. */ @@ -199,14 +200,14 @@ export const ModalBlock: BlockConfig = { access: ['modal_call_function', 'modal_chat_completion', 'modal_list_models'], config: { tool: (params) => `modal_${params.operation}`, - params: (params) => { - const { operation, tokenId, tokenSecret, ...rest } = params + params: (params, context) => { + const { tokenId, tokenSecret, ...rest } = params const baseParams: Record = { tokenId, tokenSecret } - switch (operation) { + switch (mapperOperation(params, context)) { case 'call_function': - baseParams.url = rest.functionUrl + baseParams.url = rest.functionUrl ?? toolCallArg(context, rest.url) if (rest.method) baseParams.method = rest.method if (rest.requestBody !== undefined && rest.requestBody !== '') { baseParams.body = rest.requestBody diff --git a/apps/sim/blocks/blocks/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/netsuite.test.ts b/apps/sim/blocks/blocks/netsuite.test.ts new file mode 100644 index 00000000000..5a4e6dc75af --- /dev/null +++ b/apps/sim/blocks/blocks/netsuite.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'vitest' +import { NetSuiteBlock } from '@/blocks/blocks/netsuite' + +const blockParams = NetSuiteBlock.tools.config?.params +if (!blockParams) throw new Error('NetSuiteBlock has no params mapper') + +describe('NetSuiteBlock', () => { + it('parses a JSON body on an agent tool call, whose operation arrives only in context', () => { + const args = { recordType: 'customer', body: '{"companyName":"Acme"}' } + const result = { + ...args, + ...blockParams(args, { operation: 'netsuite_create_record' }), + } + + expect(result.body).toEqual({ companyName: 'Acme' }) + }) + + it('keeps the model task ID on an agent async status call', () => { + const args = { jobId: '42', view: 'task', taskId: '7' } + const result = { + ...args, + ...blockParams(args, { operation: 'netsuite_get_async_status' }), + } + + expect(result.taskId).toBe('7') + }) +}) diff --git a/apps/sim/blocks/blocks/netsuite.ts b/apps/sim/blocks/blocks/netsuite.ts index 7801ad87d9b..d4048b05e56 100644 --- a/apps/sim/blocks/blocks/netsuite.ts +++ b/apps/sim/blocks/blocks/netsuite.ts @@ -1,7 +1,7 @@ import { NetSuiteIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { parseOptionalNumberInput } from '@/blocks/utils' +import { mapperOperation, parseOptionalNumberInput, toolCallArg } from '@/blocks/utils' const RECORD_TYPE_OPERATIONS = [ 'netsuite_list_records', @@ -95,10 +95,6 @@ const BATCH_WRITE_OPERATIONS = [ 'netsuite_batch_upsert_records', ] -function usesOperation(operation: unknown, operations: readonly string[]): boolean { - return typeof operation === 'string' && operations.includes(operation) -} - function optionalBoolean(value: unknown): boolean | undefined { if (value === true || value === 'true') return true if (value === false || value === 'false') return false @@ -844,35 +840,36 @@ Return ONLY the SuiteQL query - no explanations, no markdown, no extra text.`, ], config: { tool: (params) => params.operation, - params: (params) => { - if (typeof params.operation !== 'string') return {} - const { operation, resultTaskId, statusTaskId, ...rest } = params + params: (params, context) => { + const operation = mapperOperation(params, context) + if (!operation) return {} + const { resultTaskId, statusTaskId, ...rest } = params const taskId = operation === 'netsuite_get_async_status' - ? statusTaskId + ? (statusTaskId ?? toolCallArg(context, rest.taskId)) : operation === 'netsuite_get_async_result' - ? resultTaskId + ? (resultTaskId ?? toolCallArg(context, rest.taskId)) : undefined return { ...rest, - body: usesOperation(operation, BODY_OPERATIONS) + body: BODY_OPERATIONS.includes(operation) ? parseJson(rest.body, 'Record fields') : undefined, - items: usesOperation(operation, BATCH_WRITE_OPERATIONS) + items: BATCH_WRITE_OPERATIONS.includes(operation) ? parseJson(rest.items, 'Records') : undefined, - limit: usesOperation(operation, PAGING_OPERATIONS) + limit: PAGING_OPERATIONS.includes(operation) ? parseOptionalNumberInput(rest.limit, 'Limit', { integer: true, min: 1, max: 1_000, }) : undefined, - offset: usesOperation(operation, PAGING_OPERATIONS) + offset: PAGING_OPERATIONS.includes(operation) ? parseOptionalNumberInput(rest.offset, 'Offset', { integer: true, min: 0 }) : undefined, - expand: usesOperation(operation, RECORD_QUERY_OPERATIONS) ? rest.expand : undefined, - expandSubResources: usesOperation(operation, RECORD_QUERY_OPERATIONS) + expand: RECORD_QUERY_OPERATIONS.includes(operation) ? rest.expand : undefined, + expandSubResources: RECORD_QUERY_OPERATIONS.includes(operation) ? optionalBoolean(rest.expandSubResources) : undefined, roleId: diff --git a/apps/sim/blocks/blocks/new_relic.ts b/apps/sim/blocks/blocks/new_relic.ts index 18783044c72..7e7f4a2e6ef 100644 --- a/apps/sim/blocks/blocks/new_relic.ts +++ b/apps/sim/blocks/blocks/new_relic.ts @@ -2,7 +2,7 @@ import { getErrorMessage } from '@sim/utils/errors' import { NewRelicIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, withSavedCredential } from '@/blocks/utils' import type { NewRelicCustomAttributes } from '@/tools/new_relic/types' import { NEW_RELIC_REGIONS } from '@/tools/new_relic/utils' @@ -285,13 +285,13 @@ Return ONLY the numeric timestamp - no explanations, no extra text.`, ], config: { tool: (params) => String(params.operation || 'new_relic_nrql_query'), - params: (params) => { + params: (params, context) => { const baseParams = { apiKey: params.apiKey, region: params.region || 'us', } - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'new_relic_nrql_query': return { ...baseParams, diff --git a/apps/sim/blocks/blocks/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/okta.test.ts b/apps/sim/blocks/blocks/okta.test.ts index 1788e5e0c67..97816403c7c 100644 --- a/apps/sim/blocks/blocks/okta.test.ts +++ b/apps/sim/blocks/blocks/okta.test.ts @@ -68,6 +68,53 @@ describe('Okta block params transform', () => { }) }) +/** + * Mirrors `providers/utils.ts` on an Agent tool call: the model's args arrive + * keyed by the tool's param names, the operation only in the context, and the + * mapper's result is spread over the merged params. + */ +function agentCall(operation: string, modelArgs: Record): Record { + const transform = OktaBlock.tools.config?.params + if (!transform) throw new Error('Okta block has no params transform') + const args = { apiKey: 'token', domain: 'dev-1.okta.com', ...modelArgs } + return { ...args, ...transform(args, { operation }) } +} + +describe('Okta params transform on an agent tool call', () => { + it('keeps the cursor the model sends for the next page', () => { + expect(agentCall('okta_get_logs', { after: 'cursor-2' }).after).toBe('cursor-2') + expect(agentCall('okta_list_groups', { after: 'cursor-3' }).after).toBe('cursor-3') + }) + + it('keeps sendEmail false on a password reset so the link comes back instead of an email', () => { + expect(agentCall('okta_reset_password', { userId: '00u1', sendEmail: false }).sendEmail).toBe( + false + ) + }) + + it('keeps sendEmail on a deactivation, which the canvas reads from its own switch', () => { + expect(agentCall('okta_deactivate_user', { userId: '00u1', sendEmail: true }).sendEmail).toBe( + true + ) + }) + + it('keeps the activate flag on a factor enrollment', () => { + expect( + agentCall('okta_enroll_factor', { + userId: '00u1', + factorType: 'sms', + provider: 'OKTA', + phoneNumber: '+14155550123', + activate: true, + }).activate + ).toBe(true) + }) + + it('keeps the keyword on a group rule listing', () => { + expect(agentCall('okta_list_group_rules', { search: 'Engineering' }).search).toBe('Engineering') + }) +}) + /** Block state for a block created after the split: every current id present. */ function modernBlockState(overrides: Record): BlockState { const subBlocks: Record = {} diff --git a/apps/sim/blocks/blocks/okta.ts b/apps/sim/blocks/blocks/okta.ts index e9324f8336c..6df7cda7f51 100644 --- a/apps/sim/blocks/blocks/okta.ts +++ b/apps/sim/blocks/blocks/okta.ts @@ -1,7 +1,7 @@ import { OktaIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' /** * Coerces a numeric subBlock value, dropping anything that is not a real number. @@ -32,6 +32,7 @@ const CURSOR_FIELD_BY_OPERATION: Record = { okta_list_users: 'after', okta_list_groups: 'groupsAfter', okta_list_group_members: 'groupMembersAfter', + okta_list_user_groups: 'userGroupsAfter', okta_get_logs: 'logsAfter', okta_list_apps: 'appsAfter', okta_list_app_users: 'appUsersAfter', @@ -83,6 +84,11 @@ export const OktaBlock: BlockConfig = { okta_deactivate_user: [{ text: 'Deactivate user', field: 'userId', core: true }], okta_suspend_user: [{ text: 'Suspend user', field: 'userId', core: true }], okta_unsuspend_user: [{ text: 'Unsuspend user', field: 'userId', core: true }], + okta_unlock_user: [{ text: 'Unlock user', field: 'userId', core: true }], + okta_list_user_groups: [ + { text: 'List the groups of user', field: 'userId', core: true }, + { text: ', up to', field: 'limit' }, + ], okta_reset_password: [{ text: 'Reset the password of user', field: 'userId', core: true }], okta_delete_user: [{ text: 'Permanently delete user', field: 'userId', core: true }], okta_list_groups: [ @@ -214,6 +220,7 @@ export const OktaBlock: BlockConfig = { { label: 'Deactivate User', id: 'okta_deactivate_user' }, { label: 'Suspend User', id: 'okta_suspend_user' }, { label: 'Unsuspend User', id: 'okta_unsuspend_user' }, + { label: 'Unlock User', id: 'okta_unlock_user' }, { label: 'Reset Password', id: 'okta_reset_password' }, { label: 'Delete User', id: 'okta_delete_user' }, { label: 'List Groups', id: 'okta_list_groups' }, @@ -224,6 +231,7 @@ export const OktaBlock: BlockConfig = { { label: 'Add User to Group', id: 'okta_add_user_to_group' }, { label: 'Remove User from Group', id: 'okta_remove_user_from_group' }, { label: 'List Group Members', id: 'okta_list_group_members' }, + { label: 'List User Groups', id: 'okta_list_user_groups' }, { label: 'List Group Rules', id: 'okta_list_group_rules' }, { label: 'Get Group Rule', id: 'okta_get_group_rule' }, { label: 'Create Group Rule', id: 'okta_create_group_rule' }, @@ -330,7 +338,7 @@ export const OktaBlock: BlockConfig = { id: 'userId', title: 'User ID', type: 'short-input', - placeholder: 'User ID or login (email)', + placeholder: 'Okta user ID (some operations also accept a login)', condition: { field: 'operation', value: [ @@ -340,6 +348,8 @@ export const OktaBlock: BlockConfig = { 'okta_deactivate_user', 'okta_suspend_user', 'okta_unsuspend_user', + 'okta_unlock_user', + 'okta_list_user_groups', 'okta_reset_password', 'okta_delete_user', 'okta_add_user_to_group', @@ -366,6 +376,8 @@ export const OktaBlock: BlockConfig = { 'okta_deactivate_user', 'okta_suspend_user', 'okta_unsuspend_user', + 'okta_unlock_user', + 'okta_list_user_groups', 'okta_reset_password', 'okta_delete_user', 'okta_add_user_to_group', @@ -639,6 +651,7 @@ export const OktaBlock: BlockConfig = { title: 'Factor Type', type: 'dropdown', options: [ + { label: 'Select a factor type', id: '' }, { label: 'SMS', id: 'sms' }, { label: 'Voice Call', id: 'call' }, { label: 'Email', id: 'email' }, @@ -656,6 +669,7 @@ export const OktaBlock: BlockConfig = { title: 'Factor Provider', type: 'dropdown', options: [ + { label: 'Select a provider', id: '' }, { label: 'Okta', id: 'OKTA' }, { label: 'Google', id: 'GOOGLE' }, { label: 'FIDO', id: 'FIDO' }, @@ -805,6 +819,7 @@ export const OktaBlock: BlockConfig = { title: 'Role Type', type: 'dropdown', options: [ + { label: 'Select a role', id: '' }, { label: 'Super Admin', id: 'SUPER_ADMIN' }, { label: 'Org Admin', id: 'ORG_ADMIN' }, { label: 'App Admin', id: 'APP_ADMIN' }, @@ -903,6 +918,7 @@ export const OktaBlock: BlockConfig = { title: 'Sort Order', type: 'dropdown', options: [ + { label: 'Default (ascending)', id: '' }, { label: 'Ascending', id: 'ASCENDING' }, { label: 'Descending', id: 'DESCENDING' }, ], @@ -921,6 +937,7 @@ export const OktaBlock: BlockConfig = { 'okta_list_users', 'okta_list_groups', 'okta_list_group_members', + 'okta_list_user_groups', 'okta_get_logs', 'okta_list_apps', 'okta_list_app_users', @@ -963,6 +980,14 @@ export const OktaBlock: BlockConfig = { condition: { field: 'operation', value: 'okta_list_group_members' }, mode: 'advanced', }, + { + id: 'userGroupsAfter', + title: 'Cursor', + type: 'short-input', + placeholder: 'nextCursor from a previous run', + condition: { field: 'operation', value: 'okta_list_user_groups' }, + mode: 'advanced', + }, { id: 'logsAfter', title: 'Cursor', @@ -1015,6 +1040,7 @@ export const OktaBlock: BlockConfig = { 'okta_deactivate_user', 'okta_suspend_user', 'okta_unsuspend_user', + 'okta_unlock_user', 'okta_reset_password', 'okta_delete_user', 'okta_list_groups', @@ -1025,6 +1051,7 @@ export const OktaBlock: BlockConfig = { 'okta_add_user_to_group', 'okta_remove_user_from_group', 'okta_list_group_members', + 'okta_list_user_groups', 'okta_list_group_rules', 'okta_get_group_rule', 'okta_create_group_rule', @@ -1066,8 +1093,8 @@ export const OktaBlock: BlockConfig = { * (`update_user` is a POST merge) would overwrite the stored Okta value * with an empty string rather than leaving it untouched. */ - params: (params) => { - const operation = String(params.operation) + params: (params, context) => { + const operation = mapperOperation(params, context) const cursorField = CURSOR_FIELD_BY_OPERATION[operation] const result: Record = { @@ -1080,8 +1107,9 @@ export const OktaBlock: BlockConfig = { description: blankToUndefined(params.groupDescription), /** Group rules get their own keyword field but the same wire param. */ search: - params.operation === 'okta_list_group_rules' - ? blankToUndefined(params.ruleSearch) + operation === 'okta_list_group_rules' + ? (blankToUndefined(params.ruleSearch) ?? + toolCallArg(context, blankToUndefined(params.search))) : blankToUndefined(params.search), /** * Keyed off the operation rather than `??`: both switches are advanced, @@ -1091,14 +1119,19 @@ export const OktaBlock: BlockConfig = { */ sendEmail: SEND_EMAIL_DEFAULT_ON.has(operation) ? blankToUndefined(params.sendEmail) - : blankToUndefined(params.sendDeactivationEmail), + : (blankToUndefined(params.sendDeactivationEmail) ?? + toolCallArg(context, blankToUndefined(params.sendEmail))), /** Same stale-advanced-value hazard: pick the toggle for this operation. */ activate: operation === 'okta_enroll_factor' - ? blankToUndefined(params.activateFactor) + ? (blankToUndefined(params.activateFactor) ?? + toolCallArg(context, blankToUndefined(params.activate))) : blankToUndefined(params.activate), /** A cursor is only valid on the endpoint that minted it. */ - after: cursorField ? blankToUndefined(params[cursorField]) : undefined, + after: cursorField + ? (blankToUndefined(params[cursorField]) ?? + toolCallArg(context, blankToUndefined(params.after))) + : undefined, } const mappedKeys = new Set([ @@ -1161,6 +1194,7 @@ export const OktaBlock: BlockConfig = { after: { type: 'string', description: 'Cursor for the next page of users' }, groupsAfter: { type: 'string', description: 'Cursor for the next page of groups' }, groupMembersAfter: { type: 'string', description: 'Cursor for the next page of group members' }, + userGroupsAfter: { type: 'string', description: 'Cursor for the next page of user groups' }, logsAfter: { type: 'string', description: 'Cursor for the next page of System Log events' }, appsAfter: { type: 'string', description: 'Cursor for the next page of applications' }, appUsersAfter: { @@ -1268,6 +1302,7 @@ export const OktaBlock: BlockConfig = { deactivated: { type: 'boolean', description: 'Whether user was deactivated' }, suspended: { type: 'boolean', description: 'Whether user was suspended' }, unsuspended: { type: 'boolean', description: 'Whether user was unsuspended' }, + unlocked: { type: 'boolean', description: 'Whether user was unlocked' }, activated: { type: 'string', description: 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/otter.ts b/apps/sim/blocks/blocks/otter.ts index 47b82d27654..7af188a053b 100644 --- a/apps/sim/blocks/blocks/otter.ts +++ b/apps/sim/blocks/blocks/otter.ts @@ -1,6 +1,6 @@ import { OtterIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, withSavedCredential } from '@/blocks/utils' import { getTrigger } from '@/triggers' const CONVERSATION_ID_OPERATIONS = ['get_conversation', 'get_conversation_audio'] @@ -205,13 +205,13 @@ export const OtterBlock: BlockConfig = { ], config: { tool: (params) => `otter_${params.operation}`, - params: (params) => { + params: (params, context) => { const result: Record = {} if (params.limit !== undefined && params.limit !== null && params.limit !== '') { result.limit = Number(params.limit) } if ( - params.operation === 'list_conversations' && + mapperOperation(params, context) === 'list_conversations' && params.includeShared !== undefined && params.includeShared !== null && params.includeShared !== '' 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/pagerduty.ts b/apps/sim/blocks/blocks/pagerduty.ts index 7dc5ad95d49..388e8f75d33 100644 --- a/apps/sim/blocks/blocks/pagerduty.ts +++ b/apps/sim/blocks/blocks/pagerduty.ts @@ -1,6 +1,6 @@ import { PagerDutyIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, withSavedCredential } from '@/blocks/utils' import { getTrigger } from '@/triggers' export const PagerDutyBlock: BlockConfig = { @@ -744,6 +744,55 @@ export const PagerDutyBlock: BlockConfig = { }, mode: 'advanced', }, + { + id: 'eventTimestamp', + title: 'Timestamp', + type: 'short-input', + placeholder: 'When the event was detected (ISO 8601, e.g., 2024-01-01T00:00:00Z)', + condition: { + field: 'operation', + value: 'send_event', + and: { field: 'eventAction', value: 'trigger' }, + }, + mode: 'advanced', + wandConfig: { + enabled: true, + prompt: + 'Generate an ISO 8601 timestamp. Return ONLY the timestamp string - no explanations, no extra text.', + generationType: 'timestamp', + }, + }, + { + id: 'eventCustomDetails', + title: 'Custom Details', + type: 'code', + language: 'json', + placeholder: '{\n "region": "us-east-1",\n "error_rate": 0.42\n}', + condition: { + field: 'operation', + value: 'send_event', + and: { field: 'eventAction', value: 'trigger' }, + }, + mode: 'advanced', + }, + { + id: 'includeTotal', + title: 'Include Total Count', + type: 'switch', + condition: { + field: 'operation', + value: [ + 'list_incidents', + 'list_incident_alerts', + 'list_services', + 'list_oncalls', + 'list_escalation_policies', + 'list_schedules', + 'list_users', + ], + }, + mode: 'advanced', + }, ...getTrigger('pagerduty_incident_triggered').subBlocks, ...getTrigger('pagerduty_incident_acknowledged').subBlocks, ...getTrigger('pagerduty_incident_resolved').subBlocks, @@ -772,10 +821,10 @@ export const PagerDutyBlock: BlockConfig = { ], config: { tool: (params) => `pagerduty_${params.operation}`, - params: (params) => { + params: (params, context) => { const result: Record = {} - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'list_incidents': if (params.statuses) result.statuses = params.statuses if (params.listUrgencies) result.urgencies = params.listUrgencies @@ -875,6 +924,8 @@ export const PagerDutyBlock: BlockConfig = { if (params.eventComponent) result.component = params.eventComponent if (params.eventGroup) result.group = params.eventGroup if (params.eventClass) result.class = params.eventClass + if (params.eventTimestamp) result.timestamp = params.eventTimestamp + if (params.eventCustomDetails) result.customDetails = params.eventCustomDetails break } @@ -950,6 +1001,9 @@ export const PagerDutyBlock: BlockConfig = { eventComponent: { type: 'string', description: 'Event component' }, eventGroup: { type: 'string', description: 'Event group' }, eventClass: { type: 'string', description: 'Event class' }, + eventTimestamp: { type: 'string', description: 'Event detection time (ISO 8601)' }, + eventCustomDetails: { type: 'json', description: 'Additional event details object' }, + includeTotal: { type: 'boolean', description: 'Populate the total count on list operations' }, }, outputs: { diff --git a/apps/sim/blocks/blocks/parallel.test.ts b/apps/sim/blocks/blocks/parallel.test.ts new file mode 100644 index 00000000000..2fe1530b226 --- /dev/null +++ b/apps/sim/blocks/blocks/parallel.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from 'vitest' +import { ParallelBlock } from '@/blocks/blocks/parallel' + +const blockParams = ParallelBlock.tools.config?.params +if (!blockParams) throw new Error('ParallelBlock has no params mapper') + +describe('ParallelBlock', () => { + it('maps an agent search call, whose operation arrives only in context', () => { + const args: Record = { + objective: 'When was the UN founded?', + include_domains: 'un.org', + } + const result = { + ...args, + ...blockParams(args, { operation: 'search' }), + } + + expect(result.search_queries).toBe('When was the UN founded?') + expect(result.include_domains).toBe('un.org') + }) +}) diff --git a/apps/sim/blocks/blocks/parallel.ts b/apps/sim/blocks/blocks/parallel.ts index 540f567f121..33616fe7c5b 100644 --- a/apps/sim/blocks/blocks/parallel.ts +++ b/apps/sim/blocks/blocks/parallel.ts @@ -1,5 +1,6 @@ import { ParallelIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' export const ParallelBlock: BlockConfig = { type: 'parallel_ai', @@ -220,9 +221,9 @@ export const ParallelBlock: BlockConfig = { return 'parallel_search' } }, - params: (params) => { + params: (params, context) => { const result: Record = {} - const operation = params.operation + const operation = mapperOperation(params, context) if (operation === 'search') { if (!params.search_queries && params.objective) { @@ -233,8 +234,14 @@ export const ParallelBlock: BlockConfig = { if (params.max_chars_per_result) { result.max_chars_per_result = Number(params.max_chars_per_result) } - result.include_domains = params.search_include_domains || undefined - result.exclude_domains = params.search_exclude_domains || undefined + result.include_domains = + params.search_include_domains || + toolCallArg(context, params.include_domains) || + undefined + result.exclude_domains = + params.search_exclude_domains || + toolCallArg(context, params.exclude_domains) || + undefined } if (operation === 'extract') { diff --git a/apps/sim/blocks/blocks/peopledatalabs.test.ts b/apps/sim/blocks/blocks/peopledatalabs.test.ts new file mode 100644 index 00000000000..08d45e4f620 --- /dev/null +++ b/apps/sim/blocks/blocks/peopledatalabs.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'vitest' +import { PeopleDataLabsBlock } from '@/blocks/blocks/peopledatalabs' +import type { BlockToolParamsContext } from '@/blocks/types' + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = PeopleDataLabsBlock.tools.config?.params + if (!mapper) throw new Error('People Data Labs block has no params mapper') + return { ...params, ...mapper(params, context) } +} + +describe('People Data Labs tool calls', () => { + it('keeps the model company identifiers and likelihood on Company Enrich', () => { + const result = mapParams( + { apiKey: 'k', name: 'Acme', website: 'acme.com', min_likelihood: 6 }, + { operation: 'pdl_company_enrich' } + ) + expect(result).toMatchObject({ name: 'Acme', website: 'acme.com', min_likelihood: 6 }) + }) + + it('keeps the model size on Autocomplete', () => { + const result = mapParams( + { apiKey: 'k', field: 'company', text: 'acm', size: 5 }, + { operation: 'pdl_autocomplete' } + ) + expect(result.size).toBe(5) + }) +}) diff --git a/apps/sim/blocks/blocks/peopledatalabs.ts b/apps/sim/blocks/blocks/peopledatalabs.ts index f5f6ec9ba7d..c66c6d0ae44 100644 --- a/apps/sim/blocks/blocks/peopledatalabs.ts +++ b/apps/sim/blocks/blocks/peopledatalabs.ts @@ -1,6 +1,7 @@ import { PeopleDataLabsIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' /** Mutually exclusive person identifiers — first one supplied is the match key. */ const PERSON_MATCH_FIELD = ['email', 'profile', 'phone', 'first_name'] as const @@ -492,9 +493,9 @@ export const PeopleDataLabsBlock: BlockConfig = { return 'pdl_person_enrich' } }, - params: (params) => { + params: (params, context) => { const result: Record = { ...params } - const op = params.operation + const op = mapperOperation(params, context) // Strip alternate-operation aliases so stale values from prior operations // can't leak into the current request. @@ -554,9 +555,8 @@ export const PeopleDataLabsBlock: BlockConfig = { // accept `size` at all. result.size = undefined if (op === 'pdl_autocomplete') { - if (params.autocomplete_size !== undefined) { - result.size = Number(params.autocomplete_size) - } + const size = params.autocomplete_size ?? toolCallArg(context, params.size) + if (size !== undefined) result.size = Number(size) } else if (op === 'pdl_person_search' || op === 'pdl_company_search') { if (params.size !== undefined) result.size = Number(params.size) } diff --git a/apps/sim/blocks/blocks/perplexity.test.ts b/apps/sim/blocks/blocks/perplexity.test.ts new file mode 100644 index 00000000000..5fb993d7ce3 --- /dev/null +++ b/apps/sim/blocks/blocks/perplexity.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from 'vitest' +import { PerplexityBlock } from '@/blocks/blocks/perplexity' +import type { BlockToolParamsContext } from '@/blocks/types' + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = PerplexityBlock.tools.config?.params + if (!mapper) throw new Error('Perplexity block has no params mapper') + return { ...params, ...mapper(params, context) } +} + +describe('Perplexity tool calls', () => { + it('keeps a model temperature of 0 on Chat', () => { + const result = mapParams( + { apiKey: 'k', content: 'q', temperature: 0 }, + { operation: 'perplexity_chat' } + ) + expect(result.temperature).toBe(0) + }) + + it('keeps a model domain filter array on Search', () => { + const result = mapParams( + { apiKey: 'k', query: 'q', search_domain_filter: ['nature.com', ' science.org '] }, + { operation: 'perplexity_search' } + ) + expect(result.search_domain_filter).toEqual(['nature.com', 'science.org']) + }) +}) + +describe('Perplexity canvas', () => { + it('sends a Temperature of 0 on Chat', () => { + const result = mapParams({ + operation: 'perplexity_chat', + apiKey: 'k', + content: 'q', + temperature: 0, + }) + expect(result.temperature).toBe(0) + }) +}) diff --git a/apps/sim/blocks/blocks/perplexity.ts b/apps/sim/blocks/blocks/perplexity.ts index 777973ea5eb..175bbcc45c3 100644 --- a/apps/sim/blocks/blocks/perplexity.ts +++ b/apps/sim/blocks/blocks/perplexity.ts @@ -1,5 +1,6 @@ import { PerplexityIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' +import { mapperOperation } from '@/blocks/utils' export const PerplexityBlock: BlockConfig = { type: 'perplexity', @@ -202,16 +203,16 @@ Return ONLY the date string in MM/DD/YYYY format - no explanations, no quotes, n return 'perplexity_chat' } }, - params: (params) => { - if (params.operation === 'perplexity_search') { - // Process domain filter from comma-separated string to array - let domainFilter: string[] | undefined - if (params.search_domain_filter && typeof params.search_domain_filter === 'string') { - domainFilter = params.search_domain_filter - .split(',') - .map((d) => d.trim()) - .filter((d) => d.length > 0) - } + params: (params, context) => { + if (mapperOperation(params, context) === 'perplexity_search') { + // The block takes a comma-separated string; a tool call already sends an array. + const rawDomains: unknown[] | undefined = + params.search_domain_filter && typeof params.search_domain_filter === 'string' + ? params.search_domain_filter.split(',') + : Array.isArray(params.search_domain_filter) + ? params.search_domain_filter + : undefined + const domainFilter = rawDomains?.map((d) => String(d).trim()).filter((d) => d.length > 0) const searchParams = { apiKey: params.apiKey, @@ -237,7 +238,12 @@ Return ONLY the date string in MM/DD/YYYY format - no explanations, no quotes, n content: params.content, systemPrompt: params.systemPrompt, max_tokens: params.max_tokens ? Number.parseInt(params.max_tokens) : undefined, - temperature: params.temperature ? Number.parseFloat(params.temperature) : undefined, + temperature: + params.temperature === 0 + ? 0 + : params.temperature + ? Number.parseFloat(params.temperature) + : undefined, } return chatParams diff --git a/apps/sim/blocks/blocks/persona.test.ts b/apps/sim/blocks/blocks/persona.test.ts new file mode 100644 index 00000000000..c0ee154c2b2 --- /dev/null +++ b/apps/sim/blocks/blocks/persona.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest' +import { PersonaBlock } from '@/blocks/blocks/persona' +import type { BlockToolParamsContext } from '@/blocks/types' + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = PersonaBlock.tools.config?.params + if (!mapper) throw new Error('Persona block has no params mapper') + return { ...params, ...mapper(params, context) } +} + +describe('Persona tool calls', () => { + it('normalizes the stored CSV file on Import Accounts', () => { + const file = { name: 'accounts.csv', key: 'workspace/accounts.csv', size: 10 } + const result = mapParams( + { apiKey: 'k', file: JSON.stringify(file) }, + { operation: 'import_accounts' } + ) + expect(result.file).toEqual(file) + }) +}) diff --git a/apps/sim/blocks/blocks/persona.ts b/apps/sim/blocks/blocks/persona.ts index fddf90d4717..32a5414b8b7 100644 --- a/apps/sim/blocks/blocks/persona.ts +++ b/apps/sim/blocks/blocks/persona.ts @@ -1,6 +1,6 @@ import { PersonaIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' -import { normalizeFileInput, withSavedCredential } from '@/blocks/utils' +import { mapperOperation, normalizeFileInput, withSavedCredential } from '@/blocks/utils' /** Canonical basic/advanced pair for the account importer's CSV. */ const IMPORT_FILE_FIELD = ['importFile', 'importFileRef'] as const @@ -519,10 +519,10 @@ export const PersonaBlock: BlockConfig = { ], config: { tool: (params) => `persona_${params.operation || 'create_inquiry'}`, - params: (params) => { + params: (params, context) => { const result: Record = {} - if (params.operation === 'import_accounts') { + if (mapperOperation(params, context) === 'import_accounts') { const file = normalizeFileInput(params.file, { single: true }) if (!file) { throw new Error('A CSV file is required to import accounts') diff --git a/apps/sim/blocks/blocks/pitchbook.test.ts b/apps/sim/blocks/blocks/pitchbook.test.ts new file mode 100644 index 00000000000..fce58c4fe40 --- /dev/null +++ b/apps/sim/blocks/blocks/pitchbook.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from 'vitest' +import { PitchBookBlock } from '@/blocks/blocks/pitchbook' +import type { BlockToolParamsContext } from '@/blocks/types' + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = PitchBookBlock.tools.config?.params + if (!mapper) throw new Error('PitchBook block has no params mapper') + return { ...params, ...mapper(params, context) } +} + +describe('PitchBook tool calls', () => { + it('keeps the model pbId on a profile lookup', () => { + const result = mapParams({ apiKey: 'k', pbId: '10618-03' }, { operation: 'company_bio' }) + expect(result.pbId).toBe('10618-03') + }) + + it('keeps the model search filters on the owning search', () => { + const result = mapParams( + { apiKey: 'k', country: 'US', dealType: 'VC' }, + { operation: 'deal_search' } + ) + expect(result).toMatchObject({ country: 'US', dealType: 'VC' }) + }) +}) diff --git a/apps/sim/blocks/blocks/pitchbook.ts b/apps/sim/blocks/blocks/pitchbook.ts index bfd41f5aae5..da5663ca64d 100644 --- a/apps/sim/blocks/blocks/pitchbook.ts +++ b/apps/sim/blocks/blocks/pitchbook.ts @@ -3,6 +3,7 @@ import { getErrorMessage } from '@sim/utils/errors' import { PitchBookIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' /** * Search subblock ids are prefixed per entity family because subblock ids must @@ -1906,9 +1907,9 @@ export const PitchBookBlock: BlockConfig = { } return `pitchbook_${operation}` }, - params: (params) => { + params: (params, context) => { const { additionalFilters, articleIds, page, perPage, trailingRange, ...rest } = params - const operation = String(params.operation ?? '') + const operation = mapperOperation(params, context) const mapped: Record = { ...rest } // Collapse only the ID subblock this operation owns onto `pbId`, clearing @@ -1916,7 +1917,10 @@ export const PitchBookBlock: BlockConfig = { for (const id of ID_SUBBLOCK_IDS) mapped[id] = undefined const idSubBlock = ID_SUBBLOCK_FOR_OPERATION[operation] const idValue = idSubBlock ? params[idSubBlock] : undefined - mapped.pbId = typeof idValue === 'string' && idValue !== '' ? idValue : undefined + mapped.pbId = + typeof idValue === 'string' && idValue !== '' + ? idValue + : toolCallArg(context, params.pbId) // Rename the prefixed filter subblocks onto their PitchBook param names, // dropping any that belong to a different operation (see the table's TSDoc). @@ -1926,7 +1930,8 @@ export const PitchBookBlock: BlockConfig = { const value = mapped[subBlockId] mapped[subBlockId] = undefined if (owner !== operation) continue - mapped[param] = value === undefined || value === '' ? undefined : value + mapped[param] = + value === undefined || value === '' ? toolCallArg(context, params[param]) : value } const parseJson = (raw: unknown, label: string): unknown => { diff --git a/apps/sim/blocks/blocks/plane.test.ts b/apps/sim/blocks/blocks/plane.test.ts new file mode 100644 index 00000000000..862ed4bb1ab --- /dev/null +++ b/apps/sim/blocks/blocks/plane.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from 'vitest' +import { PlaneBlock } from '@/blocks/blocks/plane' +import type { BlockToolParamsContext } from '@/blocks/types' + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = PlaneBlock.tools.config?.params + if (!mapper) throw new Error('Plane block has no params mapper') + return { ...params, ...mapper(params, context) } +} + +describe('Plane tool calls', () => { + it('coerces the fields of the called operation, not List Projects', () => { + const result = mapParams( + { apiKey: 'k', workspace_slug: 'w', project_id: 'p', name: 'Sprint', sort_order: '5' }, + { operation: 'plane_create_cycle' } + ) + expect(result.sort_order).toBe(5) + }) +}) diff --git a/apps/sim/blocks/blocks/plane.ts b/apps/sim/blocks/blocks/plane.ts index 3c6dd503d61..7c62ad0112f 100644 --- a/apps/sim/blocks/blocks/plane.ts +++ b/apps/sim/blocks/blocks/plane.ts @@ -1,7 +1,7 @@ import { PlaneIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, withSavedCredential } from '@/blocks/utils' import { getTrigger } from '@/triggers' interface PlaneOperationField { @@ -4189,8 +4189,8 @@ export const PlaneBlock: BlockConfig = { ], config: { tool: (params) => String(params.operation || 'plane_list_projects'), - params: (params) => { - const operation = String(params.operation || 'plane_list_projects') + params: (params, context) => { + const operation = mapperOperation(params, context) || 'plane_list_projects' const result: Record = { apiKey: params.apiKey, baseUrl: params.baseUrl, diff --git a/apps/sim/blocks/blocks/planetscale.test.ts b/apps/sim/blocks/blocks/planetscale.test.ts new file mode 100644 index 00000000000..29d6d5cff73 --- /dev/null +++ b/apps/sim/blocks/blocks/planetscale.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from 'vitest' +import { PlanetScaleBlock } from '@/blocks/blocks/planetscale' + +const mapParams = PlanetScaleBlock.tools.config?.params +if (!mapParams) { + throw new Error('PlanetScale block must define tools.config.params') +} + +/** + * On an agent tool call the operation arrives only on `context` and the model sends the tool's + * `state` param, which the block collects as `backupState`, `deployRequestState`, or `reviewState`. + */ +describe('PlanetScale block agent tool calls', () => { + it('keeps the state filter the model sent', () => { + const args = { organization: 'org', database: 'db', branch: 'main', state: 'success' } + + const params = { ...args, ...mapParams(args, { operation: 'list_backups' }) } + + expect(params.state).toBe('success') + }) +}) diff --git a/apps/sim/blocks/blocks/planetscale.ts b/apps/sim/blocks/blocks/planetscale.ts index b9fa9557230..11095dd2651 100644 --- a/apps/sim/blocks/blocks/planetscale.ts +++ b/apps/sim/blocks/blocks/planetscale.ts @@ -1,6 +1,6 @@ import { PlanetScaleIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' function optionalBoolean(value: unknown): boolean | undefined { if (value === undefined || value === null || value === '') return undefined @@ -973,29 +973,33 @@ export const PlanetScaleBlock: BlockConfig = { ], config: { tool: (params) => `planetscale_${params.operation}`, - params: (params) => ({ - ...params, - page: optionalNumber(params.page), - perPage: optionalNumber(params.perPage), - production: optionalBoolean(params.production), - safeMigrations: optionalBoolean(params.safeMigrations), - deletionProtected: optionalBoolean(params.deletionProtected), - replicas: optionalNumber(params.replicas), - deleteDescendants: optionalBoolean(params.deleteDescendants), - all: optionalBoolean(params.all), - retentionValue: optionalNumber(params.retentionValue), - emergency: optionalBoolean(params.emergency), - autoCutover: optionalBoolean(params.autoCutover), - autoDeleteBranch: optionalBoolean(params.autoDeleteBranch), - deployRequestNumber: optionalNumber(params.deployRequestNumber), - instantDdl: optionalBoolean(params.instantDdl), - state: - params.operation === 'list_backups' + params: (params, context) => { + const operation = mapperOperation(params, context) + const blockState = + operation === 'list_backups' ? params.backupState - : params.operation === 'list_deploy_requests' + : operation === 'list_deploy_requests' ? params.deployRequestState - : params.reviewState, - }), + : params.reviewState + return { + ...params, + page: optionalNumber(params.page), + perPage: optionalNumber(params.perPage), + production: optionalBoolean(params.production), + safeMigrations: optionalBoolean(params.safeMigrations), + deletionProtected: optionalBoolean(params.deletionProtected), + replicas: optionalNumber(params.replicas), + deleteDescendants: optionalBoolean(params.deleteDescendants), + all: optionalBoolean(params.all), + retentionValue: optionalNumber(params.retentionValue), + emergency: optionalBoolean(params.emergency), + autoCutover: optionalBoolean(params.autoCutover), + autoDeleteBranch: optionalBoolean(params.autoDeleteBranch), + deployRequestNumber: optionalNumber(params.deployRequestNumber), + instantDdl: optionalBoolean(params.instantDdl), + state: blockState ?? toolCallArg(context, params.state) ?? blockState, + } + }, }, }, outputs: { diff --git a/apps/sim/blocks/blocks/polymarket.ts b/apps/sim/blocks/blocks/polymarket.ts index a067e56dab2..909b101f42b 100644 --- a/apps/sim/blocks/blocks/polymarket.ts +++ b/apps/sim/blocks/blocks/polymarket.ts @@ -1,6 +1,7 @@ import { PolymarketIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { IntegrationType } from '@/blocks/types' +import { mapperOperation } from '@/blocks/utils' const MARKET_REF_FIELD = ['marketId', 'marketSlug'] as const const EVENT_REF_FIELD = ['eventId', 'eventSlug'] as const @@ -757,9 +758,8 @@ Return ONLY the Unix timestamp as a number - no explanations, no quotes, no extr return 'polymarket_get_markets' } }, - params: (params) => { + params: (params, context) => { const { - operation, marketSlug, eventSlug, orderEvents, @@ -787,6 +787,7 @@ Return ONLY the Unix timestamp as a number - no explanations, no quotes, no extr holdersMinBalance, ...rest } = params + const operation = mapperOperation(params, context) const cleanParams: Record = {} if (operation === 'get_market' && marketSlug) { diff --git a/apps/sim/blocks/blocks/powerbi.test.ts b/apps/sim/blocks/blocks/powerbi.test.ts new file mode 100644 index 00000000000..987c5441a51 --- /dev/null +++ b/apps/sim/blocks/blocks/powerbi.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest' +import { PowerBIBlock } from '@/blocks/blocks/powerbi' + +/** Runs the mapper the way an agent tool call does: its output spreads over the merged params. */ +function runToolCall(args: Record, operation: string) { + const mapper = PowerBIBlock.tools.config?.params + if (!mapper) throw new Error('Power BI block has no params mapper') + return { ...args, ...mapper(args, { operation }) } +} + +describe('PowerBIBlock tool-call params', () => { + it('keeps and coerces the model list arguments when the operation arrives only in context', () => { + const params = runToolCall( + { top: '25', skip: 5, filter: "contains(name,'Sales')" }, + 'powerbi_list_workspaces' + ) + + expect(params).toMatchObject({ top: 25, skip: 5, filter: "contains(name,'Sales')" }) + }) +}) diff --git a/apps/sim/blocks/blocks/powerbi.ts b/apps/sim/blocks/blocks/powerbi.ts index 772887c7c7b..db2e06f0493 100644 --- a/apps/sim/blocks/blocks/powerbi.ts +++ b/apps/sim/blocks/blocks/powerbi.ts @@ -2,7 +2,7 @@ import { PowerBIIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { parseOptionalNumberInput } from '@/blocks/utils' +import { mapperOperation, parseOptionalNumberInput, toolCallArg } from '@/blocks/utils' const WORKSPACE_FIELD = ['workspaceSelector', 'manualWorkspaceId'] as const const DATASET_FIELD = ['datasetSelector', 'manualDatasetId'] as const @@ -294,29 +294,32 @@ export const PowerBIBlock: BlockConfig = { ], config: { tool: (params) => params.operation, - params: (params) => { - switch (params.operation) { + params: (params, context) => { + switch (mapperOperation(params, context)) { case 'powerbi_list_workspaces': return { top: - parseOptionalNumberInput(params.workspaceTop, 'Maximum workspaces', { - integer: true, - min: 0, - }) ?? 100, + parseOptionalNumberInput( + params.workspaceTop ?? toolCallArg(context, params.top), + 'Maximum workspaces', + { integer: true, min: 0 } + ) ?? 100, skip: - parseOptionalNumberInput(params.workspaceSkip, 'Workspace offset', { - integer: true, - min: 0, - }) ?? 0, - filter: params.workspaceFilter, + parseOptionalNumberInput( + params.workspaceSkip ?? toolCallArg(context, params.skip), + 'Workspace offset', + { integer: true, min: 0 } + ) ?? 0, + filter: params.workspaceFilter ?? toolCallArg(context, params.filter), } case 'powerbi_get_refresh_history': return { top: - parseOptionalNumberInput(params.refreshHistoryTop, 'Maximum refreshes', { - integer: true, - min: 1, - }) ?? 60, + parseOptionalNumberInput( + params.refreshHistoryTop ?? toolCallArg(context, params.top), + 'Maximum refreshes', + { integer: true, min: 1 } + ) ?? 60, } case 'powerbi_execute_query': return { includeNulls: parseIncludeNulls(params.includeNulls) } diff --git a/apps/sim/blocks/blocks/profound.ts b/apps/sim/blocks/blocks/profound.ts index e5e5334dba2..f8e99df8059 100644 --- a/apps/sim/blocks/blocks/profound.ts +++ b/apps/sim/blocks/blocks/profound.ts @@ -1,7 +1,7 @@ import { ProfoundIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, withSavedCredential } from '@/blocks/utils' const CATEGORY_REPORT_OPS = [ 'visibility_report', @@ -439,7 +439,7 @@ export const ProfoundBlock: BlockConfig = { ], config: { tool: (params) => `profound_${params.operation}`, - params: (params) => { + params: (params, context) => { const result: Record = {} const metricsMap: Record = { visibility_report: 'visibilityMetrics', @@ -450,7 +450,7 @@ export const ProfoundBlock: BlockConfig = { query_fanouts: 'fanoutsMetrics', prompt_volume: 'volumeMetrics', } - const metricsField = metricsMap[params.operation as string] + const metricsField = metricsMap[mapperOperation(params, context)] if (metricsField && params[metricsField]) { result.metrics = params[metricsField] } 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/railway.test.ts b/apps/sim/blocks/blocks/railway.test.ts new file mode 100644 index 00000000000..076e24e38d4 --- /dev/null +++ b/apps/sim/blocks/blocks/railway.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from 'vitest' +import { RailwayBlock } from '@/blocks/blocks/railway' + +const mapParams = RailwayBlock.tools.config?.params +if (!mapParams) { + throw new Error('Railway block must define tools.config.params') +} + +/** + * On an agent tool call the operation arrives only on `context`. A yes/no dropdown filled in the + * tool row stays the string `'true'`, which Railway's GraphQL `Boolean` variables reject. + */ +describe('Railway block agent tool calls', () => { + it('sends a dropdown answer from the tool row as a boolean and keeps the model args', () => { + const args = { apiKey: 'token', name: 'my-project', isPublic: false, prDeploys: 'true' } + + const params = { ...args, ...mapParams(args, { operation: 'create_project' }) } + + expect(params).toMatchObject({ name: 'my-project', isPublic: false, prDeploys: true }) + }) +}) diff --git a/apps/sim/blocks/blocks/railway.ts b/apps/sim/blocks/blocks/railway.ts index 3f3d397bc69..d95332ce5e3 100644 --- a/apps/sim/blocks/blocks/railway.ts +++ b/apps/sim/blocks/blocks/railway.ts @@ -1,7 +1,15 @@ import { RailwayIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' + +/** + * Reads a Railway yes/no dropdown (`'true'`/`'false'`, blank for unset) or a boolean a model sent. + */ +function dropdownBoolean(value: unknown): boolean | undefined { + if (typeof value === 'boolean') return value + return value ? value === 'true' : undefined +} export const RailwayBlock: BlockConfig = { type: 'railway', @@ -690,114 +698,110 @@ export const RailwayBlock: BlockConfig = { ], config: { tool: (params) => `railway_${params.operation}`, - params: (params) => { + params: (params, context) => { + const arg = (key: string) => toolCallArg(context, params[key]) + /** The block field, else (on a tool call) the model's arg for the tool param `key`. */ + const field = (value: unknown, key: string) => value ?? arg(key) ?? value const baseParams = { apiKey: params.apiKey, tokenType: params.tokenType, } - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'list_projects': return { ...baseParams, - workspaceId: params.listProjectsWorkspaceId, + workspaceId: field(params.listProjectsWorkspaceId, 'workspaceId'), first: params.first ? Number(params.first) : undefined, after: params.after, } case 'create_project': return { ...baseParams, - name: params.createProjectName, - description: params.createProjectDescription, - workspaceId: params.createProjectWorkspaceId, - isPublic: params.createProjectIsPublic - ? params.createProjectIsPublic === 'true' - : undefined, + name: field(params.createProjectName, 'name'), + description: field(params.createProjectDescription, 'description'), + workspaceId: field(params.createProjectWorkspaceId, 'workspaceId'), + isPublic: + dropdownBoolean(params.createProjectIsPublic) ?? dropdownBoolean(arg('isPublic')), defaultEnvironmentName: params.defaultEnvironmentName, - prDeploys: params.prDeploys ? params.prDeploys === 'true' : undefined, + prDeploys: dropdownBoolean(params.prDeploys), } case 'update_project': return { ...baseParams, - projectId: params.updateProjectId, - name: params.updateProjectName, - description: params.updateProjectDescription, - isPublic: params.updateProjectIsPublic - ? params.updateProjectIsPublic === 'true' - : undefined, - prDeploys: params.updateProjectPrDeploys - ? params.updateProjectPrDeploys === 'true' - : undefined, + projectId: field(params.updateProjectId, 'projectId'), + name: field(params.updateProjectName, 'name'), + description: field(params.updateProjectDescription, 'description'), + isPublic: + dropdownBoolean(params.updateProjectIsPublic) ?? dropdownBoolean(arg('isPublic')), + prDeploys: + dropdownBoolean(params.updateProjectPrDeploys) ?? dropdownBoolean(arg('prDeploys')), } case 'delete_project': return { ...baseParams, - projectId: params.deleteProjectId, + projectId: field(params.deleteProjectId, 'projectId'), } case 'transfer_project': return { ...baseParams, - projectId: params.transferProjectId, + projectId: field(params.transferProjectId, 'projectId'), workspaceId: params.workspaceId, } case 'list_project_members': return { ...baseParams, - projectId: params.membersProjectId, + projectId: field(params.membersProjectId, 'projectId'), } case 'create_environment': return { ...baseParams, - projectId: params.createEnvironmentProjectId, - name: params.environmentName, + projectId: field(params.createEnvironmentProjectId, 'projectId'), + name: field(params.environmentName, 'name'), sourceEnvironmentId: params.sourceEnvironmentId, - ephemeral: params.ephemeral ? params.ephemeral === 'true' : undefined, - skipInitialDeploys: params.skipInitialDeploys - ? params.skipInitialDeploys === 'true' - : undefined, - stageInitialChanges: params.stageInitialChanges - ? params.stageInitialChanges === 'true' - : undefined, + ephemeral: dropdownBoolean(params.ephemeral), + skipInitialDeploys: dropdownBoolean(params.skipInitialDeploys), + stageInitialChanges: dropdownBoolean(params.stageInitialChanges), } case 'delete_environment': return { ...baseParams, - environmentId: params.deleteEnvironmentId, + environmentId: field(params.deleteEnvironmentId, 'environmentId'), } case 'get_project': return { ...baseParams, - projectId: params.detailProjectId, + projectId: field(params.detailProjectId, 'projectId'), } case 'list_deployments': return { ...baseParams, - projectId: params.deploymentProjectId, - serviceId: params.deploymentServiceId, - environmentId: params.deploymentEnvironmentId, - first: params.deploymentFirst ? Number(params.deploymentFirst) : undefined, - after: params.deploymentAfter, + projectId: field(params.deploymentProjectId, 'projectId'), + serviceId: field(params.deploymentServiceId, 'serviceId'), + environmentId: field(params.deploymentEnvironmentId, 'environmentId'), + first: params.deploymentFirst ? Number(params.deploymentFirst) : arg('first'), + after: field(params.deploymentAfter, 'after'), } case 'deploy_service': return { ...baseParams, - serviceId: params.deployServiceId, - environmentId: params.deployEnvironmentId, - commitSha: params.deployCommitSha, + serviceId: field(params.deployServiceId, 'serviceId'), + environmentId: field(params.deployEnvironmentId, 'environmentId'), + commitSha: field(params.deployCommitSha, 'commitSha'), } case 'create_service': return { ...baseParams, - projectId: params.createServiceProjectId, - name: params.createServiceName, - repo: params.createServiceRepo, - image: params.createServiceImage, - branch: params.createServiceBranch, + projectId: field(params.createServiceProjectId, 'projectId'), + name: field(params.createServiceName, 'name'), + repo: field(params.createServiceRepo, 'repo'), + image: field(params.createServiceImage, 'image'), + branch: field(params.createServiceBranch, 'branch'), } case 'delete_service': return { ...baseParams, - serviceId: params.deleteServiceId, + serviceId: field(params.deleteServiceId, 'serviceId'), } case 'get_deployment': return { @@ -818,32 +822,32 @@ export const RailwayBlock: BlockConfig = { return { ...baseParams, deploymentId: params.deploymentId, - limit: params.logsLimit ? Number(params.logsLimit) : undefined, + limit: params.logsLimit ? Number(params.logsLimit) : arg('limit'), } case 'list_variables': return { ...baseParams, - projectId: params.variablesProjectId, - environmentId: params.variablesEnvironmentId, - serviceId: params.variablesServiceId, + projectId: field(params.variablesProjectId, 'projectId'), + environmentId: field(params.variablesEnvironmentId, 'environmentId'), + serviceId: field(params.variablesServiceId, 'serviceId'), } case 'upsert_variable': return { ...baseParams, - projectId: params.upsertProjectId, - environmentId: params.upsertEnvironmentId, - serviceId: params.upsertServiceId, - name: params.variableName, - value: params.variableValue, - skipDeploys: params.skipDeploys ? params.skipDeploys === 'true' : undefined, + projectId: field(params.upsertProjectId, 'projectId'), + environmentId: field(params.upsertEnvironmentId, 'environmentId'), + serviceId: field(params.upsertServiceId, 'serviceId'), + name: field(params.variableName, 'name'), + value: field(params.variableValue, 'value'), + skipDeploys: dropdownBoolean(params.skipDeploys), } case 'delete_variable': return { ...baseParams, - projectId: params.deleteVariableProjectId, - environmentId: params.deleteVariableEnvironmentId, - serviceId: params.deleteVariableServiceId, - name: params.deleteVariableName, + projectId: field(params.deleteVariableProjectId, 'projectId'), + environmentId: field(params.deleteVariableEnvironmentId, 'environmentId'), + serviceId: field(params.deleteVariableServiceId, 'serviceId'), + name: field(params.deleteVariableName, 'name'), } default: return baseParams diff --git a/apps/sim/blocks/blocks/ramp.ts b/apps/sim/blocks/blocks/ramp.ts index 3d4f0e7d23b..15849684e14 100644 --- a/apps/sim/blocks/blocks/ramp.ts +++ b/apps/sim/blocks/blocks/ramp.ts @@ -254,11 +254,14 @@ export const RampBlock: BlockConfig = { { label: 'Init', id: 'INIT' }, { label: 'Manually Reimbursed', id: 'MANUALLY_REIMBURSED' }, { label: 'Missing Ach', id: 'MISSING_ACH' }, + { label: 'Payroll Failed', id: 'PAYROLL_FAILED' }, + { label: 'Payroll Submitted', id: 'PAYROLL_SUBMITTED' }, { label: 'Pending', id: 'PENDING' }, { label: 'Processing', id: 'PROCESSING' }, { label: 'Push Payment Failed', id: 'PUSH_PAYMENT_FAILED' }, { label: 'Push Payment Initiated', id: 'PUSH_PAYMENT_INITIATED' }, { label: 'Reimbursed', id: 'REIMBURSED' }, + { label: 'Reimbursed Via Payroll', id: 'REIMBURSED_VIA_PAYROLL' }, { label: 'Reimbursed Via Push', id: 'REIMBURSED_VIA_PUSH' }, { label: 'Rejected', id: 'REJECTED' }, ], diff --git a/apps/sim/blocks/blocks/rds.ts b/apps/sim/blocks/blocks/rds.ts index 89799071952..6df9d3bf6da 100644 --- a/apps/sim/blocks/blocks/rds.ts +++ b/apps/sim/blocks/blocks/rds.ts @@ -2,7 +2,7 @@ import { getErrorMessage } from '@sim/utils/errors' import { RDSIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, withSavedCredential } from '@/blocks/utils' export const RDSBlock: BlockConfig = { type: 'rds', @@ -451,8 +451,9 @@ Return ONLY valid JSON - no explanations, no markdown code blocks.`, throw new Error(`Invalid RDS operation: ${params.operation}`) } }, - params: (params) => { - const { operation, data, conditions, schema, engine, parameters, ...rest } = params + params: (params, context) => { + const operation = mapperOperation(params, context) + const { data, conditions, schema, engine, parameters, ...rest } = params // Parse JSON fields const parseJson = (value: unknown, fieldName: string) => { diff --git a/apps/sim/blocks/blocks/reddit.test.ts b/apps/sim/blocks/blocks/reddit.test.ts new file mode 100644 index 00000000000..4c642884d95 --- /dev/null +++ b/apps/sim/blocks/blocks/reddit.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from 'vitest' +import { RedditBlock } from '@/blocks/blocks/reddit' + +/** Runs the mapper the way an agent tool call does: its output spreads over the merged params. */ +function runToolCall(args: Record, operation: string) { + const mapper = RedditBlock.tools.config?.params + if (!mapper) throw new Error('Reddit block has no params mapper') + return { ...args, ...mapper(args, { operation }) } +} + +describe('RedditBlock tool-call params', () => { + it('keeps the model time window for controversial posts', () => { + const params = runToolCall({ subreddit: 'news', time: 'week', limit: 10 }, 'get_controversial') + + expect(params).toMatchObject({ subreddit: 'news', time: 'week', limit: 10 }) + }) + + it('submits the model post body and typed flags without the block-only post type', () => { + const params = runToolCall( + { subreddit: 'test', title: 'Hello', text: 'Body', nsfw: true, send_replies: false }, + 'submit_post' + ) + + expect(params).toMatchObject({ + subreddit: 'test', + title: 'Hello', + text: 'Body', + nsfw: true, + spoiler: false, + send_replies: false, + }) + }) + + it('keeps the model vote direction', () => { + const params = runToolCall({ id: 't3_abc', dir: -1 }, 'vote') + + expect(params).toMatchObject({ id: 't3_abc', dir: -1 }) + }) +}) diff --git a/apps/sim/blocks/blocks/reddit.ts b/apps/sim/blocks/blocks/reddit.ts index 3e27c778d67..fa1bd85f183 100644 --- a/apps/sim/blocks/blocks/reddit.ts +++ b/apps/sim/blocks/blocks/reddit.ts @@ -2,6 +2,7 @@ import { RedditIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { isToolCall, mapperOperation } from '@/blocks/utils' const REPORT_REASON_FIELD = ['reportReason', 'reportOtherReason'] as const @@ -1080,17 +1081,36 @@ Return ONLY the message content - no meta-commentary.`, } return toolMap[operation] || 'reddit_get_posts' }, - params: (inputs) => { - const operation = inputs.operation || 'get_posts' + params: (inputs, context) => { + const operation = mapperOperation(inputs, context) || 'get_posts' const { oauthCredential } = inputs + /** + * The block field's value, or on a tool call with that field blank, the model's arg under the + * tool's own param name. Canvas runs get the block field unchanged. + */ + const pick = (dedicated: unknown, toolParam: string): unknown => + isToolCall(context) && (dedicated === undefined || dedicated === null || dedicated === '') + ? inputs[toolParam] + : dedicated + const int = (value: unknown): number | undefined => + value ? Number.parseInt(String(value)) : undefined + const flag = (dedicated: unknown, toolParam: string): boolean => { + const value = pick(dedicated, toolParam) + return value === true || value === 'true' + } + const optionalFlag = (dedicated: unknown, toolParam: string): boolean | undefined => { + const value = pick(dedicated, toolParam) + return value !== undefined ? value === true || value === 'true' : undefined + } + if (operation === 'get_posts') { return { subreddit: inputs.subreddit, sort: inputs.sort, time: inputs.sort === 'top' || inputs.sort === 'controversial' ? inputs.time : undefined, - limit: inputs.limit ? Number.parseInt(inputs.limit) : undefined, + limit: int(inputs.limit), after: inputs.after || undefined, before: inputs.before || undefined, oauthCredential, @@ -1101,10 +1121,10 @@ Return ONLY the message content - no meta-commentary.`, return { postId: inputs.postId, subreddit: inputs.subreddit, - sort: inputs.commentSort, - limit: inputs.commentLimit ? Number.parseInt(inputs.commentLimit) : undefined, - depth: inputs.commentDepth ? Number.parseInt(inputs.commentDepth) : undefined, - comment: inputs.commentFocus || undefined, + sort: pick(inputs.commentSort, 'sort'), + limit: int(pick(inputs.commentLimit, 'limit')), + depth: int(pick(inputs.commentDepth, 'depth')), + comment: pick(inputs.commentFocus, 'comment') || undefined, oauthCredential, } } @@ -1112,10 +1132,8 @@ Return ONLY the message content - no meta-commentary.`, if (operation === 'get_controversial') { return { subreddit: inputs.subreddit, - time: inputs.controversialTime, - limit: inputs.controversialLimit - ? Number.parseInt(inputs.controversialLimit) - : undefined, + time: pick(inputs.controversialTime, 'time'), + limit: int(pick(inputs.controversialLimit, 'limit')), after: inputs.after || undefined, before: inputs.before || undefined, oauthCredential, @@ -1125,10 +1143,10 @@ Return ONLY the message content - no meta-commentary.`, if (operation === 'search') { return { subreddit: inputs.subreddit, - query: inputs.searchQuery, - sort: inputs.searchSort, - time: inputs.searchTime, - limit: inputs.searchLimit ? Number.parseInt(inputs.searchLimit) : undefined, + query: pick(inputs.searchQuery, 'query'), + sort: pick(inputs.searchSort, 'sort'), + time: pick(inputs.searchTime, 'time'), + limit: int(pick(inputs.searchLimit, 'limit')), after: inputs.after || undefined, before: inputs.before || undefined, oauthCredential, @@ -1136,71 +1154,71 @@ Return ONLY the message content - no meta-commentary.`, } if (operation === 'submit_post') { + const postTypeUnset = isToolCall(context) && !inputs.postType return { - subreddit: inputs.submitSubreddit, + subreddit: pick(inputs.submitSubreddit, 'subreddit'), title: inputs.title, - text: inputs.postType === 'text' ? inputs.text : undefined, - url: inputs.postType === 'link' ? inputs.url : undefined, - nsfw: inputs.nsfw === 'true', - spoiler: inputs.spoiler === 'true', - send_replies: - inputs.sendReplies !== undefined ? inputs.sendReplies === 'true' : undefined, - flair_id: inputs.flairId || undefined, - flair_text: inputs.flairText || undefined, + text: postTypeUnset || inputs.postType === 'text' ? inputs.text : undefined, + url: postTypeUnset || inputs.postType === 'link' ? inputs.url : undefined, + nsfw: flag(inputs.nsfw, 'nsfw'), + spoiler: flag(inputs.spoiler, 'spoiler'), + send_replies: optionalFlag(inputs.sendReplies, 'send_replies'), + flair_id: pick(inputs.flairId, 'flair_id') || undefined, + flair_text: pick(inputs.flairText, 'flair_text') || undefined, oauthCredential, } } if (operation === 'vote') { return { - id: inputs.voteId, - dir: Number.parseInt(inputs.voteDirection), + id: pick(inputs.voteId, 'id'), + dir: Number.parseInt(String(pick(inputs.voteDirection, 'dir'))), oauthCredential, } } if (operation === 'save') { return { - id: inputs.saveId, - category: inputs.saveCategory || undefined, + id: pick(inputs.saveId, 'id'), + category: pick(inputs.saveCategory, 'category') || undefined, oauthCredential, } } if (operation === 'unsave') { return { - id: inputs.saveId, + id: pick(inputs.saveId, 'id'), oauthCredential, } } if (operation === 'reply') { return { - parent_id: inputs.replyParentId, - text: inputs.replyText, + parent_id: pick(inputs.replyParentId, 'parent_id'), + text: pick(inputs.replyText, 'text'), oauthCredential, } } if (operation === 'edit') { return { - thing_id: inputs.editThingId, - text: inputs.editText, + thing_id: pick(inputs.editThingId, 'thing_id'), + text: pick(inputs.editText, 'text'), oauthCredential, } } if (operation === 'delete') { return { - id: inputs.deleteId, + id: pick(inputs.deleteId, 'id'), oauthCredential, } } if (operation === 'subscribe') { return { - subreddit: inputs.subscribeSubreddit, - action: inputs.subscribeAction, + subreddit: pick(inputs.subscribeSubreddit, 'subreddit'), + action: pick(inputs.subscribeAction, 'action'), oauthCredential, } } @@ -1218,19 +1236,19 @@ Return ONLY the message content - no meta-commentary.`, if (operation === 'send_message') { return { - to: inputs.messageTo, - subject: inputs.messageSubject, - text: inputs.messageText, - from_sr: inputs.messageFromSr || undefined, + to: pick(inputs.messageTo, 'to'), + subject: pick(inputs.messageSubject, 'subject'), + text: pick(inputs.messageText, 'text'), + from_sr: pick(inputs.messageFromSr, 'from_sr') || undefined, oauthCredential, } } if (operation === 'get_messages') { return { - where: inputs.messageWhere, - limit: inputs.messageLimit ? Number.parseInt(inputs.messageLimit) : undefined, - mark: inputs.messageMark !== undefined ? inputs.messageMark === 'true' : undefined, + where: pick(inputs.messageWhere, 'where'), + limit: int(pick(inputs.messageLimit, 'limit')), + mark: optionalFlag(inputs.messageMark, 'mark'), after: inputs.after || undefined, before: inputs.before || undefined, oauthCredential, @@ -1252,14 +1270,15 @@ Return ONLY the message content - no meta-commentary.`, } if (operation === 'get_user_posts' || operation === 'get_user_comments') { + const sort = pick(inputs.userListSort, 'sort') return { - username: inputs.userListUsername, - sort: inputs.userListSort, + username: pick(inputs.userListUsername, 'username'), + sort, time: - inputs.userListSort === 'top' || inputs.userListSort === 'controversial' - ? inputs.userListTime + sort === 'top' || sort === 'controversial' + ? pick(inputs.userListTime, 'time') : undefined, - limit: inputs.userListLimit ? Number.parseInt(inputs.userListLimit) : undefined, + limit: int(pick(inputs.userListLimit, 'limit')), after: inputs.after || undefined, before: inputs.before || undefined, oauthCredential, @@ -1268,8 +1287,8 @@ Return ONLY the message content - no meta-commentary.`, if (operation === 'get_saved') { return { - username: inputs.userListUsername, - limit: inputs.userListLimit ? Number.parseInt(inputs.userListLimit) : undefined, + username: pick(inputs.userListUsername, 'username'), + limit: int(pick(inputs.userListLimit, 'limit')), after: inputs.after || undefined, before: inputs.before || undefined, oauthCredential, @@ -1278,18 +1297,16 @@ Return ONLY the message content - no meta-commentary.`, if (operation === 'get_info') { return { - id: inputs.infoIds, + id: pick(inputs.infoIds, 'id'), oauthCredential, } } if (operation === 'search_subreddits') { return { - q: inputs.searchSubredditsQuery, - sort: inputs.searchSubredditsSort, - limit: inputs.searchSubredditsLimit - ? Number.parseInt(inputs.searchSubredditsLimit) - : undefined, + q: pick(inputs.searchSubredditsQuery, 'q'), + sort: pick(inputs.searchSubredditsSort, 'sort'), + limit: int(pick(inputs.searchSubredditsLimit, 'limit')), after: inputs.after || undefined, before: inputs.before || undefined, oauthCredential, @@ -1298,7 +1315,7 @@ Return ONLY the message content - no meta-commentary.`, if (operation === 'list_my_subreddits') { return { - limit: inputs.listMineLimit ? Number.parseInt(inputs.listMineLimit) : undefined, + limit: int(pick(inputs.listMineLimit, 'limit')), after: inputs.after || undefined, before: inputs.before || undefined, oauthCredential, @@ -1307,30 +1324,30 @@ Return ONLY the message content - no meta-commentary.`, if (operation === 'report') { return { - thing_id: inputs.reportThingId, - reason: inputs.reportReason || undefined, - other_reason: inputs.reportOtherReason || undefined, + thing_id: pick(inputs.reportThingId, 'thing_id'), + reason: pick(inputs.reportReason, 'reason') || undefined, + other_reason: pick(inputs.reportOtherReason, 'other_reason') || undefined, oauthCredential, } } if (operation === 'hide' || operation === 'unhide') { return { - id: inputs.hideId, + id: pick(inputs.hideId, 'id'), oauthCredential, } } if (operation === 'marknsfw' || operation === 'unmarknsfw') { return { - id: inputs.nsfwId, + id: pick(inputs.nsfwId, 'id'), oauthCredential, } } if (operation === 'mark_read') { return { - id: inputs.markReadId, + id: pick(inputs.markReadId, 'id'), oauthCredential, } } @@ -1341,36 +1358,33 @@ Return ONLY the message content - no meta-commentary.`, if (operation === 'mod_approve' || operation === 'lock' || operation === 'unlock') { return { - id: inputs.modThingId, + id: pick(inputs.modThingId, 'id'), oauthCredential, } } if (operation === 'mod_remove') { return { - id: inputs.modThingId, - spam: inputs.removeSpam === 'true', + id: pick(inputs.modThingId, 'id'), + spam: flag(inputs.removeSpam, 'spam'), oauthCredential, } } if (operation === 'mod_distinguish') { return { - id: inputs.modThingId, - how: inputs.distinguishHow, - sticky: - inputs.distinguishSticky !== undefined - ? inputs.distinguishSticky === 'true' - : undefined, + id: pick(inputs.modThingId, 'id'), + how: pick(inputs.distinguishHow, 'how'), + sticky: optionalFlag(inputs.distinguishSticky, 'sticky'), oauthCredential, } } if (operation === 'mod_sticky') { return { - id: inputs.stickyId, - state: inputs.stickyState === 'true', - num: inputs.stickyNum ? Number.parseInt(inputs.stickyNum) : undefined, + id: pick(inputs.stickyId, 'id'), + state: flag(inputs.stickyState, 'state'), + num: int(pick(inputs.stickyNum, 'num')), oauthCredential, } } @@ -1378,7 +1392,7 @@ Return ONLY the message content - no meta-commentary.`, return { subreddit: inputs.subreddit, sort: inputs.sort, - limit: inputs.limit ? Number.parseInt(inputs.limit) : undefined, + limit: int(inputs.limit), oauthCredential, } }, diff --git a/apps/sim/blocks/blocks/resend.test.ts b/apps/sim/blocks/blocks/resend.test.ts new file mode 100644 index 00000000000..ccd59529e31 --- /dev/null +++ b/apps/sim/blocks/blocks/resend.test.ts @@ -0,0 +1,97 @@ +import { describe, expect, it, vi } from 'vitest' +import { ResendBlock, ResendV2Block } from '@/blocks/blocks/resend' +import type { BlockConfig, BlockToolParamsContext } from '@/blocks/types' +import { collectBlockFieldIssues } from '@/serializer/index' + +/** Lint checks fields against the real tool params, which vitest.setup.ts mocks empty. */ +vi.unmock('@/tools/metadata') + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = ResendV2Block.tools.config?.params + if (!mapper) throw new Error('Resend block has no params mapper') + return mapper(params, context) +} + +describe('Resend contact subscription status', () => { + it.each([true, false])('keeps a model-sent boolean unsubscribed=%s on a tool call', (value) => { + expect( + mapParams( + { contactId: 'jane@example.com', unsubscribed: value }, + { operation: 'update_contact' } + ).unsubscribed + ).toBe(value) + }) + + it.each([ + ['true', true], + ['false', false], + ['', undefined], + ])('maps the canvas dropdown value %j to %j', (value, expected) => { + expect( + mapParams({ operation: 'create_contact', email: 'a@example.com', unsubscribed: value }) + .unsubscribed + ).toBe(expected) + }) +}) + +describe('Resend list pagination limit', () => { + it('keeps a model-sent numeric limit on a tool call', () => { + expect(mapParams({ limit: 50 }, { operation: 'list_contacts' }).limit).toBe(50) + }) + + it('turns the canvas text limit into a number and drops a blank one', () => { + expect(mapParams({ operation: 'list_domains', limit: ' 75 ' }).limit).toBe(75) + expect(mapParams({ operation: 'list_domains', limit: '' }).limit).toBeUndefined() + }) +}) + +describe('Resend Create Broadcast recipient', () => { + function missingFields(config: BlockConfig, values: Record) { + const params = { + operation: 'create_broadcast', + broadcastFrom: 'news@example.com', + broadcastSubject: 'Hi', + ...values, + } + const subBlocks = Object.fromEntries( + Object.entries(params).map(([id, value]) => [id, { id, type: 'short-input' as const, value }]) + ) + const block = { + id: 'b1', + type: config.type, + name: 'Resend', + enabled: true, + position: { x: 0, y: 0 }, + subBlocks, + outputs: {}, + data: {}, + } + return collectBlockFieldIssues(block, config, params, { mode: 'lint' }).missingRequiredFields + } + + it.each([ResendBlock, ResendV2Block])( + 'flags Audience ID only when no segment is given', + (config) => { + expect(missingFields(config, { segmentId: '', audienceId: '' })).toContain('Audience ID') + expect(missingFields(config, { segmentId: 'seg_1', audienceId: '' })).not.toContain( + 'Audience ID' + ) + expect(missingFields(config, { segmentId: '', audienceId: 'aud_1' })).not.toContain( + 'Audience ID' + ) + } + ) + + it.each([ResendBlock, ResendV2Block])( + 'publishes Audience ID as required only for the audience operations when no values are known', + (config) => { + const audienceId = config.subBlocks.find((subBlock) => subBlock.id === 'audienceId') + const required = audienceId?.required + if (typeof required !== 'function') throw new Error('Audience ID requirement is not dynamic') + expect(required()).toEqual({ + field: 'operation', + value: ['get_audience', 'delete_audience'], + }) + } + ) +}) diff --git a/apps/sim/blocks/blocks/resend.ts b/apps/sim/blocks/blocks/resend.ts index 6e362217d74..80387b437ad 100644 --- a/apps/sim/blocks/blocks/resend.ts +++ b/apps/sim/blocks/blocks/resend.ts @@ -1,3 +1,4 @@ +import { toBooleanFromInput } from '@sim/utils/coerce' import { ResendIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' @@ -39,7 +40,7 @@ export const ResendBlock: BlockConfig = { delete_audience: [{ text: 'Delete audience', field: 'audienceId', core: true }], create_broadcast: [ 'Draft a broadcast', - { text: 'for audience', field: 'audienceId', core: true }, + { text: 'for', field: ['segmentId', 'audienceId'], core: true }, { text: ', subject', field: 'broadcastSubject' }, { text: ', named', field: 'broadcastName' }, ], @@ -300,6 +301,13 @@ Return ONLY the email body - no explanations, no extra text.`, condition: { field: 'operation', value: 'create_audience' }, required: true, }, + { + id: 'segmentId', + title: 'Segment ID', + type: 'short-input', + placeholder: 'Segment ID (takes precedence over Audience ID)', + condition: { field: 'operation', value: 'create_broadcast' }, + }, { id: 'audienceId', title: 'Audience ID', @@ -309,10 +317,18 @@ Return ONLY the email body - no explanations, no extra text.`, field: 'operation', value: ['get_audience', 'delete_audience', 'create_broadcast'], }, - required: { + /** + * Create Broadcast needs an audience only when no segment is set. Without block values (the + * public catalog, Copilot validation) a segment may still be given, so only the audience + * operations require it. + */ + required: (values) => ({ field: 'operation', - value: ['get_audience', 'delete_audience', 'create_broadcast'], - }, + value: + values && !String(values.segmentId ?? '').trim() + ? ['get_audience', 'delete_audience', 'create_broadcast'] + : ['get_audience', 'delete_audience'], + }), }, { @@ -395,6 +411,23 @@ Return ONLY the email body - no explanations, no extra text.`, }, }, + { + id: 'limit', + title: 'Limit', + type: 'short-input', + placeholder: '20 (max 100)', + condition: { field: 'operation', value: ['list_contacts', 'list_domains'] }, + mode: 'advanced', + }, + { + id: 'after', + title: 'After (Cursor)', + type: 'short-input', + placeholder: 'ID of the last item from the previous page', + condition: { field: 'operation', value: ['list_contacts', 'list_domains'] }, + mode: 'advanced', + }, + ...getTrigger('resend_email_sent').subBlocks, ...getTrigger('resend_email_delivered').subBlocks, ...getTrigger('resend_email_bounced').subBlocks, @@ -430,13 +463,19 @@ Return ONLY the email body - no explanations, no extra text.`, if (operation === 'send_email') return 'resend_send' return `resend_${operation}` }, - params: (params) => { + params: (params, context) => { const { operation, ...rest } = params - if (rest.unsubscribed === undefined || rest.unsubscribed === '') { - rest.unsubscribed = undefined - } else { - rest.unsubscribed = rest.unsubscribed === 'true' + rest.unsubscribed = toBooleanFromInput(rest.unsubscribed) + + // The tool prefers a segment, so a model's segmentId would retarget a row's pinned audience. + if (context?.pinnedParams?.has('audienceId') && !context.pinnedParams.has('segmentId')) { + rest.segmentId = undefined + } + + if (typeof rest.limit === 'string') { + const limit = rest.limit.trim() + rest.limit = limit ? Number(limit) : undefined } return rest @@ -466,6 +505,9 @@ Return ONLY the email body - no explanations, no extra text.`, cancelEmailId: { type: 'string', description: 'Scheduled email ID to cancel' }, audienceName: { type: 'string', description: 'Audience name' }, audienceId: { type: 'string', description: 'Audience ID' }, + segmentId: { type: 'string', description: 'Segment ID for a broadcast' }, + limit: { type: 'number', description: 'Number of items to return when listing (1-100)' }, + after: { type: 'string', description: 'Pagination cursor: ID of the last item already read' }, broadcastFrom: { type: 'string', description: 'Broadcast sender email address' }, broadcastSubject: { type: 'string', description: 'Broadcast subject' }, broadcastHtml: { type: 'string', description: 'Broadcast HTML content' }, @@ -500,7 +542,7 @@ Return ONLY the email body - no explanations, no extra text.`, name: { type: 'string', description: 'Audience or broadcast name' }, audienceId: { type: 'string', description: 'Audience ID (legacy)' }, segmentId: { type: 'string', description: 'Broadcast segment ID (current recipient field)' }, - replyTo: { type: 'string', description: 'Broadcast reply-to email address' }, + replyTo: { type: 'json', description: 'Broadcast reply-to email addresses' }, previewText: { type: 'string', description: 'Broadcast inbox preview text' }, status: { type: 'string', description: 'Broadcast status' }, sentAt: { type: 'string', description: 'Broadcast sent timestamp' }, diff --git a/apps/sim/blocks/blocks/revenuecat.ts b/apps/sim/blocks/blocks/revenuecat.ts index 6bd1f2f227e..1cca0509257 100644 --- a/apps/sim/blocks/blocks/revenuecat.ts +++ b/apps/sim/blocks/blocks/revenuecat.ts @@ -1,6 +1,7 @@ import { RevenueCatIcon } 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' export const RevenueCatBlock: BlockConfig = { @@ -443,13 +444,14 @@ Return ONLY the numeric timestamp, no text.`, ], config: { tool: (params) => `revenuecat_${params.operation}`, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const next: Record = { ...params } - if (params.purchasePlatform && params.operation === 'create_purchase') { + if (params.purchasePlatform && operation === 'create_purchase') { next.platform = params.purchasePlatform } next.purchasePlatform = undefined - if (params.productId && params.operation === 'refund_google_subscription') { + if (params.productId && operation === 'refund_google_subscription') { next.storeTransactionId = params.productId next.productId = undefined } diff --git a/apps/sim/blocks/blocks/rippling.test.ts b/apps/sim/blocks/blocks/rippling.test.ts new file mode 100644 index 00000000000..819bd288c34 --- /dev/null +++ b/apps/sim/blocks/blocks/rippling.test.ts @@ -0,0 +1,167 @@ +import { describe, expect, it } from 'vitest' +import { RipplingBlock } from '@/blocks/blocks/rippling' +import type { BlockToolParamsContext } from '@/blocks/types' + +/** The block's `tools.config.params` mapper; `context` is set on a tool call, absent on the canvas. */ +const buildParams = ( + inputs: Record, + context?: BlockToolParamsContext +): Record => RipplingBlock.tools.config?.params?.(inputs, context) ?? {} + +/** A tool call: model args under the tool's param names, the operation only on `context`. */ +const agentCall = (operation: string, args: Record) => ({ + ...args, + ...buildParams(args, { operation }), +}) + +/** The canvas: serialized block inputs, operation included, merged as `{ ...inputs, ...mapped }`. */ +const canvasRun = (inputs: Record) => ({ ...inputs, ...buildParams(inputs) }) + +describe('RipplingBlock agent tool calls', () => { + it('keeps a model boolean true for all_or_nothing on a bulk update', () => { + const mapped = agentCall('bulk_update_custom_object_records', { + customObjectApiName: 'pet__c', + rowsToUpdate: [{ id: 'r1', name: 'Rex' }], + allOrNothing: true, + }) + expect(mapped.allOrNothing).toBe(true) + }) + + it('keeps model boolean flags on a custom object field update', () => { + const mapped = agentCall('update_custom_object_field', { + customObjectApiName: 'pet__c', + fieldApiName: 'tag__c', + isUnique: true, + enableHistory: true, + }) + expect(mapped).toMatchObject({ isUnique: true, enableHistory: true }) + }) + + it('passes a custom setting data type through instead of parsing it as JSON', () => { + const mapped = agentCall('create_custom_setting', { + displayName: 'Region', + apiName: 'region', + dataType: 'STRING', + stringValue: 'us', + }) + expect(mapped.dataType).toBe('STRING') + }) + + it('keeps a model order_by on a custom object records query', () => { + const mapped = agentCall('query_custom_object_records', { + customObjectApiName: 'pet__c', + orderBy: 'name desc', + }) + expect(mapped.orderBy).toBe('name desc') + }) +}) + +describe('RipplingBlock canvas', () => { + it('drops an advanced filter saved under another operation', () => { + const mapped = canvasRun({ + operation: 'list_companies', + apiKey: 'key', + filter: "status eq 'ACTIVE'", + orderBy: 'name', + }) + expect(mapped.filter).toBeUndefined() + expect(mapped.orderBy).toBe('name') + }) + + it('drops a list Order By saved before switching to a records query', () => { + const mapped = canvasRun({ + operation: 'query_custom_object_records', + apiKey: 'key', + customObjectId: 'pet__c', + orderBy: 'created_at,updated_at desc', + }) + expect(mapped.orderBy).toBeUndefined() + }) + + it('sends the query Order By field as order_by on a records query', () => { + const mapped = canvasRun({ + operation: 'query_custom_object_records', + apiKey: 'key', + customObjectId: 'pet__c', + orderBy: 'created_at,updated_at desc', + queryOrderBy: 'name desc', + }) + expect(mapped.orderBy).toBe('name desc') + }) + + it.each([ + { operation: 'bulk_delete_custom_object_records', flag: 'allOrNothing' }, + { operation: 'create_custom_object_field', flag: 'isUnique' }, + { operation: 'update_custom_object_field', flag: 'enableHistory' }, + { operation: 'trigger_report_run', flag: 'includeObjectIds' }, + { operation: 'trigger_report_run', flag: 'includeTotalRows' }, + ])('sends a $flag left on No as a boolean false on $operation', ({ operation, flag }) => { + expect(canvasRun({ operation, apiKey: 'key', [flag]: 'false' })[flag]).toBe(false) + }) + + it.each([ + { operation: 'create_custom_app', key: 'apiName', field: 'apiName', value: 'my_app' }, + { operation: 'update_custom_app', key: 'apiName', field: 'apiName', value: 'my_app' }, + { + operation: 'create_custom_object_field', + key: 'dataType', + field: 'dataType', + value: '{"type":"TEXT"}', + }, + ])( + 'ignores a custom setting $key left from a setting operation on $operation', + ({ operation, key, field, value }) => { + const mapped = canvasRun({ + operation, + apiKey: 'key', + [field]: value, + settingApiName: 'stale_setting', + settingDataType: 'STRING', + }) + expect(mapped[key]).toEqual(key === 'dataType' ? { type: 'TEXT' } : value) + } + ) + + it('sends the setting API name and data type on a custom setting write', () => { + const mapped = canvasRun({ + operation: 'update_custom_setting', + apiKey: 'key', + id: 'setting-1', + settingApiName: 'region', + settingDataType: 'STRING', + }) + expect(mapped).toMatchObject({ apiName: 'region', dataType: 'STRING' }) + }) +}) + +describe('RipplingBlock custom object field flags', () => { + const flags = ['isUnique', 'enableHistory'] as const + + it.each(flags)('offers No change for %s everywhere except a known create', (id) => { + const subBlock = RipplingBlock.subBlocks.find((candidate) => candidate.id === id) + const options = subBlock?.options + if (typeof options !== 'function') throw new Error(`${id} options are static`) + expect(options({ values: {} })[0]?.id).toBe('') + expect(options({ values: { operation: 'update_custom_object_field' } })[0]?.id).toBe('') + expect(options({ values: { operation: 'create_custom_object_field' } })[0]?.id).toBe('false') + expect(subBlock?.value?.({ operation: 'create_custom_object_field' })).toBe('false') + expect(subBlock?.value?.({ operation: 'update_custom_object_field' })).toBe('') + expect(subBlock?.value?.({})).toBeUndefined() + expect(subBlock?.dependsOn).toEqual(expect.arrayContaining(['operation'])) + }) + + it.each(flags)('sends no %s when an update leaves it on No change', (id) => { + const mapped = canvasRun({ operation: 'update_custom_object_field', apiKey: 'key', [id]: '' }) + expect(mapped).toHaveProperty(id, undefined) + }) + + it.each(['true', 'false'])('keeps sending a saved %s as a boolean on an update', (saved) => { + const mapped = canvasRun({ + operation: 'update_custom_object_field', + apiKey: 'key', + isUnique: saved, + enableHistory: saved, + }) + expect(mapped).toMatchObject({ isUnique: saved === 'true', enableHistory: saved === 'true' }) + }) +}) diff --git a/apps/sim/blocks/blocks/rippling.ts b/apps/sim/blocks/blocks/rippling.ts index 1150340685c..9fa3487ceb2 100644 --- a/apps/sim/blocks/blocks/rippling.ts +++ b/apps/sim/blocks/blocks/rippling.ts @@ -1,7 +1,12 @@ import { RipplingIcon } from '@/components/icons' -import type { BlockConfig, BlockMeta } from '@/blocks/types' +import type { BlockConfig, BlockMeta, SubBlockConfig } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { + isToolCall, + mapperOperation, + parseOptionalBooleanInput, + withSavedCredential, +} from '@/blocks/utils' /** Operations that support the filter query parameter */ const FILTER_OPS = ['list_workers', 'list_business_partners', 'list_supergroups'] as const @@ -62,8 +67,27 @@ const CURSOR_OPS = [ 'list_users', 'list_work_locations', 'query_custom_object_records', + 'list_custom_objects', + 'list_custom_object_fields', + 'list_custom_object_records', + 'list_object_categories', + 'list_supergroups', + 'list_supergroup_members', + 'list_supergroup_inclusion_members', + 'list_supergroup_exclusion_members', ] as const +/** + * Query params each tied to the operations whose tools accept them. The fields are advanced, so the + * serializer keeps a value saved under one operation after the user switches to another. + */ +const QUERY_PARAM_OPS = [ + ['filter', FILTER_OPS], + ['expand', EXPAND_OPS], + ['orderBy', ORDER_BY_OPS], + ['cursor', CURSOR_OPS], +] as const satisfies ReadonlyArray + /** Operations that require a resource ID */ const ID_OPS = [ 'get_worker', @@ -178,6 +202,33 @@ const CUSTOM_OBJECT_FIELD_WRITE_OPS = [ 'update_custom_object_field', ] as const +/** + * A Yes/No custom object field setting. Create defaults to No; every other context (an update, an + * agent tool row with no operation) leads with "No change" so an update does not resend it. + */ +const customObjectFieldFlag = ( + id: 'isUnique' | 'enableHistory', + title: string +): SubBlockConfig => ({ + id, + title, + type: 'dropdown', + options: ({ values } = { values: {} }) => [ + ...(values?.operation === 'create_custom_object_field' ? [] : [{ label: 'No change', id: '' }]), + { label: 'No', id: 'false' }, + { label: 'Yes', id: 'true' }, + ], + value: (p) => + p?.operation === 'create_custom_object_field' + ? 'false' + : p?.operation === 'update_custom_object_field' + ? '' + : undefined, + dependsOn: ['operation'], + mode: 'advanced', + condition: { field: 'operation', value: [...CUSTOM_OBJECT_FIELD_WRITE_OPS] }, +}) + /** Operations for custom setting fields */ const CUSTOM_SETTING_WRITE_OPS = ['create_custom_setting', 'update_custom_setting'] as const @@ -776,28 +827,8 @@ Return ONLY the JSON - no explanations, no extra text.`, mode: 'advanced', condition: { field: 'operation', value: [...CUSTOM_OBJECT_FIELD_WRITE_OPS] }, }, - { - id: 'isUnique', - title: 'Unique', - type: 'dropdown', - options: [ - { label: 'No', id: 'false' }, - { label: 'Yes', id: 'true' }, - ], - mode: 'advanced', - condition: { field: 'operation', value: [...CUSTOM_OBJECT_FIELD_WRITE_OPS] }, - }, - { - id: 'enableHistory', - title: 'Enable History', - type: 'dropdown', - options: [ - { label: 'No', id: 'false' }, - { label: 'Yes', id: 'true' }, - ], - mode: 'advanced', - condition: { field: 'operation', value: [...CUSTOM_OBJECT_FIELD_WRITE_OPS] }, - }, + customObjectFieldFlag('isUnique', 'Unique'), + customObjectFieldFlag('enableHistory', 'Enable History'), { id: 'rqlDefinition', title: 'RQL Definition', @@ -964,8 +995,8 @@ Return ONLY the JSON - no explanations, no extra text.`, enabled: true, prompt: `Generate a JSON object for a Rippling API request based on the user's description. For custom object records: { "field_name": "value", ... } -For draft hires: { "draft_hires": [{ "personal_info": { "first_name": "", "last_name": "", "email": "" }, "employment_info": { "start_date": "", "title": "" }, "work_location_info": { "work_location_id": "" } }] } -For supergroup member updates: { "Operations": [{ "op": "add", "path": "members", "value": [{ "value": "worker_id" }] }] } +For draft hires, the array only: [{ "personal_info": { "name": { "first": "", "last": "" }, "invite_email": "" }, "employment_info": { "employment_type_id": "", "title": "", "start_date": "" }, "work_location_info": { "location_id": "" } }] +For supergroup member updates, the operations array only: [{ "op": "add", "value": [{ "id": "member_id" }] }] (op is "add" or "remove") Return ONLY the JSON - no explanations, no extra text.`, placeholder: 'Describe the data to send', }, @@ -983,7 +1014,8 @@ Return ONLY the JSON - no explanations, no extra text.`, id: 'records', title: 'Records', type: 'long-input', - placeholder: '[{ "data": { ... } }, ...]', + placeholder: + 'Create: [{ "external_id": "x", "name": "..." }] · Update: [{ "id": "...", "name": "..." }] · Delete: ["record_id", ...]', condition: { field: 'operation', value: [ @@ -1054,7 +1086,7 @@ Return ONLY the query expression - no explanations, no extra text.`, prompt: `Generate an OData filter expression for the Rippling API based on the user's description. Examples: - "active workers" -> status eq 'ACTIVE' -- "workers in engineering" -> department eq 'Engineering' +- "workers with a given work email" -> work_email eq 'jane@example.com' - "created after January" -> created_at gt '2024-01-01' Return ONLY the filter expression - no explanations, no extra text.`, placeholder: 'Describe what to filter for', @@ -1085,11 +1117,29 @@ Return ONLY the comma-separated field names - no explanations, no extra text.`, wandConfig: { enabled: true, prompt: `Generate a sort expression for the Rippling API based on the user's description. -Format: field_name for ascending, -field_name for descending. Common fields: id, created_at, updated_at, name. +Format: comma-separated field names, ascending by default; append " desc" for descending. Common fields: id, created_at, updated_at, name. Examples: -- "newest first" -> -created_at +- "newest first" -> created_at desc +- "alphabetical" -> name +- "recently updated" -> updated_at desc +Return ONLY the sort expression - no explanations, no extra text.`, + placeholder: 'Describe how to sort results', + }, + }, + { + id: 'queryOrderBy', + title: 'Order By', + type: 'short-input', + placeholder: 'e.g., name desc', + mode: 'advanced', + condition: { field: 'operation', value: 'query_custom_object_records' }, + wandConfig: { + enabled: true, + prompt: `Generate a sort expression for the Rippling custom object records query based on the user's description. +Format: exactly one field API name, optionally followed by " asc" or " desc" (ascending by default). Multiple fields and nested paths are not supported. +Examples: +- "newest first" -> created_at desc - "alphabetical" -> name -- "recently updated" -> -updated_at Return ONLY the sort expression - no explanations, no extra text.`, placeholder: 'Describe how to sort results', }, @@ -1098,7 +1148,8 @@ Return ONLY the sort expression - no explanations, no extra text.`, id: 'cursor', title: 'Cursor', type: 'short-input', - placeholder: 'Pagination cursor from previous response', + placeholder: + 'nextCursor output of the previous page (cursor for Query Custom Object Records)', mode: 'advanced', condition: { field: 'operation', value: [...CURSOR_OPS] }, }, @@ -1203,11 +1254,24 @@ Return ONLY the sort expression - no explanations, no extra text.`, ], config: { tool: (params) => `rippling_${params.operation}`, - params: (params) => { - const mapped: Record = { - apiKey: params.apiKey, + params: (params, context) => { + const mapped: Record = {} + if (params.apiKey !== undefined) mapped.apiKey = params.apiKey + const op = mapperOperation(params, context) + /** A dropdown `'true'` or a model's `true` sets the flag; false or blank leaves it out. */ + const setFlag = (key: string, value: unknown) => { + if (parseOptionalBooleanInput(value) === true) mapped[key] = true + } + /** + * A Yes/No field whose id is the tool's own param: a `'false'` left unmapped would reach the + * tool as text, so both answers are sent as booleans and "No change" (`''`) sends nothing. + */ + const setBoolean = (key: string, value: unknown) => { + const flag = parseOptionalBooleanInput(value) + if (flag !== undefined) mapped[key] = flag + else if (value === '') mapped[key] = undefined } - const op = params.operation as string + const isSettingWrite = (CUSTOM_SETTING_WRITE_OPS as readonly string[]).includes(op) if (params.id != null && params.id !== '') mapped.id = params.id if (params.customObjectId != null && params.customObjectId !== '') @@ -1246,7 +1310,11 @@ Return ONLY the sort expression - no explanations, no extra text.`, mapped.pluralLabel = params.pluralLabel if (params.ownerRole != null && params.ownerRole !== '') mapped.ownerRole = params.ownerRole - if (params.dataType != null && params.dataType !== '') { + if ( + (CUSTOM_OBJECT_FIELD_WRITE_OPS as readonly string[]).includes(op) && + params.dataType != null && + params.dataType !== '' + ) { try { mapped.dataType = typeof params.dataType === 'string' ? JSON.parse(params.dataType) : params.dataType @@ -1256,20 +1324,9 @@ Return ONLY the sort expression - no explanations, no extra text.`, ) } } - if ( - params.fieldRequired != null && - params.fieldRequired !== '' && - params.fieldRequired !== 'false' - ) - mapped.required = params.fieldRequired === 'true' - if (params.isUnique != null && params.isUnique !== '' && params.isUnique !== 'false') - mapped.isUnique = params.isUnique === 'true' - if ( - params.enableHistory != null && - params.enableHistory !== '' && - params.enableHistory !== 'false' - ) - mapped.enableHistory = params.enableHistory === 'true' + setFlag('required', params.fieldRequired) + setBoolean('isUnique', params.isUnique) + setBoolean('enableHistory', params.enableHistory) if (params.rqlDefinition != null && params.rqlDefinition !== '') { try { mapped.rqlDefinition = @@ -1325,9 +1382,9 @@ Return ONLY the sort expression - no explanations, no extra text.`, if (params.displayName != null && params.displayName !== '') mapped.displayName = params.displayName - if (params.settingApiName != null && params.settingApiName !== '') + if (isSettingWrite && params.settingApiName != null && params.settingApiName !== '') mapped.apiName = params.settingApiName - if (params.settingDataType != null && params.settingDataType !== '') + if (isSettingWrite && params.settingDataType != null && params.settingDataType !== '') mapped.dataType = params.settingDataType if (params.secretValue != null && params.secretValue !== '') mapped.secretValue = params.secretValue @@ -1338,18 +1395,8 @@ Return ONLY the sort expression - no explanations, no extra text.`, if (params.settingBooleanValue != null && params.settingBooleanValue !== '') mapped.booleanValue = params.settingBooleanValue === 'true' - if ( - params.includeObjectIds != null && - params.includeObjectIds !== '' && - params.includeObjectIds !== 'false' - ) - mapped.includeObjectIds = params.includeObjectIds === 'true' - if ( - params.includeTotalRows != null && - params.includeTotalRows !== '' && - params.includeTotalRows !== 'false' - ) - mapped.includeTotalRows = params.includeTotalRows === 'true' + setBoolean('includeObjectIds', params.includeObjectIds) + setBoolean('includeTotalRows', params.includeTotalRows) if (params.formatDateFields != null && params.formatDateFields !== '') { try { mapped.formatDateFields = @@ -1373,17 +1420,23 @@ Return ONLY the sort expression - no explanations, no extra text.`, if (params.outputType != null && params.outputType !== '') mapped.outputType = params.outputType + setBoolean('allOrNothing', params.allOrNothing) + + for (const [key, ops] of QUERY_PARAM_OPS) { + const value = params[key] + if ((ops as readonly string[]).includes(op)) { + if (value != null && value !== '') mapped[key] = value + } else if (value != null && !isToolCall(context)) { + mapped[key] = undefined + } + } + if ( - params.allOrNothing != null && - params.allOrNothing !== '' && - params.allOrNothing !== 'false' + op === 'query_custom_object_records' && + params.queryOrderBy != null && + params.queryOrderBy !== '' ) - mapped.allOrNothing = params.allOrNothing === 'true' - - if (params.filter != null && params.filter !== '') mapped.filter = params.filter - if (params.expand != null && params.expand !== '') mapped.expand = params.expand - if (params.orderBy != null && params.orderBy !== '') mapped.orderBy = params.orderBy - if (params.cursor != null && params.cursor !== '') mapped.cursor = params.cursor + mapped.orderBy = params.queryOrderBy if (params.query != null && params.query !== '') mapped.query = params.query if (params.limit != null && params.limit !== '') mapped.limit = Number(params.limit) @@ -1565,6 +1618,10 @@ Return ONLY the sort expression - no explanations, no extra text.`, filter: { type: 'string', description: 'OData filter expression' }, expand: { type: 'string', description: 'Fields to expand' }, orderBy: { type: 'string', description: 'Ordering expression' }, + queryOrderBy: { + type: 'string', + description: 'Custom object records query ordering: one field with optional asc or desc', + }, cursor: { type: 'string', description: 'Pagination cursor' }, apiKey: { type: 'string', description: 'Rippling API key' }, }, @@ -1599,8 +1656,16 @@ Return ONLY the sort expression - no explanations, no extra text.`, objectCategories: { type: 'array', description: 'List of object categories' }, totalCount: { type: 'number', description: 'Total number of items returned' }, nextLink: { type: 'string', description: 'URL or cursor for the next page of results' }, + nextCursor: { + type: 'string', + description: 'Cursor for the next page; pass it back in the Cursor field', + }, cursor: { type: 'string', description: 'Cursor for next page of query results' }, deleted: { type: 'boolean', description: 'Whether the resource was deleted' }, + deletedRecordIds: { + type: 'array', + description: 'Record IDs whose bulk deletion was applied', + }, createdRecords: { type: 'array', description: 'Bulk created custom object records' }, updatedRecords: { type: 'array', description: 'Bulk updated custom object records' }, report_id: { type: 'string', description: 'Report ID' }, diff --git a/apps/sim/blocks/blocks/rocketlane.test.ts b/apps/sim/blocks/blocks/rocketlane.test.ts new file mode 100644 index 00000000000..87f444feab4 --- /dev/null +++ b/apps/sim/blocks/blocks/rocketlane.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it } from 'vitest' +import { RocketlaneBlock } from '@/blocks/blocks/rocketlane' + +/** Runs the mapper the way a tool call does: model args merged under the mapper's result. */ +function resolveToolCall(args: Record, operation: string) { + const mapper = RocketlaneBlock.tools.config?.params + if (!mapper) throw new Error('Rocketlane block has no params mapper') + return { ...args, ...mapper(args, { operation }) } +} + +describe('RocketlaneBlock agent tool calls', () => { + it('keeps and coerces the time source the model names when the operation arrives only in context', () => { + const result = resolveToolCall( + { apiKey: 'key', date: '2026-11-15', minutes: '30', projectId: '101' }, + 'create_time_entry' + ) + + expect(result).toMatchObject({ date: '2026-11-15', minutes: 30, projectId: 101 }) + expect(result.taskId).toBeUndefined() + }) + + it('sends only the saved time source when the model also names a different one', () => { + const result = resolveToolCall( + { + apiKey: 'key', + date: '2026-11-15', + minutes: '30', + timeEntrySource: 'task', + timeEntryTaskId: '42', + projectId: '101', + }, + 'create_time_entry' + ) + + expect(result).toMatchObject({ taskId: 42 }) + expect(result.projectId).toBeUndefined() + }) +}) + +describe('RocketlaneBlock canvas mapping', () => { + it('sends a text filter that a reference resolved to a number instead of dropping it', () => { + const mapper = RocketlaneBlock.tools.config?.params + if (!mapper) throw new Error('Rocketlane block has no params mapper') + + const result = mapper({ + operation: 'list_projects', + apiKey: 'key', + externalReferenceIdEquals: 42, + }) + + expect(result.externalReferenceIdEquals).toBe('42') + }) +}) diff --git a/apps/sim/blocks/blocks/rocketlane.ts b/apps/sim/blocks/blocks/rocketlane.ts index a502311cb88..18f9535fe96 100644 --- a/apps/sim/blocks/blocks/rocketlane.ts +++ b/apps/sim/blocks/blocks/rocketlane.ts @@ -1,7 +1,7 @@ import { RocketlaneIcon } from '@/components/icons' -import type { BlockConfig, BlockMeta } from '@/blocks/types' +import type { BlockConfig, BlockMeta, BlockToolParamsContext } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' /** * Who a membership change targets, for the card sentences below. Rocketlane @@ -219,8 +219,12 @@ function toNumber(value: unknown): number | undefined { return Number.isFinite(parsed) ? parsed : undefined } -/** Returns the trimmed string, or undefined for empty/non-string values. */ +/** + * Returns the trimmed string, or undefined for empty values. A finite number is stringified so an + * id or filter a model (or a resolved reference) sends as a number is not dropped. + */ function toStr(value: unknown): string | undefined { + if (typeof value === 'number') return Number.isFinite(value) ? String(value) : undefined if (typeof value !== 'string') return undefined const trimmed = value.trim() return trimmed.length > 0 ? trimmed : undefined @@ -302,9 +306,16 @@ function includeList(params: BlockParams) { } } -/** Builds the exact param set declared by the selected operation's tool. */ -function buildOperationParams(params: BlockParams): Record { - switch (params.operation) { +/** + * Builds the exact param set declared by the selected operation's tool. Where a block field is + * named differently from its tool param, a tool call (model args keyed by tool param names) falls + * back to the tool param via `toolCallArg`, so canvas output is unchanged. + */ +function buildOperationParams( + params: BlockParams, + context?: BlockToolParamsContext +): Record { + switch (mapperOperation(params, context)) { case 'create_project': return { projectName: toStr(params.projectName), @@ -411,7 +422,7 @@ function buildOperationParams(params: BlockParams): Record { projectId: toNumber(params.projectId), placeholderId: toNumber(params.placeholderId), userId: toNumber(params.userId), - userEmailId: toStr(params.userEmail), + userEmailId: toStr(params.userEmail) ?? toolCallArg(context, toStr(params.userEmailId)), } case 'unassign_placeholders': return { @@ -430,7 +441,7 @@ function buildOperationParams(params: BlockParams): Record { effortInMinutes: toNumber(params.effortInMinutes), progress: toNumber(params.progress), atRisk: toBool(params.atRisk), - type: toStr(params.taskType), + type: toStr(params.taskType) ?? toolCallArg(context, toStr(params.type)), phaseId: toNumber(params.phaseId), statusValue: toNumber(params.statusValue), assigneeUserIds: toNumberList(params.assigneeUserIds), @@ -472,7 +483,7 @@ function buildOperationParams(params: BlockParams): Record { effortInMinutes: toNumber(params.effortInMinutes), progress: toNumber(params.progress), atRisk: toBool(params.atRisk), - type: toStr(params.taskType), + type: toStr(params.taskType) ?? toolCallArg(context, toStr(params.type)), statusValue: toNumber(params.statusValue), externalReferenceId: toStr(params.externalReferenceId), private: toBool(params.private), @@ -582,14 +593,27 @@ function buildOperationParams(params: BlockParams): Record { case 'create_time_entry': { const source = params.timeEntrySource ?? 'task' - return { - date: toStr(params.date), - minutes: toNumber(params.minutes), - // Exactly one time source may be sent — pass only the selected one. + // Exactly one time source may be sent. A saved source is used alone; only when none is + // saved does a tool call fall back to the sources the model passed under the tool names. + const savedSource = { activityName: source === 'activity' ? toStr(params.timeEntryActivityName) : undefined, taskId: source === 'task' ? toNumber(params.timeEntryTaskId) : undefined, projectPhaseId: source === 'phase' ? toNumber(params.timeEntryPhaseId) : undefined, projectId: source === 'project' ? toNumber(params.timeEntryProjectId) : undefined, + } + const hasSavedSource = Object.values(savedSource).some((value) => value !== undefined) + const timeSource = hasSavedSource + ? savedSource + : { + activityName: toolCallArg(context, toStr(params.activityName)), + taskId: toolCallArg(context, toNumber(params.taskId)), + projectPhaseId: toolCallArg(context, toNumber(params.projectPhaseId)), + projectId: toolCallArg(context, toNumber(params.projectId)), + } + return { + date: toStr(params.date), + minutes: toNumber(params.minutes), + ...timeSource, billable: toBool(params.billable), userId: toNumber(params.userId), userEmail: toStr(params.userEmail), @@ -634,8 +658,8 @@ function buildOperationParams(params: BlockParams): Record { dateEq: toStr(params.dateEq), dateGe: toStr(params.dateGe), dateLe: toStr(params.dateLe), - projectEq: toNumber(params.projectIdEq), - taskEq: toNumber(params.taskIdEq), + projectEq: toNumber(params.projectIdEq) ?? toolCallArg(context, toNumber(params.projectEq)), + taskEq: toNumber(params.taskIdEq) ?? toolCallArg(context, toNumber(params.taskEq)), projectPhaseIdEq: toNumber(params.projectPhaseIdEq), categoryIdEq: toNumber(params.categoryIdEq), userIdEq: toNumber(params.userIdEq), @@ -666,7 +690,7 @@ function buildOperationParams(params: BlockParams): Record { userEmail: toStr(params.userEmail), startDate: toStr(params.startDate), endDate: toStr(params.endDate), - type: toStr(params.timeOffType), + type: toStr(params.timeOffType) ?? toolCallArg(context, toStr(params.type)), durationInMinutes: toNumber(params.durationInMinutes), note: toStr(params.note), notifyProjectOwners: toBool(params.notifyProjectOwners), @@ -685,7 +709,7 @@ function buildOperationParams(params: BlockParams): Record { startDateLe: toStr(params.startDateLe), endDateGe: toStr(params.endDateGe), endDateLe: toStr(params.endDateLe), - typeEq: toStr(params.timeOffTypeEq), + typeEq: toStr(params.timeOffTypeEq) ?? toolCallArg(context, toStr(params.typeEq)), userIdEq: toStr(params.userIdEq), emailIdEq: toStr(params.emailIdEq), } @@ -703,8 +727,8 @@ function buildOperationParams(params: BlockParams): Record { lastNameCn: toStr(params.lastNameCn), emailEq: toStr(params.emailEq), emailCn: toStr(params.emailCn), - statusEq: toStr(params.userStatusEq), - typeEq: toStr(params.userTypeEq), + statusEq: toStr(params.userStatusEq) ?? toolCallArg(context, toStr(params.statusEq)), + typeEq: toStr(params.userTypeEq) ?? toolCallArg(context, toStr(params.typeEq)), } case 'create_space': @@ -738,7 +762,8 @@ function buildOperationParams(params: BlockParams): Record { spaceDocumentType: toStr(params.spaceDocumentType), spaceDocumentName: toStr(params.spaceDocumentName), url: toStr(params.url), - templateId: toNumber(params.documentTemplateId), + templateId: + toNumber(params.documentTemplateId) ?? toolCallArg(context, toNumber(params.templateId)), } case 'get_space_document': return { spaceDocumentId: toNumber(params.spaceDocumentId) } @@ -792,8 +817,9 @@ function buildOperationParams(params: BlockParams): Record { amountOutstandingGt: toNumber(params.amountOutstandingGt), invoiceNumberEq: toStr(params.invoiceNumberEq), invoiceNumberCn: toStr(params.invoiceNumberCn), - statusEq: toStr(params.invoiceStatusEq), - statusOneOf: toStr(params.invoiceStatusOneOf), + statusEq: toStr(params.invoiceStatusEq) ?? toolCallArg(context, toStr(params.statusEq)), + statusOneOf: + toStr(params.invoiceStatusOneOf) ?? toolCallArg(context, toStr(params.statusOneOf)), companyIdEq: toStr(params.companyIdEq), companyIdOneOf: toStr(params.companyIdOneOf), } @@ -2824,8 +2850,8 @@ export const RocketlaneBlock: BlockConfig = { ], config: { tool: (params) => `rocketlane_${params.operation}`, - params: (params) => ({ - ...buildOperationParams(params), + params: (params, context) => ({ + ...buildOperationParams(params, context), apiKey: params.apiKey, }), }, diff --git a/apps/sim/blocks/blocks/rootly.test.ts b/apps/sim/blocks/blocks/rootly.test.ts new file mode 100644 index 00000000000..81928ce3d0b --- /dev/null +++ b/apps/sim/blocks/blocks/rootly.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from 'vitest' +import { RootlyBlock } from '@/blocks/blocks/rootly' + +/** Runs the mapper the way a tool call does: merged row and model args under the mapper's result. */ +function resolveToolCall(args: Record, operation: string) { + const mapper = RootlyBlock.tools.config?.params + if (!mapper) throw new Error('Rootly block has no params mapper') + return { ...args, ...mapper(args, { operation }) } +} + +describe('RootlyBlock agent tool calls', () => { + it('maps a field saved on the tool row while keeping the model args named after tool params', () => { + const result = resolveToolCall( + { apiKey: 'key', updateIncidentId: 'inc_1', title: 'Database degraded', private: true }, + 'rootly_update_incident' + ) + + expect(result).toMatchObject({ + incidentId: 'inc_1', + title: 'Database degraded', + private: true, + }) + }) + + it('keeps a boolean resolveRelatedIncidents sent by the model', () => { + const result = resolveToolCall( + { apiKey: 'key', alertId: 'a1', resolveRelatedIncidents: true }, + 'rootly_resolve_alert' + ) + + expect(result).toMatchObject({ alertId: 'a1', resolveRelatedIncidents: true }) + }) +}) diff --git a/apps/sim/blocks/blocks/rootly.ts b/apps/sim/blocks/blocks/rootly.ts index 26c48533fa3..51b3e958e25 100644 --- a/apps/sim/blocks/blocks/rootly.ts +++ b/apps/sim/blocks/blocks/rootly.ts @@ -1,9 +1,439 @@ import { RootlyIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { + isToolCall, + mapperOperation, + parseOptionalBooleanInput, + withSavedCredential, +} from '@/blocks/utils' import { getTrigger } from '@/triggers' +/** + * Maps the block's per-operation fields onto the selected tool's params. Most block fields carry an + * operation prefix and are renamed to their tool param here. A few share the tool param's id + * (`title`, `resolveRelatedIncidents`, `mitigationMessage`, `resolutionMessage`, + * `cancellationMessage`), so on tool calls they hold the model's typed value and any coercion must + * accept it. + */ +function buildOperationParams( + params: Record, + operation: string +): Record { + const baseParams: Record = { + apiKey: params.apiKey, + } + + switch (operation) { + case 'rootly_create_incident': + return { + ...baseParams, + title: params.title, + summary: params.createSummary, + severityId: params.createSeverityId, + status: params.createStatus, + kind: params.createKind, + serviceIds: params.createServiceIds, + environmentIds: params.createEnvironmentIds, + groupIds: params.createGroupIds, + incidentTypeIds: params.createIncidentTypeIds, + functionalityIds: params.createFunctionalityIds, + labels: params.createLabels, + private: params.createPrivate ? params.createPrivate === 'true' : undefined, + } + + case 'rootly_get_incident': + return { + ...baseParams, + incidentId: params.getIncidentId, + } + + case 'rootly_update_incident': + return { + ...baseParams, + incidentId: params.updateIncidentId, + title: params.updateTitle, + summary: params.updateSummary, + status: params.updateStatus, + severityId: params.updateSeverityId, + kind: params.updateKind, + private: params.updatePrivate ? params.updatePrivate === 'true' : undefined, + mitigationMessage: params.mitigationMessage, + resolutionMessage: params.resolutionMessage, + cancellationMessage: params.cancellationMessage, + serviceIds: params.updateServiceIds, + environmentIds: params.updateEnvironmentIds, + groupIds: params.updateGroupIds, + incidentTypeIds: params.updateIncidentTypeIds, + functionalityIds: params.updateFunctionalityIds, + labels: params.updateLabels, + } + + case 'rootly_list_incidents': + return { + ...baseParams, + status: params.listIncidentsStatus, + search: params.listIncidentsSearch, + severity: params.listIncidentsSeverity, + services: params.listIncidentsServices, + teams: params.listIncidentsTeams, + environments: params.listIncidentsEnvironments, + sort: params.listIncidentsSort, + pageSize: params.listIncidentsPageSize ? Number(params.listIncidentsPageSize) : undefined, + pageNumber: params.listIncidentsPageNumber + ? Number(params.listIncidentsPageNumber) + : undefined, + } + + case 'rootly_create_alert': + return { + ...baseParams, + summary: params.alertSummary, + description: params.alertDescription, + source: params.alertSource, + status: params.alertStatus, + serviceIds: params.alertServiceIds, + groupIds: params.alertGroupIds, + environmentIds: params.alertEnvironmentIds, + externalId: params.alertExternalId, + deduplicationKey: params.alertDeduplicationKey, + externalUrl: params.alertExternalUrl, + } + + case 'rootly_list_alerts': + return { + ...baseParams, + status: params.listAlertsStatus, + source: params.listAlertsSource, + services: params.listAlertsServices, + environments: params.listAlertsEnvironments, + groups: params.listAlertsGroups, + pageSize: params.listAlertsPageSize ? Number(params.listAlertsPageSize) : undefined, + pageNumber: params.listAlertsPageNumber ? Number(params.listAlertsPageNumber) : undefined, + } + + case 'rootly_add_incident_event': + return { + ...baseParams, + incidentId: params.eventIncidentId, + event: params.eventText, + visibility: params.eventVisibility, + } + + case 'rootly_list_services': + return { + ...baseParams, + search: params.servicesSearch, + pageSize: params.servicesPageSize ? Number(params.servicesPageSize) : undefined, + pageNumber: params.servicesPageNumber ? Number(params.servicesPageNumber) : undefined, + } + + case 'rootly_list_severities': + return { + ...baseParams, + search: params.severitiesSearch, + pageSize: params.severitiesPageSize ? Number(params.severitiesPageSize) : undefined, + pageNumber: params.severitiesPageNumber ? Number(params.severitiesPageNumber) : undefined, + } + + case 'rootly_list_teams': + return { + ...baseParams, + search: params.teamsSearch, + pageSize: params.teamsPageSize ? Number(params.teamsPageSize) : undefined, + pageNumber: params.teamsPageNumber ? Number(params.teamsPageNumber) : undefined, + } + + case 'rootly_list_environments': + return { + ...baseParams, + search: params.environmentsSearch, + pageSize: params.environmentsPageSize ? Number(params.environmentsPageSize) : undefined, + pageNumber: params.environmentsPageNumber + ? Number(params.environmentsPageNumber) + : undefined, + } + + case 'rootly_list_incident_types': + return { + ...baseParams, + search: params.incidentTypesSearch, + pageSize: params.incidentTypesPageSize ? Number(params.incidentTypesPageSize) : undefined, + pageNumber: params.incidentTypesPageNumber + ? Number(params.incidentTypesPageNumber) + : undefined, + } + + case 'rootly_list_functionalities': + return { + ...baseParams, + search: params.functionalitiesSearch, + pageSize: params.functionalitiesPageSize + ? Number(params.functionalitiesPageSize) + : undefined, + pageNumber: params.functionalitiesPageNumber + ? Number(params.functionalitiesPageNumber) + : undefined, + } + + case 'rootly_list_retrospectives': + return { + ...baseParams, + status: params.retrospectivesStatus, + search: params.retrospectivesSearch, + pageSize: params.retrospectivesPageSize ? Number(params.retrospectivesPageSize) : undefined, + pageNumber: params.retrospectivesPageNumber + ? Number(params.retrospectivesPageNumber) + : undefined, + } + + case 'rootly_delete_incident': + return { + ...baseParams, + incidentId: params.deleteIncidentId, + } + + case 'rootly_get_alert': + return { + ...baseParams, + alertId: params.getAlertId, + } + + case 'rootly_update_alert': + return { + ...baseParams, + alertId: params.updateAlertId, + summary: params.updateAlertSummary, + description: params.updateAlertDescription, + source: params.updateAlertSource, + serviceIds: params.updateAlertServiceIds, + groupIds: params.updateAlertGroupIds, + environmentIds: params.updateAlertEnvironmentIds, + externalId: params.updateAlertExternalId, + externalUrl: params.updateAlertExternalUrl, + deduplicationKey: params.updateAlertDeduplicationKey, + } + + case 'rootly_acknowledge_alert': + return { + ...baseParams, + alertId: params.ackAlertId, + } + + case 'rootly_resolve_alert': + return { + ...baseParams, + alertId: params.resolveAlertId, + resolutionMessage: params.resolveResolutionMessage, + resolveRelatedIncidents: parseOptionalBooleanInput(params.resolveRelatedIncidents), + } + + case 'rootly_create_action_item': + return { + ...baseParams, + incidentId: params.actionItemIncidentId, + summary: params.actionItemSummary, + description: params.actionItemDescription, + kind: params.actionItemKind, + priority: params.actionItemPriority, + status: params.actionItemStatus, + assignedToUserId: params.actionItemAssignedToUserId, + dueDate: params.actionItemDueDate, + } + + case 'rootly_list_action_items': + return { + ...baseParams, + incidentId: params.listActionItemsIncidentId, + pageSize: params.listActionItemsPageSize + ? Number(params.listActionItemsPageSize) + : undefined, + pageNumber: params.listActionItemsPageNumber + ? Number(params.listActionItemsPageNumber) + : undefined, + } + + case 'rootly_list_users': + return { + ...baseParams, + search: params.usersSearch, + email: params.usersEmail, + pageSize: params.usersPageSize ? Number(params.usersPageSize) : undefined, + pageNumber: params.usersPageNumber ? Number(params.usersPageNumber) : undefined, + } + + case 'rootly_list_on_calls': + return { + ...baseParams, + scheduleIds: params.onCallsScheduleIds, + escalationPolicyIds: params.onCallsEscalationPolicyIds, + userIds: params.onCallsUserIds, + serviceIds: params.onCallsServiceIds, + } + + case 'rootly_list_schedules': + return { + ...baseParams, + search: params.schedulesSearch, + pageSize: params.schedulesPageSize ? Number(params.schedulesPageSize) : undefined, + pageNumber: params.schedulesPageNumber ? Number(params.schedulesPageNumber) : undefined, + } + + case 'rootly_list_escalation_policies': + return { + ...baseParams, + search: params.escalationPoliciesSearch, + pageSize: params.escalationPoliciesPageSize + ? Number(params.escalationPoliciesPageSize) + : undefined, + pageNumber: params.escalationPoliciesPageNumber + ? Number(params.escalationPoliciesPageNumber) + : undefined, + } + + case 'rootly_list_causes': + return { + ...baseParams, + search: params.causesSearch, + pageSize: params.causesPageSize ? Number(params.causesPageSize) : undefined, + pageNumber: params.causesPageNumber ? Number(params.causesPageNumber) : undefined, + } + + case 'rootly_list_playbooks': + return { + ...baseParams, + pageSize: params.playbooksPageSize ? Number(params.playbooksPageSize) : undefined, + pageNumber: params.playbooksPageNumber ? Number(params.playbooksPageNumber) : undefined, + } + + case 'rootly_mitigate_incident': + return { + ...baseParams, + incidentId: params.mitigateIncidentId, + mitigationMessage: params.mitigateMessage, + } + + case 'rootly_resolve_incident': + return { + ...baseParams, + incidentId: params.resolveIncidentId, + resolutionMessage: params.resolveIncidentMessage, + } + + case 'rootly_assign_incident_role': + return { + ...baseParams, + incidentId: params.assignRoleIncidentId, + userId: params.assignRoleUserId, + incidentRoleId: params.assignRoleId, + } + + case 'rootly_unassign_incident_role': + return { + ...baseParams, + incidentId: params.unassignRoleIncidentId, + userId: params.unassignRoleUserId, + incidentRoleId: params.unassignRoleId, + } + + case 'rootly_add_subscribers': + return { + ...baseParams, + incidentId: params.addSubsIncidentId, + userIds: params.addSubsUserIds, + } + + case 'rootly_remove_subscribers': + return { + ...baseParams, + incidentId: params.removeSubsIncidentId, + userIds: params.removeSubsUserIds, + } + + case 'rootly_create_status_page_event': + return { + ...baseParams, + incidentId: params.statusEventIncidentId, + event: params.statusEventText, + status: params.statusEventStatus, + statusPageId: params.statusEventStatusPageId, + notifySubscribers: params.statusEventNotify + ? params.statusEventNotify === 'true' + : undefined, + shouldTweet: params.statusEventTweet ? params.statusEventTweet === 'true' : undefined, + } + + case 'rootly_update_action_item': + return { + ...baseParams, + actionItemId: params.updateActionItemId, + summary: params.updateActionItemSummary, + description: params.updateActionItemDescription, + status: params.updateActionItemStatus, + priority: params.updateActionItemPriority, + kind: params.updateActionItemKind, + assignedToUserId: params.updateActionItemAssignee, + dueDate: params.updateActionItemDueDate, + } + + case 'rootly_delete_action_item': + return { + ...baseParams, + actionItemId: params.deleteActionItemId, + } + + case 'rootly_snooze_alert': + return { + ...baseParams, + alertId: params.snoozeAlertId, + delayMinutes: params.snoozeDelayMinutes ? Number(params.snoozeDelayMinutes) : undefined, + } + + case 'rootly_escalate_alert': + return { + ...baseParams, + alertId: params.escalateAlertId, + escalationPolicyId: params.escalatePolicyId, + escalationPolicyLevel: params.escalatePolicyLevel + ? Number(params.escalatePolicyLevel) + : undefined, + } + + case 'rootly_list_incident_events': + return { + ...baseParams, + incidentId: params.listEventsIncidentId, + pageSize: params.listEventsPageSize ? Number(params.listEventsPageSize) : undefined, + pageNumber: params.listEventsPageNumber ? Number(params.listEventsPageNumber) : undefined, + } + + case 'rootly_run_workflow': + return { + ...baseParams, + workflowId: params.runWorkflowId, + incidentId: params.runWorkflowIncidentId, + alertId: params.runWorkflowAlertId, + immediate: params.runWorkflowImmediate ? params.runWorkflowImmediate === 'true' : undefined, + checkConditions: params.runWorkflowCheckConditions + ? params.runWorkflowCheckConditions === 'true' + : undefined, + } + + case 'rootly_list_incident_roles': + return { + ...baseParams, + search: params.incidentRolesSearch, + pageSize: params.incidentRolesPageSize ? Number(params.incidentRolesPageSize) : undefined, + pageNumber: params.incidentRolesPageNumber + ? Number(params.incidentRolesPageNumber) + : undefined, + } + + default: + return baseParams + } +} + export const RootlyBlock: BlockConfig = { type: 'rootly', hideFromToolbar: true, @@ -1887,445 +2317,16 @@ export const RootlyBlock: BlockConfig = { ], config: { tool: (params) => params.operation, - params: (params) => { - const baseParams: Record = { - apiKey: params.apiKey, - } - - switch (params.operation) { - case 'rootly_create_incident': - return { - ...baseParams, - title: params.title, - summary: params.createSummary, - severityId: params.createSeverityId, - status: params.createStatus, - kind: params.createKind, - serviceIds: params.createServiceIds, - environmentIds: params.createEnvironmentIds, - groupIds: params.createGroupIds, - incidentTypeIds: params.createIncidentTypeIds, - functionalityIds: params.createFunctionalityIds, - labels: params.createLabels, - private: params.createPrivate ? params.createPrivate === 'true' : undefined, - } - - case 'rootly_get_incident': - return { - ...baseParams, - incidentId: params.getIncidentId, - } - - case 'rootly_update_incident': - return { - ...baseParams, - incidentId: params.updateIncidentId, - title: params.updateTitle, - summary: params.updateSummary, - status: params.updateStatus, - severityId: params.updateSeverityId, - kind: params.updateKind, - private: params.updatePrivate ? params.updatePrivate === 'true' : undefined, - mitigationMessage: params.mitigationMessage, - resolutionMessage: params.resolutionMessage, - cancellationMessage: params.cancellationMessage, - serviceIds: params.updateServiceIds, - environmentIds: params.updateEnvironmentIds, - groupIds: params.updateGroupIds, - incidentTypeIds: params.updateIncidentTypeIds, - functionalityIds: params.updateFunctionalityIds, - labels: params.updateLabels, - } - - case 'rootly_list_incidents': - return { - ...baseParams, - status: params.listIncidentsStatus, - search: params.listIncidentsSearch, - severity: params.listIncidentsSeverity, - services: params.listIncidentsServices, - teams: params.listIncidentsTeams, - environments: params.listIncidentsEnvironments, - sort: params.listIncidentsSort, - pageSize: params.listIncidentsPageSize - ? Number(params.listIncidentsPageSize) - : undefined, - pageNumber: params.listIncidentsPageNumber - ? Number(params.listIncidentsPageNumber) - : undefined, - } - - case 'rootly_create_alert': - return { - ...baseParams, - summary: params.alertSummary, - description: params.alertDescription, - source: params.alertSource, - status: params.alertStatus, - serviceIds: params.alertServiceIds, - groupIds: params.alertGroupIds, - environmentIds: params.alertEnvironmentIds, - externalId: params.alertExternalId, - deduplicationKey: params.alertDeduplicationKey, - externalUrl: params.alertExternalUrl, - } - - case 'rootly_list_alerts': - return { - ...baseParams, - status: params.listAlertsStatus, - source: params.listAlertsSource, - services: params.listAlertsServices, - environments: params.listAlertsEnvironments, - groups: params.listAlertsGroups, - pageSize: params.listAlertsPageSize ? Number(params.listAlertsPageSize) : undefined, - pageNumber: params.listAlertsPageNumber - ? Number(params.listAlertsPageNumber) - : undefined, - } - - case 'rootly_add_incident_event': - return { - ...baseParams, - incidentId: params.eventIncidentId, - event: params.eventText, - visibility: params.eventVisibility, - } - - case 'rootly_list_services': - return { - ...baseParams, - search: params.servicesSearch, - pageSize: params.servicesPageSize ? Number(params.servicesPageSize) : undefined, - pageNumber: params.servicesPageNumber ? Number(params.servicesPageNumber) : undefined, - } - - case 'rootly_list_severities': - return { - ...baseParams, - search: params.severitiesSearch, - pageSize: params.severitiesPageSize ? Number(params.severitiesPageSize) : undefined, - pageNumber: params.severitiesPageNumber - ? Number(params.severitiesPageNumber) - : undefined, - } - - case 'rootly_list_teams': - return { - ...baseParams, - search: params.teamsSearch, - pageSize: params.teamsPageSize ? Number(params.teamsPageSize) : undefined, - pageNumber: params.teamsPageNumber ? Number(params.teamsPageNumber) : undefined, - } - - case 'rootly_list_environments': - return { - ...baseParams, - search: params.environmentsSearch, - pageSize: params.environmentsPageSize - ? Number(params.environmentsPageSize) - : undefined, - pageNumber: params.environmentsPageNumber - ? Number(params.environmentsPageNumber) - : undefined, - } - - case 'rootly_list_incident_types': - return { - ...baseParams, - search: params.incidentTypesSearch, - pageSize: params.incidentTypesPageSize - ? Number(params.incidentTypesPageSize) - : undefined, - pageNumber: params.incidentTypesPageNumber - ? Number(params.incidentTypesPageNumber) - : undefined, - } - - case 'rootly_list_functionalities': - return { - ...baseParams, - search: params.functionalitiesSearch, - pageSize: params.functionalitiesPageSize - ? Number(params.functionalitiesPageSize) - : undefined, - pageNumber: params.functionalitiesPageNumber - ? Number(params.functionalitiesPageNumber) - : undefined, - } - - case 'rootly_list_retrospectives': - return { - ...baseParams, - status: params.retrospectivesStatus, - search: params.retrospectivesSearch, - pageSize: params.retrospectivesPageSize - ? Number(params.retrospectivesPageSize) - : undefined, - pageNumber: params.retrospectivesPageNumber - ? Number(params.retrospectivesPageNumber) - : undefined, - } - - case 'rootly_delete_incident': - return { - ...baseParams, - incidentId: params.deleteIncidentId, - } - - case 'rootly_get_alert': - return { - ...baseParams, - alertId: params.getAlertId, - } - - case 'rootly_update_alert': - return { - ...baseParams, - alertId: params.updateAlertId, - summary: params.updateAlertSummary, - description: params.updateAlertDescription, - source: params.updateAlertSource, - serviceIds: params.updateAlertServiceIds, - groupIds: params.updateAlertGroupIds, - environmentIds: params.updateAlertEnvironmentIds, - externalId: params.updateAlertExternalId, - externalUrl: params.updateAlertExternalUrl, - deduplicationKey: params.updateAlertDeduplicationKey, - } - - case 'rootly_acknowledge_alert': - return { - ...baseParams, - alertId: params.ackAlertId, - } - - case 'rootly_resolve_alert': - return { - ...baseParams, - alertId: params.resolveAlertId, - resolutionMessage: params.resolveResolutionMessage, - resolveRelatedIncidents: params.resolveRelatedIncidents - ? params.resolveRelatedIncidents === 'true' - : undefined, - } - - case 'rootly_create_action_item': - return { - ...baseParams, - incidentId: params.actionItemIncidentId, - summary: params.actionItemSummary, - description: params.actionItemDescription, - kind: params.actionItemKind, - priority: params.actionItemPriority, - status: params.actionItemStatus, - assignedToUserId: params.actionItemAssignedToUserId, - dueDate: params.actionItemDueDate, - } - - case 'rootly_list_action_items': - return { - ...baseParams, - incidentId: params.listActionItemsIncidentId, - pageSize: params.listActionItemsPageSize - ? Number(params.listActionItemsPageSize) - : undefined, - pageNumber: params.listActionItemsPageNumber - ? Number(params.listActionItemsPageNumber) - : undefined, - } - - case 'rootly_list_users': - return { - ...baseParams, - search: params.usersSearch, - email: params.usersEmail, - pageSize: params.usersPageSize ? Number(params.usersPageSize) : undefined, - pageNumber: params.usersPageNumber ? Number(params.usersPageNumber) : undefined, - } - - case 'rootly_list_on_calls': - return { - ...baseParams, - scheduleIds: params.onCallsScheduleIds, - escalationPolicyIds: params.onCallsEscalationPolicyIds, - userIds: params.onCallsUserIds, - serviceIds: params.onCallsServiceIds, - } - - case 'rootly_list_schedules': - return { - ...baseParams, - search: params.schedulesSearch, - pageSize: params.schedulesPageSize ? Number(params.schedulesPageSize) : undefined, - pageNumber: params.schedulesPageNumber - ? Number(params.schedulesPageNumber) - : undefined, - } - - case 'rootly_list_escalation_policies': - return { - ...baseParams, - search: params.escalationPoliciesSearch, - pageSize: params.escalationPoliciesPageSize - ? Number(params.escalationPoliciesPageSize) - : undefined, - pageNumber: params.escalationPoliciesPageNumber - ? Number(params.escalationPoliciesPageNumber) - : undefined, - } - - case 'rootly_list_causes': - return { - ...baseParams, - search: params.causesSearch, - pageSize: params.causesPageSize ? Number(params.causesPageSize) : undefined, - pageNumber: params.causesPageNumber ? Number(params.causesPageNumber) : undefined, - } - - case 'rootly_list_playbooks': - return { - ...baseParams, - pageSize: params.playbooksPageSize ? Number(params.playbooksPageSize) : undefined, - pageNumber: params.playbooksPageNumber - ? Number(params.playbooksPageNumber) - : undefined, - } - - case 'rootly_mitigate_incident': - return { - ...baseParams, - incidentId: params.mitigateIncidentId, - mitigationMessage: params.mitigateMessage, - } - - case 'rootly_resolve_incident': - return { - ...baseParams, - incidentId: params.resolveIncidentId, - resolutionMessage: params.resolveIncidentMessage, - } - - case 'rootly_assign_incident_role': - return { - ...baseParams, - incidentId: params.assignRoleIncidentId, - userId: params.assignRoleUserId, - incidentRoleId: params.assignRoleId, - } - - case 'rootly_unassign_incident_role': - return { - ...baseParams, - incidentId: params.unassignRoleIncidentId, - userId: params.unassignRoleUserId, - incidentRoleId: params.unassignRoleId, - } - - case 'rootly_add_subscribers': - return { - ...baseParams, - incidentId: params.addSubsIncidentId, - userIds: params.addSubsUserIds, - } - - case 'rootly_remove_subscribers': - return { - ...baseParams, - incidentId: params.removeSubsIncidentId, - userIds: params.removeSubsUserIds, - } - - case 'rootly_create_status_page_event': - return { - ...baseParams, - incidentId: params.statusEventIncidentId, - event: params.statusEventText, - status: params.statusEventStatus, - statusPageId: params.statusEventStatusPageId, - notifySubscribers: params.statusEventNotify - ? params.statusEventNotify === 'true' - : undefined, - shouldTweet: params.statusEventTweet ? params.statusEventTweet === 'true' : undefined, - } - - case 'rootly_update_action_item': - return { - ...baseParams, - actionItemId: params.updateActionItemId, - summary: params.updateActionItemSummary, - description: params.updateActionItemDescription, - status: params.updateActionItemStatus, - priority: params.updateActionItemPriority, - kind: params.updateActionItemKind, - assignedToUserId: params.updateActionItemAssignee, - dueDate: params.updateActionItemDueDate, - } - - case 'rootly_delete_action_item': - return { - ...baseParams, - actionItemId: params.deleteActionItemId, - } - - case 'rootly_snooze_alert': - return { - ...baseParams, - alertId: params.snoozeAlertId, - delayMinutes: params.snoozeDelayMinutes - ? Number(params.snoozeDelayMinutes) - : undefined, - } - - case 'rootly_escalate_alert': - return { - ...baseParams, - alertId: params.escalateAlertId, - escalationPolicyId: params.escalatePolicyId, - escalationPolicyLevel: params.escalatePolicyLevel - ? Number(params.escalatePolicyLevel) - : undefined, - } - - case 'rootly_list_incident_events': - return { - ...baseParams, - incidentId: params.listEventsIncidentId, - pageSize: params.listEventsPageSize ? Number(params.listEventsPageSize) : undefined, - pageNumber: params.listEventsPageNumber - ? Number(params.listEventsPageNumber) - : undefined, - } - - case 'rootly_run_workflow': - return { - ...baseParams, - workflowId: params.runWorkflowId, - incidentId: params.runWorkflowIncidentId, - alertId: params.runWorkflowAlertId, - immediate: params.runWorkflowImmediate - ? params.runWorkflowImmediate === 'true' - : undefined, - checkConditions: params.runWorkflowCheckConditions - ? params.runWorkflowCheckConditions === 'true' - : undefined, - } - - case 'rootly_list_incident_roles': - return { - ...baseParams, - search: params.incidentRolesSearch, - pageSize: params.incidentRolesPageSize - ? Number(params.incidentRolesPageSize) - : undefined, - pageNumber: params.incidentRolesPageNumber - ? Number(params.incidentRolesPageNumber) - : undefined, - } - - default: - return baseParams - } + params: (params, context) => { + const mapped = buildOperationParams(params, mapperOperation(params, context)) + if (!isToolCall(context)) return mapped + // Model args arrive under the tool's param names; keep one wherever its block field is empty. + return Object.fromEntries( + Object.entries(mapped).map(([key, value]) => [ + key, + value === undefined || value === '' ? params[key] : value, + ]) + ) }, }, }, diff --git a/apps/sim/blocks/blocks/s3.test.ts b/apps/sim/blocks/blocks/s3.test.ts new file mode 100644 index 00000000000..32020227dbb --- /dev/null +++ b/apps/sim/blocks/blocks/s3.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from 'vitest' +import { S3Block } from '@/blocks/blocks/s3' + +const mapParams = S3Block.tools.config?.params +if (!mapParams) { + throw new Error('S3 block must define tools.config.params') +} + +const CONNECTION = { + accessKeyId: 'AKIAIOSFODNN7EXAMPLE', + secretAccessKey: 'secret', + region: 'us-east-1', +} + +/** Runs the mapper the way an agent tool call does: no `operation` in params, merged over them. */ +function toolCall(args: Record, operation: string) { + return { ...args, ...mapParams?.(args, { operation }) } +} + +/** + * On an agent tool call the operation arrives only on `context` and the model's args use the + * tool's param names (`keys`, `method`), not the block's field ids (`objectKeys`, `presignedMethod`). + */ +describe('S3 block agent tool calls', () => { + it('deletes the keys the model sent', () => { + const params = toolCall( + { ...CONNECTION, bucketName: 'bucket', keys: ['a.txt', 'b.txt'] }, + 'delete_objects' + ) + + expect(params.keys).toEqual(['a.txt', 'b.txt']) + }) + + it('presigns with the URL method the model sent', () => { + const params = toolCall( + { ...CONNECTION, bucketName: 'bucket', objectKey: 'a.txt', method: 'put', expiresIn: 600 }, + 'presigned_url' + ) + + expect(params).toMatchObject({ method: 'put', expiresIn: 600, bucketName: 'bucket' }) + }) +}) diff --git a/apps/sim/blocks/blocks/s3.ts b/apps/sim/blocks/blocks/s3.ts index 7c3bee8f9c5..98fc9421064 100644 --- a/apps/sim/blocks/blocks/s3.ts +++ b/apps/sim/blocks/blocks/s3.ts @@ -1,7 +1,17 @@ import { S3Icon } from '@/components/icons' -import type { BlockConfig, BlockMeta, BlockToolParams } from '@/blocks/types' +import type { + BlockConfig, + BlockMeta, + BlockToolParams, + BlockToolParamsContext, +} from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput, withSavedCredential } from '@/blocks/utils' +import { + mapperOperation, + normalizeFileInput, + toolCallArg, + withSavedCredential, +} from '@/blocks/utils' /** * Normalize the batch-delete keys input into a string array. Accepts an array, @@ -33,9 +43,11 @@ function parseObjectKeys(value: unknown): string[] { const UPLOAD_SOURCE_FIELD = ['uploadFile', 'fileReference', 'content'] as const /** Tool params for an S3 operation; credentials are validated by the caller. */ -function s3ToolParams(params: BlockToolParams) { +function s3ToolParams(params: BlockToolParams, context?: BlockToolParamsContext) { // Default to get_object for backward compatibility with existing workflows - const operation = params.operation || 'get_object' + const operation = mapperOperation(params, context) || 'get_object' + /** The block field, else (on a tool call) the model's arg for the tool param `key`. */ + const field = (value: unknown, key: string) => value ?? toolCallArg(context, params[key]) ?? value // Operation-specific parameters switch (operation) { @@ -63,7 +75,7 @@ function s3ToolParams(params: BlockToolParams) { content: params.content, contentType: params.contentType, acl: params.acl, - metadata: params.objectMetadata, + metadata: field(params.objectMetadata, 'metadata'), storageClass: params.storageClass, serverSideEncryption: params.serverSideEncryption, sseKmsKeyId: @@ -155,11 +167,11 @@ function s3ToolParams(params: BlockToolParams) { accessKeyId: params.accessKeyId, secretAccessKey: params.secretAccessKey, region: params.region, - prefix: params.bucketPrefix, + prefix: field(params.bucketPrefix, 'prefix'), maxBuckets: params.maxBuckets ? Number.parseInt(params.maxBuckets as string, 10) : undefined, - continuationToken: params.bucketsContinuationToken, + continuationToken: field(params.bucketsContinuationToken, 'continuationToken'), } case 'head_object': @@ -178,7 +190,7 @@ function s3ToolParams(params: BlockToolParams) { region: params.region, bucketName: params.bucketName, objectKey: params.objectKey, - versionId: params.headVersionId, + versionId: field(params.headVersionId, 'versionId'), } case 'create_bucket': @@ -193,7 +205,7 @@ function s3ToolParams(params: BlockToolParams) { secretAccessKey: params.secretAccessKey, region: params.region, bucketName: params.bucketName, - acl: params.createBucketAcl, + acl: field(params.createBucketAcl, 'acl'), } case 'delete_bucket': @@ -220,7 +232,8 @@ function s3ToolParams(params: BlockToolParams) { if (!params.objectKey) { throw new Error('Object Key is required') } - if (!params.presignedMethod) { + const method = params.presignedMethod || toolCallArg(context, params.method) + if (!method) { throw new Error('URL Type (get or put) is required') } return { @@ -229,9 +242,9 @@ function s3ToolParams(params: BlockToolParams) { region: params.region, bucketName: params.bucketName, objectKey: params.objectKey, - method: params.presignedMethod, + method, expiresIn: params.expiresIn ? Number.parseInt(params.expiresIn as string, 10) : undefined, - contentType: params.presignedContentType, + contentType: field(params.presignedContentType, 'contentType'), } } @@ -242,7 +255,7 @@ function s3ToolParams(params: BlockToolParams) { if (!params.bucketName) { throw new Error('Bucket Name is required') } - const keys = parseObjectKeys(params.objectKeys) + const keys = parseObjectKeys(field(params.objectKeys, 'keys')) if (keys.length === 0) { throw new Error('At least one object key is required') } @@ -783,7 +796,7 @@ export const S3Block: BlockConfig = { throw new Error(`Invalid S3 operation: ${operation}`) } }, - params: (params) => { + params: (params, context) => { // Validate required fields (common to all operations) if (!params.accessKeyId) { throw new Error('Access Key ID is required') @@ -792,7 +805,7 @@ export const S3Block: BlockConfig = { throw new Error('Secret Access Key is required') } - return s3ToolParams(params) + return s3ToolParams(params, context) }, }, }, diff --git a/apps/sim/blocks/blocks/sailpoint.test.ts b/apps/sim/blocks/blocks/sailpoint.test.ts new file mode 100644 index 00000000000..d4157f5bfbb --- /dev/null +++ b/apps/sim/blocks/blocks/sailpoint.test.ts @@ -0,0 +1,150 @@ +import { describe, expect, it } from 'vitest' +import { SailPointV2Block } from '@/blocks/blocks/sailpoint' +import type { BlockToolParamsContext } from '@/blocks/types' +import { sailpointSearchTool } from '@/tools/sailpoint/definitions' + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = SailPointV2Block.tools.config?.params + if (!mapper) throw new Error('SailPoint block has no params mapper') + return mapper(params, context) +} + +/** What the canvas executor hands the tool: raw inputs overlaid by the mapper output. */ +function canvasToolInput(params: Record) { + return { ...params, ...mapParams(params) } +} + +/** What a tool call hands the tool: merged row and model args overlaid by the mapper output. */ +function toolCallInput(params: Record, operation: string) { + return { ...params, ...mapParams(params, { operation }) } +} + +describe('SailPoint tool-call mapping', () => { + it('coerces stored row dropdowns and pagination when the operation arrives only in the context', () => { + const input = toolCallInput( + { includeIDNSource: 'false', limit: '25', count: 'true' }, + 'sailpoint_list_sources' + ) + expect(input).toMatchObject({ includeIDNSource: false, limit: 25, count: true }) + }) + + it('sends a row approval comment and keeps the model comment when the row has none', () => { + expect( + toolCallInput( + { approvalId: 'a1', approvalComment: 'Looks good' }, + 'sailpoint_reject_access_request' + ).comment + ).toBe('Looks good') + expect( + toolCallInput( + { approvalId: 'a1', comment: 'From the model' }, + 'sailpoint_reject_access_request' + ).comment + ).toBe('From the model') + }) + + it('keeps model filter arguments that a canvas selector would gate', () => { + const input = toolCallInput( + { id: 'cert', reviewItemFilterType: '', roles: 'r1' }, + 'sailpoint_list_certification_review_items' + ) + expect(input.roles).toBe('r1') + expect( + toolCallInput( + { identityScopeType: '', requestedBy: 'me' }, + 'sailpoint_list_account_activities' + ).requestedBy + ).toBe('me') + }) +}) + +describe('SailPoint search list fields', () => { + it('passes a comma-separated sort through to the tool instead of failing the mapping', () => { + expect(canvasToolInput({ operation: 'sailpoint_search', sort: 'displayName,-id' }).sort).toBe( + 'displayName,-id' + ) + }) + + it.each([ + [ + 'a canvas JSON number', + canvasToolInput({ operation: 'sailpoint_search', searchAfter: '12345' }), + ], + ['a model number', toolCallInput({ searchAfter: 12345 }, 'sailpoint_search')], + ])('sends a lone searchAfter given as %s as a one-entry string list', (_label, input) => { + const operationInput = sailpointSearchTool.operation?.input + if (!operationInput) throw new Error('SailPoint search has no operation input') + const request = operationInput({ + ...input, + tenant: 't', + accessToken: 'token', + query: { query: '*' }, + }) + expect(request).toMatchObject({ searchAfter: ['12345'] }) + }) +}) + +describe('SailPoint canvas selector gates', () => { + it('drops a review-item filter left over from a previously selected type', () => { + const input = canvasToolInput({ + operation: 'sailpoint_list_certification_review_items', + id: 'cert', + reviewItemFilterType: 'roles', + roles: 'r1', + entitlements: 'e1', + }) + expect(input.roles).toBe('r1') + expect(input.entitlements).toBeUndefined() + }) + + it('drops a stale includeUnsegmented once segmentation is turned off', () => { + const input = canvasToolInput({ + operation: 'sailpoint_list_roles', + accessModelSegmentationMode: '', + forSegmentIds: 'seg-1', + includeUnsegmented: 'false', + }) + expect(input.forSegmentIds).toBeUndefined() + expect(input.includeUnsegmented).toBeUndefined() + }) + + it('drops an identity scope that is no longer selected', () => { + const input = canvasToolInput({ + operation: 'sailpoint_get_access_request_status', + identityScopeType: 'regardingIdentity', + regardingIdentity: 'id-2', + requestedBy: 'id-1', + }) + expect(input.regardingIdentity).toBe('id-2') + expect(input.requestedBy).toBeUndefined() + }) + + it('drops a list filter expression left over when switching to a search', () => { + const input = canvasToolInput({ operation: 'sailpoint_search', filters: 'name eq "x"' }) + expect(input.filters).toBeUndefined() + expect( + canvasToolInput({ operation: 'sailpoint_search', searchFilters: '{"a":{}}' }).filters + ).toEqual({ a: {} }) + }) + + it('drops a search cursor left over when switching to list entitlements', () => { + expect( + canvasToolInput({ operation: 'sailpoint_list_entitlements', searchAfter: '["a"]' }) + .searchAfter + ).toBeUndefined() + expect( + canvasToolInput({ + operation: 'sailpoint_list_entitlements', + searchAfter: '["a"]', + entitlementSearchAfter: 'cursor-1', + }).searchAfter + ).toBe('cursor-1') + }) + + it('keeps model filters and searchAfter on tool calls', () => { + expect(toolCallInput({ filters: '{"a":{}}' }, 'sailpoint_search').filters).toBe('{"a":{}}') + expect( + toolCallInput({ searchAfter: 'cursor-2' }, 'sailpoint_list_entitlements').searchAfter + ).toBe('cursor-2') + }) +}) diff --git a/apps/sim/blocks/blocks/sailpoint.ts b/apps/sim/blocks/blocks/sailpoint.ts index b164a1633e2..2e7d2513a6d 100644 --- a/apps/sim/blocks/blocks/sailpoint.ts +++ b/apps/sim/blocks/blocks/sailpoint.ts @@ -2,6 +2,8 @@ import { SailPointIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' import { + isToolCall, + mapperOperation, normalizeFileInput, parseOptionalJsonInput, parseOptionalNumberInput, @@ -1236,7 +1238,7 @@ export const SailPointBlock: BlockConfig = { ? (operation as SailPointOperation) : 'sailpoint_search' }, - params: (params) => { + params: (params, context) => { const mapped: Record = { clientId: params.clientId, clientSecret: params.clientSecret, @@ -1263,6 +1265,29 @@ export const SailPointBlock: BlockConfig = { const parsed = parseOptionalJsonInput(value, label) if (parsed !== undefined) mapped[key] = parsed } + /** + * Search list fields accept a JSON array or the comma-separated string the tool splits + * itself (and validates), so a non-JSON string passes through instead of failing the + * whole mapping. + */ + const setList = (key: string, value: unknown) => { + try { + setJson(key, value) + } catch { + setStr(key, value) + } + } + /** + * On the canvas, advanced fields hidden behind a selector still serialize and would reach + * the tool raw under their own ids, so the ones this mapping left unset are cleared. A tool + * call never clears them: those keys hold the model's arguments. + */ + const clearUnsetOnCanvas = (...keys: string[]) => { + if (isToolCall(context)) return + for (const key of keys) { + if (!(key in mapped)) mapped[key] = undefined + } + } const applyPagination = () => { setNum('limit', params.limit) setNum('offset', params.offset) @@ -1284,9 +1309,10 @@ export const SailPointBlock: BlockConfig = { setStr('regardingIdentity', params.regardingIdentity) break } + clearUnsetOnCanvas('requestedFor', 'requestedBy', 'regardingIdentity') } const applySearchBody = () => { - setJson('indices', params.indices) + setList('indices', params.indices) setStr('queryType', params.queryType) setStr('queryVersion', params.queryVersion) setJson('query', params.query) @@ -1299,12 +1325,13 @@ export const SailPointBlock: BlockConfig = { setStr('aggregationsVersion', params.aggregationsVersion) setJson('aggregationsDsl', params.aggregationsDsl) setJson('aggregations', params.aggregations) - setJson('sort', params.sort) - setJson('searchAfter', params.searchAfter) + setList('sort', params.sort) + setList('searchAfter', params.searchAfter) setJson('filters', params.searchFilters, 'searchFilters') + clearUnsetOnCanvas('filters') } - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'sailpoint_search': applySearchBody() applyPagination() @@ -1347,7 +1374,9 @@ export const SailPointBlock: BlockConfig = { ) { setBoolean('includeUnsegmented', params.entitlementIncludeUnsegmented) } + clearUnsetOnCanvas('segmentedForIdentity', 'forSegmentIds', 'includeUnsegmented') setStr('searchAfter', params.entitlementSearchAfter) + clearUnsetOnCanvas('searchAfter') applyPagination() break case 'sailpoint_list_roles': @@ -1358,6 +1387,7 @@ export const SailPointBlock: BlockConfig = { setStr('forSegmentIds', params.forSegmentIds) setBoolean('includeUnsegmented', params.includeUnsegmented) } + clearUnsetOnCanvas('forSegmentIds', 'includeUnsegmented') applyPagination() break case 'sailpoint_get_role_entitlements': @@ -1406,6 +1436,7 @@ export const SailPointBlock: BlockConfig = { setStr('accessProfiles', params.accessProfiles) } if (params.reviewItemFilterType === 'roles') setStr('roles', params.roles) + clearUnsetOnCanvas('entitlements', 'accessProfiles', 'roles') applyPagination() break case 'sailpoint_get_identity': 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/secrets_manager.test.ts b/apps/sim/blocks/blocks/secrets_manager.test.ts new file mode 100644 index 00000000000..997b43391ab --- /dev/null +++ b/apps/sim/blocks/blocks/secrets_manager.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from 'vitest' +import { SecretsManagerBlock } from '@/blocks/blocks/secrets_manager' + +/** + * On an agent tool call the operation arrives only on `context`, and the merged row and model + * values are keyed by the tool's param names (row fields hold strings). The handler forwards + * `{ ...merged, ...mapped }`. + */ +const agentCall = (operation: string, merged: Record) => ({ + ...merged, + ...SecretsManagerBlock.tools.config?.params?.(merged, { operation }), +}) + +describe('SecretsManagerBlock agent tool calls', () => { + it('coerces the max results typed in the tool row when listing secrets', () => { + expect(agentCall('list_secrets', { maxResults: '10' })).toMatchObject({ maxResults: 10 }) + }) + + it('keeps the tags the model supplied when creating a secret', () => { + const tags = [{ Key: 'team', Value: 'core' }] + expect(agentCall('create_secret', { name: 'db', secretValue: 'x', tags })).toMatchObject({ + tags, + }) + }) +}) diff --git a/apps/sim/blocks/blocks/secrets_manager.ts b/apps/sim/blocks/blocks/secrets_manager.ts index c17b40be430..756f32d8d92 100644 --- a/apps/sim/blocks/blocks/secrets_manager.ts +++ b/apps/sim/blocks/blocks/secrets_manager.ts @@ -2,7 +2,7 @@ import { getErrorMessage } from '@sim/utils/errors' import { SecretsManagerIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' /** Parses a JSON field typed into the block, naming the field when it is invalid. */ function parseJsonField(value: unknown, fieldName: string): unknown { @@ -412,9 +412,9 @@ Return ONLY the JSON array - no explanations, no markdown code blocks.`, throw new Error(`Invalid Secrets Manager operation: ${params.operation}`) } }, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { - operation, forceDelete, recoveryWindowInDays, maxResults, @@ -457,7 +457,9 @@ Return ONLY the JSON array - no explanations, no markdown code blocks.`, result.secretValue = rest.secretValue if (rest.description) result.description = rest.description result.kmsKeyId = rest.kmsKeyId || undefined - result.tags = rest.createTags ? parseJsonField(rest.createTags, 'Tags') : undefined + result.tags = rest.createTags + ? parseJsonField(rest.createTags, 'Tags') + : toolCallArg(context, rest.tags) break case 'update_secret': result.secretId = rest.secretId diff --git a/apps/sim/blocks/blocks/sendblue.test.ts b/apps/sim/blocks/blocks/sendblue.test.ts new file mode 100644 index 00000000000..b89299686d5 --- /dev/null +++ b/apps/sim/blocks/blocks/sendblue.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from 'vitest' +import { SendblueBlock } from '@/blocks/blocks/sendblue' + +/** Runs the mapper the way a tool call does: merged row and model args under the mapper's result. */ +function resolveToolCall(args: Record, operation: string) { + const mapper = SendblueBlock.tools.config?.params + if (!mapper) throw new Error('Sendblue block has no params mapper') + return { ...args, ...mapper(args, { operation }) } +} + +describe('SendblueBlock agent tool calls', () => { + it('splits recipients saved on the tool row when the operation arrives only in context', () => { + const result = resolveToolCall( + { numbers: '+19998887777\n+13334445555', from_number: '+15550001111', content: 'hi' }, + 'sendblue_send_group_message' + ) + + expect(result.numbers).toEqual(['+19998887777', '+13334445555']) + }) + + it('keeps the typing state the model sends under the tool param name', () => { + const result = resolveToolCall( + { number: '+19998887777', state: 'stop' }, + 'sendblue_send_typing_indicator' + ) + + expect(result.state).toBe('stop') + }) +}) diff --git a/apps/sim/blocks/blocks/sendblue.ts b/apps/sim/blocks/blocks/sendblue.ts index 11648dcdb0d..a1d1a747cf6 100644 --- a/apps/sim/blocks/blocks/sendblue.ts +++ b/apps/sim/blocks/blocks/sendblue.ts @@ -1,6 +1,7 @@ import { SendblueIcon } 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 SEND_STYLE_OPTIONS = [ @@ -245,13 +246,13 @@ export const SendblueBlock: BlockConfig = { ], config: { tool: (params) => params.operation || 'sendblue_send_message', - params: (params) => { + params: (params, context) => { const base: Record = { apiKeyId: params.apiKeyId, apiSecretKey: params.apiSecretKey, } - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'sendblue_send_message': return { ...base, @@ -293,7 +294,7 @@ export const SendblueBlock: BlockConfig = { ...base, number: params.number, from_number: params.from_number || undefined, - state: params.typing_state || undefined, + state: params.typing_state || toolCallArg(context, params.state) || undefined, max_duration_ms: params.max_duration_ms !== undefined && params.max_duration_ms !== '' && diff --git a/apps/sim/blocks/blocks/sendgrid.test.ts b/apps/sim/blocks/blocks/sendgrid.test.ts new file mode 100644 index 00000000000..3b34db6a594 --- /dev/null +++ b/apps/sim/blocks/blocks/sendgrid.test.ts @@ -0,0 +1,73 @@ +/** + * Workflow runs hand a tool `{ ...rawInputs, ...mappedParams }`, and the serializer keeps advanced + * values saved under another operation, so the mapper may only rename a field for the operation it + * belongs to. Agent tool calls pass the operation in context, never in params. + */ +import { describe, expect, it } from 'vitest' +import { SendGridV2Block } from '@/blocks/blocks/sendgrid' +import { sendGridDeleteListTool } from '@/tools/sendgrid/delete_list' +import { sendGridDeleteTemplateTool } from '@/tools/sendgrid/delete_template' +import { sendGridListAllListsTool } from '@/tools/sendgrid/list_all_lists' +import { sendGridListTemplatesTool } from '@/tools/sendgrid/list_templates' +import type { ToolConfig } from '@/tools/types' + +const CREDENTIAL = { oauthCredential: 'cred-1', apiKey: 'SG.test' } + +function requestUrl(tool: ToolConfig, params: Record): URL { + const { url } = tool.request + return new URL(typeof url === 'function' ? url(params) : url) +} + +function workflowParams(inputs: Record): Record { + const mapped = SendGridV2Block.tools.config?.params?.(inputs) ?? {} + return { ...inputs, ...mapped } +} + +function agentParams(operation: string, args: Record): Record { + const inputs = { ...CREDENTIAL, ...args } + const mapped = SendGridV2Block.tools.config?.params?.(inputs, { operation }) ?? {} + return { ...inputs, ...mapped } +} + +describe('SendGrid block parameter mapping', () => { + it('deletes the template the user entered, not a Send Mail template id left behind', () => { + const params = workflowParams({ + ...CREDENTIAL, + operation: 'delete_template', + mailTemplateId: 'd-AAA', + templateId: 'd-BBB', + }) + expect(requestUrl(sendGridDeleteTemplateTool, params).pathname).toBe('/v3/templates/d-BBB') + }) + + it('ignores a list page size left behind when listing templates', () => { + const params = workflowParams({ + ...CREDENTIAL, + operation: 'list_templates', + listPageSize: '500', + }) + expect(requestUrl(sendGridListTemplatesTool, params).searchParams.get('page_size')).toBe('20') + }) + + it('maps a stored template page token on an agent tool call', () => { + const params = agentParams('list_templates', { templatePageToken: 'tok-2' }) + expect(requestUrl(sendGridListTemplatesTool, params).searchParams.get('page_token')).toBe( + 'tok-2' + ) + }) + + it('keeps the page size and token the model supplied', () => { + const params = agentParams('list_all_lists', { pageSize: 250, pageToken: 'tok-9' }) + const url = requestUrl(sendGridListAllListsTool, params) + expect(url.searchParams.get('page_size')).toBe('250') + expect(url.searchParams.get('page_token')).toBe('tok-9') + }) +}) + +describe('SendGrid path ids', () => { + it('rejects a list id that would escape the lists path', () => { + expect(() => + requestUrl(sendGridDeleteListTool, { ...CREDENTIAL, listId: '../../templates/d-XYZ' }) + ).toThrow(/listId/) + }) +}) diff --git a/apps/sim/blocks/blocks/sendgrid.ts b/apps/sim/blocks/blocks/sendgrid.ts index 65fc35240cd..a4362acb0c3 100644 --- a/apps/sim/blocks/blocks/sendgrid.ts +++ b/apps/sim/blocks/blocks/sendgrid.ts @@ -1,7 +1,7 @@ import { SendgridIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput, withSavedCredential } from '@/blocks/utils' +import { mapperOperation, normalizeFileInput, withSavedCredential } from '@/blocks/utils' import { toActiveFlag } from '@/tools/sendgrid/create_template_version' export const SendGridBlock: BlockConfig = { @@ -474,7 +474,7 @@ Return ONLY the JSON array.`, id: 'templateGenerations', title: 'Filter by Generation', type: 'short-input', - placeholder: 'legacy, dynamic, or both', + placeholder: 'legacy, dynamic, or legacy,dynamic (default: legacy only)', condition: { field: 'operation', value: 'list_templates' }, mode: 'advanced', }, @@ -626,9 +626,15 @@ Return ONLY the HTML content.`, ], config: { tool: (params) => `sendgrid_${params.operation}`, - params: (params) => { + /** + * Renames block-only fields to tool param names for the operation that runs. Advanced + * fields keep their value after the operation changes, so each rename applies only to the + * operation its field belongs to; tool-call arguments already use the tool param names and + * pass through `rest`. + */ + params: (params, context) => { + const operation = mapperOperation(params, context) const { - operation, mailSubject, mailTemplateId, listName, @@ -646,25 +652,26 @@ Return ONLY the HTML content.`, ...rest } = params - // Normalize attachments for send_mail operation const normalizedAttachments = normalizeFileInput(attachments) + const isSendMail = operation === 'send_mail' + const isListAllLists = operation === 'list_all_lists' + const isListTemplates = operation === 'list_templates' + const isTemplateVersion = operation === 'create_template_version' - // Map renamed fields back to tool parameter names return { ...rest, - ...(mailSubject && { subject: mailSubject }), - ...(mailTemplateId && { templateId: mailTemplateId }), - ...(listName && { name: listName }), - ...(templateName && { name: templateName }), - ...(versionName && { name: versionName }), - ...(templateSubject && { subject: templateSubject }), - ...(contactListIds && { listIds: contactListIds }), - ...(templateGenerations && { generations: templateGenerations }), - ...(listPageSize && { pageSize: listPageSize }), - ...(templatePageSize && { pageSize: templatePageSize }), - ...(operation === 'list_all_lists' && listPageToken && { pageToken: listPageToken }), - ...(operation === 'list_templates' && - templatePageToken && { pageToken: templatePageToken }), + ...(isSendMail && mailSubject && { subject: mailSubject }), + ...(isSendMail && mailTemplateId && { templateId: mailTemplateId }), + ...(operation === 'create_list' && listName && { name: listName }), + ...(operation === 'create_template' && templateName && { name: templateName }), + ...(isTemplateVersion && versionName && { name: versionName }), + ...(isTemplateVersion && templateSubject && { subject: templateSubject }), + ...(operation === 'add_contact' && contactListIds && { listIds: contactListIds }), + ...(isListTemplates && templateGenerations && { generations: templateGenerations }), + ...(isListAllLists && listPageSize && { pageSize: listPageSize }), + ...(isListTemplates && templatePageSize && { pageSize: templatePageSize }), + ...(isListAllLists && listPageToken && { pageToken: listPageToken }), + ...(isListTemplates && templatePageToken && { pageToken: templatePageToken }), ...(normalizedAttachments && { attachments: normalizedAttachments }), ...(active !== undefined && { active: toActiveFlag(active) }), } diff --git a/apps/sim/blocks/blocks/sentry.ts b/apps/sim/blocks/blocks/sentry.ts index 18f42e618ed..431ae4ecc1b 100644 --- a/apps/sim/blocks/blocks/sentry.ts +++ b/apps/sim/blocks/blocks/sentry.ts @@ -95,9 +95,9 @@ export const SentryBlock: BlockConfig = { { id: 'projectSlug', - title: 'Project ID', + title: 'Project ID or Slug', type: 'short-input', - placeholder: 'Numeric project ID (optional)', + placeholder: 'Project ID or slug (optional)', condition: { field: 'operation', value: 'sentry_issues_list' }, mode: 'advanced', }, @@ -206,6 +206,19 @@ Return ONLY the search query.`, value: () => '', condition: { field: 'operation', value: 'sentry_issues_update' }, }, + { + id: 'priority', + title: 'New Priority', + type: 'dropdown', + options: [ + { label: 'No Change', id: '' }, + { label: 'High', id: 'high' }, + { label: 'Medium', id: 'medium' }, + { label: 'Low', id: 'low' }, + ], + value: () => '', + condition: { field: 'operation', value: 'sentry_issues_update' }, + }, { id: 'assignedTo', title: 'Assign To', @@ -387,7 +400,7 @@ Return ONLY the search query.`, id: 'limit', title: 'Limit', type: 'short-input', - placeholder: '50', + placeholder: '10', condition: { field: 'operation', value: 'sentry_events_list' }, mode: 'advanced', }, @@ -419,9 +432,9 @@ Return ONLY the search query.`, { id: 'projectSlug', - title: 'Project ID', + title: 'Project ID or Slug', type: 'short-input', - placeholder: 'Numeric project ID (optional)', + placeholder: 'Project ID or slug (optional)', condition: { field: 'operation', value: 'sentry_releases_list' }, mode: 'advanced', }, @@ -737,6 +750,7 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, apiKey: { type: 'string', description: 'Sentry API authentication token' }, organizationSlug: { type: 'string', description: 'Organization slug' }, issueId: { type: 'string', description: 'Issue ID' }, + priority: { type: 'string', description: 'Issue priority (low, medium, high)' }, assignedTo: { type: 'string', description: 'User to assign issue to' }, isBookmarked: { type: 'boolean', description: 'Bookmark state' }, isSubscribed: { type: 'boolean', description: 'Subscription state' }, 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/ses.test.ts b/apps/sim/blocks/blocks/ses.test.ts new file mode 100644 index 00000000000..5106351c119 --- /dev/null +++ b/apps/sim/blocks/blocks/ses.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'vitest' +import { SESBlock } from '@/blocks/blocks/ses' + +/** + * On an agent tool call the operation arrives only on `context`, and the merged row and model + * values are keyed by the tool's param names (row fields hold strings). The handler forwards + * `{ ...merged, ...mapped }`. + */ +const agentCall = (operation: string, merged: Record) => ({ + ...merged, + ...SESBlock.tools.config?.params?.(merged, { operation }), +}) + +describe('SESBlock agent tool calls', () => { + it('coerces the page size typed in the tool row when listing templates', () => { + expect(agentCall('list_templates', { pageSize: '20' })).toMatchObject({ pageSize: 20 }) + }) + + it('keeps the model-supplied configuration set name and reply-to', () => { + expect( + agentCall('create_configuration_set', { configurationSetName: 'transactional' }) + ).toMatchObject({ configurationSetName: 'transactional' }) + expect(agentCall('send_bulk_email', { replyToAddresses: 'ops@example.com' })).toMatchObject({ + replyToAddresses: 'ops@example.com', + }) + }) +}) diff --git a/apps/sim/blocks/blocks/ses.ts b/apps/sim/blocks/blocks/ses.ts index ed55f6f6a02..ed0821fa9cc 100644 --- a/apps/sim/blocks/blocks/ses.ts +++ b/apps/sim/blocks/blocks/ses.ts @@ -1,7 +1,7 @@ import { SESIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { isToolCall, mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' export const SESBlock: BlockConfig = { type: 'ses', @@ -671,8 +671,9 @@ export const SESBlock: BlockConfig = { throw new Error(`Invalid SES operation: ${params.operation}`) } }, - params: (params) => { - const { operation, pageSize, ...rest } = params + params: (params, context) => { + const operation = mapperOperation(params, context) + const { pageSize, ...rest } = params const parseEmailTags = (value: unknown) => { if (value === undefined || value === null || value === '') return undefined @@ -741,7 +742,9 @@ export const SESBlock: BlockConfig = { result.emailIdentity = rest.emailIdentity break case 'create_configuration_set': - result.configurationSetName = rest.newConfigurationSetName + result.configurationSetName = isToolCall(context) + ? rest.newConfigurationSetName || rest.configurationSetName + : rest.newConfigurationSetName if (rest.customRedirectDomain) result.customRedirectDomain = rest.customRedirectDomain if (rest.httpsPolicy) result.httpsPolicy = rest.httpsPolicy if (rest.tlsPolicy) result.tlsPolicy = rest.tlsPolicy @@ -778,7 +781,10 @@ export const SESBlock: BlockConfig = { if (rest.ccAddresses) result.ccAddresses = rest.ccAddresses if (rest.bccAddresses) result.bccAddresses = rest.bccAddresses if (rest.configurationSetName) result.configurationSetName = rest.configurationSetName - applySendOptions(result, rest.templateReplyToAddresses) + applySendOptions( + result, + rest.templateReplyToAddresses || toolCallArg(context, rest.replyToAddresses) + ) break case 'send_bulk_email': result.fromAddress = rest.fromAddress @@ -786,7 +792,10 @@ export const SESBlock: BlockConfig = { result.destinations = rest.destinations if (rest.defaultTemplateData) result.defaultTemplateData = rest.defaultTemplateData if (rest.configurationSetName) result.configurationSetName = rest.configurationSetName - applySendOptions(result, rest.templateReplyToAddresses) + applySendOptions( + result, + rest.templateReplyToAddresses || toolCallArg(context, rest.replyToAddresses) + ) break case 'list_identities': if (pageSize != null) { diff --git a/apps/sim/blocks/blocks/sftp.test.ts b/apps/sim/blocks/blocks/sftp.test.ts new file mode 100644 index 00000000000..880240e6ff8 --- /dev/null +++ b/apps/sim/blocks/blocks/sftp.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from 'vitest' +import { SftpV2Block } from '@/blocks/blocks/sftp' + +/** + * On an agent tool call the operation arrives only on `context`, and the create-directory tool row + * has no Create Parent Directories field, so the mapper applies the switch's default. + */ +describe('SftpV2Block agent tool calls', () => { + it('creates parent directories by default on a create-directory call', () => { + const merged = { host: 'h', username: 'u', password: 'p', remotePath: '/a/b' } + expect({ + ...merged, + ...SftpV2Block.tools.config?.params?.(merged, { operation: 'sftp_mkdir' }), + }).toMatchObject({ recursive: true }) + }) + it('keeps recursive: false the model supplied on a create-directory call', () => { + const merged = { + host: 'h', + username: 'u', + password: 'p', + remotePath: '/a/b', + recursive: false, + } + expect({ + ...merged, + ...SftpV2Block.tools.config?.params?.(merged, { operation: 'sftp_mkdir' }), + }).toMatchObject({ recursive: false }) + }) +}) diff --git a/apps/sim/blocks/blocks/sftp.ts b/apps/sim/blocks/blocks/sftp.ts index aaf84f3126b..9cc27574f62 100644 --- a/apps/sim/blocks/blocks/sftp.ts +++ b/apps/sim/blocks/blocks/sftp.ts @@ -1,9 +1,14 @@ import { ClipboardList, Download, File, Search, Server, Trash, Upload } from '@sim/emcn/icons' import { omit } from '@sim/utils/object' import { SftpIcon } from '@/components/icons' -import type { BlockConfig, BlockMeta } from '@/blocks/types' +import type { BlockConfig, BlockMeta, BlockToolParamsContext } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { createVersionedToolSelector, normalizeFileInput } from '@/blocks/utils' +import { + createVersionedToolSelector, + mapperOperation, + normalizeFileInput, + toolCallArg, +} from '@/blocks/utils' export const SftpBlock = { type: 'sftp', @@ -227,7 +232,7 @@ export const SftpBlock = { if (operation === 'sftp_create') return 'sftp_upload' return operation }, - params: (params) => { + params: (params, context?: BlockToolParamsContext) => { const connectionConfig: Record = { host: params.host, port: @@ -244,7 +249,7 @@ export const SftpBlock = { connectionConfig.password = params.password } - const operation = params.operation || 'sftp_upload' + const operation = mapperOperation(params, context) || 'sftp_upload' switch (operation) { case 'sftp_upload': @@ -287,7 +292,8 @@ export const SftpBlock = { return { ...connectionConfig, remotePath: params.remotePath, - recursive: params.mkdirRecursive !== false, + recursive: + (params.mkdirRecursive ?? toolCallArg(context, params.recursive)) !== false, } default: return { @@ -360,8 +366,8 @@ export const SftpV2Block: BlockConfig = { params.operation === 'sftp_download' ? selectSftpV2Tool(params) : SftpBlock.tools.config.tool(params), - params: (params) => { - const input: Record = SftpBlock.tools.config.params(params) + params: (params, context) => { + const input: Record = SftpBlock.tools.config.params(params, context) return omit(input, ['encoding']) }, }, diff --git a/apps/sim/blocks/blocks/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/shopify.test.ts b/apps/sim/blocks/blocks/shopify.test.ts index e3b59fb4cb5..98bc6de02c5 100644 --- a/apps/sim/blocks/blocks/shopify.test.ts +++ b/apps/sim/blocks/blocks/shopify.test.ts @@ -27,3 +27,66 @@ describe('Shopify operation changes', () => { expect(mapParams({ operation, [idField]: id })[field]).toBeUndefined() }) }) + +describe('Shopify tool calls (operation only in context)', () => { + it.each([ + 'shopify_list_products', + 'shopify_list_orders', + 'shopify_list_customers', + 'shopify_list_collections', + 'shopify_list_locations', + ])('keeps the model query and sortKey for %s', (operation) => { + const params = mapParams({ query: 'title:Summer', sortKey: 'ID' }, { operation }) + expect(params.query).toBe('title:Summer') + expect(params.sortKey).toBe('ID') + }) + + it('keeps the model status filter when listing orders', () => { + const params = mapParams({ status: 'open' }, { operation: 'shopify_list_orders' }) + expect(params.status).toBe('open') + }) + + it('cancels an order with the model reason and notify flag', () => { + const params = mapParams( + { orderId: 'gid://shopify/Order/1', reason: 'CUSTOMER', notifyCustomer: true }, + { operation: 'shopify_cancel_order' } + ) + expect(params.reason).toBe('CUSTOMER') + expect(params.notifyCustomer).toBe(true) + }) + + it('keeps model note, email, phone and array tags when updating an order', () => { + const params = mapParams( + { + orderId: 'gid://shopify/Order/1', + note: 'Gift', + email: 'a@example.com', + phone: '+15550100', + tags: ['vip', ' rush '], + }, + { operation: 'shopify_update_order' } + ) + expect(params).toMatchObject({ + note: 'Gift', + email: 'a@example.com', + phone: '+15550100', + tags: ['vip', 'rush'], + }) + }) + + it('keeps model email, note and array tags when creating a customer', () => { + const params = mapParams( + { email: 'a@example.com', note: 'VIP', tags: ['vip'] }, + { operation: 'shopify_create_customer' } + ) + expect(params).toMatchObject({ email: 'a@example.com', note: 'VIP', tags: ['vip'] }) + }) + + it('accepts model array tags when creating a product', () => { + const params = mapParams( + { title: 'Hat', tags: ['summer', 'sale'] }, + { operation: 'shopify_create_product' } + ) + expect(params.tags).toEqual(['summer', 'sale']) + }) +}) diff --git a/apps/sim/blocks/blocks/shopify.ts b/apps/sim/blocks/blocks/shopify.ts index 2f08ab273c8..7752024358e 100644 --- a/apps/sim/blocks/blocks/shopify.ts +++ b/apps/sim/blocks/blocks/shopify.ts @@ -2,7 +2,12 @@ import { ShopifyIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { parseOptionalBooleanInput, parseOptionalNumberInput } from '@/blocks/utils' +import { + mapperOperation, + parseOptionalBooleanInput, + parseOptionalNumberInput, + toolCallArg, +} from '@/blocks/utils' const LIST_OPERATIONS = [ 'shopify_list_products', @@ -17,6 +22,20 @@ const LIST_OPERATIONS = [ 'shopify_get_inventory_level', ] as const +/** + * Parses a tag list from a comma-separated block field or an array a model sent on a tool call. + */ +function parseTagList(value: unknown): string[] | undefined { + if (Array.isArray(value)) { + return value.map((tag) => String(tag).trim()).filter(Boolean) + } + if (typeof value !== 'string') return undefined + return value + .split(',') + .map((tag) => tag.trim()) + .filter(Boolean) +} + export const ShopifyBlock: BlockConfig = { type: 'shopify', name: 'Shopify', @@ -224,6 +243,7 @@ export const ShopifyBlock: BlockConfig = { mode: 'advanced', options: [ { label: 'Shopify default', id: '' }, + { label: 'Created At', id: 'CREATED_AT' }, { label: 'Id', id: 'ID' }, { label: 'Name', id: 'NAME' }, { label: 'Relevance', id: 'RELEVANCE' }, @@ -1513,8 +1533,8 @@ export const ShopifyBlock: BlockConfig = { tool: (params) => { return params.operation || 'shopify_list_products' }, - params: (params) => { - const operation = params.operation || 'shopify_list_products' + params: (params, context) => { + const operation = mapperOperation(params, context) || 'shopify_list_products' const first = LIST_OPERATIONS.some((listOperation) => listOperation === operation) ? parseOptionalNumberInput(params.first, 'first') : undefined @@ -1579,10 +1599,7 @@ export const ShopifyBlock: BlockConfig = { descriptionHtml: params.descriptionHtml?.trim(), productType: params.productType?.trim(), vendor: params.vendor?.trim(), - tags: params.tags - ?.split(',') - .map((t: string) => t.trim()) - .filter(Boolean), + tags: parseTagList(params.tags), status: params.status || undefined, } @@ -1600,9 +1617,9 @@ export const ShopifyBlock: BlockConfig = { case 'shopify_list_products': return { ...baseParams, - sortKey: params.productsSortKey || undefined, + sortKey: params.productsSortKey || toolCallArg(context, params.sortKey), first, - query: params.productQuery?.trim(), + query: params.productQuery?.trim() || toolCallArg(context, params.query), } case 'shopify_update_product': @@ -1616,10 +1633,7 @@ export const ShopifyBlock: BlockConfig = { descriptionHtml: params.descriptionHtml?.trim(), productType: params.productType?.trim(), vendor: params.vendor?.trim(), - tags: params.tags - ?.split(',') - .map((t: string) => t.trim()) - .filter(Boolean), + tags: parseTagList(params.tags), status: params.status || undefined, } @@ -1645,10 +1659,13 @@ export const ShopifyBlock: BlockConfig = { case 'shopify_list_orders': return { ...baseParams, - sortKey: params.ordersSortKey || undefined, + sortKey: params.ordersSortKey || toolCallArg(context, params.sortKey), first, - status: params.orderStatus !== 'any' ? params.orderStatus : undefined, - query: params.orderQuery?.trim(), + status: + params.orderStatus && params.orderStatus !== 'any' + ? params.orderStatus + : toolCallArg(context, params.status), + query: params.orderQuery?.trim() || toolCallArg(context, params.query), } case 'shopify_update_order': @@ -1658,48 +1675,50 @@ export const ShopifyBlock: BlockConfig = { return { ...baseParams, orderId: params.orderId.trim(), - note: params.orderNote?.trim(), - email: params.orderEmail?.trim(), - phone: params.orderPhone?.trim(), - tags: params.orderTags - ?.split(',') - .map((t: string) => t.trim()) - .filter(Boolean), + note: params.orderNote?.trim() ?? toolCallArg(context, params.note), + email: params.orderEmail?.trim() ?? toolCallArg(context, params.email), + phone: params.orderPhone?.trim() ?? toolCallArg(context, params.phone), + tags: + parseTagList(params.orderTags) ?? toolCallArg(context, parseTagList(params.tags)), } case 'shopify_cancel_order': if (!params.orderId?.trim()) { throw new Error('Order ID is required.') } - if (!params.cancelReason) { - throw new Error('Cancel reason is required.') - } - return { - ...baseParams, - orderId: params.orderId.trim(), - reason: params.cancelReason, - restock: parseOptionalBooleanInput(params.restock) ?? false, - notifyCustomer: parseOptionalBooleanInput(params.cancelNotifyCustomer), - refundMethod: - params.refundMethod || - (parseOptionalBooleanInput(params.refundOriginalPayment) === true - ? { originalPaymentMethodsRefund: true } - : undefined), - staffNote: params.staffNote?.trim(), + { + const reason = params.cancelReason || toolCallArg(context, params.reason) + if (!reason) { + throw new Error('Cancel reason is required.') + } + return { + ...baseParams, + orderId: params.orderId.trim(), + reason, + restock: parseOptionalBooleanInput(params.restock) ?? false, + notifyCustomer: + parseOptionalBooleanInput(params.cancelNotifyCustomer) ?? + toolCallArg(context, parseOptionalBooleanInput(params.notifyCustomer)), + refundMethod: + params.refundMethod || + (parseOptionalBooleanInput(params.refundOriginalPayment) === true + ? { originalPaymentMethodsRefund: true } + : undefined), + staffNote: params.staffNote?.trim(), + } } case 'shopify_create_customer': return { ...baseParams, - email: params.customerEmail?.trim(), + email: params.customerEmail?.trim() ?? toolCallArg(context, params.email), firstName: params.firstName?.trim(), lastName: params.lastName?.trim(), phone: params.phone?.trim(), - note: params.customerNote?.trim(), - tags: params.customerTags - ?.split(',') - .map((t: string) => t.trim()) - .filter(Boolean), + note: params.customerNote?.trim() ?? toolCallArg(context, params.note), + tags: + parseTagList(params.customerTags) ?? + toolCallArg(context, parseTagList(params.tags)), } case 'shopify_get_customer': @@ -1714,9 +1733,9 @@ export const ShopifyBlock: BlockConfig = { case 'shopify_list_customers': return { ...baseParams, - sortKey: params.customersSortKey || undefined, + sortKey: params.customersSortKey || toolCallArg(context, params.sortKey), first, - query: params.customerQuery?.trim(), + query: params.customerQuery?.trim() || toolCallArg(context, params.query), } case 'shopify_update_customer': @@ -1726,15 +1745,14 @@ export const ShopifyBlock: BlockConfig = { return { ...baseParams, customerId: params.customerId.trim(), - email: params.customerEmail?.trim(), + email: params.customerEmail?.trim() ?? toolCallArg(context, params.email), firstName: params.firstName?.trim(), lastName: params.lastName?.trim(), phone: params.phone?.trim(), - note: params.customerNote?.trim(), - tags: params.customerTags - ?.split(',') - .map((t: string) => t.trim()) - .filter(Boolean), + note: params.customerNote?.trim() ?? toolCallArg(context, params.note), + tags: + parseTagList(params.customerTags) ?? + toolCallArg(context, parseTagList(params.tags)), } case 'shopify_delete_customer': @@ -1750,7 +1768,7 @@ export const ShopifyBlock: BlockConfig = { return { ...baseParams, first, - query: params.inventoryQuery?.trim(), + query: params.inventoryQuery?.trim() || toolCallArg(context, params.query), } case 'shopify_get_inventory_level': @@ -1787,11 +1805,11 @@ export const ShopifyBlock: BlockConfig = { case 'shopify_list_locations': return { ...baseParams, - sortKey: params.locationsSortKey || undefined, + sortKey: params.locationsSortKey || toolCallArg(context, params.sortKey), first, includeInactive: parseOptionalBooleanInput(params.includeInactive), includeLegacy: parseOptionalBooleanInput(params.includeLegacy), - query: params.locationQuery?.trim(), + query: params.locationQuery?.trim() || toolCallArg(context, params.query), } case 'shopify_create_fulfillment': @@ -1810,9 +1828,9 @@ export const ShopifyBlock: BlockConfig = { case 'shopify_list_collections': return { ...baseParams, - sortKey: params.collectionsSortKey || undefined, + sortKey: params.collectionsSortKey || toolCallArg(context, params.sortKey), first, - query: params.collectionQuery?.trim(), + query: params.collectionQuery?.trim() || toolCallArg(context, params.query), } case 'shopify_get_collection': @@ -1841,7 +1859,9 @@ export const ShopifyBlock: BlockConfig = { return { ...baseParams, fulfillmentId: params.fulfillmentId?.trim(), - notifyCustomer: parseOptionalBooleanInput(params.trackingNotifyCustomer), + notifyCustomer: + parseOptionalBooleanInput(params.trackingNotifyCustomer) ?? + toolCallArg(context, parseOptionalBooleanInput(params.notifyCustomer)), } default: return baseParams diff --git a/apps/sim/blocks/blocks/sixtyfour.test.ts b/apps/sim/blocks/blocks/sixtyfour.test.ts new file mode 100644 index 00000000000..1827ce6b4c0 --- /dev/null +++ b/apps/sim/blocks/blocks/sixtyfour.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest' +import { SixtyfourBlock } from '@/blocks/blocks/sixtyfour' + +/** Runs the mapper the way a tool call does: merged row and model args under the mapper's result. */ +function resolveToolCall(args: Record, operation: string) { + const mapper = SixtyfourBlock.tools.config?.params + if (!mapper) throw new Error('Sixtyfour block has no params mapper') + return { ...args, ...mapper(args, { operation }) } +} + +describe('SixtyfourBlock agent tool calls', () => { + it('maps the struct saved on the tool row when the operation arrives only in context', () => { + const struct = { website: 'Company website' } + const result = resolveToolCall( + { targetCompany: { name: 'Acme' }, companyStruct: struct }, + 'enrich_company' + ) + + expect(result.struct).toEqual(struct) + }) + + it('keeps the struct the model sends under the tool param name', () => { + const struct = { title: 'Job title' } + const result = resolveToolCall({ leadInfo: { name: 'Ada' }, struct }, 'enrich_lead') + + expect(result.struct).toEqual(struct) + }) +}) diff --git a/apps/sim/blocks/blocks/sixtyfour.ts b/apps/sim/blocks/blocks/sixtyfour.ts index 1a4cdeefacf..a16c28ad78d 100644 --- a/apps/sim/blocks/blocks/sixtyfour.ts +++ b/apps/sim/blocks/blocks/sixtyfour.ts @@ -1,6 +1,6 @@ import { SixtyfourIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' const PHONE_LOOKUP_FIELD = ['name', 'linkedinUrl', 'emailInput'] as const const EMAIL_LOOKUP_FIELD = ['name', 'linkedinUrl', 'phoneInput'] as const @@ -223,20 +223,21 @@ export const SixtyfourBlock: BlockConfig = { ], config: { tool: (params) => `sixtyfour_${params.operation}`, - params: (params) => { + params: (params, context) => { const result: Record = {} + const operation = mapperOperation(params, context) - if (params.operation === 'find_phone') { + if (operation === 'find_phone') { if (params.emailInput) result.email = params.emailInput - } else if (params.operation === 'find_email') { + } else if (operation === 'find_email') { if (params.phoneInput) result.phone = params.phoneInput - } else if (params.operation === 'enrich_lead') { + } else if (operation === 'enrich_lead') { result.leadInfo = params.leadInfo - result.struct = params.leadStruct + result.struct = params.leadStruct ?? toolCallArg(context, params.struct) if (params.leadResearchPlan) result.researchPlan = params.leadResearchPlan - } else if (params.operation === 'enrich_company') { + } else if (operation === 'enrich_company') { result.targetCompany = params.targetCompany - result.struct = params.companyStruct + result.struct = params.companyStruct ?? toolCallArg(context, params.struct) if (params.findPeople !== undefined) result.findPeople = Boolean(params.findPeople) if (params.fullOrgChart !== undefined) result.fullOrgChart = Boolean(params.fullOrgChart) if (params.peopleFocusPrompt) result.peopleFocusPrompt = params.peopleFocusPrompt diff --git a/apps/sim/blocks/blocks/slack-workflow-operations.test.ts b/apps/sim/blocks/blocks/slack-workflow-operations.test.ts index 3597b4d26db..6f655f9b313 100644 --- a/apps/sim/blocks/blocks/slack-workflow-operations.test.ts +++ b/apps/sim/blocks/blocks/slack-workflow-operations.test.ts @@ -58,9 +58,22 @@ describe('Slack workflow operations in the existing block', () => { ).toEqual({ credential: 'bot', channel_id: 'C1', bookmark_id: 'Bk1', emoji: '' }) expect(() => mapParams({ operation: 'list_files', slack_list_files_count: 'many' })).toThrow() expect(() => - mapParams({ operation: 'share_canvas', slack_share_canvas_user_ids: 'invalid JSON' }) + mapParams({ + operation: 'revoke_list_access', + slack_revoke_list_access_user_ids: 'invalid JSON', + }) ).toThrow() }) + + it("passes a Slack ID list's comma-separated form through for the tool to parse", () => { + expect( + mapParams({ + operation: 'get_team_dnd_info', + apiBotCredentialId: 'bot', + slack_get_team_dnd_info_users: 'U1,U2', + }) + ).toEqual({ credential: 'bot', users: 'U1,U2' }) + }) }) describe('Slack custom-app permissions', () => { diff --git a/apps/sim/blocks/blocks/slack-workflow-operations.ts b/apps/sim/blocks/blocks/slack-workflow-operations.ts index 0f1ce5f1924..7fe319b01db 100644 --- a/apps/sim/blocks/blocks/slack-workflow-operations.ts +++ b/apps/sim/blocks/blocks/slack-workflow-operations.ts @@ -1,9 +1,10 @@ import { getScopesForService } from '@/lib/oauth/utils' -import type { BlockConfig, SubBlockConfig } from '@/blocks/types' +import type { BlockConfig, BlockToolParamsContext, SubBlockConfig } from '@/blocks/types' import { parseOptionalBooleanInput, parseOptionalJsonInput, parseOptionalNumberInput, + toolCallArg, } from '@/blocks/utils' interface SlackWorkflowField { @@ -17,6 +18,8 @@ interface SlackWorkflowField { dependsOn?: string[] default?: string allowEmpty?: boolean + /** A Slack ID list: Slack's comma-separated form (`U1,U2`) is passed through for the tool to parse. */ + idList?: boolean basic?: boolean min?: number max?: number @@ -214,6 +217,7 @@ export const SLACK_WORKFLOW_OPERATIONS: readonly SlackWorkflowOperation[] = [ param: 'user_ids', title: 'User IDs', type: 'json', + idList: true, required: false, }, { @@ -222,6 +226,7 @@ export const SLACK_WORKFLOW_OPERATIONS: readonly SlackWorkflowOperation[] = [ param: 'channel_ids', title: 'Channel IDs', type: 'json', + idList: true, required: false, }, ], @@ -245,6 +250,7 @@ export const SLACK_WORKFLOW_OPERATIONS: readonly SlackWorkflowOperation[] = [ param: 'user_ids', title: 'User IDs', type: 'json', + idList: true, required: false, }, { @@ -253,6 +259,7 @@ export const SLACK_WORKFLOW_OPERATIONS: readonly SlackWorkflowOperation[] = [ param: 'channel_ids', title: 'Channel IDs', type: 'json', + idList: true, required: false, }, ], @@ -373,6 +380,7 @@ export const SLACK_WORKFLOW_OPERATIONS: readonly SlackWorkflowOperation[] = [ param: 'users', title: 'User IDs', type: 'json', + idList: true, required: false, }, { @@ -945,6 +953,7 @@ export const SLACK_WORKFLOW_OPERATIONS: readonly SlackWorkflowOperation[] = [ param: 'channels', title: 'Default Channel IDs', type: 'json', + idList: true, required: false, }, { @@ -952,6 +961,7 @@ export const SLACK_WORKFLOW_OPERATIONS: readonly SlackWorkflowOperation[] = [ param: 'additional_channels', title: 'Additional Channel IDs', type: 'json', + idList: true, required: false, }, { @@ -1021,6 +1031,7 @@ export const SLACK_WORKFLOW_OPERATIONS: readonly SlackWorkflowOperation[] = [ param: 'channels', title: 'Default Channel IDs', type: 'json', + idList: true, required: false, }, { @@ -1028,6 +1039,7 @@ export const SLACK_WORKFLOW_OPERATIONS: readonly SlackWorkflowOperation[] = [ param: 'additional_channels', title: 'Additional Channel IDs', type: 'json', + idList: true, required: false, }, { @@ -1194,6 +1206,7 @@ export const SLACK_WORKFLOW_OPERATIONS: readonly SlackWorkflowOperation[] = [ param: 'users', title: 'User IDs', type: 'json', + idList: true, required: true, }, { @@ -1201,6 +1214,7 @@ export const SLACK_WORKFLOW_OPERATIONS: readonly SlackWorkflowOperation[] = [ param: 'additional_channels', title: 'Additional Channel IDs', type: 'json', + idList: true, required: false, }, { @@ -1259,6 +1273,7 @@ export const SLACK_WORKFLOW_OPERATIONS: readonly SlackWorkflowOperation[] = [ param: 'users', title: 'User IDs', type: 'json', + idList: true, required: true, }, { @@ -1420,20 +1435,36 @@ export function getSlackWorkflowSubBlocks(): SubBlockConfig[] { return result } +/** + * Maps a workflow operation's `slack__` block fields to its tool params. On a tool call + * those fields are absent and the model's args arrive under the tool's param names; an empty field + * then leaves the model's value in place instead of writing the field's default over it. + */ export function mapSlackWorkflowParams( operation: SlackWorkflowOperation, - params: Record + params: Record, + context?: BlockToolParamsContext ): Record { const result: Record = { - credential: params[operation.auth === 'bot' ? 'apiBotCredentialId' : 'apiOAuthCredentialId'], + credential: + params[operation.auth === 'bot' ? 'apiBotCredentialId' : 'apiOAuthCredentialId'] ?? + toolCallArg(context, params.credential), } for (const field of operation.fields) { const raw = params[field.id] - const value = - raw === undefined || raw === null || (raw === '' && !field.allowEmpty) ? field.default : raw + const isEmpty = raw === undefined || raw === null || (raw === '' && !field.allowEmpty) + if (isEmpty && toolCallArg(context, params[field.param]) !== undefined) continue + const value = isEmpty ? field.default : raw if (value === undefined) continue - if (field.type === 'json') result[field.param] = parseOptionalJsonInput(value, field.title) - else if (field.type === 'number') + if (field.type === 'json') { + const csvIdList = + field.idList === true && + typeof value === 'string' && + value.trim() !== '' && + !/^\s*[[{"]/.test(value) + if (csvIdList) result[field.param] = value + else result[field.param] = parseOptionalJsonInput(value, field.title) + } else if (field.type === 'number') result[field.param] = parseOptionalNumberInput(value, field.title, { integer: true, min: field.min, diff --git a/apps/sim/blocks/blocks/slack.test.ts b/apps/sim/blocks/blocks/slack.test.ts index ba244f1b057..bc0f68f1c5a 100644 --- a/apps/sim/blocks/blocks/slack.test.ts +++ b/apps/sim/blocks/blocks/slack.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import { evaluateSubBlockCondition } from '@/lib/workflows/subblocks/visibility' -import { SlackV2Block } from '@/blocks/blocks/slack' +import { SlackBlock, SlackV2Block } from '@/blocks/blocks/slack' function mapSlackV2Params(params: Record): Record { const mapParams = SlackV2Block.tools.config?.params @@ -8,6 +8,20 @@ function mapSlackV2Params(params: Record): Record +): Record { + const mapParams = block.tools.config?.params + if (!mapParams) throw new Error('Slack parameter mapper is required') + return { ...merged, ...mapParams(merged, { operation }) } +} + function isSlackV2SubBlockVisible(subBlockId: string, values: Record): boolean { const subBlock = SlackV2Block.subBlocks.find((candidate) => candidate.id === subBlockId) if (!subBlock) throw new Error(`Slack v2 subblock not found: ${subBlockId}`) @@ -110,4 +124,94 @@ describe('Slack block release', () => { { limit: 100 } ) }) + + describe('tool calls (operation only in context)', () => { + it('sends the stored bot credential for workflow operations', () => { + expect( + toolCall(SlackV2Block, 'add_bookmark', { + apiBotCredentialId: 'bot-cred', + channel_id: 'C1', + title: 'Docs', + link: 'https://example.com', + }) + ).toMatchObject({ credential: 'bot-cred', channel_id: 'C1', title: 'Docs' }) + }) + + it('keeps the model value over a workflow field default', () => { + expect( + toolCall(SlackV2Block, 'get_team_profile', { + apiBotCredentialId: 'bot-cred', + visibility: 'hidden', + }) + ).toMatchObject({ credential: 'bot-cred', visibility: 'hidden' }) + }) + + it('maps stored workflow fields when the model omits them', () => { + expect( + toolCall(SlackV2Block, 'list_files', { + apiOAuthCredentialId: 'cred', + slack_list_files_channel: 'C123', + }) + ).toMatchObject({ credential: 'cred', channel: 'C123' }) + }) + + it('keeps model args the v1 branches would otherwise overwrite', () => { + expect( + toolCall(SlackBlock, 'edit_canvas', { + oauthCredential: 'cred', + canvasId: 'F1', + operation: 'insert_at_end', + content: 'x', + }) + ).toMatchObject({ credential: 'cred', canvasId: 'F1', operation: 'insert_at_end' }) + expect( + toolCall(SlackBlock, 'get_channel_history', { channel: 'C1', inclusive: true }) + ).toMatchObject({ inclusive: true }) + expect(toolCall(SlackBlock, 'list_users', { includeDeleted: true, limit: 5 })).toMatchObject({ + includeDeleted: true, + limit: 5, + }) + expect( + toolCall(SlackBlock, 'list_channels', { includePrivate: false, limit: 20 }) + ).toMatchObject({ includePrivate: false, limit: 20 }) + expect(toolCall(SlackBlock, 'list_channels', { excludeArchived: false })).toMatchObject({ + excludeArchived: false, + }) + expect( + toolCall(SlackBlock, 'schedule_message', { channel: 'C1', text: 'hi', postAt: 1900000000 }) + ).toMatchObject({ postAt: 1900000000 }) + expect( + toolCall(SlackBlock, 'update_view', { externalId: 'ext-1', view: { type: 'modal' } }) + ).toMatchObject({ externalId: 'ext-1', view: { type: 'modal' } }) + }) + + it('maps stored v1 fields under their tool param names', () => { + expect( + toolCall(SlackV2Block, 'lookup_canvas_sections', { + oauthCredential: 'cred', + lookupCanvasId: 'F1', + sectionCriteria: '{"contains_text":"x"}', + }) + ).toMatchObject({ canvasId: 'F1', criteria: '{"contains_text":"x"}' }) + }) + + it('keeps model args for List and agent session operations', () => { + expect( + toolCall(SlackV2Block, 'list_items', { + listCredentialId: 'bot', + listId: 'L1', + limit: 10, + cursor: 'c1', + }) + ).toMatchObject({ credential: 'bot', listId: 'L1', limit: 10, cursor: 'c1' }) + expect( + toolCall(SlackV2Block, 'set_agent_session_status', { + agentCredentialId: 'bot', + channel: 'C1', + threadTs: '1.2', + status: 'processing', + }) + ).toMatchObject({ credential: 'bot', channel: 'C1', threadTs: '1.2', status: 'processing' }) + }) + }) }) diff --git a/apps/sim/blocks/blocks/slack.ts b/apps/sim/blocks/blocks/slack.ts index 54b6e93cee3..5ff889943bf 100644 --- a/apps/sim/blocks/blocks/slack.ts +++ b/apps/sim/blocks/blocks/slack.ts @@ -10,13 +10,16 @@ import { SLACK_WORKFLOW_OPERATIONS, SLACK_WORKFLOW_SENTENCES, } from '@/blocks/blocks/slack-workflow-operations' -import type { BlockConfig, BlockMeta, SubBlockConfig } from '@/blocks/types' +import type { BlockConfig, BlockMeta, BlockToolParamsContext, SubBlockConfig } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' import { + isToolCall, + mapperOperation, normalizeFileInput, parseOptionalBooleanInput, parseOptionalJsonInput, parseOptionalNumberInput, + toolCallArg, } from '@/blocks/utils' import { getTrigger } from '@/triggers' import { SLACK_AGENT_SCOPES } from '@/triggers/slack/shared' @@ -1045,7 +1048,7 @@ Return ONLY the JSON array - no explanations, no quotes around the array, no ext id: 'historyMaxPages', title: 'Max Pages', type: 'short-input', - placeholder: '10', + placeholder: '10 (max 50)', mode: 'advanced', condition: { field: 'operation', @@ -1508,7 +1511,6 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, field: 'operation', value: ['open_view', 'push_view'], }, - required: true, }, { id: 'viewInteractivityPointer', @@ -1877,13 +1879,13 @@ Return ONLY the integer Unix timestamp - no explanations, no quotes, no extra te throw new Error(`Invalid Slack operation: ${params.operation}`) } }, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { oauthCredential, authMethod, botToken, botCredential, - operation, destinationType, channel, dmUserId, @@ -2013,7 +2015,9 @@ Return ONLY the integer Unix timestamp - no explanations, no quotes, no extra te case 'ephemeral': { baseParams.text = messageFormat === 'blocks' && !text ? ' ' : text - baseParams.user = ephemeralUser ? String(ephemeralUser).trim() : '' + baseParams.user = ephemeralUser + ? String(ephemeralUser).trim() + : (toolCallArg(context, params.user) ?? '') if (threadTs) { baseParams.threadTs = threadTs } @@ -2041,11 +2045,11 @@ Return ONLY the integer Unix timestamp - no explanations, no quotes, no extra te } case 'get_message': - baseParams.timestamp = getMessageTimestamp + baseParams.timestamp = getMessageTimestamp ?? toolCallArg(context, params.timestamp) break case 'get_thread': { - baseParams.threadTs = getThreadTimestamp + baseParams.threadTs = getThreadTimestamp ?? toolCallArg(context, params.threadTs) if (threadLimit) { const parsedLimit = Number.parseInt(threadLimit, 10) if (!Number.isNaN(parsedLimit) && parsedLimit > 0) { @@ -2056,7 +2060,7 @@ Return ONLY the integer Unix timestamp - no explanations, no quotes, no extra te } case 'set_status': { - baseParams.threadTs = getThreadTimestamp + baseParams.threadTs = getThreadTimestamp ?? toolCallArg(context, params.threadTs) baseParams.status = status ?? '' if (loadingMessages) { baseParams.loadingMessages = loadingMessages @@ -2065,14 +2069,14 @@ Return ONLY the integer Unix timestamp - no explanations, no quotes, no extra te } case 'set_title': { - baseParams.threadTs = getThreadTimestamp - baseParams.title = assistantTitle + baseParams.threadTs = getThreadTimestamp ?? toolCallArg(context, params.threadTs) + baseParams.title = assistantTitle ?? toolCallArg(context, params.title) break } case 'set_suggested_prompts': { - baseParams.threadTs = getThreadTimestamp - baseParams.prompts = suggestedPrompts + baseParams.threadTs = getThreadTimestamp ?? toolCallArg(context, params.threadTs) + baseParams.prompts = suggestedPrompts ?? toolCallArg(context, params.prompts) if (promptsTitle) { baseParams.promptsTitle = promptsTitle } @@ -2080,14 +2084,14 @@ Return ONLY the integer Unix timestamp - no explanations, no quotes, no extra te } case 'get_permalink': { - baseParams.messageTs = getMessageTimestamp + baseParams.messageTs = getMessageTimestamp ?? toolCallArg(context, params.messageTs) break } case 'get_channel_history': case 'get_thread_replies': { if (operation === 'get_thread_replies') { - baseParams.threadTs = getThreadTimestamp + baseParams.threadTs = getThreadTimestamp ?? toolCallArg(context, params.threadTs) } if (historyOldest) { baseParams.oldest = String(historyOldest).trim() @@ -2110,18 +2114,28 @@ Return ONLY the integer Unix timestamp - no explanations, no quotes, no extra te if (historyCursor) { baseParams.cursor = String(historyCursor).trim() } - baseParams.inclusive = historyInclusive === 'true' + baseParams.inclusive = + historyInclusive === undefined + ? (toolCallArg(context, params.inclusive) ?? false) + : historyInclusive === 'true' || historyInclusive === true break } case 'list_channels': { - baseParams.includePrivate = includePrivate !== 'false' - baseParams.excludeArchived = true + baseParams.includePrivate = includePrivate !== 'false' && includePrivate !== false + const modelExcludeArchived = toolCallArg(context, params.excludeArchived) + baseParams.excludeArchived = + modelExcludeArchived !== false && modelExcludeArchived !== 'false' const hasChannelLimit = channelLimit !== undefined && channelLimit !== null && (typeof channelLimit !== 'string' || Boolean(channelLimit.trim())) - const parsedLimit = hasChannelLimit ? Number(channelLimit) : 100 + const modelLimit = toolCallArg(context, params.limit) + const parsedLimit = hasChannelLimit + ? Number(channelLimit) + : modelLimit === undefined || modelLimit === null || modelLimit === '' + ? 100 + : Number(modelLimit) if (!Number.isInteger(parsedLimit) || parsedLimit < 1 || parsedLimit > 200) { throw new Error('Conversations per page must be an integer between 1 and 200') } @@ -2133,7 +2147,9 @@ Return ONLY the integer Unix timestamp - no explanations, no quotes, no extra te } case 'list_members': { - baseParams.limit = memberLimit ? Number.parseInt(memberLimit, 10) : 100 + baseParams.limit = memberLimit + ? Number.parseInt(memberLimit, 10) + : (toolCallArg(context, params.limit) ?? 100) if (paginationCursor) { baseParams.cursor = String(paginationCursor).trim() } @@ -2141,8 +2157,10 @@ Return ONLY the integer Unix timestamp - no explanations, no quotes, no extra te } case 'list_users': { - baseParams.includeDeleted = includeDeleted === 'true' - baseParams.limit = userLimit ? Number.parseInt(userLimit, 10) : 100 + baseParams.includeDeleted = includeDeleted === 'true' || includeDeleted === true + baseParams.limit = userLimit + ? Number.parseInt(userLimit, 10) + : (toolCallArg(context, params.limit) ?? 100) if (paginationCursor) { baseParams.cursor = String(paginationCursor).trim() } @@ -2161,35 +2179,41 @@ Return ONLY the integer Unix timestamp - no explanations, no quotes, no extra te break } - case 'update': - baseParams.timestamp = updateTimestamp - baseParams.text = messageFormat === 'blocks' && !updateText ? ' ' : updateText + case 'update': { + baseParams.timestamp = updateTimestamp ?? toolCallArg(context, params.timestamp) + const updateBody = updateText ?? toolCallArg(context, params.text) + baseParams.text = messageFormat === 'blocks' && !updateBody ? ' ' : updateBody if (blocks) { baseParams.blocks = blocks } break + } case 'delete': - baseParams.timestamp = deleteTimestamp + baseParams.timestamp = deleteTimestamp ?? toolCallArg(context, params.timestamp) break case 'react': case 'unreact': - baseParams.timestamp = reactionTimestamp - baseParams.name = emojiName + baseParams.timestamp = reactionTimestamp ?? toolCallArg(context, params.timestamp) + baseParams.name = emojiName ?? toolCallArg(context, params.name) break case 'get_channel_info': - baseParams.includeNumMembers = includeNumMembers !== 'false' + baseParams.includeNumMembers = + includeNumMembers !== 'false' && includeNumMembers !== false break case 'get_user_presence': - baseParams.userId = presenceUserId + baseParams.userId = presenceUserId ?? toolCallArg(context, params.userId) break case 'edit_canvas': - baseParams.canvasId = editCanvasId - baseParams.operation = canvasOperation + baseParams.canvasId = editCanvasId ?? toolCallArg(context, params.canvasId) + // A tool call's own `operation` arg (the edit kind) stays in the merged params. + if (canvasOperation !== undefined || !isToolCall(context)) { + baseParams.operation = canvasOperation + } if (canvasContent) { baseParams.content = canvasContent } @@ -2211,18 +2235,20 @@ Return ONLY the integer Unix timestamp - no explanations, no quotes, no extra te break case 'get_canvas': - baseParams.canvasId = getCanvasId + baseParams.canvasId = getCanvasId ?? toolCallArg(context, params.canvasId) break case 'list_canvases': - baseParams.count = parseOptionalNumberInput(canvasListCount, 'Canvas Limit', { - integer: true, - min: 1, - }) - baseParams.page = parseOptionalNumberInput(canvasListPage, 'Canvas Page', { - integer: true, - min: 1, - }) + baseParams.count = + parseOptionalNumberInput(canvasListCount, 'Canvas Limit', { + integer: true, + min: 1, + }) ?? toolCallArg(context, params.count) + baseParams.page = + parseOptionalNumberInput(canvasListPage, 'Canvas Page', { + integer: true, + min: 1, + }) ?? toolCallArg(context, params.page) if (canvasListUser) { baseParams.user = String(canvasListUser).trim() } @@ -2238,40 +2264,41 @@ Return ONLY the integer Unix timestamp - no explanations, no quotes, no extra te break case 'lookup_canvas_sections': - baseParams.canvasId = lookupCanvasId - baseParams.criteria = sectionCriteria + baseParams.canvasId = lookupCanvasId ?? toolCallArg(context, params.canvasId) + baseParams.criteria = sectionCriteria ?? toolCallArg(context, params.criteria) break case 'delete_canvas': - baseParams.canvasId = deleteCanvasId + baseParams.canvasId = deleteCanvasId ?? toolCallArg(context, params.canvasId) break case 'create_conversation': - baseParams.name = conversationName - baseParams.isPrivate = isPrivate === 'true' + baseParams.name = conversationName ?? toolCallArg(context, params.name) + baseParams.isPrivate = isPrivate === 'true' || isPrivate === true if (teamId) { baseParams.teamId = teamId } break case 'invite_to_conversation': - baseParams.users = inviteUsers + baseParams.users = inviteUsers ?? toolCallArg(context, params.users) if (inviteForce === 'true') { baseParams.force = true } break case 'open_view': - baseParams.triggerId = viewTriggerId + baseParams.triggerId = viewTriggerId ?? toolCallArg(context, params.triggerId) if (viewInteractivityPointer) { baseParams.interactivityPointer = viewInteractivityPointer } - baseParams.view = viewPayload + baseParams.view = viewPayload ?? toolCallArg(context, params.view) break case 'update_view': { const trimmedViewId = viewId ? String(viewId).trim() : '' - const trimmedExternalId = viewExternalId ? String(viewExternalId).trim() : '' + const externalId = viewExternalId || toolCallArg(context, params.externalId) + const trimmedExternalId = externalId ? String(externalId).trim() : '' if (!trimmedViewId && !trimmedExternalId) { throw new Error('update_view requires either View ID or External ID') } @@ -2284,24 +2311,24 @@ Return ONLY the integer Unix timestamp - no explanations, no quotes, no extra te if (viewHash) { baseParams.hash = viewHash } - baseParams.view = viewPayload + baseParams.view = viewPayload ?? toolCallArg(context, params.view) break } case 'push_view': - baseParams.triggerId = viewTriggerId + baseParams.triggerId = viewTriggerId ?? toolCallArg(context, params.triggerId) if (viewInteractivityPointer) { baseParams.interactivityPointer = viewInteractivityPointer } - baseParams.view = viewPayload + baseParams.view = viewPayload ?? toolCallArg(context, params.view) break case 'publish_view': - baseParams.userId = publishUserId + baseParams.userId = publishUserId ?? toolCallArg(context, params.userId) if (viewHash) { baseParams.hash = viewHash } - baseParams.view = viewPayload + baseParams.view = viewPayload ?? toolCallArg(context, params.view) break case 'schedule_message': { @@ -2312,7 +2339,8 @@ Return ONLY the integer Unix timestamp - no explanations, no quotes, no extra te if (threadTs) { baseParams.threadTs = threadTs } - const parsedPostAt = Number.parseInt(String(scheduleAt ?? '').trim(), 10) + const postAt = scheduleAt ?? toolCallArg(context, params.postAt) + const parsedPostAt = Number.parseInt(String(postAt ?? '').trim(), 10) if (Number.isNaN(parsedPostAt)) { throw new Error('Send At must be a Unix timestamp in seconds') } @@ -2341,15 +2369,15 @@ Return ONLY the integer Unix timestamp - no explanations, no quotes, no extra te break case 'rename_conversation': - baseParams.name = renameChannelName + baseParams.name = renameChannelName ?? toolCallArg(context, params.name) break case 'set_conversation_topic': - baseParams.topic = conversationTopic + baseParams.topic = conversationTopic ?? toolCallArg(context, params.topic) break case 'set_conversation_purpose': - baseParams.purpose = conversationPurpose + baseParams.purpose = conversationPurpose ?? toolCallArg(context, params.purpose) break } @@ -2598,6 +2626,8 @@ Return ONLY the integer Unix timestamp - no explanations, no quotes, no extra te type: 'json', description: 'Array of user IDs who are members of the channel', }, + ids: { type: 'json', description: 'IDs of the returned channels or users' }, + names: { type: 'json', description: 'Names of the returned channels or users' }, users: { type: 'json', @@ -3017,12 +3047,8 @@ function getSlackV2AgentSubBlocks(): SubBlockConfig[] { id: 'agentThreadTs', title: 'Thread Timestamp', type: 'short-input', - placeholder: 'Thread timestamp (thread_ts)', + placeholder: 'Thread timestamp (thread_ts); leave empty for session channels', condition: { field: 'operation', value: [...SLACK_V2_AGENT_OPERATIONS] }, - required: { - field: 'operation', - value: ['set_agent_session_status', 'rename_agent_session'], - }, }, { id: 'agentSessionStatus', @@ -3102,9 +3128,19 @@ function getSlackV2AgentSubBlocks(): SubBlockConfig[] { ] } -function mapSlackListParams(params: Record): Record { +/** + * Maps a Slack List operation's block fields to its tool params. On a tool call the block-only + * fields are absent and the model's args arrive under the tool's param names, so each assignment + * falls back to the model's value through {@link toolCallArg}. + */ +function mapSlackListParams( + operation: string, + params: Record, + context: BlockToolParamsContext | undefined +): Record { + const modelArg = (param: string) => toolCallArg(context, params[param]) const result: Record = { - credential: params.listCredentialId, + credential: params.listCredentialId ?? modelArg('credential'), listId: params.listId, } const optional = (field: string) => { @@ -3117,56 +3153,63 @@ function mapSlackListParams(params: Record): Record { - const operation = getSlackWorkflowOperation(params.operation) - if (operation) return mapSlackWorkflowParams(operation, params) - if (SLACK_V2_LIST_OPERATIONS.includes(params.operation as never)) { - return mapSlackListParams(params) + params: (params, context) => { + const operationId = mapperOperation(params, context) + const workflowOperation = getSlackWorkflowOperation(operationId) + if (workflowOperation) return mapSlackWorkflowParams(workflowOperation, params, context) + if (SLACK_V2_LIST_OPERATIONS.includes(operationId as never)) { + return mapSlackListParams(operationId, params, context) } const mapParams = SlackBlock.tools.config?.params if (!mapParams) throw new Error('Slack parameter mapper is required') - const baseParams = mapParams(params) - if (!SLACK_V2_AGENT_OPERATIONS.includes(params.operation as never)) return baseParams + const baseParams = mapParams(params, context) + if (!SLACK_V2_AGENT_OPERATIONS.includes(operationId as never)) return baseParams + const modelArg = (param: string) => toolCallArg(context, params[param]) return { ...baseParams, - credential: params.agentCredentialId, - channel: params.agentChannelId, - threadTs: params.agentThreadTs, - status: params.agentSessionStatus, - title: params.agentSessionTitle, - initiatorUserId: params.agentInitiatorUserId, - iconEmoji: params.agentIconEmoji, - iconUrl: params.agentIconUrl, - username: params.agentUsername, - prompts: params.suggestedPrompts, + credential: params.agentCredentialId ?? modelArg('credential'), + channel: params.agentChannelId ?? modelArg('channel'), + threadTs: params.agentThreadTs ?? modelArg('threadTs'), + status: params.agentSessionStatus ?? modelArg('status'), + title: params.agentSessionTitle ?? modelArg('title'), + initiatorUserId: params.agentInitiatorUserId ?? modelArg('initiatorUserId'), + iconEmoji: params.agentIconEmoji ?? modelArg('iconEmoji'), + iconUrl: params.agentIconUrl ?? modelArg('iconUrl'), + username: params.agentUsername ?? modelArg('username'), + prompts: params.suggestedPrompts ?? modelArg('prompts'), promptsTitle: params.promptsTitle, } }, @@ -3864,7 +3909,7 @@ Block Kit messages can contain buttons, selects and forms, but interactions requ emoji: { type: 'json', description: 'Custom emoji names mapped to image URLs or aliases' }, team: { type: 'json', description: 'Workspace details' }, job_id: { type: 'string', description: 'List export job ID' }, - status: { type: 'string', description: 'List export job status' }, + status: { type: 'string', description: 'List export job status, or agent session status' }, download_url: { type: 'string', description: 'List export download URL when ready' }, response_metadata: { type: 'json', description: 'Pagination metadata including next_cursor' }, dnd_enabled: { type: 'boolean', description: 'Whether Do Not Disturb is enabled' }, diff --git a/apps/sim/blocks/blocks/smartlead.test.ts b/apps/sim/blocks/blocks/smartlead.test.ts new file mode 100644 index 00000000000..d536aecc676 --- /dev/null +++ b/apps/sim/blocks/blocks/smartlead.test.ts @@ -0,0 +1,35 @@ +/** + * An agent tool call passes the model's args under the tool's param names with the operation only + * in the mapper context, and the mapper's result is spread over those args. + */ +import { describe, expect, it } from 'vitest' +import { SmartleadBlock } from '@/blocks/blocks/smartlead' +import { addLeadsToCampaignTool } from '@/tools/smartlead/add_leads_to_campaign' +import { getLeadByEmailTool } from '@/tools/smartlead/get_lead_by_email' + +function agentToolParams(operation: string, args: Record) { + const mapped = SmartleadBlock.tools.config?.params?.(args, { operation }) ?? {} + return { ...args, ...mapped } as never +} + +describe('Smartlead agent tool calls', () => { + it('adds the leads the model passes to the campaign', () => { + const params = agentToolParams('add_leads_to_campaign', { + apiKey: 'key', + campaignId: 42, + leads: [{ email: 'ada@example.com', first_name: 'Ada' }], + }) + const body = addLeadsToCampaignTool.request.body?.(params) as { lead_list: unknown[] } + expect(body.lead_list).toHaveLength(1) + expect(body.lead_list[0]).toMatchObject({ email: 'ada@example.com' }) + }) + + it('looks up the lead by the email the model passes', () => { + const params = agentToolParams('get_lead_by_email', { + apiKey: 'key', + email: 'ada@example.com', + }) + const url = new URL((getLeadByEmailTool.request.url as (p: never) => string)(params)) + expect(url.searchParams.get('email')).toBe('ada@example.com') + }) +}) diff --git a/apps/sim/blocks/blocks/smartlead.ts b/apps/sim/blocks/blocks/smartlead.ts index a61d074b85a..2f551f2ed15 100644 --- a/apps/sim/blocks/blocks/smartlead.ts +++ b/apps/sim/blocks/blocks/smartlead.ts @@ -2,7 +2,7 @@ import { isRecordLike } from '@sim/utils/object' import { SmartleadIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' const CAMPAIGN_ID_OPERATIONS = [ 'get_campaign', @@ -913,69 +913,76 @@ export const SmartleadBlock: BlockConfig = { ], config: { tool: (params) => `smartlead_${params.operation}`, - params: (params) => ({ - campaignId: toNumberParam(params.campaignId), - leadId: toNumberParam(params.leadId), - clientId: toNumberParam(params.clientId), - categoryId: toNumberParam(params.categoryId), - webhookId: toNumberParam( - params.operation === 'delete_campaign_webhook' ? params.deleteWebhookId : params.webhookId - ), - campaignLeadMapId: toNumberParam(params.campaignLeadMapId), - leadListId: toNumberParam(params.leadListId), - emailAccountIds: parseNumberList(params.emailAccountIds), - listName: emptyToUndefined(params.listName), - fromTime: emptyToUndefined(params.fromTime), - toTime: emptyToUndefined(params.toTime), - unreadOnly: toBooleanParam(params.unreadOnly), - offset: toNumberParam(params.offset), - limit: toNumberParam(params.limit), - emailSequenceNumber: toNumberParam(params.emailSequenceNumber), - minTimeBetweenEmails: toNumberParam(params.minTimeBetweenEmails), - maxNewLeadsPerDay: toNumberParam(params.maxNewLeadsPerDay), - resumeLeadWithDelayDays: toNumberParam(params.resumeLeadWithDelayDays), - includeTags: toBooleanParam(params.includeTags), - sendAsPlainText: toBooleanParam(params.sendAsPlainText), - pauseLead: toBooleanParam(params.pauseLead), - name: params.operation === 'create_campaign' ? params.campaignName : params.webhookName, - email: emptyToUndefined(params.leadEmail), - // Empty means "not chosen", so required validation reports it instead of - // the API rejecting an empty status. - status: emptyToUndefined(params.status), - emailStatus: emptyToUndefined(params.emailStatus), - stopLeadSettings: emptyToUndefined(params.stopLeadSettings), - daysOfTheWeek: parseNumberList(params.daysOfTheWeek), - trackSettings: parseStringList(params.trackSettings), - eventTypes: parseStringList(params.eventTypes), - categories: parseStringList(params.categories), - followUpPercentage: toNumberParam(params.followUpPercentage), - enableAiEspMatching: toBooleanParam(params.enableAiEspMatching), - unsubscribeText: emptyToUndefined(params.unsubscribeText), - scheduleStartTime: emptyToUndefined(params.scheduleStartTime), - companyUrl: emptyToUndefined(params.companyUrl), - sentTimeStartDate: emptyToUndefined(params.sentTimeStartDate), - sentTimeEndDate: emptyToUndefined(params.sentTimeEndDate), - ignoreGlobalBlockList: toBooleanParam(params.ignoreGlobalBlockList), - ignoreUnsubscribeList: toBooleanParam(params.ignoreUnsubscribeList), - ignoreDuplicateLeadsInOtherCampaign: toBooleanParam( - params.ignoreDuplicateLeadsInOtherCampaign - ), - ignoreCommunityBounceList: toBooleanParam(params.ignoreCommunityBounceList), - // Parsed only for the operation that consumes them, so a stale value left in a - // hidden field cannot fail an unrelated operation. - leads: - params.operation === 'add_leads_to_campaign' - ? parseJsonArray(params.leads, 'Leads') - : undefined, - sequences: - params.operation === 'save_campaign_sequences' - ? parseJsonArray(params.sequences, 'Sequences') - : undefined, - customFields: - params.operation === 'update_lead' - ? parseJsonObject(params.customFields, 'Custom Fields') - : undefined, - }), + params: (params, context) => { + const operation = mapperOperation(params, context) + return { + campaignId: toNumberParam(params.campaignId), + leadId: toNumberParam(params.leadId), + clientId: toNumberParam(params.clientId), + categoryId: toNumberParam(params.categoryId), + webhookId: + operation === 'delete_campaign_webhook' + ? (toNumberParam(params.deleteWebhookId) ?? + toNumberParam(toolCallArg(context, params.webhookId))) + : toNumberParam(params.webhookId), + campaignLeadMapId: toNumberParam(params.campaignLeadMapId), + leadListId: toNumberParam(params.leadListId), + emailAccountIds: parseNumberList(params.emailAccountIds), + listName: emptyToUndefined(params.listName), + fromTime: emptyToUndefined(params.fromTime), + toTime: emptyToUndefined(params.toTime), + unreadOnly: toBooleanParam(params.unreadOnly), + offset: toNumberParam(params.offset), + limit: toNumberParam(params.limit), + emailSequenceNumber: toNumberParam(params.emailSequenceNumber), + minTimeBetweenEmails: toNumberParam(params.minTimeBetweenEmails), + maxNewLeadsPerDay: toNumberParam(params.maxNewLeadsPerDay), + resumeLeadWithDelayDays: toNumberParam(params.resumeLeadWithDelayDays), + includeTags: toBooleanParam(params.includeTags), + sendAsPlainText: toBooleanParam(params.sendAsPlainText), + pauseLead: toBooleanParam(params.pauseLead), + name: + (operation === 'create_campaign' ? params.campaignName : params.webhookName) ?? + toolCallArg(context, params.name), + email: emptyToUndefined(params.leadEmail) ?? toolCallArg(context, params.email), + // Empty means "not chosen", so required validation reports it instead of + // the API rejecting an empty status. + status: emptyToUndefined(params.status), + emailStatus: emptyToUndefined(params.emailStatus), + stopLeadSettings: emptyToUndefined(params.stopLeadSettings), + daysOfTheWeek: parseNumberList(params.daysOfTheWeek), + trackSettings: parseStringList(params.trackSettings), + eventTypes: parseStringList(params.eventTypes), + categories: parseStringList(params.categories), + followUpPercentage: toNumberParam(params.followUpPercentage), + enableAiEspMatching: toBooleanParam(params.enableAiEspMatching), + unsubscribeText: emptyToUndefined(params.unsubscribeText), + scheduleStartTime: emptyToUndefined(params.scheduleStartTime), + companyUrl: emptyToUndefined(params.companyUrl), + sentTimeStartDate: emptyToUndefined(params.sentTimeStartDate), + sentTimeEndDate: emptyToUndefined(params.sentTimeEndDate), + ignoreGlobalBlockList: toBooleanParam(params.ignoreGlobalBlockList), + ignoreUnsubscribeList: toBooleanParam(params.ignoreUnsubscribeList), + ignoreDuplicateLeadsInOtherCampaign: toBooleanParam( + params.ignoreDuplicateLeadsInOtherCampaign + ), + ignoreCommunityBounceList: toBooleanParam(params.ignoreCommunityBounceList), + // Parsed only for the operation that consumes them, so a stale value left in a + // hidden field cannot fail an unrelated operation. + leads: + operation === 'add_leads_to_campaign' + ? parseJsonArray(params.leads, 'Leads') + : undefined, + sequences: + operation === 'save_campaign_sequences' + ? parseJsonArray(params.sequences, 'Sequences') + : undefined, + customFields: + operation === 'update_lead' + ? parseJsonObject(params.customFields, 'Custom Fields') + : undefined, + } + }, }, }, inputs: { diff --git a/apps/sim/blocks/blocks/snowflake.ts b/apps/sim/blocks/blocks/snowflake.ts index f0fd5994c9e..ddd42d5e3f1 100644 --- a/apps/sim/blocks/blocks/snowflake.ts +++ b/apps/sim/blocks/blocks/snowflake.ts @@ -1,7 +1,8 @@ +import { toBooleanFromInput } from '@sim/utils/coerce' import { SnowflakeIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { parseOptionalJsonInput, parseOptionalNumberInput } from '@/blocks/utils' +import { mapperOperation, parseOptionalJsonInput, parseOptionalNumberInput } from '@/blocks/utils' import { SNOWFLAKE_WAREHOUSE_SIZES } from '@/tools/snowflake/types' const sqlSubmissionOperations = [ @@ -210,8 +211,9 @@ const limitOperationSet: ReadonlySet = new Set(limitOperations) * asked for — `AUTO_RESUME = FALSE`, which permanently disables auto-resume on * the warehouse, being the damaging one. * - * The string forms are accepted because a direct tool call delivers booleans - * that way, matching the other boolean readers on this block. + * Only the exact strings `'true'`/`'false'` are accepted, so a case-variant + * string never enables PURGE, FORCE, SQL execution, or a rating. Switches whose + * builders already read case-insensitively use `toBooleanFromInput` instead. */ function optionalBoolean(value: unknown): boolean | undefined { if (typeof value === 'boolean') return value @@ -1184,8 +1186,8 @@ export const SnowflakeBlock: BlockConfig = { ], config: { tool: (params) => `snowflake_${params.operation}`, - params: (params) => { - const operation = String(params.operation) + params: (params, context) => { + const operation = mapperOperation(params, context) const result: Record = {} if (sqlSubmissionOperationSet.has(operation)) { @@ -1234,16 +1236,16 @@ export const SnowflakeBlock: BlockConfig = { params.maxFileSizeBytes, 'Maximum file size' ) - result.header = optionalBoolean(params.header) - result.overwrite = optionalBoolean(params.overwrite) - result.singleFile = optionalBoolean(params.singleFile) + result.header = toBooleanFromInput(params.header) + result.overwrite = toBooleanFromInput(params.overwrite) + result.singleFile = toBooleanFromInput(params.singleFile) break case 'alter_warehouse': result.autoSuspendSeconds = parseOptionalNumberInput( params.autoSuspendSeconds, 'Auto-suspend seconds' ) - result.autoResume = optionalBoolean(params.autoResume) + result.autoResume = toBooleanFromInput(params.autoResume) break case 'call_procedure': result.procedureArguments = parseOptionalJsonInput( @@ -1253,22 +1255,26 @@ export const SnowflakeBlock: BlockConfig = { break case 'cortex_analyst_ask': { /* - * Only the selected source reaches the tool, which requires exactly one. A caller - * that never set the dropdown (API, Copilot, or a direct tool call) is matched to - * the single source field it filled. + * Only the selected source reaches the tool, which requires exactly one. The dropdown + * wins only when its field is filled: an agent tool row seeds it with its first + * option, so a model that filled a different source is matched to that field. */ const sourceFields = Object.values(CORTEX_SEMANTIC_SOURCE_FIELDS) const filled = sourceFields.filter((field) => { const value = params[field] return value !== undefined && value !== null && String(value).trim() !== '' }) - const selected = params.semanticSource + const dropdownField = params.semanticSource ? CORTEX_SEMANTIC_SOURCE_FIELDS[ String(params.semanticSource) as keyof typeof CORTEX_SEMANTIC_SOURCE_FIELDS ] - : filled.length === 1 - ? filled[0] - : undefined + : undefined + const selected = + dropdownField && filled.includes(dropdownField) + ? dropdownField + : filled.length === 1 + ? filled[0] + : dropdownField if (selected) { for (const field of sourceFields) { if (field !== selected) result[field] = undefined diff --git a/apps/sim/blocks/blocks/splunk.test.ts b/apps/sim/blocks/blocks/splunk.test.ts index bd94ebe951f..27fadc72545 100644 --- a/apps/sim/blocks/blocks/splunk.test.ts +++ b/apps/sim/blocks/blocks/splunk.test.ts @@ -4,13 +4,14 @@ import { describe, expect, it, vi } from 'vitest' vi.mock('@/triggers', () => triggersMock) import { SplunkBlock } from '@/blocks/blocks/splunk' +import type { BlockToolParamsContext } from '@/blocks/types' import { buildSplunkFormBody, buildSplunkUrl } from '@/tools/splunk/utils' const toParams = SplunkBlock.tools.config?.params -function mapParams(params: Record) { +function mapParams(params: Record, context?: BlockToolParamsContext) { if (!toParams) throw new Error('SplunkBlock is missing tools.config.params') - return toParams(params as Parameters[0]) + return toParams(params as Parameters[0], context) } /** @@ -141,3 +142,27 @@ describe('SplunkBlock numeric coercion', () => { expect(buildSplunkFormBody({ max_count: merged.count as number | undefined })).toBe('') }) }) + +/** + * On an agent tool call the operation arrives only on `context`, and the merged row and model + * values are keyed by the tool's param names (row switches hold strings). The handler forwards + * `{ ...merged, ...mapped }`. + */ +describe('SplunkBlock agent tool calls', () => { + const agentCall = (operation: string, merged: Record) => ({ + ...merged, + ...mapParams(merged, { operation }), + }) + + it('coerces the switches typed in the tool row when dispatching a saved search', () => { + expect( + agentCall('splunk_dispatch_saved_search', { name: 'Errors', forceDispatch: 'false' }) + ).toMatchObject({ name: 'Errors', forceDispatch: false }) + }) + + it('keeps the name the model supplied for fired alerts', () => { + expect(agentCall('splunk_get_fired_alerts', { name: 'Disk full' })).toMatchObject({ + name: 'Disk full', + }) + }) +}) diff --git a/apps/sim/blocks/blocks/splunk.ts b/apps/sim/blocks/blocks/splunk.ts index 0c8a45511ff..4263f437a04 100644 --- a/apps/sim/blocks/blocks/splunk.ts +++ b/apps/sim/blocks/blocks/splunk.ts @@ -1,7 +1,7 @@ import { SplunkIcon } from '@/components/icons' -import type { BlockConfig, BlockMeta } from '@/blocks/types' +import type { BlockConfig, BlockMeta, BlockToolParamsContext } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { isToolCall, mapperOperation, withSavedCredential } from '@/blocks/utils' /** * Normalize a Splunk toggle. A dropdown supplies the strings `'true'`/`'false'`, @@ -40,6 +40,18 @@ function assignSplunkNumber(target: Record, key: string, value: target[key] = Number.isFinite(parsed) ? parsed : undefined } +/** + * A dedicated block field, or on a tool call the model's arg under the tool's own param name + * when that field is blank: the model fills `name`/`search`, never the block-only field. + */ +function blockFieldOrToolArg( + dedicated: unknown, + toolArg: unknown, + context: BlockToolParamsContext | undefined +): unknown { + return isToolCall(context) && (dedicated == null || dedicated === '') ? toolArg : dedicated +} + export const SplunkBlock: BlockConfig = { type: 'splunk', hideFromToolbar: true, @@ -492,13 +504,13 @@ Examples: ], config: { tool: (params) => params.operation, - params: (params) => { + params: (params, context) => { const result: Record = {} assignSplunkNumber(result, 'count', params.count) assignSplunkNumber(result, 'offset', params.offset) - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'splunk_run_search': assignSplunkNumber(result, 'autoCancel', params.autoCancel) assignSplunkNumber(result, 'maxCount', params.maxCount) @@ -513,11 +525,12 @@ Examples: result.addSummaryToMetadata = toSplunkToggle(params.addSummaryToMetadata) break case 'splunk_list_saved_searches': - result.search = params.savedSearchFilter ?? '' + result.search = + blockFieldOrToolArg(params.savedSearchFilter, params.search, context) ?? '' break case 'splunk_get_saved_search': case 'splunk_dispatch_saved_search': - result.name = params.savedSearchName + result.name = blockFieldOrToolArg(params.savedSearchName, params.name, context) result.triggerActions = toSplunkToggle(params.triggerActions) result.forceDispatch = toSplunkToggle(params.forceDispatch) assignSplunkNumber(result, 'dispatchMaxCount', params.dispatchMaxCount) @@ -525,7 +538,7 @@ Examples: assignSplunkNumber(result, 'dispatchTtl', params.dispatchTtl) break case 'splunk_get_fired_alerts': - result.name = params.alertName + result.name = blockFieldOrToolArg(params.alertName, params.name, context) break } diff --git a/apps/sim/blocks/blocks/sqs.test.ts b/apps/sim/blocks/blocks/sqs.test.ts index fc49c5b1d31..2294e0778ee 100644 --- a/apps/sim/blocks/blocks/sqs.test.ts +++ b/apps/sim/blocks/blocks/sqs.test.ts @@ -32,3 +32,25 @@ describe('SQS block integer parsing', () => { ).toThrow('maxNumberOfMessages must be a whole number') }) }) + +/** + * On an agent tool call the operation arrives only on `context`, and the merged row and model + * values are keyed by the tool's param names (row fields hold strings). + */ +describe('SQS block agent tool calls', () => { + it('coerces the delay typed in the tool row when sending a message', () => { + const merged = { ...CONNECTION, queueUrl: QUEUE_URL, data: '{"a":1}', delaySeconds: '5' } + expect({ ...merged, ...mapParams(merged, { operation: 'send' }) }).toMatchObject({ + delaySeconds: 5, + data: { a: 1 }, + }) + }) + + it('keeps the batch entries the model supplied', () => { + const entries = [{ id: '1', data: { a: 1 } }] + const merged = { ...CONNECTION, queueUrl: QUEUE_URL, entries } + expect({ ...merged, ...mapParams(merged, { operation: 'send_message_batch' }) }).toMatchObject({ + entries, + }) + }) +}) diff --git a/apps/sim/blocks/blocks/sqs.ts b/apps/sim/blocks/blocks/sqs.ts index 9fd7845e452..a41fe97878c 100644 --- a/apps/sim/blocks/blocks/sqs.ts +++ b/apps/sim/blocks/blocks/sqs.ts @@ -2,7 +2,7 @@ import { getErrorMessage } from '@sim/utils/errors' import { SQSIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, withSavedCredential } from '@/blocks/utils' export const SQSBlock: BlockConfig = { type: 'sqs', @@ -603,8 +603,8 @@ export const SQSBlock: BlockConfig = { throw new Error(`Invalid SQS operation: ${params.operation}`) } }, - params: (params) => { - const { operation, ...rest } = params + params: (params, context) => { + const operation = mapperOperation(params, context) const parseJson = (value: unknown, fieldName: string) => { if (value === undefined || value === null || value === '') return undefined @@ -637,166 +637,166 @@ export const SQSBlock: BlockConfig = { } const result: Record = { - region: rest.region, - accessKeyId: rest.accessKeyId, - secretAccessKey: rest.secretAccessKey, + region: params.region, + accessKeyId: params.accessKeyId, + secretAccessKey: params.secretAccessKey, } switch (operation) { case 'send': { - result.queueUrl = rest.queueUrl - const data = parseJson(rest.data, 'data') + result.queueUrl = params.queueUrl + const data = parseJson(params.data, 'data') if (data !== undefined) result.data = data - const delaySeconds = parseInteger(rest.delaySeconds, 'delaySeconds') + const delaySeconds = parseInteger(params.delaySeconds, 'delaySeconds') if (delaySeconds !== undefined) result.delaySeconds = delaySeconds - const messageAttributes = parseJson(rest.messageAttributes, 'messageAttributes') + const messageAttributes = parseJson(params.messageAttributes, 'messageAttributes') if (messageAttributes !== undefined) result.messageAttributes = messageAttributes - if (rest.messageGroupId) result.messageGroupId = rest.messageGroupId - if (rest.messageDeduplicationId) { - result.messageDeduplicationId = rest.messageDeduplicationId + if (params.messageGroupId) result.messageGroupId = params.messageGroupId + if (params.messageDeduplicationId) { + result.messageDeduplicationId = params.messageDeduplicationId } break } case 'send_message_batch': { - result.queueUrl = rest.queueUrl - const entries = parseJson(rest.sendEntries, 'entries') + result.queueUrl = params.queueUrl + const entries = parseJson(params.sendEntries, 'entries') if (entries !== undefined) result.entries = entries break } case 'receive_message': { - result.queueUrl = rest.queueUrl + result.queueUrl = params.queueUrl const maxNumberOfMessages = parseInteger( - rest.maxNumberOfMessages, + params.maxNumberOfMessages, 'maxNumberOfMessages' ) if (maxNumberOfMessages !== undefined) result.maxNumberOfMessages = maxNumberOfMessages - const waitTimeSeconds = parseInteger(rest.waitTimeSeconds, 'waitTimeSeconds') + const waitTimeSeconds = parseInteger(params.waitTimeSeconds, 'waitTimeSeconds') if (waitTimeSeconds !== undefined) result.waitTimeSeconds = waitTimeSeconds const visibilityTimeout = parseInteger( - rest.receiveVisibilityTimeout, + params.receiveVisibilityTimeout, 'visibilityTimeout' ) if (visibilityTimeout !== undefined) result.visibilityTimeout = visibilityTimeout const messageAttributeNames = parseJson( - rest.messageAttributeNames, + params.messageAttributeNames, 'messageAttributeNames' ) if (messageAttributeNames !== undefined) { result.messageAttributeNames = messageAttributeNames } const messageSystemAttributeNames = parseJson( - rest.messageSystemAttributeNames, + params.messageSystemAttributeNames, 'messageSystemAttributeNames' ) if (messageSystemAttributeNames !== undefined) { result.messageSystemAttributeNames = messageSystemAttributeNames } - if (rest.receiveRequestAttemptId) { - result.receiveRequestAttemptId = rest.receiveRequestAttemptId + if (params.receiveRequestAttemptId) { + result.receiveRequestAttemptId = params.receiveRequestAttemptId } break } case 'delete_message': { - result.queueUrl = rest.queueUrl - result.receiptHandle = rest.receiptHandle + result.queueUrl = params.queueUrl + result.receiptHandle = params.receiptHandle break } case 'delete_message_batch': { - result.queueUrl = rest.queueUrl - const entries = parseJson(rest.deleteEntries, 'entries') + result.queueUrl = params.queueUrl + const entries = parseJson(params.deleteEntries, 'entries') if (entries !== undefined) result.entries = entries break } case 'change_message_visibility': { - result.queueUrl = rest.queueUrl - result.receiptHandle = rest.receiptHandle - const visibilityTimeout = parseInteger(rest.visibilityTimeout, 'visibilityTimeout') + result.queueUrl = params.queueUrl + result.receiptHandle = params.receiptHandle + const visibilityTimeout = parseInteger(params.visibilityTimeout, 'visibilityTimeout') if (visibilityTimeout !== undefined) result.visibilityTimeout = visibilityTimeout break } case 'change_message_visibility_batch': { - result.queueUrl = rest.queueUrl - const entries = parseJson(rest.visibilityEntries, 'entries') + result.queueUrl = params.queueUrl + const entries = parseJson(params.visibilityEntries, 'entries') if (entries !== undefined) result.entries = entries break } case 'list_queues': { - if (rest.queueNamePrefix) result.queueNamePrefix = rest.queueNamePrefix - const maxResults = parseInteger(rest.maxResults, 'maxResults') + if (params.queueNamePrefix) result.queueNamePrefix = params.queueNamePrefix + const maxResults = parseInteger(params.maxResults, 'maxResults') if (maxResults !== undefined) result.maxResults = maxResults - if (rest.nextToken) result.nextToken = rest.nextToken + if (params.nextToken) result.nextToken = params.nextToken break } case 'get_queue_url': { - result.queueName = rest.queueName - if (rest.queueOwnerAwsAccountId) { - result.queueOwnerAwsAccountId = rest.queueOwnerAwsAccountId + result.queueName = params.queueName + if (params.queueOwnerAwsAccountId) { + result.queueOwnerAwsAccountId = params.queueOwnerAwsAccountId } break } case 'get_queue_attributes': { - result.queueUrl = rest.queueUrl - const attributeNames = parseJson(rest.attributeNames, 'attributeNames') + result.queueUrl = params.queueUrl + const attributeNames = parseJson(params.attributeNames, 'attributeNames') if (attributeNames !== undefined) result.attributeNames = attributeNames break } case 'set_queue_attributes': { - result.queueUrl = rest.queueUrl - const attributes = parseJson(rest.queueAttributes, 'attributes') + result.queueUrl = params.queueUrl + const attributes = parseJson(params.queueAttributes, 'attributes') if (attributes !== undefined) result.attributes = attributes break } case 'create_queue': { - result.queueName = rest.queueName - const attributes = parseJson(rest.createQueueAttributes, 'attributes') + result.queueName = params.queueName + const attributes = parseJson(params.createQueueAttributes, 'attributes') if (attributes !== undefined) result.attributes = attributes - const tags = parseJson(rest.createQueueTags, 'tags') + const tags = parseJson(params.createQueueTags, 'tags') if (tags !== undefined) result.tags = tags break } case 'delete_queue': case 'purge_queue': case 'list_queue_tags': { - result.queueUrl = rest.queueUrl + result.queueUrl = params.queueUrl break } case 'list_dead_letter_source_queues': { - result.queueUrl = rest.queueUrl - const maxResults = parseInteger(rest.maxResults, 'maxResults') + result.queueUrl = params.queueUrl + const maxResults = parseInteger(params.maxResults, 'maxResults') if (maxResults !== undefined) result.maxResults = maxResults - if (rest.nextToken) result.nextToken = rest.nextToken + if (params.nextToken) result.nextToken = params.nextToken break } case 'tag_queue': { - result.queueUrl = rest.queueUrl - const tags = parseJson(rest.queueTags, 'tags') + result.queueUrl = params.queueUrl + const tags = parseJson(params.queueTags, 'tags') if (tags !== undefined) result.tags = tags break } case 'untag_queue': { - result.queueUrl = rest.queueUrl - const tagKeys = parseJson(rest.tagKeys, 'tagKeys') + result.queueUrl = params.queueUrl + const tagKeys = parseJson(params.tagKeys, 'tagKeys') if (tagKeys !== undefined) result.tagKeys = tagKeys break } case 'start_message_move_task': { - result.sourceArn = rest.sourceArn - if (rest.destinationArn) result.destinationArn = rest.destinationArn + result.sourceArn = params.sourceArn + if (params.destinationArn) result.destinationArn = params.destinationArn const maxPerSecond = parseInteger( - rest.maxNumberOfMessagesPerSecond, + params.maxNumberOfMessagesPerSecond, 'maxNumberOfMessagesPerSecond' ) if (maxPerSecond !== undefined) result.maxNumberOfMessagesPerSecond = maxPerSecond break } case 'list_message_move_tasks': { - result.sourceArn = rest.sourceArn - const maxResults = parseInteger(rest.moveTaskMaxResults, 'maxResults') + result.sourceArn = params.sourceArn + const maxResults = parseInteger(params.moveTaskMaxResults, 'maxResults') if (maxResults !== undefined) result.maxResults = maxResults break } case 'cancel_message_move_task': { - result.taskHandle = rest.taskHandle + result.taskHandle = params.taskHandle break } } diff --git a/apps/sim/blocks/blocks/ssh.test.ts b/apps/sim/blocks/blocks/ssh.test.ts new file mode 100644 index 00000000000..e77e8d60572 --- /dev/null +++ b/apps/sim/blocks/blocks/ssh.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from 'vitest' +import { SSHBlock } from '@/blocks/blocks/ssh' + +const CONNECTION = { host: 'example.com', port: 22, username: 'deploy', password: 'pw' } + +/** + * On an agent tool call the operation arrives only on `context` and the model sends the tool's + * `path`, which the block collects under a per-operation field (`listPath`, `readPath`, ...). + */ +describe('SSH block agent tool calls', () => { + it('keeps the model path and coerces maxSize when reading a file', () => { + const merged = { ...CONNECTION, path: '/etc/hosts', maxSize: '5' } + const mapped = SSHBlock.tools.config.params(merged, { operation: 'ssh_read_file_content' }) + expect({ ...merged, ...mapped }).toMatchObject({ path: '/etc/hosts', maxSize: 5 }) + }) +}) diff --git a/apps/sim/blocks/blocks/ssh.ts b/apps/sim/blocks/blocks/ssh.ts index e85e51bbbb8..d313b3a5a85 100644 --- a/apps/sim/blocks/blocks/ssh.ts +++ b/apps/sim/blocks/blocks/ssh.ts @@ -3,7 +3,7 @@ import { omit } from '@sim/utils/object' import { SshIcon, SshTerminalIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { createVersionedToolSelector } from '@/blocks/utils' +import { createVersionedToolSelector, mapperOperation, toolCallArg } from '@/blocks/utils' export const SSHBlock = { type: 'ssh', @@ -524,7 +524,7 @@ Examples: tool: (params) => { return params.operation || 'ssh_execute_command' }, - params: (params) => { + params: (params, context) => { // Build connection config const connectionConfig: Record = { host: params.host, @@ -544,7 +544,7 @@ Examples: } // Build operation-specific parameters based on the selected operation - const operation = params.operation || 'ssh_execute_command' + const operation = mapperOperation(params, context) || 'ssh_execute_command' switch (operation) { case 'ssh_execute_command': @@ -558,7 +558,8 @@ Examples: ...connectionConfig, script: params.script, interpreter: params.interpreter || '/bin/bash', - workingDirectory: params.scriptWorkingDirectory, + workingDirectory: + params.scriptWorkingDirectory ?? toolCallArg(context, params.workingDirectory), } case 'ssh_check_command_exists': return { @@ -576,31 +577,31 @@ Examples: case 'ssh_download_file': return { ...connectionConfig, - remotePath: params.downloadRemotePath, + remotePath: params.downloadRemotePath ?? toolCallArg(context, params.remotePath), } case 'ssh_list_directory': return { ...connectionConfig, - path: params.listPath, + path: params.listPath ?? toolCallArg(context, params.path), detailed: params.detailed, } case 'ssh_check_file_exists': return { ...connectionConfig, - path: params.checkPath, - type: params.checkType || 'any', + path: params.checkPath ?? toolCallArg(context, params.path), + type: params.checkType || toolCallArg(context, params.type) || 'any', } case 'ssh_create_directory': return { ...connectionConfig, - path: params.createPath, + path: params.createPath ?? toolCallArg(context, params.path), recursive: params.recursive !== false, } case 'ssh_delete_file': return { ...connectionConfig, - path: params.deletePath, - recursive: params.deleteRecursive, + path: params.deletePath ?? toolCallArg(context, params.path), + recursive: params.deleteRecursive ?? toolCallArg(context, params.recursive), force: params.force, } case 'ssh_move_rename': @@ -615,17 +616,17 @@ Examples: case 'ssh_read_file_content': return { ...connectionConfig, - path: params.readPath, + path: params.readPath ?? toolCallArg(context, params.path), encoding: params.encoding || 'utf-8', maxSize: params.maxSize ? Number.parseInt(params.maxSize, 10) : 10, } case 'ssh_write_file_content': return { ...connectionConfig, - path: params.writePath, + path: params.writePath ?? toolCallArg(context, params.path), content: params.content, - mode: params.writeMode || 'overwrite', - permissions: params.writePermissions, + mode: params.writeMode || toolCallArg(context, params.mode) || 'overwrite', + permissions: params.writePermissions ?? toolCallArg(context, params.permissions), } default: return connectionConfig diff --git a/apps/sim/blocks/blocks/ssm.test.ts b/apps/sim/blocks/blocks/ssm.test.ts new file mode 100644 index 00000000000..e09f8362844 --- /dev/null +++ b/apps/sim/blocks/blocks/ssm.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from 'vitest' +import { SSMBlock } from '@/blocks/blocks/ssm' + +const mapParams = SSMBlock.tools.config?.params +if (!mapParams) { + throw new Error('SSM block must define tools.config.params') +} + +const CONNECTION = { + region: 'us-east-1', + accessKeyId: 'AKIAIOSFODNN7EXAMPLE', + secretAccessKey: 'secret', +} + +/** + * On an agent tool call the operation arrives only on `context` and the model's args are keyed by + * the tool's param names, so the mapper must coerce them and never replace them with an empty + * block-only field. + */ +describe('SSM block agent tool calls', () => { + it.each([ + { + operation: 'get_parameters', + args: { names: '["/app/db","/app/key"]' }, + expected: { names: ['/app/db', '/app/key'] }, + }, + { + operation: 'get_parameter', + args: { name: '/app/db', withDecryption: 'true' }, + expected: { name: '/app/db', withDecryption: true }, + }, + ])('$operation keeps and coerces the model args', ({ operation, args, expected }) => { + const merged = { ...CONNECTION, ...args } + expect({ ...merged, ...mapParams(merged, { operation }) }).toMatchObject(expected) + }) +}) diff --git a/apps/sim/blocks/blocks/ssm.ts b/apps/sim/blocks/blocks/ssm.ts index df5d2736d0f..c581ce0d92c 100644 --- a/apps/sim/blocks/blocks/ssm.ts +++ b/apps/sim/blocks/blocks/ssm.ts @@ -1,7 +1,7 @@ import { SSMIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' /** Operations whose SSM API caps `MaxResults` at 50. */ const STANDARD_PAGE_OPERATIONS = [ @@ -798,7 +798,7 @@ export const SSMBlock: BlockConfig = { throw new Error(`Invalid Systems Manager operation: ${params.operation}`) } }, - params: (params) => { + params: (params, context) => { const result: Record = { region: params.region, accessKeyId: params.accessKeyId, @@ -822,7 +822,7 @@ export const SSMBlock: BlockConfig = { result[key] = String(value) } - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'send_command': result.documentName = params.documentName setJson('instanceIds', params.instanceIds) @@ -840,14 +840,14 @@ export const SSMBlock: BlockConfig = { case 'list_commands': setString('commandId', params.commandId) setString('instanceId', params.instanceId) - setJson('filters', params.commandFilters) + setJson('filters', params.commandFilters ?? toolCallArg(context, params.filters)) setNumber('maxResults', params.maxResults) setString('nextToken', params.nextToken) break case 'list_command_invocations': setString('commandId', params.commandId) setString('instanceId', params.instanceId) - setJson('filters', params.commandFilters) + setJson('filters', params.commandFilters ?? toolCallArg(context, params.filters)) setBoolean('details', params.details) setNumber('maxResults', params.maxResults) setString('nextToken', params.nextToken) @@ -862,35 +862,41 @@ export const SSMBlock: BlockConfig = { setJson('instanceIds', params.instanceIds) break case 'get_parameter': - result.name = params.parameterName + result.name = params.parameterName ?? toolCallArg(context, params.name) setBoolean('withDecryption', params.withDecryption) break case 'get_parameters': - setJson('names', params.parameterNames) + setJson('names', params.parameterNames ?? toolCallArg(context, params.names)) setBoolean('withDecryption', params.withDecryption) break case 'get_parameters_by_path': - result.path = params.parameterPath + result.path = params.parameterPath ?? toolCallArg(context, params.path) setBoolean('recursive', params.recursive) setBoolean('withDecryption', params.withDecryption) setJson('parameterFilters', params.parameterFilters) - setNumber('maxResults', params.pathMaxResults) + setNumber( + 'maxResults', + params.pathMaxResults ?? toolCallArg(context, params.maxResults) + ) setString('nextToken', params.nextToken) break case 'put_parameter': - result.name = params.parameterName - result.value = params.parameterValue - setString('type', params.parameterType) - setString('description', params.parameterDescription) - setString('keyId', params.kmsKeyId) + result.name = params.parameterName ?? toolCallArg(context, params.name) + result.value = params.parameterValue ?? toolCallArg(context, params.value) + setString('type', params.parameterType ?? toolCallArg(context, params.type)) + setString( + 'description', + params.parameterDescription ?? toolCallArg(context, params.description) + ) + setString('keyId', params.kmsKeyId ?? toolCallArg(context, params.keyId)) setBoolean('overwrite', params.overwrite) setString('allowedPattern', params.allowedPattern) - setString('tier', params.parameterTier) - setString('dataType', params.parameterDataType) - setString('policies', params.parameterPolicies) + setString('tier', params.parameterTier ?? toolCallArg(context, params.tier)) + setString('dataType', params.parameterDataType ?? toolCallArg(context, params.dataType)) + setString('policies', params.parameterPolicies ?? toolCallArg(context, params.policies)) break case 'delete_parameter': - result.name = params.parameterName + result.name = params.parameterName ?? toolCallArg(context, params.name) break case 'describe_parameters': setJson('parameterFilters', params.parameterFilters) @@ -899,30 +905,39 @@ export const SSMBlock: BlockConfig = { setString('nextToken', params.nextToken) break case 'describe_instance_information': - setJson('filters', params.instanceInfoFilters) - setNumber('maxResults', params.instanceInfoMaxResults) + setJson('filters', params.instanceInfoFilters ?? toolCallArg(context, params.filters)) + setNumber( + 'maxResults', + params.instanceInfoMaxResults ?? toolCallArg(context, params.maxResults) + ) setString('nextToken', params.nextToken) break case 'describe_instance_patches': result.instanceId = params.instanceId - setJson('filters', params.patchFilters) - setNumber('maxResults', params.patchMaxResults) + setJson('filters', params.patchFilters ?? toolCallArg(context, params.filters)) + setNumber( + 'maxResults', + params.patchMaxResults ?? toolCallArg(context, params.maxResults) + ) setString('nextToken', params.nextToken) break case 'describe_instance_patch_states': setJson('instanceIds', params.instanceIds) - setNumber('maxResults', params.patchMaxResults) + setNumber( + 'maxResults', + params.patchMaxResults ?? toolCallArg(context, params.maxResults) + ) setString('nextToken', params.nextToken) break case 'list_compliance_items': setJson('resourceIds', params.resourceIds) setJson('resourceTypes', params.resourceTypes) - setJson('filters', params.complianceFilters) + setJson('filters', params.complianceFilters ?? toolCallArg(context, params.filters)) setNumber('maxResults', params.maxResults) setString('nextToken', params.nextToken) break case 'list_compliance_summaries': - setJson('filters', params.complianceFilters) + setJson('filters', params.complianceFilters ?? toolCallArg(context, params.filters)) setNumber('maxResults', params.maxResults) setString('nextToken', params.nextToken) break @@ -938,7 +953,7 @@ export const SSMBlock: BlockConfig = { setString('clientToken', params.clientToken) break case 'describe_automation_executions': - setJson('filters', params.automationFilters) + setJson('filters', params.automationFilters ?? toolCallArg(context, params.filters)) setNumber('maxResults', params.maxResults) setString('nextToken', params.nextToken) break @@ -950,12 +965,12 @@ export const SSMBlock: BlockConfig = { setString('stopType', params.stopType) break case 'list_documents': - setJson('filters', params.documentFilters) + setJson('filters', params.documentFilters ?? toolCallArg(context, params.filters)) setNumber('maxResults', params.maxResults) setString('nextToken', params.nextToken) break case 'get_document': - result.name = params.documentName + result.name = params.documentName ?? toolCallArg(context, params.name) setString('documentVersion', params.documentVersion) setString('versionName', params.versionName) setString('documentFormat', params.documentFormat) diff --git a/apps/sim/blocks/blocks/stagehand.ts b/apps/sim/blocks/blocks/stagehand.ts index e4b555f8072..b7ffdbd226d 100644 --- a/apps/sim/blocks/blocks/stagehand.ts +++ b/apps/sim/blocks/blocks/stagehand.ts @@ -1,5 +1,6 @@ import { StagehandIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' +import { mapperOperation } from '@/blocks/utils' import type { StagehandAgentResponse, StagehandExtractResponse } from '@/tools/stagehand/types' export type StagehandResponse = StagehandExtractResponse | StagehandAgentResponse @@ -375,14 +376,13 @@ Example 3 (Data Collection): tool: (params) => { return params.operation === 'agent' ? 'stagehand_agent' : 'stagehand_extract' }, - params: (params) => { + params: (params, context) => { const baseParams = { - operation: params.operation, provider: params.provider, apiKey: params.apiKey, } - if (params.operation !== 'agent') { + if (mapperOperation(params, context) !== 'agent') { return { ...baseParams, url: params.url, diff --git a/apps/sim/blocks/blocks/stripe.test.ts b/apps/sim/blocks/blocks/stripe.test.ts index 4f77fad8616..1afc7c94741 100644 --- a/apps/sim/blocks/blocks/stripe.test.ts +++ b/apps/sim/blocks/blocks/stripe.test.ts @@ -95,6 +95,15 @@ describe('Stripe block keeps unset fields out of requests', () => { ).toThrow(/path separator/) }) + it('an agent updates a subscription with the metadata object it passes', () => { + const params = agentToolParams(StripeBlock, 'update_subscription', { + apiKey: 'sk_test', + id: 'sub_1', + metadata: { plan: 'pro' }, + }) + expect(formBody(stripeUpdateSubscriptionTool, params).get('metadata[plan]')).toBe('pro') + }) + it('an agent paginates list charges with the cursor it passes', () => { const params = agentToolParams(StripeBlock, 'list_charges', { apiKey: 'sk_test', diff --git a/apps/sim/blocks/blocks/stripe.ts b/apps/sim/blocks/blocks/stripe.ts index 48a57a62a0d..60e3958738f 100644 --- a/apps/sim/blocks/blocks/stripe.ts +++ b/apps/sim/blocks/blocks/stripe.ts @@ -1,7 +1,8 @@ +import { getErrorMessage } from '@sim/utils/errors' import { StripeIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { isToolCall, withSavedCredential } from '@/blocks/utils' +import { isToolCall, mapperOperation, withSavedCredential } from '@/blocks/utils' import { getTrigger } from '@/triggers' /** @@ -20,6 +21,15 @@ function parseOptionalBoolean(value: unknown): boolean | undefined { return value === true || value === 'true' } +/** + * Reads a JSON input. The canvas stores it as text; a tool call passes the model's already-parsed + * object or array, which is kept as is. + */ +function parseJsonInput(value: unknown): unknown { + if (!value) return undefined + return typeof value === 'string' ? JSON.parse(value) : value +} + const SUBSCRIPTION_LIST_OPERATION = 'list_subscriptions' const SUBSCRIPTION_SEARCH_OPERATION = 'search_subscriptions' @@ -928,8 +938,8 @@ export const StripeBlock: BlockConfig = { return `stripe_${params.operation}` }, params: (params, context) => { + const operation = mapperOperation(params, context) const { - operation, apiKey, address, metadata, @@ -952,20 +962,20 @@ export const StripeBlock: BlockConfig = { ...rest } = params - let parsedAddress: any | undefined - let parsedMetadata: any | undefined - let parsedItems: any | undefined - let parsedImages: any | undefined - let parsedRecurring: any | undefined + let parsedAddress: unknown + let parsedMetadata: unknown + let parsedItems: unknown + let parsedImages: unknown + let parsedRecurring: unknown try { - if (address) parsedAddress = JSON.parse(address) - if (metadata) parsedMetadata = JSON.parse(metadata) - if (items) parsedItems = JSON.parse(items) - if (images) parsedImages = JSON.parse(images) - if (recurring) parsedRecurring = JSON.parse(recurring) - } catch (error: any) { - throw new Error(`Invalid JSON input: ${error.message}`) + parsedAddress = parseJsonInput(address) + parsedMetadata = parseJsonInput(metadata) + parsedItems = parseJsonInput(items) + parsedImages = parseJsonInput(images) + parsedRecurring = parseJsonInput(recurring) + } catch (error) { + throw new Error(`Invalid JSON input: ${getErrorMessage(error)}`) } // Every key is assigned, unset ones as `undefined`: the executor merges these over the raw @@ -996,11 +1006,11 @@ export const StripeBlock: BlockConfig = { return { apiKey, ...rest, - ...(parsedAddress && { address: parsedAddress }), - ...(parsedMetadata && { metadata: parsedMetadata }), - ...(parsedItems && { items: parsedItems }), - ...(parsedImages && { images: parsedImages }), - ...(parsedRecurring && { recurring: parsedRecurring }), + ...(parsedAddress ? { address: parsedAddress } : {}), + ...(parsedMetadata ? { metadata: parsedMetadata } : {}), + ...(parsedItems ? { items: parsedItems } : {}), + ...(parsedImages ? { images: parsedImages } : {}), + ...(parsedRecurring ? { recurring: parsedRecurring } : {}), ...parsedBooleans, ...pagination, } diff --git a/apps/sim/blocks/blocks/sts.ts b/apps/sim/blocks/blocks/sts.ts index d520fbe56eb..d6f3c1437c6 100644 --- a/apps/sim/blocks/blocks/sts.ts +++ b/apps/sim/blocks/blocks/sts.ts @@ -1,7 +1,7 @@ import { STSIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, withSavedCredential } from '@/blocks/utils' export const STSBlock: BlockConfig = { type: 'sts', @@ -296,12 +296,12 @@ export const STSBlock: BlockConfig = { throw new Error(`Invalid STS operation: ${params.operation}`) } }, - params: (params) => { - const { operation, durationSeconds, ...rest } = params + params: (params, context) => { + const { durationSeconds, ...rest } = params const result: Record = { region: rest.region } - switch (operation) { + switch (mapperOperation(params, context)) { case 'assume_role': result.accessKeyId = rest.accessKeyId result.secretAccessKey = rest.secretAccessKey diff --git a/apps/sim/blocks/blocks/supabase.ts b/apps/sim/blocks/blocks/supabase.ts index 01187471c6d..9491c0cf066 100644 --- a/apps/sim/blocks/blocks/supabase.ts +++ b/apps/sim/blocks/blocks/supabase.ts @@ -1,7 +1,7 @@ import { getErrorMessage } from '@sim/utils/errors' import { SupabaseIcon } from '@/components/icons' import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' -import { normalizeFileInput, withSavedCredential } from '@/blocks/utils' +import { mapperOperation, normalizeFileInput, withSavedCredential } from '@/blocks/utils' /** Canonical basic/advanced pair for the storage upload payload. */ const FILE_DATA_FIELD = ['file', 'fileContent'] as const @@ -1178,9 +1178,9 @@ Return ONLY the PostgREST filter expression - no explanations, no markdown, no e throw new Error(`Invalid Supabase operation: ${params.operation}`) } }, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { - operation, data, filter, queryEmbedding, diff --git a/apps/sim/blocks/blocks/table.test.ts b/apps/sim/blocks/blocks/table.test.ts index 127789492a8..ed9208ffb6f 100644 --- a/apps/sim/blocks/blocks/table.test.ts +++ b/apps/sim/blocks/blocks/table.test.ts @@ -5,8 +5,11 @@ vi.mock('@/triggers', () => triggersMock) import { TableBlock } from '@/blocks/blocks/table' -function params(input: Record): Record { - return TableBlock.tools.config?.params?.(input as never) as Record +function params( + input: Record, + context?: { operation: string } +): Record { + return TableBlock.tools.config?.params?.(input as never, context) as Record } describe('table query_rows transformer', () => { @@ -33,3 +36,60 @@ describe('table query_rows transformer', () => { ).toBeUndefined() }) }) + +describe('table transformers on an Agent tool call (operation only in context)', () => { + const winsRule = [ + { id: '1', logicalOperator: 'and', column: 'wins', operator: 'gte', value: '10' }, + ] + + it('compiles the tool row builder filter and sort and coerces the limit', () => { + const out = params( + { + tableId: 'table-1', + builderMode: 'builder', + filterBuilder: winsRule, + sortBuilder: [{ id: '1', column: 'wins', direction: 'desc' }], + limit: 5, + }, + { operation: 'query_rows' } + ) + expect(out.filter).toEqual({ wins: { $gte: 10 } }) + expect(out.sort).toEqual({ wins: 'desc' }) + expect(out.limit).toBe(5) + }) + + it('keeps the model filter and sort when the stored builder rule list is empty', () => { + const out = params( + { + tableId: 'table-1', + builderMode: 'builder', + filterBuilder: [], + sortBuilder: [], + filter: { status: 'active' }, + sort: '{"wins":"desc"}', + }, + { operation: 'query_rows' } + ) + expect(out.filter).toEqual({ status: 'active' }) + expect(out.sort).toEqual({ wins: 'desc' }) + }) + + it('keeps the model filter for a bulk delete when the stored bulk builder is empty', () => { + const out = params( + { tableId: 'table-1', bulkFilterMode: 'builder', bulkFilterBuilder: [], filter: '{"a":1}' }, + { operation: 'delete_rows_by_filter' } + ) + expect(out.filter).toEqual({ a: 1 }) + }) + + it('leaves an empty canvas builder with no filter even when a stale JSON filter is saved', () => { + const out = params({ + operation: 'query_rows', + tableId: 'table-1', + builderMode: 'builder', + filterBuilder: [], + filter: '{"stale":true}', + }) + expect(out.filter).toBeUndefined() + }) +}) diff --git a/apps/sim/blocks/blocks/table.ts b/apps/sim/blocks/blocks/table.ts index 9a969db1d60..cee3e621c26 100644 --- a/apps/sim/blocks/blocks/table.ts +++ b/apps/sim/blocks/blocks/table.ts @@ -2,12 +2,16 @@ import { Table } from '@sim/emcn/icons' import { toError } from '@sim/utils/errors' import { TABLE_LIMITS } from '@/lib/table/constants' import { filterRulesToFilter, sortRulesToSort } from '@/lib/table/query-builder/converters' -import type { BlockConfig } from '@/blocks/types' +import type { BlockConfig, BlockToolParamsContext } from '@/blocks/types' import { + failToolCallOnError, + isToolCall, + mapperOperation, parseOptionalNumberInput, resolveTableColumnSelection, TABLE_OUTPUT_COLUMNS_INPUT, TABLE_OUTPUT_COLUMNS_SUBBLOCK, + toolCallArg, } from '@/blocks/utils' import { TABLE_ID_PARAM } from '@/tools/table/params' import { getTrigger } from '@/triggers' @@ -68,6 +72,8 @@ interface TableBlockParams { bulkFilterMode?: string bulkFilterBuilder?: unknown conflictColumn?: string + /** The tool's own `conflictTarget` param, set in an Agent tool row. */ + conflictTarget?: string } /** Normalized params after parsing, ready for tool request body */ @@ -83,17 +89,63 @@ interface ParsedParams { conflictTarget?: string } +/** + * Resolves a filter or sort from its builder rules when the builder is active, else from the + * JSON field. On a tool call a builder that yields nothing (a stored empty or incomplete rule + * list) falls back to the model's `filter`/`sort` arg instead of discarding it; the canvas keeps + * the builder's result. + */ +function resolveBuilderOrJson( + builderActive: boolean, + builderValue: unknown, + fromBuilder: (rules: TRule[]) => unknown, + json: unknown, + fieldName: string, + context: BlockToolParamsContext | undefined +): unknown { + if (builderActive) { + // A tool row's rules that did not decode to an array are corrupt, not empty: falling back + // would run the operation on the model's filter instead of the one the user pinned. + if (isToolCall(context) && !Array.isArray(builderValue)) { + throw new Error(`Invalid ${fieldName} builder rules: expected a list of conditions.`) + } + const built = fromBuilder(builderValue as TRule[]) || undefined + if (built !== undefined || !isToolCall(context) || !json) return built + } else if (!json) { + return undefined + } + return parseJSON(json, fieldName) +} + +function resolveBulkFilter( + params: TableBlockParams, + context: BlockToolParamsContext | undefined +): unknown { + return resolveBuilderOrJson( + params.bulkFilterMode === 'builder' && Boolean(params.bulkFilterBuilder), + params.bulkFilterBuilder, + filterRulesToFilter, + params.filter, + 'Filter', + context + ) +} + /** Transforms raw block params into tool request params for each operation */ -const paramTransformers: Record ParsedParams> = { +const paramTransformers: Record< + string, + (params: TableBlockParams, context: BlockToolParamsContext | undefined) => ParsedParams +> = { insert_row: (params) => ({ tableId: params.tableId, data: parseJSON(params.data, 'Row Data'), }), - upsert_row: (params) => ({ + upsert_row: (params, context) => ({ tableId: params.tableId, data: parseJSON(params.data, 'Row Data'), - conflictTarget: params.conflictColumn || undefined, + conflictTarget: + params.conflictColumn || toolCallArg(context, params.conflictTarget) || undefined, }), batch_insert_rows: (params) => ({ @@ -107,20 +159,10 @@ const paramTransformers: Record ParsedPara data: parseJSON(params.data, 'Row Data'), }), - update_rows_by_filter: (params) => { - let filter: unknown - if (params.bulkFilterMode === 'builder' && params.bulkFilterBuilder) { - filter = - filterRulesToFilter( - params.bulkFilterBuilder as Parameters[0] - ) || undefined - } else if (params.filter) { - filter = parseJSON(params.filter, 'Filter') - } - + update_rows_by_filter: (params, context) => { return { tableId: params.tableId, - filter, + filter: resolveBulkFilter(params, context), data: parseJSON(params.data, 'Row Data'), limit: parseOptionalNumberInput(params.limit, 'Limit', { integer: true, @@ -135,20 +177,10 @@ const paramTransformers: Record ParsedPara rowId: params.rowId, }), - delete_rows_by_filter: (params) => { - let filter: unknown - if (params.bulkFilterMode === 'builder' && params.bulkFilterBuilder) { - filter = - filterRulesToFilter( - params.bulkFilterBuilder as Parameters[0] - ) || undefined - } else if (params.filter) { - filter = parseJSON(params.filter, 'Filter') - } - + delete_rows_by_filter: (params, context) => { return { tableId: params.tableId, - filter, + filter: resolveBulkFilter(params, context), limit: parseOptionalNumberInput(params.limit, 'Limit', { integer: true, min: 1, @@ -166,23 +198,24 @@ const paramTransformers: Record ParsedPara tableId: params.tableId, }), - query_rows: (params) => { - let filter: unknown - if (params.builderMode === 'builder' && params.filterBuilder) { - filter = - filterRulesToFilter(params.filterBuilder as Parameters[0]) || - undefined - } else if (params.filter) { - filter = parseJSON(params.filter, 'Filter') - } - - let sort: unknown - if (params.builderMode === 'builder' && params.sortBuilder) { - sort = - sortRulesToSort(params.sortBuilder as Parameters[0]) || undefined - } else if (params.sort) { - sort = parseJSON(params.sort, 'Sort') - } + query_rows: (params, context) => { + const builderMode = params.builderMode === 'builder' + const filter = resolveBuilderOrJson( + builderMode && Boolean(params.filterBuilder), + params.filterBuilder, + filterRulesToFilter, + params.filter, + 'Filter', + context + ) + const sort = resolveBuilderOrJson( + builderMode && Boolean(params.sortBuilder), + params.sortBuilder, + sortRulesToSort, + params.sort, + 'Sort', + context + ) return { tableId: params.tableId, @@ -731,12 +764,12 @@ Return ONLY the sort JSON:`, } return toolMap[params.operation] || 'table_query_rows' }, - params: (params) => { + params: (params, context) => { const { operation, ...rest } = params - const transformer = paramTransformers[operation] + const transformer = paramTransformers[mapperOperation(params, context)] if (transformer) { - return transformer(rest as TableBlockParams) + return failToolCallOnError(context, () => transformer(rest as TableBlockParams, context)) } return rest diff --git a/apps/sim/blocks/blocks/table_v2.test.ts b/apps/sim/blocks/blocks/table_v2.test.ts index 356ca950197..0a320087e80 100644 --- a/apps/sim/blocks/blocks/table_v2.test.ts +++ b/apps/sim/blocks/blocks/table_v2.test.ts @@ -10,8 +10,11 @@ vi.mock('@/triggers', () => triggersMock) import { TableV2Block } from '@/blocks/blocks/table_v2' -function params(input: Record): Record { - return TableV2Block.tools.config?.params?.(input as never) as Record +function params( + input: Record, + context?: { operation: string } +): Record { + return TableV2Block.tools.config?.params?.(input as never, context) as Record } describe('table_v2 query_rows transformer', () => { @@ -173,3 +176,36 @@ describe('table_v2 blank and malformed editor inputs', () => { ) }) }) + +/** + * On an Agent tool call the operation arrives only in context, and the model's `filter`/`order` + * args have already been folded into the `filterInput`/`sortInput` canonical values. + */ +describe('table_v2 transformers on an Agent tool call', () => { + it('forwards the model filter as a predicate for a bulk update', () => { + const out = params( + { + tableId: 't', + filterInput: { field: 'status', op: 'eq', value: 'stale' }, + data: { archived: true }, + limit: 50, + }, + { operation: 'update_rows_by_filter' } + ) + expect(out.filter).toEqual({ all: [{ field: 'status', op: 'eq', value: 'stale' }] }) + expect(out.limit).toBe(50) + }) + + it('forwards the model order and filter for a query', () => { + const out = params( + { + tableId: 't', + filterInput: '{"field":"wins","op":"gte","value":10}', + sortInput: [{ field: 'wins', direction: 'desc' }], + }, + { operation: 'query_rows' } + ) + expect(out.filter).toEqual({ all: [{ field: 'wins', op: 'gte', value: 10 }] }) + expect(out.order).toEqual([{ field: 'wins', direction: 'desc' }]) + }) +}) diff --git a/apps/sim/blocks/blocks/table_v2.ts b/apps/sim/blocks/blocks/table_v2.ts index 94efed49f91..e7e303b2934 100644 --- a/apps/sim/blocks/blocks/table_v2.ts +++ b/apps/sim/blocks/blocks/table_v2.ts @@ -11,11 +11,14 @@ import type { TablePredicate, TablePredicateInput, } from '@/lib/table/types' -import type { BlockConfig } from '@/blocks/types' +import type { BlockConfig, BlockToolParamsContext } from '@/blocks/types' import { + failToolCallOnError, + mapperOperation, resolveTableColumnSelection, TABLE_OUTPUT_COLUMNS_INPUT, TABLE_OUTPUT_COLUMNS_SUBBLOCK, + toolCallArg, } from '@/blocks/utils' import { TABLE_ID_PARAM } from '@/tools/table/params' import { getTrigger } from '@/triggers' @@ -62,9 +65,12 @@ interface TableBlockParams { columns?: unknown filterInput?: unknown sortInput?: unknown - limit?: string + /** A string on the canvas; a number when a model supplies it on a tool call. */ + limit?: string | number cursor?: string conflictColumn?: string + /** The tool's own `conflictTarget` param, set in an Agent tool row. */ + conflictTarget?: string } /** @@ -86,9 +92,24 @@ function resolveFilter(params: TableBlockParams): TablePredicate | undefined { return normalizeTablePredicate(predicate) } +/** + * A sort-spec array (`[{field, direction}]`), as a model passes the tool's `order` arg, rather + * than the visual builder's rules, which always carry `column`. + */ +function isSortSpec(raw: unknown[]): raw is SortSpec { + return ( + raw.length > 0 && + raw.every( + (entry) => + typeof entry === 'object' && entry !== null && 'field' in entry && !('column' in entry) + ) + ) +} + function resolveOrder(params: TableBlockParams): SortSpec | undefined { const raw = params.sortInput if (Array.isArray(raw)) { + if (isSortSpec(raw)) return raw return raw.length > 0 ? (sortRulesToSortSpec(raw as SortRule[]) ?? undefined) : undefined } const parsed = parseJSON(raw, 'Sort') @@ -112,11 +133,11 @@ interface ParsedParams { * Fail-fast limit parsing for bulk ops: an unparseable limit must never * silently widen the operation to every matching row. */ -function parseOptionalLimit(raw: string | undefined): number | undefined { - if (!raw) return undefined - const value = Number.parseInt(raw, 10) +function parseOptionalLimit(raw: unknown): number | undefined { + if (raw === undefined || raw === null || raw === '') return undefined + const value = typeof raw === 'number' ? Math.trunc(raw) : Number.parseInt(String(raw), 10) if (Number.isNaN(value)) { - throw new Error(`Invalid Limit "${raw}" — expected a number.`) + throw new Error(`Invalid Limit "${String(raw)}" — expected a number.`) } return value } @@ -130,16 +151,20 @@ function resolveCursor(raw: string | undefined): string | undefined { return raw } -const paramTransformers: Record ParsedParams> = { +const paramTransformers: Record< + string, + (params: TableBlockParams, context: BlockToolParamsContext | undefined) => ParsedParams +> = { insert_row: (params) => ({ tableId: params.tableId, data: parseJSON(params.data, 'Row Data'), }), - upsert_row: (params) => ({ + upsert_row: (params, context) => ({ tableId: params.tableId, data: parseJSON(params.data, 'Row Data'), - conflictTarget: params.conflictColumn || undefined, + conflictTarget: + params.conflictColumn || toolCallArg(context, params.conflictTarget) || undefined, }), batch_insert_rows: (params) => ({ @@ -542,11 +567,11 @@ Return ONLY the JSON object:`, } return toolMap[params.operation] || 'table_query_rows_v2' }, - params: (params) => { + params: (params, context) => { const { operation, ...rest } = params - const transformer = paramTransformers[operation] + const transformer = paramTransformers[mapperOperation(params, context)] if (transformer) { - return transformer(rest as TableBlockParams) + return failToolCallOnError(context, () => transformer(rest as TableBlockParams, context)) } return rest }, diff --git a/apps/sim/blocks/blocks/tailscale.test.ts b/apps/sim/blocks/blocks/tailscale.test.ts new file mode 100644 index 00000000000..c2ab64d91cf --- /dev/null +++ b/apps/sim/blocks/blocks/tailscale.test.ts @@ -0,0 +1,54 @@ +/** + * Agent tool calls pass the operation only in context and supply arguments under the tool's + * param names, so the mapper must keep them rather than overwrite them from block-only fields. + */ +import { describe, expect, it } from 'vitest' +import { TailscaleBlock } from '@/blocks/blocks/tailscale' +import { tailscaleCreateAuthKeyTool } from '@/tools/tailscale/create_auth_key' +import { tailscaleListUsersTool } from '@/tools/tailscale/list_users' +import { tailscaleSetDnsNameserversTool } from '@/tools/tailscale/set_dns_nameservers' +import type { ToolConfig } from '@/tools/types' + +const STORED = { apiKey: 'tskey-api-test', tailnet: '-' } + +function agentParams(operation: string, args: Record): Record { + const inputs = { ...STORED, ...args } + const mapped = TailscaleBlock.tools.config?.params?.(inputs, { operation }) ?? {} + return { ...inputs, ...mapped } +} + +function requestBody(tool: ToolConfig, params: Record) { + const body = tool.request.body + if (typeof body !== 'function') throw new Error(`${tool.id} has no request body`) + return body(params) +} + +function requestUrl(tool: ToolConfig, params: Record) { + const url = tool.request.url + return typeof url === 'function' ? url(params) : url +} + +describe('Tailscale block agent tool calls', () => { + it('sends the model description and expiry when creating an auth key', () => { + const params = agentParams('create_auth_key', { + description: 'ci runner', + expirySeconds: 3600, + }) + expect(requestBody(tailscaleCreateAuthKeyTool, params)).toMatchObject({ + description: 'ci runner', + expirySeconds: 3600, + }) + }) + + it('sends the model nameservers when setting DNS nameservers', () => { + const params = agentParams('set_dns_nameservers', { dns: '8.8.8.8, 1.1.1.1' }) + expect(requestBody(tailscaleSetDnsNameserversTool, params)).toEqual({ + dns: ['8.8.8.8', '1.1.1.1'], + }) + }) + + it('keeps the model role filter when listing users', () => { + const params = agentParams('list_users', { role: 'admin' }) + expect(requestUrl(tailscaleListUsersTool, params)).toContain('role=admin') + }) +}) diff --git a/apps/sim/blocks/blocks/tailscale.ts b/apps/sim/blocks/blocks/tailscale.ts index 9962aa450ab..011e1888a75 100644 --- a/apps/sim/blocks/blocks/tailscale.ts +++ b/apps/sim/blocks/blocks/tailscale.ts @@ -1,7 +1,7 @@ import { TailscaleIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' const SWITCH_DEFAULTS = { authorize_device: { authorized: true }, @@ -750,18 +750,22 @@ export const TailscaleBlock: BlockConfig = { ], config: { tool: (params) => `tailscale_${params.operation}`, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const mapped: Record = { ...params, - dns: params.dnsServers, - description: params.authKeyDescription, + dns: params.dnsServers ?? toolCallArg(context, params.dns), + description: params.authKeyDescription ?? toolCallArg(context, params.description), expirySeconds: undefined, name: params.name ?? '', - role: params.operation === 'list_users' ? params.roleFilter || undefined : params.role, + role: + operation === 'list_users' + ? params.roleFilter || toolCallArg(context, params.role) || undefined + : params.role, } const defaults = Object.entries(SWITCH_DEFAULTS).find( - ([operation]) => operation === params.operation + ([switchOperation]) => switchOperation === operation )?.[1] ?? {} for (const [field, defaultValue] of Object.entries(defaults)) { const value = params[field] @@ -776,7 +780,7 @@ export const TailscaleBlock: BlockConfig = { } } if ( - params.operation === 'create_auth_key' && + operation === 'create_auth_key' && params.expirySeconds != null && !(typeof params.expirySeconds === 'string' && params.expirySeconds.trim() === '') ) { diff --git a/apps/sim/blocks/blocks/telegram.test.ts b/apps/sim/blocks/blocks/telegram.test.ts index 5037c5b0603..80216f20d71 100644 --- a/apps/sim/blocks/blocks/telegram.test.ts +++ b/apps/sim/blocks/blocks/telegram.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { TelegramBlock } from '@/blocks/blocks/telegram' +import { TelegramBlock, TelegramV2Block } from '@/blocks/blocks/telegram' const MEDIA_OPS = [ { operation: 'telegram_send_photo', key: 'photo', label: 'Photo' }, @@ -53,3 +53,49 @@ describe('Telegram media params', () => { }) } }) + +/** + * A tool call (Agent tool row, Pi, Human v2) passes the operation only in the context, and the + * merged params hold the model's args under the tool's param names next to any block-only values + * the user stored on the row. + */ +function mapToolCall(operation: string, merged: Record) { + const mapper = TelegramV2Block.tools.config?.params + if (!mapper) throw new Error('Telegram V2 has no params mapper') + return mapper({ chatId: '12345', ...merged }, { operation }) as Record +} + +describe('Telegram tool-call params', () => { + it('keeps the model emoji instead of clearing the reaction', () => { + const mapped = mapToolCall('telegram_set_message_reaction', { messageId: 5, reaction: '👍' }) + expect(mapped.reaction).toBe('👍') + }) + + it('keeps the model poll options and coerces a stored dropdown boolean', () => { + const mapped = mapToolCall('telegram_send_poll', { + question: 'Lunch?', + options: ['Pizza', 'Sushi'], + isAnonymous: 'false', + }) + expect(mapped.options).toEqual(['Pizza', 'Sushi']) + expect(mapped.isAnonymous).toBe(false) + }) + + it('sends poll options the user stored on the tool row', () => { + const mapped = mapToolCall('telegram_send_poll', { + question: 'Lunch?', + pollOptions: 'Pizza\nSushi', + }) + expect(mapped.options).toBe('Pizza\nSushi') + }) + + it('sends a photo uploaded on the tool row as its https URL', () => { + const mapped = mapToolCall('telegram_send_photo', { photoSource: userFile }) + expect(mapped.photo).toBe('https://storage.example/pic.jpg') + }) + + it('accepts a numeric chat ID from the model', () => { + const mapped = mapToolCall('telegram_get_chat', { chatId: -1001234 }) + expect(mapped.chatId).toBe('-1001234') + }) +}) diff --git a/apps/sim/blocks/blocks/telegram.ts b/apps/sim/blocks/blocks/telegram.ts index 398bc6c2bdd..37ca2a8efd9 100644 --- a/apps/sim/blocks/blocks/telegram.ts +++ b/apps/sim/blocks/blocks/telegram.ts @@ -1,8 +1,18 @@ import { TelegramIcon } from '@/components/icons' import { resolveHttpsUrlFromFileInput } from '@/lib/uploads/utils/file' -import type { BlockConfig, BlockMeta, BlockToolParams } from '@/blocks/types' +import type { + BlockConfig, + BlockMeta, + BlockToolParams, + BlockToolParamsContext, +} from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput, withSavedCredential } from '@/blocks/utils' +import { + mapperOperation, + normalizeFileInput, + toolCallArg, + withSavedCredential, +} from '@/blocks/utils' import { getTrigger } from '@/triggers' /** @@ -58,13 +68,21 @@ function toBoolean(value: unknown): boolean { return value === true || String(value).toLowerCase() === 'true' } -/** Builds Telegram tool params; a saved credential supplies the bot token, so only the legacy block requires it inline. */ -function telegramToolParams(params: BlockToolParams, requireBotToken: boolean) { +/** + * Builds Telegram tool params; a saved credential supplies the bot token, so only the legacy block + * requires it inline. On a tool call the operation arrives in `context` and model args use the + * tool's param names, so a block-only field falls back to the model's value for that param. + */ +function telegramToolParams( + params: BlockToolParams, + requireBotToken: boolean, + context?: BlockToolParamsContext +) { if (requireBotToken && !params.botToken) { throw new Error('Bot token required for this operation') } - const chatId = (params.chatId || '').trim() + const chatId = String(params.chatId ?? '').trim() if (!chatId) { throw new Error('Chat ID is required.') } @@ -74,7 +92,7 @@ function telegramToolParams(params: BlockToolParams, requireBotToken: boolean) { chatId, } - switch (params.operation) { + switch (mapperOperation(params, context)) { case 'telegram_message': if (!params.text) { throw new Error('Message text is required.') @@ -134,7 +152,7 @@ function telegramToolParams(params: BlockToolParams, requireBotToken: boolean) { text: params.text, } case 'telegram_forward_message': { - const fromChatId = (params.fromChatId || '').trim() + const fromChatId = String(params.fromChatId ?? '').trim() if (!fromChatId) { throw new Error('Source chat ID is required.') } @@ -145,7 +163,7 @@ function telegramToolParams(params: BlockToolParams, requireBotToken: boolean) { } } case 'telegram_copy_message': { - const fromChatId = (params.fromChatId || '').trim() + const fromChatId = String(params.fromChatId ?? '').trim() if (!fromChatId) { throw new Error('Source chat ID is required.') } @@ -180,7 +198,7 @@ function telegramToolParams(params: BlockToolParams, requireBotToken: boolean) { const pollParams: Record = { ...commonParams, question: params.question, - options: params.pollOptions, + options: params.pollOptions || toolCallArg(context, params.options), } if (params.isAnonymous !== undefined && params.isAnonymous !== '') { pollParams.isAnonymous = toBoolean(params.isAnonymous) @@ -211,7 +229,7 @@ function telegramToolParams(params: BlockToolParams, requireBotToken: boolean) { const reactionParams: Record = { ...commonParams, messageId: requireNumber(params.messageId, 'Message ID'), - reaction: params.reactionEmoji, + reaction: params.reactionEmoji || toolCallArg(context, params.reaction), } if (params.isBig !== undefined && params.isBig !== '') { reactionParams.isBig = toBoolean(params.isBig) @@ -701,7 +719,7 @@ export const TelegramBlock: BlockConfig = { id: 'pollOptions', title: 'Poll Options', type: 'long-input', - placeholder: 'One answer option per line (2-10 options)', + placeholder: 'One answer option per line (1-12 options)', description: 'Enter each answer option on its own line', required: { field: 'operation', value: 'telegram_send_poll' }, condition: { field: 'operation', value: 'telegram_send_poll' }, @@ -812,7 +830,7 @@ export const TelegramBlock: BlockConfig = { ], config: { tool: (params) => params.operation || 'telegram_message', - params: (params) => telegramToolParams(params, true), + params: (params, context) => telegramToolParams(params, true, context), }, }, inputs: { @@ -1022,7 +1040,7 @@ export const TelegramBlockMeta = { name: 'run-a-poll', description: 'Post a poll to a Telegram chat to collect a quick vote from members.', content: - '# Run a Telegram Poll\n\nGather a fast decision or sentiment check from a chat or channel.\n\n## Steps\n1. Use the Send Poll operation with your Bot Token and the target Chat ID.\n2. Set the Poll Question and add one answer option per line (2-10 options).\n3. In advanced settings, choose whether the poll is anonymous and whether multiple answers are allowed.\n4. Send the poll, then read replies from the chat to act on the outcome.\n\n## Output\nReturn the sent message ID so the poll post can be referenced or pinned later.', + '# Run a Telegram Poll\n\nGather a fast decision or sentiment check from a chat or channel.\n\n## Steps\n1. Use the Send Poll operation with your Bot Token and the target Chat ID.\n2. Set the Poll Question and add one answer option per line (1-12 options).\n3. In advanced settings, choose whether the poll is anonymous and whether multiple answers are allowed.\n4. Send the poll, then read replies from the chat to act on the outcome.\n\n## Output\nReturn the sent message ID so the poll post can be referenced or pinned later.', }, { name: 'pin-and-react-to-messages', @@ -1042,6 +1060,6 @@ export const TelegramV2Block: BlockConfig = { ...withSavedCredential( TelegramBlock, { id: 'credential', type: 'oauth-input', serviceId: 'telegram', title: 'Telegram Credential' }, - { params: (params) => telegramToolParams(params, false) } + { params: (params, context) => telegramToolParams(params, false, context) } ), } diff --git a/apps/sim/blocks/blocks/temporal.test.ts b/apps/sim/blocks/blocks/temporal.test.ts new file mode 100644 index 00000000000..88122d8ed58 --- /dev/null +++ b/apps/sim/blocks/blocks/temporal.test.ts @@ -0,0 +1,37 @@ +/** + * Temporal block mapper on the agent tool-call path, where the operation arrives only in the + * mapper context and the merged params mix stored block fields with model args keyed by tool params. + */ +import { describe, expect, it } from 'vitest' +import { TemporalBlock } from '@/blocks/blocks/temporal' + +function params( + input: Record, + context?: { operation: string } +): Record { + return TemporalBlock.tools.config?.params?.(input as never, context) as Record +} + +describe('temporal mapper on tool calls', () => { + it('forwards a stored schedule query and keeps the model page size and token', () => { + expect( + params( + { scheduleQuery: 'TemporalScheduledById = "x"', maximumPageSize: 25, nextPageToken: 'abc' }, + { operation: 'list_schedules' } + ) + ).toMatchObject({ + query: 'TemporalScheduledById = "x"', + maximumPageSize: 25, + nextPageToken: 'abc', + }) + }) + + it('does not create a paused schedule when the model sends paused as the string "false"', () => { + expect( + params( + { scheduleId: 's', cronExpressions: '0 12 * * *', paused: 'false' }, + { operation: 'create_schedule' } + ) + ).toMatchObject({ cronExpressions: '0 12 * * *', paused: false }) + }) +}) diff --git a/apps/sim/blocks/blocks/temporal.ts b/apps/sim/blocks/blocks/temporal.ts index 5a5790c4448..c6f3ea2464b 100644 --- a/apps/sim/blocks/blocks/temporal.ts +++ b/apps/sim/blocks/blocks/temporal.ts @@ -1,6 +1,7 @@ import { TemporalIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { IntegrationType } from '@/blocks/types' +import { mapperOperation, parseOptionalBooleanInput, toolCallArg } from '@/blocks/utils' /** Coerces a subBlock value to a finite number, returning undefined for empty or non-numeric input. */ function toFiniteNumber(value: unknown): number | undefined { @@ -665,56 +666,72 @@ Return ONLY a valid JSON object - no explanations, no extra text.`, ], config: { tool: (params) => `temporal_${params.operation}`, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const result: Record = {} - if (params.operation === 'start_workflow' || params.operation === 'signal_with_start') { + if (operation === 'start_workflow' || operation === 'signal_with_start') { result.executionTimeoutSeconds = toFiniteNumber(params.executionTimeoutSeconds) result.runTimeoutSeconds = toFiniteNumber(params.runTimeoutSeconds) if (!params.workflowIdReusePolicy) result.workflowIdReusePolicy = undefined if (!params.workflowIdConflictPolicy) result.workflowIdConflictPolicy = undefined } - if (params.operation === 'list_workflows' || params.operation === 'count_workflows') { - result.query = params.listQuery || undefined + if (operation === 'list_workflows' || operation === 'count_workflows') { + result.query = params.listQuery || toolCallArg(context, params.query) || undefined } - if (params.operation === 'list_workflows') { + if (operation === 'list_workflows') { result.pageSize = toFiniteNumber(params.pageSize) } - if (params.operation === 'get_workflow_history') { - result.maximumPageSize = toFiniteNumber(params.historyPageSize) - result.nextPageToken = params.historyNextPageToken || undefined + if (operation === 'get_workflow_history') { + result.maximumPageSize = + toFiniteNumber(params.historyPageSize) ?? + toolCallArg(context, toFiniteNumber(params.maximumPageSize)) + result.nextPageToken = + params.historyNextPageToken || toolCallArg(context, params.nextPageToken) || undefined if (!params.historyEventFilterType) result.historyEventFilterType = undefined } - if (params.operation === 'reset_workflow') { + if (operation === 'reset_workflow') { result.workflowTaskFinishEventId = toFiniteNumber(params.workflowTaskFinishEventId) } - if (params.operation === 'create_schedule') { - result.cronExpressions = params.scheduleCronExpressions || undefined - result.intervalSeconds = toFiniteNumber(params.scheduleIntervalSeconds) - result.timezone = params.scheduleTimezone || undefined - result.notes = params.scheduleNotes || undefined - result.paused = params.schedulePaused === 'true' ? true : undefined + if (operation === 'create_schedule') { + result.cronExpressions = + params.scheduleCronExpressions || + toolCallArg(context, params.cronExpressions) || + undefined + result.intervalSeconds = + toFiniteNumber(params.scheduleIntervalSeconds) ?? + toolCallArg(context, toFiniteNumber(params.intervalSeconds)) + result.timezone = + params.scheduleTimezone || toolCallArg(context, params.timezone) || undefined + result.notes = params.scheduleNotes || toolCallArg(context, params.notes) || undefined + result.paused = + params.schedulePaused === 'true' + ? true + : toolCallArg(context, parseOptionalBooleanInput(params.paused)) } - if (params.operation === 'list_schedules') { - result.query = params.scheduleQuery || undefined - result.maximumPageSize = toFiniteNumber(params.schedulePageSize) - result.nextPageToken = params.scheduleNextPageToken || undefined + if (operation === 'list_schedules') { + result.query = params.scheduleQuery || toolCallArg(context, params.query) || undefined + result.maximumPageSize = + toFiniteNumber(params.schedulePageSize) ?? + toolCallArg(context, toFiniteNumber(params.maximumPageSize)) + result.nextPageToken = + params.scheduleNextPageToken || toolCallArg(context, params.nextPageToken) || undefined } if ( - (params.operation === 'trigger_schedule' || params.operation === 'create_schedule') && + (operation === 'trigger_schedule' || operation === 'create_schedule') && !params.overlapPolicy ) { result.overlapPolicy = undefined } - if (params.operation === 'describe_task_queue' && !params.taskQueueType) { + if (operation === 'describe_task_queue' && !params.taskQueueType) { result.taskQueueType = undefined } diff --git a/apps/sim/blocks/blocks/textract.test.ts b/apps/sim/blocks/blocks/textract.test.ts new file mode 100644 index 00000000000..68e3b5565d5 --- /dev/null +++ b/apps/sim/blocks/blocks/textract.test.ts @@ -0,0 +1,38 @@ +/** + * An Agent tool call runs the block mapper over `{ ...storedRowParams, ...modelArgs }` with the + * operation only in `context`; the tool then receives `{ ...merged, ...mapped }`. + */ +import { describe, expect, it } from 'vitest' +import { TextractV2Block } from '@/blocks/blocks/textract' + +const AWS = { accessKeyId: 'key', secretAccessKey: 'secret', region: 'us-east-1' } + +function toolCallParams(args: Record, operation: string) { + const mapped = TextractV2Block.tools.config?.params?.(args, { operation }) ?? {} + return { ...args, ...mapped } +} + +describe('Textract on an Agent tool call', () => { + it('sends the identity document URL stored on an Analyze ID tool row', () => { + expect( + toolCallParams({ ...AWS, document: 'https://example.com/id.png' }, 'analyze_id') + ).toMatchObject({ filePath: 'https://example.com/id.png' }) + }) + + it('keeps the feature types the model chose when it also sends queries', () => { + expect( + toolCallParams( + { + ...AWS, + document: { name: 'doc.png', key: 'k', url: 'https://example.com/doc.png' }, + featureTypes: ['FORMS'], + queries: [{ Text: 'What is the total?' }], + }, + 'analyze_document' + ) + ).toMatchObject({ + featureTypes: ['FORMS', 'QUERIES'], + queries: [{ Text: 'What is the total?' }], + }) + }) +}) diff --git a/apps/sim/blocks/blocks/textract.ts b/apps/sim/blocks/blocks/textract.ts index 9fc0c6a3ec2..707eb8c7a7b 100644 --- a/apps/sim/blocks/blocks/textract.ts +++ b/apps/sim/blocks/blocks/textract.ts @@ -5,10 +5,16 @@ import { type BlockConfig, type BlockMeta, type BlockToolParams, + type BlockToolParamsContext, IntegrationType, type SubBlockType, } from '@/blocks/types' -import { normalizeFileInput, withSavedCredential } from '@/blocks/utils' +import { + mapperOperation, + normalizeFileInput, + toolCallArg, + withSavedCredential, +} from '@/blocks/utils' const LEGACY_DOCUMENT_FIELD = ['fileUpload', 'filePath', 's3Uri'] as const const DOCUMENT_FIELD = ['fileUpload', 'fileReference', 's3Uri'] as const @@ -333,9 +339,13 @@ function requireAwsRegion(params: Record): string { * Tool params for a Textract v2+ operation. `accessKeys` is empty when a saved * AWS credential supplies them server-side. */ -function textractToolParams(params: BlockToolParams, accessKeys: Partial) { +function textractToolParams( + params: BlockToolParams, + accessKeys: Partial, + context?: BlockToolParamsContext +) { const region = requireAwsRegion(params) - const operation = params.operation || 'analyze_document' + const operation = mapperOperation(params, context) || 'analyze_document' if (operation === 'analyze_id') { const front = resolveDocumentParam(params.document) @@ -376,17 +386,23 @@ function textractToolParams(params: BlockToolParams, accessKeys: Partial( + Array.isArray(modelFeatureTypes) + ? modelFeatureTypes.filter((type): type is string => typeof type === 'string') + : [] + ) + if (params.extractTables) featureTypes.add('TABLES') + if (params.extractForms) featureTypes.add('FORMS') + if (params.detectSignatures) featureTypes.add('SIGNATURES') + if (params.analyzeLayout) featureTypes.add('LAYOUT') const queries = parseTextractQueries(params.queries) if (queries.length > 0) { - featureTypes.push('QUERIES') + featureTypes.add('QUERIES') parameters.queries = queries } - if (featureTypes.length > 0) parameters.featureTypes = featureTypes + if (featureTypes.size > 0) parameters.featureTypes = [...featureTypes] return parameters } @@ -566,7 +582,8 @@ export const TextractV2Block: BlockConfig = { if (operation === 'analyze_id') return 'textract_analyze_id' return 'textract_parser_v2' }, - params: (params) => textractToolParams(params, requireAwsAccessKeys(params)), + params: (params, context) => + textractToolParams(params, requireAwsAccessKeys(params), context), }, }, inputs: { @@ -644,7 +661,7 @@ export const TextractV3Block: BlockConfig = { ...withSavedCredential( TextractV2Block, { id: 'credential', type: 'oauth-input', serviceId: 'aws', title: 'AWS Credential' }, - { params: (params) => textractToolParams(params, {}) } + { params: (params, context) => textractToolParams(params, {}, context) } ), } diff --git a/apps/sim/blocks/blocks/tiktok.test.ts b/apps/sim/blocks/blocks/tiktok.test.ts index 1002576562e..e8d56bbea5b 100644 --- a/apps/sim/blocks/blocks/tiktok.test.ts +++ b/apps/sim/blocks/blocks/tiktok.test.ts @@ -24,4 +24,11 @@ describe('TikTokBlock', () => { expect(finalInputs.file).toEqual(file) expect(finalInputs.videoIds).toBeUndefined() }) + + it('queries the video ids an agent passes as an array', () => { + const args = { videoIds: ['v1', ' v2 '] } + const finalInputs = { ...args, ...buildParams(args, { operation: 'tiktok_query_videos' }) } + + expect(finalInputs.videoIds).toEqual(['v1', 'v2']) + }) }) diff --git a/apps/sim/blocks/blocks/tiktok.ts b/apps/sim/blocks/blocks/tiktok.ts index 1c41d44395c..f535088adc6 100644 --- a/apps/sim/blocks/blocks/tiktok.ts +++ b/apps/sim/blocks/blocks/tiktok.ts @@ -2,7 +2,7 @@ import { TikTokIcon } 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' const TIKTOK_TOOL_IDS = new Set([ @@ -212,8 +212,8 @@ export const TikTokBlock: BlockConfig = { } return operation }, - params: (params) => { - const operation = params.operation || 'tiktok_get_user' + params: (params, context) => { + const operation = mapperOperation(params, context) || 'tiktok_get_user' const result: Record = {} for (const key of TIKTOK_OPERATION_INPUT_KEYS) { result[key] = undefined @@ -230,8 +230,11 @@ export const TikTokBlock: BlockConfig = { } break case 'tiktok_query_videos': - result.videoIds = (params.videoIds || '') - .split(/[,\n]+/) + result.videoIds = ( + Array.isArray(params.videoIds) + ? params.videoIds.map(String) + : String(params.videoIds || '').split(/[,\n]+/) + ) .map((id: string) => id.trim()) .filter(Boolean) break diff --git a/apps/sim/blocks/blocks/tinybird.test.ts b/apps/sim/blocks/blocks/tinybird.test.ts new file mode 100644 index 00000000000..0518791e6dd --- /dev/null +++ b/apps/sim/blocks/blocks/tinybird.test.ts @@ -0,0 +1,41 @@ +/** + * An Agent tool call runs the block mapper over `{ ...storedRowParams, ...modelArgs }` with the + * operation only in `context`; the tool then receives `{ ...merged, ...mapped }`. + */ +import { describe, expect, it } from 'vitest' +import { TinybirdBlock } from '@/blocks/blocks/tinybird' + +function toolCallParams(args: Record, operation: string) { + const mapped = TinybirdBlock.tools.config?.params?.(args, { operation }) ?? {} + return { ...args, ...mapped } +} + +describe('Tinybird on an Agent tool call', () => { + it('runs the selected operation instead of requiring Send Events fields', () => { + expect(toolCallParams({ token: 'tok', query: 'SELECT 1' }, 'tinybird_query')).toMatchObject({ + query: 'SELECT 1', + }) + }) + + it('appends from the source URL the model supplied as url', () => { + expect( + toolCallParams( + { token: 'tok', datasource: 'events', url: 'https://example.com/data.csv' }, + 'tinybird_append_datasource' + ) + ).toMatchObject({ datasource: 'events', url: 'https://example.com/data.csv', format: 'csv' }) + }) + it('keeps the source format the model supplied as format', () => { + expect( + toolCallParams( + { + token: 'tok', + datasource: 'events', + url: 'https://example.com/data.ndjson', + format: 'ndjson', + }, + 'tinybird_append_datasource' + ) + ).toMatchObject({ format: 'ndjson' }) + }) +}) diff --git a/apps/sim/blocks/blocks/tinybird.ts b/apps/sim/blocks/blocks/tinybird.ts index 0beee5c963c..167fe2bcd57 100644 --- a/apps/sim/blocks/blocks/tinybird.ts +++ b/apps/sim/blocks/blocks/tinybird.ts @@ -1,7 +1,7 @@ import { TinybirdIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, toolCallArg, withSavedCredential } from '@/blocks/utils' export const TinybirdBlock: BlockConfig = { type: 'tinybird', @@ -247,8 +247,8 @@ export const TinybirdBlock: BlockConfig = { ], config: { tool: (params) => params.operation || 'tinybird_events', - params: (params) => { - const operation = params.operation || 'tinybird_events' + params: (params, context) => { + const operation = mapperOperation(params, context) || 'tinybird_events' const result: Record = { base_url: params.base_url, token: params.token, @@ -302,13 +302,14 @@ export const TinybirdBlock: BlockConfig = { if (!params.datasource) { throw new Error('Data Source is required for Append Data Source operation') } - if (!params.source_url) { + const sourceUrl = params.source_url || toolCallArg(context, params.url) + if (!sourceUrl) { throw new Error('Source File URL is required for Append Data Source operation') } result.datasource = params.datasource - result.url = params.source_url - result.format = params.source_format || 'csv' + result.url = sourceUrl + result.format = params.source_format || toolCallArg(context, params.format) || 'csv' } else if (operation === 'tinybird_truncate_datasource') { // Truncate Data Source operation if (!params.datasource) { diff --git a/apps/sim/blocks/blocks/tinyfish.ts b/apps/sim/blocks/blocks/tinyfish.ts index 45dd058a02b..41cfa4139a6 100644 --- a/apps/sim/blocks/blocks/tinyfish.ts +++ b/apps/sim/blocks/blocks/tinyfish.ts @@ -1,6 +1,7 @@ import { TinyFishIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { isToolCall, mapperOperation } from '@/blocks/utils' /** Operations that build and submit an automation run. */ const AUTOMATION_OPERATIONS = ['tinyfish_run', 'tinyfish_run_async'] @@ -497,7 +498,7 @@ Return ONLY the comma-separated URL list - no explanations, no extra text.`, return 'tinyfish_run' } }, - params: (params) => { + params: (params, context) => { const result: Record = {} /** @@ -528,10 +529,10 @@ Return ONLY the comma-separated URL list - no explanations, no extra text.`, /** * The list filter has its own sub-block id so it does not collide with * the automation goal, and is renamed here to the `goal` query the tool - * sends. + * sends. A tool call's model arg arrives as `goal` already. */ - if (params.operation === 'tinyfish_list_runs') { - result.goal = params.goalFilter + if (mapperOperation(params, context) === 'tinyfish_list_runs') { + result.goal = isToolCall(context) ? params.goalFilter || params.goal : params.goalFilter } return result diff --git a/apps/sim/blocks/blocks/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/apps/sim/blocks/blocks/trigger_dev.test.ts b/apps/sim/blocks/blocks/trigger_dev.test.ts new file mode 100644 index 00000000000..9bc985ff6ea --- /dev/null +++ b/apps/sim/blocks/blocks/trigger_dev.test.ts @@ -0,0 +1,28 @@ +/** + * An Agent tool call runs the block mapper over `{ ...storedRowParams, ...modelArgs }` with the + * operation only in `context`; the tool then receives `{ ...merged, ...mapped }`. + */ +import { describe, expect, it } from 'vitest' +import { TriggerDevBlock } from '@/blocks/blocks/trigger_dev' + +function toolCallParams(args: Record, operation: string) { + const mapped = TriggerDevBlock.tools.config?.params?.(args, { operation }) ?? {} + return { ...args, ...mapped } +} + +describe('Trigger.dev on an Agent tool call', () => { + it('keeps the filters the model supplied under the tool param names', () => { + expect( + toolCallParams( + { apiKey: 'tr_dev_x', taskIdentifier: 'send-email', status: 'COMPLETED', pageSize: 10 }, + 'trigger_dev_list_runs' + ) + ).toMatchObject({ taskIdentifier: 'send-email', status: 'COMPLETED', pageSize: 10 }) + }) + + it('keeps the deployment status filter the model supplied', () => { + expect( + toolCallParams({ apiKey: 'tr_dev_x', status: 'DEPLOYED' }, 'trigger_dev_list_deployments') + ).toMatchObject({ status: 'DEPLOYED' }) + }) +}) diff --git a/apps/sim/blocks/blocks/trigger_dev.ts b/apps/sim/blocks/blocks/trigger_dev.ts index c2ccb3ebe3e..7fa9bd996b0 100644 --- a/apps/sim/blocks/blocks/trigger_dev.ts +++ b/apps/sim/blocks/blocks/trigger_dev.ts @@ -1,7 +1,8 @@ +import { filterUndefined } from '@sim/utils/object' import { TriggerDevIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { isToolCall, mapperOperation, withSavedCredential } from '@/blocks/utils' const TASK_IDENTIFIER_OPERATIONS = ['trigger_dev_trigger_task', 'trigger_dev_batch_trigger_task'] const RUN_ID_OPERATIONS = [ @@ -965,8 +966,8 @@ Return ONLY the valid JSON object - no explanations, no markdown.`, ], config: { tool: (params) => params.operation, - params: (params) => { - const operation = params.operation as string + params: (params, context) => { + const operation = mapperOperation(params, context) const result: Record = {} const scoped = (value: unknown, operations: string[]) => @@ -1012,7 +1013,9 @@ Return ONLY the valid JSON object - no explanations, no markdown.`, result.page = scopedNumber(params.page, NUMBERED_PAGE_OPERATIONS) result.perPage = scopedNumber(params.perPage, NUMBERED_PAGE_OPERATIONS) - return result + // The canvas blanks unused keys so stale values never leak; a tool call's result spreads + // over the model's args, so an unset key is dropped instead of wiping the model's value. + return isToolCall(context) ? filterUndefined(result) : result }, }, }, diff --git a/apps/sim/blocks/blocks/twilio.ts b/apps/sim/blocks/blocks/twilio.ts index 2b747a7a052..958d41d57d9 100644 --- a/apps/sim/blocks/blocks/twilio.ts +++ b/apps/sim/blocks/blocks/twilio.ts @@ -42,9 +42,9 @@ export const TwilioSMSBlock: BlockConfig = { subBlocks: [ { id: 'phoneNumbers', - title: 'Recipient Phone Numbers', + title: 'Recipient Phone Number', type: 'long-input', - placeholder: 'Enter phone numbers with country code (one per line, e.g., +1234567890)', + placeholder: 'Enter one phone number with country code (e.g., +1234567890)', required: true, }, { @@ -74,8 +74,14 @@ export const TwilioSMSBlock: BlockConfig = { id: 'fromNumber', title: 'From Twilio Phone Number', type: 'short-input', - placeholder: 'e.g. +1234567890', - required: true, + placeholder: 'e.g. +1234567890 (optional with a Messaging Service SID)', + }, + { + id: 'messagingServiceSid', + title: 'Messaging Service SID', + type: 'short-input', + placeholder: 'MG... (optional)', + mode: 'advanced', }, ...getTrigger('twilio_sms_received').subBlocks, ...getTrigger('twilio_sms_status').subBlocks, @@ -91,16 +97,19 @@ export const TwilioSMSBlock: BlockConfig = { }, }, inputs: { - phoneNumbers: { type: 'string', description: 'Recipient phone numbers' }, + phoneNumbers: { type: 'string', description: 'Recipient phone number' }, message: { type: 'string', description: 'SMS message text' }, accountSid: { type: 'string', description: 'Twilio account SID' }, authToken: { type: 'string', description: 'Twilio auth token' }, fromNumber: { type: 'string', description: 'Sender phone number' }, + messagingServiceSid: { type: 'string', description: 'Twilio Messaging Service SID' }, }, outputs: { success: { type: 'boolean', description: 'Send success status' }, messageId: { type: 'string', description: 'Twilio message SID' }, status: { type: 'string', description: 'SMS delivery status (queued, sent, delivered, etc.)' }, + fromNumber: { type: 'string', description: 'Sender the message was sent from' }, + toNumber: { type: 'string', description: 'Recipient the message was sent to' }, error: { type: 'string', description: 'Error information if sending fails' }, }, } @@ -180,22 +189,22 @@ export const TwilioSMSBlockMeta = { skills: [ { name: 'send-sms-notification', - description: 'Send an SMS notification to one or more phone numbers via Twilio.', + description: 'Send an SMS notification to a phone number via Twilio.', content: - '# Send an SMS Notification\n\nDeliver a text message to one or more recipients through your Twilio number.\n\n## Steps\n1. Enter the Recipient Phone Numbers in E.164 format with country code (for example +14155551234), one per line for multiple recipients.\n2. Write the Message text, keeping it concise since long messages split into multiple segments.\n3. Provide your Twilio Account SID, Auth Token, and the verified From Twilio Phone Number.\n\n## Output\nReturn the success status, the Twilio message SID, and the delivery status (queued, sent, delivered) so the send can be confirmed.', + '# Send an SMS Notification\n\nDeliver a text message to a recipient through your Twilio number.\n\n## Steps\n1. Enter the Recipient Phone Number in E.164 format with country code (for example +14155551234). Each send reaches one recipient, so use one send per number to reach several people.\n2. Write the Message text, keeping it concise since long messages split into multiple segments.\n3. Provide your Twilio Account SID, Auth Token, and the verified From Twilio Phone Number.\n\n## Output\nReturn the success status, the Twilio message SID, and the delivery status (queued, sent, delivered) so the send can be confirmed.', }, { name: 'send-personalized-reminder', description: 'Send a personalized SMS reminder built from upstream data such as appointment or order details.', content: - '# Send a Personalized SMS Reminder\n\nText each recipient a reminder tailored with their own details.\n\n## Steps\n1. Pull the recipient details from an upstream block (a table row, CRM record, or order event).\n2. Build the Message using those fields, for example the appointment time or tracking number, plus any link.\n3. Set the Recipient Phone Numbers to the customer number from the source record.\n4. Provide the Account SID, Auth Token, and From Twilio Phone Number.\n\n## Output\nReturn the message SID and status for each send so delivery can be logged back to the source record.', + '# Send a Personalized SMS Reminder\n\nText each recipient a reminder tailored with their own details.\n\n## Steps\n1. Pull the recipient details from an upstream block (a table row, CRM record, or order event).\n2. Build the Message using those fields, for example the appointment time or tracking number, plus any link.\n3. Set the Recipient Phone Number to the customer number from the source record.\n4. Provide the Account SID, Auth Token, and From Twilio Phone Number.\n\n## Output\nReturn the message SID and status for each send so delivery can be logged back to the source record.', }, { name: 'send-verification-code', description: 'Send a one-time verification code over SMS for two-factor authentication.', content: - '# Send a Verification Code over SMS\n\nDeliver a one-time code to a user for two-factor authentication or confirmation.\n\n## Steps\n1. Generate or receive the one-time code from an upstream step.\n2. Compose the Message with the code and a short note (for example "Your code is 482913. It expires in 10 minutes.").\n3. Set the Recipient Phone Numbers to the user number and provide the Account SID, Auth Token, and From number.\n4. Log the send outcome for audit.\n\n## Output\nReturn the message SID and delivery status so the verification send can be tracked and audited.', + '# Send a Verification Code over SMS\n\nDeliver a one-time code to a user for two-factor authentication or confirmation.\n\n## Steps\n1. Generate or receive the one-time code from an upstream step.\n2. Compose the Message with the code and a short note (for example "Your code is 482913. It expires in 10 minutes.").\n3. Set the Recipient Phone Number to the user number and provide the Account SID, Auth Token, and From number.\n4. Log the send outcome for audit.\n\n## Output\nReturn the message SID and delivery status so the verification send can be tracked and audited.', }, ], } as const satisfies BlockMeta diff --git a/apps/sim/blocks/blocks/twilio_voice.test.ts b/apps/sim/blocks/blocks/twilio_voice.test.ts new file mode 100644 index 00000000000..93fdbfbb883 --- /dev/null +++ b/apps/sim/blocks/blocks/twilio_voice.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from 'vitest' +import { TwilioVoiceV2Block } from '@/blocks/blocks/twilio_voice' + +const mapParams = TwilioVoiceV2Block.tools.config?.params +if (!mapParams) throw new Error('Twilio Voice block has no params mapper') + +describe('Twilio Voice mapper on a tool call', () => { + it("applies a List Calls row's stored filters, which the operation only names in context", () => { + const result = mapParams( + { credential: 'cred-1', listStatus: 'completed', listPageSize: '10', listTo: '+14155550100' }, + { operation: 'list_calls' } + ) + + expect(result).toMatchObject({ status: 'completed', pageSize: 10, to: '+14155550100' }) + }) + + it("keeps the model's own filters when the row stores none", () => { + const result = mapParams( + { credential: 'cred-1', status: 'busy', to: '+14155550100', pageSize: 5 }, + { operation: 'list_calls' } + ) + + expect(result).toMatchObject({ status: 'busy', to: '+14155550100', pageSize: 5 }) + }) +}) diff --git a/apps/sim/blocks/blocks/twilio_voice.ts b/apps/sim/blocks/blocks/twilio_voice.ts index eac3f471e28..db3a4470286 100644 --- a/apps/sim/blocks/blocks/twilio_voice.ts +++ b/apps/sim/blocks/blocks/twilio_voice.ts @@ -1,7 +1,7 @@ import { TwilioIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { mapperOperation, withSavedCredential } from '@/blocks/utils' import { getTrigger } from '@/triggers' export const TwilioVoiceBlock: BlockConfig = { @@ -317,6 +317,17 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n generationType: 'timestamp', }, }, + { + id: 'pageToken', + title: 'Page Token', + type: 'short-input', + placeholder: 'Next page token from a previous List Calls result', + mode: 'advanced', + condition: { + field: 'operation', + value: 'list_calls', + }, + }, { id: 'recordingSid', title: 'Recording SID', @@ -344,9 +355,9 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n return 'twilio_voice_make_call' } }, - params: (params) => { - const { operation, timeout, record, listTo, listFrom, listStatus, listPageSize, ...rest } = - params + params: (params, context) => { + const operation = mapperOperation(params, context) + const { timeout, record, listTo, listFrom, listStatus, listPageSize, ...rest } = params const baseParams = { ...rest } @@ -394,6 +405,7 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n startTimeAfter: { type: 'string', description: 'Filter calls that started after this date' }, startTimeBefore: { type: 'string', description: 'Filter calls that started before this date' }, recordingSid: { type: 'string', description: 'Recording SID to retrieve' }, + pageToken: { type: 'string', description: 'Page token from a previous List Calls result' }, }, outputs: { success: { type: 'boolean', description: 'Operation success status' }, @@ -407,6 +419,7 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n channels: { type: 'number', description: 'Number of recording channels' }, source: { type: 'string', description: 'Recording source' }, mediaUrl: { type: 'string', description: 'URL to download recording' }, + file: { type: 'file', description: 'Downloaded recording media file' }, uri: { type: 'string', description: 'Resource URI' }, transcriptionText: { type: 'string', @@ -416,10 +429,16 @@ Return ONLY the date string in YYYY-MM-DD format - no explanations, no quotes, n type: 'string', description: 'Transcription status (completed, in-progress, failed)', }, + transcriptionPrice: { type: 'string', description: 'Cost of the transcription' }, + transcriptionPriceUnit: { type: 'string', description: 'Currency of the transcription price' }, calls: { type: 'array', description: 'Array of call objects (for list_calls operation)' }, - total: { type: 'number', description: 'Total number of calls returned' }, + total: { type: 'number', description: 'Number of calls returned on this page' }, page: { type: 'number', description: 'Current page number' }, pageSize: { type: 'number', description: 'Number of calls per page' }, + nextPageToken: { + type: 'string', + description: 'Page token for the next page of calls (null on the last page)', + }, error: { type: 'string', description: 'Error message if operation failed' }, accountSid: { type: 'string', description: 'Twilio Account SID from webhook' }, from: { type: 'string', description: "Caller's phone number (E.164 format)" }, diff --git a/apps/sim/blocks/blocks/typeform.test.ts b/apps/sim/blocks/blocks/typeform.test.ts new file mode 100644 index 00000000000..53d642440a6 --- /dev/null +++ b/apps/sim/blocks/blocks/typeform.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it } from 'vitest' +import { TypeformV2Block } from '@/blocks/blocks/typeform' +import type { BlockToolParamsContext } from '@/blocks/types' +import { createFormTool } from '@/tools/typeform/create_form' +import { updateFormTool } from '@/tools/typeform/update_form' +import type { ToolConfig } from '@/tools/types' + +/** + * Assertions run against `{ ...inputs, ...mapper(inputs, context) }`, the shape both the canvas + * handler and the tool-call transform forward: a key the mapper leaves out keeps its raw value. + */ +describe('TypeformV2Block params mapper', () => { + const mapper = TypeformV2Block.tools.config?.params + if (!mapper) throw new Error('TypeformV2Block is missing its params mapper') + + const resolve = (inputs: Record, context?: BlockToolParamsContext) => ({ + ...inputs, + ...mapper(inputs, context), + }) + + const patchBody = (params: Record) => { + const tool: ToolConfig = updateFormTool + const body = tool.request.body + if (!body) throw new Error('Expected a body builder') + return body(params) + } + + const createBody = (params: Record) => { + const tool: ToolConfig = createFormTool + const body = tool.request.body + if (!body) throw new Error('Expected a body builder') + return body(params) + } + + it('sends patch operations a model passed as an array on a tool call', () => { + const operations = [{ op: 'replace', path: '/title', value: 'Renamed' }] + const params = resolve( + { apiKey: 'k', formId: 'abc123', operations }, + { operation: 'typeform_update_form' } + ) + + expect(patchBody(params)).toEqual(operations) + }) + + it('sends fields and settings a model passed as structured values on a tool call', () => { + const fields = [{ type: 'short_text', title: 'Name?' }] + const settings = { is_public: false } + const params = resolve( + { apiKey: 'k', title: 'Survey', fields, settings }, + { operation: 'typeform_create_form' } + ) + + expect(createBody(params)).toMatchObject({ title: 'Survey', fields, settings }) + }) + + it('still parses JSON text typed on the canvas', () => { + const params = resolve({ + operation: 'typeform_update_form', + apiKey: 'k', + formId: 'abc123', + operations: '[{"op":"replace","path":"/settings/is_public","value":false}]', + }) + + expect(patchBody(params)).toEqual([ + { op: 'replace', path: '/settings/is_public', value: false }, + ]) + }) +}) diff --git a/apps/sim/blocks/blocks/typeform.ts b/apps/sim/blocks/blocks/typeform.ts index e112989f102..bd71fdc02b5 100644 --- a/apps/sim/blocks/blocks/typeform.ts +++ b/apps/sim/blocks/blocks/typeform.ts @@ -1,9 +1,20 @@ +import { getErrorMessage } from '@sim/utils/errors' import { TypeformIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' import { withSavedCredential } from '@/blocks/utils' import { getTrigger } from '@/triggers' +/** Parses a JSON block input typed as text; a value a model already sent as JSON passes through. */ +function parseJsonInput(value: unknown): unknown { + if (typeof value !== 'string') return value + try { + return JSON.parse(value) + } catch (error) { + throw new Error(`Invalid JSON input: ${getErrorMessage(error)}`) + } +} + export const TypeformBlock: BlockConfig = { type: 'typeform', hideFromToolbar: true, @@ -125,7 +136,7 @@ export const TypeformBlock: BlockConfig = { id: 'since', title: 'Since', type: 'short-input', - placeholder: 'Retrieve responses after this date (ISO format)', + placeholder: 'Retrieve responses on or after this date (ISO format)', condition: { field: 'operation', value: 'typeform_responses' }, wandConfig: { enabled: true, @@ -147,7 +158,7 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, id: 'until', title: 'Until', type: 'short-input', - placeholder: 'Retrieve responses before this date (ISO format)', + placeholder: 'Retrieve responses on or before this date (ISO format)', condition: { field: 'operation', value: 'typeform_responses' }, wandConfig: { enabled: true, @@ -176,6 +187,14 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, ], condition: { field: 'operation', value: 'typeform_responses' }, }, + { + id: 'responseType', + title: 'Response Types', + type: 'short-input', + placeholder: 'e.g., partial,completed (overrides Completed)', + mode: 'advanced', + condition: { field: 'operation', value: 'typeform_responses' }, + }, // File operation fields { id: 'responseId', @@ -183,6 +202,7 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, type: 'short-input', placeholder: 'Enter response ID (token)', condition: { field: 'operation', value: 'typeform_files' }, + required: true, }, { id: 'fieldId', @@ -190,6 +210,7 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, type: 'short-input', placeholder: 'Enter file upload field ID', condition: { field: 'operation', value: 'typeform_files' }, + required: true, }, { id: 'filename', @@ -197,6 +218,7 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, type: 'short-input', placeholder: 'Enter exact filename of the file', condition: { field: 'operation', value: 'typeform_files' }, + required: true, }, { id: 'inline', @@ -249,6 +271,11 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, options: [ { label: 'Form', id: 'form' }, { label: 'Quiz', id: 'quiz' }, + { label: 'Classification', id: 'classification' }, + { label: 'Score', id: 'score' }, + { label: 'Branching', id: 'branching' }, + { label: 'Classification Branching', id: 'classification_branching' }, + { label: 'Score Branching', id: 'score_branching' }, ], condition: { field: 'operation', value: 'typeform_create_form' }, }, @@ -300,54 +327,39 @@ Current operations: {context} ### JSON PATCH OPERATIONS Each operation is an object with: -- "op": The operation type ("add", "remove", "replace", "move", "copy", "test") -- "path": JSON pointer to the target location (e.g., "/title", "/fields/0", "/settings/language") -- "value": The new value (required for "add", "replace", "copy", "test") -- "from": Source path (required for "move" and "copy") +- "op": The operation type (usually "replace") +- "path": One of the paths Typeform accepts (listed below) +- "value": The new value -### COMMON TYPEFORM PATHS -- /title - Form title -- /settings/language - Form language (e.g., "en", "es", "fr") -- /settings/is_public - Whether form is public (true/false) -- /settings/show_progress_bar - Show progress bar (true/false) -- /fields - Array of form fields -- /fields/- - Add to end of fields array -- /fields/0 - First field -- /welcome_screens - Array of welcome screens -- /thankyou_screens - Array of thank you screens -- /theme/href - Theme URL reference +### PATHS TYPEFORM ACCEPTS (no others are allowed) +- /title - Form title (string) +- /settings/is_public - Whether the form is public (true/false) +- /settings/meta - Sharing metadata object: { "title", "description", "allow_indexing", "image": { "href" } } +- /settings/google_analytics - Google Analytics tracking ID +- /settings/google_tag_manager - Google Tag Manager ID +- /settings/facebook_pixel - Facebook Pixel ID +- /settings/enrichment_in_renderer - Enrichment setting +- /settings/email_consent_notifications_config - Email consent notification settings +- /theme - Theme reference: { "href": "https://api.typeform.com/themes/{theme_id}" } +- /workspace - Workspace reference: { "href": "https://api.typeform.com/workspaces/{workspace_id}" } -### FIELD OBJECT STRUCTURE -{ - "type": "short_text" | "long_text" | "email" | "number" | "multiple_choice" | "yes_no" | "rating" | "date" | "dropdown" | "file_upload", - "title": "Question text", - "ref": "unique_reference_id", - "properties": { ... }, - "validations": { "required": true/false } -} +Fields, welcome screens, thank-you screens, and language cannot be changed with these operations. If the user asks for one of those, return only the operations for the paths above. ### EXAMPLES **Change form title:** [{"op": "replace", "path": "/title", "value": "My Updated Form"}] -**Add a new text field:** -[{"op": "add", "path": "/fields/-", "value": {"type": "short_text", "title": "What is your name?", "ref": "name_field", "validations": {"required": true}}}] - -**Add multiple choice field:** -[{"op": "add", "path": "/fields/-", "value": {"type": "multiple_choice", "title": "Select your favorite color", "ref": "color_field", "properties": {"choices": [{"label": "Red"}, {"label": "Blue"}, {"label": "Green"}]}}}] +**Make the form private:** +[{"op": "replace", "path": "/settings/is_public", "value": false}] -**Remove first field:** -[{"op": "remove", "path": "/fields/0"}] +**Update sharing metadata:** +[{"op": "replace", "path": "/settings/meta", "value": {"title": "Customer Feedback", "description": "Tell us how we did", "allow_indexing": false}}] -**Update form settings:** -[{"op": "replace", "path": "/settings/language", "value": "es"}, {"op": "replace", "path": "/settings/is_public", "value": false}] - -**Multiple operations:** +**Move the form to another workspace and apply a theme:** [ - {"op": "replace", "path": "/title", "value": "Customer Feedback Form"}, - {"op": "add", "path": "/fields/-", "value": {"type": "rating", "title": "Rate your experience", "ref": "rating_field", "properties": {"steps": 5}}}, - {"op": "replace", "path": "/settings/show_progress_bar", "value": true} + {"op": "replace", "path": "/workspace", "value": {"href": "https://api.typeform.com/workspaces/abc123"}}, + {"op": "replace", "path": "/theme", "value": {"href": "https://api.typeform.com/themes/xyz789"}} ] Do not include any explanations, markdown formatting, or other text outside the JSON array.`, @@ -402,17 +414,9 @@ Do not include any explanations, markdown formatting, or other text outside the ...rest } = params - let parsedFields: any | undefined - let parsedSettings: any | undefined - let parsedOperations: any | undefined - - try { - if (fields) parsedFields = JSON.parse(fields) - if (settings) parsedSettings = JSON.parse(settings) - if (operations) parsedOperations = JSON.parse(operations) - } catch (error: any) { - throw new Error(`Invalid JSON input: ${error.message}`) - } + const parsedFields = fields ? parseJsonInput(fields) : undefined + const parsedSettings = settings ? parseJsonInput(settings) : undefined + const parsedOperations = operations ? parseJsonInput(operations) : undefined const pageSize = listPageSize !== undefined ? listPageSize : params.pageSize @@ -422,9 +426,9 @@ Do not include any explanations, markdown formatting, or other text outside the ...rest, ...(pageSize && { pageSize }), ...(workspaceId && { workspaceId }), - ...(parsedFields && { fields: parsedFields }), - ...(parsedSettings && { settings: parsedSettings }), - ...(parsedOperations && { operations: parsedOperations }), + ...(parsedFields ? { fields: parsedFields } : {}), + ...(parsedSettings ? { settings: parsedSettings } : {}), + ...(parsedOperations ? { operations: parsedOperations } : {}), } }, }, @@ -440,6 +444,7 @@ Do not include any explanations, markdown formatting, or other text outside the since: { type: 'string', description: 'Start date filter' }, until: { type: 'string', description: 'End date filter' }, completed: { type: 'string', description: 'Completion status filter' }, + responseType: { type: 'string', description: 'Comma-separated response types to return' }, // File operation params responseId: { type: 'string', description: 'Response identifier' }, fieldId: { type: 'string', description: 'Field identifier' }, @@ -452,7 +457,7 @@ Do not include any explanations, markdown formatting, or other text outside the listPageSize: { type: 'number', description: 'Forms per page' }, // Create form operation params title: { type: 'string', description: 'Form title' }, - type: { type: 'string', description: 'Form type (form or quiz)' }, + type: { type: 'string', description: 'Form type (e.g., quiz, score, branching)' }, workspaceIdCreate: { type: 'string', description: 'Workspace ID for creation' }, fields: { type: 'json', description: 'Form fields array' }, settings: { type: 'json', description: 'Form settings object' }, diff --git a/apps/sim/blocks/blocks/vanta.ts b/apps/sim/blocks/blocks/vanta.ts index 5dd0e1616d7..30702ede8d8 100644 --- a/apps/sim/blocks/blocks/vanta.ts +++ b/apps/sim/blocks/blocks/vanta.ts @@ -1,7 +1,7 @@ import { VantaIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput } from '@/blocks/utils' +import { mapperOperation, normalizeFileInput, toolCallArg } from '@/blocks/utils' const LIST_OPERATIONS = [ 'list_frameworks', @@ -893,66 +893,78 @@ export const VantaBlock: BlockConfig = { ], config: { tool: (params) => `vanta_${params.operation}`, - params: (params) => { - const { operation, ...rest } = params + params: (params, context) => { + const operation = mapperOperation(params, context) const result: Record = {} if (LIST_OPERATIONS.includes(operation)) { result.pageSize = - rest.pageSize !== undefined && rest.pageSize !== '' && rest.pageSize !== null - ? Number(rest.pageSize) + params.pageSize !== undefined && params.pageSize !== '' && params.pageSize !== null + ? Number(params.pageSize) : undefined - result.pageCursor = optionalString(rest.pageCursor) + result.pageCursor = optionalString(params.pageCursor) } switch (operation) { case 'list_test_entities': - result.entityStatus = dropdownFilter(rest.entityStatus) + result.entityStatus = dropdownFilter(params.entityStatus) break case 'upload_document_file': { - const normalizedFile = normalizeFileInput(rest.file, { single: true }) + const normalizedFile = normalizeFileInput(params.file, { single: true }) if (normalizedFile) result.file = normalizedFile - result.fileName = optionalString(rest.uploadFileName) - result.description = optionalString(rest.uploadDescription) - result.effectiveAtDate = optionalString(rest.effectiveAtDate) + result.fileName = + optionalString(params.uploadFileName) ?? + optionalString(toolCallArg(context, params.fileName)) + result.description = + optionalString(params.uploadDescription) ?? + optionalString(toolCallArg(context, params.description)) + result.effectiveAtDate = optionalString(params.effectiveAtDate) break } case 'list_documents': - result.statusMatchesAny = optionalString(rest.documentStatusFilter) + result.statusMatchesAny = + optionalString(params.documentStatusFilter) ?? + optionalString(toolCallArg(context, params.statusMatchesAny)) break case 'list_tests': - result.statusFilter = dropdownFilter(rest.statusFilter) - result.categoryFilter = dropdownFilter(rest.categoryFilter) - result.isInRollout = triStateToBoolean(rest.isInRollout) + result.statusFilter = dropdownFilter(params.statusFilter) + result.categoryFilter = dropdownFilter(params.categoryFilter) + result.isInRollout = triStateToBoolean(params.isInRollout) break case 'list_people': - result.employmentStatus = dropdownFilter(rest.employmentStatus) + result.employmentStatus = dropdownFilter(params.employmentStatus) break case 'list_vendors': - result.name = optionalString(rest.vendorName) - result.statusMatchesAny = optionalString(rest.vendorStatusFilter) + result.name = + optionalString(params.vendorName) ?? optionalString(toolCallArg(context, params.name)) + result.statusMatchesAny = + optionalString(params.vendorStatusFilter) ?? + optionalString(toolCallArg(context, params.statusMatchesAny)) break case 'list_vulnerabilities': - result.q = optionalString(rest.searchQuery) - result.severity = dropdownFilter(rest.severity) - result.isFixAvailable = triStateToBoolean(rest.isFixAvailable) - result.isDeactivated = triStateToBoolean(rest.isDeactivated) + result.q = + optionalString(params.searchQuery) ?? optionalString(toolCallArg(context, params.q)) + result.severity = dropdownFilter(params.severity) + result.isFixAvailable = triStateToBoolean(params.isFixAvailable) + result.isDeactivated = triStateToBoolean(params.isDeactivated) result.includeVulnerabilitiesWithoutSlas = triStateToBoolean( - rest.includeVulnerabilitiesWithoutSlas + params.includeVulnerabilitiesWithoutSlas ) break case 'list_vulnerability_remediations': - result.severity = dropdownFilter(rest.severity) - result.isRemediatedOnTime = triStateToBoolean(rest.isRemediatedOnTime) + result.severity = dropdownFilter(params.severity) + result.isRemediatedOnTime = triStateToBoolean(params.isRemediatedOnTime) break case 'list_vulnerable_assets': - result.q = optionalString(rest.searchQuery) - result.assetType = dropdownFilter(rest.assetType) + result.q = + optionalString(params.searchQuery) ?? optionalString(toolCallArg(context, params.q)) + result.assetType = dropdownFilter(params.assetType) break case 'list_risk_scenarios': - result.type = dropdownFilter(rest.riskType) - result.includeIgnored = triStateToBoolean(rest.includeIgnored) - result.orderBy = dropdownFilter(rest.orderBy) + result.type = + dropdownFilter(params.riskType) ?? optionalString(toolCallArg(context, params.type)) + result.includeIgnored = triStateToBoolean(params.includeIgnored) + result.orderBy = dropdownFilter(params.orderBy) break default: break diff --git a/apps/sim/blocks/blocks/vercel.test.ts b/apps/sim/blocks/blocks/vercel.test.ts new file mode 100644 index 00000000000..9652da687eb --- /dev/null +++ b/apps/sim/blocks/blocks/vercel.test.ts @@ -0,0 +1,52 @@ +/** + * An Agent tool call runs the block mapper over `{ ...storedRowParams, ...modelArgs }` with the + * operation only in `context`; the tool then receives `{ ...merged, ...mapped }`. + */ +import { describe, expect, it } from 'vitest' +import { VercelBlock } from '@/blocks/blocks/vercel' + +function toolCallParams(args: Record, operation: string) { + const mapped = VercelBlock.tools.config?.params?.(args, { operation }) ?? {} + return { ...args, ...mapped } +} + +describe('Vercel on an Agent tool call', () => { + it('keeps the domain the model supplied', () => { + expect( + toolCallParams({ apiKey: 'tok', domain: 'example.com' }, 'list_dns_records') + ).toMatchObject({ domain: 'example.com' }) + }) + + it('sends Create Check blocking as a boolean', () => { + expect( + toolCallParams( + { apiKey: 'tok', deploymentId: 'dpl_1', name: 'e2e', blocking: 'true' }, + 'create_check' + ) + ).toMatchObject({ blocking: true }) + expect( + toolCallParams({ apiKey: 'tok', deploymentId: 'dpl_1', name: 'e2e' }, 'create_check') + ).toMatchObject({ blocking: false }) + }) + + it('keeps the args the model supplied under the tool param names', () => { + expect( + toolCallParams( + { apiKey: 'tok', deploymentId: 'dpl_1', name: 'e2e', blocking: true }, + 'create_check' + ) + ).toMatchObject({ deploymentId: 'dpl_1', name: 'e2e', blocking: true }) + expect( + toolCallParams({ apiKey: 'tok', recordId: 'rec_1', name: 'api' }, 'update_dns_record') + ).toMatchObject({ recordId: 'rec_1', name: 'api' }) + }) + + it('maps block field names on a tool row written by Copilot or the API', () => { + expect( + toolCallParams( + { apiKey: 'tok', recordId: 'rec_1', updateRecordName: 'www', updateSrvPort: '5060' }, + 'update_dns_record' + ) + ).toMatchObject({ recordId: 'rec_1', name: 'www', srvPort: 5060 }) + }) +}) diff --git a/apps/sim/blocks/blocks/vercel.ts b/apps/sim/blocks/blocks/vercel.ts index 964b3e1fd6e..3081a91bb16 100644 --- a/apps/sim/blocks/blocks/vercel.ts +++ b/apps/sim/blocks/blocks/vercel.ts @@ -1,7 +1,12 @@ import { VercelIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { + isToolCall, + mapperOperation, + parseOptionalBooleanInput, + withSavedCredential, +} from '@/blocks/utils' import { getTrigger } from '@/triggers' /** @@ -1634,10 +1639,9 @@ export const VercelBlock: BlockConfig = { ], config: { tool: (params) => `vercel_${params.operation}`, - params: (params) => { + params: (params, context) => { const { apiKey, - operation, deploymentsProjectId, deploymentsApp, deploymentsSince, @@ -1734,11 +1738,20 @@ export const VercelBlock: BlockConfig = { const base = { ...rest, apiKey, ...(teamSlug ? { slug: teamSlug } : {}) } - switch (operation) { + /** + * On a tool call the model sends the tool's own param name, so it fills a blank dedicated + * field. The canvas keeps the dedicated field as is. + */ + const orModelArg = (dedicated: unknown, modelArg: unknown) => + isToolCall(context) && (dedicated === undefined || dedicated === null || dedicated === '') + ? modelArg + : dedicated + + switch (mapperOperation(params, context)) { case 'list_deployments': return { ...base, - projectId: deploymentsProjectId || undefined, + projectId: orModelArg(deploymentsProjectId, rest.projectId) || undefined, ...(deploymentsApp ? { app: deploymentsApp } : {}), ...(deploymentsSince ? { since: Number(deploymentsSince) } : {}), ...(deploymentsUntil ? { until: Number(deploymentsUntil) } : {}), @@ -1758,21 +1771,21 @@ export const VercelBlock: BlockConfig = { case 'create_deployment': return { ...base, - deploymentId: redeployId || undefined, - target: deployTarget || undefined, + deploymentId: orModelArg(redeployId, rest.deploymentId) || undefined, + target: orModelArg(deployTarget, rest.target) || undefined, ...(deploymentGitSource ? { gitSource: deploymentGitSource } : {}), ...(deploymentForceNew ? { forceNew: deploymentForceNew } : {}), } case 'create_project': - return { ...base, name: projectName } + return { ...base, name: orModelArg(projectName, rest.name) } case 'update_project': - return { ...base, name: updateProjectName || undefined } + return { ...base, name: orModelArg(updateProjectName, rest.name) || undefined } case 'list_projects': return { ...base, ...(projectsFrom ? { from: projectsFrom } : {}) } case 'add_project_domain': return { ...base, - domain: domainName, + domain: orModelArg(domainName, rest.domain), ...(updateDomainRedirect ? { redirect: updateDomainRedirect } : {}), ...(updateDomainRedirectStatusCode ? { redirectStatusCode: Number(updateDomainRedirectStatusCode) } @@ -1781,11 +1794,11 @@ export const VercelBlock: BlockConfig = { } case 'remove_project_domain': case 'verify_project_domain': - return { ...base, domain: domainName } + return { ...base, domain: orModelArg(domainName, rest.domain) } case 'update_project_domain': return { ...base, - domain: domainName, + domain: orModelArg(domainName, rest.domain), ...(updateDomainRedirect ? { redirect: updateDomainRedirect } : {}), ...(updateDomainRedirectStatusCode ? { redirectStatusCode: Number(updateDomainRedirectStatusCode) } @@ -1795,13 +1808,13 @@ export const VercelBlock: BlockConfig = { case 'get_domain': case 'delete_domain': case 'get_domain_config': - return { ...base, domain: domainName } + return { ...base, domain: orModelArg(domainName, rest.domain) } case 'add_domain': - return { ...base, name: domainName } + return { ...base, name: orModelArg(domainName, rest.name) } case 'list_dns_records': return { ...base, - domain: domainName, + domain: orModelArg(domainName, rest.domain), ...(dnsRecordsLimit ? { limit: Number(dnsRecordsLimit) } : {}), } case 'list_project_domains': @@ -1812,7 +1825,7 @@ export const VercelBlock: BlockConfig = { case 'create_dns_record': return { ...base, - domain: domainName, + domain: orModelArg(domainName, rest.domain), recordName, recordType, ...(recordValue ? { value: recordValue } : {}), @@ -1833,12 +1846,12 @@ export const VercelBlock: BlockConfig = { ...(recordComment ? { comment: recordComment } : {}), } case 'delete_dns_record': - return { ...base, domain: domainName, recordId } + return { ...base, domain: orModelArg(domainName, rest.domain), recordId } case 'update_dns_record': return { ...base, recordId, - name: updateRecordName || undefined, + name: orModelArg(updateRecordName, rest.name) || undefined, ...(updateRecordType ? { type: updateRecordType } : {}), ...(updateRecordValue ? { value: updateRecordValue } : {}), ...(updateRecordTtl ? { ttl: updateRecordTtl } : {}), @@ -1871,10 +1884,10 @@ export const VercelBlock: BlockConfig = { case 'create_env_var': return { ...base, - key: envKey, - value: envValue, - target: envTarget, - type: envType, + key: orModelArg(envKey, rest.key), + value: orModelArg(envValue, rest.value), + target: orModelArg(envTarget, rest.target), + type: orModelArg(envType, rest.type), ...(envGitBranch ? { gitBranch: envGitBranch } : {}), ...(envComment ? { comment: envComment } : {}), } @@ -1883,7 +1896,7 @@ export const VercelBlock: BlockConfig = { ...base, ...(envKey ? { key: envKey } : {}), ...(envValue ? { value: envValue } : {}), - target: envTarget || undefined, + target: orModelArg(envTarget, rest.target) || undefined, ...(envType ? { type: envType } : {}), ...(envGitBranch ? { gitBranch: envGitBranch } : {}), ...(envComment ? { comment: envComment } : {}), @@ -1894,8 +1907,8 @@ export const VercelBlock: BlockConfig = { case 'create_alias': return { ...base, - deploymentId: aliasDeploymentId, - alias: aliasName, + deploymentId: orModelArg(aliasDeploymentId, rest.deploymentId), + alias: orModelArg(aliasName, rest.alias), ...(aliasRedirect ? { redirect: aliasRedirect } : {}), } case 'get_edge_config': @@ -1903,14 +1916,14 @@ export const VercelBlock: BlockConfig = { case 'delete_edge_config': return { ...base, edgeConfigId } case 'create_edge_config': - return { ...base, slug: edgeConfigSlug } + return { ...base, slug: orModelArg(edgeConfigSlug, rest.slug) } case 'update_edge_config_items': - return { ...base, edgeConfigId, items: edgeConfigItems } + return { ...base, edgeConfigId, items: orModelArg(edgeConfigItems, rest.items) } case 'create_webhook': return { ...base, - url: webhookUrl, - events: webhookEvents, + url: orModelArg(webhookUrl, rest.url), + events: orModelArg(webhookEvents, rest.events), ...(webhookProjectIds ? { projectIds: webhookProjectIds } : {}), } case 'delete_webhook': @@ -1919,31 +1932,38 @@ export const VercelBlock: BlockConfig = { case 'create_check': return { ...base, - deploymentId: checkDeploymentId, - name: checkName, - blocking: checkBlocking === 'true', + deploymentId: orModelArg(checkDeploymentId, rest.deploymentId), + name: orModelArg(checkName, rest.name), + blocking: + isToolCall(context) && !checkBlocking + ? (parseOptionalBooleanInput(rest.blocking) ?? false) + : checkBlocking === 'true', ...(checkPath ? { path: checkPath } : {}), ...(checkDetailsUrl ? { detailsUrl: checkDetailsUrl } : {}), ...(checkExternalId ? { externalId: checkExternalId } : {}), ...(checkRerequestable ? { rerequestable: checkRerequestable === 'true' } : {}), } case 'get_check': - return { ...base, deploymentId: checkDeploymentId, checkId } + return { + ...base, + deploymentId: orModelArg(checkDeploymentId, rest.deploymentId), + checkId, + } case 'rerequest_check': return { ...base, - deploymentId: checkDeploymentId, + deploymentId: orModelArg(checkDeploymentId, rest.deploymentId), checkId, ...(checkAutoUpdate ? { autoUpdate: checkAutoUpdate === 'true' } : {}), } case 'list_checks': - return { ...base, deploymentId: checkDeploymentId } + return { ...base, deploymentId: orModelArg(checkDeploymentId, rest.deploymentId) } case 'update_check': return { ...base, - deploymentId: checkDeploymentId, + deploymentId: orModelArg(checkDeploymentId, rest.deploymentId), checkId, - name: checkName || undefined, + name: orModelArg(checkName, rest.name) || undefined, ...(checkStatus ? { status: checkStatus } : {}), ...(checkConclusion ? { conclusion: checkConclusion } : {}), ...(checkPath ? { path: checkPath } : {}), @@ -1952,16 +1972,16 @@ export const VercelBlock: BlockConfig = { ...(checkOutput ? { output: checkOutput } : {}), } case 'get_team': - return { ...base, teamId: teamIdParam } + return { ...base, teamId: orModelArg(teamIdParam, rest.teamId) } case 'list_team_members': return { ...base, - teamId: teamIdParam, + teamId: orModelArg(teamIdParam, rest.teamId), ...(memberRole ? { role: memberRole } : {}), ...(teamMembersLimit ? { limit: Number(teamMembersLimit) } : {}), ...(teamMembersSince ? { since: Number(teamMembersSince) } : {}), ...(teamMembersUntil ? { until: Number(teamMembersUntil) } : {}), - search: teamMembersSearch || undefined, + search: orModelArg(teamMembersSearch, rest.search) || undefined, } case 'list_teams': return { diff --git a/apps/sim/blocks/blocks/wealthbox.ts b/apps/sim/blocks/blocks/wealthbox.ts index 40d50c07b2e..c849500d0d4 100644 --- a/apps/sim/blocks/blocks/wealthbox.ts +++ b/apps/sim/blocks/blocks/wealthbox.ts @@ -2,6 +2,7 @@ import { WealthboxIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { isToolCall, mapperOperation } from '@/blocks/utils' const CONTACT_FIELD = ['contactId', 'manualContactId'] as const @@ -207,8 +208,9 @@ Return ONLY the date/time string - no explanations, no quotes, no extra text.`, throw new Error(`Unknown operation: ${params.operation}`) } }, - params: (params) => { - const { oauthCredential, operation, contactId, taskId, ...rest } = params + params: (params, context) => { + const operation = mapperOperation(params, context) + const { oauthCredential, contactId, taskId, ...rest } = params // contactId is the canonical param for both basic (file-selector) and advanced (manualContactId) modes const effectiveContactId = contactId ? String(contactId).trim() : '' @@ -226,7 +228,7 @@ Return ONLY the date/time string - no explanations, no quotes, no extra text.`, } } if (operation === 'read_contact') { - if (!effectiveContactId) { + if (!effectiveContactId && !isToolCall(context)) { throw new Error('Contact ID is required for contact operations') } return { @@ -236,6 +238,7 @@ Return ONLY the date/time string - no explanations, no quotes, no extra text.`, } if (operation === 'read_task') { if (!taskId?.trim()) { + if (isToolCall(context)) return baseParams throw new Error('Task ID is required for task operations') } return { @@ -245,6 +248,7 @@ Return ONLY the date/time string - no explanations, no quotes, no extra text.`, } if (operation === 'write_task' || operation === 'write_note') { if (!contactId?.trim()) { + if (isToolCall(context)) return baseParams throw new Error('Contact ID is required for this operation') } return { diff --git a/apps/sim/blocks/blocks/webflow.test.ts b/apps/sim/blocks/blocks/webflow.test.ts new file mode 100644 index 00000000000..6a80557ea11 --- /dev/null +++ b/apps/sim/blocks/blocks/webflow.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, it } from 'vitest' +import { WebflowBlock } from '@/blocks/blocks/webflow' +import type { BlockToolParamsContext } from '@/blocks/types' + +/** The block's `tools.config.params` mapper; `context` is set on a tool call, absent on the canvas. */ +const buildParams = ( + inputs: Record, + context?: BlockToolParamsContext +): Record => WebflowBlock.tools.config?.params?.(inputs, context) ?? {} + +/** + * On an agent call the stored row and model args merge under the tool's param names, the operation + * reaches the mapper only on `context`, and the result is spread over the merged params. + */ +describe('WebflowBlock agent tool calls', () => { + const agentCall = ( + operation: string, + args: Record + ): Record => ({ + ...args, + ...buildParams(args, { operation }), + }) + + it('trims a model itemId with surrounding whitespace on update', () => { + const mapped = agentCall('update', { + oauthCredential: 'cred-1', + collectionId: '580e63fc8c9a982ac9b8b745', + itemId: ' 580e64008c9a982ac9b8b754 ', + fieldData: { name: 'Renamed' }, + }) + expect(mapped).toMatchObject({ + credential: 'cred-1', + itemId: '580e64008c9a982ac9b8b754', + fieldData: { name: 'Renamed' }, + }) + }) + + it('parses a JSON string fieldData on create', () => { + const mapped = agentCall('create', { + oauthCredential: 'cred-1', + collectionId: '580e63fc8c9a982ac9b8b745', + fieldData: '{"name":"Post","slug":"post"}', + }) + expect(mapped.fieldData).toEqual({ name: 'Post', slug: 'post' }) + }) +}) diff --git a/apps/sim/blocks/blocks/webflow.ts b/apps/sim/blocks/blocks/webflow.ts index 0c41458ee63..b74f04e014b 100644 --- a/apps/sim/blocks/blocks/webflow.ts +++ b/apps/sim/blocks/blocks/webflow.ts @@ -1,7 +1,9 @@ +import { getErrorMessage } from '@sim/utils/errors' import { WebflowIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation } from '@/blocks/utils' import { getTrigger } from '@/triggers' /** CMS collection, whichever mode the card is in. */ @@ -214,7 +216,8 @@ export const WebflowBlock: BlockConfig = { throw new Error(`Invalid Webflow operation: ${params.operation}`) } }, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { oauthCredential, fieldData, @@ -223,14 +226,16 @@ export const WebflowBlock: BlockConfig = { itemId, // Canonical param from itemSelector (basic) or manualItemId (advanced) ...rest } = params - let parsedFieldData: any | undefined + let parsedFieldData: unknown try { - if (fieldData && (params.operation === 'create' || params.operation === 'update')) { - parsedFieldData = JSON.parse(fieldData) + if (fieldData && (operation === 'create' || operation === 'update')) { + parsedFieldData = typeof fieldData === 'string' ? JSON.parse(fieldData) : fieldData } - } catch (error: any) { - throw new Error(`Invalid JSON input for ${params.operation} operation: ${error.message}`) + } catch (error) { + throw new Error( + `Invalid JSON input for ${operation} operation: ${getErrorMessage(error)}` + ) } const effectiveSiteId = siteId ? String(siteId).trim() : '' @@ -244,7 +249,7 @@ export const WebflowBlock: BlockConfig = { ...rest, } - switch (params.operation) { + switch (operation) { case 'create': case 'update': return { @@ -317,7 +322,7 @@ export const WebflowBlockMeta = { icon: WebflowIcon, title: 'Webflow CMS publisher', prompt: - 'Create a workflow that reads a draft articles table, generates an SEO-optimized post, publishes it as a Webflow CMS item, and writes the live URL back to the row.', + 'Create a workflow that reads a draft articles table, generates an SEO-optimized post, creates it as a Webflow CMS item, and writes the new item ID and slug back to the row.', modules: ['tables', 'agent', 'workflows'], category: 'marketing', tags: ['marketing', 'content'], @@ -378,14 +383,14 @@ export const WebflowBlockMeta = { description: 'Create a new item in a Webflow CMS collection from supplied or generated field data.', content: - '# Publish a Webflow CMS Item\n\nTurn structured content into a live Webflow CMS collection item.\n\n## Steps\n1. Identify the target site and collection. If unknown, list collections to confirm the collection ID and its field schema.\n2. Map the incoming content to the collection fields, including required fields like name and slug. Generate a URL-safe slug if one is not provided.\n3. Call the create-item operation with the assembled fieldData JSON.\n4. Confirm the new item ID and slug returned by the API.\n\n## Output\nReport the created item ID, slug, and the live or staged URL. If a required field was missing, name it explicitly rather than guessing a value.', + '# Publish a Webflow CMS Item\n\nTurn structured content into a new Webflow CMS collection item. Webflow creates it as a Draft.\n\n## Steps\n1. Identify the target site and collection ID. If unknown, ask for them, and list a few existing items in the collection to learn its field names.\n2. Map the incoming content to the collection fields, including required fields like name and slug. Generate a URL-safe slug if one is not provided.\n3. Call the create-item operation with the assembled fieldData JSON.\n4. Confirm the new item ID and slug returned by the API.\n\n## Output\nReport the created item ID and slug, and note that the item has Draft status: it will not go live on the next site publish until someone marks it as not a draft in Webflow. If a required field was missing, name it explicitly rather than guessing a value.', }, { name: 'update-cms-item', description: 'Find a Webflow CMS item and update specific fields without disturbing the rest.', content: - '# Update a Webflow CMS Item\n\nApply targeted edits to an existing collection item.\n\n## Steps\n1. Resolve the item by ID, or list items in the collection and match on slug or name.\n2. Get the current item so existing field values are known.\n3. Build fieldData containing only the fields that change, merged onto the current values so untouched fields are preserved.\n4. Call the update-item operation and confirm the change took effect.\n\n## Output\nList exactly which fields changed and their new values. Note the item ID and whether the change is live or staged.', + '# Update a Webflow CMS Item\n\nApply targeted edits to an existing collection item.\n\n## Steps\n1. Resolve the item by ID, or list items in the collection and match on slug or name.\n2. Get the current item so existing field values are known.\n3. Build fieldData containing only the fields that change, merged onto the current values so untouched fields are preserved.\n4. Call the update-item operation and confirm the change took effect.\n\n## Output\nList exactly which fields changed and their new values. Note the item ID. The change is not live until the site is published, and a draft item stays unpublished even then.', }, { name: 'audit-collection-content', diff --git a/apps/sim/blocks/blocks/whatsapp.ts b/apps/sim/blocks/blocks/whatsapp.ts index d675ccfaaaa..45dcd13434d 100644 --- a/apps/sim/blocks/blocks/whatsapp.ts +++ b/apps/sim/blocks/blocks/whatsapp.ts @@ -1,7 +1,12 @@ import { WhatsAppIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput, withSavedCredential } from '@/blocks/utils' +import { + mapperOperation, + normalizeFileInput, + toolCallArg, + withSavedCredential, +} from '@/blocks/utils' import { getTrigger } from '@/triggers' /** Yes/No dropdowns serialize as `'true'`/`'false'` strings; the tools expect booleans. */ @@ -526,7 +531,8 @@ Return ONLY the valid JSON array - no explanations, no extra text.`, ], config: { tool: (params) => `whatsapp_${params.operation || 'send_message'}`, - params: (params) => { + params: (params, context) => { + const operation = mapperOperation(params, context) const { interactiveType, file: uploadedFile, @@ -543,7 +549,9 @@ Return ONLY the valid JSON array - no explanations, no extra text.`, previewUrl: toOptionalBoolean(params.previewUrl), showTypingIndicator: toOptionalBoolean(params.showTypingIndicator), ...(file ? { file } : {}), - ...(params.operation === 'get_media' ? { mediaId: downloadMediaId } : {}), + ...(operation === 'get_media' + ? { mediaId: downloadMediaId || toolCallArg(context, params.mediaId) } + : {}), } }, }, diff --git a/apps/sim/blocks/blocks/wordpress.test.ts b/apps/sim/blocks/blocks/wordpress.test.ts new file mode 100644 index 00000000000..114dc04833b --- /dev/null +++ b/apps/sim/blocks/blocks/wordpress.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from 'vitest' +import { WordPressBlock } from '@/blocks/blocks/wordpress' +import type { BlockToolParamsContext } from '@/blocks/types' + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = WordPressBlock.tools.config?.params + if (!mapper) throw new Error('WordPress block has no params mapper') + return mapper(params, context) +} + +/** The tool-call path: merged args, then the mapper result spread over them. */ +function toolCallParams(modelArgs: Record, operation: string) { + return { ...modelArgs, ...mapParams(modelArgs, { operation }) } +} + +describe('WordPress tool calls', () => { + it.each([ + [ + 'wordpress_create_comment', + { siteId: 's', postId: '42', content: 'Thanks!', parent: 17, authorName: 'Ann' }, + { postId: 42, content: 'Thanks!', parent: 17, authorName: 'Ann' }, + ], + [ + 'wordpress_create_category', + { siteId: 's', name: 'News', description: 'd', slug: 'news', parent: '3' }, + { name: 'News', description: 'd', slug: 'news', parent: 3 }, + ], + [ + 'wordpress_update_tag', + { siteId: 's', tagId: 9, name: 'Renamed', slug: 'renamed' }, + { tagId: 9, name: 'Renamed', slug: 'renamed' }, + ], + [ + 'wordpress_update_comment', + { siteId: 's', commentId: 5, content: 'edited', status: 'hold' }, + { commentId: 5, content: 'edited', status: 'hold' }, + ], + [ + 'wordpress_list_posts', + { siteId: 's', status: 'draft', author: '7' }, + { status: 'draft', author: 7 }, + ], + ['wordpress_search_content', { siteId: 's', query: 'q', subtype: 'page' }, { subtype: 'page' }], + ])( + '%s keeps the model args the block renames from its own fields', + (operation, args, expected) => { + expect(toolCallParams(args, operation)).toMatchObject(expected) + } + ) + + it('unwraps a stored single-file array for upload_media', () => { + const file = { name: 'a.png', key: 'k', url: 'u', size: 1, type: 'image/png' } + expect(toolCallParams({ siteId: 's', file: [file] }, 'wordpress_upload_media').file).toEqual( + file + ) + }) +}) + +describe('WordPress list comments order', () => { + it('drops an Order By the comments endpoint rejects and keeps a valid one', () => { + const base = { operation: 'wordpress_list_comments', siteId: 's' } + expect(mapParams({ ...base, orderBy: 'title' }).orderBy).toBeUndefined() + expect(mapParams({ ...base, orderBy: 'id' }).orderBy).toBe('id') + }) +}) diff --git a/apps/sim/blocks/blocks/wordpress.ts b/apps/sim/blocks/blocks/wordpress.ts index 294e323270a..22ba307d0bb 100644 --- a/apps/sim/blocks/blocks/wordpress.ts +++ b/apps/sim/blocks/blocks/wordpress.ts @@ -2,11 +2,37 @@ import { WordpressIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { normalizeFileInput } from '@/blocks/utils' +import { mapperOperation, normalizeFileInput, toolCallArg } from '@/blocks/utils' /** The media file to upload, whichever mode the user is in. */ const MEDIA_FILE_FIELD = ['fileUpload', 'file'] as const +const CREATE_STATUS_OPERATIONS = new Set([ + 'wordpress_create_post', + 'wordpress_create_page', +]) +const UPDATE_STATUS_OPERATIONS = new Set([ + 'wordpress_update_post', + 'wordpress_update_page', +]) + +/** `orderby` values the comments endpoint accepts; the shared Order By field also offers post-only ones. */ +const COMMENT_ORDER_BY_FIELDS = new Set([ + 'date', + 'date_gmt', + 'id', + 'include', + 'post', + 'parent', + 'type', +]) + +/** A numeric field from a block input or model arg, `undefined` when blank. */ +function optionalNumber(value: unknown): number | undefined { + if (value === undefined || value === null || value === '') return undefined + return typeof value === 'number' ? value : Number(value) +} + export const WordPressBlock: BlockConfig = { type: 'wordpress', name: 'WordPress', @@ -264,13 +290,30 @@ export const WordPressBlock: BlockConfig = { id: 'status', title: 'Status', type: 'dropdown', - options: [ + dependsOn: ['operation'], + /** + * Canvas and builder create contexts default to Publish. Every other context leads with + * "No change" so the existing or model-supplied status is kept, including Agent tool rows, + * whose options see the host Agent block's values (no `operation`), so create rows there + * keep the model's status or WordPress's own `draft` default. + * Without block values (Copilot validation, catalogs) every option is listed, "No change" last. + */ + options: (params) => [ + ...(params && !CREATE_STATUS_OPERATIONS.has(params.values.operation) + ? [{ label: 'No change', id: '' }] + : []), { label: 'Publish', id: 'publish' }, { label: 'Draft', id: 'draft' }, { label: 'Pending', id: 'pending' }, { label: 'Private', id: 'private' }, + ...(params ? [] : [{ label: 'No change', id: '' }]), ], - value: () => 'publish', + value: (params) => + CREATE_STATUS_OPERATIONS.has(params?.operation) + ? 'publish' + : UPDATE_STATUS_OPERATIONS.has(params?.operation) + ? '' + : undefined, condition: { field: 'operation', value: [ @@ -316,6 +359,29 @@ export const WordPressBlock: BlockConfig = { }, }, + { + id: 'date', + title: 'Publish Date', + type: 'short-input', + placeholder: 'e.g., 2026-12-01T09:00:00 (site timezone)', + mode: 'advanced', + condition: { + field: 'operation', + value: [ + 'wordpress_create_post', + 'wordpress_update_post', + 'wordpress_create_page', + 'wordpress_update_page', + ], + }, + wandConfig: { + enabled: true, + prompt: + 'Generate an ISO 8601 date-time without a timezone offset (e.g., 2026-12-01T09:00:00), interpreted in the site timezone. Return ONLY the timestamp string.', + generationType: 'timestamp', + }, + }, + { id: 'categories', title: 'Categories', @@ -569,12 +635,13 @@ export const WordPressBlock: BlockConfig = { title: 'Comment Status', type: 'dropdown', options: [ + { label: 'No change', id: '' }, { label: 'Approved', id: 'approved' }, { label: 'Hold', id: 'hold' }, { label: 'Spam', id: 'spam' }, { label: 'Trash', id: 'trash' }, ], - value: () => 'approved', + value: () => '', mode: 'advanced', condition: { field: 'operation', value: 'wordpress_update_comment' }, }, @@ -898,13 +965,13 @@ export const WordPressBlock: BlockConfig = { ], config: { tool: (params) => params.operation || 'wordpress_create_post', - params: (params) => { - const baseParams: Record = { + params: (params, context) => { + const baseParams: Record = { credential: params.oauthCredential, siteId: params.siteId, } - switch (params.operation) { + switch (mapperOperation(params, context) || 'wordpress_create_post') { case 'wordpress_create_post': return { ...baseParams, @@ -913,55 +980,50 @@ export const WordPressBlock: BlockConfig = { status: params.status, excerpt: params.excerpt, slug: params.slug, + date: params.date, categories: params.categories, tags: params.tags, - featuredMedia: - params.featuredMedia !== undefined && params.featuredMedia !== '' - ? Number(params.featuredMedia) - : undefined, + featuredMedia: optionalNumber(params.featuredMedia), } case 'wordpress_update_post': return { ...baseParams, - postId: Number(params.postId), + postId: optionalNumber(params.postId), title: params.title, content: params.content, status: params.status, excerpt: params.excerpt, slug: params.slug, + date: params.date, categories: params.categories, tags: params.tags, - featuredMedia: - params.featuredMedia !== undefined && params.featuredMedia !== '' - ? Number(params.featuredMedia) - : undefined, + featuredMedia: optionalNumber(params.featuredMedia), } case 'wordpress_delete_post': return { ...baseParams, - postId: Number(params.postId), + postId: optionalNumber(params.postId), force: params.force, } case 'wordpress_get_post': return { ...baseParams, - postId: Number(params.postId), + postId: optionalNumber(params.postId), } case 'wordpress_list_posts': return { ...baseParams, perPage: params.perPage ? Number(params.perPage) : undefined, page: params.page ? Number(params.page) : undefined, - status: params.listStatus || undefined, + status: params.listStatus || toolCallArg(context, params.status), search: params.search, orderBy: params.orderBy, order: params.order, categories: params.categories, tags: params.tags, author: - params.listAuthor !== undefined && params.listAuthor !== '' - ? Number(params.listAuthor) - : undefined, + optionalNumber(params.listAuthor) ?? + toolCallArg(context, optionalNumber(params.author)), } case 'wordpress_create_page': return { @@ -971,81 +1033,61 @@ export const WordPressBlock: BlockConfig = { status: params.status, excerpt: params.excerpt, slug: params.slug, - parent: - params.parent !== undefined && params.parent !== '' - ? Number(params.parent) - : undefined, - menuOrder: - params.menuOrder !== undefined && params.menuOrder !== '' - ? Number(params.menuOrder) - : undefined, - featuredMedia: - params.featuredMedia !== undefined && params.featuredMedia !== '' - ? Number(params.featuredMedia) - : undefined, + date: params.date, + parent: optionalNumber(params.parent), + menuOrder: optionalNumber(params.menuOrder), + featuredMedia: optionalNumber(params.featuredMedia), } case 'wordpress_update_page': return { ...baseParams, - pageId: Number(params.pageId), + pageId: optionalNumber(params.pageId), title: params.title, content: params.content, status: params.status, excerpt: params.excerpt, slug: params.slug, - parent: - params.parent !== undefined && params.parent !== '' - ? Number(params.parent) - : undefined, - menuOrder: - params.menuOrder !== undefined && params.menuOrder !== '' - ? Number(params.menuOrder) - : undefined, - featuredMedia: - params.featuredMedia !== undefined && params.featuredMedia !== '' - ? Number(params.featuredMedia) - : undefined, + date: params.date, + parent: optionalNumber(params.parent), + menuOrder: optionalNumber(params.menuOrder), + featuredMedia: optionalNumber(params.featuredMedia), } case 'wordpress_delete_page': return { ...baseParams, - pageId: Number(params.pageId), + pageId: optionalNumber(params.pageId), force: params.force, } case 'wordpress_get_page': return { ...baseParams, - pageId: Number(params.pageId), + pageId: optionalNumber(params.pageId), } case 'wordpress_list_pages': return { ...baseParams, perPage: params.perPage ? Number(params.perPage) : undefined, page: params.page ? Number(params.page) : undefined, - status: params.listStatus || undefined, + status: params.listStatus || toolCallArg(context, params.status), search: params.search, orderBy: params.orderBy, order: params.order, - parent: - params.parent !== undefined && params.parent !== '' - ? Number(params.parent) - : undefined, + parent: optionalNumber(params.parent), } case 'wordpress_upload_media': - // file is the canonical param for both basic (fileUpload) and advanced modes return { ...baseParams, file: normalizeFileInput(params.file, { single: true }), filename: params.filename, - title: params.mediaTitle, + title: params.mediaTitle ?? toolCallArg(context, params.title), caption: params.caption, altText: params.altText, - description: params.mediaDescription || undefined, + description: params.mediaDescription || toolCallArg(context, params.description), } case 'wordpress_get_media': return { ...baseParams, - mediaId: Number(params.mediaId), + mediaId: optionalNumber(params.mediaId), } case 'wordpress_list_media': return { @@ -1060,54 +1102,56 @@ export const WordPressBlock: BlockConfig = { case 'wordpress_delete_media': return { ...baseParams, - mediaId: Number(params.mediaId), + mediaId: optionalNumber(params.mediaId), } case 'wordpress_create_comment': return { ...baseParams, - postId: Number(params.commentPostId), - content: params.commentContent, + postId: + optionalNumber(params.commentPostId) ?? + toolCallArg(context, optionalNumber(params.postId)), + content: params.commentContent ?? toolCallArg(context, params.content), parent: - params.commentParent !== undefined && params.commentParent !== '' - ? Number(params.commentParent) - : undefined, - authorName: params.commentAuthorName || undefined, - authorEmail: params.commentAuthorEmail || undefined, - authorUrl: params.commentAuthorUrl || undefined, + optionalNumber(params.commentParent) ?? + toolCallArg(context, optionalNumber(params.parent)), + authorName: params.commentAuthorName || toolCallArg(context, params.authorName), + authorEmail: params.commentAuthorEmail || toolCallArg(context, params.authorEmail), + authorUrl: params.commentAuthorUrl || toolCallArg(context, params.authorUrl), } case 'wordpress_list_comments': return { ...baseParams, perPage: params.perPage ? Number(params.perPage) : undefined, page: params.page ? Number(params.page) : undefined, - postId: params.commentPostId ? Number(params.commentPostId) : undefined, + postId: + optionalNumber(params.commentPostId) ?? + toolCallArg(context, optionalNumber(params.postId)), search: params.search, - orderBy: params.orderBy, + orderBy: COMMENT_ORDER_BY_FIELDS.has(params.orderBy) ? params.orderBy : undefined, order: params.order, } case 'wordpress_update_comment': return { ...baseParams, - commentId: Number(params.commentId), - content: params.commentContent, - status: params.commentStatus, + commentId: optionalNumber(params.commentId), + content: params.commentContent ?? toolCallArg(context, params.content), + status: params.commentStatus || toolCallArg(context, params.status), } case 'wordpress_delete_comment': return { ...baseParams, - commentId: Number(params.commentId), + commentId: optionalNumber(params.commentId), force: params.force, } case 'wordpress_create_category': return { ...baseParams, - name: params.categoryName, - description: params.categoryDescription, + name: params.categoryName ?? toolCallArg(context, params.name), + description: params.categoryDescription ?? toolCallArg(context, params.description), parent: - params.categoryParent !== undefined && params.categoryParent !== '' - ? Number(params.categoryParent) - : undefined, - slug: params.categorySlug, + optionalNumber(params.categoryParent) ?? + toolCallArg(context, optionalNumber(params.parent)), + slug: params.categorySlug ?? toolCallArg(context, params.slug), } case 'wordpress_list_categories': return { @@ -1120,31 +1164,30 @@ export const WordPressBlock: BlockConfig = { case 'wordpress_get_category': return { ...baseParams, - categoryId: Number(params.categoryId), + categoryId: optionalNumber(params.categoryId), } case 'wordpress_update_category': return { ...baseParams, - categoryId: Number(params.categoryId), - name: params.categoryName, - description: params.categoryDescription, + categoryId: optionalNumber(params.categoryId), + name: params.categoryName ?? toolCallArg(context, params.name), + description: params.categoryDescription ?? toolCallArg(context, params.description), parent: - params.categoryParent !== undefined && params.categoryParent !== '' - ? Number(params.categoryParent) - : undefined, - slug: params.categorySlug, + optionalNumber(params.categoryParent) ?? + toolCallArg(context, optionalNumber(params.parent)), + slug: params.categorySlug ?? toolCallArg(context, params.slug), } case 'wordpress_delete_category': return { ...baseParams, - categoryId: Number(params.categoryId), + categoryId: optionalNumber(params.categoryId), } case 'wordpress_create_tag': return { ...baseParams, - name: params.tagName, - description: params.tagDescription, - slug: params.tagSlug, + name: params.tagName ?? toolCallArg(context, params.name), + description: params.tagDescription ?? toolCallArg(context, params.description), + slug: params.tagSlug ?? toolCallArg(context, params.slug), } case 'wordpress_list_tags': return { @@ -1157,20 +1200,20 @@ export const WordPressBlock: BlockConfig = { case 'wordpress_get_tag': return { ...baseParams, - tagId: Number(params.tagId), + tagId: optionalNumber(params.tagId), } case 'wordpress_update_tag': return { ...baseParams, - tagId: Number(params.tagId), - name: params.tagName, - description: params.tagDescription, - slug: params.tagSlug, + tagId: optionalNumber(params.tagId), + name: params.tagName ?? toolCallArg(context, params.name), + description: params.tagDescription ?? toolCallArg(context, params.description), + slug: params.tagSlug ?? toolCallArg(context, params.slug), } case 'wordpress_delete_tag': return { ...baseParams, - tagId: Number(params.tagId), + tagId: optionalNumber(params.tagId), } case 'wordpress_get_current_user': return baseParams @@ -1186,7 +1229,7 @@ export const WordPressBlock: BlockConfig = { case 'wordpress_get_user': return { ...baseParams, - userId: Number(params.userId), + userId: optionalNumber(params.userId), } case 'wordpress_search_content': return { @@ -1194,7 +1237,7 @@ export const WordPressBlock: BlockConfig = { query: params.query, perPage: params.perPage ? Number(params.perPage) : undefined, page: params.page ? Number(params.page) : undefined, - subtype: params.searchType || undefined, + subtype: params.searchType || toolCallArg(context, params.subtype), } default: return baseParams @@ -1211,6 +1254,7 @@ export const WordPressBlock: BlockConfig = { content: { type: 'string', description: 'Post or page content' }, status: { type: 'string', description: 'Post or page status' }, excerpt: { type: 'string', description: 'Post or page excerpt' }, + date: { type: 'string', description: 'Publish date in the site timezone (ISO 8601)' }, slug: { type: 'string', description: 'URL slug' }, categories: { type: 'string', description: 'Category IDs (comma-separated)' }, tags: { type: 'string', description: 'Tag IDs (comma-separated)' }, diff --git a/apps/sim/blocks/blocks/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/blocks/zendesk.ts b/apps/sim/blocks/blocks/zendesk.ts index 9e469856d1b..cc7c083e971 100644 --- a/apps/sim/blocks/blocks/zendesk.ts +++ b/apps/sim/blocks/blocks/zendesk.ts @@ -1,7 +1,12 @@ import { ZendeskIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { parseOptionalBooleanInput, toolCallArg, withSavedCredential } from '@/blocks/utils' +import { + mapperOperation, + parseOptionalBooleanInput, + toolCallArg, + withSavedCredential, +} from '@/blocks/utils' import { getTrigger } from '@/triggers' export const ZendeskBlock: BlockConfig = { @@ -844,7 +849,7 @@ Return ONLY the search query - no explanations.`, } }, params: (params, context) => { - const { apiToken, operation, organizationName, commentPublic, ...rest } = params + const { apiToken, organizationName, commentPublic, ...rest } = params const cleanParams: Record = { apiToken } Object.entries(rest).forEach(([key, value]) => { @@ -854,7 +859,7 @@ Return ONLY the search query - no explanations.`, }) // Organization tools take `name`; the block's `name` field belongs to users. - const selectedOperation = operation ?? context?.operation + const selectedOperation = mapperOperation(params, context) if ( selectedOperation === 'autocomplete_organizations' || selectedOperation === 'create_organization' || diff --git a/apps/sim/blocks/blocks/zep.test.ts b/apps/sim/blocks/blocks/zep.test.ts new file mode 100644 index 00000000000..db340902527 --- /dev/null +++ b/apps/sim/blocks/blocks/zep.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest' +import { ZepBlock } from '@/blocks/blocks/zep' + +describe('ZepBlock', () => { + const buildParams = ZepBlock.tools.config?.params + if (!buildParams) throw new Error('ZepBlock.tools.config.params is missing') + + /** + * An agent tool call passes the operation only in `context`. The mapper must validate and + * coerce for that operation, not fall back to `create_thread` and reject the call for a + * missing user ID. + */ + it('maps an agent tool call for the operation in context', () => { + const args = { apiKey: 'key', threadId: 'thread_1', limit: '10' } + + expect({ ...args, ...buildParams(args, { operation: 'get_messages' }) }.limit).toBe(10) + }) +}) diff --git a/apps/sim/blocks/blocks/zep.ts b/apps/sim/blocks/blocks/zep.ts index 0bd138a6e58..1767a576ef8 100644 --- a/apps/sim/blocks/blocks/zep.ts +++ b/apps/sim/blocks/blocks/zep.ts @@ -1,8 +1,18 @@ import { ZepIcon } from '@/components/icons' -import { AuthMode, type BlockConfig, type BlockMeta, IntegrationType } from '@/blocks/types' -import { withSavedCredential } from '@/blocks/utils' +import { + AuthMode, + type BlockConfig, + type BlockMeta, + type BlockToolParamsContext, + IntegrationType, +} from '@/blocks/types' +import { isToolCall, mapperOperation, withSavedCredential } from '@/blocks/utils' -function zepToolParams(params: Record, requireApiKey: boolean) { +function zepToolParams( + params: Record, + requireApiKey: boolean, + context?: BlockToolParamsContext +) { const errors: string[] = [] // Validate required API key for all operations @@ -10,7 +20,7 @@ function zepToolParams(params: Record, requireApiKey: boolean) { errors.push('API Key is required') } - const operation = params.operation || 'create_thread' + const operation = mapperOperation(params, context) || 'create_thread' // Validate operation-specific required fields if ( @@ -35,7 +45,9 @@ function zepToolParams(params: Record, requireApiKey: boolean) { } } - if (operation === 'add_messages') { + // A tool call may send `messages` as a JSON string, which the tool parses and validates itself. + const toolParsesMessages = typeof params.messages === 'string' && isToolCall(context) + if (operation === 'add_messages' && !toolParsesMessages) { if (!params.messages) { errors.push('Messages are required') } else if (!Array.isArray(params.messages) || params.messages.length === 0) { @@ -290,7 +302,7 @@ export const ZepBlock: BlockConfig = { return 'zep_create_thread' } }, - params: (params) => zepToolParams(params, true), + params: (params, context) => zepToolParams(params, true, context), }, }, inputs: { @@ -436,6 +448,6 @@ export const ZepV2Block: BlockConfig = { ...withSavedCredential( ZepBlock, { id: 'credential', type: 'oauth-input', serviceId: 'zep', title: 'Zep Credential' }, - { params: (params) => zepToolParams(params, false) } + { params: (params, context) => zepToolParams(params, false, context) } ), } diff --git a/apps/sim/blocks/blocks/zoho-desk.ts b/apps/sim/blocks/blocks/zoho-desk.ts index 804b115ee36..a6eeb45be95 100644 --- a/apps/sim/blocks/blocks/zoho-desk.ts +++ b/apps/sim/blocks/blocks/zoho-desk.ts @@ -3,6 +3,7 @@ import { ZohoDeskIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { isToolCall, mapperOperation } from '@/blocks/utils' import { getTrigger } from '@/triggers' /** Both members of the `orgId` canonical pair, so the clause survives advanced mode. */ @@ -1055,7 +1056,7 @@ export const ZohoDeskBlock: BlockConfig = { id: 'sharedDepartments', title: 'Shared Departments', type: 'code', - placeholder: '[]', + placeholder: '[{"id": "1892000000006909", "type": "READ_ONLY"}]', condition: { field: 'operation', value: ['create_ticket', 'update_ticket'] }, mode: 'advanced', language: 'json', @@ -1064,7 +1065,7 @@ export const ZohoDeskBlock: BlockConfig = { generationType: 'json-array', placeholder: 'Describe the shared departments', prompt: - 'List of departments to which the ticket could be shared, along with the access privileges for each department JSON array. Return ONLY the JSON array.', + 'Departments to share the ticket with, as a JSON array of objects {"id": "", "type": "READ_ONLY" | "READ_WRITE" | "RESTRICTED_ACCESS"}. Return ONLY the JSON array.', }, }, { @@ -2640,21 +2641,11 @@ export const ZohoDeskBlock: BlockConfig = { ], config: { tool: (params) => `zoho_desk_${params.operation}`, - params: (params) => { - const fields = - typeof params.operation === 'string' - ? ADDITIONAL_OPERATION_FIELDS[params.operation] - : undefined - if (fields) { - const result: Record = { orgId: params.orgId } - for (const [name, config] of Object.entries(fields)) { - const value = params[name] - result[name] = normalizeParam(name, value, config) - } - return result - } - // Agent tools select the operation outside params; retain model args and map only configured aliases. - if (typeof params.operation !== 'string') { + params: (params, context) => { + const operation = mapperOperation(params, context) + // Tool calls keep the model's args (keyed by tool param names), so they never take the + // canvas branches below, which rebuild each param from block-only fields. + if (isToolCall(context) || !operation) { const result: Record = { ...params } for (const [alias, name] of Object.entries(LEGACY_AGENT_ALIASES)) { const value = orUndefined(params[alias]) @@ -2667,6 +2658,15 @@ export const ZohoDeskBlock: BlockConfig = { result.customFields = parseCustomFields(result.customFields) return result } + const fields = ADDITIONAL_OPERATION_FIELDS[operation] + if (fields) { + const result: Record = { orgId: params.orgId } + for (const [name, config] of Object.entries(fields)) { + const value = params[name] + result[name] = normalizeParam(name, value, config) + } + return result + } // IMPORTANT: destructuring a key out of `rest` does NOT keep it from the // tool. Both call sites merge this function's return value on top of the // original inputs (`{ ...inputs, ...transformedParams }` in @@ -2728,7 +2728,7 @@ export const ZohoDeskBlock: BlockConfig = { // param). Only forward it for add_comment so the UI can't imply an option // that has no effect elsewhere. result.contentType = - params.operation === 'add_comment' && typeof contentType === 'string' && contentType + operation === 'add_comment' && typeof contentType === 'string' && contentType ? contentType : undefined @@ -2745,7 +2745,7 @@ export const ZohoDeskBlock: BlockConfig = { // comment-only field onto every other operation's params. Destructured // out of `rest` so the default never reaches non-comment operations. result.isPublic = - params.operation === 'add_comment' && isPublic !== undefined + operation === 'add_comment' && isPublic !== undefined ? isPublic === true || isPublic === 'true' : undefined // Gated to update_ticket for the same reason as contentType and isPublic @@ -2757,15 +2757,15 @@ export const ZohoDeskBlock: BlockConfig = { // eight operations must receive neither - a ternary with a bare `else` // would forward a stale Update Ticket value into e.g. get_ticket. const activeStatus = - params.operation === 'list_tickets' + operation === 'list_tickets' ? rawStatusFilter - : params.operation === 'update_ticket' + : operation === 'update_ticket' ? rawStatus : undefined const activePriority = - params.operation === 'list_tickets' + operation === 'list_tickets' ? rawPriorityFilter - : params.operation === 'update_ticket' + : operation === 'update_ticket' ? rawPriority : undefined result.status = orUndefined(activeStatus) @@ -2777,11 +2777,11 @@ export const ZohoDeskBlock: BlockConfig = { // keeps its value across an operation change, so an ungated spread would // send list_tickets' `createdTime` to list_comments, which Zoho rejects. const activeSortBy = - params.operation === 'list_tickets' + operation === 'list_tickets' ? rawSortBy - : params.operation === 'list_comments' + : operation === 'list_comments' ? rawCommentSortBy - : params.operation === 'list_threads' + : operation === 'list_threads' ? rawThreadSortBy : undefined result.sortBy = orUndefined(activeSortBy) @@ -2793,22 +2793,22 @@ export const ZohoDeskBlock: BlockConfig = { // `contract` and `skills` - while List Tickets never reads // `ticketInclude`, so those two extra tokens can still never reach it. const activeInclude = - params.operation === 'list_tickets' + operation === 'list_tickets' ? rawInclude - : params.operation === 'get_ticket' + : operation === 'get_ticket' ? (orUndefined(rawTicketInclude) ?? rawInclude) - : params.operation === 'get_contact' + : operation === 'get_contact' ? rawContactInclude - : params.operation === 'list_comments' + : operation === 'list_comments' ? params.include - : params.operation === 'get_thread' + : operation === 'get_thread' ? rawThreadInclude : undefined result.include = orUndefined(activeInclude) // Gated for the same stale-value reason as the filters above: these three // are list_tickets-only query params, and no other operation declares them. - const isListTickets = params.operation === 'list_tickets' + const isListTickets = operation === 'list_tickets' result.assignee = isListTickets ? orUndefined(rawAssigneeFilter) : undefined result.channel = isListTickets ? orUndefined(rawChannelFilter) : undefined // Forward whatever was supplied and let the tool judge it. Filtering here @@ -2820,37 +2820,35 @@ export const ZohoDeskBlock: BlockConfig = { result.receivedInDays = receivedInDays === undefined ? undefined : Number(receivedInDays) result.customFields = - params.operation === 'update_ticket' ? parseCustomFields(rawCustomFields) : undefined - result.viewId = params.operation === 'list_tickets' ? params.viewId : undefined - result.teamIds = params.operation === 'list_tickets' ? params.teamIds : undefined - result.selectedFields = - params.operation === 'list_tickets' ? params.selectedFields : undefined - result.ticketContactId = - params.operation === 'update_ticket' ? params.ticketContactId : undefined + operation === 'update_ticket' ? parseCustomFields(rawCustomFields) : undefined + result.viewId = operation === 'list_tickets' ? params.viewId : undefined + result.teamIds = operation === 'list_tickets' ? params.teamIds : undefined + result.selectedFields = operation === 'list_tickets' ? params.selectedFields : undefined + result.ticketContactId = operation === 'update_ticket' ? params.ticketContactId : undefined result.commentInclude = - params.operation === 'list_comments' ? orUndefined(params.commentInclude) : undefined - result.contact = params.operation === 'update_ticket' ? params.contact : undefined - result.productId = params.operation === 'update_ticket' ? params.productId : undefined - result.uploads = params.operation === 'update_ticket' ? params.uploads : undefined - result.email = params.operation === 'update_ticket' ? params.email : undefined - result.phone = params.operation === 'update_ticket' ? params.phone : undefined - result.language = params.operation === 'update_ticket' ? params.language : undefined - result.channel = params.operation === 'update_ticket' ? params.channel : result.channel - result.webUrl = params.operation === 'update_ticket' ? params.webUrl : undefined + operation === 'list_comments' ? orUndefined(params.commentInclude) : undefined + result.contact = operation === 'update_ticket' ? params.contact : undefined + result.productId = operation === 'update_ticket' ? params.productId : undefined + result.uploads = operation === 'update_ticket' ? params.uploads : undefined + result.email = operation === 'update_ticket' ? params.email : undefined + result.phone = operation === 'update_ticket' ? params.phone : undefined + result.language = operation === 'update_ticket' ? params.language : undefined + result.channel = operation === 'update_ticket' ? params.channel : result.channel + result.webUrl = operation === 'update_ticket' ? params.webUrl : undefined result.sharedDepartments = - params.operation === 'update_ticket' ? params.sharedDepartments : undefined - result.teamId = params.operation === 'update_ticket' ? params.teamId : undefined + operation === 'update_ticket' ? params.sharedDepartments : undefined + result.teamId = operation === 'update_ticket' ? params.teamId : undefined result.secondaryContacts = - params.operation === 'update_ticket' ? params.secondaryContacts : undefined - result.entitySkills = params.operation === 'update_ticket' ? params.entitySkills : undefined + operation === 'update_ticket' ? params.secondaryContacts : undefined + result.entitySkills = operation === 'update_ticket' ? params.entitySkills : undefined result.disableClosureNotification = - params.operation === 'update_ticket' + operation === 'update_ticket' ? params.disableClosureNotification === '' || params.disableClosureNotification == null ? undefined : params.disableClosureNotification === true || params.disableClosureNotification === 'true' : undefined - result.attachmentIds = params.operation === 'add_comment' ? params.attachmentIds : undefined + result.attachmentIds = operation === 'add_comment' ? params.attachmentIds : undefined return result }, }, diff --git a/apps/sim/blocks/blocks/zoom.test.ts b/apps/sim/blocks/blocks/zoom.test.ts new file mode 100644 index 00000000000..704f9646c85 --- /dev/null +++ b/apps/sim/blocks/blocks/zoom.test.ts @@ -0,0 +1,94 @@ +import { describe, expect, it } from 'vitest' +import { ZoomBlock } from '@/blocks/blocks/zoom' +import type { BlockToolParamsContext } from '@/blocks/types' + +function mapParams(params: Record, context?: BlockToolParamsContext) { + const mapper = ZoomBlock.tools.config?.params + if (!mapper) throw new Error('Zoom block has no params mapper') + return mapper(params, context) +} + +/** What a tool call sends: the merged row params and model args with the mapper result over them. */ +function toolCall(args: Record, operation: string) { + return { ...args, ...mapParams(args, { operation }) } +} + +describe('Zoom tool calls', () => { + it('sends a stored From/To Date range on List Recordings', () => { + const sent = toolCall( + { userId: 'me', fromDate: '2026-10-01', toDate: '2026-10-31' }, + 'zoom_list_recordings' + ) + expect(sent.from).toBe('2026-10-01') + expect(sent.to).toBe('2026-10-31') + }) + + it("keeps the model's from/to when the row has no dates", () => { + const sent = toolCall( + { userId: 'me', from: '2026-10-01', to: '2026-10-15' }, + 'zoom_list_recordings' + ) + expect(sent.from).toBe('2026-10-01') + expect(sent.to).toBe('2026-10-15') + }) + + it('sends a stored Permanently Delete action on Delete Recording', () => { + const sent = toolCall({ meetingId: '123', deleteAction: 'delete' }, 'zoom_delete_recording') + expect(sent.action).toBe('delete') + }) + + it("keeps the model's topic and list type", () => { + expect(toolCall({ meetingId: '123', topic: 'Renamed' }, 'zoom_update_meeting').topic).toBe( + 'Renamed' + ) + expect(toolCall({ userId: 'me', type: 'upcoming' }, 'zoom_list_meetings').type).toBe('upcoming') + }) + + it('accepts a numeric meeting ID from the model', () => { + expect(toolCall({ meetingId: 85746065432 }, 'zoom_get_meeting').meetingId).toBe('85746065432') + }) + + it('coerces a stored meeting type and drops a stored "none" auto recording', () => { + const sent = toolCall( + { userId: 'me', topic: 'Standup', type: '8', autoRecording: 'none' }, + 'zoom_create_meeting' + ) + expect(sent.type).toBe(8) + expect(sent.autoRecording).toBeUndefined() + }) + + it('does not turn auto recording off from a legacy row that stored "none" on Update Meeting', () => { + const sent = toolCall({ meetingId: '123', autoRecording: 'none' }, 'zoom_update_meeting') + expect(sent.autoRecording).toBeUndefined() + }) + + it("lets the model set auto recording from a new agent tool row's seed", () => { + const field = ZoomBlock.subBlocks.find((subBlock) => subBlock.id === 'autoRecording') + const seeded = field?.value?.({}) + const stored = seeded === undefined ? {} : { autoRecording: seeded } + const sent = toolCall( + { meetingId: '123', autoRecording: 'cloud', ...stored }, + 'zoom_update_meeting' + ) + expect(sent.autoRecording).toBe('cloud') + }) +}) + +describe('Zoom canvas update', () => { + it('does not send a stale create topic', () => { + const inputs = { + operation: 'zoom_update_meeting', + meetingId: '123', + topic: 'Old create topic', + topicUpdate: '', + } + expect({ ...inputs, ...mapParams(inputs) }.topic).not.toBe('Old create topic') + }) + + it('leaves the meeting type unchanged for a new Update Meeting block', () => { + const typeField = ZoomBlock.subBlocks.find((subBlock) => subBlock.id === 'type') + const seeded = typeField?.value?.({ operation: 'zoom_update_meeting' }) + const inputs = { operation: 'zoom_update_meeting', meetingId: '123', type: seeded } + expect({ ...inputs, ...mapParams(inputs) }.type).toBeUndefined() + }) +}) diff --git a/apps/sim/blocks/blocks/zoom.ts b/apps/sim/blocks/blocks/zoom.ts index a89297ac4be..b028863d5d5 100644 --- a/apps/sim/blocks/blocks/zoom.ts +++ b/apps/sim/blocks/blocks/zoom.ts @@ -1,7 +1,8 @@ import { ZoomIcon } from '@/components/icons' import { getScopesForService } from '@/lib/oauth/utils' -import type { BlockConfig, BlockMeta } from '@/blocks/types' +import type { BlockConfig, BlockMeta, SubBlockConfig } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { mapperOperation, toolCallArg } from '@/blocks/utils' import { getTrigger } from '@/triggers' /* @@ -11,6 +12,59 @@ import { getTrigger } from '@/triggers' */ const MEETING_FIELD = ['meetingSelector', 'meetingId'] as const +const MEETING_TYPE_OPTIONS = [ + { label: 'Scheduled', id: '2' }, + { label: 'Instant', id: '1' }, + { label: 'Recurring (no fixed time)', id: '3' }, + { label: 'Recurring (fixed time)', id: '8' }, +] + +const AUTO_RECORDING_OPTIONS = [ + { label: 'None', id: 'none' }, + { label: 'Local', id: 'local' }, + { label: 'Cloud', id: 'cloud' }, +] + +const NO_CHANGE_OPTION = { label: 'No change', id: '' } + +/** + * Options and default for a meeting setting shared by Create and Update Meeting. Every context + * except a known Create Meeting leads with "No change", so a new Update Meeting block or agent tool + * row (whose values carry no operation) does not seed a value that overwrites the meeting's + * setting, such as turning a recurring meeting into a scheduled one. Without block values (Copilot + * validation, catalogs) every option is listed, with "No change" last so the first option stays the + * default. Create seeds `createDefault`. + */ +function meetingSettingDropdown( + options: { label: string; id: string }[], + createDefault: string +): Pick { + return { + dependsOn: ['operation'], + options: (params) => [ + ...(params && params.values.operation !== 'zoom_create_meeting' ? [NO_CHANGE_OPTION] : []), + ...options, + ...(params ? [] : [NO_CHANGE_OPTION]), + ], + value: (params) => + params?.operation === 'zoom_create_meeting' + ? createDefault + : params?.operation === 'zoom_update_meeting' + ? '' + : undefined, + } +} + +/** + * A text input as a trimmed string. A model may send a Zoom meeting ID as a number, which the + * spec types as an integer. + */ +function trimmedText(value: unknown): string { + if (typeof value === 'string') return value.trim() + if (typeof value === 'number' || typeof value === 'bigint') return String(value) + return '' +} + export const ZoomBlock: BlockConfig = { type: 'zoom', name: 'Zoom', @@ -203,13 +257,7 @@ export const ZoomBlock: BlockConfig = { id: 'type', title: 'Meeting Type', type: 'dropdown', - options: [ - { label: 'Scheduled', id: '2' }, - { label: 'Instant', id: '1' }, - { label: 'Recurring (no fixed time)', id: '3' }, - { label: 'Recurring (fixed time)', id: '8' }, - ], - value: () => '2', + ...meetingSettingDropdown(MEETING_TYPE_OPTIONS, '2'), condition: { field: 'operation', value: ['zoom_create_meeting', 'zoom_update_meeting'], @@ -346,12 +394,7 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, id: 'autoRecording', title: 'Auto Recording', type: 'dropdown', - options: [ - { label: 'None', id: 'none' }, - { label: 'Local', id: 'local' }, - { label: 'Cloud', id: 'cloud' }, - ], - value: () => 'none', + ...meetingSettingDropdown(AUTO_RECORDING_OPTIONS, 'none'), mode: 'advanced', condition: { field: 'operation', @@ -405,7 +448,7 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, id: 'fromDate', title: 'From Date', type: 'short-input', - placeholder: 'yyyy-mm-dd (within last 6 months)', + placeholder: 'yyyy-mm-dd (max 1-month range; defaults to today)', mode: 'advanced', condition: { field: 'operation', @@ -415,7 +458,7 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, enabled: true, prompt: `Generate a date string based on the user's description. The date should be in the format: yyyy-mm-dd (e.g., 2024-01-15). -This is for filtering Zoom recordings from this date (must be within last 6 months). +This is for filtering Zoom recordings from this date. Zoom allows at most a one-month range and defaults to today when no date is given. Examples: - "last month" -> Calculate 30 days ago in yyyy-mm-dd format - "beginning of this month" -> First day of current month in yyyy-mm-dd format @@ -497,6 +540,7 @@ Return ONLY the date string - no explanations, no quotes, no extra text.`, id: 'cancelMeetingReminder', title: 'Send Cancellation Email', type: 'switch', + description: 'Email the meeting registrants about the cancellation', mode: 'advanced', condition: { field: 'operation', @@ -527,23 +571,32 @@ Return ONLY the date string - no explanations, no quotes, no extra text.`, tool: (params) => { return params.operation || 'zoom_create_meeting' }, - params: (params) => { - const baseParams: Record = { + params: (params, context) => { + const baseParams: Record = { credential: params.oauthCredential, } + const userId = trimmedText(params.userId) + const meetingId = trimmedText(params.meetingId) + const requireUserId = () => { + if (!userId) throw new Error('User ID is required.') + return userId + } + const requireMeetingId = () => { + if (!meetingId) throw new Error('Meeting ID is required.') + return meetingId + } - switch (params.operation) { - case 'zoom_create_meeting': - if (!params.userId?.trim()) { - throw new Error('User ID is required.') - } - if (!params.topic?.trim()) { + switch (mapperOperation(params, context)) { + case 'zoom_create_meeting': { + const topic = trimmedText(params.topic) + requireUserId() + if (!topic) { throw new Error('Topic is required.') } return { ...baseParams, - userId: params.userId.trim(), - topic: params.topic.trim(), + userId, + topic, type: params.type ? Number(params.type) : 2, startTime: params.startTime, duration: params.duration ? Number(params.duration) : undefined, @@ -557,37 +610,29 @@ Return ONLY the date string - no explanations, no quotes, no extra text.`, waitingRoom: params.waitingRoom, autoRecording: params.autoRecording !== 'none' ? params.autoRecording : undefined, } + } case 'zoom_list_meetings': - if (!params.userId?.trim()) { - throw new Error('User ID is required.') - } return { ...baseParams, - userId: params.userId.trim(), - type: params.listType, + userId: requireUserId(), + type: params.listType || toolCallArg(context, params.type), pageSize: params.pageSize ? Number(params.pageSize) : undefined, nextPageToken: params.nextPageToken, } case 'zoom_get_meeting': - if (!params.meetingId?.trim()) { - throw new Error('Meeting ID is required.') - } return { ...baseParams, - meetingId: params.meetingId.trim(), + meetingId: requireMeetingId(), occurrenceId: params.occurrenceId, } case 'zoom_update_meeting': - if (!params.meetingId?.trim()) { - throw new Error('Meeting ID is required.') - } return { ...baseParams, - meetingId: params.meetingId.trim(), - topic: params.topicUpdate, + meetingId: requireMeetingId(), + topic: params.topicUpdate || toolCallArg(context, params.topic), type: params.type ? Number(params.type) : undefined, startTime: params.startTime, duration: params.duration ? Number(params.duration) : undefined, @@ -603,65 +648,42 @@ Return ONLY the date string - no explanations, no quotes, no extra text.`, } case 'zoom_delete_meeting': - if (!params.meetingId?.trim()) { - throw new Error('Meeting ID is required.') - } return { ...baseParams, - meetingId: params.meetingId.trim(), + meetingId: requireMeetingId(), occurrenceId: params.occurrenceId, cancelMeetingReminder: params.cancelMeetingReminder, } case 'zoom_get_meeting_invitation': - if (!params.meetingId?.trim()) { - throw new Error('Meeting ID is required.') - } + case 'zoom_get_meeting_recordings': return { ...baseParams, - meetingId: params.meetingId.trim(), + meetingId: requireMeetingId(), } case 'zoom_list_recordings': - if (!params.userId?.trim()) { - throw new Error('User ID is required.') - } return { ...baseParams, - userId: params.userId.trim(), - from: params.fromDate, - to: params.toDate, + userId: requireUserId(), + from: params.fromDate || toolCallArg(context, params.from), + to: params.toDate || toolCallArg(context, params.to), pageSize: params.pageSize ? Number(params.pageSize) : undefined, nextPageToken: params.nextPageToken, } - case 'zoom_get_meeting_recordings': - if (!params.meetingId?.trim()) { - throw new Error('Meeting ID is required.') - } - return { - ...baseParams, - meetingId: params.meetingId.trim(), - } - case 'zoom_delete_recording': - if (!params.meetingId?.trim()) { - throw new Error('Meeting ID is required.') - } return { ...baseParams, - meetingId: params.meetingId.trim(), + meetingId: requireMeetingId(), recordingId: params.recordingId, - action: params.deleteAction, + action: params.deleteAction || toolCallArg(context, params.action), } case 'zoom_list_past_participants': - if (!params.meetingId?.trim()) { - throw new Error('Meeting ID is required.') - } return { ...baseParams, - meetingId: params.meetingId.trim(), + meetingId: requireMeetingId(), pageSize: params.pageSize ? Number(params.pageSize) : undefined, nextPageToken: params.nextPageToken, } @@ -749,9 +771,9 @@ export const ZoomBlockMeta = { }, { icon: ZoomIcon, - title: 'Zoom webinar follow-up', + title: 'Zoom meeting follow-up', prompt: - 'Build a workflow that runs after a Zoom webinar, pulls the registrant and attendee lists, sends a follow-up email with the recording link, and writes attendance into HubSpot for marketing scoring.', + 'Build a workflow that runs after a Zoom meeting ends, lists the past participants, sends each a follow-up email with the recording link, and writes attendance into HubSpot for marketing scoring.', modules: ['agent', 'workflows'], category: 'marketing', tags: ['marketing', 'crm'], diff --git a/apps/sim/blocks/types.ts b/apps/sim/blocks/types.ts index 2d05ca153fe..4968dd54b15 100644 --- a/apps/sim/blocks/types.ts +++ b/apps/sim/blocks/types.ts @@ -615,6 +615,12 @@ export type CanvasSentence = readonly CanvasSentenceClause[] export interface BlockToolParamsContext { /** Operation selected by the configuring surface. */ operation?: string + /** + * Ids of the values the tool row itself stores non-empty (as stored, before canonical + * resolution). A model argument never overrides one of these, so a mapper can tell a pinned + * value from one the model chose when two params name the same thing. + */ + pinnedParams?: ReadonlySet } export interface BlockConfig { diff --git a/apps/sim/blocks/utils.ts b/apps/sim/blocks/utils.ts index ceffb5ed61d..c9a0fb240dd 100644 --- a/apps/sim/blocks/utils.ts +++ b/apps/sim/blocks/utils.ts @@ -23,6 +23,7 @@ import { SIM_AUTO_MODEL_ID, } from '@/providers/models' import { isPiSupportedModel } from '@/providers/pi-providers' +import { ToolCallParamsError } from '@/providers/tool-params-error' import type { ProviderId } from '@/providers/types' import { getProviderFromModel } from '@/providers/utils' import { useProvidersStore } from '@/stores/providers/store' @@ -948,6 +949,48 @@ export function toolCallArg( return isToolCall(context) ? value : undefined } +/** + * What the model is told when a block rejects a tool call's params. Deliberately static: a + * mapper's own message can quote the value it rejected (`Invalid Limit "…"`, a JSON parse + * snippet), and by then a model-written `{{SECRET}}` placeholder has been resolved to plaintext. + */ +const TOOL_CALL_PARAMS_REJECTED_MESSAGE = + 'The tool was not run: its arguments could not be mapped to the tool inputs. Check the argument values (filters, sort, row data, limit) and try again.' + +/** + * Runs a mapper body, and on a tool call turns any failure into a {@link ToolCallParamsError} so + * the call fails instead of running on the raw merged params. Use it where those raw params are + * unsafe: a pinned value under a block-only key (a filter builder) drops out of them, leaving the + * model's own argument for the same tool param in its place. The original error stays on `cause` + * for server logs; the canvas rethrows it unchanged. + */ +export function failToolCallOnError( + context: BlockToolParamsContext | undefined, + map: () => T +): T { + try { + return map() + } catch (error) { + if (!isToolCall(context) || error instanceof ToolCallParamsError) throw error + throw new ToolCallParamsError(TOOL_CALL_PARAMS_REJECTED_MESSAGE, { cause: error }) + } +} + +/** + * 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/apps/sim/connectors/confluence/app-macros.ts b/apps/sim/connectors/confluence/app-macros.ts new file mode 100644 index 00000000000..2b30ead9d3a --- /dev/null +++ b/apps/sim/connectors/confluence/app-macros.ts @@ -0,0 +1,171 @@ +import * as cheerio from 'cheerio' +import { htmlToPlainText } from '@/connectors/utils' + +/** + * Caelor Optics stores every module under one Connect macro and names the module + * in its `macro` parameter. The HTML module keeps the page author's markup in + * `contentByMode` (escaped JSON), and Confluence renders it only as an iframe + * bootstrap script, so neither body format carries its text as page prose. + */ +const OPTICS_MACRO_NAME = 'caelor-optics-entry' + +/** Every Connect app macro renders into this iframe container. */ +const CONNECT_APP_CONTAINER = 'ap-container' + +/** Markup whose text is never prose. Scripts are read for their data first. */ +const NON_PROSE_SELECTOR = 'script, style, noscript, template' + +/** + * A string or number property of an object literal, introduced by `{` or `,` so + * ternaries (`a ? 'x' : 'y'`) and `case 'x':` labels are not mistaken for data. + * JSON objects match too, so both `{name: 'Zoom'}` and `{"name": "Zoom"}` read. + */ +const OBJECT_PROPERTY_PATTERN = + /([{,])\s*(?:([A-Za-z_$][\w$]*)|"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)')\s*:\s*(?:"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)'|(-?\d+(?:\.\d+)?)(?![\w.]))/g + +/** Values that are encoded payloads (inline images, fonts), not readable data. */ +const MAX_UNBROKEN_VALUE_LENGTH = 200 +const BASE64_ALPHABET_PATTERN = /^[A-Za-z0-9+/]{24,}={0,2}$/ + +/** + * A string literal (kept, so a `//` inside `'https://…'` survives), a regex + * literal (kept, so the `//` ending `/https?:\/\//` survives; recognized only + * where an expression can start, so division is not mistaken for one), or a + * comment (dropped, so commented-out records never read as page data). + */ +const STRING_OR_COMMENT_PATTERN = + /("(?:[^"\\\r\n]|\\.)*"|'(?:[^'\\\r\n]|\\.)*'|`(?:[^`\\]|\\.)*`|\/(?<=(?:^|[=(,:;!&|?{}[\]+\-*%~^<>]|\breturn)\s*\/)(?![*/])(?:[^/\\\r\n[]|\\.|\[(?:[^\]\\\r\n]|\\.)*\])+\/[a-z]*)|\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g + +/** + * Whether a rendered `view` body may hold an Optics HTML macro, whose text only + * the storage body carries. Rendered Connect macros name themselves in + * `data-macro-name`; a page left with no text but an app container is checked + * too, so a rendering without that attribute still recovers. Other app pages + * (draw.io, Lucidchart) that have prose skip the extra request. + */ +export function mayHoldOpticsHtmlMacro(viewHtml: string, viewText: string): boolean { + return ( + viewHtml.includes(OPTICS_MACRO_NAME) || + (!viewText.trim() && viewHtml.includes(CONNECT_APP_CONTAINER)) + ) +} + +/** Parses a storage-format body, whose `ac:`/`ri:` elements and CDATA need lenient XML handling. */ +export function loadStorageBody(storage: string): cheerio.CheerioAPI { + return cheerio.load( + storage, + { xml: { xmlMode: false, recognizeCDATA: true, recognizeSelfClosing: true } }, + false + ) +} + +/** + * Text of a storage-format Optics HTML macro, or null when the element is any + * other macro. The HTML is authored on the page itself, so it is the same for + * every reader who can open the page. + */ +export function readOpticsHtmlMacroText( + $: cheerio.CheerioAPI, + element: Parameters[0] +): string | null { + const macro = $(element) + if (macro.attr('ac:name') !== OPTICS_MACRO_NAME) return null + const parameter = (name: string) => macro.children(`ac\\:parameter[ac\\:name="${name}"]`) + if (parameter('macro').text().trim() !== 'html') return null + return readMarkupSources(parameter('contentByMode').text()) + .map(markupToText) + .filter(Boolean) + .join(' ') +} + +/** Text of every Optics HTML macro in a storage-format body. */ +export function extractOpticsHtmlMacroText(storage: string): string { + if (!storage.includes(OPTICS_MACRO_NAME)) return '' + const $ = loadStorageBody(storage) + return $('ac\\:structured-macro') + .toArray() + .map((element) => readOpticsHtmlMacroText($, element)) + .filter(Boolean) + .join(' ') +} + +/** + * `contentByMode` is JSON keyed by editor mode; its markup is whichever string + * values contain tags. A value that is not JSON is read as markup directly. + */ +function readMarkupSources(content: string): string[] { + let parsed: unknown + try { + parsed = JSON.parse(content) + } catch { + return [content] + } + const sources: string[] = [] + const collect = (value: unknown) => { + if (typeof value === 'string') { + if (/<[a-z!]/i.test(value)) sources.push(value) + } else if (Array.isArray(value)) { + value.forEach(collect) + } else if (value && typeof value === 'object') { + Object.values(value).forEach(collect) + } + } + collect(parsed) + return sources +} + +/** + * Visible text of authored markup followed by the data its scripts declare. A + * page that renders a list from a JS object keeps nothing visible but a mount + * point, so the object's properties are what a reader actually sees. + */ +function markupToText(markup: string): string { + const $ = cheerio.load(markup) + const scriptData = $('script') + .toArray() + .map((script) => readScriptData($(script).text())) + .filter(Boolean) + $(NON_PROSE_SELECTOR).replaceWith(' ') + return [htmlToPlainText($.html()), ...scriptData].filter(Boolean).join(' ') +} + +/** Object-literal properties as `key: value` lines, one line per object. */ +function readScriptData(script: string): string { + const records: string[][] = [[]] + const code = script.replace(STRING_OR_COMMENT_PATTERN, (_, literal?: string) => literal ?? ' ') + for (const match of code.matchAll(OBJECT_PROPERTY_PATTERN)) { + const [, opener, bareKey, doubleKey, singleKey, doubleValue, singleValue, numberValue] = match + const key = bareKey ?? unescapeJsString(doubleKey ?? singleKey ?? '') + const value = numberValue ?? unescapeJsString(doubleValue ?? singleValue ?? '').trim() + if (opener === '{') records.push([]) + if (key && isReadableValue(value)) records[records.length - 1].push(`${key}: ${value}`) + } + return records + .filter((record) => record.length > 0) + .map((record) => `${record.join(', ')}.`) + .join(' ') +} + +function isReadableValue(value: string): boolean { + if (!value || value.startsWith('data:') || isBase64Payload(value)) return false + return value.length <= MAX_UNBROKEN_VALUE_LENGTH || /\s/.test(value) +} + +/** + * Base64-alphabet runs that also carry the evidence of encoding: padding or + * `+`/`/`, or the upper, lower, and digit mix random bytes produce. A long name + * (`MicrosoftAuthenticationLibrary`) or numeric id has the alphabet but not this. + */ +function isBase64Payload(value: string): boolean { + if (!BASE64_ALPHABET_PATTERN.test(value)) return false + return /[+/=]/.test(value) || (/[a-z]/.test(value) && /[A-Z]/.test(value) && /\d/.test(value)) +} + +const JS_ESCAPES: Record = { n: ' ', r: ' ', t: ' ', b: '', f: '', v: '' } + +function unescapeJsString(value: string): string { + return value.replace(/\\(u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|[\s\S])/g, (_, sequence: string) => { + if (sequence.length > 1) return String.fromCharCode(Number.parseInt(sequence.slice(1), 16)) + return JS_ESCAPES[sequence] ?? sequence + }) +} diff --git a/apps/sim/connectors/confluence/confluence.test.ts b/apps/sim/connectors/confluence/confluence.test.ts index f8338f2b726..3b35181f0ab 100644 --- a/apps/sim/connectors/confluence/confluence.test.ts +++ b/apps/sim/connectors/confluence/confluence.test.ts @@ -653,3 +653,203 @@ describe('confluence mirrored permissions', () => { }) }) }) + +describe('Confluence Caelor Optics HTML macros', () => { + const config = { domain: 'example.atlassian.net', spaceKey: 'DOCS' } + const escapeXml = (value: string) => + value.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"') + const opticsHtml = + '

Find your app

' + + '
' + + "' + const opticsMacro = (contentByMode: string, macro = 'html') => + '' + + `${macro}` + + `${escapeXml(contentByMode)}` + + '' + const opticsView = + '
' + + '
' + + '' + + '
' + + function stubPage(bodies: { view: string; storage: string }) { + const requestedFormats: string[] = [] + stubFetchWithoutAttachments( + vi.fn(async (input: string | URL | Request) => { + const format = new URL(String(input)).searchParams.get('body-format') ?? 'view' + requestedFormats.push(format) + return Response.json({ + id: 'optics-page', + title: 'Find your app', + status: 'current', + spaceId: 'space-1', + version: { number: 4 }, + body: { [format]: { value: format === 'storage' ? bodies.storage : bodies.view } }, + }) + }) + ) + return requestedFormats + } + + function expectOpticsText(content: string | undefined) { + expect(content).toContain('Find your app') + expect(content).toContain('name: Zoom, wave: 3, date: 2026-12-04') + expect(content).toContain('name: Slack, wave: 1') + expect(content).not.toContain('color:red') + expect(content).not.toContain('base64') + expect(content).not.toContain('getElementById') + } + + it('indexes the authored HTML and script data of an Optics-only rendered page', async () => { + stubPage({ view: opticsView, storage: opticsMacro(JSON.stringify({ html: opticsHtml })) }) + + const document = await confluenceConnector.getDocument('token', config, 'optics-page', { + cloudId: 'cloud-1', + }) + + expect(document?.skippedReason).toBeUndefined() + expectOpticsText(document?.content) + }) + + it('keeps rendered prose alongside the Optics macro text', async () => { + stubPage({ + view: `

Read this first

${opticsView}`, + storage: `

Read this first

${opticsMacro(JSON.stringify({ html: opticsHtml }))}`, + }) + + const document = await confluenceConnector.getDocument('token', config, 'optics-page', { + cloudId: 'cloud-1', + }) + + expect(document?.content).toContain('Read this first') + expectOpticsText(document?.content) + }) + + it('keeps script data around regex literals and long names, without comments or base64', async () => { + const markup = + '

Find your app

" + stubPage({ view: opticsView, storage: opticsMacro(JSON.stringify({ html: markup })) }) + + const document = await confluenceConnector.getDocument('token', config, 'optics-page', { + cloudId: 'cloud-1', + }) + + expect(document?.content).toContain('name: Zoom, url: https://zoom.example/a') + expect(document?.content).toContain( + 'name: MicrosoftAuthenticationLibrary, id: 100200300400500600700' + ) + expect(document?.content).not.toContain('Retired app') + expect(document?.content).not.toContain('Draft app') + expect(document?.content).not.toContain('iVBORw0KGgo') + }) + + it('fails hydration when the storage response omits its body so the page retries', async () => { + stubFetchWithoutAttachments( + vi.fn(async (input: string | URL | Request) => { + const format = new URL(String(input)).searchParams.get('body-format') + return Response.json({ + id: 'optics-page', + status: 'current', + version: { number: 4 }, + body: format === 'storage' ? {} : { view: { value: `

Prose

${opticsView}` } }, + }) + }) + ) + + await expect( + confluenceConnector.getDocument('token', config, 'optics-page', { cloudId: 'cloud-1' }) + ).rejects.toThrow('missing its storage body') + }) + + it('reads a contentByMode that holds raw HTML instead of JSON', async () => { + stubPage({ view: opticsView, storage: opticsMacro(opticsHtml) }) + + const document = await confluenceConnector.getDocument('token', config, 'optics-page', { + cloudId: 'cloud-1', + }) + + expectOpticsText(document?.content) + }) + + it('does not fetch the storage body for a rendered page without app macros', async () => { + const requestedFormats = stubPage({ view: '

Plain page

', storage: '

Plain page

' }) + + const document = await confluenceConnector.getDocument('token', config, 'optics-page', { + cloudId: 'cloud-1', + }) + + expect(document?.content).toBe('Plain page') + expect(requestedFormats).toEqual(['view']) + }) + + it('skips the storage request for another app macro on a page with prose', async () => { + const requestedFormats = stubPage({ + view: + '

Diagram notes

' + + '
', + storage: '

Diagram notes

', + }) + + const document = await confluenceConnector.getDocument('token', config, 'optics-page', { + cloudId: 'cloud-1', + }) + + expect(document?.content).toBe('Diagram notes') + expect(requestedFormats).toEqual(['view']) + }) + + it('reads storage for an app-only page whose rendering omits the macro name', async () => { + stubPage({ + view: opticsView.replace(' data-macro-name="caelor-optics-entry"', ''), + storage: opticsMacro(JSON.stringify({ html: opticsHtml })), + }) + + const document = await confluenceConnector.getDocument('token', config, 'optics-page', { + cloudId: 'cloud-1', + }) + + expectOpticsText(document?.content) + }) + + it('indexes an Optics HTML macro nested in a layout on the permission-scoped path', async () => { + stubPage({ + view: opticsView, + storage: + '' + + '' + + opticsMacro(JSON.stringify({ html: opticsHtml })) + + '', + }) + + const document = await confluenceConnector.getDocument('token', config, 'optics-page', { + cloudId: 'cloud-1', + mirrorsSourceAcls: true, + }) + + expect(document?.skippedReason).toBeUndefined() + expectOpticsText(document?.content) + }) + + it('still treats other Optics modules as dynamic content on the permission-scoped path', async () => { + stubPage({ + view: opticsView, + storage: opticsMacro(JSON.stringify({ html: opticsHtml }), 'cards'), + }) + + const document = await confluenceConnector.getDocument('token', config, 'optics-page', { + cloudId: 'cloud-1', + mirrorsSourceAcls: true, + }) + + expect(document?.skippedReason).toBe(DYNAMIC_CONTENT_SKIP_REASON) + }) +}) diff --git a/apps/sim/connectors/confluence/confluence.ts b/apps/sim/connectors/confluence/confluence.ts index e7943ea3da4..41fb406007b 100644 --- a/apps/sim/connectors/confluence/confluence.ts +++ b/apps/sim/connectors/confluence/confluence.ts @@ -19,6 +19,12 @@ import { type RetryOptions, VALIDATE_RETRY_OPTIONS, } from '@/lib/knowledge/documents/utils' +import { + extractOpticsHtmlMacroText, + loadStorageBody, + mayHoldOpticsHtmlMacro, + readOpticsHtmlMacroText, +} from '@/connectors/confluence/app-macros' import { getConfluenceAttachment, isConfluenceAttachment, @@ -348,11 +354,7 @@ export interface ConfluenceStorageText { * inclusion and third-party macros may render differently for each reader. */ export function extractConfluenceStorageText(storage: string): ConfluenceStorageText { - const $ = cheerio.load( - storage, - { xml: { xmlMode: false, recognizeCDATA: true, recognizeSelfClosing: true } }, - false - ) + const $ = loadStorageBody(storage) let droppedDynamicContent = false for (const element of $(ADF_NODE_SELECTOR).toArray().reverse()) { @@ -374,9 +376,13 @@ export function extractConfluenceStorageText(storage: string): ConfluenceStorage } $(STORAGE_MACRO_SELECTOR).each((_, element) => { - if (!LOCAL_STORAGE_MACROS.has($(element).attr('ac:name') ?? '')) { + if (LOCAL_STORAGE_MACROS.has($(element).attr('ac:name') ?? '')) return + const opticsText = readOpticsHtmlMacroText($, element) + if (opticsText === null) { droppedDynamicContent = true $(element).remove() + } else { + $(element).replaceWith($('

').text(opticsText)) } }) @@ -890,15 +896,20 @@ export const confluenceConnector: ConnectorConfig = { const bodyFormat = scopedContent ? 'storage' : 'view' let page: Record | null = null let contentType: 'page' | 'blogpost' = 'page' - for (const endpoint of ['pages', 'blogposts'] as const) { - const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/${endpoint}/${encodeURIComponent(externalId)}?body-format=${bodyFormat}&include-labels=true` - const response = await fetchWithRetry(url, { + const contentUrl = (endpoint: 'pages' | 'blogposts') => + `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/${endpoint}/${encodeURIComponent(externalId)}` + const fetchContent = (url: string) => + fetchWithRetry(url, { method: 'GET', headers: { Accept: 'application/json', Authorization: `Bearer ${accessToken}`, }, }) + for (const endpoint of ['pages', 'blogposts'] as const) { + const response = await fetchContent( + `${contentUrl(endpoint)}?body-format=${bodyFormat}&include-labels=true` + ) if (response.ok) { page = await response.json() @@ -919,7 +930,21 @@ export const confluenceConnector: ConnectorConfig = { } const rawContent = representation.value const scoped = scopedContent ? extractConfluenceStorageText(rawContent) : null - const plainText = scoped ? scoped.text : confluenceViewToPlainText(rawContent) + let plainText = scoped ? scoped.text : confluenceViewToPlainText(rawContent) + if (!scoped && mayHoldOpticsHtmlMacro(rawContent, plainText)) { + const endpoint = contentType === 'page' ? 'pages' : 'blogposts' + const response = await fetchContent(`${contentUrl(endpoint)}?body-format=storage`) + if (response.status === 401) throw await createRetryableHttpError(response) + if (!response.ok) { + throw new Error(`Failed to get Confluence storage body: ${response.status}`) + } + const storagePage = (await response.json()) as { body?: { storage?: { value?: unknown } } } + const storage = storagePage.body?.storage?.value + if (typeof storage !== 'string') { + throw new Error('Confluence content is missing its storage body') + } + plainText = [plainText, extractOpticsHtmlMacroText(storage)].filter(Boolean).join(' ') + } const links = page._links as Record | undefined const stub = pageToStub( diff --git a/apps/sim/connectors/gitlab/permission-config/prepare.test.ts b/apps/sim/connectors/gitlab/permission-config/prepare.test.ts new file mode 100644 index 00000000000..b29bc99d033 --- /dev/null +++ b/apps/sim/connectors/gitlab/permission-config/prepare.test.ts @@ -0,0 +1,96 @@ +import { + knowledgeSecureFetchMock, + knowledgeSecureFetchMockFns, +} from '@sim/testing/mocks/knowledge-secure-fetch.mock' +import { getMockLogger } from '@sim/testing/mocks/logger.mock' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@/lib/knowledge/documents/secure-fetch.server', () => knowledgeSecureFetchMock) + +import { OutboundRoutingError } from '@/lib/core/network/routing' +import { EGRESS_UNAVAILABLE_MESSAGE } from '@/lib/core/orchestration/types' +import { prepareGitLabPermissionChange } from '@/connectors/gitlab/permission-config/prepare' + +const fetchSource = knowledgeSecureFetchMockFns.mockSecureFetchWithRetry +const input = { + connectorType: 'gitlab', + accessMode: 'admin', + sourceConfig: { host: 'gitlab.example.com', project: 'group/project' }, + apiKey: 'test-private-token', +} + +describe('GitLab setup failures', () => { + it.each([ + { operation: 'account', status: 401, action: /token.*read_api/i }, + { operation: 'account', status: 404, action: /host.*API access/i }, + { operation: 'project', status: 403, action: /read_api.*access.*IP restrictions/i }, + { operation: 'project', status: 404, action: /project ID.*token access.*IP restrictions/i }, + ])( + 'identifies a $status during the $operation check without exposing provider content', + async ({ operation, status, action }) => { + if (operation === 'project') { + fetchSource.mockResolvedValueOnce(Response.json({ id: 1, state: 'active' })) + } + fetchSource.mockResolvedValueOnce( + new Response('Private upstream error page', { + status, + headers: { 'x-request-id': '01JEXAMPLECORRELATION' }, + }) + ) + + const result = prepareGitLabPermissionChange(input) + await expect(result).rejects.toMatchObject({ + code: 'validation', + message: expect.stringMatching(action), + }) + await expect(result).rejects.toMatchObject({ + message: expect.not.stringMatching( + /test-private-token|Private upstream|group\/project|gitlab\.example/ + ), + }) + const logs = getMockLogger('GitLabPermissions').warn.mock.calls + expect(logs).toEqual([ + [ + 'GitLab permission read failed', + { + operation, + status, + providerRequestId: '01JEXAMPLECORRELATION', + }, + ], + ]) + expect(fetchSource).toHaveBeenCalledTimes(operation === 'project' ? 2 : 1) + } + ) + + it.each([undefined, 'untrusted header text', 'x'.repeat(129)])( + 'omits absent or unsafe upstream correlation IDs (%s)', + async (requestId) => { + fetchSource.mockResolvedValueOnce( + new Response(null, { + status: 404, + headers: requestId ? { 'x-request-id': requestId } : undefined, + }) + ) + await expect(prepareGitLabPermissionChange(input)).rejects.toThrow() + expect(getMockLogger('GitLabPermissions').warn).toHaveBeenCalledWith( + 'GitLab permission read failed', + { operation: 'account', status: 404 } + ) + } + ) + + it('preserves an egress outage instead of blaming the GitLab credential', async () => { + fetchSource.mockRejectedValueOnce(new OutboundRoutingError('GATEWAY_UNAVAILABLE')) + await expect(prepareGitLabPermissionChange(input)).rejects.toMatchObject({ + code: 'unavailable', + message: EGRESS_UNAVAILABLE_MESSAGE, + }) + }) + + it('keeps a missing internal routing scope out of GitLab validation errors', async () => { + const error = new OutboundRoutingError('MISSING_SCOPE') + fetchSource.mockRejectedValueOnce(error) + await expect(prepareGitLabPermissionChange(input)).rejects.toBe(error) + }) +}) diff --git a/apps/sim/connectors/gitlab/permission-config/prepare.ts b/apps/sim/connectors/gitlab/permission-config/prepare.ts index b695928cb3d..b1ea162d7a4 100644 --- a/apps/sim/connectors/gitlab/permission-config/prepare.ts +++ b/apps/sim/connectors/gitlab/permission-config/prepare.ts @@ -1,6 +1,7 @@ import { getErrorMessage } from '@sim/utils/errors' import { decryptApiKey, encryptApiKey } from '@/lib/api-key/crypto' -import { OrchestrationError } from '@/lib/core/orchestration/types' +import { OutboundRoutingError } from '@/lib/core/network/routing' +import { asOrchestrationError, OrchestrationError } from '@/lib/core/orchestration/types' import { loadGitLabPermissionSnapshot, type PreparedGitLabPermissions, @@ -70,6 +71,9 @@ export async function prepareGitLabPermissionChange(input: { : ''), input.sourceConfig ).catch((error: unknown) => { + const classified = asOrchestrationError(error) + if (classified) throw classified + if (error instanceof OutboundRoutingError) throw error throw new OrchestrationError( 'validation', getErrorMessage(error, 'Unable to validate the GitLab token and project.') diff --git a/apps/sim/connectors/gitlab/permissions.ts b/apps/sim/connectors/gitlab/permissions.ts index d20d3813842..6020342e6a3 100644 --- a/apps/sim/connectors/gitlab/permissions.ts +++ b/apps/sim/connectors/gitlab/permissions.ts @@ -1,3 +1,4 @@ +import { createLogger } from '@sim/logger' import { normalizeEmail } from '@sim/utils/string' import { groupToken, sortAccessTokens, userToken } from '@/lib/knowledge/access/tokens' import { secureFetchWithRetry } from '@/lib/knowledge/documents/secure-fetch.server' @@ -13,6 +14,8 @@ import { import type { ConnectorDirectory, ExternalDocument } from '@/connectors/types' import { normalizeGitLabHost } from '@/tools/gitlab/utils' +const logger = createLogger('GitLabPermissions') + const MAX_DIRECTORY_PAGES = 500 const PAGE_SIZE = 100 const MAX_RESPONSE_BYTES = 4 * 1024 * 1024 @@ -39,13 +42,14 @@ export async function validateGitLabCsvToken( signal?: AbortSignal ): Promise<{ host: string; projectId: number; projectPath: string }> { const { base, project } = sourceAddress(sourceConfig) - const viewer = await read(`${base}/user`, token, true, signal) + const viewer = await read(`${base}/user`, token, 'account', true, signal) if (viewer.state !== 'active' || viewer.locked === true || !Number.isSafeInteger(viewer.id)) { throw new Error('An active GitLab identity with read_api access is required') } const record = await read( `${base}/projects/${project}`, token, + 'project', true, signal ) @@ -113,6 +117,7 @@ function sourceAddress(sourceConfig: Record) { async function read( url: string, token: string, + operation: 'account' | 'project', validating = false, signal?: AbortSignal ): Promise { @@ -125,7 +130,34 @@ async function read( }, { ...(validating ? VALIDATE_RETRY_OPTIONS : {}), maxResponseBytes: MAX_RESPONSE_BYTES, signal } ) - if (!response.ok) throw new Error(`GitLab permission lookup failed (${response.status})`) + if (!response.ok) { + const requestId = response.headers.get('x-request-id') + logger.warn('GitLab permission read failed', { + operation, + status: response.status, + ...(requestId && /^[a-zA-Z0-9_-]{1,128}$/.test(requestId) + ? { providerRequestId: requestId } + : {}), + }) + if (response.status === 401) { + throw new Error('GitLab did not accept the token. Use a valid token with read_api scope.') + } + if (response.status === 403) { + throw new Error( + 'GitLab denied access. Check read_api scope, token access, and IP restrictions.' + ) + } + if (response.status === 404) { + throw new Error( + operation === 'project' + ? 'Could not access this GitLab project. Check the project ID or full path, token access, and IP restrictions.' + : 'Could not verify the GitLab account. Check the host and API access.' + ) + } + throw new Error( + `GitLab could not verify ${operation} access (HTTP ${response.status}). Try again.` + ) + } return (await response.json()) as T } @@ -136,7 +168,12 @@ export async function validateGitLabPermissionToken( ): Promise { await requireAdministrator(token, sourceConfig) const { base, project } = sourceAddress(sourceConfig) - const record = await read(`${base}/projects/${project}`, token, true) + const record = await read( + `${base}/projects/${project}`, + token, + 'project', + true + ) await discoverGitLabPermissionPolicy(token, sourceConfig, record, true) } @@ -146,7 +183,7 @@ async function requireAdministrator( signal?: AbortSignal ): Promise { const { base } = sourceAddress(sourceConfig) - const viewer = await read(`${base}/user`, token, true, signal) + const viewer = await read(`${base}/user`, token, 'account', true, signal) if (viewer.is_admin !== true || viewer.state !== 'active' || viewer.locked === true) { throw new Error( 'Mirror source permissions requires an active GitLab instance administrator token with read_api access' @@ -295,7 +332,7 @@ async function loadSnapshot( await requireAdministrator(token, config, signal) const { base, project } = sourceAddress(config) const [record, users, members] = await Promise.all([ - read(`${base}/projects/${project}`, token, false, signal), + read(`${base}/projects/${project}`, token, 'project', false, signal), listAll( `${base}/users?pagination=keyset&order_by=id&sort=asc`, token, @@ -347,7 +384,13 @@ export async function openGitLabDirectory( } } const { tenant, base, project } = sourceAddress(config) - const identity = await read<{ id: number }>(`${base}/projects/${project}`, token, false, signal) + const identity = await read<{ id: number }>( + `${base}/projects/${project}`, + token, + 'project', + false, + signal + ) if (!Number.isInteger(identity.id)) throw new Error('GitLab did not return a project identity') const groups = FEATURES.map((feature) => ({ id: groupId(identity.id, feature) })) let pending: Promise | undefined diff --git a/apps/sim/content/library/ai-agent-identity-credentials-audit-trails-enterprise-guide/index.mdx b/apps/sim/content/library/ai-agent-identity-credentials-audit-trails-enterprise-guide/index.mdx new file mode 100644 index 00000000000..6b96fe54eea --- /dev/null +++ b/apps/sim/content/library/ai-agent-identity-credentials-audit-trails-enterprise-guide/index.mdx @@ -0,0 +1,261 @@ +--- +slug: ai-agent-identity-credentials-audit-trails-enterprise-guide +title: 'AI Agent Identity, Credential Management, and Audit Trails: Enterprise Guide' +description: 'Learn how to govern AI agent identities, scope credentials, enforce approvals, and preserve audit trails for enterprise security reviews.' +seoTitle: 'AI Agent Identity and Audit Trails Guide' +date: 2026-11-16 +updated: 2026-11-16 +authors: + - andrew +readingTime: 11 +tags: [AI Agents, Enterprise Security, Identity Governance, Audit Logs, Sim] +ogImage: /library/ai-agent-identity-credentials-audit-trails-enterprise-guide/cover.jpg +draft: false +faq: + - q: "ai agent identity governance enterprise 2026" + a: "AI agent identity governance in 2026 means assigning every production agent a stable machine identity, accountable owners, least-privilege credentials, environment boundaries, approval policies, and audit records linked to individual runs." + - q: "ai agent security vendors agent identity api keys service accounts audit 2026" + a: "AI agent security vendors should be evaluated on whether they replace shared API keys with per-agent service accounts, restrict credential use, preserve owner and run attribution, and export structured audit evidence for investigation." + - q: "how much do enterprise ai automation platforms charge for centralized audit logs and siem integrations?" + a: "Pricing varies by vendor and deployment. Buyers should request a written November 2026 quote covering platform fees, log volume, retention, export, SIEM ingestion, implementation, and support instead of comparing license price alone." + - q: "Which enterprise AI agent platforms support SSO and governance?" + a: "Sim fits an enterprise AI agent platform shortlist when teams need SSO, SCIM, access control, credential groups, audit logs, data retention, and data drains, but buyers should evaluate human identity and agent identity as separate control planes." + - q: "which ai agent platform is easiest to get through security review" + a: "Sim can simplify evidence gathering when its deployment model and enterprise controls match the organization’s requirements. The easiest AI agent platform to approve is the one that demonstrates unique attribution, least privilege, approval enforcement, structured audit export, and acceptable license and deployment terms in the buyer’s own test." + - q: "What is the difference between human identity and AI agent identity?" + a: "Human identity governs who can build, change, approve, deploy, or invoke an agent, while AI agent identity governs what the machine actor itself can access and do in connected systems." + - q: "Does every AI agent need its own service account?" + a: "Every production AI agent should have its own service account where the connected system supports one, because separate identities improve attribution, least privilege, rotation, revocation, and incident containment." + - q: "Can an approval step replace least-privilege credentials?" + a: "An approval step cannot replace least-privilege credentials because the agent should remain technically unable to exceed its authorized scope even after a human approves one action." + - q: "How long should AI agent audit logs be retained?" + a: "AI agent audit logs should be retained for the period required by the organization’s incident-response, legal, contractual, and regulatory policies, with stricter access and redaction controls for records containing sensitive data." + - q: "Is n8n open source?" + a: "n8n uses the fair-code Sustainable Use License for most source code as of November 2026, with separate proprietary licenses for enterprise code." +--- + +## TL;DR + +AI agent identity governance separates human access from machine access. SSO and SCIM govern the people who build and operate agents, while a unique identity, scoped credentials, and run-level audit records govern what each agent can do. + +The safest enterprise pattern is to give every production agent a stable identity, assign an accountable human or team owner, provide separate credentials for each tool and environment, and record every consequential action against the agent, owner, credential, and run. Shared tokens weaken attribution and make rotation, revocation, and least-privilege enforcement harder. + +## How do I centralize identity for agents with SSO and SCIM without giving every agent a shared token? + +Centralized AI agent identity uses SSO and SCIM for human users but gives each agent its own machine identity and scoped credentials instead of inheriting a shared human token. + +Treat the system as two connected identity planes: + +| Identity plane | What it governs | Recommended control | +|---|---|---| +| Human identity | Who can create, change, approve, deploy, or run an agent | SSO, SCIM, role-based access, access reviews, and separation of duties | +| Agent identity | What a deployed agent can access and perform | Unique agent ID, dedicated service accounts, scoped credentials, environment boundaries, and action policies | + +A practical identity record for every production agent should include: + +- A unique, immutable agent identifier +- A readable name that reflects the agent’s job +- A named business owner and technical owner +- The production environment and risk classification +- The service accounts and credentials assigned to it +- The tools, data stores, and actions it may access +- The approval policy for sensitive actions +- The date of its latest access review +- A status such as development, active, suspended, or retired + +This model lets IT disable a person through SCIM without breaking unrelated agents. It also lets security suspend one agent without revoking a shared token and interrupting every automation that uses it. + +For broader human access and workspace controls, see [Best Enterprise AI Agent Platforms in 2026: SSO, SCIM, RBAC, and Audit Logs](https://www.sim.ai/library/best-ai-agent-platforms-for-enterprise-teams-2026). For ownership across departments, see [Governing AI Agents Built by Different Teams in One Enterprise Workspace](https://www.sim.ai/library/govern-ai-agents-multiple-teams-enterprise-workspace). + +## Why do shared API keys fail for enterprise AI agents? + +Shared API keys fail for enterprise AI agents because they obscure which agent performed an action and force unrelated agents to share the same permissions, rotation schedule, and blast radius. + +If ten agents use one CRM token, the CRM may record only the shared integration user. Investigators can see that the integration changed a record, but they may not be able to determine which agent initiated the request, which workflow version was active, who owned it, or which run produced the change. + +Shared credentials also create operational coupling. Rotating a compromised key can disable every dependent agent, while granting one agent a new permission silently grants it to all other agents using the same credential. + +Use a shared credential only when the connected system cannot issue separate service accounts and the residual risk is documented. In that exception case, add compensating controls such as an internal credential broker, strict action allowlists, short credential lifetimes, approval gates, and complete run-level logging. + +## How should enterprises assign per-agent identities and service accounts? + +Per-agent identities should map one production agent to one stable machine identity in every connected system that supports service accounts or workload identities. + +The agent’s display name can change, but its immutable ID should remain stable so historical records continue to resolve correctly. Use a naming convention that carries enough context for administrators to recognize the workload, such as `production-salesforce-renewal-agent`, without placing secrets or personal data in the name. + +Assign ownership at two levels: + +1. The business owner approves the purpose, data access, and acceptable actions. +2. The technical owner maintains credentials, integrations, deployment settings, and incident response. + +Avoid creating service accounts under an employee’s personal identity. Personal accounts create continuity problems when someone changes roles or leaves the company, and they make it harder to distinguish human activity from autonomous agent activity. + +## How should AI agent credentials be scoped by tool and environment? + +AI agent credentials should be scoped separately for each agent, connected tool, environment, and permission set so that one compromise cannot unlock unrelated systems. + +A production support agent that reads tickets and drafts replies does not need the same credential as an agent that refunds payments. Development credentials should not reach production data, and read-only tasks should not receive write permissions. + +Apply these boundaries: + +- **Agent boundary:** Do not reuse one token across unrelated agents. +- **Tool boundary:** Issue separate credentials for the CRM, ticketing system, database, and messaging platform. +- **Environment boundary:** Separate development, staging, and production credentials. +- **Action boundary:** Prefer specific read, create, update, or delete scopes over broad administrator access. +- **Data boundary:** Restrict records, folders, projects, accounts, or database schemas where the provider supports it. +- **Time boundary:** Use short-lived credentials or workload identity federation where available. + +Model Context Protocol (MCP), a standard for connecting AI agents to external tools, requires the same controls. An MCP server can expose several tools behind one connection, so its authorization policy must restrict both which tools an agent can discover and which actions it can invoke. See [MCP Security: A Practical Guide to Secure MCP Server Development](https://www.sim.ai/library/mcp-security). + +## How should enterprises store, rotate, and revoke AI agent secrets? + +Enterprise secret management should keep AI agent credentials out of prompts, workflow definitions, source code, logs, and copied configuration files. + +Store secrets in the platform’s credential store or an approved external secret manager. Workflow definitions should reference a credential by identifier rather than contain its plaintext value. + +A rotation process should record: + +- The credential owner +- The agents and environments that depend on it +- The issuing system and granted scopes +- The creation, expiration, and last-rotation dates +- The rotation procedure and rollback path +- The emergency revocation contact + +Rotation should be testable without exposing the secret. Issue the replacement, validate it in the intended environment, update the reference, monitor failures, and revoke the old credential after the transition window. High-risk credentials should also be revocable immediately through a documented kill-switch procedure. + +## How do approval gates reduce the risk of sensitive AI agent actions? + +Human approval gates reduce AI agent risk by pausing a run before a consequential action and requiring an authorized person to review the proposed operation. + +Good approval points include sending payments, issuing refunds, changing permissions, deleting records, sharing regulated data, executing production changes, and contacting large customer lists. The approval request should show the proposed action, affected system, relevant inputs, expected impact, requesting agent, run ID, and expiration time. + +In Sim, the [Human in the Loop block](https://docs.sim.ai/workflows/blocks/human-in-the-loop) pauses the run and resumes it with submitted form fields. An approve-or-reject field does not enforce the decision by itself; a downstream Condition must check the submitted value and route rejected requests away from the sensitive action. For implementation patterns, see [What Is Human-in-the-Loop in AI Agents?](https://www.sim.ai/library/what-is-human-in-the-loop-in-ai-agents). + +Approval does not replace least privilege. The agent should still have only the permissions needed to execute an approved action, and the audit trail should preserve both the proposed action and the approver’s decision. + +## What should an AI agent audit trail record for every run? + +An AI agent audit trail should connect every material action to a stable agent identity, accountable owner, workflow version, credential reference, and unique run ID. + +At minimum, capture: + +| Audit field | Why it matters | +|---|---| +| Timestamp | Establishes the sequence of events | +| Agent ID and name | Identifies the machine actor | +| Business and technical owner | Establishes accountability | +| Environment | Distinguishes production from testing | +| Run ID | Connects related steps into one execution | +| Workflow version | Shows which logic was active | +| Trigger identity | Records the person, schedule, webhook, or system that started the run | +| Tool and action | Identifies the external operation attempted | +| Credential reference | Shows which credential was used without exposing its secret | +| Target resource | Identifies the affected record, file, account, or system | +| Approval decision | Records who approved or rejected a sensitive action | +| Outcome and error | Shows whether the operation succeeded, failed, or was blocked | +| Policy decision | Explains whether a control allowed or denied the action | + +Do not put plaintext secrets, complete authentication headers, unnecessary personal data, or unrestricted model inputs and outputs into audit records. Logs need their own access controls, retention policy, integrity protections, and redaction rules. + +Audit logs and execution traces serve different purposes. Audit logs establish who changed or authorized something; execution records explain what happened during a run. A defensible investigation usually needs both, linked by stable identifiers. See [What Is AI Agent Observability? Traces, Metrics, and Evals Explained](https://www.sim.ai/library/ai-agent-observability). + +## How should enterprises compare AI agent auditing tools? + +Enterprise buyers should compare AI agent auditing tools with a repeatable evidence test that covers attribution, retention, export, integrity, and investigation rather than relying on a generic “audit logs included” checkbox. + +Include the incumbent n8n in the shortlist alongside Sim and any platforms already approved by the organization, then run the same scenario in every product: + +1. Provision two agents with different owners and credentials. +2. Let both agents call the same external application. +3. Require approval for one high-risk action. +4. Change one agent’s configuration and rotate its credential. +5. Export the resulting records to the organization’s logging pipeline. +6. Ask an investigator to identify the agent, initiating user or trigger, approver, credential reference, workflow version, external action, and outcome. + +Evaluate the evidence across these criteria: + +| Criterion | Pass condition | +|---|---| +| Unique attribution | Every tested action resolves to one agent and one run | +| Human attribution | Administrative changes and approvals resolve to a human identity | +| Credential provenance | Records identify the credential reference without leaking the secret | +| Version history | Investigators can identify the deployed workflow version | +| Sensitive-action evidence | The proposal, decision, approver, and final action remain linked | +| Export quality | Structured records retain IDs, timestamps, outcomes, and policy decisions | +| SIEM compatibility | Records can reach the organization’s logging pipeline in the required format | +| Retention and integrity | Retention, access, deletion, and tamper resistance meet policy | +| Investigation speed | An analyst can reconstruct the scenario without joining ambiguous manual records | + +As of November 2026, [Sim’s core is licensed under Apache 2.0](https://github.com/simstudioai/sim/blob/main/LICENSE), while SSO, SCIM, access control, credential groups, audit logs, data retention, and data drains are covered by the [separate Sim Enterprise License](https://github.com/simstudioai/sim/blob/main/apps/sim/ee/LICENSE). That enterprise code is free for development, testing, and internal non-production use, while production use requires an active Sim Enterprise subscription. As of November 2026, [n8n describes its Sustainable Use License as a fair-code license](https://docs.n8n.io/n8n-community-license), with separate proprietary licenses for enterprise code. License terms do not determine audit quality, but they affect deployment, modification, and security-review decisions. + +## What software can assign unique AI agent identity names and manage them at scale? + +AI agent platforms, identity governance systems, cloud workload-identity services, and enterprise secret managers can jointly manage unique agent identities at scale, but buyers should distinguish a readable agent name from an enforceable machine identity. + +A platform qualifies only if it maintains a stable identifier after renaming, associates the identity with owners and environments, restricts credential access, records configuration changes, and exports enough metadata for investigation. A name field alone is not identity governance. + +For each shortlisted product, ask the vendor to demonstrate: + +- Creating two agents with different immutable IDs and owners +- Assigning different credentials to each agent +- Preventing one agent from reading or using the other agent’s credential +- Suspending one agent without disabling the other +- Rotating one credential without editing unrelated agents +- Finding every run and external action performed by a retired agent +- Exporting identity and action records in a structured format + +## How does Sim support AI agent identity, credentials, approvals, and auditing? + +Sim fits teams that need an enterprise workspace for human access controls, credential governance, approval steps, audit records, retention policies, and security data exports. Connected systems remain responsible for issuing and enforcing their own service-account permissions. + +Sim is the open-source AI workspace where teams build, deploy, and manage AI agents. [Sim Enterprise](https://docs.sim.ai/platform/enterprise) includes SSO, directory provisioning through SCIM, permission groups, audit logs, data retention, and data drains. Sim’s core uses Apache 2.0, while these enterprise capabilities use the [separate Sim Enterprise License](https://github.com/simstudioai/sim/blob/main/apps/sim/ee/LICENSE); production use of that enterprise code requires an active Sim Enterprise subscription. + +[Sim credential groups](https://docs.sim.ai/platform/connected-accounts) can help administrators govern credential access, but credential groups are not a substitute for creating distinct service accounts and least-privilege scopes in Salesforce, GitHub, Slack, databases, or other connected systems. The external system ultimately decides what its token or workload identity can do. + +[Sim Enterprise audit logs](https://docs.sim.ai/platform/enterprise/audit-logs) record configuration and security events, while [data drains](https://docs.sim.ai/platform/enterprise/data-drains) export retained data to a destination the organization controls. Security teams should map exported records to agent and workflow run identifiers in their logging architecture, then test the complete investigation path in the destination SIEM. Destination-specific fields, delivery behavior, retention, and alert rules should be included in the acceptance test rather than inferred from the existence of an integration. + +## What checklist should buyers use to evaluate AI agent identity and audit controls? + +An enterprise AI agent identity review should require demonstrated evidence for every control below before a platform receives production approval. + +### Identity and ownership + +AI agent identity controls should make every production agent uniquely identifiable and accountable to named owners. + +- Does every agent have an immutable identifier? +- Can names change without breaking historical attribution? +- Are business and technical owners mandatory? +- Can one agent be suspended without disrupting others? +- Are development, staging, and production identities separated? + +### Credentials and least privilege + +AI agent credential controls should prevent unrelated agents from sharing broad, long-lived access. + +- Can administrators restrict which agents may use each credential? +- Can every connected system use a dedicated service account? +- Are tool, action, data, and environment scopes supported? +- Are secrets excluded from workflow definitions and logs? +- Can credentials be rotated and revoked without editing unrelated agents? + +### Sensitive actions + +AI agent approval controls should stop consequential operations until an authorized person makes an explicit decision. + +- Can the run pause before the external action occurs? +- Does the reviewer see the proposed action and affected resource? +- Is the approver authenticated and authorized? +- Does rejection route away from the sensitive action? +- Are expired and abandoned approvals handled safely? + +### Audit and investigation + +AI agent audit controls should let an investigator reconstruct a run without guessing which machine actor used a shared token. + +- Do records link the agent, owner, trigger, version, run, credential reference, action, and outcome? +- Are configuration changes attributed to human identities? +- Are approval requests and decisions preserved? +- Can logs be exported in a structured format to the required SIEM? +- Are retention, redaction, integrity, and access policies configurable? +- Can the security team complete a test investigation within its response target? diff --git a/apps/sim/content/library/apache-2-0-vs-fair-code/index.mdx b/apps/sim/content/library/apache-2-0-vs-fair-code/index.mdx index 5c711a3bc76..52dd090da19 100644 --- a/apps/sim/content/library/apache-2-0-vs-fair-code/index.mdx +++ b/apps/sim/content/library/apache-2-0-vs-fair-code/index.mdx @@ -109,6 +109,8 @@ faq: a: "Apache 2.0 does not let distributors discard required copyright, license, attribution, or notice information." - q: "Which license is better for self hosting, Apache 2.0 or n8n's Sustainable Use License?" a: "Apache 2.0 fits self-hosting use cases that need broad rights to modify, redistribute, embed, or commercialize covered software, while n8n’s Sustainable Use License fits uses within its commercial restrictions." + - q: "Which self-hosted AI agent platforms have a permissive license instead of fair-code?" + a: "Sim (Apache 2.0 core), Langflow (MIT), CrewAI (MIT), Activepieces (MIT core), Kestra (Apache 2.0), Node-RED (Apache 2.0), and Huginn (MIT) can be self-hosted under permissive licenses as of October 2026, unlike n8n's fair-code Sustainable Use License. Flowise's repository is also Apache 2.0 but has been archived since the project reached end of life on August 31, 2026. Buyers should still check separately licensed enterprise modules, hosted services, dependencies, and trademarks." --- Fair-code software makes its source available while reserving restrictions that OSI-approved open-source licenses do not permit. As of November 2026, n8n uses the source-available Sustainable Use License rather than an OSI-approved open-source license, while [Sim’s core uses Apache License 2.0](https://github.com/simstudioai/sim/blob/main/LICENSE) with [enterprise code in `apps/sim/ee` governed separately by the Sim Enterprise License](https://github.com/simstudioai/sim/blob/main/apps/sim/ee/LICENSE). diff --git a/apps/sim/content/library/best-ai-agent-marketplaces-template-libraries/index.mdx b/apps/sim/content/library/best-ai-agent-marketplaces-template-libraries/index.mdx index 210f6ac96f9..e5fbe5c2315 100644 --- a/apps/sim/content/library/best-ai-agent-marketplaces-template-libraries/index.mdx +++ b/apps/sim/content/library/best-ai-agent-marketplaces-template-libraries/index.mdx @@ -66,6 +66,16 @@ faq: a: "Sim reduces the work needed to create common agent patterns, but production deployment still requires someone to understand credentials, data access, testing, errors, and maintenance." - q: "Do catalog-approved templates still need internal review?" a: "Catalog-approved templates still need internal security, data-access, credential, testing, and deployment review before an organization uses them in production." + - q: "When do AI agent templates save time?" + a: "Sim templates save time when their integrations, workflow structure, and intended outcome already resemble the buyer’s requirements closely enough that adaptation is faster than designing from scratch." + - q: "When should I avoid using an AI agent template?" + a: "Sim recommends avoiding a template when its behavior is opaque, its permissions are excessive, its dependencies are outdated, or auditing it would take longer than building a smaller workflow directly." + - q: "Does Sim offer editable AI agent templates?" + a: "Sim offers templates as editable starting points that teams can adapt in the workflow builder before deploying an agent." + - q: "Who maintains an AI agent template after deployment?" + a: "The adopting team usually remains responsible for its deployed agent even when a marketplace publisher or platform continues maintaining the original template." + - q: "How do I evaluate trust in an AI agent marketplace?" + a: "Sim recommends evaluating publisher identity, visible logic, requested permissions, update history, dependency health, documentation, and the ability to test a template before production use." --- ## TL;DR diff --git a/apps/sim/content/library/best-ai-agent-platforms-2026/index.mdx b/apps/sim/content/library/best-ai-agent-platforms-2026/index.mdx index 38cd3311159..4f2ede26c52 100644 --- a/apps/sim/content/library/best-ai-agent-platforms-2026/index.mdx +++ b/apps/sim/content/library/best-ai-agent-platforms-2026/index.mdx @@ -51,6 +51,40 @@ faq: a: "Make and Zapier can incorporate AI into automations, but both products remain broader SaaS automation platforms rather than agent-native development workspaces." - q: "Which AI agent platform is best for human approval workflows?" a: "Sim fits human approval workflows because Human in the Loop can pause a run, collect form fields, and resume execution, with a downstream Condition used to enforce approve-or-reject routing." + - q: "What is the best self-hosted AI agent platform?" + a: "Sim fits teams that want a self-hosted AI agent platform because its core uses the OSI-approved Apache 2.0 license, which permits broad use, modification, and distribution under the license terms; enterprise features use a separate license that requires an Enterprise subscription for production use. n8n and Dify can also be self-hosted under their own license terms." + - q: "Can n8n be self-hosted?" + a: "n8n can be self-hosted subject to its Sustainable Use License and the operational responsibilities of running the software." + - q: "What is the difference between Sim and n8n?" + a: "Sim focuses on visual AI agent workflows with an Apache 2.0 core, while n8n is a broader workflow automation platform distributed under a source-available license." + - q: "Is Sim better than n8n for AI agents?" + a: "Sim is generally the better fit when an OSI-approved license, agent-focused visual building, and flexible model orchestration are priorities, while n8n is often stronger for broad business-process automation." + - q: "What is the difference between Sim and Zapier Agents?" + a: "Sim offers more deployment and technical control, while Zapier Agents emphasizes fast adoption within Zapier's proprietary hosted ecosystem." + - q: "What is the difference between Sim and Gumloop?" + a: "Sim combines visual agent building with self-hosting of its Apache 2.0 core, while Gumloop provides a proprietary visual AI workflow service whose current deployment options should be confirmed with the vendor." + - q: "What is the difference between Sim and Make?" + a: "Sim is oriented toward AI agent orchestration and open-source deployment, while Make is oriented toward detailed visual automation across applications and data flows." + - q: "What is the best n8n alternative for AI agents?" + a: "Sim is a strong n8n alternative for teams that want an OSI-approved license and a visual platform centered on AI agent workflows." + - q: "How should a team compare AI agent platform pricing?" + a: "Sim and competing platforms should be compared using expected production volume across platform usage, model tokens, execution or task units, connectors, storage, observability, infrastructure, governance requirements, and operating labor rather than entry-level subscription prices alone." + - q: "What is the best AI agent builder in 2026?" + a: "Sim fits teams that want a visual workflow builder with tool use, branching, human input, model choice, and flexible deployment, while Zapier Agents and Gumloop fit simpler hosted builds and LangGraph fits developers who want code-first orchestration." + - q: "What is the best agentic workflow builder?" + a: "Sim fits teams that want to coordinate models, tools, conditions, and human input across multi-step agent runs, while n8n fits teams whose agents are one step inside broader integration-heavy automation." + - q: "What is the best open-source AI agent platform?" + a: "Sim fits teams seeking an open-source AI agent platform because Sim's core uses the OSI-approved Apache 2.0 license and can be self-hosted, although apps/sim/ee uses the separate Sim Enterprise License; n8n is source-available and Dify uses a modified Apache 2.0 license." + - q: "Can Sim be self-hosted?" + a: "Sim can be self-hosted, and any self-hosted Sim deployment can connect to local models through Ollama, vLLM, LM Studio, or LiteLLM." + - q: "Is Sim better than Zapier for AI agents?" + a: "Sim is better than Zapier for multi-step AI agents that need model choice, stateful orchestration, self-hosting, and deeper control, while Zapier is stronger for straightforward SaaS automation." + - q: "Is Sim better than Gumloop?" + a: "Sim is better than Gumloop when self-hosting, source access, model flexibility, and deployment control matter, while Gumloop can be preferable for teams seeking a fully managed and approachable cloud experience." + - q: "Is Dify better than Sim for RAG?" + a: "Dify can be preferable for teams focused narrowly on retrieval-augmented generation and prompt applications, while Sim is stronger for agents that coordinate RAG with tools, business systems, branching, and human input." + - q: "What should teams look for in an AI agent platform?" + a: "Sim recommends evaluating agent orchestration, model flexibility, integrations, human review, observability, deployment choices, licensing, security, and the billing unit that scales with production use." --- **Sim fits teams that want a visual workflow builder, multi-model flexibility, and self-hosting in one open-source AI workspace; Sim's core uses Apache 2.0, while `apps/sim/ee` uses the separate [Sim Enterprise License](https://github.com/simstudioai/sim/blob/main/apps/sim/ee/LICENSE) and requires an active Enterprise subscription for production use.** diff --git a/apps/sim/content/library/best-ai-agents-invoice-processing-finance-reconciliation-2026/index.mdx b/apps/sim/content/library/best-ai-agents-invoice-processing-finance-reconciliation-2026/index.mdx index b4334236fce..108fe66f9a5 100644 --- a/apps/sim/content/library/best-ai-agents-invoice-processing-finance-reconciliation-2026/index.mdx +++ b/apps/sim/content/library/best-ai-agents-invoice-processing-finance-reconciliation-2026/index.mdx @@ -63,6 +63,26 @@ faq: a: "Finance AI agents should not autonomously approve payments because accountable employees should apply the organization’s authorization thresholds and separation-of-duties controls." - q: "Can finance AI agents be self-hosted?" a: "Sim and n8n can be self-hosted, although their licenses, enterprise features, maintenance requirements, and deployment responsibilities differ." + - q: "Can an AI agent reconcile invoices against purchase orders and receipts?" + a: "Sim can coordinate three-way matching by retrieving invoice, purchase-order, and receipt data, applying deterministic tolerances, and routing unmatched or ambiguous items for review." + - q: "What invoice anomalies should an AI agent flag?" + a: "Sim can flag duplicate invoices, changed bank details, unexpected currencies, unusual totals, missing purchase orders, tax inconsistencies, arithmetic errors, out-of-period dates, split invoices, and deviations from prior vendor behavior." + - q: "Should a finance team build an invoice agent or buy an AP system?" + a: "Sim is a better fit when the process requires custom cross-system logic and AI reasoning, while a dedicated accounts-payable system is a better fit when standardized supplier, tax, payment, and ERP functionality is the primary requirement." + - q: "Can AI agents automate invoice processing?" + a: "Finance AI agents can automate invoice intake, field extraction, validation, matching, exception routing, approval requests, approved system writes, and evidence retention." + - q: "Can AI agents automate month-end reconciliation?" + a: "Finance AI agents can automate month-end data collection, normalization, deterministic comparison, exception queues, and review routing while accountable employees retain control of consequential writes." + - q: "Can AI agents create financial reports automatically?" + a: "Finance AI agents can prepare financial reports automatically, but finance teams should validate metric definitions and data-quality exceptions and approve final reports before distribution." + - q: "Can AI agents automate revenue reporting from Stripe?" + a: "Finance AI agents can automate revenue-report preparation by combining Stripe transactions and subscriptions with CRM account context and database product or usage data." + - q: "What finance tasks need human-in-the-loop approval?" + a: "Finance AI agents need human-in-the-loop approval for payments, vendor bank-detail changes, material journal entries, policy exceptions, consequential system writes, and final financial-statement distribution." + - q: "How do finance teams audit an AI agent’s actions?" + a: "Finance teams audit an AI agent’s actions by retaining immutable or exportable run evidence that connects source inputs, transformations, model outputs, tool calls, reviewer decisions, writes, retries, and reconciliation results." + - q: "Are AI agents safe for financial data?" + a: "Finance AI agents can handle financial data only when teams apply least-privilege credentials, separation of duties, access controls, evidence retention, failure handling, and deployment controls appropriate to their organization." --- ## TL;DR diff --git a/apps/sim/content/library/can-ai-agents-talk-to-each-other-multi-agent-communication-explained/index.mdx b/apps/sim/content/library/can-ai-agents-talk-to-each-other-multi-agent-communication-explained/index.mdx index 3abed950a01..e5492848cfd 100644 --- a/apps/sim/content/library/can-ai-agents-talk-to-each-other-multi-agent-communication-explained/index.mdx +++ b/apps/sim/content/library/can-ai-agents-talk-to-each-other-multi-agent-communication-explained/index.mdx @@ -39,6 +39,30 @@ faq: a: "The simplest multi agent architecture uses one coordinator agent, one specialist agent, a structured task contract, and a defined result or failure path." - q: "Can agents from different vendors communicate with each other?" a: "Agents from different vendors can communicate when both sides support compatible APIs, message schemas, or standards such as A2A, and when their authentication and task models are aligned. A protocol can standardize the exchange, but teams still need compatible permissions, data contracts, and failure handling." + - q: "What is A2A in AI agents?" + a: "A2A is an agent-to-agent protocol for discovering independent agents and exchanging messages, tasks, status updates, artifacts, and results between them." + - q: "What is MCP in AI agents?" + a: "MCP is the Model Context Protocol, a standard interface through which AI applications and agents can access tools, resources, prompts, and contextual data." + - q: "Is A2A a replacement for MCP?" + a: "A2A is not a replacement for MCP because A2A handles agent delegation and MCP handles access to tools and context." + - q: "Can A2A and MCP be used together?" + a: "A2A and MCP can be used together when an agent receives delegated work through A2A and uses MCP tools or resources to complete that work." + - q: "Does an agent handoff require A2A?" + a: "An agent handoff does not require A2A when the agents run inside the same orchestrated workflow, but A2A is useful across independent agent services and organizational boundaries." + - q: "What information should pass during an agent handoff?" + a: "An agent handoff should pass the task, minimum required context, output contract, authorization scope, provenance, deadline, and correlation identifiers." + - q: "How do you secure agent-to-agent communication?" + a: "Agent-to-agent communication should use authenticated identities, scoped authorization, encrypted transport, input and output validation, audit logs, timeouts, and explicit approval for high-impact actions." + - q: "How can buyers verify A2A support?" + a: "Buyers can verify A2A support by checking first-party documentation for agent discovery, agent cards, protocol-defined tasks and messages, artifacts, status updates, authentication, and A2A client or server endpoints." + - q: "Is MCP an agent to agent protocol?" + a: "MCP is primarily a protocol for connecting AI applications to tools and context rather than a complete protocol for collaboration between independent agents." + - q: "Is a multi agent system better than one AI agent?" + a: "A multi agent system is better only when specialization, independent review, parallel work, or permission separation creates more value than the added latency and complexity." + - q: "Can Sim build multi agent systems?" + a: "Sim is the open-source AI workspace where teams build, deploy, and manage AI agents, including workflows that coordinate specialized agent steps and review paths." + - q: "When should you not use multiple AI agents?" + a: "Teams should not use multiple AI agents when one agent can complete the task with the same context and permissions because extra agents add latency, cost, and failure points." --- ## TL;DR diff --git a/apps/sim/content/library/glean-vs-dust-enterprise-ai/index.mdx b/apps/sim/content/library/glean-vs-dust-enterprise-ai/index.mdx new file mode 100644 index 00000000000..aabc092a83c --- /dev/null +++ b/apps/sim/content/library/glean-vs-dust-enterprise-ai/index.mdx @@ -0,0 +1,138 @@ +--- +slug: glean-vs-dust-enterprise-ai +title: 'Glean vs Dust: Which Enterprise AI Platform Should You Choose?' +seoTitle: 'Glean vs Dust: Enterprise AI Comparison' +description: 'Compare Glean and Dust for enterprise search, permission-aware knowledge access, configurable AI agents, deployment, governance, and workflow automation.' +date: 2026-11-16 +updated: 2026-11-16 +authors: + - andrew +readingTime: 9 +tags: [AI Agents, Enterprise AI, Enterprise Search, Comparisons, Sim] +ogImage: /library/glean-vs-dust-enterprise-ai/cover.jpg +draft: false +faq: + - q: "Can Glean and Dust be used together?" + a: "Glean and Dust can be used together, with Glean serving company-wide search and Dust serving selected team-level agents. The enterprise should avoid duplicating indexes and governance processes unless the additional capability justifies the operational cost." + - q: "How much do Glean and Dust cost?" + a: "Glean documents per-user licensing with usage-based elements, while Dust publishes hosted plans and offers custom Enterprise terms as of November 2026. A valid comparison must include required enterprise controls, connector scope, model usage, implementation, support, and the total number of users rather than comparing headline subscription prices alone." + - q: "How do Glean and Dust handle source-system permissions?" + a: "Glean is designed to mirror source-system permissions in enterprise search, while Dust controls agent access through configured connections, data sources, Spaces, and workspace permissions. Enterprises should test both products with real users and document-level access changes because connector availability alone does not prove permission fidelity." + - q: "Can Glean or Dust be self-hosted?" + a: "Glean documents customer-hosted deployments in an organization's AWS or Google Cloud account, while Dust publishes an MIT-licensed repository that engineering teams can inspect and evaluate. Buyers must confirm deployment responsibilities, feature coverage, upgrades, security, monitoring, and support for either approach." + - q: "Are Glean and Dust open source?" + a: "Dust publishes its public repository under the MIT License, while Glean provides a commercial enterprise service. Buyers should verify which hosted Dust features and enterprise controls are included in the public repository before treating the source code and commercial service as equivalent." + - q: "Dust vs Microsoft Copilot: which should an enterprise choose?" + a: "Dust fits configurable, model-flexible agents grounded in selected company data, while Microsoft 365 Copilot fits organizations prioritizing assistance across the Microsoft 365 environment. The decision should account for required non-Microsoft data sources, model control, identity architecture, and workflow depth." + - q: "Dust vs Writer: which should an enterprise choose?" + a: "Dust fits teams that want to assemble specialized agents from connected knowledge, models, instructions, and tools, while Writer fits enterprises seeking centrally governed agents, playbooks, and language controls. Buyers should compare exact agent-building, governance, deployment, and commercial requirements rather than treating both products as generic company chat." + - q: "Dust vs Copilot Studio: which should an enterprise choose?" + a: "Dust fits focused knowledge agents with flexible model and data configuration, while Microsoft Copilot Studio fits organizations building agents inside the Microsoft Power Platform ecosystem. Copilot Studio should be evaluated together with Power Automate when the use case requires substantial cross-system workflow logic." + - q: "Which platform is easier to pilot, Glean or Dust?" + a: "Dust can be scoped as a team-level agent pilot, while Glean is often evaluated as an enterprise search and knowledge program involving identity, permissions, and multiple systems. Pilot difficulty still depends on connector setup, security review, data quality, and the number of users included." +--- + +## TL;DR + +Glean fits enterprises that need company-wide, permissions-aware search and discovery across many business systems. Dust fits teams that want to configure AI agents around selected company knowledge, models, instructions, and tools. + +Both products extend beyond simple knowledge chat, so the decision is not strictly search versus agents. The practical difference is where each platform starts: Glean starts with enterprise-wide knowledge discovery and governance, while Dust starts with configurable agents for specific teams and use cases. + +## Glean vs Dust for enterprise AI: which should we choose? + +Choose Glean when the primary requirement is to help employees find information across many systems without bypassing source permissions. Its fit is a broad rollout in which search relevance, identity, permissions, and centralized administration matter more than deeply customized workflow logic. + +Choose Dust when the primary requirement is to let teams configure agents with specific instructions, models, data sources, and tools. Its fit is a focused rollout for teams that want greater control over agent behavior than a conventional enterprise search interface provides. + +Neither choice should be made from an agent demo alone. CIOs and Heads of AI should test permission fidelity, connector depth, answer citations, administrative controls, tool execution, auditability, deployment requirements, and total cost for the expected user population. + +## How do Glean and Dust compare for enterprise AI? + +Glean centers enterprise-wide search and permission-aware discovery. Dust centers flexible team-built agents grounded in selected company data. + +| Decision area | Glean | Dust | +|---|---|---| +| Core job | [Enterprise search](https://www.glean.com/enterprise-search), knowledge discovery, assistance, and agents across company systems | [Custom AI agents](https://docs.dust.tt/docs/user-documentation/getting-started/intro-to-dust) configured around instructions, models, data sources, and tools | +| Connectors | Connectors index content, mirror source permissions, and keep data current; evaluate each required system in Glean's [connector documentation](https://docs.glean.com/connectors/about) | Connections synchronize company tools, while other data sources and tools connected through Model Context Protocol (MCP) provide access to external services; evaluate the required sources in the [Dust data-source documentation](https://docs.dust.tt/docs/user-documentation/data-sources/overview) | +| Permission model | Designed to mirror source-system access controls when indexing and retrieving information | Uses connections, Spaces, and workspace roles to control which data agents and users can access; test the design for each source and workspace in the [Spaces documentation](https://docs.dust.tt/docs/user-documentation/admins/spaces-management) | +| Agent building | [Glean Agents](https://docs.glean.com/agents/overview/about-agents) combines instructions, knowledge, tools, context, and actions on top of Glean's enterprise knowledge layer | Dust lets builders select [instructions and tools](https://docs.dust.tt/docs/user-documentation/agents/create-your-first-agent), knowledge, and [models](https://docs.dust.tt/docs/user-documentation/agents/model-selection) for specialized agents | +| Deployment and data controls | Glean offers vendor-hosted and [customer-hosted deployments](https://docs.glean.com/get-started/prepare/about-deployment), with customer-hosted environments running in the buyer's AWS or Google Cloud account | Dust sells a hosted service and publishes an [MIT-licensed repository](https://github.com/dust-tt/dust/blob/main/LICENSE) that engineering teams can inspect; buyers should establish what operating that code would require | +| Pricing model | As of November 2026, Glean documents per-user licensing with pooled or metered usage elements in its [Enterprise Flex pricing model](https://docs.glean.com/glean-enterprise-flex-pricing) | As of November 2026, Dust publishes self-serve and custom Enterprise options on its [pricing page](https://dust.tt/home/pricing) | +| Fit | Large organizations prioritizing company-wide search, discovery, and centralized governance | Teams prioritizing configurable agents for defined knowledge-intensive jobs | +| Workflow boundary | Glean Agents can take actions and run on schedules or supported events, but buyers should test the exact orchestration controls their process requires | Dust supports tools, [schedules, and webhook triggers](https://docs.dust.tt/docs/user-documentation/agents/triggers), but buyers should test branching, approvals, retries, state, and execution monitoring for each process | + +The table reflects public vendor information available as of November 2026. Buyers should run permission and connector tests against their own systems because a listed integration does not prove that every object, field, access rule, or action required by the organization is supported. + +## What are the key facts about Glean and Dust? + +Glean and Dust differ most clearly in product center of gravity, deployment model, licensing, and billing. + +- Glean combines enterprise search with assistance and agents, so its knowledge index and permission model are central to the product. Glean documents both [vendor-hosted and customer-hosted deployment models](https://docs.glean.com/get-started/prepare/about-deployment). +- Dust publishes its repository under the [MIT License](https://github.com/dust-tt/dust/blob/main/LICENSE) and sells hosted access through self-serve and custom Enterprise options as of November 2026. +- Glean's [connectors](https://docs.glean.com/connectors/connectors-power-glean) feed a unified, permission-aware knowledge layer used by Search, Chat, Assistant, and Agents. +- Dust combines connected company data with configurable agents, so [agent instructions, model selection, data scopes, and tools](https://docs.dust.tt/docs/developer-platform/overview/developer-platform) are central to the product. + +A public repository does not automatically make customer-operated deployment simple or provide every capability of a vendor-hosted enterprise plan. Enterprises evaluating Dust should compare the exact repository features, deployment burden, support model, and hosted controls they require. + +## When should an enterprise choose Glean? + +Glean fits an enterprise that needs one permissions-aware discovery layer spanning many departments and systems. + +Glean's core proposition is that employees can search company information and receive answers without manually checking each connected application. The platform's [enterprise search product](https://www.glean.com/enterprise-search) is relevant when the buying committee prioritizes broad connector coverage, relevance, identity mapping, source permissions, and adoption across a large workforce. + +Glean also offers [Glean Agents](https://docs.glean.com/agents/overview/about-agents), so buyers should not treat it as search-only. Its agents can build on an enterprise knowledge foundation designed for organization-wide discovery, use tools, take actions, and run from supported schedules or events. + +Glean may be a weaker fit when the main requirement is to model a long operational process with specialized branches, approvals, retries, transformations, and writes across systems. Buyers with that requirement should benchmark workflow-oriented platforms separately rather than assuming an enterprise search purchase will replace one. + +## When should an enterprise choose Dust? + +Dust fits teams that need configurable agents for specific knowledge-intensive jobs and want control over each agent's instructions, models, data, and tools. + +Dust organizes connected information and agent access through [data sources](https://docs.dust.tt/docs/user-documentation/data-sources/overview) and [Spaces](https://docs.dust.tt/docs/user-documentation/admins/spaces-management). That structure can suit teams that want a research assistant, support agent, internal expert, or another role-specific agent without beginning with a company-wide search rollout. + +Dust's public [developer documentation](https://docs.dust.tt/docs/developer-platform/overview/developer-platform) and [repository](https://github.com/dust-tt/dust) make its technical approach inspectable. The MIT-licensed repository is relevant to engineering-led evaluations, although buyers should separately assess the work required to operate the available code and the differences between it and Dust's hosted commercial service. + +Dust now documents [schedule and webhook triggers](https://docs.dust.tt/docs/user-documentation/agents/triggers), so it should not be treated as chat-only. Teams should still test whether Dust provides the branching, approvals, state handling, retries, observability, and operational integrations required for each process. + +## We use Dust for company knowledge but need workflow automation too. What should we evaluate? + +Sim fits teams that need governed, multi-step agent workflows that move beyond knowledge chat into triggers, branching, API calls, human input, and actions across systems. Sim is the open-source AI workspace where teams build, deploy, and manage AI agents. + +The required evaluation is different from a Glean-versus-Dust search evaluation. The team should test whether a platform can start work from schedules, webhooks, application events, or APIs; maintain state across multiple steps; route failures; pause for human input; restrict credentials; record execution history; and deploy workflows as controlled operational services. The [AI workflow automation platform buyer's checklist](https://www.sim.ai/library/ai-workflow-automation-platform-buyers-checklist) provides a fuller set of evaluation criteria. + +Several platform categories can fit: + +| Option | Reason to evaluate it | Important boundary | +|---|---|---| +| Sim | Sim provides a visual builder for multi-step agent workflows and fits teams that need controlled deployment and execution visibility | Sim's core is Apache 2.0, while SSO, SCIM, access control, audit logs, data retention, and other code in `apps/sim/ee` use the separate [Sim Enterprise License](https://github.com/simstudioai/sim/blob/main/apps/sim/ee/LICENSE); production use of that enterprise code requires an active Sim Enterprise subscription | +| n8n | n8n fits node-based application automation that combines deterministic workflow steps with AI capabilities | As of November 2026, n8n uses the [Sustainable Use License](https://docs.n8n.io/n8n-community-license/), a fair-code license with use restrictions | +| Microsoft Copilot Studio and Power Automate | These products fit organizations standardized on Microsoft 365, Power Platform, and Microsoft identity and governance; Microsoft documents [connectors shared across Copilot Studio and Power Platform](https://learn.microsoft.com/en-us/microsoft-copilot-studio/advanced-connectors) | Buyers should test licensing, environment administration, connector entitlements, and the division of work between Copilot Studio and Power Automate using Microsoft's [licensing guidance](https://learn.microsoft.com/en-us/microsoft-copilot-studio/billing-licensing) | +| Glean or Dust | Glean and Dust remain appropriate when the process is primarily knowledge retrieval, analysis, assistance, and a defined set of tool actions | Buyers should prove that either platform supports the required triggers, branches, approvals, retries, writes, and execution monitoring before using it as a workflow system | + +A team does not necessarily have to replace Dust. It can retain Dust for company-knowledge agents and use a workflow-oriented platform for processes that require durable orchestration, approvals, and cross-system actions. The deciding factor should be whether maintaining two governed platforms is simpler and safer than forcing one product to cover both jobs. + +## Which proof-of-concept tests should enterprise buyers run? + +Glean and Dust should be tested with the same permission-sensitive questions, source documents, users, and operational tasks before an enterprise makes a platform decision. + +1. Select 20 to 30 representative questions with known correct answers and authoritative source documents. +2. Include users with different roles, departments, regions, and access rights. +3. Test whether answers cite the correct source and respect document-level permissions after access changes. +4. Measure connector completeness for the exact objects, comments, attachments, metadata, and access controls the organization uses. +5. Build one realistic agent in each platform rather than relying on vendor-provided demos. +6. Test an action that writes to another system, including approval, failure, retry, and audit requirements. +7. Review administrator controls for identity, provisioning, retention, logs, model access, and credential management. +8. Calculate expected cost using the actual number of users, builders, agents, model calls, and required enterprise features. +9. Ask security and legal teams to compare hosted data handling, subprocessors, residency options, contractual terms, and customer-hosted responsibilities. +10. Evaluate search quality and workflow capability separately so strong retrieval does not hide weak orchestration, or vice versa. + +## Which related enterprise AI comparisons should buyers read? + +Sim's related guides separate the Dust-alternative, internal-search, enterprise-governance, and workflow-platform decisions so buyers can investigate each requirement directly. + +- [Best Dust Alternatives in 2026 for AI Agent Workflows](https://www.sim.ai/library/best-dust-alternatives-2026) compares broader options for teams outgrowing Dust or evaluating alternatives. +- [Best AI Agents for Internal Knowledge Search Across Docs and Tools](https://www.sim.ai/library/best-ai-agents-internal-knowledge-search) compares the wider internal-search category. +- [What to Look for in an AI Workflow Automation Platform: Buyer's Checklist](https://www.sim.ai/library/ai-workflow-automation-platform-buyers-checklist) covers triggers, control flow, governance, deployment, and operations. +- [Best Enterprise AI Agent Platforms in 2026: SSO, SCIM, RBAC, and Audit Logs](https://www.sim.ai/library/best-ai-agent-platforms-for-enterprise-teams-2026) focuses on enterprise administration and governance requirements. + +For adjacent comparisons, Microsoft describes [Copilot for enterprise organizations](https://www.microsoft.com/en-us/copilot/solutions/enterprise) and [Copilot Studio connectors](https://learn.microsoft.com/en-us/microsoft-copilot-studio/advanced-connectors). Writer describes its [enterprise governance controls](https://writer.com/product/control-center/) and [plans](https://writer.com/plans/). Use those primary sources to test the Microsoft and Writer fit against the same data, identity, governance, and orchestration requirements used for Glean and Dust. diff --git a/apps/sim/content/library/snowflake-quickbooks-mcp-servers-ai-agents/index.mdx b/apps/sim/content/library/snowflake-quickbooks-mcp-servers-ai-agents/index.mdx new file mode 100644 index 00000000000..c6c6960b3c4 --- /dev/null +++ b/apps/sim/content/library/snowflake-quickbooks-mcp-servers-ai-agents/index.mdx @@ -0,0 +1,147 @@ +--- +slug: snowflake-quickbooks-mcp-servers-ai-agents +title: 'Snowflake and QuickBooks MCP Servers for AI Agents' +description: 'Compare Snowflake and QuickBooks MCP server access for AI agents, including permissions, credentials, approvals, and Sim and n8n implementation patterns.' +date: 2026-11-16 +updated: 2026-11-16 +authors: + - andrew +readingTime: 8 +tags: [MCP, Snowflake, QuickBooks, AI Agents, Sim] +ogImage: /library/snowflake-quickbooks-mcp-servers-ai-agents/cover.jpg +draft: false +faq: + - q: "Does MCP replace Snowflake role based access control?" + a: "Snowflake role based access control remains authoritative because an MCP server can perform only the operations allowed to its authenticated Snowflake identity." + - q: "Does MCP standardize authentication for Snowflake and QuickBooks?" + a: "MCP standardizes tool discovery and invocation, but Snowflake and QuickBooks still use their own authentication, authorization, token, and role mechanisms behind the server." + - q: "Should one MCP server connect to both Snowflake and QuickBooks?" + a: "Snowflake and QuickBooks are usually safer behind separate MCP server boundaries because data warehouse queries and accounting writes have different credentials, owners, risks, and approval requirements." + - q: "Where should a Snowflake or QuickBooks MCP server run?" + a: "A Snowflake or QuickBooks MCP server should run in an environment that can reach the required APIs while keeping credentials, logs, network access, and deployment changes under organizational control." + - q: "How should teams test a Snowflake or QuickBooks MCP agent before production?" + a: "Snowflake and QuickBooks MCP agents should be tested with restricted nonproduction credentials, representative tool inputs, denied actions, malformed values, approval rejections, timeouts, and duplicate requests." + - q: "Does a Sim approval happen inside QuickBooks?" + a: "Sim performs the approval inside the workflow before the approved branch calls the QuickBooks tool, so the workflow must use a Condition to prevent rejected requests from reaching QuickBooks." + - q: "Is n8n open source?" + a: "As of November 2026, n8n is source available under the Sustainable Use License, which n8n describes as a fair-code license." + - q: "Is Sim free to self host?" + a: "As of November 2026, Sim's core is Apache 2.0 and can be self hosted, while code in apps/sim/ee uses the separate Sim Enterprise License and requires an active Enterprise subscription for production use." +--- + +## TL;DR + +As of November 2026, [Sim](https://docs.sim.ai/agents/mcp) and [n8n](https://docs.n8n.io/integrations/builtin/cluster-nodes/sub-nodes/n8n-nodes-langchain.toolmcp) can act as clients for Model Context Protocol (MCP), a standard way for AI agents to discover and call tools from other services. These agents can query Snowflake or use QuickBooks tools exposed by a compatible MCP server. Sim fits workflows that need a visual approval step before a QuickBooks write, while n8n is a practical option for teams already running its automation environment. + +An MCP connection does not bypass either system's security model. [Snowflake roles](https://docs.snowflake.com/en/user-guide/security-access-control-overview) still determine which warehouse objects an agent can query, while [QuickBooks OAuth authorization](https://developer.intuit.com/app/developer/qbo/docs/develop/authentication-and-authorization/oauth-2.0) and the MCP server's tool definitions determine which accounting records an agent can read or change. + +## Which AI agent platforms support an MCP server for querying Snowflake data? + +Sim and n8n support MCP client connections that can give an AI agent access to tools exposed by a compatible Snowflake MCP server. + +[Sim can register a remote MCP server](https://docs.sim.ai/agents/mcp), give its operations to an Agent block, combine results with other workflow blocks, pause for human input, and route the run according to a downstream Condition. [n8n's MCP Client Tool](https://docs.n8n.io/integrations/builtin/cluster-nodes/sub-nodes/n8n-nodes-langchain.toolmcp) lets its AI agents call tools from an external MCP server. + +The platform does not grant Snowflake access by itself. The MCP server must authenticate to Snowflake, and the associated Snowflake role should be limited to the databases, schemas, warehouses, and operations required by the workflow. + +| Platform | MCP client support | Credential handling | Human approval | Operational records | +| --- | --- | --- | --- | --- | +| Sim | Connects agents to tools exposed by an MCP server | Supports saved secret references for sensitive MCP authentication values | Human in the Loop pauses the run and collects a decision, then a Condition routes approved and rejected paths | [Workflow run records](https://docs.sim.ai/logs-debugging) are available, while enterprise audit logs are part of `apps/sim/ee` under the [Sim Enterprise License](https://github.com/simstudioai/sim/blob/main/apps/sim/ee/LICENSE) | +| n8n | Its [MCP Client Tool](https://docs.n8n.io/integrations/builtin/cluster-nodes/sub-nodes/n8n-nodes-langchain.toolmcp) connects an AI agent to an external MCP server | The MCP Client Tool supports bearer, header, and OAuth2 authentication | [Human review](https://docs.n8n.io/build/integrate-ai/ai-examples/human-in-the-loop-for-tools) can be required before selected AI tool calls | [Execution history](https://docs.n8n.io/build/understand-workflows/understand-executions/view-all-executions) is available, and [log streaming](https://docs.n8n.io/administer/observe-and-log/stream-logs-to-external-systems) is available for Enterprise deployments | + +For a general setup walkthrough, read [How to Connect an MCP Server to an AI Agent Workflow](https://www.sim.ai/library/connect-mcp-server-to-ai-agent-workflow). + +## Which AI agent tools have a QuickBooks MCP server integration? + +Sim and n8n can use QuickBooks tools when a compatible MCP server exposes the QuickBooks Online operations and authentication required by the agent. + +A QuickBooks MCP integration is not automatically equivalent to a native QuickBooks connector. The MCP server translates tool calls into [QuickBooks Online Accounting API](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/account) requests, so buyers must inspect the server's implementation, requested OAuth scopes, supported entities, and write behavior before connecting production books. + +Sim fits a finance workflow that must stop before creating or changing an accounting record. Its Human in the Loop block pauses the run and collects an approval field, while a downstream Condition must explicitly route the approved request to the QuickBooks write tool. + +## What does a Snowflake MCP server expose to an AI agent? + +A Snowflake MCP server can expose query execution, database metadata, schema discovery, and table discovery as callable tools for an AI agent. + +The precise tool list depends on the server. A narrow implementation might expose only a parameterized reporting query, while a broader implementation might let the agent list databases and schemas, inspect table definitions, and submit SQL. + +For production use, prefer bounded tools over unrestricted SQL whenever the reporting job is predictable. A tool such as `get_monthly_revenue_by_region` is easier to govern than a general `execute_sql` tool because the server can validate its inputs and constrain the generated query. + +Snowflake permissions remain authoritative. A server connected with a read-only role cannot turn an MCP request into a permitted write merely because the model asks for one. Snowflake explains how roles and privileges govern access in its [access control guide](https://docs.snowflake.com/en/user-guide/security-access-control-overview). + +## What does a QuickBooks MCP server expose to an AI agent? + +A QuickBooks MCP server can expose tools for customers, invoices, bills, vendors, payments, accounts, and financial reports when its QuickBooks Online scopes and implementation permit those operations. + +Read tools can retrieve records or reports for reconciliation and analysis. Write tools can create or update accounting records, which creates a higher operational risk and should require stricter validation and approval. + +The MCP server should publish clear input schemas for every write. An invoice creation tool should require validated customer, line item, account, tax, currency, and due date fields rather than accepting an unrestricted natural-language payload. Intuit documents QuickBooks Online resources and operations in its [Accounting API reference](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/account). + +## How should Snowflake and QuickBooks MCP permissions be configured? + +Snowflake and QuickBooks MCP permissions should start with read-only access and add narrowly scoped write authority only when the workflow has a documented business need. + +For Snowflake, use a dedicated service identity and role rather than a personal analyst account. Restrict that role to the required warehouse, databases, schemas, views, and usage privileges. Apply a [statement timeout](https://docs.snowflake.com/en/sql-reference/sql/alter-session), warehouse constraints, and [resource monitoring](https://docs.snowflake.com/en/user-guide/resource-monitors) so an incorrect agent query cannot consume unbounded compute. + +For QuickBooks, separate reporting tools from mutation tools. Read access may be sufficient for close preparation, variance analysis, and cash reporting. Creating an invoice, bill, payment, journal entry, or customer should be treated as a controlled write and should pass validation plus human approval before execution. + +A single broad MCP credential shared across every agent defeats least privilege. Separate credentials by environment and workflow so access can be revoked without disrupting unrelated agents. + +## How should credentials and secrets be handled for Snowflake and QuickBooks MCP servers? + +Snowflake and QuickBooks credentials should remain on the MCP server or in the agent platform's credential store rather than appearing in prompts, tool arguments, workflow outputs, or Slack messages. + +The Snowflake identity should use the authentication method supported by the selected server and approved by the organization. Rotate credentials, restrict network access where possible, and prevent the model from reading raw secret values. + +QuickBooks Online uses OAuth 2.0 authorization, so the server must protect access and refresh tokens and preserve the correct company context. Intuit's [OAuth 2.0 documentation](https://developer.intuit.com/app/developer/qbo/docs/develop/authentication-and-authorization/oauth-2.0) should govern token handling rather than instructions generated by the model. + +Credential access should also be separated from tool selection. The agent may choose an allowed tool, but it should never choose which production credential to reveal or receive the underlying secret. + +## What governance controls should an MCP agent use for Snowflake and QuickBooks? + +Snowflake and QuickBooks MCP agents should use least privilege, bounded tools, input validation, execution limits, human approval for accounting writes, and reviewable run records. + +1. Give the Snowflake server a dedicated role with access only to approved views and warehouses. +2. Prefer parameterized reporting tools over unrestricted SQL execution. +3. Set Snowflake statement timeouts, warehouse limits, and resource monitoring. +4. Give the QuickBooks server only the OAuth scopes required by its tools. +5. Separate QuickBooks read tools from create, update, delete, and payment tools. +6. Validate company, customer, account, amount, currency, tax, and date fields before any write. +7. Pause the workflow for human approval before changing QuickBooks records. +8. Route rejected requests to a nonwriting path through an explicit Condition. +9. Remove credentials and sensitive accounting data from model prompts and Slack summaries. +10. Retain enough execution information to identify the user, tool, arguments, decision, and result. + +These controls complement the broader practices in [How to Standardize MCP Servers Across an Enterprise: Platforms Compared](https://www.sim.ai/library/enterprise-mcp-server-standardization-platforms). + +## How do you build a Snowflake to QuickBooks agent with approval in Sim? + +Sim can build a governed workflow that queries Snowflake, prepares a proposed QuickBooks action, pauses for human approval, and sends a final summary to Slack. + +1. Add an MCP connection that exposes an approved Snowflake query tool. +2. Ask the Agent block to call that tool and return structured fields required by the finance process. +3. Validate the returned account, amount, customer, currency, and date values before preparing a QuickBooks write. +4. Present the proposed action in a Human in the Loop block with an approve or reject field. +5. Add a Condition that sends only an approved request to the QuickBooks MCP write tool. +6. Send rejected requests to a review queue without calling the write tool. +7. Post a Slack summary containing the decision, record identifier, and result without including credentials or unnecessary financial details. + +The approval block does not stop or route the workflow by itself. Sim's Human in the Loop block pauses and resumes with form values, and the downstream Condition enforces the decision. + +Teams that do not require MCP for both systems can use direct integrations instead. [How Do You Build a Snowflake or BigQuery AI Agent That Reports to Slack?](https://www.sim.ai/library/snowflake-bigquery-ai-agent-slack-reporting) covers warehouse reporting, while [How Do You Build a QuickBooks AI Agent for Month End Close?](https://www.sim.ai/library/quickbooks-ai-agent-month-end-close-guide) covers an accounting workflow. + +## What are the key platform facts for Sim and n8n? + +Sim and n8n both support MCP-based agent workflows, but their licenses, self-hosting terms, and billing models are different. + +As of November 2026, Sim's core is licensed under Apache 2.0 and can be self-hosted, while `apps/sim/ee` is governed by the separate [Sim Enterprise License](https://github.com/simstudioai/sim/blob/main/apps/sim/ee/LICENSE), which requires an active Enterprise subscription for production use. [Sim Cloud measures billable usage in credits](https://docs.sim.ai/platform/costs), and workspace BYOK keys work on every Sim Cloud plan. + +As of November 2026, n8n is source available under the [Sustainable Use License](https://github.com/n8n-io/n8n/blob/master/LICENSE.md), which n8n describes as a [fair-code license](https://docs.n8n.io/n8n-community-license). n8n [offers self-hosting](https://docs.n8n.io/deploy/host-n8n), while its cloud pricing is based primarily on monthly workflow executions according to [n8n pricing](https://n8n.io/pricing/). + +## Where can teams learn more about MCP agent architecture? + +These related guides cover general MCP setup, enterprise server governance, Snowflake reporting, and QuickBooks close workflows: + +1. [How to Connect an MCP Server to an AI Agent Workflow](https://www.sim.ai/library/connect-mcp-server-to-ai-agent-workflow) +2. [How to Standardize MCP Servers Across an Enterprise: Platforms Compared](https://www.sim.ai/library/enterprise-mcp-server-standardization-platforms) +3. [How Do You Build a Snowflake or BigQuery AI Agent That Reports to Slack?](https://www.sim.ai/library/snowflake-bigquery-ai-agent-slack-reporting) +4. [How Do You Build a QuickBooks AI Agent for Month End Close?](https://www.sim.ai/library/quickbooks-ai-agent-month-end-close-guide) diff --git a/apps/sim/executor/handlers/human-in-the-loop/handler.ts b/apps/sim/executor/handlers/human-in-the-loop/handler.ts index c24812b6377..29573871eda 100644 --- a/apps/sim/executor/handlers/human-in-the-loop/handler.ts +++ b/apps/sim/executor/handlers/human-in-the-loop/handler.ts @@ -7,6 +7,7 @@ import { isCanonicalPair, scopeCanonicalModesForTool, } from '@/lib/workflows/subblocks/visibility' +import { omitConditionHiddenParams } from '@/lib/workflows/tool-input/hidden-params' import { getBlock } from '@/blocks/registry' import type { BlockOutput } from '@/blocks/types' import { @@ -27,6 +28,7 @@ import type { BlockHandler, ExecutionContext, PauseMetadata } from '@/executor/t import { collectBlockData } from '@/executor/utils/block-data' import { convertBuilderDataToJson, convertPropertyValue } from '@/executor/utils/builder-data' import { parseObjectStrings } from '@/executor/utils/json' +import { ToolCallParamsError } from '@/providers/tool-params-error' import { buildBlockToolParamsTransform } from '@/providers/utils' import type { SerializedBlock } from '@/serializer/types' import { executeTool } from '@/tools' @@ -422,10 +424,13 @@ export class HumanInTheLoopBlockHandler implements BlockHandler { Object.values(buildCanonicalIndex(subBlocks).groupsById) as CanonicalGroup[] ).filter(isCanonicalPair) + const operation = + toolConfig.operation ?? + (typeof storedParams.operation === 'string' ? storedParams.operation : undefined) + const visibleParams = omitConditionHiddenParams(subBlocks, storedParams, operation) + const { paramsTransform } = buildBlockToolParamsTransform({ - operation: - toolConfig.operation ?? - (typeof storedParams.operation === 'string' ? storedParams.operation : undefined), + operation, blockSubBlocks: subBlocks, blockParamsFn: notificationBlock?.tools?.config?.params, blockInputDefs: notificationBlock?.inputs, @@ -436,20 +441,23 @@ export class HumanInTheLoopBlockHandler implements BlockHandler { toolIndex, toolConfig.type ), + storedParams: visibleParams, }) - if (!paramsTransform) return storedParams + if (!paramsTransform) return visibleParams try { - return paramsTransform(storedParams) + return paramsTransform(visibleParams) } catch (error) { // Mirrors `prepareToolExecution`: a transform that throws must not take the - // notification down with it, so the raw params still go out. + // notification down with it, so the raw params still go out — except a + // `ToolCallParamsError`, whose raw params are unsafe to send. + if (error instanceof ToolCallParamsError) throw error logger.warn('Notification tool params transform failed, using raw params', { toolId, error, }) - return storedParams + return visibleParams } } diff --git a/apps/sim/executor/handlers/human-in-the-loop/notification-params.test.ts b/apps/sim/executor/handlers/human-in-the-loop/notification-params.test.ts index dc4bd9d32a4..57066d13dab 100644 --- a/apps/sim/executor/handlers/human-in-the-loop/notification-params.test.ts +++ b/apps/sim/executor/handlers/human-in-the-loop/notification-params.test.ts @@ -27,6 +27,19 @@ const notifierBlock = { outputs: {}, } +/** A notifier whose mapper rejects its stored params, as Table's does for a corrupt filter. */ +const rejectingNotifierBlock = { + ...notifierBlock, + tools: { + ...notifierBlock.tools, + config: { + params: () => { + throw new ToolCallParamsError('Invalid JSON in Filter') + }, + }, + }, +} + vi.mock('@/tools/utils', () => toolsUtilsMock) vi.mock('@/tools', () => toolsMock) @@ -34,15 +47,18 @@ vi.mock('@/tools', () => toolsMock) import { getBlock } from '@/blocks/registry' import { PAUSE_RESUME } from '@/executor/constants' import { HumanInTheLoopBlockHandler } from '@/executor/handlers/human-in-the-loop/handler' +import { ToolCallParamsError } from '@/providers/tool-params-error' toolsUtilsMockFns.mockGetTool.mockReturnValue({ id: 'notifier_send', params: { channel: { type: 'string' }, silent: { type: 'boolean' } }, }) -vi.mocked(getBlock).mockImplementation((type: string) => - type === 'notifier' ? (notifierBlock as never) : undefined -) +vi.mocked(getBlock).mockImplementation((type: string) => { + if (type === 'notifier') return notifierBlock as never + if (type === 'rejecting_notifier') return rejectingNotifierBlock as never + return undefined +}) const executed: Array> = [] toolsMockFns.mockExecuteTool.mockImplementation( @@ -53,7 +69,10 @@ toolsMockFns.mockExecuteTool.mockImplementation( ) /** Runs one notification whose channel was configured in ADVANCED mode. */ -async function runNotification(blockTypeId: string): Promise> { +async function runNotification( + blockTypeId: string, + notifierType = 'notifier' +): Promise> { executed.length = 0 const block = { @@ -74,7 +93,7 @@ async function runNotification(blockTypeId: string): Promise { }) }) + it('v2 skips a notification whose mapper rejects its params instead of sending raw ones', async () => { + await runNotification('human_in_the_loop_v2', 'rejecting_notifier') + expect(executed).toEqual([]) + }) + it('v1 keeps handing the tool its raw stored values', async () => { // Deliberately unchanged: altering what an already-configured v1 notification sends // is exactly the break v2 exists to avoid. diff --git a/apps/sim/executor/handlers/pi/local/sim-tools.ts b/apps/sim/executor/handlers/pi/local/sim-tools.ts index acb590d644c..bcfab3229a8 100644 --- a/apps/sim/executor/handlers/pi/local/sim-tools.ts +++ b/apps/sim/executor/handlers/pi/local/sim-tools.ts @@ -23,6 +23,7 @@ import { projectResolvedSecretModelContent } from '@/executor/utils/resolved-sec import type { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' import { annotateDuplicateToolBindings } from '@/executor/utils/tool-binding-labels' import { assignProviderToolIdentities } from '@/providers/tool-identity' +import { ToolCallParamsError } from '@/providers/tool-params-error' import type { ProviderToolConfig } from '@/providers/types' import { transformBlockTool } from '@/providers/utils' import { executeTool } from '@/tools' @@ -129,8 +130,9 @@ function buildSimToolSpec( * declares. Skipping it here left Pi local tools receiving a raw selector id * where the tool expected a resolved one, and `'false'` where it expected `false`. * - * A failure keeps the raw params, matching `prepareToolExecution`. The projected - * copy is only transformed when the raw one was, so the two stay comparable. + * A failure keeps the raw params, matching `prepareToolExecution`, except a + * `ToolCallParamsError`, which fails the call. The projected copy is only + * transformed when the raw one was, so the two stay comparable. */ let transformApplied = false const applyParamsTransform = (input: Record): Record => { @@ -140,6 +142,7 @@ function buildSimToolSpec( transformApplied = true return transformed } catch (error) { + if (error instanceof ToolCallParamsError) throw error logger.warn('paramsTransform failed for Pi local tool, using raw params', { error }) return input } @@ -167,8 +170,15 @@ function buildSimToolSpec( if (!inputProjection.complete || !projectedTool) { return unavailableToolResult() } + // Only the stored keys the transform kept: a value the selected operation hides was + // dropped from `preseededParams`, so its projected copy must be dropped too. + const projectedPreseededParams = Object.fromEntries( + Object.entries(projectedTool.params || {}).filter(([key]) => + Object.hasOwn(preseededParams, key) + ) + ) const mergedProjectedParams = mergeToolParameters( - projectedTool.params || {}, + projectedPreseededParams, args as Record ) diff --git a/apps/sim/executor/utils.ts b/apps/sim/executor/utils.ts index 11deda3f9a0..32e2763b3a6 100644 --- a/apps/sim/executor/utils.ts +++ b/apps/sim/executor/utils.ts @@ -50,6 +50,7 @@ export class StreamingResponseFormatProcessor { ): ReadableStream { let buffer = '' let hasProcessedComplete = false + let endsWithBracket = false const self = this @@ -73,7 +74,12 @@ export class StreamingResponseFormatProcessor { const chunk = decoder.decode(value, { stream: true }) buffer += chunk - if (!hasProcessedComplete) { + // Only text ending in `}` or `]` can parse to an object, so skip re-parsing + // the whole buffer on every other token: that made each stream quadratic. + const trimmedChunk = chunk.trimEnd() + if (trimmedChunk) endsWithBracket = /[}\]]$/.test(trimmedChunk) + + if (!hasProcessedComplete && endsWithBracket) { const processedChunk = self.processStreamingChunk(buffer, selectedFields) if (processedChunk) { @@ -114,32 +120,6 @@ export class StreamingResponseFormatProcessor { } } catch {} - const openBraces = (buffer.match(/\{/g) || []).length - const closeBraces = (buffer.match(/\}/g) || []).length - - if (openBraces > 0 && openBraces === closeBraces) { - try { - const parsed = JSON.parse(buffer.trim()) - if (typeof parsed === 'object' && parsed !== null) { - const results: string[] = [] - for (const field of selectedFields) { - if (field in parsed) { - const value = parsed[field] - const formattedValue = typeof value === 'string' ? value : JSON.stringify(value) - results.push(formattedValue) - } - } - - if (results.length > 0) { - const result = results.join('\n') - return result - } - - return null - } - } catch {} - } - return null } diff --git a/apps/sim/lib/internal/github/execute-tool.ts b/apps/sim/lib/internal/github/execute-tool.ts index 5043273f8a4..418db0433e2 100644 --- a/apps/sim/lib/internal/github/execute-tool.ts +++ b/apps/sim/lib/internal/github/execute-tool.ts @@ -22,9 +22,9 @@ export const executeGitHubTool: InternalToolOperationHandler = async (request) = try { switch (request.toolId) { case 'github_comment': - return executeToolOperationImplementation(executeGitHubCommentOperation, request) + return await executeToolOperationImplementation(executeGitHubCommentOperation, request) case 'github_comment_v2': - return executeToolOperationImplementation(executeGitHubCommentV2Operation, request) + return await executeToolOperationImplementation(executeGitHubCommentV2Operation, request) case 'github_latest_commit': case 'github_latest_commit_v2': { const parsed = inputSchema.safeParse(request.input) diff --git a/apps/sim/lib/internal/github/operations.ts b/apps/sim/lib/internal/github/operations.ts index b30e3941b9a..70132b053e3 100644 --- a/apps/sim/lib/internal/github/operations.ts +++ b/apps/sim/lib/internal/github/operations.ts @@ -1,4 +1,5 @@ import { createLogger } from '@sim/logger' +import { getErrorMessage } from '@sim/utils/errors' import { isRecordLike } from '@sim/utils/object' import { secureFetchWithPinnedIP, @@ -11,6 +12,7 @@ import { } from '@/lib/core/utils/stream-limits' import { GitHubOperationError } from '@/lib/internal/github/errors' import { MAX_BUFFERED_TRANSFER_BYTES } from '@/lib/uploads/shared/types' +import { githubPathSegment, githubRepoPath } from '@/tools/github/request-path' import { formatGitHubErrorMessage } from '@/tools/github/response-parsers' import type { CreateCommentParams, @@ -19,6 +21,7 @@ import type { } from '@/tools/github/types' import { secureGitHubRequest } from '@/tools/github/utils.server' import type { ToolResponse } from '@/tools/types' +import { safeUrlPathSegment } from '@/tools/url-path' const logger = createLogger('GitHubLatestCommitOperation') const MAX_COMMIT_RESPONSE_BYTES = 10 * 1024 * 1024 @@ -64,16 +67,42 @@ interface GitHubCommitFile { blob_url?: string } +interface GitHubGitActor { + name: string + email: string + date: string +} + +interface GitHubCommitUser { + login: string + avatar_url: string + html_url: string + id?: number + node_id?: string + type?: string + url?: string + site_admin?: boolean +} + interface GitHubCommitResponse { sha: string html_url: string commit: { + url?: string message: string - author: { name: string; email: string; date: string } - committer: { name: string; email: string; date: string } + comment_count?: number + author: GitHubGitActor + committer: GitHubGitActor + tree?: { sha: string; url: string } + verification?: { + verified: boolean + reason: string + signature?: string | null + payload?: string | null + } } - author?: { login: string; avatar_url: string; html_url: string } - committer?: { login: string; avatar_url: string; html_url: string } + author?: GitHubCommitUser | null + committer?: GitHubCommitUser | null stats?: { additions: number; deletions: number; total: number } files?: GitHubCommitFile[] } @@ -97,8 +126,20 @@ function githubHeaders(apiKey: string): Record { } } +/** Builds a request path from caller input, reporting a rejected segment as a 400. */ +function buildRequestPath(build: () => string): string { + try { + return build() + } catch (error) { + throw new GitHubOperationError(getErrorMessage(error, 'Invalid GitHub request path'), 400) + } +} + function pullRequestUrl(params: CreateCommentParams): string { - return `${GITHUB_API_BASE}/repos/${params.owner}/${params.repo}/pulls/${params.pullNumber}` + return buildRequestPath( + () => + `${GITHUB_API_BASE}/repos/${githubRepoPath(params.owner, params.repo)}/pulls/${githubPathSegment(params.pullNumber, 'pullNumber')}` + ) } function isFileCommentRequest(params: CreateCommentParams): boolean { @@ -348,15 +389,36 @@ async function fetchChangedFileContent( } } +/** + * Merges a commit's git identity with its linked GitHub account. The account + * fields keep their `'Unknown'`/`''` fallbacks when the commit has no linked + * user, which the v1 output has always returned. + */ +function commitActorMetadata(actor: GitHubGitActor, user: GitHubCommitUser | null | undefined) { + return { + name: actor.name, + email: actor.email, + date: actor.date, + login: user?.login || 'Unknown', + avatar_url: user?.avatar_url || '', + html_url: user?.html_url || '', + id: user?.id, + node_id: user?.node_id, + type: user?.type, + url: user?.url, + site_admin: user?.site_admin, + } +} + export async function getGitHubLatestCommit( input: LatestCommitParams, context: GitHubOperationContext ): Promise { context.signal?.throwIfAborted() - const owner = encodeURIComponent(input.owner) - const repo = encodeURIComponent(input.repo) - const revision = encodeURIComponent(input.branch || 'HEAD') - const commitUrl = `https://api.github.com/repos/${owner}/${repo}/commits/${revision}` + const commitUrl = buildRequestPath( + () => + `${GITHUB_API_BASE}/repos/${githubRepoPath(input.owner, input.repo)}/commits/${safeUrlPathSegment(input.branch || 'HEAD', 'branch', { allowSeparators: true })}` + ) const validation = await validateUrlWithDNS(commitUrl, 'commitUrl', 'configuredEndpoint') context.signal?.throwIfAborted() if (!validation.isValid) { @@ -410,18 +472,12 @@ export async function getGitHubLatestCommit( sha: data.sha, html_url: data.html_url, commit_message: data.commit.message, - author: { - name: data.commit.author.name, - login: data.author?.login || 'Unknown', - avatar_url: data.author?.avatar_url || '', - html_url: data.author?.html_url || '', - }, - committer: { - name: data.commit.committer.name, - login: data.committer?.login || 'Unknown', - avatar_url: data.committer?.avatar_url || '', - html_url: data.committer?.html_url || '', - }, + commit_url: data.commit.url, + comment_count: data.commit.comment_count, + tree: data.commit.tree, + verification: data.commit.verification, + author: commitActorMetadata(data.commit.author, data.author), + committer: commitActorMetadata(data.commit.committer, data.committer), stats: data.stats, files: files.length > 0 ? files : undefined, }, diff --git a/apps/sim/lib/internal/okta/operations/update-group.ts b/apps/sim/lib/internal/okta/operations/update-group.ts index ae2f63ef237..e9be484cfc2 100644 --- a/apps/sim/lib/internal/okta/operations/update-group.ts +++ b/apps/sim/lib/internal/okta/operations/update-group.ts @@ -4,6 +4,7 @@ import { validateOktaDomain } from '@/lib/core/security/input-validation' import type { InternalToolOperationImplementation } from '@/lib/internal/tool-operations/types' import type { OktaGroup, OktaUpdateGroupParams, OktaUpdateGroupResponse } from '@/tools/okta/types' import { mergeOktaGroupProfile, oktaHeaders, throwOktaError } from '@/tools/okta/utils' +import { safeUrlPathSegment } from '@/tools/url-path' const logger = createLogger('OktaUpdateGroup') @@ -32,7 +33,7 @@ export const executeOktaUpdateGroupOperation: InternalToolOperationImplementatio OktaUpdateGroupParams > = async (params, signal): Promise => { const domain = validateOktaDomain(params.domain) - const url = `https://${domain}/api/v1/groups/${encodeURIComponent(params.groupId.trim())}` + const url = `https://${domain}/api/v1/groups/${safeUrlPathSegment(params.groupId, 'groupId')}` const headers = oktaHeaders(params.apiKey) const readResponse = await outboundFetch(url, { headers, signal }) diff --git a/apps/sim/lib/internal/resend/schema.ts b/apps/sim/lib/internal/resend/schema.ts index b818c98da8c..4004162ed79 100644 --- a/apps/sim/lib/internal/resend/schema.ts +++ b/apps/sim/lib/internal/resend/schema.ts @@ -19,7 +19,7 @@ export const resendSendInputSchema = z.object({ .union([z.string().min(1), z.array(z.string().min(1))]) .optional() .nullable(), - scheduledAt: z.string().datetime().optional().nullable(), + scheduledAt: z.string().datetime({ offset: true }).optional().nullable(), tags: z.string().optional().nullable(), }) diff --git a/apps/sim/lib/internal/sailpoint/execute-tool.test.ts b/apps/sim/lib/internal/sailpoint/execute-tool.test.ts index ec46bfc3903..6c3becab192 100644 --- a/apps/sim/lib/internal/sailpoint/execute-tool.test.ts +++ b/apps/sim/lib/internal/sailpoint/execute-tool.test.ts @@ -147,6 +147,22 @@ describe('SailPoint internal tool handler', () => { } }) + it('opts into the experimental access-request-config v2 API on every config read', async () => { + mockFetch.mockImplementation(async (url) => + new URL(String(url)).pathname === '/oauth/token' + ? tokenResponse() + : Response.json({ approvalsMustBeExternal: false }) + ) + + const response = await request('sailpoint_get_access_request_config', {}) + + expect(response.status).toBe(200) + const configCall = mockFetch.mock.calls.find( + ([url]) => new URL(String(url)).pathname === '/access-request-config/v2' + ) + expect(new Headers(configCall?.[1]?.headers).get('X-SailPoint-Experimental')).toBe('true') + }) + it('refuses input carrying neither inline credentials nor a token before any call', async () => { const response = await executeSailPointTool({ toolId: 'sailpoint_get_identity', diff --git a/apps/sim/lib/internal/sailpoint/operations.ts b/apps/sim/lib/internal/sailpoint/operations.ts index 3ed6105282b..9df5dadcaae 100644 --- a/apps/sim/lib/internal/sailpoint/operations.ts +++ b/apps/sim/lib/internal/sailpoint/operations.ts @@ -673,7 +673,7 @@ export async function executeSailPointOperation( context, (hosts) => ({ url: `${hosts.apiBaseUrl}/access-request-config/v2`, - init: { method: 'GET' }, + init: { method: 'GET', headers: { 'X-SailPoint-Experimental': 'true' } }, }), 'accessRequestConfig' ) diff --git a/apps/sim/lib/internal/slack/file-download.test.ts b/apps/sim/lib/internal/slack/file-download.test.ts new file mode 100644 index 00000000000..3605618231f --- /dev/null +++ b/apps/sim/lib/internal/slack/file-download.test.ts @@ -0,0 +1,40 @@ +/** + * @vitest-environment node + */ +import { describe, expect, it } from 'vitest' +import { assertSlackFileHost, slackFileDownloadUrl } from '@/lib/internal/slack/file-download' + +const PRIVATE = 'https://files.slack.com/files-pri/T1-F1/report.pdf' +const DOWNLOAD = 'https://files.slack.com/files-pri/T1-F1/download/report.pdf' + +describe('Slack file download URL', () => { + it('prefers the download URL, which serves bytes where the private URL may redirect', () => { + expect( + slackFileDownloadUrl({ url_private: PRIVATE, url_private_download: DOWNLOAD })?.href + ).toBe(DOWNLOAD) + expect(slackFileDownloadUrl({ url_private: PRIVATE })?.href).toBe(PRIVATE) + }) + it('never returns a URL for a file hosted outside Slack', () => { + for (const file of [ + { is_external: true, url_private: PRIVATE }, + { mode: 'external', url_private: PRIVATE }, + { filetype: 'remote', url_private: PRIVATE }, + { url_private: 'https://files.example.com/report.pdf' }, + { url_private: 'https://files.slack.com.example.com/report.pdf' }, + { url_private: 'http://files.slack.com/files-pri/T1-F1/report.pdf' }, + { url_private_download: 'https://files.example.com/report.pdf', url_private: PRIVATE }, + { url_private: 'not a url' }, + {}, + ]) + expect(slackFileDownloadUrl(file)).toBeUndefined() + }) + it('keeps a redirect on the Slack file host', () => { + expect(() => assertSlackFileHost(DOWNLOAD)).not.toThrow() + for (const target of [ + 'https://slack-files.com/files-pri-safe/T1-F1/report.pdf', + 'https://team.slack.com/?redir=%2Ffiles-pri%2FT1-F1', + 'http://files.slack.com/files-pri/T1-F1/report.pdf', + ]) + expect(() => assertSlackFileHost(target)).toThrow() + }) +}) diff --git a/apps/sim/lib/internal/slack/file-download.ts b/apps/sim/lib/internal/slack/file-download.ts new file mode 100644 index 00000000000..cd2888ac17f --- /dev/null +++ b/apps/sim/lib/internal/slack/file-download.ts @@ -0,0 +1,37 @@ +/** The only host a Slack token is sent to when downloading a file's contents. */ +const SLACK_FILE_ORIGIN = 'https://files.slack.com' + +/** + * Where to download a Slack-hosted file's bytes with a Slack token, or undefined when Slack does + * not host it. `url_private_download` comes first: Slack answers a PDF's `url_private` with a + * redirect to a sandboxed viewer on another domain, while the download URL serves the bytes from + * its file host. A remote file's URL is whatever the app that shared it chose, so a file marked + * external, or any URL off Slack's file host, never receives a token. + */ +export function slackFileDownloadUrl(file: Record): URL | undefined { + if (isExternalSlackFile(file)) return undefined + const candidate = [file.url_private_download, file.url_private].find( + (value): value is string => typeof value === 'string' && value.length > 0 + ) + const url = candidate ? URL.parse(candidate) : null + return url?.origin === SLACK_FILE_ORIGIN ? url : undefined +} + +/** Whether a file was shared from another app, whose URL is that app's own host. */ +export function isExternalSlackFile(file: Record): boolean { + return file.is_external === true || file.mode === 'external' || file.filetype === 'remote' +} + +/** + * Whether a redirect stays on Slack's file host. A hop elsewhere, such as the workspace sign-in + * page Slack sends a token it will not serve, must be refused rather than read as the file. + */ +export function isSlackFileHost(target: string): boolean { + return URL.parse(target)?.origin === SLACK_FILE_ORIGIN +} + +/** Redirect guard for a Slack file download; see {@link isSlackFileHost}. */ +export function assertSlackFileHost(target: string): void { + if (!isSlackFileHost(target)) + throw new Error('Slack redirected the file download away from its file host') +} diff --git a/apps/sim/lib/internal/slack/operations.test.ts b/apps/sim/lib/internal/slack/operations.test.ts index cce8756aaa4..976b3b9c815 100644 --- a/apps/sim/lib/internal/slack/operations.test.ts +++ b/apps/sim/lib/internal/slack/operations.test.ts @@ -19,6 +19,7 @@ vi.mock('@/lib/internal/slack/file-input', () => ({ vi.mock('@/lib/core/security/input-validation.server', () => inputValidationMock) import { executeSlackDownload } from '@/lib/internal/slack/operations' +import { executeSlackGetChannelHistoryOperation } from '@/lib/internal/slack/operations/get-channel-history' import { MAX_FILE_SIZE } from '@/lib/uploads/utils/validation' const { mockValidateUrlWithDNS, mockSecureFetchWithPinnedIP, mockSecureFetchWithValidation } = @@ -54,6 +55,7 @@ describe('Slack operations', () => { name: 'report.pdf', mimetype: 'application/pdf', url_private: 'https://files.slack.com/report.pdf', + url_private_download: 'https://files.slack.com/download/report.pdf', }, }) ) @@ -65,15 +67,23 @@ describe('Slack operations', () => { ) expect(mockSecureFetchWithPinnedIP).toHaveBeenCalledWith( - 'https://files.slack.com/report.pdf', + 'https://files.slack.com/download/report.pdf', '93.184.216.34', { headers: { Authorization: 'Bearer token' }, profile: 'contentFetch', maxResponseBytes: MAX_FILE_SIZE, signal: controller.signal, + assertRedirectTarget: expect.any(Function), } ) + const guard = mockSecureFetchWithPinnedIP.mock.lastCall?.[2]?.assertRedirectTarget + expect(() => + guard?.('https://files.slack.com/files-pri/T1-F1/download/report.pdf') + ).not.toThrow() + expect(() => guard?.('https://slack-files.com/files-pri-safe/T1-F1/report.pdf')).toThrow( + expect.objectContaining({ status: 400 }) + ) assert(isInternalToolFileResult(result)) expect(result.files).toEqual([ { name: 'report.pdf', mimeType: 'application/pdf', buffer: Buffer.from('pdf') }, @@ -90,4 +100,48 @@ describe('Slack operations', () => { } expect(result.present([storedFile])).toEqual({ success: true, output: { file: storedFile } }) }) + + it('never sends the token to a file hosted outside Slack', async () => { + vi.mocked(global.fetch).mockResolvedValueOnce( + slackResponse({ + ok: true, + file: { + name: 'plan.pdf', + is_external: true, + url_private: 'https://files.slack.com/files-pri/T1-F1/plan.pdf', + }, + }) + ) + + await expect(executeSlackDownload({ accessToken: 'token', fileId: 'F1' })).rejects.toThrow( + 'File has no Slack-hosted download URL' + ) + expect(mockValidateUrlWithDNS).not.toHaveBeenCalled() + expect(mockSecureFetchWithPinnedIP).not.toHaveBeenCalled() + }) + + it('stops following history cursors at the page ceiling whatever maxPages asks for', async () => { + vi.mocked(global.fetch).mockImplementation(async () => + slackResponse({ + ok: true, + messages: [{ ts: '1.0', text: 'hi' }], + response_metadata: { next_cursor: 'more' }, + }) + ) + + const result = await executeSlackGetChannelHistoryOperation( + { + authMethod: 'oauth', + accessToken: 'token', + botToken: '', + channel: 'C1', + limit: 999, + maxPages: 10000, + }, + new AbortController().signal + ) + + expect(global.fetch).toHaveBeenCalledTimes(50) + expect(result.output).toMatchObject({ pages: 50, hasMore: true, nextCursor: 'more' }) + }) }) diff --git a/apps/sim/lib/internal/slack/operations.ts b/apps/sim/lib/internal/slack/operations.ts index a275e8da08e..19f8abb6b6b 100644 --- a/apps/sim/lib/internal/slack/operations.ts +++ b/apps/sim/lib/internal/slack/operations.ts @@ -25,6 +25,7 @@ import { slackString, } from '@/lib/internal/slack/client' import { SlackOperationError } from '@/lib/internal/slack/errors' +import { isSlackFileHost, slackFileDownloadUrl } from '@/lib/internal/slack/file-download' import { forEachSlackAttachmentFile } from '@/lib/internal/slack/file-input' import { createInternalToolFileResult, @@ -447,10 +448,9 @@ export async function executeSlackDownload(input: SlackDownloadBody, signal?: Ab const file = slackObject(data, 'file') ?? {} const name = input.fileName || slackString(file, 'name') || 'download' const mimeType = slackString(file, 'mimetype') || 'application/octet-stream' - const urlPrivate = slackString(file, 'url_private') - if (!urlPrivate) failure(400, 'File does not have a download URL') - const downloadUrl = urlPrivate - const validation = await validateUrlWithDNS(downloadUrl, 'urlPrivate', 'contentFetch') + const downloadUrl = slackFileDownloadUrl(file)?.href + if (!downloadUrl) failure(400, 'File has no Slack-hosted download URL') + const validation = await validateUrlWithDNS(downloadUrl, 'downloadUrl', 'contentFetch') signal?.throwIfAborted() if (!validation.isValid) failure(400, validation.error || 'Invalid Slack file URL') const response = await secureFetchWithPinnedIP(downloadUrl, validation.resolvedIP, { @@ -458,6 +458,10 @@ export async function executeSlackDownload(input: SlackDownloadBody, signal?: Ab headers: { Authorization: `Bearer ${input.accessToken}` }, maxResponseBytes: MAX_FILE_SIZE, signal, + assertRedirectTarget: (target) => { + if (!isSlackFileHost(target)) + failure(400, 'Slack redirected the file download away from its file host') + }, }) signal?.throwIfAborted() if (!response.ok) failure(400, 'Failed to download file content') diff --git a/apps/sim/lib/internal/twilio-voice/operations.test.ts b/apps/sim/lib/internal/twilio-voice/operations.test.ts index abd43ee52a2..34bdbea161e 100644 --- a/apps/sim/lib/internal/twilio-voice/operations.test.ts +++ b/apps/sim/lib/internal/twilio-voice/operations.test.ts @@ -32,7 +32,9 @@ describe('getTwilioRecording', () => { ) .mockResolvedValueOnce( Response.json({ - transcriptions: [{ transcription_text: 'hello', status: 'completed' }], + transcriptions: [ + { recording_sid: 'RE123', transcription_text: 'hello', status: 'completed' }, + ], }) ) .mockResolvedValueOnce( @@ -73,6 +75,26 @@ describe('getTwilioRecording', () => { output: { duration: 42, transcriptionText: 'hello', file: storedFile }, }) }) + it("reads the transcription from the recording's own list, never another recording's", async () => { + mockSecureFetchWithPinnedIP.mockReset() + mockSecureFetchWithPinnedIP + .mockResolvedValueOnce(Response.json({ sid: 'RE123', call_sid: 'CA123' })) + .mockResolvedValueOnce( + Response.json({ + transcriptions: [{ recording_sid: 'RE999', transcription_text: 'another call' }], + }) + ) + + const result = await getTwilioRecording( + { accountSid: 'AC123', authToken: 'secret', recordingSid: 'RE123' }, + { requestId: 'request-1' } + ) + + expect(mockSecureFetchWithPinnedIP.mock.calls[1][0]).toBe( + 'https://api.twilio.com/2010-04-01/Accounts/AC123/Recordings/RE123/Transcriptions.json' + ) + expect(result).toMatchObject({ success: true, output: { transcriptionText: undefined } }) + }) it('authenticates every request with an API key as its SID and secret', async () => { const apiKey = `SK${'b'.repeat(32)}:key-secret` await getTwilioRecording( diff --git a/apps/sim/lib/internal/twilio-voice/operations.ts b/apps/sim/lib/internal/twilio-voice/operations.ts index 07749f689b2..b3b75dff2e9 100644 --- a/apps/sim/lib/internal/twilio-voice/operations.ts +++ b/apps/sim/lib/internal/twilio-voice/operations.ts @@ -37,6 +37,7 @@ interface TwilioRecordingResponse { } interface TwilioTranscription { + recording_sid?: string transcription_text?: string status?: string price?: string @@ -111,9 +112,10 @@ export async function getTwilioRecording( } const mediaUrl = data.uri ? `https://api.twilio.com${data.uri.replace('.json', '')}` : undefined + const recordingSid = data.sid || input.recordingSid let transcription: TwilioTranscription | undefined try { - const url = `https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(input.accountSid)}/Transcriptions.json?RecordingSid=${encodeURIComponent(data.sid || input.recordingSid)}` + const url = `https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(input.accountSid)}/Recordings/${encodeURIComponent(recordingSid)}/Transcriptions.json` const response = await fetchPinned( url, 'transcriptionUrl', @@ -129,7 +131,7 @@ export async function getTwilioRecording( label: 'Twilio transcription response', signal: context.signal, }) - transcription = payload.transcriptions?.[0] + transcription = payload.transcriptions?.find((item) => item.recording_sid === recordingSid) } } catch (error) { context.signal?.throwIfAborted() @@ -154,7 +156,7 @@ export async function getTwilioRecording( signal: context.signal, }) file = { - name: `${data.sid || input.recordingSid}.${getExtensionFromMimeType(mimeType) || 'dat'}`, + name: `${recordingSid}.${getExtensionFromMimeType(mimeType) || 'dat'}`, mimeType, buffer, } diff --git a/apps/sim/lib/internal/typeform/operations.ts b/apps/sim/lib/internal/typeform/operations.ts index 0d5ada8984d..c990e704f44 100644 --- a/apps/sim/lib/internal/typeform/operations.ts +++ b/apps/sim/lib/internal/typeform/operations.ts @@ -1,3 +1,4 @@ +import { getErrorMessage } from '@sim/utils/errors' import { secureFetchWithPinnedIP, validateUrlWithDNS, @@ -11,6 +12,7 @@ import { TypeformOperationError } from '@/lib/internal/typeform/errors' import { uploadCopilotFile } from '@/lib/uploads/contexts/copilot' import { uploadExecutionFile } from '@/lib/uploads/contexts/execution' import type { TypeformFilesParams, TypeformFilesResponse } from '@/tools/typeform/types' +import { safeUrlPathSegment } from '@/tools/url-path' const MAX_TYPEFORM_FILE_BYTES = 10 * 1024 * 1024 @@ -22,9 +24,30 @@ export interface TypeformOperationContext { signal?: AbortSignal } +/** + * Rejects dot segments (which `new URL` would resolve away) before they reach the authenticated request. + * Returns the trimmed, encoded segment; a filename keeps its own whitespace, so it is encoded raw after this check. + */ +function typeformPathSegment( + value: string, + paramName: string, + options?: { allowSeparators?: boolean } +): string { + try { + return safeUrlPathSegment(value, paramName, options) + } catch (error) { + throw new TypeformOperationError(getErrorMessage(error, `Invalid ${paramName}`), 400) + } +} + function buildTypeformFileUrl(input: TypeformFilesParams): string { + const formId = typeformPathSegment(input.formId, 'formId') + const responseId = typeformPathSegment(input.responseId, 'responseId') + const fieldId = typeformPathSegment(input.fieldId, 'fieldId') + typeformPathSegment(input.filename, 'filename', { allowSeparators: true }) + const filename = encodeURIComponent(input.filename) const url = new URL( - `https://api.typeform.com/forms/${encodeURIComponent(input.formId)}/responses/${encodeURIComponent(input.responseId)}/fields/${encodeURIComponent(input.fieldId)}/files/${encodeURIComponent(input.filename)}` + `https://api.typeform.com/forms/${formId}/responses/${responseId}/fields/${fieldId}/files/${filename}` ) if (input.inline !== undefined) url.searchParams.set('inline', String(input.inline)) return url.toString() diff --git a/apps/sim/lib/internal/wordpress/operations.ts b/apps/sim/lib/internal/wordpress/operations.ts index 8f2840bed43..a77c033d586 100644 --- a/apps/sim/lib/internal/wordpress/operations.ts +++ b/apps/sim/lib/internal/wordpress/operations.ts @@ -15,6 +15,7 @@ import { import { downloadServableFileFromStorage } from '@/lib/uploads/utils/file.server' import type { RawFileInput } from '@/lib/uploads/utils/file-schemas' import { assertToolFileAccess } from '@/app/api/files/authorization' +import { safeUrlPathSegment } from '@/tools/url-path' import type { WordPressUploadMediaResponse } from '@/tools/wordpress/types' const logger = createLogger('WordPressOperations') @@ -61,6 +62,12 @@ export async function uploadWordPressMedia( if (!input.file) { throw new WordPressOperationError('No file provided. Please upload a file.', 400) } + let siteSegment: string + try { + siteSegment = safeUrlPathSegment(input.siteId, 'siteId') + } catch (error) { + throw new WordPressOperationError(getErrorMessage(error, 'Invalid siteId'), 400) + } let userFile try { userFile = processSingleFileToUserFile(input.file, context.requestId, logger) @@ -97,7 +104,7 @@ export async function uploadWordPressMedia( if (input.altText) formData.append('alt_text', input.altText) if (input.description) formData.append('description', input.description) - const response = await outboundFetch(`${WORDPRESS_COM_API_BASE}/${input.siteId}/media`, { + const response = await outboundFetch(`${WORDPRESS_COM_API_BASE}/${siteSegment}/media`, { method: 'POST', headers: { Authorization: `Bearer ${input.accessToken}` }, body: formData, diff --git a/apps/sim/lib/internal/zoom/operations.test.ts b/apps/sim/lib/internal/zoom/operations.test.ts index c9f840984e7..e49275b537d 100644 --- a/apps/sim/lib/internal/zoom/operations.test.ts +++ b/apps/sim/lib/internal/zoom/operations.test.ts @@ -48,4 +48,19 @@ describe('getZoomMeetingRecordings', () => { expect.objectContaining({ maxResponseBytes: 2 }) ) }) + + it('double encodes a meeting UUID that starts with a slash', async () => { + mockSecureFetchWithPinnedIP.mockResolvedValueOnce(Response.json({ recording_files: [] })) + + await getZoomMeetingRecordings( + { accessToken: 'token', meetingId: '/ajXp112==' }, + { requestId: 'request-1' } + ) + + expect(mockSecureFetchWithPinnedIP).toHaveBeenLastCalledWith( + 'https://api.zoom.us/v2/meetings/%252FajXp112%253D%253D/recordings', + '203.0.113.1', + expect.anything() + ) + }) }) diff --git a/apps/sim/lib/internal/zoom/operations.ts b/apps/sim/lib/internal/zoom/operations.ts index 98ef6429161..deb94fec59a 100644 --- a/apps/sim/lib/internal/zoom/operations.ts +++ b/apps/sim/lib/internal/zoom/operations.ts @@ -12,6 +12,7 @@ import { ZoomOperationError } from '@/lib/internal/zoom/errors' import { MAX_BUFFERED_TRANSFER_BYTES } from '@/lib/uploads/shared/types' import { getExtensionFromMimeType } from '@/lib/uploads/utils/file' import type { ZoomGetMeetingRecordingsParams } from '@/tools/zoom/types' +import { encodeZoomMeetingPathId } from '@/tools/zoom/utils' const logger = createLogger('ZoomOperations') @@ -63,7 +64,7 @@ export async function getZoomMeetingRecordings( query.set('include_folder_items', String(input.includeFolderItems)) } if (input.ttl) query.set('ttl', String(input.ttl)) - const baseUrl = `https://api.zoom.us/v2/meetings/${encodeURIComponent(input.meetingId)}/recordings` + const baseUrl = `https://api.zoom.us/v2/meetings/${encodeZoomMeetingPathId(input.meetingId)}/recordings` const apiUrl = query.size > 0 ? `${baseUrl}?${query}` : baseUrl const validation = await validateUrlWithDNS(apiUrl, 'apiUrl', 'configuredEndpoint') context.signal?.throwIfAborted() diff --git a/apps/sim/lib/knowledge/search/diagnostics.ts b/apps/sim/lib/knowledge/search/diagnostics.ts index 8bc855b8778..4cb0e6bb2c1 100644 --- a/apps/sim/lib/knowledge/search/diagnostics.ts +++ b/apps/sim/lib/knowledge/search/diagnostics.ts @@ -239,6 +239,8 @@ type SearchProviderSignal = | 'slack.channel_filter_unresolved' /** The channel lookup failed; the search kept its results without a note. */ | 'slack.channel_lookup_failed' + /** A Slack file read returned the preview instead of the file's text. */ + | 'slack.file_preview' const FAILURE_REASONS = [ 'provider_validation', diff --git a/apps/sim/lib/sim-search/live/README.md b/apps/sim/lib/sim-search/live/README.md index 08a3eb1bcc4..c91e5f7d98a 100644 --- a/apps/sim/lib/sim-search/live/README.md +++ b/apps/sim/lib/sim-search/live/README.md @@ -58,7 +58,7 @@ Each event must exist under the source's delegated token, be in an allowed calen ### Slack -Member mode only. Search uses the connected user's Slack real-time search grant and provider search syntax. Date bounds are sent as numeric provider timestamps; date ordering selects keyword retrieval and timestamp sort, because Slack semantic retrieval uses relevance ordering. Channels, messages, direct messages, and files are limited by that grant and provider scopes; there is no admin channel filter in member mode. Missing required search scopes produce a reconnect status. Thread/file reads use the same connected identity. Real-time Search returns at most 20 results a call and counts every page against the member's rate limit, so a search across every source reads one page; a Slack-scoped or native Slack search follows the cursor for up to three pages to fill its limit, and a later page that fails keeps the earlier pages and returns the unread cursor. +Member mode only. Search uses the connected user's Slack real-time search grant and provider search syntax. Date bounds are sent as numeric provider timestamps; date ordering selects keyword retrieval and timestamp sort, because Slack semantic retrieval uses relevance ordering. Channels, messages, direct messages, and files are limited by that grant and provider scopes; there is no admin channel filter in member mode. Missing required search scopes produce a reconnect status. Thread/file reads use the same connected identity. A file read downloads the full text of a canvas (HTML), text snippet, PDF or DOCX from `files.slack.com` only, using `url_private_download` when present (Slack redirects a PDF's `url_private` to a viewer on another domain), never a remote file's own URL (redirects are followed only within that host; a hop elsewhere, such as a sign-in page, keeps the preview), within the shared response-size limit; when Slack will not serve it, the read returns the `files.info` preview. Real-time Search returns at most 20 results a call and counts every page against the member's rate limit, so a search across every source reads one page; a Slack-scoped or native Slack search follows the cursor for up to three pages to fill its limit, and a later page that fails keeps the earlier pages and returns the unread cursor. ### GitHub @@ -131,7 +131,7 @@ Self-managed GitLab is resolved from the saved source's validated host/project i | Drive | `GET /drive/v3/files` with Drive `q` | File metadata, Docs/Slides exports, Sheets values, or supported text media | Delegated Drive file visibility and configured folders/types | | Gmail | `GET /gmail/v1/users/me/messages` with Gmail operators | Anchor plus up to seven independently authorized conversation messages | Same-mailbox delegation, labels, date range, category and custom-query checks | | Calendar | CalendarList then `/calendars/{id}/events` | `/calendars/{id}/events/{eventId}` | Same-user delegation, selected calendars, event window/query | -| Slack | `POST /api/assistant.search.context` | `conversations.replies` or `files.info` preview | Member only; Slack enforces the connected user's grant | +| Slack | `POST /api/assistant.search.context` | `conversations.replies`, or the full text of a Slack-hosted canvas, text, PDF or DOCX file (`files.info` preview otherwise) | Member only; Slack enforces the connected user's grant | | Jira | `POST /ex/jira/{cloudId}/rest/api/3/search/jql` | `/rest/api/3/issue/{key}` under that cloud site | Member only | | Confluence | `/ex/confluence/{cloudId}/wiki/rest/api/search` with CQL | v2 `/wiki/api/v2/pages/{id}` or `/blogposts/{id}` (`body-format=view`); a space reads as its homepage | Same site, spaces, current type/status/labels, source readability | | GitHub | `/search/issues`, `/search/code`, `/search/repositories`, `/search/commits` | Issue, repository, commit, or contents endpoint for returned kind | Added repositories; installation coverage/stable IDs and code filters | diff --git a/apps/sim/lib/sim-search/live/drive-content.ts b/apps/sim/lib/sim-search/live/drive-content.ts index 9c284b97512..05ebcbec2c3 100644 --- a/apps/sim/lib/sim-search/live/drive-content.ts +++ b/apps/sim/lib/sim-search/live/drive-content.ts @@ -1,24 +1,10 @@ import { toStringOrNull } from '@sim/utils/coerce' import { toRecord } from '@sim/utils/object' import { isPayloadSizeLimitError } from '@/lib/core/utils/stream-limits' -import { FileParserError, getFileParserErrorCode } from '@/lib/file-parsers/errors' -import { sniffFileKind } from '@/lib/file-parsers/sniff' -import type { FileParseResult } from '@/lib/file-parsers/types' -import { - assertOoxmlArchiveWithinLimits, - DEFAULT_OOXML_SIZE_LIMITS, -} from '@/lib/file-parsers/zip-guard' +import { documentExtension, extractDocumentText } from '@/lib/sim-search/live/file-text' import { NATIVE_RESPONSE_MAX_BYTES, NativeSearchError, segment } from '@/lib/sim-search/live/http' import type { NativeClient } from '@/lib/sim-search/live/types' -const MAX_DRIVE_TEXT_BYTES = 1024 * 1024 -const MAX_DRIVE_PDF_PAGES = 100 -const DRIVE_DOCX_LIMITS = { - ...DEFAULT_OOXML_SIZE_LIMITS, - maxTotalUncompressedBytes: 10 * 1024 * 1024, - maxEntryUncompressedBytes: 4 * 1024 * 1024, -} - /** Extracts bounded text from the exact downloadable PDF or DOCX identified by Drive metadata. */ export async function readDriveFileContent( client: NativeClient, @@ -37,13 +23,7 @@ export async function readDriveFileContent( 'unavailable', 'Drive does not allow downloading this file. Ask the owner to allow downloads or open the source.' ) - const mimeType = toStringOrNull(row.mimeType) - const extension = - mimeType === 'application/pdf' - ? 'pdf' - : mimeType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - ? 'docx' - : undefined + const extension = documentExtension(toStringOrNull(row.mimeType)) if (!extension) throw new NativeSearchError( 'unavailable', @@ -78,73 +58,5 @@ export async function readDriveFileContent( ) throw error } - signal?.throwIfAborted() - try { - if (bytes.byteLength === 0) throw new FileParserError('empty_input', 'Empty file') - if (bytes.byteLength > NATIVE_RESPONSE_MAX_BYTES) - throw new FileParserError('complexity_limit', 'File exceeds the binary read limit') - const kind = sniffFileKind(bytes, extension) - if (kind === 'encrypted-ooxml') - throw new FileParserError('encrypted_file', 'Encrypted document') - if (kind !== extension) - throw new FileParserError('invalid_format', 'File content does not match its Drive MIME type') - - let parsed: FileParseResult - if (extension === 'pdf') { - const { PdfParser } = await import('@/lib/file-parsers/pdf-parser') - parsed = await new PdfParser().parseBuffer(bytes, { - signal, - pdfTextMode: 'complete', - pdfMaxPages: MAX_DRIVE_PDF_PAGES, - maxTextBytes: MAX_DRIVE_TEXT_BYTES, - }) - } else { - assertOoxmlArchiveWithinLimits(bytes, DRIVE_DOCX_LIMITS) - const { DocxParser } = await import('@/lib/file-parsers/docx-parser') - parsed = await new DocxParser().parseBuffer(bytes, { - signal, - docxTextMode: 'complete', - maxTextBytes: MAX_DRIVE_TEXT_BYTES, - }) - } - signal?.throwIfAborted() - if (parsed.metadata?.degraded || parsed.metadata?.truncated) - throw new FileParserError('complexity_limit', 'Complete document text was not extracted') - if (!parsed.content.trim()) - throw new FileParserError('no_extractable_text', 'No document text was extracted') - if (Buffer.byteLength(parsed.content, 'utf8') > MAX_DRIVE_TEXT_BYTES) - throw new FileParserError('complexity_limit', 'Extracted text exceeds the live-read limit') - return parsed.content - } catch (error) { - signal?.throwIfAborted() - switch (getFileParserErrorCode(error)) { - case 'encrypted_file': - throw new NativeSearchError( - 'unavailable', - 'This file is password-protected. Remove the password from a copy or open the source.' - ) - case 'empty_input': - case 'no_extractable_text': - throw new NativeSearchError( - 'unavailable', - 'No text could be extracted from this file. Image-only scans require OCR; open the source or provide a searchable copy.' - ) - case 'complexity_limit': - throw new NativeSearchError( - 'unavailable', - 'This file exceeds live text extraction limits. Split it into smaller files or open the source.' - ) - case 'invalid_format': - case 'unsupported_type': - throw new NativeSearchError( - 'unavailable', - 'The file content is malformed or does not match its PDF or DOCX type. Re-save it in a supported format or open the source.' - ) - default: - throw new NativeSearchError( - 'unavailable', - 'The file could not be read as text. Retry or open the source.' - ) - } - } + return extractDocumentText(bytes, extension, signal) } diff --git a/apps/sim/lib/sim-search/live/file-text.ts b/apps/sim/lib/sim-search/live/file-text.ts new file mode 100644 index 00000000000..70324912919 --- /dev/null +++ b/apps/sim/lib/sim-search/live/file-text.ts @@ -0,0 +1,105 @@ +import { FileParserError, getFileParserErrorCode } from '@/lib/file-parsers/errors' +import { sniffFileKind } from '@/lib/file-parsers/sniff' +import type { FileParseResult } from '@/lib/file-parsers/types' +import { + assertOoxmlArchiveWithinLimits, + DEFAULT_OOXML_SIZE_LIMITS, +} from '@/lib/file-parsers/zip-guard' +import { NATIVE_RESPONSE_MAX_BYTES, NativeSearchError } from '@/lib/sim-search/live/http' + +/** Extracted text one live file read may return. */ +export const MAX_FILE_TEXT_BYTES = 1024 * 1024 +const MAX_FILE_PDF_PAGES = 100 +const FILE_DOCX_LIMITS = { + ...DEFAULT_OOXML_SIZE_LIMITS, + maxTotalUncompressedBytes: 10 * 1024 * 1024, + maxEntryUncompressedBytes: 4 * 1024 * 1024, +} + +/** The document format `extractDocumentText` reads for a provider-declared MIME type. */ +export function documentExtension(mimeType: string | null | undefined): 'pdf' | 'docx' | undefined { + if (mimeType === 'application/pdf') return 'pdf' + if (mimeType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') + return 'docx' + return undefined +} + +/** + * Extracts the complete, bounded text of a downloaded PDF or DOCX whose bytes must match the type + * its provider declared. Every failure is a NativeSearchError naming what the reader can do. + */ +export async function extractDocumentText( + bytes: Buffer, + extension: 'pdf' | 'docx', + signal?: AbortSignal +): Promise { + signal?.throwIfAborted() + try { + if (bytes.byteLength === 0) throw new FileParserError('empty_input', 'Empty file') + if (bytes.byteLength > NATIVE_RESPONSE_MAX_BYTES) + throw new FileParserError('complexity_limit', 'File exceeds the binary read limit') + const kind = sniffFileKind(bytes, extension) + if (kind === 'encrypted-ooxml') + throw new FileParserError('encrypted_file', 'Encrypted document') + if (kind !== extension) + throw new FileParserError('invalid_format', 'File content does not match its declared type') + + let parsed: FileParseResult + if (extension === 'pdf') { + const { PdfParser } = await import('@/lib/file-parsers/pdf-parser') + parsed = await new PdfParser().parseBuffer(bytes, { + signal, + pdfTextMode: 'complete', + pdfMaxPages: MAX_FILE_PDF_PAGES, + maxTextBytes: MAX_FILE_TEXT_BYTES, + }) + } else { + assertOoxmlArchiveWithinLimits(bytes, FILE_DOCX_LIMITS) + const { DocxParser } = await import('@/lib/file-parsers/docx-parser') + parsed = await new DocxParser().parseBuffer(bytes, { + signal, + docxTextMode: 'complete', + maxTextBytes: MAX_FILE_TEXT_BYTES, + }) + } + signal?.throwIfAborted() + if (parsed.metadata?.degraded || parsed.metadata?.truncated) + throw new FileParserError('complexity_limit', 'Complete document text was not extracted') + if (!parsed.content.trim()) + throw new FileParserError('no_extractable_text', 'No document text was extracted') + if (Buffer.byteLength(parsed.content, 'utf8') > MAX_FILE_TEXT_BYTES) + throw new FileParserError('complexity_limit', 'Extracted text exceeds the live-read limit') + return parsed.content + } catch (error) { + signal?.throwIfAborted() + switch (getFileParserErrorCode(error)) { + case 'encrypted_file': + throw new NativeSearchError( + 'unavailable', + 'This file is password-protected. Remove the password from a copy or open the source.' + ) + case 'empty_input': + case 'no_extractable_text': + throw new NativeSearchError( + 'unavailable', + 'No text could be extracted from this file. Image-only scans require OCR; open the source or provide a searchable copy.' + ) + case 'complexity_limit': + throw new NativeSearchError( + 'unavailable', + 'This file exceeds live text extraction limits. Split it into smaller files or open the source.' + ) + case 'invalid_format': + case 'unsupported_type': + throw new NativeSearchError( + 'unavailable', + 'The file content is malformed or does not match its PDF or DOCX type. Re-save it in a supported format or open the source.' + ) + default: + throw new NativeSearchError( + 'unavailable', + 'The file could not be read as text. Retry or open the source.' + ) + } + } +} diff --git a/apps/sim/lib/sim-search/live/google.ts b/apps/sim/lib/sim-search/live/google.ts index 067cb658f2b..e42ccfba89c 100644 --- a/apps/sim/lib/sim-search/live/google.ts +++ b/apps/sim/lib/sim-search/live/google.ts @@ -124,14 +124,14 @@ export async function readDrive( } else if (document.kind === 'application/vnd.google-apps.spreadsheet') { const metadata = object( await client.json(`/v4/spreadsheets/${segment(id)}`, { - googleService: 'sheets', + service: 'sheets', query: { fields: 'sheets.properties.title' }, }) ) const titles = array(metadata.sheets).map((sheet) => string(object(sheet.properties).title)) const values = object( await client.json(`/v4/spreadsheets/${segment(id)}/values:batchGet`, { - googleService: 'sheets', + service: 'sheets', query: { ranges: titles.slice(0, 20).map((title) => `'${title.replace(/'/g, "''")}'!A1:AZ1000`), valueRenderOption: 'FORMATTED_VALUE', diff --git a/apps/sim/lib/sim-search/live/http.test.ts b/apps/sim/lib/sim-search/live/http.test.ts index 4d4efa0cd49..f0f8bc8c974 100644 --- a/apps/sim/lib/sim-search/live/http.test.ts +++ b/apps/sim/lib/sim-search/live/http.test.ts @@ -6,7 +6,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' vi.mock('@/lib/core/security/input-validation.server', () => inputValidationMock) -import { createNativeClient } from '@/lib/sim-search/live/http' +import { createNativeClient, NativeSearchError } from '@/lib/sim-search/live/http' describe('native search network boundary', () => { beforeEach(() => { @@ -63,16 +63,44 @@ describe('native search network boundary', () => { await expect(client.json('https://evil.test')).rejects.toThrow('Invalid provider path') expect(inputValidationMockFns.mockSecureFetchWithValidation).not.toHaveBeenCalled() }) - it('cannot move a non-Google token to the Sheets API', async () => { + it('only moves a token to the sibling host of its own provider', async () => { + const clientFor = (origin: string) => + createNativeClient({ origin, accessToken: 'private', signal: new AbortController().signal }) + await expect( + clientFor('https://api.github.com').json('/v4/spreadsheets/id', { service: 'sheets' }) + ).rejects.toThrow('Invalid provider service') + await expect( + clientFor('https://www.googleapis.com').text('/files-pri/T1-F1/plan', undefined, { + service: 'slackFiles', + }) + ).rejects.toThrow('Invalid provider service') + expect(inputValidationMockFns.mockSecureFetchWithValidation).not.toHaveBeenCalled() + await clientFor('https://www.googleapis.com').json('/v4/spreadsheets/id', { service: 'sheets' }) + const [url, options] = inputValidationMockFns.mockSecureFetchWithValidation.mock.lastCall ?? [] + expect(url).toBe('https://sheets.googleapis.com/v4/spreadsheets/id') + expect(options).toMatchObject({ maxRedirects: 0 }) + expect(options).not.toHaveProperty('assertRedirectTarget') + }) + it('follows Slack file redirects only within its file host', async () => { const client = createNativeClient({ - origin: 'https://api.github.com', + origin: 'https://slack.com', accessToken: 'private', signal: new AbortController().signal, }) - await expect(client.json('/v4/spreadsheets/id', { googleService: 'sheets' })).rejects.toThrow( - 'Invalid Google service' - ) - expect(inputValidationMockFns.mockSecureFetchWithValidation).not.toHaveBeenCalled() + await client.text('/files-pri/T1-F1/plan', undefined, { service: 'slackFiles' }) + const [url, options] = inputValidationMockFns.mockSecureFetchWithValidation.mock.lastCall ?? [] + expect(url).toBe('https://files.slack.com/files-pri/T1-F1/plan') + expect(options?.maxRedirects).toBeGreaterThan(0) + const assertTarget = options?.assertRedirectTarget + expect(() => + assertTarget('https://files.slack.com/files-pri/T1-F1/download/plan') + ).not.toThrow() + for (const target of [ + 'https://team.slack.com/?redir=%2Ffiles-pri%2FT1-F1', + 'https://files.slack.com.example.com/plan', + 'http://files.slack.com/files-pri/T1-F1/plan', + ]) + expect(() => assertTarget(target)).toThrow(NativeSearchError) }) it('keeps the HTTP status of a provider failure so callers can tell a missing item apart', async () => { const client = createNativeClient({ diff --git a/apps/sim/lib/sim-search/live/http.ts b/apps/sim/lib/sim-search/live/http.ts index 0d878690a1e..175de822e63 100644 --- a/apps/sim/lib/sim-search/live/http.ts +++ b/apps/sim/lib/sim-search/live/http.ts @@ -6,7 +6,7 @@ import { type SearchFailureReason, withSearchRequestDiagnostics, } from '@/lib/knowledge/search/diagnostics' -import type { NativeClient } from '@/lib/sim-search/live/types' +import type { NativeClient, NativeRequestOptions } from '@/lib/sim-search/live/types' import { isGoogleQuotaReason, safeGoogleErrorReasons, @@ -30,7 +30,34 @@ export const NATIVE_SEARCH_REQUEST_BUDGET = 30 /** Decoded bytes allowed in any native provider response, including file downloads. */ export const NATIVE_RESPONSE_MAX_BYTES = 4 * 1024 * 1024 -/** Tokens only go to a code-selected provider origin; redirects never carry credentials. */ +/** + * Sibling hosts a provider's token may reach, each only from its own provider origin: Google + * serves Sheets apart from Drive, and Slack serves file contents apart from its Web API. Slack's + * file host follows redirects only within itself: Slack sends a token it will not serve to a + * workspace sign-in page, which must be refused rather than read as the file. + */ +const NATIVE_SERVICES = { + sheets: { + origin: 'https://www.googleapis.com', + hostname: 'sheets.googleapis.com', + maxRedirects: 0, + }, + slackFiles: { origin: 'https://slack.com', hostname: 'files.slack.com', maxRedirects: 3 }, +} as const + +function assertSameHost(requested: URL, target: string) { + const next = new URL(target) + if (next.origin !== requested.origin) + throw new NativeSearchError( + 'unavailable', + `The provider redirected this file to ${next.hostname}, outside its file host. Open the source.` + ) +} + +/** A sibling host a request may target instead of its client's provider origin. */ +export type NativeService = keyof typeof NATIVE_SERVICES + +/** Tokens only go to a code-selected provider origin; a redirect never carries them elsewhere. */ export function createNativeClient(input: { origin: string accessToken: string @@ -46,12 +73,7 @@ export function createNativeClient(input: { async function request( path: string, options: - | { - query?: Record - body?: unknown - googleService?: 'sheets' - signal?: AbortSignal - } + | (NativeRequestOptions & { query?: Record; body?: unknown }) | undefined, read: (response: Awaited>) => Promise ) { @@ -69,9 +91,10 @@ export function createNativeClient(input: { 'request_budget_exceeded' ) const url = new URL(input.origin) - if (options?.googleService === 'sheets') { - if (url.origin !== 'https://www.googleapis.com') throw new Error('Invalid Google service') - url.hostname = 'sheets.googleapis.com' + const service = options?.service ? NATIVE_SERVICES[options.service] : undefined + if (service) { + if (url.origin !== service.origin) throw new Error('Invalid provider service') + url.hostname = service.hostname } if (!path.startsWith('/') || path.startsWith('//') || path.includes('\\')) throw new Error('Invalid provider path') @@ -96,7 +119,10 @@ export function createNativeClient(input: { signal, timeout: 10_000, maxResponseBytes: NATIVE_RESPONSE_MAX_BYTES, - maxRedirects: 0, + maxRedirects: service?.maxRedirects ?? 0, + ...(service?.maxRedirects + ? { assertRedirectTarget: (target: string) => assertSameHost(url, target) } + : {}), acceptCompressed: true, connectionPool: input.pool, }) @@ -164,8 +190,10 @@ export function createNativeClient(input: { }, async bytes(path, query, options) { try { - return await request(path, { query, signal: options?.signal }, async (response) => - Buffer.from(await response.arrayBuffer()) + return await request( + path, + { query, service: options?.service, signal: options?.signal }, + async (response) => Buffer.from(await response.arrayBuffer()) ) } catch (error) { input.signal.throwIfAborted() @@ -173,7 +201,11 @@ export function createNativeClient(input: { } }, async text(path, query, options) { - return request(path, { query, signal: options?.signal }, (response) => response.text()) + return request( + path, + { query, service: options?.service, signal: options?.signal }, + (response) => response.text() + ) }, }) } @@ -191,8 +223,10 @@ export function withRequestSignal(client: NativeClient, signal: AbortSignal): Na path, options?.memo && !options.body ? options : { ...options, signal: scoped(options?.signal) } ), - text: (path, query, options) => client.text(path, query, { signal: scoped(options?.signal) }), - bytes: (path, query, options) => client.bytes(path, query, { signal: scoped(options?.signal) }), + text: (path, query, options) => + client.text(path, query, { ...options, signal: scoped(options?.signal) }), + bytes: (path, query, options) => + client.bytes(path, query, { ...options, signal: scoped(options?.signal) }), } } @@ -208,7 +242,7 @@ export function withJsonMemo(client: NativeClient): NativeClient { json(...request) { const [path, options] = request if (!options?.memo || options.body) return client.json(...request) - const key = JSON.stringify([path, options.query, options.googleService]) + const key = JSON.stringify([path, options.query, options.service]) let pending = memo.get(key) if (!pending) { pending = client.json(...request) diff --git a/apps/sim/lib/sim-search/live/providers.ts b/apps/sim/lib/sim-search/live/providers.ts index 8f56a83689a..09f75ab7d48 100644 --- a/apps/sim/lib/sim-search/live/providers.ts +++ b/apps/sim/lib/sim-search/live/providers.ts @@ -177,8 +177,15 @@ export const LIVE_SEARCH_PROVIDERS = { 'joining alternatives with OR or spaces in one query, which keyword retrieval treats as all required; send them as separate native queries.', }, search: searchSlack, - read: (client, reference) => - readSlack(client, reference.id, reference.container, reference.kind, reference.threadId), + read: (client, reference, options) => + readSlack( + client, + reference.id, + reference.container, + reference.kind, + reference.threadId, + options.signal + ), }, jira: { guide: { diff --git a/apps/sim/lib/sim-search/live/slack.test.ts b/apps/sim/lib/sim-search/live/slack.test.ts new file mode 100644 index 00000000000..9eee86263b6 --- /dev/null +++ b/apps/sim/lib/sim-search/live/slack.test.ts @@ -0,0 +1,226 @@ +/** + * @vitest-environment node + */ + +import { getMockLogger } from '@sim/testing/mocks/logger.mock' +import { PDFDocument, StandardFonts } from 'pdf-lib' +import { describe, expect, it, vi } from 'vitest' +import { + withSearchDiagnostics, + withSearchProviderDiagnostics, +} from '@/lib/knowledge/search/diagnostics' +import { NativeSearchError } from '@/lib/sim-search/live/http' +import { readSlack } from '@/lib/sim-search/live/slack' + +const FILE_URL = 'https://files.slack.com/files-pri/T1-F123/plan' + +function fileClient(file: Record, download?: () => Promise) { + return { + json: vi.fn(async () => ({ + ok: true, + file: { + title: 'Rollout plan', + permalink: 'https://sim.slack.com/files/U1/F123/plan', + preview_plain_text: 'Short preview', + url_private: FILE_URL, + size: 2048, + ...file, + }, + })), + text: vi.fn(), + bytes: vi.fn(async () => { + const body = await (download ?? (async () => 'Full text'))() + return typeof body === 'string' ? Buffer.from(body) : body + }), + } +} + +describe('Slack file reads', () => { + it('reads the full text of a canvas from the Slack file host', async () => { + const api = fileClient( + { filetype: 'quip', mimetype: 'application/vnd.slack-docs' }, + async () => '

Rollout

Phase two starts after the audit.

' + ) + const read = await readSlack(api, 'F123', undefined, 'file') + expect(read.content).toContain('Phase two starts after the audit.') + expect(read.content).not.toContain('

') + expect(read.content).not.toContain('Short preview') + expect(api.bytes).toHaveBeenCalledWith( + '/files-pri/T1-F123/plan', + {}, + expect.objectContaining({ service: 'slackFiles' }) + ) + }) + it('downloads from the Slack download URL when the file has one', async () => { + const api = fileClient({ + mimetype: 'text/plain', + url_private_download: 'https://files.slack.com/files-pri/T1-F123/download/plan', + }) + expect((await readSlack(api, 'F123', undefined, 'file')).content).toBe('Full text') + expect(api.bytes).toHaveBeenCalledWith( + '/files-pri/T1-F123/download/plan', + {}, + expect.objectContaining({ service: 'slackFiles' }) + ) + }) + it('reads the full text of a text snippet', async () => { + const api = fileClient( + { filetype: 'text', mimetype: 'text/plain' }, + async () => 'line one\nline two' + ) + expect((await readSlack(api, 'F123', undefined, 'file')).content).toBe('line one\nline two') + }) + it('extracts the full text of a PDF downloaded from the Slack file host', async () => { + const pdf = await PDFDocument.create() + const font = await pdf.embedFont(StandardFonts.Helvetica) + pdf.addPage().drawText('Phase two starts after the audit.', { x: 50, y: 700, font, size: 12 }) + const api = fileClient({ mimetype: 'application/pdf', filetype: 'pdf' }) + api.bytes.mockResolvedValue(Buffer.from(await pdf.save())) + const read = await readSlack(api, 'F123', undefined, 'file') + expect(read.content).toContain('Phase two starts after the audit.') + expect(api.bytes).toHaveBeenCalledWith( + '/files-pri/T1-F123/plan', + {}, + expect.objectContaining({ service: 'slackFiles' }) + ) + }) + it('never sends the token to a file host other than Slack', async () => { + for (const file of [ + { mimetype: 'text/plain', url_private: 'https://files.example.com/plan.txt' }, + { mimetype: 'text/plain', is_external: true }, + ]) { + const api = fileClient(file) + expect((await readSlack(api, 'F123', undefined, 'file')).content).toContain('Short preview') + expect(api.bytes).not.toHaveBeenCalled() + } + }) + it('keeps the preview when Slack will not serve the file, without suggesting a reconnect', async () => { + const tooLarge = fileClient({ mimetype: 'application/pdf' }, async () => { + throw new NativeSearchError('unavailable', 'This file exceeds the 4 MiB live-read limit.') + }) + const large = await readSlack(tooLarge, 'F123', undefined, 'file') + expect(large.content).toContain( + 'Full text unavailable: This file exceeds the 4 MiB live-read limit.' + ) + expect(large.content).toContain('Short preview') + const denied = fileClient({ mimetype: 'text/plain' }, async () => { + throw new NativeSearchError( + 'reconnect', + 'The provider denied access. Reconnect your account with search and read permissions.', + undefined, + 403 + ) + }) + const read = await readSlack(denied, 'F123', undefined, 'file') + expect(read.content).toContain( + "Full text unavailable: Slack did not serve this file's contents" + ) + expect(read.content).not.toContain('Reconnect') + expect(read.content).toContain('Short preview') + const throttled = fileClient({ mimetype: 'text/plain' }, async () => { + throw new NativeSearchError( + 'rate_limited', + 'Provider rate limit reached. Try again later.', + 30, + 403 + ) + }) + expect((await readSlack(throttled, 'F123', undefined, 'file')).content).toContain( + 'Full text unavailable: Provider rate limit reached. Try again later.' + ) + const relink = fileClient({ mimetype: 'text/plain' }, async () => { + throw new NativeSearchError('reconnect', 'Reconnect this provider to restore its API host.') + }) + expect((await readSlack(relink, 'F123', undefined, 'file')).content).toContain( + 'Full text unavailable: Reconnect this provider to restore its API host.' + ) + for (const failure of [ + new Error('Too many redirects (max: 0)'), + new DOMException('The operation timed out.', 'TimeoutError'), + ]) { + const api = fileClient({ mimetype: 'text/plain' }, async () => { + throw failure + }) + const caller = new AbortController().signal + const read = await readSlack(api, 'F123', undefined, 'file', undefined, caller) + expect(read.content).toContain('Short preview') + } + }) + it('does not let an abandoned download pass as a preview', async () => { + const controller = new AbortController() + const aborted = new DOMException('aborted', 'AbortError') + const api = fileClient({ mimetype: 'text/plain' }, async () => { + controller.abort(aborted) + throw aborted + }) + await expect( + readSlack(api, 'F123', undefined, 'file', undefined, controller.signal) + ).rejects.toBe(aborted) + }) + it('keeps the preview when the file holds more text than one read returns', async () => { + const api = fileClient({ mimetype: 'text/plain', size: undefined }, async () => + 'x'.repeat(1024 * 1024 + 1) + ) + expect((await readSlack(api, 'F123', undefined, 'file')).content).toContain('Short preview') + }) + it('reads markup declared with parameters as HTML', async () => { + const api = fileClient( + { mimetype: 'Text/HTML; charset=utf-8' }, + async () => '

Rendered text

' + ) + expect((await readSlack(api, 'F123', undefined, 'file')).content).toBe('Rendered text') + }) + it('decodes text in the charset its bytes declare', async () => { + const utf16 = Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from('Größe: 3', 'utf16le')]) + const bom = fileClient({ mimetype: 'text/plain' }, async () => utf16) + expect((await readSlack(bom, 'F123', undefined, 'file')).content).toBe('Größe: 3') + const latin1 = fileClient({ mimetype: 'text/plain; charset=ISO-8859-1' }, async () => + Buffer.from('Größe: 3', 'latin1') + ) + expect((await readSlack(latin1, 'F123', undefined, 'file')).content).toBe('Größe: 3') + const utf8 = Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), Buffer.from('Größe: 3')]) + const marked = fileClient({ mimetype: 'text/plain; charset=ISO-8859-1' }, async () => utf8) + expect((await readSlack(marked, 'F123', undefined, 'file')).content).toBe('Größe: 3') + }) + it('keeps the preview when text bytes cannot be read in their charset', async () => { + for (const bytes of [ + Buffer.from('Plan: 3', 'utf16le'), + Buffer.from([0x47, 0x72, 0xff, 0xfe, 0x21]), + ]) { + const api = fileClient({ mimetype: 'text/plain' }, async () => bytes) + expect((await readSlack(api, 'F123', undefined, 'file')).content).toContain('Short preview') + } + }) + it('counts every read that returns the preview instead of the text', async () => { + await withSearchDiagnostics({ surface: 'mcp' }, () => + withSearchProviderDiagnostics({ provider: 'slack', accountIndex: 0 }, async () => { + await readSlack(fileClient({ mimetype: 'image/png' }), 'F123', undefined, 'file') + await readSlack( + fileClient({ mimetype: 'text/plain' }, async () => { + throw new Error('Too many redirects (max: 0)') + }), + 'F123', + undefined, + 'file' + ) + await readSlack(fileClient({ mimetype: 'text/plain' }), 'F123', undefined, 'file') + }) + ) + const summary = getMockLogger('KnowledgeSearchDiagnostics').info.mock.calls.find( + ([message]) => message === 'Live search provider completed' + )?.[1] + expect(summary?.signals).toEqual({ 'slack.file_preview': 2 }) + }) + it('skips the download for files it cannot read as text', async () => { + for (const file of [ + { mimetype: 'image/png', filetype: 'png' }, + { mimetype: 'text/plain', size: 2 * 1024 * 1024 }, + { filetype: 'quip', mimetype: 'application/vnd.slack-docs', size: 3 * 1024 * 1024 }, + ]) { + const api = fileClient(file) + expect((await readSlack(api, 'F123', undefined, 'file')).content).toContain('Short preview') + expect(api.text).not.toHaveBeenCalled() + expect(api.bytes).not.toHaveBeenCalled() + } + }) +}) diff --git a/apps/sim/lib/sim-search/live/slack.ts b/apps/sim/lib/sim-search/live/slack.ts index 8db571be21c..c8502dd83f6 100644 --- a/apps/sim/lib/sim-search/live/slack.ts +++ b/apps/sim/lib/sim-search/live/slack.ts @@ -1,6 +1,18 @@ +import { slackFileDownloadUrl } from '@/lib/internal/slack/file-download' import { recordSearchProviderSignal } from '@/lib/knowledge/search/diagnostics' import { dateSortDirection, nativeDateBounds, nativeText } from '@/lib/sim-search/live/dates' -import { array, NativeSearchError, object, string } from '@/lib/sim-search/live/http' +import { + documentExtension, + extractDocumentText, + MAX_FILE_TEXT_BYTES, +} from '@/lib/sim-search/live/file-text' +import { + array, + NATIVE_RESPONSE_MAX_BYTES, + NativeSearchError, + object, + string, +} from '@/lib/sim-search/live/http' import { joinMessages } from '@/lib/sim-search/live/pages' import { permitsResources } from '@/lib/sim-search/live/policy' import { @@ -8,6 +20,7 @@ import { slackConversationUrl, slackPlainText, } from '@/lib/sim-search/live/slack-format' +import { providerText } from '@/lib/sim-search/live/text' import type { NativeClient, NativeDocument, @@ -17,6 +30,15 @@ import type { /** Slack's own label for an account whose name is unavailable. */ const SLACK_MEMBER = 'Slack member' +/** Time a file download may take before the read settles for the preview it already has. */ +const FILE_DOWNLOAD_TIMEOUT_MS = 5_000 +/** Bytes downloaded per format: markup roughly doubles a canvas's text. */ +const MAX_FILE_DOWNLOAD_BYTES = { + html: 2 * MAX_FILE_TEXT_BYTES, + plain: MAX_FILE_TEXT_BYTES, + pdf: NATIVE_RESPONSE_MAX_BYTES, + docx: NATIVE_RESPONSE_MAX_BYTES, +} as const /** Directory lookups one read may make; a DM or typical thread has only a few authors. */ const MAX_AUTHOR_LOOKUPS = 10 @@ -326,24 +348,114 @@ async function searchSlackPage( } } +type SlackFileFormat = 'html' | 'plain' | 'pdf' | 'docx' + +/** How a file's full text can be read, or undefined when Slack offers only its preview. */ +function slackFileFormat(file: Record): SlackFileFormat | undefined { + const mimetype = string(file.mimetype).split(';')[0].trim().toLowerCase() + if ( + string(file.filetype) === 'quip' || + mimetype === 'application/vnd.slack-docs' || + mimetype === 'text/html' + ) + return 'html' + if (mimetype.startsWith('text/') || mimetype === 'application/json') return 'plain' + return documentExtension(mimetype) +} + +const BYTE_ORDER_MARKS = [ + [[0xef, 0xbb, 0xbf], 'utf-8'], + [[0xff, 0xfe], 'utf-16le'], + [[0xfe, 0xff], 'utf-16be'], +] as const + +/** + * Decodes downloaded text strictly: a byte-order mark wins, then the declared charset, then UTF-8. + * Bytes invalid in that charset, or text holding NULs (UTF-16 without a mark), are unreadable. + */ +function decodeFileText(bytes: Buffer, mimetype: string): string | undefined { + const charset = /;\s*charset="?([\w.:-]+)"?/i.exec(mimetype)?.[1] + const label = + BYTE_ORDER_MARKS.find(([mark]) => mark.every((byte, index) => bytes[index] === byte))?.[1] ?? + charset ?? + 'utf-8' + let text: string + try { + text = new TextDecoder(label, { fatal: true }).decode(bytes) + } catch { + return undefined + } + return text.includes('\u0000') ? undefined : text +} + +/** + * The full text of a file Slack hosts: canvases as HTML, snippets and text files as text, PDF and + * DOCX extracted, from Slack's download URL when it has one. The token only goes to Slack's file + * host. Short of the caller aborting, any failure (denial, redirect, size limit, unreadable bytes, + * slow download) leaves the read with its preview and a reason when one applies. + */ +async function slackFileText( + client: NativeClient, + file: Record, + signal?: AbortSignal +): Promise<{ text: string } | { unavailable?: string }> { + const format = slackFileFormat(file) + if (!format || Number(file.size) > MAX_FILE_DOWNLOAD_BYTES[format]) return {} + const source = slackFileDownloadUrl(file) + if (!source) return {} + const timeout = AbortSignal.timeout(FILE_DOWNLOAD_TIMEOUT_MS) + const download = signal ? AbortSignal.any([signal, timeout]) : timeout + const request = { service: 'slackFiles', signal: download } as const + const query = Object.fromEntries(source.searchParams) + try { + const bytes = await client.bytes(source.pathname, query, request) + if (format === 'pdf' || format === 'docx') + return { text: await extractDocumentText(bytes, format, download) } + const decoded = decodeFileText(bytes, string(file.mimetype)) + const text = decoded && providerText(decoded, format) + return text && Buffer.byteLength(text, 'utf8') <= MAX_FILE_TEXT_BYTES ? { text } : {} + } catch (error) { + signal?.throwIfAborted() + if (!(error instanceof NativeSearchError)) return {} + // files.info already accepted this token, so reconnecting would not change a refused file. + return { + unavailable: + error.status === 'reconnect' && (error.httpStatus === 401 || error.httpStatus === 403) + ? "Slack did not serve this file's contents to your account. Open the source." + : error.message, + } + } +} + export async function readSlack( client: NativeClient, id: string, channel?: string, kind?: string, - threadId?: string + threadId?: string, + signal?: AbortSignal ): Promise { if (kind === 'file') { if (!/^F[A-Z0-9]+$/.test(id)) throw new NativeSearchError('unavailable', 'Invalid Slack file reference.') const data = slackResult(await client.json('/api/files.info', { query: { file: id } })) const file = object(data.file) + const full = await slackFileText(client, file, signal) + if (!('text' in full)) recordSearchProviderSignal('slack.file_preview') return { id, kind, title: string(file.title), url: string(file.permalink), - content: `File preview (open the source for full contents):\n${string(file.preview_plain_text) || string(file.preview) || string(file.title)}`, + content: + 'text' in full + ? full.text + : [ + full.unavailable && `Full text unavailable: ${full.unavailable}`, + `File preview (open the source for full contents):\n${string(file.preview_plain_text) || string(file.preview) || string(file.title)}`, + ] + .filter(Boolean) + .join('\n\n'), } } if ( diff --git a/apps/sim/lib/sim-search/live/types.ts b/apps/sim/lib/sim-search/live/types.ts index 171d6502354..3e3fafb8d1d 100644 --- a/apps/sim/lib/sim-search/live/types.ts +++ b/apps/sim/lib/sim-search/live/types.ts @@ -3,6 +3,7 @@ import type { LiveSearchProvider, NativeSearchQuery, } from '@/lib/api/contracts/mothership-assistant-tools' +import type { NativeService } from '@/lib/sim-search/live/http' import type { LiveSearchPolicy } from '@/lib/sim-search/live/policy-schema' import type { TextMatch } from '@/lib/sim-search/live/text-match' @@ -77,28 +78,33 @@ export interface NativePage { message?: string } +/** Per-request options shared by every native client method. */ +export interface NativeRequestOptions { + /** Sends the request to a sibling host of the client's provider origin. */ + service?: NativeService + /** Cancels this request alongside the client's own signal. */ + signal?: AbortSignal +} + export interface NativeClient { json( path: string, - options?: { + options?: NativeRequestOptions & { query?: Record body?: unknown - googleService?: 'sheets' /** Reuse this client's earlier response to the same GET instead of requesting it again. */ memo?: boolean - /** Cancels this request alongside the client's own signal. */ - signal?: AbortSignal } ): Promise text( path: string, query?: Record, - options?: { signal?: AbortSignal } + options?: NativeRequestOptions ): Promise bytes( path: string, query?: Record, - options?: { signal?: AbortSignal } + options?: NativeRequestOptions ): Promise } diff --git a/apps/sim/lib/webhooks/providers/slack.test.ts b/apps/sim/lib/webhooks/providers/slack.test.ts index 5f7f7047ac0..934160ba1e5 100644 --- a/apps/sim/lib/webhooks/providers/slack.test.ts +++ b/apps/sim/lib/webhooks/providers/slack.test.ts @@ -1,9 +1,14 @@ import { createHmac } from 'node:crypto' import { authOAuthUtilsMock, authOAuthUtilsMockFns } from '@sim/testing/mocks/auth-oauth-utils.mock' import { queueTableRows } from '@sim/testing/mocks/database.mock' +import { + inputValidationMock, + inputValidationMockFns, +} from '@sim/testing/mocks/input-validation.mock' import { schemaMock } from '@sim/testing/mocks/schema.mock' -import { describe, expect, it, vi } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' import { OutboundRoutingError } from '@/lib/core/network/routing' +import { assertSlackFileHost } from '@/lib/internal/slack/file-download' import { handleSlackChallenge, resolveSlackEventKey, @@ -12,6 +17,9 @@ import { } from '@/lib/webhooks/providers/slack' vi.mock('@/lib/oauth/credential-service', () => authOAuthUtilsMock) +vi.mock('@/lib/core/security/input-validation.server', () => inputValidationMock) +const { mockOutboundFetch } = vi.hoisted(() => ({ mockOutboundFetch: vi.fn() })) +vi.mock('@/lib/core/network/outbound-fetch.server', () => ({ outboundFetch: mockOutboundFetch })) const ctx = (body: unknown) => ({ webhook: {}, @@ -197,6 +205,91 @@ describe('slackHandler formatInput - native app bot token', () => { }) }) +describe('slackHandler formatInput - file downloads', () => { + beforeEach(() => { + inputValidationMockFns.mockValidateUrlWithDNS.mockResolvedValue({ + isValid: true, + resolvedIP: '93.184.216.34', + originalHostname: 'files.slack.com', + }) + inputValidationMockFns.mockSecureFetchWithPinnedIP.mockResolvedValue( + new Response(Buffer.from('%PDF'), { status: 200 }) + ) + }) + + async function formatWithFiles(files: Record[]) { + const formatInput = slackHandler.formatInput + if (!formatInput) throw new Error('Slack handler has no formatInput') + return formatInput({ + ...ctx({ event: { type: 'message', channel: 'C1', user: 'U1', text: 'see file', files } }), + webhook: { providerConfig: { botToken: 'xoxb-test', includeFiles: true } }, + query: {}, + method: 'POST', + }) + } + + it('downloads from the Slack download URL and keeps redirects on the file host', async () => { + const { input } = await formatWithFiles([ + { + id: 'F1', + name: 'report.pdf', + mimetype: 'application/pdf', + size: 4, + url_private: 'https://files.slack.com/files-pri/T1-F1/report.pdf', + url_private_download: 'https://files.slack.com/files-pri/T1-F1/download/report.pdf', + }, + ]) + + const [url, , options] = inputValidationMockFns.mockSecureFetchWithPinnedIP.mock.lastCall ?? [] + expect(url).toBe('https://files.slack.com/files-pri/T1-F1/download/report.pdf') + expect(options).toMatchObject({ assertRedirectTarget: assertSlackFileHost }) + expect(eventOf(input).files).toHaveLength(1) + }) + + it("looks up the download URL when the event carries only the file's private URL", async () => { + mockOutboundFetch.mockResolvedValueOnce( + Response.json({ + ok: true, + file: { + id: 'F3', + url_private: 'https://files.slack.com/files-pri/T1-F3/report.pdf', + url_private_download: 'https://files.slack.com/files-pri/T1-F3/download/report.pdf', + }, + }) + ) + + const { input } = await formatWithFiles([ + { + id: 'F3', + name: 'report.pdf', + mimetype: 'application/pdf', + size: 4, + url_private: 'https://files.slack.com/files-pri/T1-F3/report.pdf', + }, + ]) + + expect(inputValidationMockFns.mockSecureFetchWithPinnedIP.mock.lastCall?.[0]).toBe( + 'https://files.slack.com/files-pri/T1-F3/download/report.pdf' + ) + expect(eventOf(input).files).toHaveLength(1) + }) + + it('never sends the bot token to a file hosted outside Slack', async () => { + const { input } = await formatWithFiles([ + { + id: 'F2', + name: 'plan.pdf', + is_external: true, + url_private: 'https://files.slack.com/files-pri/T1-F2/plan.pdf', + }, + ]) + + expect(mockOutboundFetch).not.toHaveBeenCalled() + expect(inputValidationMockFns.mockSecureFetchWithPinnedIP).not.toHaveBeenCalled() + expect(eventOf(input).files).toEqual([]) + }) +}) + describe('slackHandler formatInput - interactivity (block_actions)', () => { it('carries the full view (state.values + private_metadata) through for a view_submission', async () => { const { input } = await slackHandler.formatInput!( diff --git a/apps/sim/lib/webhooks/providers/slack.ts b/apps/sim/lib/webhooks/providers/slack.ts index 2f0cc3b884f..0c8299d9124 100644 --- a/apps/sim/lib/webhooks/providers/slack.ts +++ b/apps/sim/lib/webhooks/providers/slack.ts @@ -15,6 +15,11 @@ import { secureFetchWithPinnedIP, validateUrlWithDNS, } from '@/lib/core/security/input-validation.server' +import { + assertSlackFileHost, + isExternalSlackFile, + slackFileDownloadUrl, +} from '@/lib/internal/slack/file-download' import { getSlackBotCredential, refreshAccessTokenIfNeeded, @@ -287,7 +292,7 @@ function formatSlackInteractive(b: Record): SlackTriggerEvent { async function resolveSlackFileInfo( fileId: string, botToken: string -): Promise<{ url_private?: string; name?: string; mimetype?: string; size?: number } | null> { +): Promise | null> { try { const response = await outboundFetch( `https://slack.com/api/files.info?file=${encodeURIComponent(fileId)}`, @@ -302,12 +307,7 @@ async function resolveSlackFileInfo( logger.warn('Slack files.info failed', { fileId, error: data.error }) return null } - return { - url_private: data.file.url_private as string | undefined, - name: data.file.name as string | undefined, - mimetype: data.file.mimetype as string | undefined, - size: data.file.size as number | undefined, - } + return data.file } catch (error) { logger.error('Error calling Slack files.info', { fileId, @@ -325,30 +325,19 @@ async function downloadSlackFiles( const downloaded: Array<{ name: string; data: string; mimeType: string; size: number }> = [] for (const file of filesToProcess) { - const f = file as Record - let urlPrivate = f.url_private as string | undefined - let fileName = f.name as string | undefined - let fileMimeType = f.mimetype as string | undefined - let fileSize = f.size as number | undefined - - if (!urlPrivate && f.id) { + let f = file as Record + if (!f.url_private_download && f.id && !isExternalSlackFile(f)) { const resolved = await resolveSlackFileInfo(f.id as string, botToken) - if (resolved?.url_private) { - urlPrivate = resolved.url_private - fileName = fileName || resolved.name - fileMimeType = fileMimeType || resolved.mimetype - fileSize = fileSize ?? resolved.size - } + if (resolved) f = { ...f, ...resolved } } - if (!urlPrivate) { - logger.warn('Slack file has no url_private and could not be resolved, skipping', { - fileId: f.id, - }) + const downloadUrl = slackFileDownloadUrl(f)?.href + if (!downloadUrl) { + logger.warn('Slack file has no Slack-hosted download URL, skipping', { fileId: f.id }) continue } - const reportedSize = Number(fileSize) || 0 + const reportedSize = Number(f.size) || 0 if (reportedSize > SLACK_MAX_FILE_SIZE) { logger.warn('Slack file exceeds size limit, skipping', { fileId: f.id, @@ -359,18 +348,19 @@ async function downloadSlackFiles( } try { - const urlValidation = await validateUrlWithDNS(urlPrivate, 'url_private', 'contentFetch') + const urlValidation = await validateUrlWithDNS(downloadUrl, 'downloadUrl', 'contentFetch') if (!urlValidation.isValid) { - logger.warn('Slack file url_private failed DNS validation, skipping', { + logger.warn('Slack file download URL failed DNS validation, skipping', { fileId: f.id, error: urlValidation.error, }) continue } - const response = await secureFetchWithPinnedIP(urlPrivate, urlValidation.resolvedIP, { + const response = await secureFetchWithPinnedIP(downloadUrl, urlValidation.resolvedIP, { profile: 'contentFetch', headers: { Authorization: `Bearer ${botToken}` }, + assertRedirectTarget: assertSlackFileHost, }) if (!response.ok) { @@ -394,9 +384,9 @@ async function downloadSlackFiles( } downloaded.push({ - name: fileName || 'download', + name: (f.name as string | undefined) || 'download', data: buffer.toString('base64'), - mimeType: fileMimeType || 'application/octet-stream', + mimeType: (f.mimetype as string | undefined) || 'application/octet-stream', size: buffer.length, }) } catch (error) { diff --git a/apps/sim/lib/workflows/search-replace/indexer.ts b/apps/sim/lib/workflows/search-replace/indexer.ts index c2f6880c816..cccaa00e5b5 100644 --- a/apps/sim/lib/workflows/search-replace/indexer.ts +++ b/apps/sim/lib/workflows/search-replace/indexer.ts @@ -137,7 +137,6 @@ const DISPLAY_ONLY_SUBBLOCK_TYPES = new Set([ 'webhook-config', ]) -const TEXT_VALUE_ONLY_SUBBLOCK_TYPES = new Set(['filter-builder', 'variables-input']) const DISPLAY_LABEL_READONLY_REASON = 'Display labels cannot be replaced' const TOOL_INPUT_TEXT_EXCLUDED_LEAF_KEYS = new Set([ @@ -227,9 +226,6 @@ function isSearchableLeafPath( return false } } - if (mode === 'text' && subBlockType && TEXT_VALUE_ONLY_SUBBLOCK_TYPES.has(subBlockType)) { - return lastSegment === 'value' - } if ( mode === 'text' && (subBlockType === 'input-format' || diff --git a/apps/sim/lib/workflows/search-replace/json-value-fields.ts b/apps/sim/lib/workflows/search-replace/json-value-fields.ts index 37b78cc08f7..6f478dfac9f 100644 --- a/apps/sim/lib/workflows/search-replace/json-value-fields.ts +++ b/apps/sim/lib/workflows/search-replace/json-value-fields.ts @@ -23,6 +23,9 @@ const SEARCHABLE_JSON_ARRAY_VALUE_FIELDS: Partial> = { @@ -99,6 +102,7 @@ export function isSearchableJsonValueSubBlock( | 'knowledge-tag-filters' | 'document-tag-entry' | 'variables-input' + | 'filter-builder' | 'input-mapping' | 'workflow-input-mapper' | 'table' { @@ -110,11 +114,18 @@ export function isSearchableJsonValueSubBlock( ) } +/** + * Rule builders stay as their stored JSON text in a tool row so a replacement writes the param + * back as text. A filter rule's `value` is still reached through the JSON leaf replacer above. + */ +const RAW_TEXT_TOOL_PARAM_SUBBLOCK_TYPES = new Set(['filter-builder', 'sort-builder']) + export function shouldParseSerializedSubBlockValue( subBlockType: SubBlockType | undefined ): subBlockType is SubBlockType { return Boolean( subBlockType && + !RAW_TEXT_TOOL_PARAM_SUBBLOCK_TYPES.has(subBlockType) && (isSearchableJsonValueSubBlock(subBlockType) || holdsObjectValue({ type: subBlockType })) ) } diff --git a/apps/sim/lib/workflows/search-replace/replacements.test.ts b/apps/sim/lib/workflows/search-replace/replacements.test.ts index 3ed26d831c4..6ffd1518a80 100644 --- a/apps/sim/lib/workflows/search-replace/replacements.test.ts +++ b/apps/sim/lib/workflows/search-replace/replacements.test.ts @@ -6,6 +6,7 @@ import { SEARCH_REPLACE_BLOCK_CONFIGS, } from '@/lib/workflows/search-replace/search-replace.fixtures' import { WORKFLOW_SEARCH_SUBFLOW_FIELD_IDS } from '@/lib/workflows/search-replace/subflow-fields' +import { TableV2Block } from '@/blocks/blocks/table_v2' /** * Asserts real tool params and outputs, which the global `@/tools/metadata` @@ -417,6 +418,127 @@ describe('buildWorkflowSearchReplacePlan', () => { ]) }) + it('replaces a value inside filter builder rules stored as a serialized tool input param', () => { + const workflow = createSearchReplaceWorkflowFixture() + const rule = { id: 'r1', logicalOperator: 'and', column: 'status', operator: 'eq' } + workflow.blocks['tool-input-1'] = { + id: 'tool-input-1', + type: 'custom', + name: 'Tool Input Block', + position: { x: 0, y: 0 }, + enabled: true, + outputs: {}, + subBlocks: { + tools: { + id: 'tools', + type: 'tool-input', + value: [ + { + type: 'table_v2', + toolId: 'table_query_rows_v2', + operation: 'query_rows', + title: 'Table', + params: { + tableId: 'tbl_1', + filterBuilder: JSON.stringify([{ ...rule, value: 'pending' }]), + }, + }, + ], + }, + }, + } + const matches = indexWorkflowSearchMatches({ + workflow, + query: 'pending', + mode: 'text', + blockConfigs: { + ...SEARCH_REPLACE_BLOCK_CONFIGS, + custom: { subBlocks: [{ id: 'tools', title: 'Tools', type: 'tool-input' }] }, + table_v2: TableV2Block, + }, + }).filter((match) => match.blockId === 'tool-input-1' && match.editable) + + const plan = buildWorkflowSearchReplacePlan({ + blocks: workflow.blocks, + matches, + selectedMatchIds: new Set(matches.map((match) => match.id)), + defaultReplacement: 'approved', + }) + + expect(plan.conflicts).toEqual([]) + expect(plan.updates).toHaveLength(1) + expect(plan.updates[0].nextValue).toEqual([ + expect.objectContaining({ + params: expect.objectContaining({ + filterBuilder: JSON.stringify([{ ...rule, value: 'approved' }]), + }), + }), + ]) + }) + + it('edits only rule values, never rule keys, in a tool input filter builder', () => { + const workflow = createSearchReplaceWorkflowFixture() + const rule = { id: 'r1', logicalOperator: 'and', column: 'status', operator: 'eq' } + workflow.blocks['tool-input-1'] = { + id: 'tool-input-1', + type: 'custom', + name: 'Tool Input Block', + position: { x: 0, y: 0 }, + enabled: true, + outputs: {}, + subBlocks: { + tools: { + id: 'tools', + type: 'tool-input', + value: [ + { + type: 'table_v2', + toolId: 'table_query_rows_v2', + operation: 'query_rows', + title: 'Table', + params: { + tableId: 'tbl_1', + filterBuilder: JSON.stringify([{ ...rule, value: 'operator and status' }]), + }, + }, + ], + }, + }, + } + const findEditable = (query: string) => + indexWorkflowSearchMatches({ + workflow, + query, + mode: 'text', + blockConfigs: { + ...SEARCH_REPLACE_BLOCK_CONFIGS, + custom: { subBlocks: [{ id: 'tools', title: 'Tools', type: 'tool-input' }] }, + table_v2: TableV2Block, + }, + }).filter((match) => match.blockId === 'tool-input-1' && match.editable) + + expect(findEditable('logicalOperator')).toEqual([]) + expect(findEditable('eq')).toEqual([]) + + const matches = findEditable('operator') + const plan = buildWorkflowSearchReplacePlan({ + blocks: workflow.blocks, + matches, + selectedMatchIds: new Set(matches.map((match) => match.id)), + defaultReplacement: 'owner', + }) + + expect(plan.conflicts).toEqual([]) + expect(plan.updates).toHaveLength(1) + expect(plan.updates[0].nextValue).toEqual([ + expect.objectContaining({ + params: expect.objectContaining({ + filterBuilder: JSON.stringify([{ ...rule, value: 'owner and status' }]), + }), + }), + ]) + }) + it('conflicts when a selected duplicate file occurrence is removed', () => { const workflow = createSearchReplaceWorkflowFixture() const files = [ diff --git a/apps/sim/lib/workflows/tool-input/hidden-params.ts b/apps/sim/lib/workflows/tool-input/hidden-params.ts new file mode 100644 index 00000000000..5315a260106 --- /dev/null +++ b/apps/sim/lib/workflows/tool-input/hidden-params.ts @@ -0,0 +1,205 @@ +import { isRecordLike } from '@sim/utils/object' +import { + evaluateSubBlockCondition, + isNonEmptyValue, + type SubBlockCondition, +} from '@/lib/workflows/subblocks/visibility' +import type { SubBlockConfig } from '@/blocks/types' + +type ConditionSubBlock = Pick< + SubBlockConfig, + | 'id' + | 'type' + | 'mode' + | 'condition' + | 'reactiveCondition' + | 'canonicalParamId' + | 'password' + | 'options' +> + +/** + * Whether `operation` is one of the block's own operation choices. Only then can a condition on + * `operation` be decided: a stored row with no operation, or one holding a tool id the dropdown + * does not list, leaves every operation-gated field undecided. + */ +function isBlockOperation( + subBlocks: ConditionSubBlock[], + operation: string, + values: Record +): boolean { + return subBlocks.some((subBlock) => { + if (subBlock.id !== 'operation' || subBlock.mode === 'trigger') return false + if (subBlock.mode === 'trigger-advanced' || !subBlock.options) return false + let options: unknown + try { + options = + typeof subBlock.options === 'function' ? subBlock.options({ values }) : subBlock.options + } catch { + return false + } + return ( + Array.isArray(options) && + options.some((option) => isRecordLike(option) && option.id === operation) + ) + }) +} + +/** A stored scalar a condition can be decided against; JSON-shaped and empty values cannot. */ +function isDecidableValue(value: unknown): boolean { + if (typeof value === 'boolean' || typeof value === 'number') return true + if (typeof value !== 'string') return false + const trimmed = value.trim() + return trimmed.length > 0 && !trimmed.startsWith('[') && !trimmed.startsWith('{') +} + +/** The typed reading of a stored string, since a tool row stores `true` and `3` as text. */ +function decodeScalar(value: unknown): unknown { + if (value === 'true') return true + if (value === 'false') return false + if (typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value))) { + return Number(value) + } + return value +} + +/** + * True only when the clause is decidably false. A clause on a field with no decidable value is + * treated as satisfiable, and the stored value is also tried in the clause's own type, so every + * doubt resolves toward keeping the value. A clause whose options are all strings compares the + * stored value as text: a typed reading of `'true'` would always satisfy a `not` clause on the + * string option `'true'`, leaving it undecidable. + */ +function isClauseFalse( + clause: SubBlockCondition, + values: Record, + isDecidableField: (field: string) => boolean +): boolean { + const { field } = clause + if (!isDecidableField(field)) return false + const single: SubBlockCondition = { field, value: clause.value, not: clause.not } + if (evaluateSubBlockCondition(single, values)) return false + const stored = values[field] + const options = Array.isArray(clause.value) ? clause.value : [clause.value] + const alternate = options.every((option) => typeof option === 'string') + ? String(stored) + : decodeScalar(stored) + return alternate === stored || !evaluateSubBlockCondition(single, { [field]: alternate }) +} + +/** + * Resolves a function condition, or `null` when it read a field the row cannot decide. A function + * condition names one field in what it returns but may branch on others (Video Generator gates a + * setting on the model, which the model itself supplies at call time), so every read is watched. + */ +function resolveFunctionCondition( + condition: (values?: Record) => SubBlockCondition, + values: Record, + isDecidableField: (field: string) => boolean +): SubBlockCondition | null { + let readUndecidedField = false + const watched = new Proxy(values, { + get(target, key, receiver) { + if (typeof key === 'string' && !isDecidableField(key)) readUndecidedField = true + return Reflect.get(target, key, receiver) + }, + has(target, key) { + if (typeof key === 'string' && !isDecidableField(key)) readUndecidedField = true + return Reflect.has(target, key) + }, + ownKeys(target) { + readUndecidedField = true + return Reflect.ownKeys(target) + }, + }) + const resolved = condition(watched) + return readUndecidedField ? null : resolved +} + +function isCredentialSubBlock(subBlock: ConditionSubBlock): boolean { + return ( + subBlock.type === 'oauth-input' || + subBlock.canonicalParamId === 'oauthCredential' || + subBlock.password === true + ) +} + +function isConditionHidden( + subBlock: ConditionSubBlock, + values: Record, + isDecidableField: (field: string) => boolean +): boolean { + if (isCredentialSubBlock(subBlock) || !subBlock.condition || subBlock.reactiveCondition) { + return false + } + let condition: SubBlockCondition | null + try { + condition = + typeof subBlock.condition === 'function' + ? resolveFunctionCondition(subBlock.condition, values, isDecidableField) + : subBlock.condition + } catch { + return false + } + if (!condition) return false + const clauses = condition.and ? [condition, condition.and] : [condition] + return clauses.some((clause) => isClauseFalse(clause, values, isDecidableField)) +} + +/** + * Every sub-block that stores a value under `paramId`: those whose id or canonical id it is, + * widened to the whole basic/advanced group, since either member may hold the group's value. + */ +function getWritingSubBlocks(subBlocks: ConditionSubBlock[], paramId: string): ConditionSubBlock[] { + const groups = new Set() + for (const subBlock of subBlocks) { + if ( + (subBlock.id === paramId || subBlock.canonicalParamId === paramId) && + subBlock.canonicalParamId + ) { + groups.add(subBlock.canonicalParamId) + } + } + return subBlocks.filter( + (subBlock) => + subBlock.id === paramId || + (subBlock.canonicalParamId !== undefined && groups.has(subBlock.canonicalParamId)) + ) +} + +/** + * Drops stored tool-row values the selected operation hides. + * + * A tool row keeps values across operation switches, but renders only the sub-blocks whose + * `condition` holds for the selected operation. A value left by a previous operation is then + * invisible to the user, and because it counts as user-provided it is also withheld from the + * model's schema, yet it still reaches the block mapper and the tool. A value is dropped only + * when every sub-block that writes it is decidably hidden under `{ ...params, operation }`. + * + * Kept: values no sub-block writes (pure tool params), values any writing sub-block shows (a + * canonical pair counts as shown when any member is), credential and password fields, and any + * value whose condition depends on a field the row has no decidable value for. Returns `params` + * itself when nothing is dropped. + */ +export function omitConditionHiddenParams( + subBlocks: ConditionSubBlock[] | undefined, + params: Record, + operation: string | undefined +): Record { + if (!subBlocks?.length) return params + const values: Record = { ...params, operation } + const operationKnown = Boolean(operation && isBlockOperation(subBlocks, operation, values)) + const isDecidableField = (field: string) => + field === 'operation' ? operationKnown : isDecidableValue(values[field]) + const isHidden = (paramId: string, value: T): boolean => { + if (paramId === 'operation' || !isNonEmptyValue(value)) return false + const writers = getWritingSubBlocks(subBlocks, paramId) + return ( + writers.length > 0 && + writers.every((subBlock) => isConditionHidden(subBlock, values, isDecidableField)) + ) + } + const entries = Object.entries(params) + const kept = entries.filter(([paramId, value]) => !isHidden(paramId, value)) + return kept.length === entries.length ? params : Object.fromEntries(kept) +} diff --git a/apps/sim/providers/conversation-continuation.test.ts b/apps/sim/providers/conversation-continuation.test.ts index 0c1575b39f6..41976abe745 100644 --- a/apps/sim/providers/conversation-continuation.test.ts +++ b/apps/sim/providers/conversation-continuation.test.ts @@ -20,6 +20,7 @@ import { setEncryptedConversationMessage, } from '@/providers/conversation-metadata' import { executeProviderTool } from '@/providers/runtime-context' +import { ToolCallParamsError } from '@/providers/tool-params-error' import type { Message, ProviderRequest } from '@/providers/types' import { prepareToolExecution } from '@/providers/utils' @@ -137,6 +138,19 @@ describe('durable conversation restoration and continuation', () => { ).rejects.toBe(refused) }) + it('records a block mapper rejection as a failed tool call without dispatching it', async () => { + vi.mocked(prepareToolExecution).mockImplementationOnce(() => { + throw new ToolCallParamsError('Invalid JSON in Filter') + }) + const session = await pendingSession() + await continuePendingConversationCalls(toolRequest, session) + expect(session.getPendingCalls()).toEqual([]) + expect(session.getMessages('openai', 'model-a', 'binding-a')[1].content).toContain( + 'Invalid JSON in Filter' + ) + expect(executeProviderTool).not.toHaveBeenCalled() + }) + it('clears a previously restored native message when the next fallback binding changes', async () => { const messages = toolGroup() const native = { diff --git a/apps/sim/providers/conversation-continuation.ts b/apps/sim/providers/conversation-continuation.ts index f8e06c1ffaf..117d604cb2b 100644 --- a/apps/sim/providers/conversation-continuation.ts +++ b/apps/sim/providers/conversation-continuation.ts @@ -16,6 +16,7 @@ import { import { getProviderHistoryProtocol, requiresNativeToolHistory } from '@/providers/history-adapters' import { executeProviderTool } from '@/providers/runtime-context' import { isAbortError } from '@/providers/streaming-tool-loop-shared' +import { ToolCallParamsError } from '@/providers/tool-params-error' import type { Message, ProviderId, ProviderRequest } from '@/providers/types' import { prepareToolExecution } from '@/providers/utils' @@ -78,15 +79,29 @@ export async function continuePendingConversationCalls( }) continue } - const { executionParams } = prepareToolExecution( - tool, - args, - { - ...request, - resolveToolInvocationId: () => call.invocationId, - }, - call.providerCallId - ) + let executionParams: ReturnType['executionParams'] + try { + executionParams = prepareToolExecution( + tool, + args, + { + ...request, + resolveToolInvocationId: () => call.invocationId, + }, + call.providerCallId + ).executionParams + } catch (error) { + // Any other preparation refusal aborts the continuation; a block mapper rejecting the + // arguments is a failed tool call, recorded as the original attempt would have reported it. + if (!(error instanceof ToolCallParamsError)) throw error + const result = { success: false, output: {}, error: getErrorMessage(error) } + await session.recordToolResult({ + invocationId: call.invocationId, + rawResponse: result, + modelResponse: result, + }) + continue + } try { logger.info('Retrying an Agent tool with an unrecorded outcome') await executeProviderTool(tool.id, executionParams) diff --git a/apps/sim/providers/models.ts b/apps/sim/providers/models.ts index 0b62ae529b1..d6cdfce60da 100644 --- a/apps/sim/providers/models.ts +++ b/apps/sim/providers/models.ts @@ -286,7 +286,7 @@ export const PROVIDER_DEFINITIONS: Record = { id: 'nebius', name: 'Nebius', description: 'Open models via Nebius Token Factory', - defaultModel: 'nebius/Qwen/Qwen3.5-397B-A17B', + defaultModel: 'nebius/Qwen/Qwen3.8-27B', modelPatterns: [/^nebius\//], icon: NebiusIcon, color: '#052B42', @@ -301,18 +301,21 @@ export const PROVIDER_DEFINITIONS: Record = { pricing: { input: 0.3, output: 1.2, updatedAt: '2026-10-07' }, capabilities: { toolUsageControl: false, nativeStructuredOutputs: false }, contextWindow: 1048000, + sunset: { status: 'deprecated' }, }, { id: 'nebius/deepseek-ai/DeepSeek-V4-Flash-0731', pricing: { input: 0.14, output: 0.28, updatedAt: '2026-10-07' }, capabilities: { toolUsageControl: true, nativeStructuredOutputs: true }, contextWindow: 1024000, + sunset: { status: 'deprecated' }, }, { id: 'nebius/deepseek-ai/DeepSeek-V4-Pro', pricing: { input: 1.75, output: 3.5, updatedAt: '2026-10-07' }, capabilities: { toolUsageControl: true, nativeStructuredOutputs: true }, contextWindow: 1048576, + sunset: { status: 'deprecated' }, }, { id: 'nebius/deepseek-ai/DeepSeek-V4-Pro-0813', @@ -337,12 +340,14 @@ export const PROVIDER_DEFINITIONS: Record = { pricing: { input: 0.95, output: 4, updatedAt: '2026-10-07' }, capabilities: { toolUsageControl: true, nativeStructuredOutputs: false }, contextWindow: 262144, + sunset: { status: 'deprecated' }, }, { id: 'nebius/moonshotai/Kimi-K2.7-Code', pricing: { input: 0.95, output: 4, updatedAt: '2026-10-07' }, capabilities: { toolUsageControl: true, nativeStructuredOutputs: false }, contextWindow: 262144, + sunset: { status: 'deprecated' }, }, { id: 'nebius/moonshotai/Kimi-K3', @@ -361,12 +366,14 @@ export const PROVIDER_DEFINITIONS: Record = { pricing: { input: 0.06, output: 0.24, updatedAt: '2026-10-07' }, capabilities: { toolUsageControl: true, nativeStructuredOutputs: false }, contextWindow: 262144, + sunset: { status: 'legacy' }, }, { id: 'nebius/nvidia/nemotron-3-super-120b-a12b', pricing: { input: 0.3, output: 0.9, updatedAt: '2026-10-07' }, capabilities: { toolUsageControl: true, nativeStructuredOutputs: false }, contextWindow: 262144, + sunset: { status: 'legacy' }, }, { id: 'nebius/nvidia/Nemotron-3-Ultra-550b-a55b', @@ -391,12 +398,14 @@ export const PROVIDER_DEFINITIONS: Record = { pricing: { input: 0.658, output: 1.11, updatedAt: '2026-10-07' }, capabilities: { toolUsageControl: false, nativeStructuredOutputs: true }, contextWindow: 32000, + sunset: { status: 'deprecated' }, }, { id: 'nebius/Qwen/Qwen3-235B-A22B-Instruct-2507', pricing: { input: 0.2, output: 0.6, updatedAt: '2026-10-07' }, capabilities: { toolUsageControl: true, nativeStructuredOutputs: true }, contextWindow: 262144, + sunset: { status: 'legacy' }, }, { id: 'nebius/Qwen/Qwen3-30B-A3B-Instruct-2507', @@ -409,6 +418,7 @@ export const PROVIDER_DEFINITIONS: Record = { pricing: { input: 0.6, output: 3.6, updatedAt: '2026-10-07' }, capabilities: { toolUsageControl: true, nativeStructuredOutputs: false }, contextWindow: 262144, + sunset: { status: 'deprecated' }, }, { id: 'nebius/Qwen/Qwen3.8-27B', @@ -421,6 +431,7 @@ export const PROVIDER_DEFINITIONS: Record = { pricing: { input: 1.4, output: 4.4, updatedAt: '2026-10-07' }, capabilities: { toolUsageControl: true, nativeStructuredOutputs: true }, contextWindow: 202752, + sunset: { status: 'deprecated' }, }, { id: 'nebius/zai-org/GLM-5.2', diff --git a/apps/sim/providers/nebius/index.live.test.ts b/apps/sim/providers/nebius/index.live.test.ts index d99cae9c568..2bb9b3c08ab 100644 --- a/apps/sim/providers/nebius/index.live.test.ts +++ b/apps/sim/providers/nebius/index.live.test.ts @@ -98,7 +98,7 @@ describe('Nebius live acceptance', () => { const base64 = 'iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAIAAAAlC+aJAAAAb0lEQVR4nO3PAQkAAAyEwO9feoshgnABdLep8QUNyPEFDcjxBQ3I8QUNyPEFDcjxBQ3I8QUNyPEFDcjxBQ3I8QUNyPEFDcjxBQ3I8QUNyPEFDcjxBQ3I8QUNyPEFDcjxBQ3I8QUNyPEFDcjxBQ3IPanc8OLDQitxAAAAAElFTkSuQmCC' const result = (await execute({ - model: 'nebius/openbmb/MiniCPM-V-4_5', + model: 'nebius/Qwen/Qwen3.8-27B', messages: [ { role: 'user', @@ -136,7 +136,7 @@ describe('Nebius live acceptance', () => { it.each([ { name: 'native', model }, - { name: 'prompt-fallback', model: 'nebius/Qwen/Qwen3.5-397B-A17B' }, + { name: 'prompt-fallback', model: 'nebius/Qwen/Qwen3.8-27B' }, ])( 'returns a JSON-schema answer through $name', async (scenario) => { diff --git a/apps/sim/providers/tool-params-error.ts b/apps/sim/providers/tool-params-error.ts new file mode 100644 index 00000000000..73ec4b30a56 --- /dev/null +++ b/apps/sim/providers/tool-params-error.ts @@ -0,0 +1,20 @@ +/** + * Thrown by a block's `tools.config.params` mapper when a tool call must not run at all. + * + * A mapper failure on a tool call is normally logged and the tool runs with the raw merged + * params instead (`prepareToolExecution`, Pi's local tools, Human-in-the-loop v2 notifications). + * That fallback drops the canonical collapse along with everything else, so a model-supplied + * argument the user's pinned value had hidden comes back: a Table bulk delete would run with the + * model's `filter` rather than the filter the user configured. This error is rethrown instead, + * and the call is reported as failed, so its message reaches the model unredacted and must + * never quote an argument value. + * + * Deliberately a leaf module: blocks import it, and `@/blocks/utils` already imports + * `@/providers/utils`. + */ +export class ToolCallParamsError extends Error { + constructor(message: string, options?: { cause?: unknown }) { + super(message, options) + this.name = 'ToolCallParamsError' + } +} diff --git a/apps/sim/providers/utils.test.ts b/apps/sim/providers/utils.test.ts index 051ebcb6457..953cae3fb4b 100644 --- a/apps/sim/providers/utils.test.ts +++ b/apps/sim/providers/utils.test.ts @@ -1,4 +1,5 @@ import { resetEnvFlagsMock, setEnvFlags } from '@sim/testing' +import { omit } from '@sim/utils/object' import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const workflowMetadataMocks = vi.hoisted(() => ({ @@ -11,13 +12,27 @@ vi.mock('@/lib/internal/workflows/read-tool-enrichment', () => ({ readWorkflowMetadataForTool: workflowMetadataMocks.readWorkflowMetadataForTool, })) +import { + filterRulesToFilter, + filterRulesToPredicate, + sortRulesToSort, +} from '@/lib/table/query-builder/converters' +import { normalizeTablePredicate } from '@/lib/table/query-builder/predicate' +import type { FilterRule, Predicate, SortRule } from '@/lib/table/types' import { getParamsForToolOperation } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/param-dependents' +import { CbInsightsV2Block } from '@/blocks/blocks/cbinsights' +import { CheckrV2Block } from '@/blocks/blocks/checkr' import { GaugeBlock } from '@/blocks/blocks/gauge' import { GreenhouseV2Block } from '@/blocks/blocks/greenhouse' import { IntuneBlock } from '@/blocks/blocks/intune' import { MicrosoftExcelV2Block } from '@/blocks/blocks/microsoft_excel' import { RampBlock } from '@/blocks/blocks/ramp' +import { ResendV2Block } from '@/blocks/blocks/resend' import { RevenueCatBlock } from '@/blocks/blocks/revenuecat' +import { SharepointV2Block } from '@/blocks/blocks/sharepoint' +import { TableBlock } from '@/blocks/blocks/table' +import { TableV2Block } from '@/blocks/blocks/table_v2' +import { TrelloBlock } from '@/blocks/blocks/trello' import { VideoGeneratorV3Block } from '@/blocks/blocks/video_generator' import * as blockRegistry from '@/blocks/registry' import { normalizeFileInput } from '@/blocks/utils' @@ -28,6 +43,7 @@ import { supportsTemperature, } from '@/providers/models' import { assignProviderToolIdentities } from '@/providers/tool-identity' +import { ToolCallParamsError } from '@/providers/tool-params-error' import type { ProviderToolConfig } from '@/providers/types' import { buildBlockToolParamsTransform, @@ -47,6 +63,9 @@ import { transformBlockTool, } from '@/providers/utils' import { useProvidersStore } from '@/stores/providers/store' +import { cbinsightsSearchFirmographicsTool } from '@/tools/cbinsights/search_firmographics' +import { checkrCreateReportTool } from '@/tools/checkr/create_report' +import { checkrListCandidatesTool } from '@/tools/checkr/list_candidates' import { gaugeGetQueryMetadataTool } from '@/tools/gauge/get_query_metadata' import { gaugeListAnswersTool } from '@/tools/gauge/list_answers' import { gaugeListCitationsTool } from '@/tools/gauge/list_citations' @@ -85,7 +104,16 @@ import { sortRangeTool } from '@/tools/microsoft_excel/sort_range' import { getSubBlocksForToolInput } from '@/tools/params' import { rampListReimbursementsTool } from '@/tools/ramp/list-reimbursements' import { rampListTransactionsTool } from '@/tools/ramp/list-transactions' +import { resendCreateBroadcastTool } from '@/tools/resend/create_broadcast' +import type { CreateBroadcastParams } from '@/tools/resend/types' import { revenuecatGetCustomerTool } from '@/tools/revenuecat/get_customer' +import { getListTool as sharepointGetListTool } from '@/tools/sharepoint/get_list' +import { tableDeleteRowsByFilterTool } from '@/tools/table/delete_rows_by_filter' +import { tableQueryRowsTool } from '@/tools/table/query_rows' +import { tableQueryRowsV2Tool } from '@/tools/table/query_rows_v2' +import { tableUpdateRowsByFilterTool } from '@/tools/table/update_rows_by_filter' +import { trelloListListsTool } from '@/tools/trello/list_lists' +import { trelloUpdateListTool } from '@/tools/trello/update_list' import { falaiVideoTool } from '@/tools/video/falai' import { runwayVideoTool } from '@/tools/video/runway' @@ -149,7 +177,8 @@ describe('integration filters through agent execution', () => { vi.spyOn(blockRegistry, 'getBlock').mockReturnValue(GaugeBlock) const params = getParamsForToolOperation( { type: 'gauge', params: { org: 'example', category: 'example', topic: '["top_stale"]' } }, - tool + tool, + tool.id ) const providerTool = await transformBlockTool( { type: 'gauge', params }, @@ -338,7 +367,8 @@ describe('integration filters through agent execution', () => { } const params = getParamsForToolOperation( { type: 'greenhouse_v2', params: previousParams }, - tool + tool, + operation ) const providerTool = await transformBlockTool( { type: 'greenhouse_v2', params }, @@ -373,7 +403,8 @@ describe('integration filters through agent execution', () => { source_id: '81', }, }, - tool + tool, + 'update_application' ) const providerTool = await transformBlockTool( { type: 'greenhouse_v2', params }, @@ -406,7 +437,8 @@ describe('integration filters through agent execution', () => { candidate_id: '42', }, }, - tool + tool, + 'create_application' ) const providerTool = await transformBlockTool( { type: 'greenhouse_v2', params }, @@ -436,7 +468,8 @@ describe('integration filters through agent execution', () => { vi.spyOn(blockRegistry, 'getBlock').mockReturnValue(GreenhouseV2Block) const params = getParamsForToolOperation( { type: 'greenhouse_v2', params: { opening_id: 'external-opening' } }, - tool + tool, + 'hire_application' ) const providerTool = await transformBlockTool( { type: 'greenhouse_v2', params }, @@ -473,7 +506,8 @@ describe('integration filters through agent execution', () => { accessToken: 'expired-resolved-token', }, }, - greenhouseListJobsV2Tool + greenhouseListJobsV2Tool, + 'list_jobs' ) expect(params[credentialId]).toBe('fixture-credential') expect(params).not.toHaveProperty('accessToken') @@ -723,6 +757,324 @@ describe('integration filters through agent execution', () => { }) }) +describe('tool-row values hidden by the selected operation', () => { + it.each([ + { + name: 'Trello archive status left by Update Card', + block: TrelloBlock, + operation: 'trello_update_list', + tool: trelloUpdateListTool, + stored: { listId: 'list-1', closed: 'true' }, + hiddenParam: 'closed', + }, + { + name: 'CB Insights websites left by Look Up Organizations', + block: CbInsightsV2Block, + operation: 'search_firmographics', + tool: cbinsightsSearchFirmographicsTool, + stored: { keyword: 'payments', urls: 'stripe.com' }, + hiddenParam: 'urls', + }, + { + name: 'Checkr geo left by Get Geo', + block: CheckrV2Block, + operation: 'list_candidates', + tool: checkrListCandidatesTool, + stored: { geoId: 'geo-stale' }, + hiddenParam: 'geoId', + }, + { + name: 'Checkr tags left by Set Report Tags', + block: CheckrV2Block, + operation: 'create_report', + tool: checkrCreateReportTool, + stored: { candidateId: 'cand-1', package: 'basic', tags: 'stale-tag' }, + hiddenParam: 'tags', + }, + ])('neither runs nor hides from the model the $name', async (testCase) => { + const providerTool = await transformBlockTool( + { type: testCase.block.type, operation: testCase.operation, params: testCase.stored }, + { + selectedOperation: testCase.operation, + getAllBlocks: () => [testCase.block], + getTool: () => testCase.tool, + } + ) + if (!providerTool) throw new Error('Agent tool was not created') + expect(providerTool.parameters.properties).toHaveProperty(testCase.hiddenParam) + const { toolParams } = prepareToolExecution(providerTool, {}, {}, undefined) + expect(toolParams[testCase.hiddenParam]).toBeUndefined() + }) + + it.each([ + { stored: { manualBoardId: 'board-advanced' }, member: 'advanced member' }, + { stored: { boardSelector: 'board-basic' }, member: 'basic member' }, + { stored: { boardId: 'board-canonical' }, member: 'canonical id' }, + ])('keeps a board stored under the $member when the operation shows it', async ({ stored }) => { + const providerTool = await transformBlockTool( + { type: 'trello', operation: 'trello_list_lists', params: stored }, + { + selectedOperation: 'trello_list_lists', + getAllBlocks: () => [TrelloBlock], + getTool: () => trelloListListsTool, + } + ) + if (!providerTool) throw new Error('Trello agent tool was not created') + const { toolParams } = prepareToolExecution(providerTool, {}, {}, undefined) + expect(toolParams.boardId).toBe(Object.values(stored)[0]) + }) + + it.each([ + { includeColumns: 'true', kept: false }, + { includeColumns: 'false', kept: true }, + ])( + 'applies the SharePoint item filters left on a Get List row only when Include Columns is $includeColumns', + async ({ includeColumns, kept }) => { + const stored = { + siteId: 'site-1', + listId: 'list-1', + includeColumns, + filter: "fields/Status eq 'Active'", + top: '10', + selectFields: 'Title', + } + const providerTool = await transformBlockTool( + { type: 'sharepoint_v2', operation: 'sharepoint_get_list', params: stored }, + { + selectedOperation: 'sharepoint_get_list', + getAllBlocks: () => [SharepointV2Block], + getTool: () => sharepointGetListTool, + } + ) + if (!providerTool) throw new Error('SharePoint agent tool was not created') + const { toolParams } = prepareToolExecution(providerTool, {}, {}, undefined) + expect(toolParams.includeColumns).toBe(includeColumns === 'true') + expect(toolParams.filter).toBe(kept ? stored.filter : undefined) + expect(toolParams.top).toBe(kept ? 10 : undefined) + expect(toolParams.selectFields).toBe(kept ? stored.selectFields : undefined) + } + ) + + it('keeps a stored tool param no sub-block writes', async () => { + const providerTool = await transformBlockTool( + { type: 'trello', operation: 'trello_update_list', params: { listId: 'l', idBoard: 'b' } }, + { + selectedOperation: 'trello_update_list', + getAllBlocks: () => [TrelloBlock], + getTool: () => trelloUpdateListTool, + } + ) + if (!providerTool) throw new Error('Trello agent tool was not created') + expect(providerTool.params).toEqual({ listId: 'l', idBoard: 'b' }) + expect(providerTool.parameters.properties).not.toHaveProperty('idBoard') + }) + + it('keeps operation-gated values when the stored operation is not one the block lists', async () => { + const providerTool = await transformBlockTool( + { type: 'checkr_v2', params: { geoId: 'geo-1' } }, + { + selectedOperation: undefined, + getAllBlocks: () => [CheckrV2Block], + getTool: () => checkrListCandidatesTool, + } + ) + if (!providerTool) throw new Error('Checkr agent tool was not created') + expect(providerTool.params).toEqual({ geoId: 'geo-1' }) + }) + + it('drops a value the new operation hides when the row switches operations', () => { + vi.spyOn(blockRegistry, 'getBlock').mockReturnValue(CheckrV2Block) + const params = getParamsForToolOperation( + { + type: 'checkr_v2', + params: { candidateId: 'cand-1', tags: 'stale-tag', credential: 'fixture-credential' }, + }, + checkrCreateReportTool, + 'create_report' + ) + expect(params).toEqual({ candidateId: 'cand-1', credential: 'fixture-credential' }) + }) +}) + +describe('Resend broadcast recipient on a tool row', () => { + const sender = { broadcastFrom: 'team@example.com', broadcastSubject: 'News' } + + it.each([ + { + name: 'a pinned audience over the model segment', + stored: { audienceId: 'aud_row' }, + args: { segmentId: 'seg_model' }, + recipient: { audience_id: 'aud_row' }, + }, + { + name: 'a pinned segment over the model audience', + stored: { segmentId: 'seg_row' }, + args: { audienceId: 'aud_model' }, + recipient: { segment_id: 'seg_row' }, + }, + { + name: 'the model segment when the row pins no recipient', + stored: {}, + args: { segmentId: 'seg_model' }, + recipient: { segment_id: 'seg_model' }, + }, + ])('sends to $name', async ({ stored, args, recipient }) => { + const providerTool = await transformBlockTool( + { + type: 'resend_v2', + operation: 'create_broadcast', + params: { ...sender, credential: 'fixture-credential', ...stored }, + }, + { + selectedOperation: 'create_broadcast', + getAllBlocks: () => [ResendV2Block], + getTool: () => resendCreateBroadcastTool, + } + ) + if (!providerTool) throw new Error('Resend agent tool was not created') + const { toolParams } = prepareToolExecution(providerTool, args, {}, undefined) + const body = resendCreateBroadcastTool.request.body?.(toolParams as CreateBroadcastParams) + expect(body).toMatchObject(recipient) + expect(body).not.toHaveProperty('audience_id' in recipient ? 'segment_id' : 'audience_id') + }) +}) + +describe('Table builder rules pinned on an agent tool row', () => { + const pinnedRules: FilterRule[] = [ + { id: 'r1', logicalOperator: 'and', column: 'status', operator: 'eq', value: 'active' }, + ] + const modelFilter: Predicate = { field: 'status', op: 'eq', value: 'archived' } + + async function runTableTool( + block: typeof TableBlock, + operation: string, + tool: { toolEnrichment?: unknown }, + stored: Record, + modelArgs: Record + ) { + const providerTool = await transformBlockTool( + { type: block.type, operation, params: { tableId: 'tbl_1', ...stored } }, + { + selectedOperation: operation, + getAllBlocks: () => [block], + // Schema enrichment reads the live table; what reaches the tool does not depend on it. + getTool: () => omit(tool, ['toolEnrichment']), + } + ) + if (!providerTool) throw new Error('Table agent tool was not created') + return prepareToolExecution(providerTool, modelArgs, {}, undefined).executionParams + } + + it.each([ + { operation: 'update_rows_by_filter', tool: tableUpdateRowsByFilterTool }, + { operation: 'delete_rows_by_filter', tool: tableDeleteRowsByFilterTool }, + ])( + 'runs v2 $operation on the pinned filter, not the model filter', + async ({ operation, tool }) => { + const params = await runTableTool( + TableV2Block, + operation, + tool, + { filterBuilder: JSON.stringify(pinnedRules), data: '{"status":"done"}' }, + { filter: modelFilter } + ) + expect(params.filter).toEqual(filterRulesToPredicate(pinnedRules)) + } + ) + + it('lets the model filter through an emptied v2 filter builder', async () => { + const params = await runTableTool( + TableV2Block, + 'delete_rows_by_filter', + tableDeleteRowsByFilterTool, + { filterBuilder: '[]' }, + { filter: modelFilter } + ) + expect(params.filter).toEqual(normalizeTablePredicate(modelFilter)) + }) + + it('fails the call instead of running a v2 bulk delete on the model filter', async () => { + await expect( + runTableTool( + TableV2Block, + 'delete_rows_by_filter', + tableDeleteRowsByFilterTool, + { filterBuilder: '[{"column":' }, + { filter: modelFilter } + ) + ).rejects.toThrow(ToolCallParamsError) + }) + + it('never quotes a rejected argument back to the model', async () => { + const resolvedSecret = 'sk-live-fixture-value' + const rejection = runTableTool( + TableV2Block, + 'query_rows', + tableQueryRowsV2Tool, + {}, + { limit: resolvedSecret } + ) + await expect(rejection).rejects.toThrow(ToolCallParamsError) + await expect(rejection).rejects.not.toThrow(resolvedSecret) + }) + + it('sends the pinned v2 sort builder as a sort spec', async () => { + const sortRules: SortRule[] = [{ id: 's1', column: 'wins', direction: 'desc' }] + const params = await runTableTool( + TableV2Block, + 'query_rows', + tableQueryRowsV2Tool, + { sortBuilder: JSON.stringify(sortRules) }, + {} + ) + expect(params.order).toEqual([{ field: 'wins', direction: 'desc' }]) + }) + + it('runs a v1 bulk update on the pinned filter, not the model filter', async () => { + const params = await runTableTool( + TableBlock, + 'update_rows_by_filter', + tableUpdateRowsByFilterTool, + { + bulkFilterMode: 'builder', + bulkFilterBuilder: JSON.stringify(pinnedRules), + data: '{"status":"done"}', + }, + { filter: { status: 'archived' } } + ) + expect(params.filter).toEqual(filterRulesToFilter(pinnedRules)) + }) + + it('fails the call instead of running a v1 bulk delete on the model filter', async () => { + await expect( + runTableTool( + TableBlock, + 'delete_rows_by_filter', + tableDeleteRowsByFilterTool, + { bulkFilterMode: 'builder', bulkFilterBuilder: '[{"column":"status","value":"a"b"}]' }, + { filter: { status: 'archived' } } + ) + ).rejects.toThrow(ToolCallParamsError) + }) + + it('applies the pinned v1 query filter and sort builders', async () => { + const sortRules: SortRule[] = [{ id: 's1', column: 'wins', direction: 'desc' }] + const params = await runTableTool( + TableBlock, + 'query_rows', + tableQueryRowsTool, + { + builderMode: 'builder', + filterBuilder: JSON.stringify(pinnedRules), + sortBuilder: JSON.stringify(sortRules), + }, + { filter: { status: 'archived' }, sort: { name: 'asc' } } + ) + expect(params.filter).toEqual(filterRulesToFilter(pinnedRules)) + expect(params.sort).toEqual(sortRulesToSort(sortRules)) + }) +}) + describe('Excel targets through agent execution', () => { it.each(['model', 'configured'] as const)( 'clears the %s range after canonical argument mapping', diff --git a/apps/sim/providers/utils.ts b/apps/sim/providers/utils.ts index 07ef9be1b39..ecac17d3338 100644 --- a/apps/sim/providers/utils.ts +++ b/apps/sim/providers/utils.ts @@ -17,10 +17,13 @@ import { buildCanonicalIndex, type CanonicalGroup, type CanonicalModeOverrides, + getCanonicalValues, isCanonicalPair, resolveActiveCanonicalValue, + resolveCanonicalMode, scopeCanonicalModesForTool, } from '@/lib/workflows/subblocks/visibility' +import { omitConditionHiddenParams } from '@/lib/workflows/tool-input/hidden-params' import { resolveBlockToolId } from '@/lib/workflows/tool-input/identity' import { assembleCustomBlockInputMapping, isCustomBlockType } from '@/blocks/custom/build-config' import type { BlockToolParamsContext, SubBlockConfig } from '@/blocks/types' @@ -51,8 +54,9 @@ import { getProviderToolModelInputRegistry, registerPreparedProviderToolInputProvenance, } from '@/providers/tool-input-provenance' +import { ToolCallParamsError } from '@/providers/tool-params-error' import type { ModelPricing, ProviderId, ProviderToolConfig } from '@/providers/types' -import { mergeToolParameters } from '@/tools/merge-params' +import { isNonEmpty, mergeToolParameters } from '@/tools/merge-params' import { buildToolParamShapes, decodeToolParams } from '@/tools/param-shape' import type { WorkflowToolExecutionContext } from '@/tools/types' @@ -536,7 +540,10 @@ type BlockToolParamsFn = ( * Four steps, in an order each of which is load-bearing: * * 1. Collapse canonical basic/advanced pairs onto the canonical id, so a value stored - * under `manualChannel` becomes the `channel` the tool declares. + * under `manualChannel` becomes the `channel` the tool declares. The active member is + * picked from the decoded values, as the canvas sees them: a builder the user emptied + * is stored as `'[]'`, which reads as filled until it decodes to `[]`, and would + * otherwise hide the model's argument for the other member. * 2. Decode the stringified values back to their real shapes, and expand a * `checkbox-list` onto its option params. After the collapse so a pair is decoded * once under its canonical id, and BEFORE the block's `params` function because @@ -558,6 +565,8 @@ export function buildBlockToolParamsTransform(config: { toolParams: Record | undefined canonicalGroups: CanonicalGroup[] scopedCanonicalModes: CanonicalModeOverrides | undefined + /** The params the tool row stores; their non-empty ids reach the mapper as `pinnedParams`. */ + storedParams?: Record }): { paramsTransform: BlockToolParamsFn | undefined jsonShapedParamKeys: string[] @@ -570,7 +579,13 @@ export function buildBlockToolParamsTransform(config: { toolParams, canonicalGroups, scopedCanonicalModes, + storedParams, } = config + const pinnedParams = new Set( + Object.entries(storedParams ?? {}) + .filter(([, value]) => isNonEmpty(value)) + .map(([paramId]) => paramId) + ) /** * The value shape of every key this tool can receive. Keyed by the sub-block that @@ -586,16 +601,19 @@ export function buildBlockToolParamsTransform(config: { const paramsTransform = needsTransform ? (params: Record): Record => { let result = { ...params } + const decodedMembers = decodeToolParams(params, paramShapes) for (const group of canonicalGroups) { // Route through the canonical SOT: an explicit scoped override wins, else the value // heuristic - no `?? 'basic'` (which dropped an advanced-only value when basic was empty). const explicitMode = scopedCanonicalModes?.[group.canonicalId] - const chosen = resolveActiveCanonicalValue( + const mode = resolveCanonicalMode( group, - result, + decodedMembers, explicitMode ? { [group.canonicalId]: explicitMode } : undefined ) + const { basicValue, advancedValue } = getCanonicalValues(group, result) + const chosen = mode === 'advanced' ? advancedValue : basicValue const sourceIds = [group.basicId, ...group.advancedIds].filter(Boolean) as string[] result = omit(result, sourceIds) @@ -619,7 +637,7 @@ export function buildBlockToolParamsTransform(config: { } if (blockParamsFn) { - const transformed = blockParamsFn(result, { operation }) + const transformed = blockParamsFn(result, { operation, pinnedParams }) result = { ...result, ...transformed } } @@ -841,7 +859,14 @@ export async function transformBlockTool( const { createLLMToolSchema } = await import('@/tools/params') - const userProvidedParams = block.params || {} + const operation = + selectedOperation ?? + (typeof block.params?.operation === 'string' ? block.params.operation : undefined) + const userProvidedParams = omitConditionHiddenParams( + blockDef.subBlocks, + block.params || {}, + operation + ) const canonicalGroups: CanonicalGroup[] = blockDef?.subBlocks ? // canonical-index-unscoped: an agent tool resolves against `block.params`, which only ever @@ -899,15 +924,14 @@ export async function transformBlockTool( } const { paramsTransform, jsonShapedParamKeys } = buildBlockToolParamsTransform({ - operation: - selectedOperation ?? - (typeof userProvidedParams.operation === 'string' ? userProvidedParams.operation : undefined), + operation, blockSubBlocks: blockDef?.subBlocks, blockParamsFn: blockDef?.tools?.config?.params as BlockToolParamsFn | undefined, blockInputDefs: blockDef?.inputs as Record | undefined, toolParams: toolConfig.params, canonicalGroups, scopedCanonicalModes, + storedParams: userProvidedParams, }) const providerTool: ProviderToolConfig = { @@ -1611,6 +1635,7 @@ export function prepareToolExecution( toolParams = tool.paramsTransform(toolParams) transformed = true } catch (err) { + if (err instanceof ToolCallParamsError) throw err logger.warn('paramsTransform failed, using raw params', { error: err }) } diff --git a/apps/sim/public/library/ai-agent-identity-credentials-audit-trails-enterprise-guide/cover.jpg b/apps/sim/public/library/ai-agent-identity-credentials-audit-trails-enterprise-guide/cover.jpg new file mode 100644 index 00000000000..c943f72f57f Binary files /dev/null and b/apps/sim/public/library/ai-agent-identity-credentials-audit-trails-enterprise-guide/cover.jpg differ diff --git a/apps/sim/public/library/glean-vs-dust-enterprise-ai/cover.jpg b/apps/sim/public/library/glean-vs-dust-enterprise-ai/cover.jpg new file mode 100644 index 00000000000..46d660d4209 Binary files /dev/null and b/apps/sim/public/library/glean-vs-dust-enterprise-ai/cover.jpg differ diff --git a/apps/sim/public/library/snowflake-quickbooks-mcp-servers-ai-agents/cover.jpg b/apps/sim/public/library/snowflake-quickbooks-mcp-servers-ai-agents/cover.jpg new file mode 100644 index 00000000000..6fa05c4a22c Binary files /dev/null and b/apps/sim/public/library/snowflake-quickbooks-mcp-servers-ai-agents/cover.jpg differ diff --git a/apps/sim/tools/attio/json-inputs.test.ts b/apps/sim/tools/attio/json-inputs.test.ts index b92cd9869c4..71b98b64bbf 100644 --- a/apps/sim/tools/attio/json-inputs.test.ts +++ b/apps/sim/tools/attio/json-inputs.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest' import { attioCreateWebhookTool } from '@/tools/attio/create_webhook' +import { attioListRecordsTool } from '@/tools/attio/list_records' import { attioQueryListEntriesTool } from '@/tools/attio/query_list_entries' import { attioUpdateTaskTool } from '@/tools/attio/update_task' @@ -29,4 +30,23 @@ describe('Attio JSON inputs', () => { }) ).toThrow('Invalid JSON provided for subscriptions') }) + + it('sends a filter and sorts the json input already parsed', () => { + const filter = { name: { $eq: 'Acme' } } + const sorts = [{ direction: 'asc', attribute: 'name' }] + expect( + bodyOf(attioListRecordsTool, { accessToken: 't', objectType: 'companies', filter, sorts }) + ).toEqual({ filter, sorts }) + }) + + it('parses a filter and sorts sent as JSON text', () => { + expect( + bodyOf(attioListRecordsTool, { + accessToken: 't', + objectType: 'companies', + filter: '{"name":"Acme"}', + sorts: '[{"direction":"desc","attribute":"name"}]', + }) + ).toEqual({ filter: { name: 'Acme' }, sorts: [{ direction: 'desc', attribute: 'name' }] }) + }) }) diff --git a/apps/sim/tools/attio/list_records.ts b/apps/sim/tools/attio/list_records.ts index 49b917a0f18..6ed1e7429c7 100644 --- a/apps/sim/tools/attio/list_records.ts +++ b/apps/sim/tools/attio/list_records.ts @@ -66,14 +66,15 @@ export const attioListRecordsTool: ToolConfig = {} if (params.filter) { try { - body.filter = JSON.parse(params.filter) + body.filter = + typeof params.filter === 'string' ? JSON.parse(params.filter) : params.filter } catch { throw new Error('Invalid JSON provided for filter') } } if (params.sorts) { try { - body.sorts = JSON.parse(params.sorts) + body.sorts = typeof params.sorts === 'string' ? JSON.parse(params.sorts) : params.sorts } catch { throw new Error('Invalid JSON provided for sorts') } diff --git a/apps/sim/tools/attio/types.ts b/apps/sim/tools/attio/types.ts index faa1dc55c60..b8b2fb880e3 100644 --- a/apps/sim/tools/attio/types.ts +++ b/apps/sim/tools/attio/types.ts @@ -330,8 +330,10 @@ interface AttioRecord { export interface AttioListRecordsParams { accessToken: string objectType: string - filter?: string - sorts?: string + /** JSON text, or the object the block's `json` input already parsed. */ + filter?: string | Record + /** JSON text, or the array the block's `json` input already parsed. */ + sorts?: string | unknown[] limit?: number offset?: number } diff --git a/apps/sim/tools/brex/create_spend_limit.test.ts b/apps/sim/tools/brex/create_spend_limit.test.ts new file mode 100644 index 00000000000..e5f9e026651 --- /dev/null +++ b/apps/sim/tools/brex/create_spend_limit.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from 'vitest' +import { brexCreateSpendLimitTool } from '@/tools/brex/create_spend_limit' + +const REQUIRED = { + apiKey: 'token', + name: 'Travel', + periodRecurrenceType: 'PER_MONTH', + spendType: 'BUDGET_PROVISIONED_CARDS_ONLY', + expenseVisibility: 'SHARED', + authorizationVisibility: 'PUBLIC', + limitIncreaseSetting: 'DISABLED', + autoTransferCardsSetting: 'DISABLED', + autoCreateLimitCardsSetting: 'DISABLED', + expensePolicyId: 'pol_1', + baseLimitAmount: 50000, + authorizationType: 'HARD', + rolloverRefreshRate: 'OFF', +} + +/** Builds the request body from canvas params the way a saved workflow delivers them, blanks included. */ +function buildBody(overrides: Record): Record { + const body = brexCreateSpendLimitTool.request.body + if (!body) throw new Error('create_spend_limit has no request body builder') + const result = body({ ...REQUIRED, ...overrides } as Parameters[0]) + if (typeof result !== 'object' || result instanceof FormData) { + throw new Error('create_spend_limit must build a JSON object body') + } + return result +} + +function authorizationSettings(body: Record): Record { + return body.authorization_settings as Record +} + +describe('brexCreateSpendLimitTool request body', () => { + it.each([null, '', ' '])( + 'omits limit_buffer_percentage when the saved value is %j instead of sending 0', + (blank) => { + const body = buildBody({ limitBufferPercentage: blank }) + expect(authorizationSettings(body)).not.toHaveProperty('limit_buffer_percentage') + } + ) + + it('sends an explicit 0 buffer the user set', () => { + const body = buildBody({ limitBufferPercentage: 0 }) + expect(authorizationSettings(body).limit_buffer_percentage).toBe(0) + }) + + it.each([null, '', ' '])( + 'omits transaction_limit when the saved amount is %j instead of sending a null Money amount', + (blank) => { + const body = buildBody({ transactionLimitAmount: blank }) + expect(body).not.toHaveProperty('transaction_limit') + } + ) + + it('sends a set transaction limit in the spend limit currency', () => { + const body = buildBody({ transactionLimitAmount: 2500, currency: 'EUR' }) + expect(body.transaction_limit).toEqual({ amount: 2500, currency: 'EUR' }) + }) +}) diff --git a/apps/sim/tools/brex/create_spend_limit.ts b/apps/sim/tools/brex/create_spend_limit.ts index 37ecbc18957..4ee0db0ed98 100644 --- a/apps/sim/tools/brex/create_spend_limit.ts +++ b/apps/sim/tools/brex/create_spend_limit.ts @@ -14,6 +14,23 @@ const DELIVERY = defineBrexKeyedSite( 'a second card program of the same size would be created, doubling the spend the company has authorized' ) +/** + * True when an optional canvas value was left blank. Saved workflows can carry `null` or `''` + * for a cleared field, which `Number()` would silently turn into `0`. + */ +function isUnset(value: unknown): value is undefined | null | '' { + return value === undefined || value === null || (typeof value === 'string' && !value.trim()) +} + +/** Brex accepts `limit_buffer_percentage` only as a 0-100 integer; reject anything else before the request. */ +function toLimitBufferPercentage(value: number): number { + const percentage = Number(value) + if (!Number.isInteger(percentage) || percentage < 0 || percentage > 100) { + throw new Error('Limit buffer percentage must be a whole number from 0 to 100') + } + return percentage +} + export const brexCreateSpendLimitTool: ToolConfig< BrexCreateSpendLimitParams & BrexDeliveryContextParams, BrexCreateSpendLimitResponse @@ -120,7 +137,7 @@ export const brexCreateSpendLimitTool: ToolConfig< type: 'number', required: false, visibility: 'user-or-llm', - description: 'Flexible buffer on the limit as a 0-100 percentage', + description: 'Flexible buffer on the limit as a whole-number percentage from 0 to 100', }, description: { type: 'string', @@ -193,8 +210,8 @@ export const brexCreateSpendLimitTool: ToolConfig< }, authorization_type: params.authorizationType, rollover_refresh_rate: params.rolloverRefreshRate, - ...(params.limitBufferPercentage !== undefined - ? { limit_buffer_percentage: params.limitBufferPercentage } + ...(!isUnset(params.limitBufferPercentage) + ? { limit_buffer_percentage: toLimitBufferPercentage(params.limitBufferPercentage) } : {}), }, } @@ -202,7 +219,7 @@ export const brexCreateSpendLimitTool: ToolConfig< if (params.parentBudgetId) body.parent_budget_id = params.parentBudgetId if (params.startDate) body.start_date = params.startDate if (params.endDate) body.end_date = params.endDate - if (params.transactionLimitAmount !== undefined) { + if (!isUnset(params.transactionLimitAmount)) { body.transaction_limit = { amount: params.transactionLimitAmount, currency } } const ownerUserIds = splitBrexIdList(params.ownerUserIds) diff --git a/apps/sim/tools/brex/get_budget.ts b/apps/sim/tools/brex/get_budget.ts index 8eda3bdfe6d..d74a5807280 100644 --- a/apps/sim/tools/brex/get_budget.ts +++ b/apps/sim/tools/brex/get_budget.ts @@ -74,7 +74,7 @@ export const brexGetBudgetTool: ToolConfig { + it('reads the camelCase accountType Brex returns on CompanyResponse', async () => { + const transform = brexGetCompanyTool.transformResponse + if (!transform) throw new Error('get_company has no transformResponse') + const response = new Response( + JSON.stringify({ + id: 'co_1', + legal_name: 'Acme Inc', + mailing_address: null, + accountType: 'BREX_EMPOWER', + }), + { status: 200, headers: { 'Content-Type': 'application/json' } } + ) + const result = await transform(response) + expect(result.output.accountType).toBe('BREX_EMPOWER') + }) +}) diff --git a/apps/sim/tools/brex/get_company.ts b/apps/sim/tools/brex/get_company.ts index 68a2bbc0e41..6e0dd17411b 100644 --- a/apps/sim/tools/brex/get_company.ts +++ b/apps/sim/tools/brex/get_company.ts @@ -33,7 +33,7 @@ export const brexGetCompanyTool: ToolConfig status: { type: 'string', description: - 'User status (INVITED, ACTIVE, CLOSED, DISABLED, DELETED, PENDING_ACTIVATION, INACTIVE, ARCHIVED)', + 'User status (INVITED, ACTIVE, DISABLED, PENDING_ACTIVATION, INACTIVE, ARCHIVED)', optional: true, }, managerId: { type: 'string', description: 'ID of the manager', optional: true }, diff --git a/apps/sim/tools/brex/list_cards.ts b/apps/sim/tools/brex/list_cards.ts index 3826c48babf..5d96260b2ba 100644 --- a/apps/sim/tools/brex/list_cards.ts +++ b/apps/sim/tools/brex/list_cards.ts @@ -76,7 +76,8 @@ export const brexListCardsTool: ToolConfig = { payment_status: { type: 'string', description: - 'Payment status (NOT_STARTED, PROCESSING, CANCELED, DECLINED, CLEARED, REFUNDING, REFUNDED, CASH_ADVANCE, CREDITED, AWAITING_PAYMENT, SCHEDULED)', + 'Payment status (NOT_STARTED, PROCESSING, CANCELED, DECLINED, CLEARED, REFUNDING, REFUNDED, CASH_ADVANCE, CREDITED, AWAITING_PAYMENT, SCHEDULED, HELD)', optional: true, }, expense_type: { @@ -911,8 +911,7 @@ export const BREX_USER_PROPERTIES: Record = { email: { type: 'string', description: 'Email address' }, status: { type: 'string', - description: - 'User status (INVITED, ACTIVE, CLOSED, DISABLED, DELETED, PENDING_ACTIVATION, INACTIVE, ARCHIVED)', + description: 'User status (INVITED, ACTIVE, DISABLED, PENDING_ACTIVATION, INACTIVE, ARCHIVED)', optional: true, }, manager_id: { type: 'string', description: 'ID of the manager', optional: true }, diff --git a/apps/sim/tools/brex/update_expense.ts b/apps/sim/tools/brex/update_expense.ts index 511dca67302..90379dfd773 100644 --- a/apps/sim/tools/brex/update_expense.ts +++ b/apps/sim/tools/brex/update_expense.ts @@ -73,7 +73,7 @@ export const brexUpdateExpenseTool: ToolConfig = { @@ -42,7 +43,7 @@ export const cancelBookingTool: ToolConfig { - return `https://api.cal.com/v2/bookings/${encodeURIComponent(params.bookingUid)}/cancel` + return `https://api.cal.com/v2/bookings/${safeUrlPathSegment(params.bookingUid, 'bookingUid')}/cancel` }, method: 'POST', headers: (params) => ({ diff --git a/apps/sim/tools/calcom/confirm_booking.ts b/apps/sim/tools/calcom/confirm_booking.ts index cab2feb3f9c..b9ca4566be6 100644 --- a/apps/sim/tools/calcom/confirm_booking.ts +++ b/apps/sim/tools/calcom/confirm_booking.ts @@ -6,6 +6,7 @@ import { HOSTS_OUTPUT, } from '@/tools/calcom/types' import type { ToolConfig } from '@/tools/types' +import { safeUrlPathSegment } from '@/tools/url-path' export const confirmBookingTool: ToolConfig< CalcomConfirmBookingParams, @@ -38,7 +39,7 @@ export const confirmBookingTool: ToolConfig< request: { url: (params: CalcomConfirmBookingParams) => { - return `https://api.cal.com/v2/bookings/${encodeURIComponent(params.bookingUid)}/confirm` + return `https://api.cal.com/v2/bookings/${safeUrlPathSegment(params.bookingUid, 'bookingUid')}/confirm` }, method: 'POST', headers: (params) => ({ diff --git a/apps/sim/tools/calcom/create_event_type.ts b/apps/sim/tools/calcom/create_event_type.ts index 5a84bfe5627..2e0ed43a03e 100644 --- a/apps/sim/tools/calcom/create_event_type.ts +++ b/apps/sim/tools/calcom/create_event_type.ts @@ -215,6 +215,12 @@ export const createEventTypeTool: ToolConfig< disableGuests: { type: 'boolean', description: 'Whether guests are disabled' }, createdAt: { type: 'string', description: 'ISO timestamp of creation' }, updatedAt: { type: 'string', description: 'ISO timestamp of last update' }, + bookingUrl: { type: 'string', description: 'Public booking page URL for the event type' }, + hidden: { + type: 'boolean', + description: 'Whether the event type is hidden from the profile', + }, + ownerId: { type: 'number', description: 'ID of the user who owns the event type' }, }, }, }, diff --git a/apps/sim/tools/calcom/decline_booking.ts b/apps/sim/tools/calcom/decline_booking.ts index ed7e25cdf2e..e7c159ed570 100644 --- a/apps/sim/tools/calcom/decline_booking.ts +++ b/apps/sim/tools/calcom/decline_booking.ts @@ -6,6 +6,7 @@ import { HOSTS_OUTPUT, } from '@/tools/calcom/types' import type { ToolConfig } from '@/tools/types' +import { safeUrlPathSegment } from '@/tools/url-path' export const declineBookingTool: ToolConfig< CalcomDeclineBookingParams, @@ -44,7 +45,7 @@ export const declineBookingTool: ToolConfig< request: { url: (params: CalcomDeclineBookingParams) => { - return `https://api.cal.com/v2/bookings/${encodeURIComponent(params.bookingUid)}/decline` + return `https://api.cal.com/v2/bookings/${safeUrlPathSegment(params.bookingUid, 'bookingUid')}/decline` }, method: 'POST', headers: (params) => ({ diff --git a/apps/sim/tools/calcom/delete_event_type.ts b/apps/sim/tools/calcom/delete_event_type.ts index 4e703b8559a..c2546ea136e 100644 --- a/apps/sim/tools/calcom/delete_event_type.ts +++ b/apps/sim/tools/calcom/delete_event_type.ts @@ -3,6 +3,7 @@ import type { CalcomDeleteEventTypeResponse, } from '@/tools/calcom/types' import type { ToolConfig } from '@/tools/types' +import { safeUrlPathSegment } from '@/tools/url-path' export const deleteEventTypeTool: ToolConfig< CalcomDeleteEventTypeParams, @@ -35,7 +36,7 @@ export const deleteEventTypeTool: ToolConfig< request: { url: (params: CalcomDeleteEventTypeParams) => - `https://api.cal.com/v2/event-types/${params.eventTypeId}`, + `https://api.cal.com/v2/event-types/${safeUrlPathSegment(params.eventTypeId, 'eventTypeId')}`, method: 'DELETE', headers: (params) => ({ Authorization: `Bearer ${params.accessToken}`, diff --git a/apps/sim/tools/calcom/delete_schedule.ts b/apps/sim/tools/calcom/delete_schedule.ts index 15e9162e889..dab0d5b33d4 100644 --- a/apps/sim/tools/calcom/delete_schedule.ts +++ b/apps/sim/tools/calcom/delete_schedule.ts @@ -1,5 +1,6 @@ import type { CalcomDeleteScheduleParams, CalcomDeleteScheduleResponse } from '@/tools/calcom/types' import type { ToolConfig } from '@/tools/types' +import { safeUrlPathSegment } from '@/tools/url-path' export const deleteScheduleTool: ToolConfig< CalcomDeleteScheduleParams, @@ -32,7 +33,7 @@ export const deleteScheduleTool: ToolConfig< request: { url: (params: CalcomDeleteScheduleParams) => - `https://api.cal.com/v2/schedules/${encodeURIComponent(params.scheduleId)}`, + `https://api.cal.com/v2/schedules/${safeUrlPathSegment(params.scheduleId, 'scheduleId')}`, method: 'DELETE', headers: (params) => ({ Authorization: `Bearer ${params.accessToken}`, diff --git a/apps/sim/tools/calcom/get_booking.ts b/apps/sim/tools/calcom/get_booking.ts index 83dd1cc952e..42925400c0a 100644 --- a/apps/sim/tools/calcom/get_booking.ts +++ b/apps/sim/tools/calcom/get_booking.ts @@ -6,6 +6,7 @@ import { HOSTS_OUTPUT, } from '@/tools/calcom/types' import type { ToolConfig } from '@/tools/types' +import { safeUrlPathSegment } from '@/tools/url-path' export const getBookingTool: ToolConfig = { id: 'calcom_get_booking', @@ -35,7 +36,7 @@ export const getBookingTool: ToolConfig { - return `https://api.cal.com/v2/bookings/${encodeURIComponent(params.bookingUid)}` + return `https://api.cal.com/v2/bookings/${safeUrlPathSegment(params.bookingUid, 'bookingUid')}` }, method: 'GET', headers: (params) => ({ diff --git a/apps/sim/tools/calcom/get_event_type.ts b/apps/sim/tools/calcom/get_event_type.ts index 461db469d53..793dee34f09 100644 --- a/apps/sim/tools/calcom/get_event_type.ts +++ b/apps/sim/tools/calcom/get_event_type.ts @@ -1,5 +1,6 @@ import type { CalcomGetEventTypeParams, CalcomGetEventTypeResponse } from '@/tools/calcom/types' import type { ToolConfig } from '@/tools/types' +import { safeUrlPathSegment } from '@/tools/url-path' export const getEventTypeTool: ToolConfig = { id: 'calcom_get_event_type', @@ -29,7 +30,7 @@ export const getEventTypeTool: ToolConfig - `https://api.cal.com/v2/event-types/${params.eventTypeId}`, + `https://api.cal.com/v2/event-types/${safeUrlPathSegment(params.eventTypeId, 'eventTypeId')}`, method: 'GET', headers: (params) => ({ Authorization: `Bearer ${params.accessToken}`, @@ -69,6 +70,12 @@ export const getEventTypeTool: ToolConfig