mirror of
https://github.com/simstudioai/sim.git
synced 2026-03-15 03:00:33 -04:00
Compare commits
4 Commits
v0.5.100
...
feat/tools
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
315e4509a3 | ||
|
|
5e3c43ff83 | ||
|
|
8db43b775c | ||
|
|
edf3c0dc06 |
@@ -0,0 +1,96 @@
|
||||
---
|
||||
title: Umgebungsvariablen
|
||||
---
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout'
|
||||
import { Image } from '@/components/ui/image'
|
||||
|
||||
Umgebungsvariablen bieten eine sichere Möglichkeit, Konfigurationswerte und Geheimnisse in Ihren Workflows zu verwalten, einschließlich API-Schlüssel und anderer sensibler Daten, auf die Ihre Workflows zugreifen müssen. Sie halten Geheimnisse aus Ihren Workflow-Definitionen heraus und machen sie während der Ausführung verfügbar.
|
||||
|
||||
## Variablentypen
|
||||
|
||||
Umgebungsvariablen in Sim funktionieren auf zwei Ebenen:
|
||||
|
||||
- **Persönliche Umgebungsvariablen**: Privat für Ihr Konto, nur Sie können sie sehen und verwenden
|
||||
- **Workspace-Umgebungsvariablen**: Werden im gesamten Workspace geteilt und sind für alle Teammitglieder verfügbar
|
||||
|
||||
<Callout type="info">
|
||||
Workspace-Umgebungsvariablen haben Vorrang vor persönlichen Variablen, wenn es einen Namenskonflikt gibt.
|
||||
</Callout>
|
||||
|
||||
## Einrichten von Umgebungsvariablen
|
||||
|
||||
Navigieren Sie zu den Einstellungen, um Ihre Umgebungsvariablen zu konfigurieren:
|
||||
|
||||
<Image
|
||||
src="/static/environment/environment-1.png"
|
||||
alt="Umgebungsvariablen-Modal zum Erstellen neuer Variablen"
|
||||
width={500}
|
||||
height={350}
|
||||
/>
|
||||
|
||||
In Ihren Workspace-Einstellungen können Sie sowohl persönliche als auch Workspace-Umgebungsvariablen erstellen und verwalten. Persönliche Variablen sind privat für Ihr Konto, während Workspace-Variablen mit allen Teammitgliedern geteilt werden.
|
||||
|
||||
### Variablen auf Workspace-Ebene setzen
|
||||
|
||||
Verwenden Sie den Workspace-Bereichsschalter, um Variablen für Ihr gesamtes Team verfügbar zu machen:
|
||||
|
||||
<Image
|
||||
src="/static/environment/environment-2.png"
|
||||
alt="Workspace-Bereich für Umgebungsvariablen umschalten"
|
||||
width={500}
|
||||
height={350}
|
||||
/>
|
||||
|
||||
Wenn Sie den Workspace-Bereich aktivieren, wird die Variable für alle Workspace-Mitglieder verfügbar und kann in jedem Workflow innerhalb dieses Workspaces verwendet werden.
|
||||
|
||||
### Ansicht der Workspace-Variablen
|
||||
|
||||
Sobald Sie Workspace-Variablen haben, erscheinen sie in Ihrer Liste der Umgebungsvariablen:
|
||||
|
||||
<Image
|
||||
src="/static/environment/environment-3.png"
|
||||
alt="Workspace-Variablen in der Liste der Umgebungsvariablen"
|
||||
width={500}
|
||||
height={350}
|
||||
/>
|
||||
|
||||
## Verwendung von Variablen in Workflows
|
||||
|
||||
Um Umgebungsvariablen in Ihren Workflows zu referenzieren, verwenden Sie die `{{}}` Notation. Wenn Sie `{{` in ein beliebiges Eingabefeld eingeben, erscheint ein Dropdown-Menü mit Ihren persönlichen und Workspace-Umgebungsvariablen. Wählen Sie einfach die Variable aus, die Sie verwenden möchten.
|
||||
|
||||
<Image
|
||||
src="/static/environment/environment-4.png"
|
||||
alt="Verwendung von Umgebungsvariablen mit doppelter Klammernotation"
|
||||
width={500}
|
||||
height={350}
|
||||
/>
|
||||
|
||||
## Wie Variablen aufgelöst werden
|
||||
|
||||
**Workspace-Variablen haben immer Vorrang** vor persönlichen Variablen, unabhängig davon, wer den Workflow ausführt.
|
||||
|
||||
Wenn keine Workspace-Variable für einen Schlüssel existiert, werden persönliche Variablen verwendet:
|
||||
- **Manuelle Ausführungen (UI)**: Ihre persönlichen Variablen
|
||||
- **Automatisierte Ausführungen (API, Webhook, Zeitplan, bereitgestellter Chat)**: Persönliche Variablen des Workflow-Besitzers
|
||||
|
||||
<Callout type="info">
|
||||
Persönliche Variablen eignen sich am besten zum Testen. Verwenden Sie Workspace-Variablen für Produktions-Workflows.
|
||||
</Callout>
|
||||
|
||||
## Sicherheits-Best-Practices
|
||||
|
||||
### Für sensible Daten
|
||||
- Speichern Sie API-Schlüssel, Tokens und Passwörter als Umgebungsvariablen anstatt sie im Code festzuschreiben
|
||||
- Verwenden Sie Workspace-Variablen für gemeinsam genutzte Ressourcen, die mehrere Teammitglieder benötigen
|
||||
- Bewahren Sie persönliche Anmeldedaten in persönlichen Variablen auf
|
||||
|
||||
### Variablenbenennung
|
||||
- Verwenden Sie beschreibende Namen: `DATABASE_URL` anstatt `DB`
|
||||
- Folgen Sie einheitlichen Benennungskonventionen in Ihrem Team
|
||||
- Erwägen Sie Präfixe, um Konflikte zu vermeiden: `PROD_API_KEY`, `DEV_API_KEY`
|
||||
|
||||
### Zugriffskontrolle
|
||||
- Workspace-Umgebungsvariablen respektieren Workspace-Berechtigungen
|
||||
- Nur Benutzer mit Schreibzugriff oder höher können Workspace-Variablen erstellen/ändern
|
||||
- Persönliche Variablen sind immer privat für den einzelnen Benutzer
|
||||
@@ -95,17 +95,11 @@ const apiUrl = `https://api.example.com/users/${userId}/profile`;
|
||||
|
||||
### Request Retries
|
||||
|
||||
The API block supports **configurable retries** (see the block’s **Advanced** settings):
|
||||
|
||||
- **Retries**: Number of retry attempts (additional tries after the first request)
|
||||
- **Retry delay (ms)**: Initial delay before retrying (uses exponential backoff)
|
||||
- **Max retry delay (ms)**: Maximum delay between retries
|
||||
- **Retry non-idempotent methods**: Allow retries for **POST/PATCH** (may create duplicate requests)
|
||||
|
||||
Retries are attempted for:
|
||||
|
||||
- Network/connection failures and timeouts (with exponential backoff)
|
||||
- Rate limits (**429**) and server errors (**5xx**)
|
||||
The API block automatically handles:
|
||||
- Network timeouts with exponential backoff
|
||||
- Rate limit responses (429 status codes)
|
||||
- Server errors (5xx status codes) with retry logic
|
||||
- Connection failures with reconnection attempts
|
||||
|
||||
### Response Validation
|
||||
|
||||
|
||||
@@ -1,192 +0,0 @@
|
||||
---
|
||||
title: Credentials
|
||||
description: Manage secrets, API keys, and OAuth connections for your workflows
|
||||
---
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout'
|
||||
import { Image } from '@/components/ui/image'
|
||||
import { Step, Steps } from 'fumadocs-ui/components/steps'
|
||||
|
||||
Credentials provide a secure way to manage API keys, tokens, and third-party service connections across your workflows. Instead of hardcoding sensitive values into your workflow, you store them as credentials and reference them at runtime.
|
||||
|
||||
Sim supports two categories of credentials: **secrets** for static values like API keys, and **OAuth accounts** for authenticated service connections like Google or Slack.
|
||||
|
||||
## Getting Started
|
||||
|
||||
To manage credentials, open your workspace **Settings** and navigate to the **Secrets** tab.
|
||||
|
||||
<Image
|
||||
src="/static/credentials/settings-secrets.png"
|
||||
alt="Settings modal showing the Secrets tab with a list of saved credentials"
|
||||
width={700}
|
||||
height={200}
|
||||
/>
|
||||
|
||||
From here you can search, create, and delete both secrets and OAuth connections.
|
||||
|
||||
## Secrets
|
||||
|
||||
Secrets are key-value pairs that store sensitive data like API keys, tokens, and passwords. Each secret has a **key** (used to reference it in workflows) and a **value** (the actual secret).
|
||||
|
||||
### Creating a Secret
|
||||
|
||||
<Image
|
||||
src="/static/credentials/create-secret.png"
|
||||
alt="Create Secret dialog with fields for key, value, description, and scope toggle"
|
||||
width={500}
|
||||
height={400}
|
||||
/>
|
||||
|
||||
<Steps>
|
||||
<Step>
|
||||
Click **+ Add** and select **Secret** as the type
|
||||
</Step>
|
||||
<Step>
|
||||
Enter a **Key** name (letters, numbers, and underscores only, e.g. `OPENAI_API_KEY`)
|
||||
</Step>
|
||||
<Step>
|
||||
Enter the **Value**
|
||||
</Step>
|
||||
<Step>
|
||||
Optionally add a **Description** to help your team understand what the secret is for
|
||||
</Step>
|
||||
<Step>
|
||||
Choose the **Scope** — Workspace or Personal
|
||||
</Step>
|
||||
<Step>
|
||||
Click **Create**
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
### Using Secrets in Workflows
|
||||
|
||||
To reference a secret in any input field, type `{{` to open the dropdown. It will show your available secrets grouped by scope.
|
||||
|
||||
<Image
|
||||
src="/static/credentials/secret-dropdown.png"
|
||||
alt="Typing {{ in a code block opens a dropdown showing available workspace secrets"
|
||||
width={400}
|
||||
height={250}
|
||||
/>
|
||||
|
||||
Select the secret you want to use. The reference will appear highlighted in blue, indicating it will be resolved at runtime.
|
||||
|
||||
<Image
|
||||
src="/static/credentials/secret-resolved.png"
|
||||
alt="A resolved secret reference shown in blue text as {{OPENAI_API_KEY}}"
|
||||
width={400}
|
||||
height={200}
|
||||
/>
|
||||
|
||||
<Callout type="warn">
|
||||
Secret values are never exposed in the workflow editor or logs. They are only resolved during execution.
|
||||
</Callout>
|
||||
|
||||
### Bulk Import
|
||||
|
||||
You can import multiple secrets at once by pasting `.env`-style content:
|
||||
|
||||
1. Click **+ Add**, then switch to **Bulk** mode
|
||||
2. Paste your environment variables in `KEY=VALUE` format
|
||||
3. Choose the scope for all imported secrets
|
||||
4. Click **Create**
|
||||
|
||||
The parser supports standard `KEY=VALUE` pairs, quoted values, comments (`#`), and blank lines.
|
||||
|
||||
## OAuth Accounts
|
||||
|
||||
OAuth accounts are authenticated connections to third-party services like Google, Slack, GitHub, and more. Sim handles the OAuth flow, token storage, and automatic refresh.
|
||||
|
||||
You can connect **multiple accounts per provider** — for example, two separate Gmail accounts for different workflows.
|
||||
|
||||
### Connecting an OAuth Account
|
||||
|
||||
<Image
|
||||
src="/static/credentials/create-oauth.png"
|
||||
alt="Create Secret dialog with OAuth Account type selected, showing display name and provider dropdown"
|
||||
width={500}
|
||||
height={400}
|
||||
/>
|
||||
|
||||
<Steps>
|
||||
<Step>
|
||||
Click **+ Add** and select **OAuth Account** as the type
|
||||
</Step>
|
||||
<Step>
|
||||
Enter a **Display name** to identify this connection (e.g. "Work Gmail" or "Marketing Slack")
|
||||
</Step>
|
||||
<Step>
|
||||
Optionally add a **Description**
|
||||
</Step>
|
||||
<Step>
|
||||
Select the **Account** provider from the dropdown
|
||||
</Step>
|
||||
<Step>
|
||||
Click **Connect** and complete the authorization flow
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
### Using OAuth Accounts in Workflows
|
||||
|
||||
Blocks that require authentication (e.g. Gmail, Slack, Google Sheets) display a credential selector dropdown. Select the OAuth account you want the block to use.
|
||||
|
||||
<Image
|
||||
src="/static/credentials/oauth-selector.png"
|
||||
alt="Gmail block showing the account selector dropdown with a connected account and option to connect another"
|
||||
width={500}
|
||||
height={350}
|
||||
/>
|
||||
|
||||
You can also connect additional accounts directly from the block by selecting **Connect another account** at the bottom of the dropdown.
|
||||
|
||||
<Callout type="info">
|
||||
If a block requires an OAuth connection and none is selected, the workflow will fail at that step.
|
||||
</Callout>
|
||||
|
||||
## Workspace vs. Personal
|
||||
|
||||
Credentials can be scoped to your **workspace** (shared with your team) or kept **personal** (private to you).
|
||||
|
||||
| | Workspace | Personal |
|
||||
|---|---|---|
|
||||
| **Visibility** | All workspace members | Only you |
|
||||
| **Use in workflows** | Any member can use | Only you can use |
|
||||
| **Best for** | Production workflows, shared services | Testing, personal API keys |
|
||||
| **Who can edit** | Workspace admins | Only you |
|
||||
| **Auto-shared** | Yes — all members get access on creation | No — only you have access |
|
||||
|
||||
<Callout type="info">
|
||||
When a workspace and personal secret share the same key name, the **workspace secret takes precedence**.
|
||||
</Callout>
|
||||
|
||||
### Resolution Order
|
||||
|
||||
When a workflow runs, Sim resolves secrets in this order:
|
||||
|
||||
1. **Workspace secrets** are checked first
|
||||
2. **Personal secrets** are used as a fallback — from the user who triggered the run (manual) or the workflow owner (automated runs via API, webhook, or schedule)
|
||||
|
||||
## Access Control
|
||||
|
||||
Each credential has role-based access control:
|
||||
|
||||
- **Admin** — can view, edit, delete, and manage who has access
|
||||
- **Member** — can use the credential in workflows (read-only)
|
||||
|
||||
When you create a workspace secret, all current workspace members are automatically granted access. Personal secrets are only accessible to you by default.
|
||||
|
||||
### Sharing a Credential
|
||||
|
||||
To share a credential with specific team members:
|
||||
|
||||
1. Click **Details** on the credential
|
||||
2. Invite members by email
|
||||
3. Assign them an **Admin** or **Member** role
|
||||
|
||||
## Best Practices
|
||||
|
||||
- **Use workspace credentials for production** so workflows work regardless of who triggers them
|
||||
- **Use personal credentials for development** to keep your test keys separate
|
||||
- **Name keys descriptively** — `STRIPE_SECRET_KEY` over `KEY1`
|
||||
- **Connect multiple OAuth accounts** when you need different permissions or identities per workflow
|
||||
- **Never hardcode secrets** in workflow input fields — always use `{{KEY}}` references
|
||||
@@ -13,7 +13,6 @@
|
||||
"skills",
|
||||
"knowledgebase",
|
||||
"variables",
|
||||
"credentials",
|
||||
"execution",
|
||||
"permissions",
|
||||
"sdks",
|
||||
|
||||
@@ -1012,8 +1012,8 @@ Update a webhook in Attio (target URL and/or subscriptions)
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `webhookId` | string | Yes | The webhook ID to update |
|
||||
| `targetUrl` | string | Yes | HTTPS target URL for webhook delivery |
|
||||
| `subscriptions` | string | Yes | JSON array of subscriptions, e.g. \[\{"event_type":"note.created"\}\] |
|
||||
| `targetUrl` | string | No | New HTTPS target URL |
|
||||
| `subscriptions` | string | No | New JSON array of subscriptions |
|
||||
|
||||
#### Output
|
||||
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
---
|
||||
title: Environment Variables
|
||||
---
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout'
|
||||
import { Image } from '@/components/ui/image'
|
||||
|
||||
Environment variables provide a secure way to manage configuration values and secrets across your workflows, including API keys and other sensitive data that your workflows need to access. They keep secrets out of your workflow definitions while making them available during execution.
|
||||
|
||||
## Variable Types
|
||||
|
||||
Environment variables in Sim work at two levels:
|
||||
|
||||
- **Personal Environment Variables**: Private to your account, only you can see and use them
|
||||
- **Workspace Environment Variables**: Shared across the entire workspace, available to all team members
|
||||
|
||||
<Callout type="info">
|
||||
Workspace environment variables take precedence over personal ones when there's a naming conflict.
|
||||
</Callout>
|
||||
|
||||
## Setting up Environment Variables
|
||||
|
||||
Navigate to Settings to configure your environment variables:
|
||||
|
||||
<Image
|
||||
src="/static/environment/environment-1.png"
|
||||
alt="Environment variables modal for creating new variables"
|
||||
width={500}
|
||||
height={350}
|
||||
/>
|
||||
|
||||
From your workspace settings, you can create and manage both personal and workspace-level environment variables. Personal variables are private to your account, while workspace variables are shared with all team members.
|
||||
|
||||
### Making Variables Workspace-Scoped
|
||||
|
||||
Use the workspace scope toggle to make variables available to your entire team:
|
||||
|
||||
<Image
|
||||
src="/static/environment/environment-2.png"
|
||||
alt="Toggle workspace scope for environment variables"
|
||||
width={500}
|
||||
height={350}
|
||||
/>
|
||||
|
||||
When you enable workspace scope, the variable becomes available to all workspace members and can be used in any workflow within that workspace.
|
||||
|
||||
### Workspace Variables View
|
||||
|
||||
Once you have workspace-scoped variables, they appear in your environment variables list:
|
||||
|
||||
<Image
|
||||
src="/static/environment/environment-3.png"
|
||||
alt="Workspace-scoped variables in the environment variables list"
|
||||
width={500}
|
||||
height={350}
|
||||
/>
|
||||
|
||||
## Using Variables in Workflows
|
||||
|
||||
To reference environment variables in your workflows, use the `{{}}` notation. When you type `{{` in any input field, a dropdown will appear showing both your personal and workspace-level environment variables. Simply select the variable you want to use.
|
||||
|
||||
<Image
|
||||
src="/static/environment/environment-4.png"
|
||||
alt="Using environment variables with double brace notation"
|
||||
width={500}
|
||||
height={350}
|
||||
/>
|
||||
|
||||
## How Variables are Resolved
|
||||
|
||||
**Workspace variables always take precedence** over personal variables, regardless of who runs the workflow.
|
||||
|
||||
When no workspace variable exists for a key, personal variables are used:
|
||||
- **Manual runs (UI)**: Your personal variables
|
||||
- **Automated runs (API, webhook, schedule, deployed chat)**: Workflow owner's personal variables
|
||||
|
||||
<Callout type="info">
|
||||
Personal variables are best for testing. Use workspace variables for production workflows.
|
||||
</Callout>
|
||||
|
||||
## Security Best Practices
|
||||
|
||||
### For Sensitive Data
|
||||
- Store API keys, tokens, and passwords as environment variables instead of hardcoding them
|
||||
- Use workspace variables for shared resources that multiple team members need
|
||||
- Keep personal credentials in personal variables
|
||||
|
||||
### Variable Naming
|
||||
- Use descriptive names: `DATABASE_URL` instead of `DB`
|
||||
- Follow consistent naming conventions across your team
|
||||
- Consider prefixes to avoid conflicts: `PROD_API_KEY`, `DEV_API_KEY`
|
||||
|
||||
### Access Control
|
||||
- Workspace environment variables respect workspace permissions
|
||||
- Only users with write access or higher can create/modify workspace variables
|
||||
- Personal variables are always private to the individual user
|
||||
@@ -0,0 +1,96 @@
|
||||
---
|
||||
title: Variables de entorno
|
||||
---
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout'
|
||||
import { Image } from '@/components/ui/image'
|
||||
|
||||
Las variables de entorno proporcionan una forma segura de gestionar valores de configuración y secretos en tus flujos de trabajo, incluyendo claves API y otros datos sensibles que tus flujos de trabajo necesitan acceder. Mantienen los secretos fuera de las definiciones de tu flujo de trabajo mientras los hacen disponibles durante la ejecución.
|
||||
|
||||
## Tipos de variables
|
||||
|
||||
Las variables de entorno en Sim funcionan en dos niveles:
|
||||
|
||||
- **Variables de entorno personales**: Privadas para tu cuenta, solo tú puedes verlas y usarlas
|
||||
- **Variables de entorno del espacio de trabajo**: Compartidas en todo el espacio de trabajo, disponibles para todos los miembros del equipo
|
||||
|
||||
<Callout type="info">
|
||||
Las variables de entorno del espacio de trabajo tienen prioridad sobre las personales cuando hay un conflicto de nombres.
|
||||
</Callout>
|
||||
|
||||
## Configuración de variables de entorno
|
||||
|
||||
Navega a Configuración para configurar tus variables de entorno:
|
||||
|
||||
<Image
|
||||
src="/static/environment/environment-1.png"
|
||||
alt="Modal de variables de entorno para crear nuevas variables"
|
||||
width={500}
|
||||
height={350}
|
||||
/>
|
||||
|
||||
Desde la configuración de tu espacio de trabajo, puedes crear y gestionar variables de entorno tanto personales como a nivel de espacio de trabajo. Las variables personales son privadas para tu cuenta, mientras que las variables del espacio de trabajo se comparten con todos los miembros del equipo.
|
||||
|
||||
### Hacer variables con ámbito de espacio de trabajo
|
||||
|
||||
Usa el interruptor de ámbito del espacio de trabajo para hacer que las variables estén disponibles para todo tu equipo:
|
||||
|
||||
<Image
|
||||
src="/static/environment/environment-2.png"
|
||||
alt="Interruptor de ámbito del espacio de trabajo para variables de entorno"
|
||||
width={500}
|
||||
height={350}
|
||||
/>
|
||||
|
||||
Cuando habilitas el ámbito del espacio de trabajo, la variable se vuelve disponible para todos los miembros del espacio de trabajo y puede ser utilizada en cualquier flujo de trabajo dentro de ese espacio de trabajo.
|
||||
|
||||
### Vista de variables del espacio de trabajo
|
||||
|
||||
Una vez que tienes variables con ámbito de espacio de trabajo, aparecen en tu lista de variables de entorno:
|
||||
|
||||
<Image
|
||||
src="/static/environment/environment-3.png"
|
||||
alt="Variables con ámbito de espacio de trabajo en la lista de variables de entorno"
|
||||
width={500}
|
||||
height={350}
|
||||
/>
|
||||
|
||||
## Uso de variables en flujos de trabajo
|
||||
|
||||
Para hacer referencia a variables de entorno en tus flujos de trabajo, utiliza la notación `{{}}`. Cuando escribas `{{` en cualquier campo de entrada, aparecerá un menú desplegable mostrando tanto tus variables de entorno personales como las del espacio de trabajo. Simplemente selecciona la variable que deseas utilizar.
|
||||
|
||||
<Image
|
||||
src="/static/environment/environment-4.png"
|
||||
alt="Uso de variables de entorno con notación de doble llave"
|
||||
width={500}
|
||||
height={350}
|
||||
/>
|
||||
|
||||
## Cómo se resuelven las variables
|
||||
|
||||
**Las variables del espacio de trabajo siempre tienen prioridad** sobre las variables personales, independientemente de quién ejecute el flujo de trabajo.
|
||||
|
||||
Cuando no existe una variable de espacio de trabajo para una clave, se utilizan las variables personales:
|
||||
- **Ejecuciones manuales (UI)**: Tus variables personales
|
||||
- **Ejecuciones automatizadas (API, webhook, programación, chat implementado)**: Variables personales del propietario del flujo de trabajo
|
||||
|
||||
<Callout type="info">
|
||||
Las variables personales son mejores para pruebas. Usa variables de espacio de trabajo para flujos de trabajo de producción.
|
||||
</Callout>
|
||||
|
||||
## Mejores prácticas de seguridad
|
||||
|
||||
### Para datos sensibles
|
||||
- Almacena claves API, tokens y contraseñas como variables de entorno en lugar de codificarlos directamente
|
||||
- Usa variables de espacio de trabajo para recursos compartidos que varios miembros del equipo necesitan
|
||||
- Mantén las credenciales personales en variables personales
|
||||
|
||||
### Nomenclatura de variables
|
||||
- Usa nombres descriptivos: `DATABASE_URL` en lugar de `DB`
|
||||
- Sigue convenciones de nomenclatura consistentes en todo tu equipo
|
||||
- Considera usar prefijos para evitar conflictos: `PROD_API_KEY`, `DEV_API_KEY`
|
||||
|
||||
### Control de acceso
|
||||
- Las variables de entorno del espacio de trabajo respetan los permisos del espacio de trabajo
|
||||
- Solo los usuarios con acceso de escritura o superior pueden crear/modificar variables del espacio de trabajo
|
||||
- Las variables personales siempre son privadas para el usuario individual
|
||||
@@ -0,0 +1,96 @@
|
||||
---
|
||||
title: Variables d'environnement
|
||||
---
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout'
|
||||
import { Image } from '@/components/ui/image'
|
||||
|
||||
Les variables d'environnement offrent un moyen sécurisé de gérer les valeurs de configuration et les secrets dans vos workflows, y compris les clés API et autres données sensibles dont vos workflows ont besoin. Elles gardent les secrets en dehors de vos définitions de workflow tout en les rendant disponibles pendant l'exécution.
|
||||
|
||||
## Types de variables
|
||||
|
||||
Les variables d'environnement dans Sim fonctionnent à deux niveaux :
|
||||
|
||||
- **Variables d'environnement personnelles** : privées à votre compte, vous seul pouvez les voir et les utiliser
|
||||
- **Variables d'environnement d'espace de travail** : partagées dans tout l'espace de travail, disponibles pour tous les membres de l'équipe
|
||||
|
||||
<Callout type="info">
|
||||
Les variables d'environnement d'espace de travail ont priorité sur les variables personnelles en cas de conflit de noms.
|
||||
</Callout>
|
||||
|
||||
## Configuration des variables d'environnement
|
||||
|
||||
Accédez aux Paramètres pour configurer vos variables d'environnement :
|
||||
|
||||
<Image
|
||||
src="/static/environment/environment-1.png"
|
||||
alt="Fenêtre modale de variables d'environnement pour créer de nouvelles variables"
|
||||
width={500}
|
||||
height={350}
|
||||
/>
|
||||
|
||||
Depuis les paramètres de votre espace de travail, vous pouvez créer et gérer des variables d'environnement personnelles et au niveau de l'espace de travail. Les variables personnelles sont privées à votre compte, tandis que les variables d'espace de travail sont partagées avec tous les membres de l'équipe.
|
||||
|
||||
### Définir des variables au niveau de l'espace de travail
|
||||
|
||||
Utilisez le bouton de portée d'espace de travail pour rendre les variables disponibles à toute votre équipe :
|
||||
|
||||
<Image
|
||||
src="/static/environment/environment-2.png"
|
||||
alt="Activer la portée d'espace de travail pour les variables d'environnement"
|
||||
width={500}
|
||||
height={350}
|
||||
/>
|
||||
|
||||
Lorsque vous activez la portée d'espace de travail, la variable devient disponible pour tous les membres de l'espace de travail et peut être utilisée dans n'importe quel workflow au sein de cet espace de travail.
|
||||
|
||||
### Vue des variables d'espace de travail
|
||||
|
||||
Une fois que vous avez des variables à portée d'espace de travail, elles apparaissent dans votre liste de variables d'environnement :
|
||||
|
||||
<Image
|
||||
src="/static/environment/environment-3.png"
|
||||
alt="Variables à portée d'espace de travail dans la liste des variables d'environnement"
|
||||
width={500}
|
||||
height={350}
|
||||
/>
|
||||
|
||||
## Utilisation des variables dans les workflows
|
||||
|
||||
Pour référencer des variables d'environnement dans vos workflows, utilisez la notation `{{}}`. Lorsque vous tapez `{{` dans n'importe quel champ de saisie, un menu déroulant apparaîtra affichant à la fois vos variables d'environnement personnelles et celles au niveau de l'espace de travail. Sélectionnez simplement la variable que vous souhaitez utiliser.
|
||||
|
||||
<Image
|
||||
src="/static/environment/environment-4.png"
|
||||
alt="Utilisation des variables d'environnement avec la notation à double accolade"
|
||||
width={500}
|
||||
height={350}
|
||||
/>
|
||||
|
||||
## Comment les variables sont résolues
|
||||
|
||||
**Les variables d'espace de travail ont toujours la priorité** sur les variables personnelles, quel que soit l'utilisateur qui exécute le flux de travail.
|
||||
|
||||
Lorsqu'aucune variable d'espace de travail n'existe pour une clé, les variables personnelles sont utilisées :
|
||||
- **Exécutions manuelles (UI)** : Vos variables personnelles
|
||||
- **Exécutions automatisées (API, webhook, planification, chat déployé)** : Variables personnelles du propriétaire du flux de travail
|
||||
|
||||
<Callout type="info">
|
||||
Les variables personnelles sont idéales pour les tests. Utilisez les variables d'espace de travail pour les flux de travail en production.
|
||||
</Callout>
|
||||
|
||||
## Bonnes pratiques de sécurité
|
||||
|
||||
### Pour les données sensibles
|
||||
- Stockez les clés API, les jetons et les mots de passe comme variables d'environnement au lieu de les coder en dur
|
||||
- Utilisez des variables d'espace de travail pour les ressources partagées dont plusieurs membres de l'équipe ont besoin
|
||||
- Conservez vos identifiants personnels dans des variables personnelles
|
||||
|
||||
### Nommage des variables
|
||||
- Utilisez des noms descriptifs : `DATABASE_URL` au lieu de `DB`
|
||||
- Suivez des conventions de nommage cohérentes au sein de votre équipe
|
||||
- Envisagez des préfixes pour éviter les conflits : `PROD_API_KEY`, `DEV_API_KEY`
|
||||
|
||||
### Contrôle d'accès
|
||||
- Les variables d'environnement de l'espace de travail respectent les permissions de l'espace de travail
|
||||
- Seuls les utilisateurs disposant d'un accès en écriture ou supérieur peuvent créer/modifier les variables d'espace de travail
|
||||
- Les variables personnelles sont toujours privées pour l'utilisateur individuel
|
||||
@@ -0,0 +1,96 @@
|
||||
---
|
||||
title: 環境変数
|
||||
---
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout'
|
||||
import { Image } from '@/components/ui/image'
|
||||
|
||||
環境変数は、APIキーやワークフローがアクセスする必要のあるその他の機密データなど、ワークフロー全体で設定値や機密情報を安全に管理する方法を提供します。これにより、実行中にそれらを利用可能にしながら、ワークフロー定義から機密情報を切り離すことができます。
|
||||
|
||||
## 変数タイプ
|
||||
|
||||
Simの環境変数は2つのレベルで機能します:
|
||||
|
||||
- **個人環境変数**:あなたのアカウントに限定され、あなただけが閲覧・使用できます
|
||||
- **ワークスペース環境変数**:ワークスペース全体で共有され、すべてのチームメンバーが利用できます
|
||||
|
||||
<Callout type="info">
|
||||
名前の競合がある場合、ワークスペース環境変数は個人環境変数よりも優先されます。
|
||||
</Callout>
|
||||
|
||||
## 環境変数の設定
|
||||
|
||||
設定に移動して環境変数を構成します:
|
||||
|
||||
<Image
|
||||
src="/static/environment/environment-1.png"
|
||||
alt="新しい変数を作成するための環境変数モーダル"
|
||||
width={500}
|
||||
height={350}
|
||||
/>
|
||||
|
||||
ワークスペース設定から、個人レベルとワークスペースレベルの両方の環境変数を作成・管理できます。個人変数はあなたのアカウントに限定されますが、ワークスペース変数はすべてのチームメンバーと共有されます。
|
||||
|
||||
### 変数をワークスペーススコープにする
|
||||
|
||||
ワークスペーススコープトグルを使用して、変数をチーム全体で利用可能にします:
|
||||
|
||||
<Image
|
||||
src="/static/environment/environment-2.png"
|
||||
alt="環境変数のワークスペーススコープを切り替えるトグル"
|
||||
width={500}
|
||||
height={350}
|
||||
/>
|
||||
|
||||
ワークスペーススコープを有効にすると、その変数はすべてのワークスペースメンバーが利用でき、そのワークスペース内のあらゆるワークフローで使用できるようになります。
|
||||
|
||||
### ワークスペース変数ビュー
|
||||
|
||||
ワークスペーススコープの変数を作成すると、環境変数リストに表示されます:
|
||||
|
||||
<Image
|
||||
src="/static/environment/environment-3.png"
|
||||
alt="環境変数リスト内のワークスペーススコープ変数"
|
||||
width={500}
|
||||
height={350}
|
||||
/>
|
||||
|
||||
## ワークフローでの変数の使用
|
||||
|
||||
ワークフローで環境変数を参照するには、`{{}}`表記を使用します。任意の入力フィールドで`{{`と入力すると、個人用とワークスペースレベルの両方の環境変数を表示するドロップダウンが表示されます。使用したい変数を選択するだけです。
|
||||
|
||||
<Image
|
||||
src="/static/environment/environment-4.png"
|
||||
alt="二重括弧表記を使用した環境変数の使用方法"
|
||||
width={500}
|
||||
height={350}
|
||||
/>
|
||||
|
||||
## 変数の解決方法
|
||||
|
||||
**ワークスペース変数は常に優先されます**。誰がワークフローを実行するかに関わらず、個人変数よりも優先されます。
|
||||
|
||||
キーに対するワークスペース変数が存在しない場合、個人変数が使用されます:
|
||||
- **手動実行(UI)**:あなたの個人変数
|
||||
- **自動実行(API、ウェブフック、スケジュール、デプロイされたチャット)**:ワークフロー所有者の個人変数
|
||||
|
||||
<Callout type="info">
|
||||
個人変数はテストに最適です。本番環境のワークフローにはワークスペース変数を使用してください。
|
||||
</Callout>
|
||||
|
||||
## セキュリティのベストプラクティス
|
||||
|
||||
### 機密データについて
|
||||
- APIキー、トークン、パスワードはハードコーディングせず、環境変数として保存してください
|
||||
- 複数のチームメンバーが必要とする共有リソースにはワークスペース変数を使用してください
|
||||
- 個人の認証情報は個人変数に保管してください
|
||||
|
||||
### 変数の命名
|
||||
- 説明的な名前を使用する:`DATABASE_URL`ではなく`DB`
|
||||
- チーム全体で一貫した命名規則に従う
|
||||
- 競合を避けるために接頭辞を検討する:`PROD_API_KEY`、`DEV_API_KEY`
|
||||
|
||||
### アクセス制御
|
||||
- ワークスペース環境変数はワークスペースの権限を尊重します
|
||||
- 書き込みアクセス権以上を持つユーザーのみがワークスペース変数を作成/変更できます
|
||||
- 個人変数は常に個々のユーザーにプライベートです
|
||||
@@ -0,0 +1,96 @@
|
||||
---
|
||||
title: 环境变量
|
||||
---
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout'
|
||||
import { Image } from '@/components/ui/image'
|
||||
|
||||
环境变量为管理工作流中的配置值和密钥(包括 API 密钥和其他敏感数据)提供了一种安全的方式。它们可以在执行期间使用,同时将敏感信息从工作流定义中隔离开来。
|
||||
|
||||
## 变量类型
|
||||
|
||||
Sim 中的环境变量分为两个级别:
|
||||
|
||||
- **个人环境变量**:仅限于您的账户,只有您可以查看和使用
|
||||
- **工作区环境变量**:在整个工作区内共享,所有团队成员都可以使用
|
||||
|
||||
<Callout type="info">
|
||||
当命名冲突时,工作区环境变量优先于个人环境变量。
|
||||
</Callout>
|
||||
|
||||
## 设置环境变量
|
||||
|
||||
前往设置页面配置您的环境变量:
|
||||
|
||||
<Image
|
||||
src="/static/environment/environment-1.png"
|
||||
alt="用于创建新变量的环境变量弹窗"
|
||||
width={500}
|
||||
height={350}
|
||||
/>
|
||||
|
||||
在工作区设置中,您可以创建和管理个人及工作区级别的环境变量。个人变量仅限于您的账户,而工作区变量会与所有团队成员共享。
|
||||
|
||||
### 将变量设为工作区范围
|
||||
|
||||
使用工作区范围切换按钮,使变量对整个团队可用:
|
||||
|
||||
<Image
|
||||
src="/static/environment/environment-2.png"
|
||||
alt="切换环境变量的工作区范围"
|
||||
width={500}
|
||||
height={350}
|
||||
/>
|
||||
|
||||
启用工作区范围后,该变量将对所有工作区成员可用,并可在该工作区内的任何工作流中使用。
|
||||
|
||||
### 工作区变量视图
|
||||
|
||||
一旦您拥有了工作区范围的变量,它们将显示在您的环境变量列表中:
|
||||
|
||||
<Image
|
||||
src="/static/environment/environment-3.png"
|
||||
alt="环境变量列表中的工作区范围变量"
|
||||
width={500}
|
||||
height={350}
|
||||
/>
|
||||
|
||||
## 在工作流中使用变量
|
||||
|
||||
要在工作流中引用环境变量,请使用 `{{}}` 表示法。当您在任何输入字段中键入 `{{` 时,将会出现一个下拉菜单,显示您的个人和工作区级别的环境变量。只需选择您想要使用的变量即可。
|
||||
|
||||
<Image
|
||||
src="/static/environment/environment-4.png"
|
||||
alt="使用双大括号表示法的环境变量"
|
||||
width={500}
|
||||
height={350}
|
||||
/>
|
||||
|
||||
## 变量的解析方式
|
||||
|
||||
**工作区变量始终优先于**个人变量,无论是谁运行工作流。
|
||||
|
||||
当某个键没有工作区变量时,将使用个人变量:
|
||||
- **手动运行(UI)**:使用您的个人变量
|
||||
- **自动运行(API、Webhook、计划任务、已部署的聊天)**:使用工作流所有者的个人变量
|
||||
|
||||
<Callout type="info">
|
||||
个人变量最适合用于测试。生产环境的工作流请使用工作区变量。
|
||||
</Callout>
|
||||
|
||||
## 安全最佳实践
|
||||
|
||||
### 针对敏感数据
|
||||
- 将 API 密钥、令牌和密码存储为环境变量,而不是硬编码它们
|
||||
- 对于多个团队成员需要的共享资源,使用工作区变量
|
||||
- 将个人凭据保存在个人变量中
|
||||
|
||||
### 变量命名
|
||||
- 使用描述性名称:`DATABASE_URL` 而不是 `DB`
|
||||
- 在团队中遵循一致的命名约定
|
||||
- 考虑使用前缀以避免冲突:`PROD_API_KEY`、`DEV_API_KEY`
|
||||
|
||||
### 访问控制
|
||||
- 工作区环境变量遵循工作区权限
|
||||
- 只有具有写入权限或更高权限的用户才能创建/修改工作区变量
|
||||
- 个人变量始终对个人用户私有
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 83 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 84 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 48 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 23 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 26 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 72 KiB |
@@ -3,8 +3,8 @@
|
||||
import type React from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { motion } from 'framer-motion'
|
||||
import { Paperclip, Send, Square, X } from 'lucide-react'
|
||||
import { Badge, Tooltip } from '@/components/emcn'
|
||||
import { AlertCircle, Paperclip, Send, Square, X } from 'lucide-react'
|
||||
import { Tooltip } from '@/components/emcn'
|
||||
import { VoiceInput } from '@/app/chat/components/input/voice-input'
|
||||
|
||||
const logger = createLogger('ChatInput')
|
||||
@@ -218,12 +218,24 @@ export const ChatInput: React.FC<{
|
||||
<div ref={wrapperRef} className='w-full max-w-3xl md:max-w-[748px]'>
|
||||
{/* Error Messages */}
|
||||
{uploadErrors.length > 0 && (
|
||||
<div className='mb-3 flex flex-col gap-2'>
|
||||
{uploadErrors.map((error, idx) => (
|
||||
<Badge key={idx} variant='red' size='lg' dot className='max-w-full'>
|
||||
{error}
|
||||
</Badge>
|
||||
))}
|
||||
<div className='mb-3'>
|
||||
<div className='rounded-lg border border-red-200 bg-red-50 p-3 dark:border-red-800/50 dark:bg-red-950/20'>
|
||||
<div className='flex items-start gap-2'>
|
||||
<AlertCircle className='mt-0.5 h-4 w-4 shrink-0 text-red-600 dark:text-red-400' />
|
||||
<div className='flex-1'>
|
||||
<div className='mb-1 font-medium text-red-800 text-sm dark:text-red-300'>
|
||||
File upload error
|
||||
</div>
|
||||
<div className='space-y-1'>
|
||||
{uploadErrors.map((error, idx) => (
|
||||
<div key={idx} className='text-red-700 text-sm dark:text-red-400'>
|
||||
{error}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
Combobox,
|
||||
DatePicker,
|
||||
@@ -707,10 +706,12 @@ export function DocumentTagsModal({
|
||||
(def) =>
|
||||
def.displayName.toLowerCase() === editTagForm.displayName.toLowerCase()
|
||||
) && (
|
||||
<Badge variant='amber' size='lg' dot className='max-w-full'>
|
||||
Maximum tag definitions reached. You can still use existing tag definitions,
|
||||
but cannot create new ones.
|
||||
</Badge>
|
||||
<div className='rounded-[4px] border border-amber-500/50 bg-amber-500/10 p-[8px]'>
|
||||
<p className='text-[11px] text-amber-600 dark:text-amber-400'>
|
||||
Maximum tag definitions reached. You can still use existing tag
|
||||
definitions, but cannot create new ones.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className='flex gap-[8px]'>
|
||||
|
||||
@@ -142,7 +142,7 @@ export function ApiKeys({ onOpenChange }: ApiKeysProps) {
|
||||
strokeWidth={2}
|
||||
/>
|
||||
<Input
|
||||
placeholder='Search Sim keys...'
|
||||
placeholder='Search API keys...'
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className='h-auto flex-1 border-0 bg-transparent p-0 font-base leading-none placeholder:text-[var(--text-tertiary)] focus-visible:ring-0 focus-visible:ring-offset-0'
|
||||
@@ -195,7 +195,7 @@ export function ApiKeys({ onOpenChange }: ApiKeysProps) {
|
||||
</div>
|
||||
{workspaceKeys.length === 0 ? (
|
||||
<div className='text-[13px] text-[var(--text-muted)]'>
|
||||
No workspace Sim keys yet
|
||||
No workspace API keys yet
|
||||
</div>
|
||||
) : (
|
||||
workspaceKeys.map((key) => (
|
||||
@@ -301,7 +301,7 @@ export function ApiKeys({ onOpenChange }: ApiKeysProps) {
|
||||
</div>
|
||||
{isConflict && (
|
||||
<div className='text-[12px] text-[var(--text-error)] leading-tight'>
|
||||
Workspace Sim key with the same name overrides this. Rename your
|
||||
Workspace API key with the same name overrides this. Rename your
|
||||
personal key to use it.
|
||||
</div>
|
||||
)}
|
||||
@@ -317,7 +317,7 @@ export function ApiKeys({ onOpenChange }: ApiKeysProps) {
|
||||
filteredWorkspaceKeys.length === 0 &&
|
||||
(personalKeys.length > 0 || workspaceKeys.length > 0) && (
|
||||
<div className='py-[16px] text-center text-[13px] text-[var(--text-muted)]'>
|
||||
No Sim keys found matching "{searchTerm}"
|
||||
No API keys found matching "{searchTerm}"
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
@@ -331,7 +331,7 @@ export function ApiKeys({ onOpenChange }: ApiKeysProps) {
|
||||
<div className='mt-auto flex items-center justify-between'>
|
||||
<div className='flex items-center gap-[8px]'>
|
||||
<span className='font-medium text-[13px] text-[var(--text-secondary)]'>
|
||||
Allow personal Sim keys
|
||||
Allow personal API keys
|
||||
</span>
|
||||
<Tooltip.Root>
|
||||
<Tooltip.Trigger asChild>
|
||||
@@ -383,7 +383,7 @@ export function ApiKeys({ onOpenChange }: ApiKeysProps) {
|
||||
{/* Delete Confirmation Dialog */}
|
||||
<Modal open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
|
||||
<ModalContent size='sm'>
|
||||
<ModalHeader>Delete Sim key</ModalHeader>
|
||||
<ModalHeader>Delete API key</ModalHeader>
|
||||
<ModalBody>
|
||||
<p className='text-[12px] text-[var(--text-secondary)]'>
|
||||
Deleting{' '}
|
||||
|
||||
@@ -62,8 +62,8 @@ export function CreateApiKeyModal({
|
||||
if (isDuplicate) {
|
||||
setCreateError(
|
||||
keyType === 'workspace'
|
||||
? `A workspace Sim key named "${trimmedName}" already exists. Please choose a different name.`
|
||||
: `A personal Sim key named "${trimmedName}" already exists. Please choose a different name.`
|
||||
? `A workspace API key named "${trimmedName}" already exists. Please choose a different name.`
|
||||
: `A personal API key named "${trimmedName}" already exists. Please choose a different name.`
|
||||
)
|
||||
return
|
||||
}
|
||||
@@ -86,11 +86,11 @@ export function CreateApiKeyModal({
|
||||
} catch (error: unknown) {
|
||||
logger.error('API key creation failed:', { error })
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : 'Failed to create Sim key. Please try again.'
|
||||
error instanceof Error ? error.message : 'Failed to create API key. Please try again.'
|
||||
if (errorMessage.toLowerCase().includes('already exists')) {
|
||||
setCreateError(errorMessage)
|
||||
} else {
|
||||
setCreateError('Failed to create Sim key. Please check your connection and try again.')
|
||||
setCreateError('Failed to create API key. Please check your connection and try again.')
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -113,7 +113,7 @@ export function CreateApiKeyModal({
|
||||
{/* Create API Key Dialog */}
|
||||
<Modal open={open} onOpenChange={onOpenChange}>
|
||||
<ModalContent size='sm'>
|
||||
<ModalHeader>Create new Sim key</ModalHeader>
|
||||
<ModalHeader>Create new API key</ModalHeader>
|
||||
<ModalBody>
|
||||
<p className='text-[12px] text-[var(--text-secondary)]'>
|
||||
{keyType === 'workspace'
|
||||
@@ -125,7 +125,7 @@ export function CreateApiKeyModal({
|
||||
{canManageWorkspaceKeys && (
|
||||
<div className='flex flex-col gap-[8px]'>
|
||||
<p className='font-medium text-[13px] text-[var(--text-secondary)]'>
|
||||
Sim Key Type
|
||||
API Key Type
|
||||
</p>
|
||||
<ButtonGroup
|
||||
value={keyType}
|
||||
@@ -143,7 +143,7 @@ export function CreateApiKeyModal({
|
||||
)}
|
||||
<div className='flex flex-col gap-[8px]'>
|
||||
<p className='font-medium text-[13px] text-[var(--text-secondary)]'>
|
||||
Enter a name for your Sim key to help you identify it later.
|
||||
Enter a name for your API key to help you identify it later.
|
||||
</p>
|
||||
{/* Hidden decoy fields to prevent browser autofill */}
|
||||
<input
|
||||
@@ -216,10 +216,10 @@ export function CreateApiKeyModal({
|
||||
}}
|
||||
>
|
||||
<ModalContent size='sm'>
|
||||
<ModalHeader>Your Sim key has been created</ModalHeader>
|
||||
<ModalHeader>Your API key has been created</ModalHeader>
|
||||
<ModalBody>
|
||||
<p className='text-[12px] text-[var(--text-secondary)]'>
|
||||
This is the only time you will see your Sim key.{' '}
|
||||
This is the only time you will see your API key.{' '}
|
||||
<span className='font-semibold text-[var(--text-primary)]'>
|
||||
Copy it now and store it securely.
|
||||
</span>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -6,10 +6,10 @@ interface CredentialsProps {
|
||||
onOpenChange?: (open: boolean) => void
|
||||
}
|
||||
|
||||
export function Credentials({ onOpenChange }: CredentialsProps) {
|
||||
export function Credentials(_props: CredentialsProps) {
|
||||
return (
|
||||
<div className='h-full min-h-0'>
|
||||
<CredentialsManager onOpenChange={onOpenChange} />
|
||||
<CredentialsManager />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -484,12 +484,12 @@ function ServerDetailView({ workspaceId, serverId, onBack }: ServerDetailViewPro
|
||||
{activeConfigTab === 'cursor' && (
|
||||
<a
|
||||
href={getCursorInstallUrl(server.isPublic, server.name)}
|
||||
className='absolute top-[6px] right-2 inline-flex rounded-[6px] bg-[var(--surface-5)] ring-1 ring-[var(--border-1)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--brand-primary)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--surface-2)]'
|
||||
className='absolute top-[6px] right-2'
|
||||
>
|
||||
<img
|
||||
src='https://cursor.com/deeplink/mcp-install-dark.svg'
|
||||
alt='Add to Cursor'
|
||||
className='h-[26px] rounded-[6px] align-middle'
|
||||
className='h-[26px]'
|
||||
/>
|
||||
</a>
|
||||
)}
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
} from 'lucide-react'
|
||||
import {
|
||||
Card,
|
||||
Connections,
|
||||
HexSimple,
|
||||
Key,
|
||||
SModal,
|
||||
@@ -31,7 +32,6 @@ import {
|
||||
SModalSidebarItem,
|
||||
SModalSidebarSection,
|
||||
SModalSidebarSectionTitle,
|
||||
TerminalWindow,
|
||||
} from '@/components/emcn'
|
||||
import { AgentSkillsIcon, McpIcon } from '@/components/icons'
|
||||
import { useSession } from '@/lib/auth/auth-client'
|
||||
@@ -153,11 +153,11 @@ const allNavigationItems: NavigationItem[] = [
|
||||
requiresHosted: true,
|
||||
requiresTeam: true,
|
||||
},
|
||||
{ id: 'credentials', label: 'Secrets', icon: Key, section: 'account' },
|
||||
{ id: 'credentials', label: 'Credentials', icon: Connections, section: 'account' },
|
||||
{ id: 'custom-tools', label: 'Custom Tools', icon: Wrench, section: 'tools' },
|
||||
{ id: 'skills', label: 'Skills', icon: AgentSkillsIcon, section: 'tools' },
|
||||
{ id: 'mcp', label: 'MCP Tools', icon: McpIcon, section: 'tools' },
|
||||
{ id: 'apikeys', label: 'Sim Keys', icon: TerminalWindow, section: 'system' },
|
||||
{ id: 'apikeys', label: 'API Keys', icon: Key, section: 'system' },
|
||||
{ id: 'workflow-mcp-servers', label: 'MCP Servers', icon: Server, section: 'system' },
|
||||
{
|
||||
id: 'byok',
|
||||
@@ -449,18 +449,7 @@ export function SettingsModal({ open, onOpenChange }: SettingsModalProps) {
|
||||
}
|
||||
}
|
||||
|
||||
const { hasUnsavedChanges, onCloseAttempt, setHasUnsavedChanges, setOnCloseAttempt } =
|
||||
useSettingsModalStore()
|
||||
|
||||
const handleDialogOpenChange = (newOpen: boolean) => {
|
||||
if (!newOpen && hasUnsavedChanges && onCloseAttempt) {
|
||||
onCloseAttempt()
|
||||
return
|
||||
}
|
||||
if (!newOpen) {
|
||||
setHasUnsavedChanges(false)
|
||||
setOnCloseAttempt(null)
|
||||
}
|
||||
onOpenChange(newOpen)
|
||||
}
|
||||
|
||||
@@ -472,7 +461,7 @@ export function SettingsModal({ open, onOpenChange }: SettingsModalProps) {
|
||||
</VisuallyHidden.Root>
|
||||
<VisuallyHidden.Root>
|
||||
<DialogPrimitive.Description>
|
||||
Configure your workspace settings, secrets, and preferences
|
||||
Configure your workspace settings, credentials, and preferences
|
||||
</DialogPrimitive.Description>
|
||||
</VisuallyHidden.Root>
|
||||
|
||||
|
||||
@@ -89,38 +89,6 @@ Example:
|
||||
'Request timeout in milliseconds (default: 300000 = 5 minutes, max: 600000 = 10 minutes)',
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
id: 'retries',
|
||||
title: 'Retries',
|
||||
type: 'short-input',
|
||||
placeholder: '0',
|
||||
description:
|
||||
'Number of retry attempts for timeouts, 429 responses, and 5xx errors (default: 0, no retries)',
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
id: 'retryDelayMs',
|
||||
title: 'Retry delay (ms)',
|
||||
type: 'short-input',
|
||||
placeholder: '500',
|
||||
description: 'Initial retry delay in milliseconds (exponential backoff)',
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
id: 'retryMaxDelayMs',
|
||||
title: 'Max retry delay (ms)',
|
||||
type: 'short-input',
|
||||
placeholder: '30000',
|
||||
description: 'Maximum delay between retries in milliseconds',
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
id: 'retryNonIdempotent',
|
||||
title: 'Retry non-idempotent methods',
|
||||
type: 'switch',
|
||||
description: 'Allow retries for POST/PATCH requests (may create duplicate requests)',
|
||||
mode: 'advanced',
|
||||
},
|
||||
],
|
||||
tools: {
|
||||
access: ['http_request'],
|
||||
@@ -132,16 +100,6 @@ Example:
|
||||
body: { type: 'json', description: 'Request body data' },
|
||||
params: { type: 'json', description: 'URL query parameters' },
|
||||
timeout: { type: 'number', description: 'Request timeout in milliseconds' },
|
||||
retries: { type: 'number', description: 'Number of retry attempts for retryable failures' },
|
||||
retryDelayMs: { type: 'number', description: 'Initial retry delay in milliseconds' },
|
||||
retryMaxDelayMs: {
|
||||
type: 'number',
|
||||
description: 'Maximum delay between retries in milliseconds',
|
||||
},
|
||||
retryNonIdempotent: {
|
||||
type: 'boolean',
|
||||
description: 'Allow retries for non-idempotent methods like POST/PATCH',
|
||||
},
|
||||
},
|
||||
outputs: {
|
||||
data: { type: 'json', description: 'API response data (JSON, text, or other formats)' },
|
||||
|
||||
@@ -161,25 +161,21 @@ export const AttioBlock: BlockConfig<AttioResponse> = {
|
||||
Return ONLY the JSON object with Attio attribute values. No explanations, no markdown, no extra text.
|
||||
|
||||
### ATTIO VALUES STRUCTURE
|
||||
Keys are attribute slugs. Most text attributes use array-of-objects format [{"value": "..."}]. Special attributes have their own format.
|
||||
Keys are attribute slugs, values follow Attio's attribute format. Simple values can be strings; complex values are arrays of objects.
|
||||
|
||||
### COMMON PEOPLE ATTRIBUTES
|
||||
- name: [{"first_name": "...", "last_name": "...", "full_name": "..."}] (personal-name type, full_name is required)
|
||||
- name: [{"first_name": "...", "last_name": "..."}]
|
||||
- email_addresses: [{"email_address": "..."}]
|
||||
- phone_numbers: [{"original_phone_number": "...", "country_code": "US"}]
|
||||
- job_title: [{"value": "..."}]
|
||||
- description: [{"value": "..."}]
|
||||
- linkedin: [{"value": "https://linkedin.com/in/..."}]
|
||||
- twitter: [{"value": "@handle"}]
|
||||
- job_title, description, linkedin, twitter
|
||||
|
||||
### COMMON COMPANY ATTRIBUTES
|
||||
- name: [{"value": "..."}]
|
||||
- domains: [{"domain": "..."}]
|
||||
- description: [{"value": "..."}]
|
||||
- primary_location: [{"line_1": "...", "locality": "...", "region": "...", "postcode": "...", "country_code": "US"}]
|
||||
- description, primary_location, categories
|
||||
|
||||
### EXAMPLES
|
||||
Person: {"name": [{"first_name": "John", "last_name": "Doe", "full_name": "John Doe"}], "email_addresses": [{"email_address": "john@example.com"}], "job_title": [{"value": "Engineer"}]}
|
||||
Person: {"name": [{"first_name": "John", "last_name": "Doe"}], "email_addresses": [{"email_address": "john@example.com"}]}
|
||||
Company: {"name": [{"value": "Acme Corp"}], "domains": [{"domain": "acme.com"}]}`,
|
||||
placeholder: 'Describe the record values you want to set...',
|
||||
generationType: 'json-object',
|
||||
@@ -189,7 +185,7 @@ Company: {"name": [{"value": "Acme Corp"}], "domains": [{"domain": "acme.com"}]}
|
||||
id: 'filter',
|
||||
title: 'Filter',
|
||||
type: 'code',
|
||||
placeholder: '{"name": "John Smith"}',
|
||||
placeholder: '{"name": "John Smith"} (optional)',
|
||||
condition: { field: 'operation', value: 'list_records' },
|
||||
wandConfig: {
|
||||
enabled: true,
|
||||
@@ -220,7 +216,7 @@ Empty (list all): {}`,
|
||||
id: 'sorts',
|
||||
title: 'Sort',
|
||||
type: 'code',
|
||||
placeholder: '[{"direction":"asc","attribute":"name"}]',
|
||||
placeholder: '[{"direction":"asc","attribute":"name"}] (optional)',
|
||||
condition: { field: 'operation', value: 'list_records' },
|
||||
wandConfig: {
|
||||
enabled: true,
|
||||
@@ -336,7 +332,7 @@ YYYY-MM-DDTHH:mm:ss.SSSZ
|
||||
id: 'noteMeetingId',
|
||||
title: 'Meeting ID',
|
||||
type: 'short-input',
|
||||
placeholder: 'Link to a meeting',
|
||||
placeholder: 'Link to a meeting (optional)',
|
||||
condition: { field: 'operation', value: 'create_note' },
|
||||
mode: 'advanced',
|
||||
},
|
||||
@@ -362,7 +358,7 @@ YYYY-MM-DDTHH:mm:ss.SSSZ
|
||||
id: 'taskDeadline',
|
||||
title: 'Deadline',
|
||||
type: 'short-input',
|
||||
placeholder: '2024-12-01T15:00:00.000Z',
|
||||
placeholder: '2024-12-01T15:00:00.000Z (optional)',
|
||||
condition: { field: 'operation', value: ['create_task', 'update_task'] },
|
||||
wandConfig: {
|
||||
enabled: true,
|
||||
@@ -399,7 +395,7 @@ YYYY-MM-DDTHH:mm:ss.SSSZ
|
||||
id: 'taskLinkedRecords',
|
||||
title: 'Linked Records',
|
||||
type: 'code',
|
||||
placeholder: '[{"target_object":"people","target_record_id":"..."}]',
|
||||
placeholder: '[{"target_object":"people","target_record_id":"..."}] (optional)',
|
||||
condition: { field: 'operation', value: ['create_task', 'update_task'] },
|
||||
wandConfig: {
|
||||
enabled: true,
|
||||
@@ -425,7 +421,8 @@ Return ONLY the JSON array. No explanations, no markdown, no extra text.
|
||||
id: 'taskAssignees',
|
||||
title: 'Assignees',
|
||||
type: 'code',
|
||||
placeholder: '[{"referenced_actor_type":"workspace-member","referenced_actor_id":"..."}]',
|
||||
placeholder:
|
||||
'[{"referenced_actor_type":"workspace-member","referenced_actor_id":"..."}] (optional)',
|
||||
condition: { field: 'operation', value: ['create_task', 'update_task'] },
|
||||
wandConfig: {
|
||||
enabled: true,
|
||||
@@ -459,21 +456,21 @@ Return ONLY the JSON array. No explanations, no markdown, no extra text.
|
||||
id: 'taskFilterObject',
|
||||
title: 'Linked Object Type',
|
||||
type: 'short-input',
|
||||
placeholder: 'e.g. people, companies',
|
||||
placeholder: 'e.g. people, companies (optional)',
|
||||
condition: { field: 'operation', value: 'list_tasks' },
|
||||
},
|
||||
{
|
||||
id: 'taskFilterRecordId',
|
||||
title: 'Linked Record ID',
|
||||
type: 'short-input',
|
||||
placeholder: 'Filter by linked record ID',
|
||||
placeholder: 'Filter by linked record ID (optional)',
|
||||
condition: { field: 'operation', value: 'list_tasks' },
|
||||
},
|
||||
{
|
||||
id: 'taskFilterAssignee',
|
||||
title: 'Assignee',
|
||||
type: 'short-input',
|
||||
placeholder: 'Filter by assignee email or ID',
|
||||
placeholder: 'Filter by assignee email or ID (optional)',
|
||||
condition: { field: 'operation', value: 'list_tasks' },
|
||||
},
|
||||
{
|
||||
@@ -574,7 +571,7 @@ Return ONLY the JSON array. No explanations, no markdown, no extra text.
|
||||
id: 'listApiSlug',
|
||||
title: 'API Slug',
|
||||
type: 'short-input',
|
||||
placeholder: 'e.g. my_list (auto-generated from name)',
|
||||
placeholder: 'e.g. my_list (optional, auto-generated)',
|
||||
condition: { field: 'operation', value: ['create_list', 'update_list'] },
|
||||
mode: 'advanced',
|
||||
},
|
||||
@@ -626,7 +623,7 @@ Return ONLY the JSON array. No explanations, no markdown, no extra text.
|
||||
id: 'entryValues',
|
||||
title: 'Entry Values',
|
||||
type: 'code',
|
||||
placeholder: '{"attribute_slug": "value"}',
|
||||
placeholder: '{"attribute_slug": "value"} (optional)',
|
||||
condition: {
|
||||
field: 'operation',
|
||||
value: ['create_list_entry', 'update_list_entry'],
|
||||
@@ -656,7 +653,7 @@ Keys are list attribute slugs. Values follow Attio attribute format.
|
||||
id: 'entryFilter',
|
||||
title: 'Filter',
|
||||
type: 'code',
|
||||
placeholder: '{"attribute": {"$operator": "value"}}',
|
||||
placeholder: '{"attribute": {"$operator": "value"}} (optional)',
|
||||
condition: { field: 'operation', value: 'query_list_entries' },
|
||||
wandConfig: {
|
||||
enabled: true,
|
||||
@@ -683,7 +680,7 @@ Logical: $and, $or, $not
|
||||
id: 'entrySorts',
|
||||
title: 'Sort',
|
||||
type: 'code',
|
||||
placeholder: '[{"direction":"asc","attribute":"created_at"}]',
|
||||
placeholder: '[{"direction":"asc","attribute":"created_at"}] (optional)',
|
||||
condition: { field: 'operation', value: 'query_list_entries' },
|
||||
wandConfig: {
|
||||
enabled: true,
|
||||
@@ -822,7 +819,7 @@ YYYY-MM-DDTHH:mm:ss.SSSZ
|
||||
id: 'threadFilterRecordId',
|
||||
title: 'Record ID',
|
||||
type: 'short-input',
|
||||
placeholder: 'Filter by record ID',
|
||||
placeholder: 'Filter by record ID (optional)',
|
||||
condition: { field: 'operation', value: 'list_threads' },
|
||||
},
|
||||
{
|
||||
@@ -836,7 +833,7 @@ YYYY-MM-DDTHH:mm:ss.SSSZ
|
||||
id: 'threadFilterEntryId',
|
||||
title: 'Entry ID',
|
||||
type: 'short-input',
|
||||
placeholder: 'Filter by entry ID',
|
||||
placeholder: 'Filter by entry ID (optional)',
|
||||
condition: { field: 'operation', value: 'list_threads' },
|
||||
},
|
||||
{
|
||||
@@ -868,7 +865,7 @@ YYYY-MM-DDTHH:mm:ss.SSSZ
|
||||
type: 'short-input',
|
||||
placeholder: 'https://example.com/webhook',
|
||||
condition: { field: 'operation', value: ['create_webhook', 'update_webhook'] },
|
||||
required: { field: 'operation', value: ['create_webhook', 'update_webhook'] },
|
||||
required: { field: 'operation', value: 'create_webhook' },
|
||||
},
|
||||
{
|
||||
id: 'webhookSubscriptions',
|
||||
@@ -876,7 +873,7 @@ YYYY-MM-DDTHH:mm:ss.SSSZ
|
||||
type: 'code',
|
||||
placeholder: '[{"event_type":"record.created","filter":{"object_id":"..."}}]',
|
||||
condition: { field: 'operation', value: ['create_webhook', 'update_webhook'] },
|
||||
required: { field: 'operation', value: ['create_webhook', 'update_webhook'] },
|
||||
required: { field: 'operation', value: 'create_webhook' },
|
||||
wandConfig: {
|
||||
enabled: true,
|
||||
maintainHistory: true,
|
||||
@@ -914,8 +911,7 @@ workspace-member.created
|
||||
id: 'limit',
|
||||
title: 'Limit',
|
||||
type: 'short-input',
|
||||
placeholder: 'Max results',
|
||||
mode: 'advanced',
|
||||
placeholder: 'Max results (optional)',
|
||||
condition: {
|
||||
field: 'operation',
|
||||
value: [
|
||||
@@ -929,24 +925,6 @@ workspace-member.created
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'offset',
|
||||
title: 'Offset',
|
||||
type: 'short-input',
|
||||
placeholder: 'Number of results to skip',
|
||||
mode: 'advanced',
|
||||
condition: {
|
||||
field: 'operation',
|
||||
value: [
|
||||
'list_records',
|
||||
'list_notes',
|
||||
'list_tasks',
|
||||
'query_list_entries',
|
||||
'list_threads',
|
||||
'list_webhooks',
|
||||
],
|
||||
},
|
||||
},
|
||||
...getTrigger('attio_record_created').subBlocks,
|
||||
...getTrigger('attio_record_updated').subBlocks,
|
||||
...getTrigger('attio_record_deleted').subBlocks,
|
||||
@@ -1125,7 +1103,6 @@ workspace-member.created
|
||||
|
||||
// Shared params
|
||||
if (params.limit) cleanParams.limit = Number(params.limit)
|
||||
if (params.offset) cleanParams.offset = Number(params.offset)
|
||||
|
||||
return cleanParams
|
||||
},
|
||||
@@ -1187,7 +1164,6 @@ workspace-member.created
|
||||
webhookTargetUrl: { type: 'string', description: 'Webhook target URL' },
|
||||
webhookSubscriptions: { type: 'json', description: 'Webhook event subscriptions' },
|
||||
limit: { type: 'string', description: 'Maximum number of results' },
|
||||
offset: { type: 'string', description: 'Number of results to skip for pagination' },
|
||||
},
|
||||
|
||||
outputs: {
|
||||
|
||||
@@ -24,7 +24,6 @@ export { PanelLeft } from './panel-left'
|
||||
export { Play, PlayOutline } from './play'
|
||||
export { Redo } from './redo'
|
||||
export { Rocket } from './rocket'
|
||||
export { TerminalWindow } from './terminal-window'
|
||||
export { Trash } from './trash'
|
||||
export { Trash2 } from './trash2'
|
||||
export { Undo } from './undo'
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
import type { SVGProps } from 'react'
|
||||
|
||||
/**
|
||||
* Terminal window icon component
|
||||
* @param props - SVG properties including className, fill, etc.
|
||||
*/
|
||||
export function TerminalWindow(props: SVGProps<SVGSVGElement>) {
|
||||
return (
|
||||
<svg
|
||||
width='16'
|
||||
height='14'
|
||||
viewBox='0 0 16 14'
|
||||
fill='none'
|
||||
xmlns='http://www.w3.org/2000/svg'
|
||||
{...props}
|
||||
>
|
||||
<path
|
||||
d='M3 0C1.34315 0 0 1.34315 0 3V11C0 12.6569 1.34315 14 3 14H13C14.6569 14 16 12.6569 16 11V3C16 1.34315 14.6569 0 13 0H3ZM1 3C1 1.89543 1.89543 1 3 1H13C14.1046 1 15 1.89543 15 3V4H1V3ZM1 5H15V11C15 12.1046 14.1046 13 13 13H3C1.89543 13 1 12.1046 1 11V5Z'
|
||||
fill='currentColor'
|
||||
/>
|
||||
<circle cx='3.5' cy='2.5' r='0.75' fill='currentColor' />
|
||||
<circle cx='5.75' cy='2.5' r='0.75' fill='currentColor' />
|
||||
<circle cx='8' cy='2.5' r='0.75' fill='currentColor' />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@@ -1086,7 +1086,6 @@ export class AgentBlockHandler implements BlockHandler {
|
||||
verbosity: providerRequest.verbosity,
|
||||
thinkingLevel: providerRequest.thinkingLevel,
|
||||
previousInteractionId: providerRequest.previousInteractionId,
|
||||
abortSignal: ctx.abortSignal,
|
||||
})
|
||||
|
||||
return this.processProviderResponse(response, block, responseFormat)
|
||||
|
||||
@@ -2,11 +2,7 @@ import crypto from 'crypto'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import type { PermissionGroupConfig } from '@/lib/permission-groups/types'
|
||||
import { getEffectiveBlockOutputs } from '@/lib/workflows/blocks/block-outputs'
|
||||
import {
|
||||
buildCanonicalIndex,
|
||||
buildDefaultCanonicalModes,
|
||||
isCanonicalPair,
|
||||
} from '@/lib/workflows/subblocks/visibility'
|
||||
import { buildCanonicalIndex, isCanonicalPair } from '@/lib/workflows/subblocks/visibility'
|
||||
import { hasTriggerCapability } from '@/lib/workflows/triggers/trigger-utils'
|
||||
import { getAllBlocks } from '@/blocks/registry'
|
||||
import type { BlockConfig } from '@/blocks/types'
|
||||
@@ -134,12 +130,6 @@ export function createBlockFromParams(
|
||||
}
|
||||
})
|
||||
|
||||
const defaultModes = buildDefaultCanonicalModes(blockConfig.subBlocks)
|
||||
if (Object.keys(defaultModes).length > 0) {
|
||||
if (!blockState.data) blockState.data = {}
|
||||
blockState.data.canonicalModes = defaultModes
|
||||
}
|
||||
|
||||
if (validatedInputs) {
|
||||
updateCanonicalModesForInputs(blockState, Object.keys(validatedInputs), blockConfig)
|
||||
}
|
||||
|
||||
@@ -13,7 +13,6 @@ import { convertSquareBracketsToTwiML } from '@/lib/webhooks/utils'
|
||||
import {
|
||||
handleSlackChallenge,
|
||||
handleWhatsAppVerification,
|
||||
validateAttioSignature,
|
||||
validateCalcomSignature,
|
||||
validateCirclebackSignature,
|
||||
validateFirefliesSignature,
|
||||
@@ -598,33 +597,6 @@ export async function verifyProviderAuth(
|
||||
}
|
||||
}
|
||||
|
||||
if (foundWebhook.provider === 'attio') {
|
||||
const secret = providerConfig.webhookSecret as string | undefined
|
||||
|
||||
if (!secret) {
|
||||
logger.debug(
|
||||
`[${requestId}] Attio webhook ${foundWebhook.id} has no signing secret, skipping signature verification`
|
||||
)
|
||||
} else {
|
||||
const signature = request.headers.get('Attio-Signature')
|
||||
|
||||
if (!signature) {
|
||||
logger.warn(`[${requestId}] Attio webhook missing signature header`)
|
||||
return new NextResponse('Unauthorized - Missing Attio signature', { status: 401 })
|
||||
}
|
||||
|
||||
const isValidSignature = validateAttioSignature(secret, signature, rawBody)
|
||||
|
||||
if (!isValidSignature) {
|
||||
logger.warn(`[${requestId}] Attio signature verification failed`, {
|
||||
signatureLength: signature.length,
|
||||
secretLength: secret.length,
|
||||
})
|
||||
return new NextResponse('Unauthorized - Invalid Attio signature', { status: 401 })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (foundWebhook.provider === 'linear') {
|
||||
const secret = providerConfig.webhookSecret as string | undefined
|
||||
|
||||
@@ -979,10 +951,9 @@ export async function queueWebhookExecution(
|
||||
const triggerId = providerConfig.triggerId as string | undefined
|
||||
|
||||
if (triggerId && triggerId !== 'attio_webhook') {
|
||||
const { isAttioPayloadMatch, getAttioEvent } = await import('@/triggers/attio/utils')
|
||||
const { isAttioPayloadMatch } = await import('@/triggers/attio/utils')
|
||||
if (!isAttioPayloadMatch(triggerId, body)) {
|
||||
const event = getAttioEvent(body)
|
||||
const eventType = event?.event_type as string | undefined
|
||||
const eventType = body?.event_type as string | undefined
|
||||
logger.debug(
|
||||
`[${options.requestId}] Attio event mismatch for trigger ${triggerId}. Event: ${eventType}. Skipping execution.`,
|
||||
{
|
||||
@@ -990,7 +961,6 @@ export async function queueWebhookExecution(
|
||||
workflowId: foundWorkflow.id,
|
||||
triggerId,
|
||||
receivedEvent: eventType,
|
||||
bodyKeys: Object.keys(body),
|
||||
}
|
||||
)
|
||||
return NextResponse.json({ status: 'skipped', reason: 'event_type_mismatch' })
|
||||
|
||||
@@ -19,7 +19,6 @@ const calendlyLogger = createLogger('CalendlyWebhook')
|
||||
const grainLogger = createLogger('GrainWebhook')
|
||||
const lemlistLogger = createLogger('LemlistWebhook')
|
||||
const webflowLogger = createLogger('WebflowWebhook')
|
||||
const attioLogger = createLogger('AttioWebhook')
|
||||
const providerSubscriptionsLogger = createLogger('WebhookProviderSubscriptions')
|
||||
|
||||
function getProviderConfig(webhook: any): Record<string, any> {
|
||||
@@ -977,203 +976,6 @@ export async function deleteWebflowWebhook(
|
||||
}
|
||||
}
|
||||
|
||||
export async function createAttioWebhookSubscription(
|
||||
userId: string,
|
||||
webhookData: any,
|
||||
requestId: string
|
||||
): Promise<{ externalId: string; webhookSecret: string } | undefined> {
|
||||
try {
|
||||
const { path, providerConfig } = webhookData
|
||||
const { triggerId, credentialId } = providerConfig || {}
|
||||
|
||||
if (!credentialId) {
|
||||
attioLogger.warn(`[${requestId}] Missing credentialId for Attio webhook creation.`, {
|
||||
webhookId: webhookData.id,
|
||||
})
|
||||
throw new Error(
|
||||
'Attio account connection required. Please connect your Attio account in the trigger configuration and try again.'
|
||||
)
|
||||
}
|
||||
|
||||
const credentialOwner = await getCredentialOwner(credentialId, requestId)
|
||||
const accessToken = credentialOwner
|
||||
? await refreshAccessTokenIfNeeded(
|
||||
credentialOwner.accountId,
|
||||
credentialOwner.userId,
|
||||
requestId
|
||||
)
|
||||
: null
|
||||
|
||||
if (!accessToken) {
|
||||
attioLogger.warn(
|
||||
`[${requestId}] Could not retrieve Attio access token for user ${userId}. Cannot create webhook.`
|
||||
)
|
||||
throw new Error(
|
||||
'Attio account connection required. Please connect your Attio account in the trigger configuration and try again.'
|
||||
)
|
||||
}
|
||||
|
||||
const notificationUrl = `${getBaseUrl()}/api/webhooks/trigger/${path}`
|
||||
|
||||
const { TRIGGER_EVENT_MAP } = await import('@/triggers/attio/utils')
|
||||
|
||||
let subscriptions: Array<{ event_type: string; filter: null }> = []
|
||||
if (triggerId === 'attio_webhook') {
|
||||
const allEvents = new Set<string>()
|
||||
for (const events of Object.values(TRIGGER_EVENT_MAP)) {
|
||||
for (const event of events) {
|
||||
allEvents.add(event)
|
||||
}
|
||||
}
|
||||
subscriptions = Array.from(allEvents).map((event_type) => ({ event_type, filter: null }))
|
||||
} else {
|
||||
const events = TRIGGER_EVENT_MAP[triggerId]
|
||||
if (!events || events.length === 0) {
|
||||
attioLogger.warn(`[${requestId}] No event types mapped for trigger ${triggerId}`, {
|
||||
webhookId: webhookData.id,
|
||||
})
|
||||
throw new Error(`Unknown Attio trigger type: ${triggerId}`)
|
||||
}
|
||||
subscriptions = events.map((event_type) => ({ event_type, filter: null }))
|
||||
}
|
||||
|
||||
const requestBody = {
|
||||
data: {
|
||||
target_url: notificationUrl,
|
||||
subscriptions,
|
||||
},
|
||||
}
|
||||
|
||||
const attioResponse = await fetch('https://api.attio.com/v2/webhooks', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(requestBody),
|
||||
})
|
||||
|
||||
if (!attioResponse.ok) {
|
||||
const errorBody = await attioResponse.json().catch(() => ({}))
|
||||
attioLogger.error(
|
||||
`[${requestId}] Failed to create webhook in Attio for webhook ${webhookData.id}. Status: ${attioResponse.status}`,
|
||||
{ response: errorBody }
|
||||
)
|
||||
|
||||
let userFriendlyMessage = 'Failed to create webhook subscription in Attio'
|
||||
if (attioResponse.status === 401) {
|
||||
userFriendlyMessage = 'Attio authentication failed. Please reconnect your Attio account.'
|
||||
} else if (attioResponse.status === 403) {
|
||||
userFriendlyMessage =
|
||||
'Attio access denied. Please ensure your integration has webhook permissions.'
|
||||
}
|
||||
|
||||
throw new Error(userFriendlyMessage)
|
||||
}
|
||||
|
||||
const responseBody = await attioResponse.json()
|
||||
const data = responseBody.data || responseBody
|
||||
const webhookId = data.id?.webhook_id || data.webhook_id || data.id
|
||||
const secret = data.secret
|
||||
|
||||
if (!webhookId) {
|
||||
attioLogger.error(
|
||||
`[${requestId}] Attio webhook created but no webhook_id returned for webhook ${webhookData.id}`,
|
||||
{ response: responseBody }
|
||||
)
|
||||
throw new Error('Attio webhook creation succeeded but no webhook ID was returned')
|
||||
}
|
||||
|
||||
if (!secret) {
|
||||
attioLogger.warn(
|
||||
`[${requestId}] Attio webhook created but no secret returned for webhook ${webhookData.id}. Signature verification will be skipped.`,
|
||||
{ response: responseBody }
|
||||
)
|
||||
}
|
||||
|
||||
attioLogger.info(
|
||||
`[${requestId}] Successfully created webhook in Attio for webhook ${webhookData.id}.`,
|
||||
{
|
||||
attioWebhookId: webhookId,
|
||||
targetUrl: notificationUrl,
|
||||
subscriptionCount: subscriptions.length,
|
||||
status: data.status,
|
||||
}
|
||||
)
|
||||
|
||||
return { externalId: webhookId, webhookSecret: secret || '' }
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
attioLogger.error(
|
||||
`[${requestId}] Exception during Attio webhook creation for webhook ${webhookData.id}.`,
|
||||
{ message }
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteAttioWebhook(
|
||||
webhook: any,
|
||||
_workflow: any,
|
||||
requestId: string
|
||||
): Promise<void> {
|
||||
try {
|
||||
const config = getProviderConfig(webhook)
|
||||
const externalId = config.externalId as string | undefined
|
||||
const credentialId = config.credentialId as string | undefined
|
||||
|
||||
if (!externalId) {
|
||||
attioLogger.warn(
|
||||
`[${requestId}] Missing externalId for Attio webhook deletion ${webhook.id}, skipping cleanup`
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if (!credentialId) {
|
||||
attioLogger.warn(
|
||||
`[${requestId}] Missing credentialId for Attio webhook deletion ${webhook.id}, skipping cleanup`
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
const credentialOwner = await getCredentialOwner(credentialId, requestId)
|
||||
const accessToken = credentialOwner
|
||||
? await refreshAccessTokenIfNeeded(
|
||||
credentialOwner.accountId,
|
||||
credentialOwner.userId,
|
||||
requestId
|
||||
)
|
||||
: null
|
||||
|
||||
if (!accessToken) {
|
||||
attioLogger.warn(
|
||||
`[${requestId}] Could not retrieve Attio access token. Cannot delete webhook.`,
|
||||
{ webhookId: webhook.id }
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
const attioResponse = await fetch(`https://api.attio.com/v2/webhooks/${externalId}`, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
})
|
||||
|
||||
if (!attioResponse.ok && attioResponse.status !== 404) {
|
||||
const responseBody = await attioResponse.json().catch(() => ({}))
|
||||
attioLogger.warn(
|
||||
`[${requestId}] Failed to delete Attio webhook (non-fatal): ${attioResponse.status}`,
|
||||
{ response: responseBody }
|
||||
)
|
||||
} else {
|
||||
attioLogger.info(`[${requestId}] Successfully deleted Attio webhook ${externalId}`)
|
||||
}
|
||||
} catch (error) {
|
||||
attioLogger.warn(`[${requestId}] Error deleting Attio webhook (non-fatal)`, error)
|
||||
}
|
||||
}
|
||||
|
||||
export async function createGrainWebhookSubscription(
|
||||
_request: NextRequest,
|
||||
webhookData: any,
|
||||
@@ -1809,7 +1611,6 @@ type RecreateCheckInput = {
|
||||
/** Providers that create external webhook subscriptions */
|
||||
const PROVIDERS_WITH_EXTERNAL_SUBSCRIPTIONS = new Set([
|
||||
'airtable',
|
||||
'attio',
|
||||
'calendly',
|
||||
'webflow',
|
||||
'typeform',
|
||||
@@ -1825,7 +1626,6 @@ const SYSTEM_MANAGED_FIELDS = new Set([
|
||||
'externalSubscriptionId',
|
||||
'eventTypes',
|
||||
'webhookTag',
|
||||
'webhookSecret',
|
||||
'historyId',
|
||||
'lastCheckedTimestamp',
|
||||
'setupCompleted',
|
||||
@@ -1886,16 +1686,6 @@ export async function createExternalWebhookSubscription(
|
||||
updatedProviderConfig = { ...updatedProviderConfig, externalId }
|
||||
externalSubscriptionCreated = true
|
||||
}
|
||||
} else if (provider === 'attio') {
|
||||
const result = await createAttioWebhookSubscription(userId, webhookData, requestId)
|
||||
if (result) {
|
||||
updatedProviderConfig = {
|
||||
...updatedProviderConfig,
|
||||
externalId: result.externalId,
|
||||
webhookSecret: result.webhookSecret,
|
||||
}
|
||||
externalSubscriptionCreated = true
|
||||
}
|
||||
} else if (provider === 'calendly') {
|
||||
const externalId = await createCalendlyWebhookSubscription(webhookData, requestId)
|
||||
if (externalId) {
|
||||
@@ -1946,7 +1736,7 @@ export async function createExternalWebhookSubscription(
|
||||
|
||||
/**
|
||||
* Clean up external webhook subscriptions for a webhook
|
||||
* Handles Airtable, Attio, Teams, Telegram, Typeform, Calendly, Grain, and Lemlist cleanup
|
||||
* Handles Airtable, Teams, Telegram, Typeform, Calendly, Grain, and Lemlist cleanup
|
||||
* Don't fail deletion if cleanup fails
|
||||
*/
|
||||
export async function cleanupExternalWebhook(
|
||||
@@ -1956,8 +1746,6 @@ export async function cleanupExternalWebhook(
|
||||
): Promise<void> {
|
||||
if (webhook.provider === 'airtable') {
|
||||
await deleteAirtableWebhook(webhook, workflow, requestId)
|
||||
} else if (webhook.provider === 'attio') {
|
||||
await deleteAttioWebhook(webhook, workflow, requestId)
|
||||
} else if (webhook.provider === 'microsoft-teams') {
|
||||
await deleteTeamsSubscription(webhook, workflow, requestId)
|
||||
} else if (webhook.provider === 'telegram') {
|
||||
|
||||
@@ -1291,49 +1291,6 @@ export async function formatWebhookInput(
|
||||
}
|
||||
}
|
||||
|
||||
if (foundWebhook.provider === 'attio') {
|
||||
const {
|
||||
extractAttioRecordData,
|
||||
extractAttioRecordUpdatedData,
|
||||
extractAttioRecordMergedData,
|
||||
extractAttioNoteData,
|
||||
extractAttioTaskData,
|
||||
extractAttioCommentData,
|
||||
extractAttioListEntryData,
|
||||
extractAttioListEntryUpdatedData,
|
||||
extractAttioGenericData,
|
||||
} = await import('@/triggers/attio/utils')
|
||||
|
||||
const providerConfig = (foundWebhook.providerConfig as Record<string, any>) || {}
|
||||
const triggerId = providerConfig.triggerId as string | undefined
|
||||
|
||||
if (triggerId === 'attio_record_updated') {
|
||||
return extractAttioRecordUpdatedData(body)
|
||||
}
|
||||
if (triggerId === 'attio_record_merged') {
|
||||
return extractAttioRecordMergedData(body)
|
||||
}
|
||||
if (triggerId === 'attio_record_created' || triggerId === 'attio_record_deleted') {
|
||||
return extractAttioRecordData(body)
|
||||
}
|
||||
if (triggerId?.startsWith('attio_note_')) {
|
||||
return extractAttioNoteData(body)
|
||||
}
|
||||
if (triggerId?.startsWith('attio_task_')) {
|
||||
return extractAttioTaskData(body)
|
||||
}
|
||||
if (triggerId?.startsWith('attio_comment_')) {
|
||||
return extractAttioCommentData(body)
|
||||
}
|
||||
if (triggerId === 'attio_list_entry_updated') {
|
||||
return extractAttioListEntryUpdatedData(body)
|
||||
}
|
||||
if (triggerId === 'attio_list_entry_created' || triggerId === 'attio_list_entry_deleted') {
|
||||
return extractAttioListEntryData(body)
|
||||
}
|
||||
return extractAttioGenericData(body)
|
||||
}
|
||||
|
||||
return body
|
||||
}
|
||||
|
||||
@@ -1438,41 +1395,6 @@ export function validateLinearSignature(secret: string, signature: string, body:
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates an Attio webhook request signature using HMAC SHA-256
|
||||
* @param secret - Attio webhook signing secret (plain text)
|
||||
* @param signature - Attio-Signature header value (hex-encoded HMAC SHA-256 signature)
|
||||
* @param body - Raw request body string
|
||||
* @returns Whether the signature is valid
|
||||
*/
|
||||
export function validateAttioSignature(secret: string, signature: string, body: string): boolean {
|
||||
try {
|
||||
if (!secret || !signature || !body) {
|
||||
logger.warn('Attio signature validation missing required fields', {
|
||||
hasSecret: !!secret,
|
||||
hasSignature: !!signature,
|
||||
hasBody: !!body,
|
||||
})
|
||||
return false
|
||||
}
|
||||
|
||||
const computedHash = crypto.createHmac('sha256', secret).update(body, 'utf8').digest('hex')
|
||||
|
||||
logger.debug('Attio signature comparison', {
|
||||
computedSignature: `${computedHash.substring(0, 10)}...`,
|
||||
providedSignature: `${signature.substring(0, 10)}...`,
|
||||
computedLength: computedHash.length,
|
||||
providedLength: signature.length,
|
||||
match: computedHash === signature,
|
||||
})
|
||||
|
||||
return safeCompare(computedHash, signature)
|
||||
} catch (error) {
|
||||
logger.error('Error validating Attio signature:', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a Circleback webhook request signature using HMAC SHA-256
|
||||
* @param secret - Circleback signing secret (plain text)
|
||||
|
||||
@@ -75,23 +75,6 @@ export function isCanonicalPair(group?: CanonicalGroup): boolean {
|
||||
return Boolean(group?.basicId && group?.advancedIds?.length)
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds default canonical mode overrides for a block's subblocks.
|
||||
* All canonical pairs default to `'basic'`.
|
||||
*/
|
||||
export function buildDefaultCanonicalModes(
|
||||
subBlocks: SubBlockConfig[]
|
||||
): Record<string, 'basic' | 'advanced'> {
|
||||
const index = buildCanonicalIndex(subBlocks)
|
||||
const modes: Record<string, 'basic' | 'advanced'> = {}
|
||||
for (const group of Object.values(index.groupsById)) {
|
||||
if (isCanonicalPair(group)) {
|
||||
modes[group.canonicalId] = 'basic'
|
||||
}
|
||||
}
|
||||
return modes
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine the active mode for a canonical group.
|
||||
*/
|
||||
|
||||
@@ -138,20 +138,14 @@ const ANTHROPIC_SDK_NON_STREAMING_MAX_TOKENS = 21333
|
||||
*/
|
||||
async function createMessage(
|
||||
anthropic: Anthropic,
|
||||
payload: AnthropicPayload,
|
||||
abortSignal?: AbortSignal
|
||||
payload: AnthropicPayload
|
||||
): Promise<Anthropic.Messages.Message> {
|
||||
const options = abortSignal ? { signal: abortSignal } : undefined
|
||||
if (payload.max_tokens > ANTHROPIC_SDK_NON_STREAMING_MAX_TOKENS && !payload.stream) {
|
||||
const stream = anthropic.messages.stream(
|
||||
payload as Anthropic.Messages.MessageStreamParams,
|
||||
options
|
||||
)
|
||||
const stream = anthropic.messages.stream(payload as Anthropic.Messages.MessageStreamParams)
|
||||
return stream.finalMessage()
|
||||
}
|
||||
return anthropic.messages.create(
|
||||
payload as Anthropic.Messages.MessageCreateParamsNonStreaming,
|
||||
options
|
||||
payload as Anthropic.Messages.MessageCreateParamsNonStreaming
|
||||
) as Promise<Anthropic.Messages.Message>
|
||||
}
|
||||
|
||||
@@ -373,13 +367,10 @@ export async function executeAnthropicProviderRequest(
|
||||
const providerStartTime = Date.now()
|
||||
const providerStartTimeISO = new Date(providerStartTime).toISOString()
|
||||
|
||||
const streamResponse = await anthropic.messages.create(
|
||||
{
|
||||
...payload,
|
||||
stream: true,
|
||||
} as Anthropic.Messages.MessageCreateParamsStreaming,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
const streamResponse = await anthropic.messages.create({
|
||||
...payload,
|
||||
stream: true,
|
||||
} as Anthropic.Messages.MessageCreateParamsStreaming)
|
||||
|
||||
const streamingResult = {
|
||||
stream: createReadableStreamFromAnthropicStream(
|
||||
@@ -470,7 +461,7 @@ export async function executeAnthropicProviderRequest(
|
||||
const forcedTools = preparedTools?.forcedTools || []
|
||||
let usedForcedTools: string[] = []
|
||||
|
||||
let currentResponse = await createMessage(anthropic, payload, request.abortSignal)
|
||||
let currentResponse = await createMessage(anthropic, payload)
|
||||
const firstResponseTime = Date.now() - initialCallTime
|
||||
|
||||
let content = ''
|
||||
@@ -717,7 +708,7 @@ export async function executeAnthropicProviderRequest(
|
||||
|
||||
const nextModelStartTime = Date.now()
|
||||
|
||||
currentResponse = await createMessage(anthropic, nextPayload, request.abortSignal)
|
||||
currentResponse = await createMessage(anthropic, nextPayload)
|
||||
|
||||
const nextCheckResult = checkForForcedToolUsage(
|
||||
currentResponse,
|
||||
@@ -767,8 +758,7 @@ export async function executeAnthropicProviderRequest(
|
||||
}
|
||||
|
||||
const streamResponse = await anthropic.messages.create(
|
||||
streamingPayload as Anthropic.Messages.MessageCreateParamsStreaming,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
streamingPayload as Anthropic.Messages.MessageCreateParamsStreaming
|
||||
)
|
||||
|
||||
const streamingResult = {
|
||||
@@ -870,7 +860,7 @@ export async function executeAnthropicProviderRequest(
|
||||
const forcedTools = preparedTools?.forcedTools || []
|
||||
let usedForcedTools: string[] = []
|
||||
|
||||
let currentResponse = await createMessage(anthropic, payload, request.abortSignal)
|
||||
let currentResponse = await createMessage(anthropic, payload)
|
||||
const firstResponseTime = Date.now() - initialCallTime
|
||||
|
||||
let content = ''
|
||||
@@ -1128,7 +1118,7 @@ export async function executeAnthropicProviderRequest(
|
||||
|
||||
const nextModelStartTime = Date.now()
|
||||
|
||||
currentResponse = await createMessage(anthropic, nextPayload, request.abortSignal)
|
||||
currentResponse = await createMessage(anthropic, nextPayload)
|
||||
|
||||
const nextCheckResult = checkForForcedToolUsage(
|
||||
currentResponse,
|
||||
@@ -1192,8 +1182,7 @@ export async function executeAnthropicProviderRequest(
|
||||
}
|
||||
|
||||
const streamResponse = await anthropic.messages.create(
|
||||
streamingPayload as Anthropic.Messages.MessageCreateParamsStreaming,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
streamingPayload as Anthropic.Messages.MessageCreateParamsStreaming
|
||||
)
|
||||
|
||||
const streamingResult = {
|
||||
|
||||
@@ -165,10 +165,7 @@ async function executeChatCompletionsRequest(
|
||||
stream: true,
|
||||
stream_options: { include_usage: true },
|
||||
}
|
||||
const streamResponse = await azureOpenAI.chat.completions.create(
|
||||
streamingParams,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
const streamResponse = await azureOpenAI.chat.completions.create(streamingParams)
|
||||
|
||||
const streamingResult = {
|
||||
stream: createReadableStreamFromAzureOpenAIStream(streamResponse, (content, usage) => {
|
||||
@@ -246,10 +243,7 @@ async function executeChatCompletionsRequest(
|
||||
const forcedTools = preparedTools?.forcedTools || []
|
||||
let usedForcedTools: string[] = []
|
||||
|
||||
let currentResponse = (await azureOpenAI.chat.completions.create(
|
||||
payload,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)) as ChatCompletion
|
||||
let currentResponse = (await azureOpenAI.chat.completions.create(payload)) as ChatCompletion
|
||||
const firstResponseTime = Date.now() - initialCallTime
|
||||
|
||||
let content = currentResponse.choices[0]?.message?.content || ''
|
||||
@@ -427,10 +421,7 @@ async function executeChatCompletionsRequest(
|
||||
}
|
||||
|
||||
const nextModelStartTime = Date.now()
|
||||
currentResponse = (await azureOpenAI.chat.completions.create(
|
||||
nextPayload,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)) as ChatCompletion
|
||||
currentResponse = (await azureOpenAI.chat.completions.create(nextPayload)) as ChatCompletion
|
||||
|
||||
const nextCheckResult = checkForForcedToolUsage(
|
||||
currentResponse,
|
||||
@@ -480,10 +471,7 @@ async function executeChatCompletionsRequest(
|
||||
stream: true,
|
||||
stream_options: { include_usage: true },
|
||||
}
|
||||
const streamResponse = await azureOpenAI.chat.completions.create(
|
||||
streamingParams,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
const streamResponse = await azureOpenAI.chat.completions.create(streamingParams)
|
||||
|
||||
const streamingResult = {
|
||||
stream: createReadableStreamFromAzureOpenAIStream(streamResponse, (content, usage) => {
|
||||
|
||||
@@ -284,10 +284,7 @@ export const bedrockProvider: ProviderConfig = {
|
||||
inferenceConfig,
|
||||
})
|
||||
|
||||
const streamResponse = await client.send(
|
||||
command,
|
||||
request.abortSignal ? { abortSignal: request.abortSignal } : undefined
|
||||
)
|
||||
const streamResponse = await client.send(command)
|
||||
|
||||
if (!streamResponse.stream) {
|
||||
throw new Error('No stream returned from Bedrock')
|
||||
@@ -382,10 +379,7 @@ export const bedrockProvider: ProviderConfig = {
|
||||
toolConfig,
|
||||
})
|
||||
|
||||
let currentResponse = await client.send(
|
||||
command,
|
||||
request.abortSignal ? { abortSignal: request.abortSignal } : undefined
|
||||
)
|
||||
let currentResponse = await client.send(command)
|
||||
const firstResponseTime = Date.now() - initialCallTime
|
||||
|
||||
let content = ''
|
||||
@@ -634,10 +628,7 @@ export const bedrockProvider: ProviderConfig = {
|
||||
: undefined,
|
||||
})
|
||||
|
||||
currentResponse = await client.send(
|
||||
nextCommand,
|
||||
request.abortSignal ? { abortSignal: request.abortSignal } : undefined
|
||||
)
|
||||
currentResponse = await client.send(nextCommand)
|
||||
|
||||
const nextToolUseContentBlocks = (currentResponse.output?.message?.content || []).filter(
|
||||
(block): block is ContentBlock & { toolUse: ToolUseBlock } => 'toolUse' in block
|
||||
@@ -705,10 +696,7 @@ export const bedrockProvider: ProviderConfig = {
|
||||
},
|
||||
})
|
||||
|
||||
const structuredResponse = await client.send(
|
||||
structuredOutputCommand,
|
||||
request.abortSignal ? { abortSignal: request.abortSignal } : undefined
|
||||
)
|
||||
const structuredResponse = await client.send(structuredOutputCommand)
|
||||
const structuredOutputEndTime = Date.now()
|
||||
|
||||
timeSegments.push({
|
||||
@@ -794,10 +782,7 @@ export const bedrockProvider: ProviderConfig = {
|
||||
toolConfig: streamToolConfig,
|
||||
})
|
||||
|
||||
const streamResponse = await client.send(
|
||||
streamCommand,
|
||||
request.abortSignal ? { abortSignal: request.abortSignal } : undefined
|
||||
)
|
||||
const streamResponse = await client.send(streamCommand)
|
||||
|
||||
if (!streamResponse.stream) {
|
||||
throw new Error('No stream returned from Bedrock')
|
||||
|
||||
@@ -117,13 +117,10 @@ export const cerebrasProvider: ProviderConfig = {
|
||||
if (request.stream && (!tools || tools.length === 0)) {
|
||||
logger.info('Using streaming response for Cerebras request (no tools)')
|
||||
|
||||
const streamResponse: any = await client.chat.completions.create(
|
||||
{
|
||||
...payload,
|
||||
stream: true,
|
||||
},
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
const streamResponse: any = await client.chat.completions.create({
|
||||
...payload,
|
||||
stream: true,
|
||||
})
|
||||
|
||||
const streamingResult = {
|
||||
stream: createReadableStreamFromCerebrasStream(streamResponse, (content, usage) => {
|
||||
@@ -182,10 +179,7 @@ export const cerebrasProvider: ProviderConfig = {
|
||||
}
|
||||
const initialCallTime = Date.now()
|
||||
|
||||
let currentResponse = (await client.chat.completions.create(
|
||||
payload,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)) as CerebrasResponse
|
||||
let currentResponse = (await client.chat.completions.create(payload)) as CerebrasResponse
|
||||
const firstResponseTime = Date.now() - initialCallTime
|
||||
|
||||
let content = currentResponse.choices[0]?.message?.content || ''
|
||||
@@ -371,8 +365,7 @@ export const cerebrasProvider: ProviderConfig = {
|
||||
finalPayload.tool_choice = 'none'
|
||||
|
||||
const finalResponse = (await client.chat.completions.create(
|
||||
finalPayload,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
finalPayload
|
||||
)) as CerebrasResponse
|
||||
|
||||
const nextModelEndTime = Date.now()
|
||||
@@ -408,8 +401,7 @@ export const cerebrasProvider: ProviderConfig = {
|
||||
|
||||
const nextModelStartTime = Date.now()
|
||||
currentResponse = (await client.chat.completions.create(
|
||||
nextPayload,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
nextPayload
|
||||
)) as CerebrasResponse
|
||||
|
||||
const nextModelEndTime = Date.now()
|
||||
@@ -451,10 +443,7 @@ export const cerebrasProvider: ProviderConfig = {
|
||||
stream: true,
|
||||
}
|
||||
|
||||
const streamResponse: any = await client.chat.completions.create(
|
||||
streamingPayload,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
const streamResponse: any = await client.chat.completions.create(streamingPayload)
|
||||
|
||||
const accumulatedCost = calculateCost(request.model, tokens.input, tokens.output)
|
||||
|
||||
|
||||
@@ -114,13 +114,10 @@ export const deepseekProvider: ProviderConfig = {
|
||||
if (request.stream && (!tools || tools.length === 0)) {
|
||||
logger.info('Using streaming response for DeepSeek request (no tools)')
|
||||
|
||||
const streamResponse = await deepseek.chat.completions.create(
|
||||
{
|
||||
...payload,
|
||||
stream: true,
|
||||
},
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
const streamResponse = await deepseek.chat.completions.create({
|
||||
...payload,
|
||||
stream: true,
|
||||
})
|
||||
|
||||
const streamingResult = {
|
||||
stream: createReadableStreamFromDeepseekStream(
|
||||
@@ -186,10 +183,7 @@ export const deepseekProvider: ProviderConfig = {
|
||||
const forcedTools = preparedTools?.forcedTools || []
|
||||
let usedForcedTools: string[] = []
|
||||
|
||||
let currentResponse = await deepseek.chat.completions.create(
|
||||
payload,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
let currentResponse = await deepseek.chat.completions.create(payload)
|
||||
const firstResponseTime = Date.now() - initialCallTime
|
||||
|
||||
let content = currentResponse.choices[0]?.message?.content || ''
|
||||
@@ -381,10 +375,7 @@ export const deepseekProvider: ProviderConfig = {
|
||||
}
|
||||
|
||||
const nextModelStartTime = Date.now()
|
||||
currentResponse = await deepseek.chat.completions.create(
|
||||
nextPayload,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
currentResponse = await deepseek.chat.completions.create(nextPayload)
|
||||
|
||||
if (
|
||||
typeof nextPayload.tool_choice === 'object' &&
|
||||
@@ -448,10 +439,7 @@ export const deepseekProvider: ProviderConfig = {
|
||||
stream: true,
|
||||
}
|
||||
|
||||
const streamResponse = await deepseek.chat.completions.create(
|
||||
streamingPayload,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
const streamResponse = await deepseek.chat.completions.create(streamingPayload)
|
||||
|
||||
const accumulatedCost = calculateCost(request.model, tokens.input, tokens.output)
|
||||
|
||||
|
||||
@@ -387,25 +387,10 @@ const DEEP_RESEARCH_POLL_INTERVAL_MS = 10_000
|
||||
const DEEP_RESEARCH_MAX_DURATION_MS = 60 * 60 * 1000
|
||||
|
||||
/**
|
||||
* Sleeps for the specified number of milliseconds, respecting an optional abort signal.
|
||||
* Sleeps for the specified number of milliseconds
|
||||
*/
|
||||
function sleep(ms: number, signal?: AbortSignal): Promise<void> {
|
||||
if (signal?.aborted) {
|
||||
return Promise.reject(
|
||||
signal.reason ?? new DOMException('The operation was aborted.', 'AbortError')
|
||||
)
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
const onAbort = () => {
|
||||
clearTimeout(timer)
|
||||
reject(signal!.reason ?? new DOMException('The operation was aborted.', 'AbortError'))
|
||||
}
|
||||
const timer = setTimeout(() => {
|
||||
signal?.removeEventListener('abort', onAbort)
|
||||
resolve()
|
||||
}, ms)
|
||||
signal?.addEventListener('abort', onAbort, { once: true })
|
||||
})
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -695,10 +680,7 @@ export async function executeDeepResearchRequest(
|
||||
stream: true,
|
||||
}
|
||||
|
||||
const streamResponse = await ai.interactions.create(
|
||||
streamParams,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
const streamResponse = await ai.interactions.create(streamParams)
|
||||
const firstResponseTime = Date.now() - providerStartTime
|
||||
|
||||
const streamingResult: StreamingExecution = {
|
||||
@@ -783,10 +765,7 @@ export async function executeDeepResearchRequest(
|
||||
stream: false,
|
||||
}
|
||||
|
||||
const interaction = await ai.interactions.create(
|
||||
createParams,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
const interaction = await ai.interactions.create(createParams)
|
||||
const interactionId = interaction.id
|
||||
|
||||
logger.info('Deep research interaction created', { interactionId, status: interaction.status })
|
||||
@@ -814,12 +793,8 @@ export async function executeDeepResearchRequest(
|
||||
elapsedMs: Date.now() - pollStartTime,
|
||||
})
|
||||
|
||||
await sleep(DEEP_RESEARCH_POLL_INTERVAL_MS, request.abortSignal)
|
||||
result = await ai.interactions.get(
|
||||
interactionId,
|
||||
undefined,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
await sleep(DEEP_RESEARCH_POLL_INTERVAL_MS)
|
||||
result = await ai.interactions.get(interactionId)
|
||||
}
|
||||
|
||||
if (result.status !== 'completed') {
|
||||
@@ -907,9 +882,6 @@ export async function executeGeminiRequest(
|
||||
// Build configuration
|
||||
const geminiConfig: GenerateContentConfig = {}
|
||||
|
||||
if (request.abortSignal) {
|
||||
geminiConfig.abortSignal = request.abortSignal
|
||||
}
|
||||
if (request.temperature !== undefined) {
|
||||
geminiConfig.temperature = request.temperature
|
||||
}
|
||||
|
||||
@@ -118,13 +118,10 @@ export const groqProvider: ProviderConfig = {
|
||||
const providerStartTime = Date.now()
|
||||
const providerStartTimeISO = new Date(providerStartTime).toISOString()
|
||||
|
||||
const streamResponse = await groq.chat.completions.create(
|
||||
{
|
||||
...payload,
|
||||
stream: true,
|
||||
},
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
const streamResponse = await groq.chat.completions.create({
|
||||
...payload,
|
||||
stream: true,
|
||||
})
|
||||
|
||||
const streamingResult = {
|
||||
stream: createReadableStreamFromGroqStream(streamResponse as any, (content, usage) => {
|
||||
@@ -188,10 +185,7 @@ export const groqProvider: ProviderConfig = {
|
||||
try {
|
||||
const initialCallTime = Date.now()
|
||||
|
||||
let currentResponse = await groq.chat.completions.create(
|
||||
payload,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
let currentResponse = await groq.chat.completions.create(payload)
|
||||
const firstResponseTime = Date.now() - initialCallTime
|
||||
|
||||
let content = currentResponse.choices[0]?.message?.content || ''
|
||||
@@ -361,10 +355,7 @@ export const groqProvider: ProviderConfig = {
|
||||
}
|
||||
|
||||
const nextModelStartTime = Date.now()
|
||||
currentResponse = await groq.chat.completions.create(
|
||||
nextPayload,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
currentResponse = await groq.chat.completions.create(nextPayload)
|
||||
|
||||
const nextModelEndTime = Date.now()
|
||||
const thisModelTime = nextModelEndTime - nextModelStartTime
|
||||
@@ -405,10 +396,7 @@ export const groqProvider: ProviderConfig = {
|
||||
stream: true,
|
||||
}
|
||||
|
||||
const streamResponse = await groq.chat.completions.create(
|
||||
streamingPayload,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
const streamResponse = await groq.chat.completions.create(streamingPayload)
|
||||
|
||||
const accumulatedCost = calculateCost(request.model, tokens.input, tokens.output)
|
||||
|
||||
|
||||
@@ -143,10 +143,7 @@ export const mistralProvider: ProviderConfig = {
|
||||
...payload,
|
||||
stream: true,
|
||||
}
|
||||
const streamResponse = await mistral.chat.completions.create(
|
||||
streamingParams,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
const streamResponse = await mistral.chat.completions.create(streamingParams)
|
||||
|
||||
const streamingResult = {
|
||||
stream: createReadableStreamFromMistralStream(streamResponse, (content, usage) => {
|
||||
@@ -245,10 +242,7 @@ export const mistralProvider: ProviderConfig = {
|
||||
}
|
||||
}
|
||||
|
||||
let currentResponse = await mistral.chat.completions.create(
|
||||
payload,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
let currentResponse = await mistral.chat.completions.create(payload)
|
||||
const firstResponseTime = Date.now() - initialCallTime
|
||||
|
||||
let content = currentResponse.choices[0]?.message?.content || ''
|
||||
@@ -419,10 +413,7 @@ export const mistralProvider: ProviderConfig = {
|
||||
|
||||
const nextModelStartTime = Date.now()
|
||||
|
||||
currentResponse = await mistral.chat.completions.create(
|
||||
nextPayload,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
currentResponse = await mistral.chat.completions.create(nextPayload)
|
||||
|
||||
checkForForcedToolUsage(currentResponse, nextPayload.tool_choice)
|
||||
|
||||
@@ -463,10 +454,7 @@ export const mistralProvider: ProviderConfig = {
|
||||
tool_choice: 'auto',
|
||||
stream: true,
|
||||
}
|
||||
const streamResponse = await mistral.chat.completions.create(
|
||||
streamingParams,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
const streamResponse = await mistral.chat.completions.create(streamingParams)
|
||||
|
||||
const streamingResult = {
|
||||
stream: createReadableStreamFromMistralStream(streamResponse, (content, usage) => {
|
||||
|
||||
@@ -166,10 +166,7 @@ export const ollamaProvider: ProviderConfig = {
|
||||
stream: true,
|
||||
stream_options: { include_usage: true },
|
||||
}
|
||||
const streamResponse = await ollama.chat.completions.create(
|
||||
streamingParams,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
const streamResponse = await ollama.chat.completions.create(streamingParams)
|
||||
|
||||
const streamingResult = {
|
||||
stream: createReadableStreamFromOllamaStream(streamResponse, (content, usage) => {
|
||||
@@ -251,10 +248,7 @@ export const ollamaProvider: ProviderConfig = {
|
||||
|
||||
const initialCallTime = Date.now()
|
||||
|
||||
let currentResponse = await ollama.chat.completions.create(
|
||||
payload,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
let currentResponse = await ollama.chat.completions.create(payload)
|
||||
const firstResponseTime = Date.now() - initialCallTime
|
||||
|
||||
let content = currentResponse.choices[0]?.message?.content || ''
|
||||
@@ -414,10 +408,7 @@ export const ollamaProvider: ProviderConfig = {
|
||||
|
||||
const nextModelStartTime = Date.now()
|
||||
|
||||
currentResponse = await ollama.chat.completions.create(
|
||||
nextPayload,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
currentResponse = await ollama.chat.completions.create(nextPayload)
|
||||
|
||||
const nextModelEndTime = Date.now()
|
||||
const thisModelTime = nextModelEndTime - nextModelStartTime
|
||||
@@ -459,10 +450,7 @@ export const ollamaProvider: ProviderConfig = {
|
||||
stream: true,
|
||||
stream_options: { include_usage: true },
|
||||
}
|
||||
const streamResponse = await ollama.chat.completions.create(
|
||||
streamingParams,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
const streamResponse = await ollama.chat.completions.create(streamingParams)
|
||||
|
||||
const streamingResult = {
|
||||
stream: createReadableStreamFromOllamaStream(streamResponse, (content, usage) => {
|
||||
|
||||
@@ -265,7 +265,6 @@ export async function executeResponsesProviderRequest(
|
||||
method: 'POST',
|
||||
headers: config.headers,
|
||||
body: JSON.stringify(body),
|
||||
signal: request.abortSignal,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
@@ -287,7 +286,6 @@ export async function executeResponsesProviderRequest(
|
||||
method: 'POST',
|
||||
headers: config.headers,
|
||||
body: JSON.stringify(createRequestBody(initialInput, { stream: true })),
|
||||
signal: request.abortSignal,
|
||||
})
|
||||
|
||||
if (!streamResponse.ok) {
|
||||
@@ -706,7 +704,6 @@ export async function executeResponsesProviderRequest(
|
||||
method: 'POST',
|
||||
headers: config.headers,
|
||||
body: JSON.stringify(createRequestBody(currentInput, streamOverrides)),
|
||||
signal: request.abortSignal,
|
||||
})
|
||||
|
||||
if (!streamResponse.ok) {
|
||||
|
||||
@@ -157,10 +157,7 @@ export const openRouterProvider: ProviderConfig = {
|
||||
stream: true,
|
||||
stream_options: { include_usage: true },
|
||||
}
|
||||
const streamResponse = await client.chat.completions.create(
|
||||
streamingParams,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
const streamResponse = await client.chat.completions.create(streamingParams)
|
||||
|
||||
const streamingResult = {
|
||||
stream: createReadableStreamFromOpenAIStream(streamResponse, (content, usage) => {
|
||||
@@ -234,10 +231,7 @@ export const openRouterProvider: ProviderConfig = {
|
||||
const forcedTools = preparedTools?.forcedTools || []
|
||||
let usedForcedTools: string[] = []
|
||||
|
||||
let currentResponse = await client.chat.completions.create(
|
||||
payload,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
let currentResponse = await client.chat.completions.create(payload)
|
||||
const firstResponseTime = Date.now() - initialCallTime
|
||||
|
||||
let content = currentResponse.choices[0]?.message?.content || ''
|
||||
@@ -406,10 +400,7 @@ export const openRouterProvider: ProviderConfig = {
|
||||
}
|
||||
|
||||
const nextModelStartTime = Date.now()
|
||||
currentResponse = await client.chat.completions.create(
|
||||
nextPayload,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
currentResponse = await client.chat.completions.create(nextPayload)
|
||||
const nextForcedToolResult = checkForForcedToolUsage(
|
||||
currentResponse,
|
||||
nextPayload.tool_choice,
|
||||
@@ -459,10 +450,7 @@ export const openRouterProvider: ProviderConfig = {
|
||||
)
|
||||
}
|
||||
|
||||
const streamResponse = await client.chat.completions.create(
|
||||
streamingParams,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
const streamResponse = await client.chat.completions.create(streamingParams)
|
||||
|
||||
const streamingResult = {
|
||||
stream: createReadableStreamFromOpenAIStream(streamResponse, (content, usage) => {
|
||||
@@ -545,10 +533,7 @@ export const openRouterProvider: ProviderConfig = {
|
||||
)
|
||||
|
||||
const finalStartTime = Date.now()
|
||||
const finalResponse = await client.chat.completions.create(
|
||||
finalPayload,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
const finalResponse = await client.chat.completions.create(finalPayload)
|
||||
const finalEndTime = Date.now()
|
||||
const finalDuration = finalEndTime - finalStartTime
|
||||
|
||||
|
||||
@@ -176,7 +176,6 @@ export interface ProviderRequest {
|
||||
isDeployedContext?: boolean
|
||||
/** Previous interaction ID for multi-turn Interactions API requests (deep research follow-ups) */
|
||||
previousInteractionId?: string
|
||||
abortSignal?: AbortSignal
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -189,10 +189,7 @@ export const vllmProvider: ProviderConfig = {
|
||||
stream: true,
|
||||
stream_options: { include_usage: true },
|
||||
}
|
||||
const streamResponse = await vllm.chat.completions.create(
|
||||
streamingParams,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
const streamResponse = await vllm.chat.completions.create(streamingParams)
|
||||
|
||||
const streamingResult = {
|
||||
stream: createReadableStreamFromVLLMStream(streamResponse, (content, usage) => {
|
||||
@@ -296,10 +293,7 @@ export const vllmProvider: ProviderConfig = {
|
||||
}
|
||||
}
|
||||
|
||||
let currentResponse = await vllm.chat.completions.create(
|
||||
payload,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
let currentResponse = await vllm.chat.completions.create(payload)
|
||||
const firstResponseTime = Date.now() - initialCallTime
|
||||
|
||||
let content = currentResponse.choices[0]?.message?.content || ''
|
||||
@@ -480,10 +474,7 @@ export const vllmProvider: ProviderConfig = {
|
||||
|
||||
const nextModelStartTime = Date.now()
|
||||
|
||||
currentResponse = await vllm.chat.completions.create(
|
||||
nextPayload,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
currentResponse = await vllm.chat.completions.create(nextPayload)
|
||||
|
||||
checkForForcedToolUsage(currentResponse, nextPayload.tool_choice)
|
||||
|
||||
@@ -528,10 +519,7 @@ export const vllmProvider: ProviderConfig = {
|
||||
stream: true,
|
||||
stream_options: { include_usage: true },
|
||||
}
|
||||
const streamResponse = await vllm.chat.completions.create(
|
||||
streamingParams,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
const streamResponse = await vllm.chat.completions.create(streamingParams)
|
||||
|
||||
const streamingResult = {
|
||||
stream: createReadableStreamFromVLLMStream(streamResponse, (content, usage) => {
|
||||
|
||||
@@ -115,10 +115,7 @@ export const xAIProvider: ProviderConfig = {
|
||||
}
|
||||
: { ...basePayload, stream: true, stream_options: { include_usage: true } }
|
||||
|
||||
const streamResponse = await xai.chat.completions.create(
|
||||
streamingParams,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
const streamResponse = await xai.chat.completions.create(streamingParams)
|
||||
|
||||
const streamingResult = {
|
||||
stream: createReadableStreamFromXAIStream(streamResponse, (content, usage) => {
|
||||
@@ -202,10 +199,7 @@ export const xAIProvider: ProviderConfig = {
|
||||
Object.assign(initialPayload, responseFormatPayload)
|
||||
}
|
||||
|
||||
let currentResponse = await xai.chat.completions.create(
|
||||
initialPayload,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
let currentResponse = await xai.chat.completions.create(initialPayload)
|
||||
const firstResponseTime = Date.now() - initialCallTime
|
||||
|
||||
let content = currentResponse.choices[0]?.message?.content || ''
|
||||
@@ -420,10 +414,7 @@ export const xAIProvider: ProviderConfig = {
|
||||
|
||||
const nextModelStartTime = Date.now()
|
||||
|
||||
currentResponse = await xai.chat.completions.create(
|
||||
nextPayload,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
currentResponse = await xai.chat.completions.create(nextPayload)
|
||||
if (nextPayload.tool_choice && typeof nextPayload.tool_choice === 'object') {
|
||||
const result = checkForForcedToolUsage(
|
||||
currentResponse,
|
||||
@@ -488,10 +479,7 @@ export const xAIProvider: ProviderConfig = {
|
||||
}
|
||||
}
|
||||
|
||||
const streamResponse = await xai.chat.completions.create(
|
||||
finalStreamingPayload as any,
|
||||
request.abortSignal ? { signal: request.abortSignal } : undefined
|
||||
)
|
||||
const streamResponse = await xai.chat.completions.create(finalStreamingPayload as any)
|
||||
|
||||
const accumulatedCost = calculateCost(request.model, tokens.input, tokens.output)
|
||||
|
||||
|
||||
@@ -683,37 +683,34 @@ describe('Serializer', () => {
|
||||
expect(slackBlock?.config.params.username).toBe('bot')
|
||||
})
|
||||
|
||||
it.concurrent(
|
||||
'should fall back to legacy advancedMode for non-credential canonical groups when canonicalModes not set',
|
||||
() => {
|
||||
const serializer = new Serializer()
|
||||
it.concurrent('should fall back to legacy advancedMode when canonicalModes not set', () => {
|
||||
const serializer = new Serializer()
|
||||
|
||||
const block: any = {
|
||||
id: 'slack-1',
|
||||
type: 'slack',
|
||||
name: 'Test Slack Block',
|
||||
position: { x: 0, y: 0 },
|
||||
advancedMode: true,
|
||||
subBlocks: {
|
||||
operation: { value: 'send' },
|
||||
destinationType: { value: 'channel' },
|
||||
channel: { value: 'general' },
|
||||
manualChannel: { value: 'C1234567890' },
|
||||
text: { value: 'Hello world' },
|
||||
username: { value: 'bot' },
|
||||
},
|
||||
outputs: {},
|
||||
enabled: true,
|
||||
}
|
||||
|
||||
const serialized = serializer.serializeWorkflow({ 'slack-1': block }, [], {})
|
||||
const slackBlock = serialized.blocks.find((b) => b.id === 'slack-1')
|
||||
|
||||
expect(slackBlock).toBeDefined()
|
||||
expect(slackBlock?.config.params.channel).toBe('C1234567890')
|
||||
expect(slackBlock?.config.params.manualChannel).toBeUndefined()
|
||||
const block: any = {
|
||||
id: 'slack-1',
|
||||
type: 'slack',
|
||||
name: 'Test Slack Block',
|
||||
position: { x: 0, y: 0 },
|
||||
advancedMode: true,
|
||||
subBlocks: {
|
||||
operation: { value: 'send' },
|
||||
destinationType: { value: 'channel' },
|
||||
channel: { value: 'general' },
|
||||
manualChannel: { value: 'C1234567890' },
|
||||
text: { value: 'Hello world' },
|
||||
username: { value: 'bot' },
|
||||
},
|
||||
outputs: {},
|
||||
enabled: true,
|
||||
}
|
||||
)
|
||||
|
||||
const serialized = serializer.serializeWorkflow({ 'slack-1': block }, [], {})
|
||||
const slackBlock = serialized.blocks.find((b) => b.id === 'slack-1')
|
||||
|
||||
expect(slackBlock).toBeDefined()
|
||||
expect(slackBlock?.config.params.channel).toBe('C1234567890')
|
||||
expect(slackBlock?.config.params.manualChannel).toBeUndefined()
|
||||
})
|
||||
|
||||
it.concurrent('should use basic value by default when no mode specified', () => {
|
||||
const serializer = new Serializer()
|
||||
|
||||
@@ -61,9 +61,8 @@ function shouldSerializeSubBlock(
|
||||
const group = canonicalId ? canonicalIndex.groupsById[canonicalId] : undefined
|
||||
if (group && isCanonicalPair(group)) {
|
||||
const mode =
|
||||
canonicalModeOverrides?.[group.canonicalId] != null || !displayAdvancedOptions
|
||||
? resolveCanonicalMode(group, values, canonicalModeOverrides)
|
||||
: 'advanced'
|
||||
canonicalModeOverrides?.[group.canonicalId] ??
|
||||
(displayAdvancedOptions ? 'advanced' : resolveCanonicalMode(group, values))
|
||||
const matchesMode =
|
||||
mode === 'advanced'
|
||||
? group.advancedIds.includes(subBlockConfig.id)
|
||||
@@ -375,11 +374,8 @@ export class Serializer {
|
||||
|
||||
Object.values(canonicalIndex.groupsById).forEach((group) => {
|
||||
const { basicValue, advancedValue } = getCanonicalValues(group, params)
|
||||
const hasExplicitOverride = canonicalModeOverrides?.[group.canonicalId] != null
|
||||
const pairMode =
|
||||
hasExplicitOverride || !legacyAdvancedMode
|
||||
? resolveCanonicalMode(group, allValues, canonicalModeOverrides)
|
||||
: 'advanced'
|
||||
canonicalModeOverrides?.[group.canonicalId] ?? (legacyAdvancedMode ? 'advanced' : 'basic')
|
||||
const chosen = pairMode === 'advanced' ? advancedValue : basicValue
|
||||
|
||||
const sourceIds = [group.basicId, ...group.advancedIds].filter(Boolean) as string[]
|
||||
|
||||
@@ -7,8 +7,6 @@ export const useSettingsModalStore = create<SettingsModalState>((set) => ({
|
||||
isOpen: false,
|
||||
initialSection: null,
|
||||
mcpServerId: null,
|
||||
hasUnsavedChanges: false,
|
||||
onCloseAttempt: null,
|
||||
|
||||
openModal: (options) =>
|
||||
set({
|
||||
@@ -20,8 +18,6 @@ export const useSettingsModalStore = create<SettingsModalState>((set) => ({
|
||||
closeModal: () =>
|
||||
set({
|
||||
isOpen: false,
|
||||
hasUnsavedChanges: false,
|
||||
onCloseAttempt: null,
|
||||
}),
|
||||
|
||||
clearInitialState: () =>
|
||||
@@ -29,14 +25,4 @@ export const useSettingsModalStore = create<SettingsModalState>((set) => ({
|
||||
initialSection: null,
|
||||
mcpServerId: null,
|
||||
}),
|
||||
|
||||
setHasUnsavedChanges: (hasChanges) =>
|
||||
set({
|
||||
hasUnsavedChanges: hasChanges,
|
||||
}),
|
||||
|
||||
setOnCloseAttempt: (callback) =>
|
||||
set({
|
||||
onCloseAttempt: callback,
|
||||
}),
|
||||
}))
|
||||
|
||||
@@ -16,12 +16,8 @@ export interface SettingsModalState {
|
||||
isOpen: boolean
|
||||
initialSection: SettingsSection | null
|
||||
mcpServerId: string | null
|
||||
hasUnsavedChanges: boolean
|
||||
onCloseAttempt: (() => void) | null
|
||||
|
||||
openModal: (options?: { section?: SettingsSection; mcpServerId?: string }) => void
|
||||
closeModal: () => void
|
||||
clearInitialState: () => void
|
||||
setHasUnsavedChanges: (hasChanges: boolean) => void
|
||||
setOnCloseAttempt: (callback: (() => void) | null) => void
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ import { v4 as uuidv4 } from 'uuid'
|
||||
import { DEFAULT_DUPLICATE_OFFSET } from '@/lib/workflows/autolayout/constants'
|
||||
import { getEffectiveBlockOutputs } from '@/lib/workflows/blocks/block-outputs'
|
||||
import { mergeSubblockStateWithValues } from '@/lib/workflows/subblocks'
|
||||
import { buildDefaultCanonicalModes } from '@/lib/workflows/subblocks/visibility'
|
||||
import { hasTriggerCapability } from '@/lib/workflows/triggers/trigger-utils'
|
||||
import { TriggerUtils } from '@/lib/workflows/triggers/triggers'
|
||||
import { getBlock } from '@/blocks'
|
||||
@@ -197,13 +196,6 @@ export function prepareBlockState(options: PrepareBlockStateOptions): BlockState
|
||||
preferToolOutputs: !effectiveTriggerMode,
|
||||
})
|
||||
|
||||
if (blockConfig.subBlocks) {
|
||||
const canonicalModes = buildDefaultCanonicalModes(blockConfig.subBlocks)
|
||||
if (Object.keys(canonicalModes).length > 0) {
|
||||
blockData.canonicalModes = canonicalModes
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id,
|
||||
type,
|
||||
|
||||
@@ -65,19 +65,12 @@ export const attioCreateListTool: ToolConfig<AttioCreateListParams, AttioCreateL
|
||||
'Content-Type': 'application/json',
|
||||
}),
|
||||
body: (params) => {
|
||||
const apiSlug =
|
||||
params.apiSlug ||
|
||||
params.name
|
||||
?.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '_')
|
||||
.replace(/^_|_$/g, '')
|
||||
const data: Record<string, unknown> = {
|
||||
name: params.name,
|
||||
api_slug: apiSlug,
|
||||
parent_object: params.parentObject,
|
||||
workspace_access: params.workspaceAccess ?? null,
|
||||
workspace_member_access: [] as unknown[],
|
||||
}
|
||||
if (params.apiSlug) data.api_slug = params.apiSlug
|
||||
if (params.workspaceAccess) data.workspace_access = params.workspaceAccess
|
||||
if (params.workspaceMemberAccess) {
|
||||
try {
|
||||
data.workspace_member_access =
|
||||
|
||||
@@ -60,22 +60,20 @@ export const attioCreateListEntryTool: ToolConfig<
|
||||
'Content-Type': 'application/json',
|
||||
}),
|
||||
body: (params) => {
|
||||
let entryValues: unknown = {}
|
||||
const data: Record<string, unknown> = {
|
||||
parent_record_id: params.parentRecordId,
|
||||
parent_object: params.parentObject,
|
||||
}
|
||||
if (params.entryValues) {
|
||||
try {
|
||||
entryValues =
|
||||
data.entry_values =
|
||||
typeof params.entryValues === 'string'
|
||||
? JSON.parse(params.entryValues)
|
||||
: params.entryValues
|
||||
} catch {
|
||||
entryValues = {}
|
||||
data.entry_values = {}
|
||||
}
|
||||
}
|
||||
const data: Record<string, unknown> = {
|
||||
parent_record_id: params.parentRecordId,
|
||||
parent_object: params.parentObject,
|
||||
entry_values: entryValues,
|
||||
}
|
||||
return { data }
|
||||
},
|
||||
},
|
||||
|
||||
@@ -83,7 +83,7 @@ export const attioCreateNoteTool: ToolConfig<AttioCreateNoteParams, AttioCreateN
|
||||
content: params.content,
|
||||
}
|
||||
if (params.createdAt) body.created_at = params.createdAt
|
||||
if (params.meetingId != null) body.meeting_id = params.meetingId || null
|
||||
if (params.meetingId !== undefined) body.meeting_id = params.meetingId || null
|
||||
return { data: body }
|
||||
},
|
||||
},
|
||||
|
||||
@@ -54,8 +54,8 @@ export const attioListNotesTool: ToolConfig<AttioListNotesParams, AttioListNotes
|
||||
const searchParams = new URLSearchParams()
|
||||
if (params.parentObject) searchParams.set('parent_object', params.parentObject)
|
||||
if (params.parentRecordId) searchParams.set('parent_record_id', params.parentRecordId)
|
||||
if (params.limit != null) searchParams.set('limit', String(params.limit))
|
||||
if (params.offset != null) searchParams.set('offset', String(params.offset))
|
||||
if (params.limit !== undefined) searchParams.set('limit', String(params.limit))
|
||||
if (params.offset !== undefined) searchParams.set('offset', String(params.offset))
|
||||
const qs = searchParams.toString()
|
||||
return `https://api.attio.com/v2/notes${qs ? `?${qs}` : ''}`
|
||||
},
|
||||
|
||||
@@ -78,8 +78,8 @@ export const attioListRecordsTool: ToolConfig<AttioListRecordsParams, AttioListR
|
||||
body.sorts = params.sorts
|
||||
}
|
||||
}
|
||||
if (params.limit != null) body.limit = params.limit
|
||||
if (params.offset != null) body.offset = params.offset
|
||||
if (params.limit !== undefined) body.limit = params.limit
|
||||
if (params.offset !== undefined) body.offset = params.offset
|
||||
return body
|
||||
},
|
||||
},
|
||||
|
||||
@@ -73,12 +73,12 @@ export const attioListTasksTool: ToolConfig<AttioListTasksParams, AttioListTasks
|
||||
if (params.linkedObject) searchParams.set('linked_object', params.linkedObject)
|
||||
if (params.linkedRecordId) searchParams.set('linked_record_id', params.linkedRecordId)
|
||||
if (params.assignee) searchParams.set('assignee', params.assignee)
|
||||
if (params.isCompleted != null) {
|
||||
if (params.isCompleted !== undefined) {
|
||||
searchParams.set('is_completed', String(params.isCompleted))
|
||||
}
|
||||
if (params.sort) searchParams.set('sort', params.sort)
|
||||
if (params.limit != null) searchParams.set('limit', String(params.limit))
|
||||
if (params.offset != null) searchParams.set('offset', String(params.offset))
|
||||
if (params.limit !== undefined) searchParams.set('limit', String(params.limit))
|
||||
if (params.offset !== undefined) searchParams.set('offset', String(params.offset))
|
||||
const qs = searchParams.toString()
|
||||
return `https://api.attio.com/v2/tasks${qs ? `?${qs}` : ''}`
|
||||
},
|
||||
|
||||
@@ -67,8 +67,8 @@ export const attioListThreadsTool: ToolConfig<AttioListThreadsParams, AttioListT
|
||||
if (params.object) searchParams.set('object', params.object)
|
||||
if (params.entryId) searchParams.set('entry_id', params.entryId)
|
||||
if (params.list) searchParams.set('list', params.list)
|
||||
if (params.limit != null) searchParams.set('limit', String(params.limit))
|
||||
if (params.offset != null) searchParams.set('offset', String(params.offset))
|
||||
if (params.limit !== undefined) searchParams.set('limit', String(params.limit))
|
||||
if (params.offset !== undefined) searchParams.set('offset', String(params.offset))
|
||||
const qs = searchParams.toString()
|
||||
return `https://api.attio.com/v2/threads${qs ? `?${qs}` : ''}`
|
||||
},
|
||||
|
||||
@@ -41,8 +41,8 @@ export const attioListWebhooksTool: ToolConfig<AttioListWebhooksParams, AttioLis
|
||||
request: {
|
||||
url: (params) => {
|
||||
const searchParams = new URLSearchParams()
|
||||
if (params.limit != null) searchParams.set('limit', String(params.limit))
|
||||
if (params.offset != null) searchParams.set('offset', String(params.offset))
|
||||
if (params.limit !== undefined) searchParams.set('limit', String(params.limit))
|
||||
if (params.offset !== undefined) searchParams.set('offset', String(params.offset))
|
||||
const qs = searchParams.toString()
|
||||
return `https://api.attio.com/v2/webhooks${qs ? `?${qs}` : ''}`
|
||||
},
|
||||
|
||||
@@ -83,8 +83,8 @@ export const attioQueryListEntriesTool: ToolConfig<
|
||||
body.sorts = []
|
||||
}
|
||||
}
|
||||
if (params.limit != null) body.limit = params.limit
|
||||
if (params.offset != null) body.offset = params.offset
|
||||
if (params.limit !== undefined) body.limit = params.limit
|
||||
if (params.offset !== undefined) body.offset = params.offset
|
||||
return body
|
||||
},
|
||||
},
|
||||
|
||||
@@ -66,10 +66,10 @@ export const attioUpdateListTool: ToolConfig<AttioUpdateListParams, AttioUpdateL
|
||||
}),
|
||||
body: (params) => {
|
||||
const data: Record<string, unknown> = {}
|
||||
if (params.name != null) data.name = params.name
|
||||
if (params.apiSlug != null) data.api_slug = params.apiSlug
|
||||
if (params.workspaceAccess != null) data.workspace_access = params.workspaceAccess
|
||||
if (params.workspaceMemberAccess != null) {
|
||||
if (params.name !== undefined) data.name = params.name
|
||||
if (params.apiSlug !== undefined) data.api_slug = params.apiSlug
|
||||
if (params.workspaceAccess !== undefined) data.workspace_access = params.workspaceAccess
|
||||
if (params.workspaceMemberAccess !== undefined) {
|
||||
try {
|
||||
data.workspace_member_access =
|
||||
typeof params.workspaceMemberAccess === 'string'
|
||||
|
||||
@@ -59,9 +59,9 @@ export const attioUpdateObjectTool: ToolConfig<AttioUpdateObjectParams, AttioUpd
|
||||
}),
|
||||
body: (params) => {
|
||||
const data: Record<string, unknown> = {}
|
||||
if (params.apiSlug != null) data.api_slug = params.apiSlug
|
||||
if (params.singularNoun != null) data.singular_noun = params.singularNoun
|
||||
if (params.pluralNoun != null) data.plural_noun = params.pluralNoun
|
||||
if (params.apiSlug !== undefined) data.api_slug = params.apiSlug
|
||||
if (params.singularNoun !== undefined) data.singular_noun = params.singularNoun
|
||||
if (params.pluralNoun !== undefined) data.plural_noun = params.pluralNoun
|
||||
return { data }
|
||||
},
|
||||
},
|
||||
|
||||
@@ -64,8 +64,8 @@ export const attioUpdateTaskTool: ToolConfig<AttioUpdateTaskParams, AttioUpdateT
|
||||
}),
|
||||
body: (params) => {
|
||||
const data: Record<string, unknown> = {}
|
||||
if (params.deadlineAt != null) data.deadline_at = params.deadlineAt || null
|
||||
if (params.isCompleted != null) data.is_completed = params.isCompleted
|
||||
if (params.deadlineAt !== undefined) data.deadline_at = params.deadlineAt || null
|
||||
if (params.isCompleted !== undefined) data.is_completed = params.isCompleted
|
||||
if (params.linkedRecords) {
|
||||
try {
|
||||
data.linked_records =
|
||||
|
||||
@@ -34,15 +34,15 @@ export const attioUpdateWebhookTool: ToolConfig<
|
||||
},
|
||||
targetUrl: {
|
||||
type: 'string',
|
||||
required: true,
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description: 'HTTPS target URL for webhook delivery',
|
||||
description: 'New HTTPS target URL',
|
||||
},
|
||||
subscriptions: {
|
||||
type: 'string',
|
||||
required: true,
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description: 'JSON array of subscriptions, e.g. [{"event_type":"note.created"}]',
|
||||
description: 'New JSON array of subscriptions',
|
||||
},
|
||||
},
|
||||
|
||||
@@ -54,21 +54,18 @@ export const attioUpdateWebhookTool: ToolConfig<
|
||||
'Content-Type': 'application/json',
|
||||
}),
|
||||
body: (params) => {
|
||||
let subscriptions: unknown = []
|
||||
const data: Record<string, unknown> = {}
|
||||
if (params.targetUrl !== undefined) data.target_url = params.targetUrl
|
||||
if (params.subscriptions) {
|
||||
try {
|
||||
subscriptions =
|
||||
data.subscriptions =
|
||||
typeof params.subscriptions === 'string'
|
||||
? JSON.parse(params.subscriptions)
|
||||
: params.subscriptions
|
||||
} catch {
|
||||
subscriptions = []
|
||||
data.subscriptions = []
|
||||
}
|
||||
}
|
||||
const data: Record<string, unknown> = {
|
||||
target_url: params.targetUrl,
|
||||
subscriptions,
|
||||
}
|
||||
return { data }
|
||||
},
|
||||
},
|
||||
|
||||
@@ -53,28 +53,6 @@ export const requestTool: ToolConfig<RequestParams, RequestResponse> = {
|
||||
visibility: 'user-only',
|
||||
description: 'Request timeout in milliseconds (default: 300000 = 5 minutes)',
|
||||
},
|
||||
retries: {
|
||||
type: 'number',
|
||||
visibility: 'hidden',
|
||||
description:
|
||||
'Number of retry attempts for retryable failures (timeouts, 429, 5xx). Default: 0 (no retries).',
|
||||
},
|
||||
retryDelayMs: {
|
||||
type: 'number',
|
||||
visibility: 'hidden',
|
||||
description: 'Initial retry delay in milliseconds (default: 500)',
|
||||
},
|
||||
retryMaxDelayMs: {
|
||||
type: 'number',
|
||||
visibility: 'hidden',
|
||||
description: 'Maximum delay between retries in milliseconds (default: 30000)',
|
||||
},
|
||||
retryNonIdempotent: {
|
||||
type: 'boolean',
|
||||
visibility: 'hidden',
|
||||
description:
|
||||
'Allow retries for non-idempotent methods like POST/PATCH (may create duplicate requests).',
|
||||
},
|
||||
},
|
||||
|
||||
request: {
|
||||
@@ -141,14 +119,6 @@ export const requestTool: ToolConfig<RequestParams, RequestResponse> = {
|
||||
|
||||
return undefined
|
||||
}) as (params: RequestParams) => Record<string, any> | string | FormData | undefined,
|
||||
|
||||
retry: {
|
||||
enabled: true,
|
||||
maxRetries: 0,
|
||||
initialDelayMs: 500,
|
||||
maxDelayMs: 30000,
|
||||
retryIdempotentOnly: true,
|
||||
},
|
||||
},
|
||||
|
||||
transformResponse: async (response: Response) => {
|
||||
|
||||
@@ -9,10 +9,6 @@ export interface RequestParams {
|
||||
pathParams?: Record<string, string>
|
||||
formData?: Record<string, string | Blob>
|
||||
timeout?: number
|
||||
retries?: number
|
||||
retryDelayMs?: number
|
||||
retryMaxDelayMs?: number
|
||||
retryNonIdempotent?: boolean
|
||||
}
|
||||
|
||||
export interface RequestResponse extends ToolResponse {
|
||||
|
||||
@@ -958,231 +958,4 @@ describe('MCP Tool Execution', () => {
|
||||
expect(result.error).toContain('Network error')
|
||||
expect(result.timing).toBeDefined()
|
||||
})
|
||||
|
||||
describe('Tool request retries', () => {
|
||||
function makeJsonResponse(
|
||||
status: number,
|
||||
body: unknown,
|
||||
extraHeaders?: Record<string, string>
|
||||
): any {
|
||||
const headers = new Headers({ 'content-type': 'application/json', ...(extraHeaders ?? {}) })
|
||||
return {
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
statusText: status >= 200 && status < 300 ? 'OK' : 'Error',
|
||||
headers,
|
||||
json: () => Promise.resolve(body),
|
||||
text: () => Promise.resolve(typeof body === 'string' ? body : JSON.stringify(body)),
|
||||
arrayBuffer: () => Promise.resolve(new ArrayBuffer(0)),
|
||||
blob: () => Promise.resolve(new Blob()),
|
||||
}
|
||||
}
|
||||
|
||||
it('retries on 5xx responses for http_request', async () => {
|
||||
global.fetch = Object.assign(
|
||||
vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(makeJsonResponse(500, { error: 'nope' }))
|
||||
.mockResolvedValueOnce(makeJsonResponse(200, { ok: true })),
|
||||
{ preconnect: vi.fn() }
|
||||
) as typeof fetch
|
||||
|
||||
const result = await executeTool('http_request', {
|
||||
url: '/api/test',
|
||||
method: 'GET',
|
||||
retries: 2,
|
||||
retryDelayMs: 0,
|
||||
retryMaxDelayMs: 0,
|
||||
})
|
||||
|
||||
expect(global.fetch).toHaveBeenCalledTimes(2)
|
||||
expect(result.success).toBe(true)
|
||||
expect((result.output as any).status).toBe(200)
|
||||
})
|
||||
|
||||
it('does not retry when retries is not specified (default: 0)', async () => {
|
||||
global.fetch = Object.assign(
|
||||
vi.fn().mockResolvedValue(makeJsonResponse(500, { error: 'server error' })),
|
||||
{ preconnect: vi.fn() }
|
||||
) as typeof fetch
|
||||
|
||||
const result = await executeTool('http_request', {
|
||||
url: '/api/test',
|
||||
method: 'GET',
|
||||
})
|
||||
|
||||
expect(global.fetch).toHaveBeenCalledTimes(1)
|
||||
expect(result.success).toBe(false)
|
||||
})
|
||||
|
||||
it('stops retrying after max attempts for http_request', async () => {
|
||||
global.fetch = Object.assign(
|
||||
vi.fn().mockResolvedValue(makeJsonResponse(502, { error: 'bad gateway' })),
|
||||
{ preconnect: vi.fn() }
|
||||
) as typeof fetch
|
||||
|
||||
const result = await executeTool('http_request', {
|
||||
url: '/api/test',
|
||||
method: 'GET',
|
||||
retries: 2,
|
||||
retryDelayMs: 0,
|
||||
retryMaxDelayMs: 0,
|
||||
})
|
||||
|
||||
expect(global.fetch).toHaveBeenCalledTimes(3)
|
||||
expect(result.success).toBe(false)
|
||||
})
|
||||
|
||||
it('does not retry on 4xx responses for http_request', async () => {
|
||||
global.fetch = Object.assign(
|
||||
vi.fn().mockResolvedValue(makeJsonResponse(400, { error: 'bad request' })),
|
||||
{ preconnect: vi.fn() }
|
||||
) as typeof fetch
|
||||
|
||||
const result = await executeTool('http_request', {
|
||||
url: '/api/test',
|
||||
method: 'GET',
|
||||
retries: 5,
|
||||
retryDelayMs: 0,
|
||||
retryMaxDelayMs: 0,
|
||||
})
|
||||
|
||||
expect(global.fetch).toHaveBeenCalledTimes(1)
|
||||
expect(result.success).toBe(false)
|
||||
})
|
||||
|
||||
it('does not retry POST by default (non-idempotent)', async () => {
|
||||
global.fetch = Object.assign(
|
||||
vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(makeJsonResponse(500, { error: 'nope' }))
|
||||
.mockResolvedValueOnce(makeJsonResponse(200, { ok: true })),
|
||||
{ preconnect: vi.fn() }
|
||||
) as typeof fetch
|
||||
|
||||
const result = await executeTool('http_request', {
|
||||
url: '/api/test',
|
||||
method: 'POST',
|
||||
retries: 2,
|
||||
retryDelayMs: 0,
|
||||
retryMaxDelayMs: 0,
|
||||
})
|
||||
|
||||
expect(global.fetch).toHaveBeenCalledTimes(1)
|
||||
expect(result.success).toBe(false)
|
||||
})
|
||||
|
||||
it('retries POST when retryNonIdempotent is enabled', async () => {
|
||||
global.fetch = Object.assign(
|
||||
vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(makeJsonResponse(500, { error: 'nope' }))
|
||||
.mockResolvedValueOnce(makeJsonResponse(200, { ok: true })),
|
||||
{ preconnect: vi.fn() }
|
||||
) as typeof fetch
|
||||
|
||||
const result = await executeTool('http_request', {
|
||||
url: '/api/test',
|
||||
method: 'POST',
|
||||
retries: 1,
|
||||
retryNonIdempotent: true,
|
||||
retryDelayMs: 0,
|
||||
retryMaxDelayMs: 0,
|
||||
})
|
||||
|
||||
expect(global.fetch).toHaveBeenCalledTimes(2)
|
||||
expect(result.success).toBe(true)
|
||||
expect((result.output as any).status).toBe(200)
|
||||
})
|
||||
|
||||
it('retries on timeout errors for http_request', async () => {
|
||||
const abortError = Object.assign(new Error('Aborted'), { name: 'AbortError' })
|
||||
global.fetch = Object.assign(
|
||||
vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(abortError)
|
||||
.mockResolvedValueOnce(makeJsonResponse(200, { ok: true })),
|
||||
{ preconnect: vi.fn() }
|
||||
) as typeof fetch
|
||||
|
||||
const result = await executeTool('http_request', {
|
||||
url: '/api/test',
|
||||
method: 'GET',
|
||||
retries: 1,
|
||||
retryDelayMs: 0,
|
||||
retryMaxDelayMs: 0,
|
||||
})
|
||||
|
||||
expect(global.fetch).toHaveBeenCalledTimes(2)
|
||||
expect(result.success).toBe(true)
|
||||
})
|
||||
|
||||
it('skips retry when Retry-After header exceeds maxDelayMs', async () => {
|
||||
global.fetch = Object.assign(
|
||||
vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(
|
||||
makeJsonResponse(429, { error: 'rate limited' }, { 'retry-after': '60' })
|
||||
)
|
||||
.mockResolvedValueOnce(makeJsonResponse(200, { ok: true })),
|
||||
{ preconnect: vi.fn() }
|
||||
) as typeof fetch
|
||||
|
||||
const result = await executeTool('http_request', {
|
||||
url: '/api/test',
|
||||
method: 'GET',
|
||||
retries: 3,
|
||||
retryMaxDelayMs: 5000,
|
||||
})
|
||||
|
||||
expect(global.fetch).toHaveBeenCalledTimes(1)
|
||||
expect(result.success).toBe(false)
|
||||
})
|
||||
|
||||
it('retries when Retry-After header is within maxDelayMs', async () => {
|
||||
global.fetch = Object.assign(
|
||||
vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(
|
||||
makeJsonResponse(429, { error: 'rate limited' }, { 'retry-after': '1' })
|
||||
)
|
||||
.mockResolvedValueOnce(makeJsonResponse(200, { ok: true })),
|
||||
{ preconnect: vi.fn() }
|
||||
) as typeof fetch
|
||||
|
||||
const result = await executeTool('http_request', {
|
||||
url: '/api/test',
|
||||
method: 'GET',
|
||||
retries: 2,
|
||||
retryMaxDelayMs: 5000,
|
||||
})
|
||||
|
||||
expect(global.fetch).toHaveBeenCalledTimes(2)
|
||||
expect(result.success).toBe(true)
|
||||
})
|
||||
|
||||
it('retries on ETIMEDOUT errors for http_request', async () => {
|
||||
const etimedoutError = Object.assign(new Error('connect ETIMEDOUT 10.0.0.1:443'), {
|
||||
code: 'ETIMEDOUT',
|
||||
})
|
||||
global.fetch = Object.assign(
|
||||
vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(etimedoutError)
|
||||
.mockResolvedValueOnce(makeJsonResponse(200, { ok: true })),
|
||||
{ preconnect: vi.fn() }
|
||||
) as typeof fetch
|
||||
|
||||
const result = await executeTool('http_request', {
|
||||
url: '/api/test',
|
||||
method: 'GET',
|
||||
retries: 1,
|
||||
retryDelayMs: 0,
|
||||
retryMaxDelayMs: 0,
|
||||
})
|
||||
|
||||
expect(global.fetch).toHaveBeenCalledTimes(2)
|
||||
expect(result.success).toBe(true)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -14,7 +14,7 @@ import { resolveSkillContent } from '@/executor/handlers/agent/skills-resolver'
|
||||
import type { ExecutionContext } from '@/executor/types'
|
||||
import type { ErrorInfo } from '@/tools/error-extractors'
|
||||
import { extractErrorMessage } from '@/tools/error-extractors'
|
||||
import type { OAuthTokenPayload, ToolConfig, ToolResponse, ToolRetryConfig } from '@/tools/types'
|
||||
import type { OAuthTokenPayload, ToolConfig, ToolResponse } from '@/tools/types'
|
||||
import {
|
||||
formatRequestParams,
|
||||
getTool,
|
||||
@@ -610,68 +610,6 @@ async function addInternalAuthIfNeeded(
|
||||
}
|
||||
}
|
||||
|
||||
interface ResolvedRetryConfig {
|
||||
maxRetries: number
|
||||
initialDelayMs: number
|
||||
maxDelayMs: number
|
||||
}
|
||||
|
||||
function getRetryConfig(
|
||||
retry: ToolRetryConfig | undefined,
|
||||
params: Record<string, any>,
|
||||
method: string
|
||||
): ResolvedRetryConfig | null {
|
||||
if (!retry?.enabled) return null
|
||||
|
||||
const isIdempotent = ['GET', 'HEAD', 'PUT', 'DELETE'].includes(method.toUpperCase())
|
||||
if (retry.retryIdempotentOnly && !isIdempotent && !params.retryNonIdempotent) {
|
||||
return null
|
||||
}
|
||||
|
||||
const maxRetries = Math.min(10, Math.max(0, Number(params.retries) || retry.maxRetries || 0))
|
||||
if (maxRetries === 0) return null
|
||||
|
||||
return {
|
||||
maxRetries,
|
||||
initialDelayMs: Number(params.retryDelayMs) || retry.initialDelayMs || 500,
|
||||
maxDelayMs: Number(params.retryMaxDelayMs) || retry.maxDelayMs || 30000,
|
||||
}
|
||||
}
|
||||
|
||||
function isRetryableFailure(error: unknown, status?: number): boolean {
|
||||
if (status === 429 || (status && status >= 500 && status <= 599)) return true
|
||||
if (error instanceof Error) {
|
||||
const code = (error as NodeJS.ErrnoException).code
|
||||
if (code === 'ETIMEDOUT' || code === 'ECONNRESET' || code === 'ECONNABORTED') {
|
||||
return true
|
||||
}
|
||||
const msg = error.message.toLowerCase()
|
||||
if (isBodySizeLimitError(msg)) return false
|
||||
return msg.includes('timeout') || msg.includes('timed out')
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function calculateBackoff(attempt: number, initialDelayMs: number, maxDelayMs: number): number {
|
||||
const base = Math.min(initialDelayMs * 2 ** attempt, maxDelayMs)
|
||||
return Math.round(base / 2 + Math.random() * (base / 2))
|
||||
}
|
||||
|
||||
function parseRetryAfterHeader(header: string | null): number {
|
||||
if (!header) return 0
|
||||
const trimmed = header.trim()
|
||||
if (/^\d+$/.test(trimmed)) {
|
||||
const seconds = Number.parseInt(trimmed, 10)
|
||||
return seconds > 0 ? seconds * 1000 : 0
|
||||
}
|
||||
const date = new Date(trimmed)
|
||||
if (!Number.isNaN(date.getTime())) {
|
||||
const deltaMs = date.getTime() - Date.now()
|
||||
return deltaMs > 0 ? deltaMs : 0
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a tool request directly
|
||||
* Internal routes (/api/...) use regular fetch
|
||||
@@ -753,123 +691,59 @@ async function executeToolRequest(
|
||||
headersRecord[key] = value
|
||||
})
|
||||
|
||||
const retryConfig = getRetryConfig(tool.request.retry, params, requestParams.method)
|
||||
const maxAttempts = retryConfig ? 1 + retryConfig.maxRetries : 1
|
||||
let response: Response
|
||||
|
||||
let response: Response | undefined
|
||||
let lastError: unknown
|
||||
|
||||
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
||||
const isLastAttempt = attempt === maxAttempts - 1
|
||||
if (isInternalRoute) {
|
||||
const controller = new AbortController()
|
||||
const timeout = requestParams.timeout || DEFAULT_EXECUTION_TIMEOUT_MS
|
||||
const timeoutId = setTimeout(() => controller.abort(), timeout)
|
||||
|
||||
try {
|
||||
if (isInternalRoute) {
|
||||
const controller = new AbortController()
|
||||
const timeout = requestParams.timeout || DEFAULT_EXECUTION_TIMEOUT_MS
|
||||
const timeoutId = setTimeout(() => controller.abort(), timeout)
|
||||
|
||||
try {
|
||||
response = await fetch(fullUrl, {
|
||||
method: requestParams.method,
|
||||
headers: headers,
|
||||
body: requestParams.body,
|
||||
signal: controller.signal,
|
||||
})
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.name === 'AbortError') {
|
||||
throw new Error(`Request timed out after ${timeout}ms`)
|
||||
}
|
||||
throw error
|
||||
} finally {
|
||||
clearTimeout(timeoutId)
|
||||
}
|
||||
} else {
|
||||
const urlValidation = await validateUrlWithDNS(fullUrl, 'toolUrl')
|
||||
if (!urlValidation.isValid) {
|
||||
throw new Error(`Invalid tool URL: ${urlValidation.error}`)
|
||||
}
|
||||
|
||||
const secureResponse = await secureFetchWithPinnedIP(fullUrl, urlValidation.resolvedIP!, {
|
||||
method: requestParams.method,
|
||||
headers: headersRecord,
|
||||
body: requestParams.body ?? undefined,
|
||||
timeout: requestParams.timeout,
|
||||
})
|
||||
|
||||
const responseHeaders = new Headers(secureResponse.headers.toRecord())
|
||||
const nullBodyStatuses = new Set([101, 204, 205, 304])
|
||||
|
||||
if (nullBodyStatuses.has(secureResponse.status)) {
|
||||
response = new Response(null, {
|
||||
status: secureResponse.status,
|
||||
statusText: secureResponse.statusText,
|
||||
headers: responseHeaders,
|
||||
})
|
||||
} else {
|
||||
const bodyBuffer = await secureResponse.arrayBuffer()
|
||||
response = new Response(bodyBuffer, {
|
||||
status: secureResponse.status,
|
||||
statusText: secureResponse.statusText,
|
||||
headers: responseHeaders,
|
||||
})
|
||||
}
|
||||
}
|
||||
response = await fetch(fullUrl, {
|
||||
method: requestParams.method,
|
||||
headers: headers,
|
||||
body: requestParams.body,
|
||||
signal: controller.signal,
|
||||
})
|
||||
} catch (error) {
|
||||
lastError = error
|
||||
if (!retryConfig || isLastAttempt || !isRetryableFailure(error)) {
|
||||
throw error
|
||||
// Convert AbortError to a timeout error message
|
||||
if (error instanceof Error && error.name === 'AbortError') {
|
||||
throw new Error(`Request timed out after ${timeout}ms`)
|
||||
}
|
||||
const delayMs = calculateBackoff(
|
||||
attempt,
|
||||
retryConfig.initialDelayMs,
|
||||
retryConfig.maxDelayMs
|
||||
)
|
||||
logger.warn(
|
||||
`[${requestId}] Retrying ${toolId} after error (attempt ${attempt + 1}/${maxAttempts})`,
|
||||
{ delayMs }
|
||||
)
|
||||
await new Promise((r) => setTimeout(r, delayMs))
|
||||
continue
|
||||
throw error
|
||||
} finally {
|
||||
clearTimeout(timeoutId)
|
||||
}
|
||||
} else {
|
||||
const urlValidation = await validateUrlWithDNS(fullUrl, 'toolUrl')
|
||||
if (!urlValidation.isValid) {
|
||||
throw new Error(`Invalid tool URL: ${urlValidation.error}`)
|
||||
}
|
||||
|
||||
if (
|
||||
retryConfig &&
|
||||
!isLastAttempt &&
|
||||
response &&
|
||||
!response.ok &&
|
||||
isRetryableFailure(null, response.status)
|
||||
) {
|
||||
const retryAfterMs = parseRetryAfterHeader(response.headers.get('retry-after'))
|
||||
if (retryAfterMs > retryConfig.maxDelayMs) {
|
||||
logger.warn(
|
||||
`[${requestId}] Retry-After (${retryAfterMs}ms) exceeds maxDelayMs (${retryConfig.maxDelayMs}ms), skipping retry`
|
||||
)
|
||||
break
|
||||
}
|
||||
try {
|
||||
await response.arrayBuffer()
|
||||
} catch {
|
||||
// Ignore errors when consuming body
|
||||
}
|
||||
const backoffMs = calculateBackoff(
|
||||
attempt,
|
||||
retryConfig.initialDelayMs,
|
||||
retryConfig.maxDelayMs
|
||||
)
|
||||
const delayMs = Math.max(backoffMs, retryAfterMs)
|
||||
logger.warn(
|
||||
`[${requestId}] Retrying ${toolId} after HTTP ${response.status} (attempt ${attempt + 1}/${maxAttempts})`,
|
||||
{ delayMs }
|
||||
)
|
||||
await new Promise((r) => setTimeout(r, delayMs))
|
||||
continue
|
||||
const secureResponse = await secureFetchWithPinnedIP(fullUrl, urlValidation.resolvedIP!, {
|
||||
method: requestParams.method,
|
||||
headers: headersRecord,
|
||||
body: requestParams.body ?? undefined,
|
||||
timeout: requestParams.timeout,
|
||||
})
|
||||
|
||||
const responseHeaders = new Headers(secureResponse.headers.toRecord())
|
||||
const nullBodyStatuses = new Set([101, 204, 205, 304])
|
||||
|
||||
if (nullBodyStatuses.has(secureResponse.status)) {
|
||||
response = new Response(null, {
|
||||
status: secureResponse.status,
|
||||
statusText: secureResponse.statusText,
|
||||
headers: responseHeaders,
|
||||
})
|
||||
} else {
|
||||
const bodyBuffer = await secureResponse.arrayBuffer()
|
||||
response = new Response(bodyBuffer, {
|
||||
status: secureResponse.status,
|
||||
statusText: secureResponse.statusText,
|
||||
headers: responseHeaders,
|
||||
})
|
||||
}
|
||||
|
||||
break
|
||||
}
|
||||
|
||||
if (!response) {
|
||||
throw lastError ?? new Error(`Request failed for ${toolId}`)
|
||||
}
|
||||
|
||||
// For non-OK responses, attempt JSON first; if parsing fails, fall back to text
|
||||
|
||||
@@ -58,14 +58,6 @@ export interface OAuthConfig {
|
||||
requiredScopes?: string[] // Specific scopes this tool needs (for granular scope validation)
|
||||
}
|
||||
|
||||
export interface ToolRetryConfig {
|
||||
enabled: boolean
|
||||
maxRetries?: number
|
||||
initialDelayMs?: number
|
||||
maxDelayMs?: number
|
||||
retryIdempotentOnly?: boolean
|
||||
}
|
||||
|
||||
export interface ToolConfig<P = any, R = any> {
|
||||
// Basic tool identification
|
||||
id: string
|
||||
@@ -123,7 +115,6 @@ export interface ToolConfig<P = any, R = any> {
|
||||
method: HttpMethod | ((params: P) => HttpMethod)
|
||||
headers: (params: P) => Record<string, string>
|
||||
body?: (params: P) => Record<string, any> | string | FormData | undefined
|
||||
retry?: ToolRetryConfig
|
||||
}
|
||||
|
||||
// Post-processing (optional) - allows additional processing after the initial request
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { AttioIcon } from '@/components/icons'
|
||||
import { buildAttioTriggerSubBlocks, buildCommentOutputs } from '@/triggers/attio/utils'
|
||||
import { buildTriggerSubBlocks } from '@/triggers'
|
||||
import {
|
||||
attioSetupInstructions,
|
||||
attioTriggerOptions,
|
||||
buildAttioExtraFields,
|
||||
buildCommentOutputs,
|
||||
} from '@/triggers/attio/utils'
|
||||
import type { TriggerConfig } from '@/triggers/types'
|
||||
|
||||
/**
|
||||
@@ -15,7 +21,12 @@ export const attioCommentCreatedTrigger: TriggerConfig = {
|
||||
version: '1.0.0',
|
||||
icon: AttioIcon,
|
||||
|
||||
subBlocks: buildAttioTriggerSubBlocks('attio_comment_created'),
|
||||
subBlocks: buildTriggerSubBlocks({
|
||||
triggerId: 'attio_comment_created',
|
||||
triggerOptions: attioTriggerOptions,
|
||||
setupInstructions: attioSetupInstructions('comment.created'),
|
||||
extraFields: buildAttioExtraFields('attio_comment_created'),
|
||||
}),
|
||||
|
||||
outputs: buildCommentOutputs(),
|
||||
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { AttioIcon } from '@/components/icons'
|
||||
import { buildAttioTriggerSubBlocks, buildCommentOutputs } from '@/triggers/attio/utils'
|
||||
import { buildTriggerSubBlocks } from '@/triggers'
|
||||
import {
|
||||
attioSetupInstructions,
|
||||
attioTriggerOptions,
|
||||
buildAttioExtraFields,
|
||||
buildCommentOutputs,
|
||||
} from '@/triggers/attio/utils'
|
||||
import type { TriggerConfig } from '@/triggers/types'
|
||||
|
||||
/**
|
||||
@@ -15,7 +21,12 @@ export const attioCommentDeletedTrigger: TriggerConfig = {
|
||||
version: '1.0.0',
|
||||
icon: AttioIcon,
|
||||
|
||||
subBlocks: buildAttioTriggerSubBlocks('attio_comment_deleted'),
|
||||
subBlocks: buildTriggerSubBlocks({
|
||||
triggerId: 'attio_comment_deleted',
|
||||
triggerOptions: attioTriggerOptions,
|
||||
setupInstructions: attioSetupInstructions('comment.deleted'),
|
||||
extraFields: buildAttioExtraFields('attio_comment_deleted'),
|
||||
}),
|
||||
|
||||
outputs: buildCommentOutputs(),
|
||||
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { AttioIcon } from '@/components/icons'
|
||||
import { buildAttioTriggerSubBlocks, buildCommentOutputs } from '@/triggers/attio/utils'
|
||||
import { buildTriggerSubBlocks } from '@/triggers'
|
||||
import {
|
||||
attioSetupInstructions,
|
||||
attioTriggerOptions,
|
||||
buildAttioExtraFields,
|
||||
buildCommentOutputs,
|
||||
} from '@/triggers/attio/utils'
|
||||
import type { TriggerConfig } from '@/triggers/types'
|
||||
|
||||
/**
|
||||
@@ -15,7 +21,12 @@ export const attioCommentResolvedTrigger: TriggerConfig = {
|
||||
version: '1.0.0',
|
||||
icon: AttioIcon,
|
||||
|
||||
subBlocks: buildAttioTriggerSubBlocks('attio_comment_resolved'),
|
||||
subBlocks: buildTriggerSubBlocks({
|
||||
triggerId: 'attio_comment_resolved',
|
||||
triggerOptions: attioTriggerOptions,
|
||||
setupInstructions: attioSetupInstructions('comment.resolved'),
|
||||
extraFields: buildAttioExtraFields('attio_comment_resolved'),
|
||||
}),
|
||||
|
||||
outputs: buildCommentOutputs(),
|
||||
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { AttioIcon } from '@/components/icons'
|
||||
import { buildAttioTriggerSubBlocks, buildCommentOutputs } from '@/triggers/attio/utils'
|
||||
import { buildTriggerSubBlocks } from '@/triggers'
|
||||
import {
|
||||
attioSetupInstructions,
|
||||
attioTriggerOptions,
|
||||
buildAttioExtraFields,
|
||||
buildCommentOutputs,
|
||||
} from '@/triggers/attio/utils'
|
||||
import type { TriggerConfig } from '@/triggers/types'
|
||||
|
||||
/**
|
||||
@@ -15,7 +21,12 @@ export const attioCommentUnresolvedTrigger: TriggerConfig = {
|
||||
version: '1.0.0',
|
||||
icon: AttioIcon,
|
||||
|
||||
subBlocks: buildAttioTriggerSubBlocks('attio_comment_unresolved'),
|
||||
subBlocks: buildTriggerSubBlocks({
|
||||
triggerId: 'attio_comment_unresolved',
|
||||
triggerOptions: attioTriggerOptions,
|
||||
setupInstructions: attioSetupInstructions('comment.unresolved'),
|
||||
extraFields: buildAttioExtraFields('attio_comment_unresolved'),
|
||||
}),
|
||||
|
||||
outputs: buildCommentOutputs(),
|
||||
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { AttioIcon } from '@/components/icons'
|
||||
import { buildAttioTriggerSubBlocks, buildListEntryOutputs } from '@/triggers/attio/utils'
|
||||
import { buildTriggerSubBlocks } from '@/triggers'
|
||||
import {
|
||||
attioSetupInstructions,
|
||||
attioTriggerOptions,
|
||||
buildAttioExtraFields,
|
||||
buildListEntryOutputs,
|
||||
} from '@/triggers/attio/utils'
|
||||
import type { TriggerConfig } from '@/triggers/types'
|
||||
|
||||
/**
|
||||
@@ -15,7 +21,12 @@ export const attioListEntryCreatedTrigger: TriggerConfig = {
|
||||
version: '1.0.0',
|
||||
icon: AttioIcon,
|
||||
|
||||
subBlocks: buildAttioTriggerSubBlocks('attio_list_entry_created'),
|
||||
subBlocks: buildTriggerSubBlocks({
|
||||
triggerId: 'attio_list_entry_created',
|
||||
triggerOptions: attioTriggerOptions,
|
||||
setupInstructions: attioSetupInstructions('list-entry.created'),
|
||||
extraFields: buildAttioExtraFields('attio_list_entry_created'),
|
||||
}),
|
||||
|
||||
outputs: buildListEntryOutputs(),
|
||||
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { AttioIcon } from '@/components/icons'
|
||||
import { buildAttioTriggerSubBlocks, buildListEntryOutputs } from '@/triggers/attio/utils'
|
||||
import { buildTriggerSubBlocks } from '@/triggers'
|
||||
import {
|
||||
attioSetupInstructions,
|
||||
attioTriggerOptions,
|
||||
buildAttioExtraFields,
|
||||
buildListEntryOutputs,
|
||||
} from '@/triggers/attio/utils'
|
||||
import type { TriggerConfig } from '@/triggers/types'
|
||||
|
||||
/**
|
||||
@@ -15,7 +21,12 @@ export const attioListEntryDeletedTrigger: TriggerConfig = {
|
||||
version: '1.0.0',
|
||||
icon: AttioIcon,
|
||||
|
||||
subBlocks: buildAttioTriggerSubBlocks('attio_list_entry_deleted'),
|
||||
subBlocks: buildTriggerSubBlocks({
|
||||
triggerId: 'attio_list_entry_deleted',
|
||||
triggerOptions: attioTriggerOptions,
|
||||
setupInstructions: attioSetupInstructions('list-entry.deleted'),
|
||||
extraFields: buildAttioExtraFields('attio_list_entry_deleted'),
|
||||
}),
|
||||
|
||||
outputs: buildListEntryOutputs(),
|
||||
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { AttioIcon } from '@/components/icons'
|
||||
import { buildAttioTriggerSubBlocks, buildListEntryUpdatedOutputs } from '@/triggers/attio/utils'
|
||||
import { buildTriggerSubBlocks } from '@/triggers'
|
||||
import {
|
||||
attioSetupInstructions,
|
||||
attioTriggerOptions,
|
||||
buildAttioExtraFields,
|
||||
buildListEntryUpdatedOutputs,
|
||||
} from '@/triggers/attio/utils'
|
||||
import type { TriggerConfig } from '@/triggers/types'
|
||||
|
||||
/**
|
||||
@@ -15,7 +21,12 @@ export const attioListEntryUpdatedTrigger: TriggerConfig = {
|
||||
version: '1.0.0',
|
||||
icon: AttioIcon,
|
||||
|
||||
subBlocks: buildAttioTriggerSubBlocks('attio_list_entry_updated'),
|
||||
subBlocks: buildTriggerSubBlocks({
|
||||
triggerId: 'attio_list_entry_updated',
|
||||
triggerOptions: attioTriggerOptions,
|
||||
setupInstructions: attioSetupInstructions('list-entry.updated'),
|
||||
extraFields: buildAttioExtraFields('attio_list_entry_updated'),
|
||||
}),
|
||||
|
||||
outputs: buildListEntryUpdatedOutputs(),
|
||||
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { AttioIcon } from '@/components/icons'
|
||||
import { buildAttioTriggerSubBlocks, buildNoteOutputs } from '@/triggers/attio/utils'
|
||||
import { buildTriggerSubBlocks } from '@/triggers'
|
||||
import {
|
||||
attioSetupInstructions,
|
||||
attioTriggerOptions,
|
||||
buildAttioExtraFields,
|
||||
buildNoteOutputs,
|
||||
} from '@/triggers/attio/utils'
|
||||
import type { TriggerConfig } from '@/triggers/types'
|
||||
|
||||
/**
|
||||
@@ -15,7 +21,12 @@ export const attioNoteCreatedTrigger: TriggerConfig = {
|
||||
version: '1.0.0',
|
||||
icon: AttioIcon,
|
||||
|
||||
subBlocks: buildAttioTriggerSubBlocks('attio_note_created'),
|
||||
subBlocks: buildTriggerSubBlocks({
|
||||
triggerId: 'attio_note_created',
|
||||
triggerOptions: attioTriggerOptions,
|
||||
setupInstructions: attioSetupInstructions('note.created'),
|
||||
extraFields: buildAttioExtraFields('attio_note_created'),
|
||||
}),
|
||||
|
||||
outputs: buildNoteOutputs(),
|
||||
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { AttioIcon } from '@/components/icons'
|
||||
import { buildAttioTriggerSubBlocks, buildNoteOutputs } from '@/triggers/attio/utils'
|
||||
import { buildTriggerSubBlocks } from '@/triggers'
|
||||
import {
|
||||
attioSetupInstructions,
|
||||
attioTriggerOptions,
|
||||
buildAttioExtraFields,
|
||||
buildNoteOutputs,
|
||||
} from '@/triggers/attio/utils'
|
||||
import type { TriggerConfig } from '@/triggers/types'
|
||||
|
||||
/**
|
||||
@@ -15,7 +21,12 @@ export const attioNoteDeletedTrigger: TriggerConfig = {
|
||||
version: '1.0.0',
|
||||
icon: AttioIcon,
|
||||
|
||||
subBlocks: buildAttioTriggerSubBlocks('attio_note_deleted'),
|
||||
subBlocks: buildTriggerSubBlocks({
|
||||
triggerId: 'attio_note_deleted',
|
||||
triggerOptions: attioTriggerOptions,
|
||||
setupInstructions: attioSetupInstructions('note.deleted'),
|
||||
extraFields: buildAttioExtraFields('attio_note_deleted'),
|
||||
}),
|
||||
|
||||
outputs: buildNoteOutputs(),
|
||||
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { AttioIcon } from '@/components/icons'
|
||||
import { buildAttioTriggerSubBlocks, buildNoteOutputs } from '@/triggers/attio/utils'
|
||||
import { buildTriggerSubBlocks } from '@/triggers'
|
||||
import {
|
||||
attioSetupInstructions,
|
||||
attioTriggerOptions,
|
||||
buildAttioExtraFields,
|
||||
buildNoteOutputs,
|
||||
} from '@/triggers/attio/utils'
|
||||
import type { TriggerConfig } from '@/triggers/types'
|
||||
|
||||
/**
|
||||
@@ -15,7 +21,12 @@ export const attioNoteUpdatedTrigger: TriggerConfig = {
|
||||
version: '1.0.0',
|
||||
icon: AttioIcon,
|
||||
|
||||
subBlocks: buildAttioTriggerSubBlocks('attio_note_updated'),
|
||||
subBlocks: buildTriggerSubBlocks({
|
||||
triggerId: 'attio_note_updated',
|
||||
triggerOptions: attioTriggerOptions,
|
||||
setupInstructions: attioSetupInstructions('note.updated'),
|
||||
extraFields: buildAttioExtraFields('attio_note_updated'),
|
||||
}),
|
||||
|
||||
outputs: buildNoteOutputs(),
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { AttioIcon } from '@/components/icons'
|
||||
import { buildTriggerSubBlocks } from '@/triggers'
|
||||
import {
|
||||
attioSetupInstructions,
|
||||
attioTriggerOptions,
|
||||
buildAttioTriggerSubBlocks,
|
||||
buildAttioExtraFields,
|
||||
buildRecordOutputs,
|
||||
} from '@/triggers/attio/utils'
|
||||
import type { TriggerConfig } from '@/triggers/types'
|
||||
@@ -20,18 +22,13 @@ export const attioRecordCreatedTrigger: TriggerConfig = {
|
||||
version: '1.0.0',
|
||||
icon: AttioIcon,
|
||||
|
||||
subBlocks: [
|
||||
{
|
||||
id: 'selectedTriggerId',
|
||||
title: 'Trigger Type',
|
||||
type: 'dropdown',
|
||||
mode: 'trigger',
|
||||
options: attioTriggerOptions,
|
||||
value: () => 'attio_record_created',
|
||||
required: true,
|
||||
},
|
||||
...buildAttioTriggerSubBlocks('attio_record_created'),
|
||||
],
|
||||
subBlocks: buildTriggerSubBlocks({
|
||||
triggerId: 'attio_record_created',
|
||||
triggerOptions: attioTriggerOptions,
|
||||
includeDropdown: true,
|
||||
setupInstructions: attioSetupInstructions('record.created'),
|
||||
extraFields: buildAttioExtraFields('attio_record_created'),
|
||||
}),
|
||||
|
||||
outputs: buildRecordOutputs(),
|
||||
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { AttioIcon } from '@/components/icons'
|
||||
import { buildAttioTriggerSubBlocks, buildRecordOutputs } from '@/triggers/attio/utils'
|
||||
import { buildTriggerSubBlocks } from '@/triggers'
|
||||
import {
|
||||
attioSetupInstructions,
|
||||
attioTriggerOptions,
|
||||
buildAttioExtraFields,
|
||||
buildRecordOutputs,
|
||||
} from '@/triggers/attio/utils'
|
||||
import type { TriggerConfig } from '@/triggers/types'
|
||||
|
||||
/**
|
||||
@@ -15,7 +21,12 @@ export const attioRecordDeletedTrigger: TriggerConfig = {
|
||||
version: '1.0.0',
|
||||
icon: AttioIcon,
|
||||
|
||||
subBlocks: buildAttioTriggerSubBlocks('attio_record_deleted'),
|
||||
subBlocks: buildTriggerSubBlocks({
|
||||
triggerId: 'attio_record_deleted',
|
||||
triggerOptions: attioTriggerOptions,
|
||||
setupInstructions: attioSetupInstructions('record.deleted'),
|
||||
extraFields: buildAttioExtraFields('attio_record_deleted'),
|
||||
}),
|
||||
|
||||
outputs: buildRecordOutputs(),
|
||||
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { AttioIcon } from '@/components/icons'
|
||||
import { buildAttioTriggerSubBlocks, buildRecordMergedEventOutputs } from '@/triggers/attio/utils'
|
||||
import { buildTriggerSubBlocks } from '@/triggers'
|
||||
import {
|
||||
attioSetupInstructions,
|
||||
attioTriggerOptions,
|
||||
buildAttioExtraFields,
|
||||
buildRecordMergedEventOutputs,
|
||||
} from '@/triggers/attio/utils'
|
||||
import type { TriggerConfig } from '@/triggers/types'
|
||||
|
||||
/**
|
||||
@@ -15,7 +21,12 @@ export const attioRecordMergedTrigger: TriggerConfig = {
|
||||
version: '1.0.0',
|
||||
icon: AttioIcon,
|
||||
|
||||
subBlocks: buildAttioTriggerSubBlocks('attio_record_merged'),
|
||||
subBlocks: buildTriggerSubBlocks({
|
||||
triggerId: 'attio_record_merged',
|
||||
triggerOptions: attioTriggerOptions,
|
||||
setupInstructions: attioSetupInstructions('record.merged'),
|
||||
extraFields: buildAttioExtraFields('attio_record_merged'),
|
||||
}),
|
||||
|
||||
outputs: buildRecordMergedEventOutputs(),
|
||||
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { AttioIcon } from '@/components/icons'
|
||||
import { buildAttioTriggerSubBlocks, buildRecordUpdatedOutputs } from '@/triggers/attio/utils'
|
||||
import { buildTriggerSubBlocks } from '@/triggers'
|
||||
import {
|
||||
attioSetupInstructions,
|
||||
attioTriggerOptions,
|
||||
buildAttioExtraFields,
|
||||
buildRecordUpdatedOutputs,
|
||||
} from '@/triggers/attio/utils'
|
||||
import type { TriggerConfig } from '@/triggers/types'
|
||||
|
||||
/**
|
||||
@@ -15,7 +21,12 @@ export const attioRecordUpdatedTrigger: TriggerConfig = {
|
||||
version: '1.0.0',
|
||||
icon: AttioIcon,
|
||||
|
||||
subBlocks: buildAttioTriggerSubBlocks('attio_record_updated'),
|
||||
subBlocks: buildTriggerSubBlocks({
|
||||
triggerId: 'attio_record_updated',
|
||||
triggerOptions: attioTriggerOptions,
|
||||
setupInstructions: attioSetupInstructions('record.updated'),
|
||||
extraFields: buildAttioExtraFields('attio_record_updated'),
|
||||
}),
|
||||
|
||||
outputs: buildRecordUpdatedOutputs(),
|
||||
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { AttioIcon } from '@/components/icons'
|
||||
import { buildAttioTriggerSubBlocks, buildTaskOutputs } from '@/triggers/attio/utils'
|
||||
import { buildTriggerSubBlocks } from '@/triggers'
|
||||
import {
|
||||
attioSetupInstructions,
|
||||
attioTriggerOptions,
|
||||
buildAttioExtraFields,
|
||||
buildTaskOutputs,
|
||||
} from '@/triggers/attio/utils'
|
||||
import type { TriggerConfig } from '@/triggers/types'
|
||||
|
||||
/**
|
||||
@@ -15,7 +21,12 @@ export const attioTaskCreatedTrigger: TriggerConfig = {
|
||||
version: '1.0.0',
|
||||
icon: AttioIcon,
|
||||
|
||||
subBlocks: buildAttioTriggerSubBlocks('attio_task_created'),
|
||||
subBlocks: buildTriggerSubBlocks({
|
||||
triggerId: 'attio_task_created',
|
||||
triggerOptions: attioTriggerOptions,
|
||||
setupInstructions: attioSetupInstructions('task.created'),
|
||||
extraFields: buildAttioExtraFields('attio_task_created'),
|
||||
}),
|
||||
|
||||
outputs: buildTaskOutputs(),
|
||||
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { AttioIcon } from '@/components/icons'
|
||||
import { buildAttioTriggerSubBlocks, buildTaskOutputs } from '@/triggers/attio/utils'
|
||||
import { buildTriggerSubBlocks } from '@/triggers'
|
||||
import {
|
||||
attioSetupInstructions,
|
||||
attioTriggerOptions,
|
||||
buildAttioExtraFields,
|
||||
buildTaskOutputs,
|
||||
} from '@/triggers/attio/utils'
|
||||
import type { TriggerConfig } from '@/triggers/types'
|
||||
|
||||
/**
|
||||
@@ -15,7 +21,12 @@ export const attioTaskDeletedTrigger: TriggerConfig = {
|
||||
version: '1.0.0',
|
||||
icon: AttioIcon,
|
||||
|
||||
subBlocks: buildAttioTriggerSubBlocks('attio_task_deleted'),
|
||||
subBlocks: buildTriggerSubBlocks({
|
||||
triggerId: 'attio_task_deleted',
|
||||
triggerOptions: attioTriggerOptions,
|
||||
setupInstructions: attioSetupInstructions('task.deleted'),
|
||||
extraFields: buildAttioExtraFields('attio_task_deleted'),
|
||||
}),
|
||||
|
||||
outputs: buildTaskOutputs(),
|
||||
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { AttioIcon } from '@/components/icons'
|
||||
import { buildAttioTriggerSubBlocks, buildTaskOutputs } from '@/triggers/attio/utils'
|
||||
import { buildTriggerSubBlocks } from '@/triggers'
|
||||
import {
|
||||
attioSetupInstructions,
|
||||
attioTriggerOptions,
|
||||
buildAttioExtraFields,
|
||||
buildTaskOutputs,
|
||||
} from '@/triggers/attio/utils'
|
||||
import type { TriggerConfig } from '@/triggers/types'
|
||||
|
||||
/**
|
||||
@@ -15,7 +21,12 @@ export const attioTaskUpdatedTrigger: TriggerConfig = {
|
||||
version: '1.0.0',
|
||||
icon: AttioIcon,
|
||||
|
||||
subBlocks: buildAttioTriggerSubBlocks('attio_task_updated'),
|
||||
subBlocks: buildTriggerSubBlocks({
|
||||
triggerId: 'attio_task_updated',
|
||||
triggerOptions: attioTriggerOptions,
|
||||
setupInstructions: attioSetupInstructions('task.updated'),
|
||||
extraFields: buildAttioExtraFields('attio_task_updated'),
|
||||
}),
|
||||
|
||||
outputs: buildTaskOutputs(),
|
||||
|
||||
|
||||
@@ -22,11 +22,15 @@ export const attioTriggerOptions = [
|
||||
{ label: 'Generic Webhook (All Events)', id: 'attio_webhook' },
|
||||
]
|
||||
|
||||
export function attioSetupInstructions(): string {
|
||||
export function attioSetupInstructions(eventType: string): string {
|
||||
const instructions = [
|
||||
'<strong>Note:</strong> Webhooks are automatically created in Attio when you deploy this workflow, and deleted when you undeploy. See the <a href="https://docs.attio.com/rest-api/guides/webhooks" target="_blank" rel="noopener noreferrer">Attio webhook documentation</a> for details.',
|
||||
'Connect your <strong>Attio account</strong> using the credential selector above.',
|
||||
'<strong>Deploy</strong> the workflow — a webhook will be created automatically in your Attio workspace.',
|
||||
'<strong>Note:</strong> You need access to the Attio developer settings to create webhooks. See the <a href="https://docs.attio.com/rest-api/guides/webhooks" target="_blank" rel="noopener noreferrer">Attio webhook documentation</a> for details.',
|
||||
'In Attio, navigate to <strong>Settings > Developers</strong> and select your integration.',
|
||||
'Go to the <strong>Webhooks</strong> tab and click <strong>"Create Webhook"</strong>.',
|
||||
'Paste the <strong>Webhook URL</strong> from above into the target URL field.',
|
||||
`Add a subscription with the event type <strong>${eventType}</strong>. You can optionally add filters to scope the events.`,
|
||||
'Save the webhook. Copy the <strong>signing secret</strong> shown and paste it in the field above for signature verification.',
|
||||
'The webhook is now active. Attio will send events to the URL you configured.',
|
||||
]
|
||||
|
||||
return instructions
|
||||
@@ -37,34 +41,17 @@ export function attioSetupInstructions(): string {
|
||||
.join('')
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds subBlocks for an Attio trigger with OAuth credentials and automatic webhook lifecycle.
|
||||
* Used by both the primary trigger (with dropdown) and secondary triggers.
|
||||
*/
|
||||
export function buildAttioTriggerSubBlocks(triggerId: string): SubBlockConfig[] {
|
||||
export function buildAttioExtraFields(triggerId: string): SubBlockConfig[] {
|
||||
return [
|
||||
{
|
||||
id: 'triggerCredentials',
|
||||
title: 'Attio Account',
|
||||
type: 'oauth-input',
|
||||
serviceId: 'attio',
|
||||
mode: 'trigger',
|
||||
required: true,
|
||||
condition: { field: 'selectedTriggerId', value: triggerId },
|
||||
},
|
||||
{
|
||||
id: 'triggerSave',
|
||||
title: 'Save',
|
||||
type: 'trigger-save',
|
||||
mode: 'trigger',
|
||||
condition: { field: 'selectedTriggerId', value: triggerId },
|
||||
},
|
||||
{
|
||||
id: 'triggerInstructions',
|
||||
title: 'Setup Instructions',
|
||||
hideFromPreview: true,
|
||||
type: 'text',
|
||||
defaultValue: attioSetupInstructions(),
|
||||
id: 'webhookSecret',
|
||||
title: 'Webhook Secret',
|
||||
type: 'short-input',
|
||||
placeholder: 'Enter the webhook signing secret from Attio',
|
||||
description:
|
||||
'The signing secret from Attio used to verify webhook deliveries via HMAC-SHA256 signature',
|
||||
password: true,
|
||||
required: false,
|
||||
mode: 'trigger',
|
||||
condition: { field: 'selectedTriggerId', value: triggerId },
|
||||
},
|
||||
@@ -270,7 +257,7 @@ export function buildGenericWebhookOutputs(): Record<string, TriggerOutput> {
|
||||
/**
|
||||
* Maps trigger IDs to the exact Attio event type strings.
|
||||
*/
|
||||
export const TRIGGER_EVENT_MAP: Record<string, string[]> = {
|
||||
const TRIGGER_EVENT_MAP: Record<string, string[]> = {
|
||||
attio_record_created: ['record.created'],
|
||||
attio_record_updated: ['record.updated'],
|
||||
attio_record_deleted: ['record.deleted'],
|
||||
@@ -290,15 +277,6 @@ export const TRIGGER_EVENT_MAP: Record<string, string[]> = {
|
||||
attio_list_entry_deleted: ['list-entry.deleted'],
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the first event from an Attio webhook payload.
|
||||
* Attio wraps events in an `events` array: `{ webhook_id, events: [{ event_type, id, ... }] }`.
|
||||
*/
|
||||
export function getAttioEvent(body: Record<string, unknown>): Record<string, unknown> | undefined {
|
||||
const events = body.events as Array<Record<string, unknown>> | undefined
|
||||
return events?.[0]
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if an Attio webhook payload matches a trigger.
|
||||
*/
|
||||
@@ -307,8 +285,7 @@ export function isAttioPayloadMatch(triggerId: string, body: Record<string, unkn
|
||||
return true
|
||||
}
|
||||
|
||||
const event = getAttioEvent(body)
|
||||
const eventType = event?.event_type as string | undefined
|
||||
const eventType = body.event_type as string | undefined
|
||||
if (!eventType) {
|
||||
return false
|
||||
}
|
||||
@@ -316,146 +293,3 @@ export function isAttioPayloadMatch(triggerId: string, body: Record<string, unkn
|
||||
const acceptedEvents = TRIGGER_EVENT_MAP[triggerId]
|
||||
return acceptedEvents ? acceptedEvents.includes(eventType) : false
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts formatted data from an Attio record event payload.
|
||||
* Used for record.created, record.deleted triggers.
|
||||
*/
|
||||
export function extractAttioRecordData(body: Record<string, unknown>): Record<string, unknown> {
|
||||
const event = getAttioEvent(body) ?? {}
|
||||
const id = (event.id as Record<string, unknown>) ?? {}
|
||||
return {
|
||||
eventType: event.event_type ?? null,
|
||||
workspaceId: id.workspace_id ?? null,
|
||||
objectId: id.object_id ?? null,
|
||||
recordId: id.record_id ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts formatted data from an Attio record.updated event payload.
|
||||
*/
|
||||
export function extractAttioRecordUpdatedData(
|
||||
body: Record<string, unknown>
|
||||
): Record<string, unknown> {
|
||||
const event = getAttioEvent(body) ?? {}
|
||||
const id = (event.id as Record<string, unknown>) ?? {}
|
||||
return {
|
||||
eventType: event.event_type ?? null,
|
||||
workspaceId: id.workspace_id ?? null,
|
||||
objectId: id.object_id ?? null,
|
||||
recordId: id.record_id ?? null,
|
||||
attributeId: id.attribute_id ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts formatted data from an Attio record.merged event payload.
|
||||
*/
|
||||
export function extractAttioRecordMergedData(
|
||||
body: Record<string, unknown>
|
||||
): Record<string, unknown> {
|
||||
const event = getAttioEvent(body) ?? {}
|
||||
const id = (event.id as Record<string, unknown>) ?? {}
|
||||
return {
|
||||
eventType: event.event_type ?? null,
|
||||
workspaceId: id.workspace_id ?? null,
|
||||
objectId: id.object_id ?? null,
|
||||
recordId: id.record_id ?? null,
|
||||
duplicateObjectId: (event.duplicate_object_id as string) ?? null,
|
||||
duplicateRecordId: (event.duplicate_record_id as string) ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts formatted data from an Attio note event payload.
|
||||
*/
|
||||
export function extractAttioNoteData(body: Record<string, unknown>): Record<string, unknown> {
|
||||
const event = getAttioEvent(body) ?? {}
|
||||
const id = (event.id as Record<string, unknown>) ?? {}
|
||||
return {
|
||||
eventType: event.event_type ?? null,
|
||||
workspaceId: id.workspace_id ?? null,
|
||||
noteId: id.note_id ?? null,
|
||||
parentObjectId: (event.parent_object_id as string) ?? null,
|
||||
parentRecordId: (event.parent_record_id as string) ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts formatted data from an Attio task event payload.
|
||||
*/
|
||||
export function extractAttioTaskData(body: Record<string, unknown>): Record<string, unknown> {
|
||||
const event = getAttioEvent(body) ?? {}
|
||||
const id = (event.id as Record<string, unknown>) ?? {}
|
||||
return {
|
||||
eventType: event.event_type ?? null,
|
||||
workspaceId: id.workspace_id ?? null,
|
||||
taskId: id.task_id ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts formatted data from an Attio comment event payload.
|
||||
*/
|
||||
export function extractAttioCommentData(body: Record<string, unknown>): Record<string, unknown> {
|
||||
const event = getAttioEvent(body) ?? {}
|
||||
const id = (event.id as Record<string, unknown>) ?? {}
|
||||
return {
|
||||
eventType: event.event_type ?? null,
|
||||
workspaceId: id.workspace_id ?? null,
|
||||
threadId: (event.thread_id as string) ?? null,
|
||||
commentId: id.comment_id ?? null,
|
||||
objectId: (event.object_id as string) ?? null,
|
||||
recordId: (event.record_id as string) ?? null,
|
||||
listId: (event.list_id as string) ?? null,
|
||||
entryId: (event.entry_id as string) ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts formatted data from an Attio list-entry event payload.
|
||||
* Used for list-entry.created, list-entry.deleted triggers.
|
||||
*/
|
||||
export function extractAttioListEntryData(body: Record<string, unknown>): Record<string, unknown> {
|
||||
const event = getAttioEvent(body) ?? {}
|
||||
const id = (event.id as Record<string, unknown>) ?? {}
|
||||
return {
|
||||
eventType: event.event_type ?? null,
|
||||
workspaceId: id.workspace_id ?? null,
|
||||
listId: id.list_id ?? null,
|
||||
entryId: id.entry_id ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts formatted data from an Attio list-entry.updated event payload.
|
||||
*/
|
||||
export function extractAttioListEntryUpdatedData(
|
||||
body: Record<string, unknown>
|
||||
): Record<string, unknown> {
|
||||
const event = getAttioEvent(body) ?? {}
|
||||
const id = (event.id as Record<string, unknown>) ?? {}
|
||||
return {
|
||||
eventType: event.event_type ?? null,
|
||||
workspaceId: id.workspace_id ?? null,
|
||||
listId: id.list_id ?? null,
|
||||
entryId: id.entry_id ?? null,
|
||||
attributeId: id.attribute_id ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts formatted data from a generic Attio webhook payload.
|
||||
* Passes through the first event with camelCase field mapping.
|
||||
*/
|
||||
export function extractAttioGenericData(body: Record<string, unknown>): Record<string, unknown> {
|
||||
const event = getAttioEvent(body) ?? {}
|
||||
const id = (event.id as Record<string, unknown>) ?? {}
|
||||
return {
|
||||
eventType: event.event_type ?? null,
|
||||
id,
|
||||
parentObjectId: (event.parent_object_id as string) ?? null,
|
||||
parentRecordId: (event.parent_record_id as string) ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { AttioIcon } from '@/components/icons'
|
||||
import { buildAttioTriggerSubBlocks, buildGenericWebhookOutputs } from '@/triggers/attio/utils'
|
||||
import { buildTriggerSubBlocks } from '@/triggers'
|
||||
import {
|
||||
attioSetupInstructions,
|
||||
attioTriggerOptions,
|
||||
buildAttioExtraFields,
|
||||
buildGenericWebhookOutputs,
|
||||
} from '@/triggers/attio/utils'
|
||||
import type { TriggerConfig } from '@/triggers/types'
|
||||
|
||||
/**
|
||||
@@ -15,7 +21,12 @@ export const attioWebhookTrigger: TriggerConfig = {
|
||||
version: '1.0.0',
|
||||
icon: AttioIcon,
|
||||
|
||||
subBlocks: buildAttioTriggerSubBlocks('attio_webhook'),
|
||||
subBlocks: buildTriggerSubBlocks({
|
||||
triggerId: 'attio_webhook',
|
||||
triggerOptions: attioTriggerOptions,
|
||||
setupInstructions: attioSetupInstructions('All Events'),
|
||||
extraFields: buildAttioExtraFields('attio_webhook'),
|
||||
}),
|
||||
|
||||
outputs: buildGenericWebhookOutputs(),
|
||||
|
||||
|
||||
Reference in New Issue
Block a user