Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
Update triggers to use the new PusherService class
haxzie72c6801199fa
diff --git a/docs/providers/custom.md b/docs/providers/custom.mdindex e3a8befc5..ab0dd836b 100644--- a/docs/providers/custom.md+++ b/docs/providers/custom.md@@ -75,13 +75,13 @@ type LangchainTool = {};// Define the collection type for your provider-type LangchainToolset = {+type LangchainToolCollection = {tools: LangchainTool[];executor: (tool: LangchainTool, input: Record<string, unknown>) => Promise<unknown>;};// Create the provider class-export class LangchainProvider extends BaseAgenticProvider<LangchainToolset, LangchainTool> {+export class LangchainProvider extends BaseAgenticProvider<LangchainToolCollection, LangchainTool> {// Define the provider name (used for telemetry)readonly name = 'langchain';@@ -98,7 +98,7 @@ export class LangchainProvider extends BaseAgenticProvider<LangchainToolset, Lan}// Implement the wrapTools method (note the executeToolFn parameter)- override wrapTools(tools: Tool[], executeToolFn: ExecuteToolFn): LangchainToolset {+ override wrapTools(tools: Tool[], executeToolFn: ExecuteToolFn): LangchainToolCollection {const langchainTools = tools.map(tool => this.wrapTool(tool, executeToolFn));return {@@ -110,7 +110,7 @@ export class LangchainProvider extends BaseAgenticProvider<LangchainToolset, Lan}// Add provider-specific methods- async createAgent(tools: LangchainToolset, model: any) {+ async createAgent(tools: LangchainToolCollection, model: any) {// Create a Langchain agent with the tools// This is just an example, the actual implementation would depend on the Langchain APIreturn {@@ -297,9 +297,9 @@ type LangChainTool = {call: (input: Record<string, unknown>) => Promise<any>;};-type LangChainToolset = LangChainTool[];+type LangChainToolCollection = LangChainTool[];-export class LangChainProvider extends BaseAgenticProvider<LangChainToolset, LangChainTool> {+export class LangChainProvider extends BaseAgenticProvider<LangChainToolCollection, LangChainTool> {readonly name = 'langchain';override wrapTool(tool: Tool, executeToolFn: ExecuteToolFn): LangChainTool {@@ -317,12 +317,12 @@ export class LangChainProvider extends BaseAgenticProvider<LangChainToolset, Lan};}- override wrapTools(tools: Tool[], executeToolFn: ExecuteToolFn): LangChainToolset {+ override wrapTools(tools: Tool[], executeToolFn: ExecuteToolFn): LangChainToolCollection {return tools.map(tool => this.wrapTool(tool, executeToolFn));}// LangChain-specific helper methods- createAgent(tools: LangChainToolset, model: any) {+ createAgent(tools: LangChainToolCollection, model: any) {// Implement LangChain agent creation// This is just a placeholder - the actual implementation would use the LangChain API}diff --git a/packages/core/src/errors/TriggerErrors.ts b/packages/core/src/errors/TriggerErrors.tsnew file mode 100644index 000000000..ec457d845--- /dev/null+++ b/packages/core/src/errors/TriggerErrors.ts@@ -0,0 +1,53 @@+import { ComposioError } from '@composio/client';++export const TriggerErrorCodes = {+ TRIGGER_FAILED_TO_GET_SDK_REALTIME_CREDENTIALS: 'TRIGGER_FAILED_TO_GET_SDK_REALTIME_CREDENTIALS',+ TRIGGER_FAILED_TO_CREATE_PUSHER_CLIENT: 'TRIGGER_FAILED_TO_CREATE_PUSHER_CLIENT',+ TRIGGER_FAILED_TO_SUBSCRIBE_TO_PUSHER_CHANNEL: 'TRIGGER_FAILED_TO_SUBSCRIBE_TO_PUSHER_CHANNEL',+ TRIGGER_FAILED_TO_UNSUBSCRIBE_FROM_PUSHER_CHANNEL:+ 'TRIGGER_FAILED_TO_UNSUBSCRIBE_FROM_PUSHER_CHANNEL',+} as const;++export class ComposioFailedToGetSDKRealtimeCredentialsError extends ComposioError {+ public name = 'ComposioFailedToGetSDKRealtimeCredentialsError';+ public code = TriggerErrorCodes.TRIGGER_FAILED_TO_GET_SDK_REALTIME_CREDENTIALS;+ public statusCode = 500;+ public possibleFixes = ['Please contact support.'];++ constructor(message: string, options?: ErrorOptions) {+ super(message, options);+ }+}++export class ComposioFailedToCreatePusherClientError extends ComposioError {+ public name = 'ComposioFailedToCreatePusherClientError';+ public code = TriggerErrorCodes.TRIGGER_FAILED_TO_CREATE_PUSHER_CLIENT;+ public statusCode = 500;+ public possibleFixes = ['Please contact support.'];++ constructor(message: string, options?: ErrorOptions) {+ super(message, options);+ }+}++export class ComposioFailedToSubscribeToPusherChannelError extends ComposioError {+ public name = 'ComposioFailedToSubscribeToPusherChannelError';+ public code = TriggerErrorCodes.TRIGGER_FAILED_TO_SUBSCRIBE_TO_PUSHER_CHANNEL;+ public statusCode = 500;+ public possibleFixes = ['Please contact support.'];++ constructor(message: string, options?: ErrorOptions) {+ super(message, options);+ }+}++export class ComposioFailedToUnsubscribeFromPusherChannelError extends ComposioError {+ public name = 'ComposioFailedToUnsubscribeFromPusherChannelError';+ public code = TriggerErrorCodes.TRIGGER_FAILED_TO_UNSUBSCRIBE_FROM_PUSHER_CHANNEL;+ public statusCode = 500;+ public possibleFixes = ['Please contact support.'];++ constructor(message: string, options?: ErrorOptions) {+ super(message, options);+ }+}diff --git a/packages/core/src/models/Triggers.ts b/packages/core/src/models/Triggers.tsindex d02bf87e6..279174f2e 100644--- a/packages/core/src/models/Triggers.ts+++ b/packages/core/src/models/Triggers.ts@@ -25,11 +25,11 @@ import {IncomingTriggerPayloadSchema,IncomingTriggerPayload,} from '../types/triggers.types';-import { PusherUtils, TriggerData } from '../utils/pusher';+import { TriggerData } from '../utils/pusher';import logger from '../utils/logger';-import { Session } from './Session';import { telemetry } from '../telemetry/Telemetry';import { ValidationError } from '../errors';+import { PusherService } from '../services/pusher/Pusher';/*** Trigger (Instance) class* /api/v3/trigger_instances@@ -37,9 +37,11 @@ import { ValidationError } from '../errors';*/export class Triggers {private client: ComposioClient;+ private pusherService: PusherService;constructor(client: ComposioClient) {this.client = client;+ this.pusherService = new PusherService(client);telemetry.instrument(this);}@@ -289,16 +291,6 @@ export class Triggers {});}- // @TODO: Get the client id from the backend- const session = new Session(this.client);- const sessionInfo = await session.getInfo();- const clientId = sessionInfo.project?.id;-- if (!clientId) throw new Error('Client ID not found');- if (!this.client.apiKey) throw new Error('API key not found');-- await PusherUtils.getPusherClient(this.client.baseURL, this.client.apiKey);-/*** Applies compound filters to the trigger data* @param data data to apply filters to@@ -381,10 +373,12 @@ export class Triggers {return true;};- logger.debug('Subscribing to triggers', JSON.stringify(filters, null, 2));- PusherUtils.triggerSubscribe(clientId, (data: TriggerData) => {- logger.debug('Received trigger data', JSON.stringify(data, null, 2));-+ logger.debug('π Subscribing to triggers with filters: ', JSON.stringify(filters, null, 2));+ this.pusherService.subscribe((_data: Record<string, unknown>) => {+ logger.debug('Received trigger data', JSON.stringify(_data, null, 2));+ // @TODO: This is a temporary fix to get the trigger data+ // ideally we should have a type for the trigger data+ const data = _data as TriggerData;const parsedData = IncomingTriggerPayloadSchema.safeParse({id: data.metadata.id,clientId: String(data.clientId),@@ -436,12 +430,6 @@ export class Triggers {* ```*/async unsubscribe() {- const session = new Session(this.client);- const sessionInfo = await session.getInfo();- const clientId = sessionInfo.project?.id;-- if (!clientId) throw new Error('Client ID not found');-- PusherUtils.triggerUnsubscribe(clientId);+ await this.pusherService.unsubscribe();}}diff --git a/packages/core/src/services/internal/InternalService.ts b/packages/core/src/services/internal/InternalService.tsnew file mode 100644index 000000000..352f38401--- /dev/null+++ b/packages/core/src/services/internal/InternalService.ts@@ -0,0 +1,44 @@+/**+ * @internal+ * This service is used to get the SDK realtime credentials.+ * It is used to get the Pusher key and project ID for the SDK realtime credentials.+ * These are the endpoints which are not exposed to the public via the client SDKs.+ */+import ComposioClitent from '@composio/client';+import {+ ComposioSDKRealtimeCredentialsResponse,+ SDKRealtimeCredentialsResponse,+ SDKRealtimeCredentialsResponseSchema,+} from './InternalService.types';+import { ValidationError } from '../../errors';+const SDK_REALTIME_CREDENTIALS_ENDPOINT = '/v3/internal/sdk/realtime/credentials';++export class InternalService {+ constructor(private readonly client: ComposioClitent) {+ this.client = client;+ }++ /**+ * Get the SDK realtime credentials+ * @returns {SDKRealtimeCredentialsResponse} The SDK realtime credentials+ */+ async getSDKRealtimeCredentials(): Promise<SDKRealtimeCredentialsResponse> {+ const response = await this.client.request<ComposioSDKRealtimeCredentialsResponse>({+ method: 'get',+ path: SDK_REALTIME_CREDENTIALS_ENDPOINT,+ });++ const parsedResponse = SDKRealtimeCredentialsResponseSchema.safeParse({+ pusherKey: response.pusher_key,+ projectId: response.project_id,+ });++ if (!parsedResponse.success) {+ throw new ValidationError(`Failed to parse SDK realtime credentials`, {+ cause: parsedResponse.error,+ });+ }++ return parsedResponse.data;+ }+}diff --git a/packages/core/src/services/internal/InternalService.types.ts b/packages/core/src/services/internal/InternalService.types.tsnew file mode 100644index 000000000..7e50603b5--- /dev/null+++ b/packages/core/src/services/internal/InternalService.types.ts@@ -0,0 +1,13 @@+import { z } from 'zod';++export interface ComposioSDKRealtimeCredentialsResponse {+ pusher_key: string;+ project_id: string;+}++export const SDKRealtimeCredentialsResponseSchema = z.object({+ pusherKey: z.string().describe('The Pusher key'),+ pusherCluster: z.string().describe('The Pusher cluster'),+ projectId: z.string().describe('The project ID'),+});+export type SDKRealtimeCredentialsResponse = z.infer<typeof SDKRealtimeCredentialsResponseSchema>;diff --git a/packages/core/src/services/pusher/Pusher.ts b/packages/core/src/services/pusher/Pusher.tsnew file mode 100644index 000000000..faaba0d20--- /dev/null+++ b/packages/core/src/services/pusher/Pusher.ts@@ -0,0 +1,225 @@+import ComposioClient from '@composio/client';+import { PusherClient, TChunkedTriggerData } from '../../types/pusher.types';+import { InternalService } from '../internal/InternalService';+import { SDKRealtimeCredentialsResponse } from '../internal/InternalService.types';+import {+ ComposioFailedToCreatePusherClientError,+ ComposioFailedToGetSDKRealtimeCredentialsError,+ ComposioFailedToSubscribeToPusherChannelError,+} from '../../errors/TriggerErrors';+import logger from '../../utils/logger';+import { telemetry } from '../../telemetry/Telemetry';++export class PusherService {+ // these values are set via the Apollo API `/internal/sdk/realtime/credentials` endpoint+ private clientId!: string;+ private pusherKey!: string;+ private pusherCluster!: string;+ private pusherChannel!: string;+ // these details are set via the client SDK+ private pusherBaseURL!: string;+ private apiKey!: string;+ private pusherClient!: PusherClient;+ private composioClient!: ComposioClient;++ constructor(client: ComposioClient) {+ this.composioClient = client;+ this.pusherBaseURL = client.baseURL;+ this.apiKey = client.apiKey ?? process.env.COMPOSIO_API_KEY ?? '';+ telemetry.instrument(this);+ }++ /**+ * Creates a Pusher client+ *+ * This method is called when the Pusher client is first used.+ * It will fetch the SDK realtime credentials from the Apollo API and create a Pusher client.+ */+ private async getPusherClient() {+ if (!this.pusherClient) {+ const internalService = new InternalService(this.composioClient);+ let sdkRealtimeCredentials: SDKRealtimeCredentialsResponse;+ try {+ sdkRealtimeCredentials = await internalService.getSDKRealtimeCredentials();+ } catch (error) {+ throw new ComposioFailedToGetSDKRealtimeCredentialsError(+ 'Failed to get SDK realtime credentials',+ {+ cause: error,+ }+ );+ }++ this.clientId = sdkRealtimeCredentials.projectId;+ this.pusherKey = sdkRealtimeCredentials.pusherKey;+ this.pusherCluster = sdkRealtimeCredentials.pusherCluster;+ this.pusherChannel = `private-${this.clientId}_triggers`;++ logger.debug(`[PusherService] Creating Pusher client for client ID: ${this.clientId}`);++ // create the Pusher client+ try {+ const { default: Pusher } = await import('pusher-js');+ this.pusherClient = new Pusher(this.pusherKey, {+ cluster: this.pusherCluster,+ channelAuthorization: {+ endpoint: `${this.pusherBaseURL}/api/v1/client/auth/pusher_auth`,+ headers: {+ 'x-api-key': this.apiKey,+ },+ transport: 'ajax',+ },+ });+ } catch (error) {+ throw new ComposioFailedToCreatePusherClientError('Failed to create Pusher client', {+ cause: error,+ });+ }+ }++ return this.pusherClient;+ }++ /**+ * Binds a chunked event to a Pusher client+ *+ *+ * @param channel - The Pusher client to bind the event to+ * @param event - The event to bind to+ * @param callback - The function to call when the event is received+ */+ private bindWithChunking(+ channel: PusherClient,+ event: string,+ callback: (data: Record<string, unknown>) => void+ ): void {+ try {+ channel.bind(event, callback);++ // Now the chunked variation. Allows arbitrarily long messages.+ const events: {+ [key: string]: { chunks: string[]; receivedFinal: boolean };+ } = {};++ channel.bind('chunked-' + event, data => {+ try {+ const typedData = data as TChunkedTriggerData;++ // Validate chunked data+ if (+ !typedData ||+ typeof typedData.id !== 'string' ||+ typeof typedData.index !== 'number'+ ) {+ throw new Error('Invalid chunked trigger data format');+ }++ if (!events.hasOwnProperty(typedData.id)) {+ events[typedData.id] = { chunks: [], receivedFinal: false };+ }++ const ev = events[typedData.id];+ ev.chunks[typedData.index] = typedData.chunk;++ if (typedData.final) ev.receivedFinal = true;++ if (ev.receivedFinal && ev.chunks.length === Object.keys(ev.chunks).length) {+ try {+ const parsedData = JSON.parse(ev.chunks.join(''));+ callback(parsedData);+ } catch (parseError: unknown) {+ const errorMessage =+ parseError instanceof Error ? parseError.message : String(parseError);+ logger.error('Failed to parse chunked data:', errorMessage);+ } finally {+ delete events[typedData.id];+ }+ }+ } catch (error: unknown) {+ const errorMessage = error instanceof Error ? error.message : String(error);+ logger.error('Error processing chunked trigger data:', errorMessage);+ // Clean up the event data to prevent memory leaks+ if (data && typeof data === 'object' && 'id' in data) {+ delete events[data.id as string];+ }+ }+ });+ } catch (error: unknown) {+ const errorMessage = error instanceof Error ? error.message : String(error);+ logger.error('Failed to bind chunked events:', error);+ throw new Error(`Failed to bind chunked events: ${errorMessage}`);+ }+ }++ /**+ * Subscribes to pusher to receive events from the server+ *+ * This method is used to subscribe to a Pusher channel.+ * It will create a Pusher client if it doesn't exist.+ *+ * @param channelName - The name of the Pusher channel to subscribe to+ * @param event - The event to subscribe to+ * @param fn - The function to call when the event is received+ */+ async subscribe(fn: (data: Record<string, unknown>) => void) {+ try {+ logger.debug(`[PusherService] Subscribing to channel: ${this.pusherChannel}`);+ const pusherClient = await this.getPusherClient();+ const channel = await pusherClient.subscribe(this.pusherChannel);++ // add subscription error handling+ channel.bind('pusher:subscription_error', (data: Record<string, unknown>) => {+ const error = data.error ? String(data.error) : 'Unknown subscription error';+ throw new ComposioFailedToSubscribeToPusherChannelError(`Trigger subscription error`, {+ cause: error,+ });+ });++ // wrap the callback to handle errors+ const safeCallback = (data: Record<string, unknown>) => {+ try {+ fn(data);+ } catch (error: unknown) {+ const errorMessage = error instanceof Error ? error.message : String(error);+ logger.error('β Error in trigger callback:', errorMessage);+ // don't throw here to prevent breaking the subscription+ }+ };++ this.bindWithChunking(channel as PusherClient, 'trigger_to_client', safeCallback);++ logger.info(`β Subscribed to triggers. You should start receiving events now.`);+ } catch (error) {+ throw new ComposioFailedToSubscribeToPusherChannelError(+ 'Failed to subscribe to Pusher channel',+ {+ cause: error,+ }+ );+ }+ }++ /**+ * Unsubscribes from a Pusher channel+ *+ * This method is used to unsubscribe from a Pusher channel.+ * It will create a Pusher client if it doesn't exist.+ *+ * @param channelName - The name of the Pusher channel to unsubscribe from+ */+ async unsubscribe() {+ try {+ logger.debug(`[PusherService] Unsubscribing from channel: ${this.pusherChannel}`);+ const pusherClient = await this.getPusherClient();+ await pusherClient.unsubscribe(this.pusherChannel);+ logger.info(`β Unsubscribed from triggers.`);+ } catch (error) {+ throw new ComposioFailedToSubscribeToPusherChannelError(+ 'Failed to unsubscribe from Pusher channel',+ {+ cause: error,+ }+ );+ }+ }+}diff --git a/packages/core/src/types/pusher.types.ts b/packages/core/src/types/pusher.types.tsnew file mode 100644index 000000000..e0fc097ac--- /dev/null+++ b/packages/core/src/types/pusher.types.ts@@ -0,0 +1,18 @@+export interface PusherClient {+ subscribe: (channelName: string) => PusherChannel;+ unsubscribe: (channelName: string) => void;+ bind: (event: string, callback: (data: Record<string, unknown>) => void) => void;+}++export interface PusherChannel {+ subscribe: (channelName: string) => unknown;+ unsubscribe: (channelName: string) => void;+ bind: (event: string, callback: (data: Record<string, unknown>) => void) => void;+}++export type TChunkedTriggerData = {+ id: string;+ index: number;+ chunk: string;+ final: boolean;+};diff --git a/packages/wrappers/.gitkeep b/packages/wrappers/.gitkeepdeleted file mode 100644index e69de29bb..000000000diff --git a/packages/wrappers/README.md b/packages/wrappers/README.mddeleted file mode 100644index 1cc6dd75b..000000000--- a/packages/wrappers/README.md+++ /dev/null@@ -1,154 +0,0 @@-# Composio Wrappers--> **Note:** This is a work in progress. The wrapper system is under active development and may change in future releases.--## Overview--Composio Wrappers provide runtime-specific implementations of Composio Core functionality. These wrappers adapt the core functionality to work in different environments such as:--- Browser environments-- Edge runtimes-- Serverless environments-- Node.js environments-- Mobile environments--## Available Interfaces--### Core Components--- **@composio/core**: The main package containing core functionality and interfaces-- **BaseComposioProvider**: Abstract base class for creating custom providers--### Telemetry--Composio provides built-in telemetry capabilities that can be used in your wrappers:--- **Telemetry**: Core telemetry implementation-- **BaseTelemetryTransport**: Base class for creating custom telemetry transports--### Models--The following models are available for extension:--- **Tools**: Manage and interact with tools-- **Toolkits**: Handle collections of tools-- **Triggers**: Manage event triggers and subscriptions-- **AuthConfigs**: Handle authentication configurations-- **ConnectedAccounts**: Manage connected accounts-- **Session**: Handle session management--## Creating a Runtime Wrapper--To create a runtime-specific wrapper, you need to implement the core functionality while adapting it to your target environment:--```typescript-import { Composio } from '@composio/core';--class BrowserRuntimeWrapper {- private composio: Composio;-- constructor(config: ComposioConfig) {- // Initialize with browser-specific configurations- this.composio = new Composio({- ...config,- // Add browser-specific configurations- allowTracking: true,- telemetryTransport: new BrowserTelemetryTransport(),- });- }-- // Implement browser-specific methods- async initialize() {- // Browser-specific initialization- }-- // Override or extend core methods as needed- async getTools() {- // Browser-specific implementation- return this.composio.tools.get();- }-}-```--## Configuration--Wrappers can be configured using the `ComposioConfig` interface with runtime-specific options:--```typescript-const config = {- apiKey: 'your-api-key',- baseURL: 'https://api.composio.dev',- allowTracking: true,- allowTracing: true,- // Runtime-specific configurations- runtime: 'browser',- userId: 'user-id',- connectedAccountIds: {},- telemetryTransport: new RuntimeSpecificTelemetryTransport(),-};-```--## Best Practices--1. **Environment Detection**: Implement proper environment detection for your target runtime-2. **Telemetry Integration**: Implement telemetry that works in your target environment-3. **Error Handling**: Implement runtime-specific error handling-4. **Type Safety**: Use TypeScript for better type safety and developer experience-5. **Documentation**: Document your wrapper's functionality and usage-6. **Polyfills**: Include necessary polyfills for your target environment-7. **Size Optimization**: Optimize bundle size for your target environment--## Example: Browser Wrapper--Here's a simple example of creating a browser-specific wrapper:--```typescript-import { Composio } from '@composio/core';--class BrowserWrapper {- private composio: Composio;-- constructor(config: ComposioConfig) {- // Initialize with browser-specific configurations- this.composio = new Composio({- ...config,- runtime: 'browser',- telemetryTransport: new BrowserTelemetryTransport(),- });- }-- async initialize() {- // Check if running in browser- if (typeof window === 'undefined') {- throw new Error('This wrapper is only for browser environments');- }-- // Initialize browser-specific features- await this.initializeBrowserFeatures();- }-- private async initializeBrowserFeatures() {- // Initialize browser-specific features- // e.g., service workers, indexedDB, etc.- }-- // Browser-specific implementation of core methods- async getTools() {- // Add browser-specific caching or other optimizations- return this.composio.tools.get();- }-}-```--## Contributing--We welcome contributions to the wrapper system. Please follow these guidelines:--1. Create a new package in the `packages/wrappers` directory-2. Follow the existing code structure and patterns-3. Include proper documentation and tests-4. Submit a pull request with a clear description of your changes--## License--This project is licensed under the ISC License.