Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Mirrored from https://github.com/Camo67/composio.git
Synced Nov 23, 01:45 UTC
Update triggers to use the new PusherService class
haxzie committed
May 27, 2025 at 18:10 UTC
72c6801199fa9989f86fc1ea2a6671fadf1d5081
9 files changed
+372
-185
docs/providers/custom.md
+8
-8
@@ -75,13 +75,13 @@ type LangchainTool = {
75
};
76
77
// Define the collection type for your provider
78
-type LangchainToolset = {
78
+type LangchainToolCollection = {
79
tools: LangchainTool[];
80
executor: (tool: LangchainTool, input: Record<string, unknown>) => Promise<unknown>;
81
};
82
83
// Create the provider class
84
-export class LangchainProvider extends BaseAgenticProvider<LangchainToolset, LangchainTool> {
84
+export class LangchainProvider extends BaseAgenticProvider<LangchainToolCollection, LangchainTool> {
85
// Define the provider name (used for telemetry)
86
readonly name = 'langchain';
87
@@ -98,7 +98,7 @@ export class LangchainProvider extends BaseAgenticProvider<LangchainToolset, Lan
98
}
99
100
// Implement the wrapTools method (note the executeToolFn parameter)
101
- override wrapTools(tools: Tool[], executeToolFn: ExecuteToolFn): LangchainToolset {
101
+ override wrapTools(tools: Tool[], executeToolFn: ExecuteToolFn): LangchainToolCollection {
102
const langchainTools = tools.map(tool => this.wrapTool(tool, executeToolFn));
103
104
return {
@@ -110,7 +110,7 @@ export class LangchainProvider extends BaseAgenticProvider<LangchainToolset, Lan
110
}
111
112
// Add provider-specific methods
113
- async createAgent(tools: LangchainToolset, model: any) {
113
+ async createAgent(tools: LangchainToolCollection, model: any) {
114
// Create a Langchain agent with the tools
115
// This is just an example, the actual implementation would depend on the Langchain API
116
return {
@@ -297,9 +297,9 @@ type LangChainTool = {
297
call: (input: Record<string, unknown>) => Promise<any>;
298
};
299
300
-type LangChainToolset = LangChainTool[];
300
+type LangChainToolCollection = LangChainTool[];
301
302
-export class LangChainProvider extends BaseAgenticProvider<LangChainToolset, LangChainTool> {
302
+export class LangChainProvider extends BaseAgenticProvider<LangChainToolCollection, LangChainTool> {
303
readonly name = 'langchain';
304
305
override wrapTool(tool: Tool, executeToolFn: ExecuteToolFn): LangChainTool {
@@ -317,12 +317,12 @@ export class LangChainProvider extends BaseAgenticProvider<LangChainToolset, Lan
317
};
318
}
319
320
- override wrapTools(tools: Tool[], executeToolFn: ExecuteToolFn): LangChainToolset {
320
+ override wrapTools(tools: Tool[], executeToolFn: ExecuteToolFn): LangChainToolCollection {
321
return tools.map(tool => this.wrapTool(tool, executeToolFn));
322
}
323
324
// LangChain-specific helper methods
325
- createAgent(tools: LangChainToolset, model: any) {
325
+ createAgent(tools: LangChainToolCollection, model: any) {
326
// Implement LangChain agent creation
327
// This is just a placeholder - the actual implementation would use the LangChain API
328
}
packages/core/src/errors/TriggerErrors.ts
new
+53
@@ -0,0 +1,53 @@
1
+import { ComposioError } from '@composio/client';
2
+
3
+export const TriggerErrorCodes = {
4
+ TRIGGER_FAILED_TO_GET_SDK_REALTIME_CREDENTIALS: 'TRIGGER_FAILED_TO_GET_SDK_REALTIME_CREDENTIALS',
5
+ TRIGGER_FAILED_TO_CREATE_PUSHER_CLIENT: 'TRIGGER_FAILED_TO_CREATE_PUSHER_CLIENT',
6
+ TRIGGER_FAILED_TO_SUBSCRIBE_TO_PUSHER_CHANNEL: 'TRIGGER_FAILED_TO_SUBSCRIBE_TO_PUSHER_CHANNEL',
7
+ TRIGGER_FAILED_TO_UNSUBSCRIBE_FROM_PUSHER_CHANNEL:
8
+ 'TRIGGER_FAILED_TO_UNSUBSCRIBE_FROM_PUSHER_CHANNEL',
9
+} as const;
10
+
11
+export class ComposioFailedToGetSDKRealtimeCredentialsError extends ComposioError {
12
+ public name = 'ComposioFailedToGetSDKRealtimeCredentialsError';
13
+ public code = TriggerErrorCodes.TRIGGER_FAILED_TO_GET_SDK_REALTIME_CREDENTIALS;
14
+ public statusCode = 500;
15
+ public possibleFixes = ['Please contact support.'];
16
+
17
+ constructor(message: string, options?: ErrorOptions) {
18
+ super(message, options);
19
+ }
20
+}
21
+
22
+export class ComposioFailedToCreatePusherClientError extends ComposioError {
23
+ public name = 'ComposioFailedToCreatePusherClientError';
24
+ public code = TriggerErrorCodes.TRIGGER_FAILED_TO_CREATE_PUSHER_CLIENT;
25
+ public statusCode = 500;
26
+ public possibleFixes = ['Please contact support.'];
27
+
28
+ constructor(message: string, options?: ErrorOptions) {
29
+ super(message, options);
30
+ }
31
+}
32
+
33
+export class ComposioFailedToSubscribeToPusherChannelError extends ComposioError {
34
+ public name = 'ComposioFailedToSubscribeToPusherChannelError';
35
+ public code = TriggerErrorCodes.TRIGGER_FAILED_TO_SUBSCRIBE_TO_PUSHER_CHANNEL;
36
+ public statusCode = 500;
37
+ public possibleFixes = ['Please contact support.'];
38
+
39
+ constructor(message: string, options?: ErrorOptions) {
40
+ super(message, options);
41
+ }
42
+}
43
+
44
+export class ComposioFailedToUnsubscribeFromPusherChannelError extends ComposioError {
45
+ public name = 'ComposioFailedToUnsubscribeFromPusherChannelError';
46
+ public code = TriggerErrorCodes.TRIGGER_FAILED_TO_UNSUBSCRIBE_FROM_PUSHER_CHANNEL;
47
+ public statusCode = 500;
48
+ public possibleFixes = ['Please contact support.'];
49
+
50
+ constructor(message: string, options?: ErrorOptions) {
51
+ super(message, options);
52
+ }
53
+}
packages/core/src/models/Triggers.ts
+11
-23
@@ -25,11 +25,11 @@ import {
25
IncomingTriggerPayloadSchema,
26
IncomingTriggerPayload,
27
} from '../types/triggers.types';
28
-import { PusherUtils, TriggerData } from '../utils/pusher';
28
+import { TriggerData } from '../utils/pusher';
29
import logger from '../utils/logger';
30
-import { Session } from './Session';
30
import { telemetry } from '../telemetry/Telemetry';
31
import { ValidationError } from '../errors';
32
+import { PusherService } from '../services/pusher/Pusher';
33
/**
34
* Trigger (Instance) class
35
* /api/v3/trigger_instances
@@ -37,9 +37,11 @@ import { ValidationError } from '../errors';
37
*/
38
export class Triggers {
39
private client: ComposioClient;
40
+ private pusherService: PusherService;
41
42
constructor(client: ComposioClient) {
43
this.client = client;
44
+ this.pusherService = new PusherService(client);
45
telemetry.instrument(this);
46
}
47
@@ -289,16 +291,6 @@ export class Triggers {
291
});
292
}
293
292
- // @TODO: Get the client id from the backend
293
- const session = new Session(this.client);
294
- const sessionInfo = await session.getInfo();
295
- const clientId = sessionInfo.project?.id;
296
-
297
- if (!clientId) throw new Error('Client ID not found');
298
- if (!this.client.apiKey) throw new Error('API key not found');
299
-
300
- await PusherUtils.getPusherClient(this.client.baseURL, this.client.apiKey);
301
-
294
/**
295
* Applies compound filters to the trigger data
296
* @param data data to apply filters to
@@ -381,10 +373,12 @@ export class Triggers {
373
return true;
374
};
375
384
- logger.debug('Subscribing to triggers', JSON.stringify(filters, null, 2));
385
- PusherUtils.triggerSubscribe(clientId, (data: TriggerData) => {
386
- logger.debug('Received trigger data', JSON.stringify(data, null, 2));
387
-
376
+ logger.debug('🔄 Subscribing to triggers with filters: ', JSON.stringify(filters, null, 2));
377
+ this.pusherService.subscribe((_data: Record<string, unknown>) => {
378
+ logger.debug('Received trigger data', JSON.stringify(_data, null, 2));
379
+ // @TODO: This is a temporary fix to get the trigger data
380
+ // ideally we should have a type for the trigger data
381
+ const data = _data as TriggerData;
382
const parsedData = IncomingTriggerPayloadSchema.safeParse({
383
id: data.metadata.id,
384
clientId: String(data.clientId),
@@ -436,12 +430,6 @@ export class Triggers {
430
* ```
431
*/
432
async unsubscribe() {
439
- const session = new Session(this.client);
440
- const sessionInfo = await session.getInfo();
441
- const clientId = sessionInfo.project?.id;
442
-
443
- if (!clientId) throw new Error('Client ID not found');
444
-
445
- PusherUtils.triggerUnsubscribe(clientId);
433
+ await this.pusherService.unsubscribe();
434
}
435
}
packages/core/src/services/internal/InternalService.ts
new
+44
@@ -0,0 +1,44 @@
1
+/**
2
+ * @internal
3
+ * This service is used to get the SDK realtime credentials.
4
+ * It is used to get the Pusher key and project ID for the SDK realtime credentials.
5
+ * These are the endpoints which are not exposed to the public via the client SDKs.
6
+ */
7
+import ComposioClitent from '@composio/client';
8
+import {
9
+ ComposioSDKRealtimeCredentialsResponse,
10
+ SDKRealtimeCredentialsResponse,
11
+ SDKRealtimeCredentialsResponseSchema,
12
+} from './InternalService.types';
13
+import { ValidationError } from '../../errors';
14
+const SDK_REALTIME_CREDENTIALS_ENDPOINT = '/v3/internal/sdk/realtime/credentials';
15
+
16
+export class InternalService {
17
+ constructor(private readonly client: ComposioClitent) {
18
+ this.client = client;
19
+ }
20
+
21
+ /**
22
+ * Get the SDK realtime credentials
23
+ * @returns {SDKRealtimeCredentialsResponse} The SDK realtime credentials
24
+ */
25
+ async getSDKRealtimeCredentials(): Promise<SDKRealtimeCredentialsResponse> {
26
+ const response = await this.client.request<ComposioSDKRealtimeCredentialsResponse>({
27
+ method: 'get',
28
+ path: SDK_REALTIME_CREDENTIALS_ENDPOINT,
29
+ });
30
+
31
+ const parsedResponse = SDKRealtimeCredentialsResponseSchema.safeParse({
32
+ pusherKey: response.pusher_key,
33
+ projectId: response.project_id,
34
+ });
35
+
36
+ if (!parsedResponse.success) {
37
+ throw new ValidationError(`Failed to parse SDK realtime credentials`, {
38
+ cause: parsedResponse.error,
39
+ });
40
+ }
41
+
42
+ return parsedResponse.data;
43
+ }
44
+}
packages/core/src/services/internal/InternalService.types.ts
new
+13
@@ -0,0 +1,13 @@
1
+import { z } from 'zod';
2
+
3
+export interface ComposioSDKRealtimeCredentialsResponse {
4
+ pusher_key: string;
5
+ project_id: string;
6
+}
7
+
8
+export const SDKRealtimeCredentialsResponseSchema = z.object({
9
+ pusherKey: z.string().describe('The Pusher key'),
10
+ pusherCluster: z.string().describe('The Pusher cluster'),
11
+ projectId: z.string().describe('The project ID'),
12
+});
13
+export type SDKRealtimeCredentialsResponse = z.infer<typeof SDKRealtimeCredentialsResponseSchema>;
packages/core/src/services/pusher/Pusher.ts
new
+225
@@ -0,0 +1,225 @@
1
+import ComposioClient from '@composio/client';
2
+import { PusherClient, TChunkedTriggerData } from '../../types/pusher.types';
3
+import { InternalService } from '../internal/InternalService';
4
+import { SDKRealtimeCredentialsResponse } from '../internal/InternalService.types';
5
+import {
6
+ ComposioFailedToCreatePusherClientError,
7
+ ComposioFailedToGetSDKRealtimeCredentialsError,
8
+ ComposioFailedToSubscribeToPusherChannelError,
9
+} from '../../errors/TriggerErrors';
10
+import logger from '../../utils/logger';
11
+import { telemetry } from '../../telemetry/Telemetry';
12
+
13
+export class PusherService {
14
+ // these values are set via the Apollo API `/internal/sdk/realtime/credentials` endpoint
15
+ private clientId!: string;
16
+ private pusherKey!: string;
17
+ private pusherCluster!: string;
18
+ private pusherChannel!: string;
19
+ // these details are set via the client SDK
20
+ private pusherBaseURL!: string;
21
+ private apiKey!: string;
22
+ private pusherClient!: PusherClient;
23
+ private composioClient!: ComposioClient;
24
+
25
+ constructor(client: ComposioClient) {
26
+ this.composioClient = client;
27
+ this.pusherBaseURL = client.baseURL;
28
+ this.apiKey = client.apiKey ?? process.env.COMPOSIO_API_KEY ?? '';
29
+ telemetry.instrument(this);
30
+ }
31
+
32
+ /**
33
+ * Creates a Pusher client
34
+ *
35
+ * This method is called when the Pusher client is first used.
36
+ * It will fetch the SDK realtime credentials from the Apollo API and create a Pusher client.
37
+ */
38
+ private async getPusherClient() {
39
+ if (!this.pusherClient) {
40
+ const internalService = new InternalService(this.composioClient);
41
+ let sdkRealtimeCredentials: SDKRealtimeCredentialsResponse;
42
+ try {
43
+ sdkRealtimeCredentials = await internalService.getSDKRealtimeCredentials();
44
+ } catch (error) {
45
+ throw new ComposioFailedToGetSDKRealtimeCredentialsError(
46
+ 'Failed to get SDK realtime credentials',
47
+ {
48
+ cause: error,
49
+ }
50
+ );
51
+ }
52
+
53
+ this.clientId = sdkRealtimeCredentials.projectId;
54
+ this.pusherKey = sdkRealtimeCredentials.pusherKey;
55
+ this.pusherCluster = sdkRealtimeCredentials.pusherCluster;
56
+ this.pusherChannel = `private-${this.clientId}_triggers`;
57
+
58
+ logger.debug(`[PusherService] Creating Pusher client for client ID: ${this.clientId}`);
59
+
60
+ // create the Pusher client
61
+ try {
62
+ const { default: Pusher } = await import('pusher-js');
63
+ this.pusherClient = new Pusher(this.pusherKey, {
64
+ cluster: this.pusherCluster,
65
+ channelAuthorization: {
66
+ endpoint: `${this.pusherBaseURL}/api/v1/client/auth/pusher_auth`,
67
+ headers: {
68
+ 'x-api-key': this.apiKey,
69
+ },
70
+ transport: 'ajax',
71
+ },
72
+ });
73
+ } catch (error) {
74
+ throw new ComposioFailedToCreatePusherClientError('Failed to create Pusher client', {
75
+ cause: error,
76
+ });
77
+ }
78
+ }
79
+
80
+ return this.pusherClient;
81
+ }
82
+
83
+ /**
84
+ * Binds a chunked event to a Pusher client
85
+ *
86
+ *
87
+ * @param channel - The Pusher client to bind the event to
88
+ * @param event - The event to bind to
89
+ * @param callback - The function to call when the event is received
90
+ */
91
+ private bindWithChunking(
92
+ channel: PusherClient,
93
+ event: string,
94
+ callback: (data: Record<string, unknown>) => void
95
+ ): void {
96
+ try {
97
+ channel.bind(event, callback);
98
+
99
+ // Now the chunked variation. Allows arbitrarily long messages.
100
+ const events: {
101
+ [key: string]: { chunks: string[]; receivedFinal: boolean };
102
+ } = {};
103
+
104
+ channel.bind('chunked-' + event, data => {
105
+ try {
106
+ const typedData = data as TChunkedTriggerData;
107
+
108
+ // Validate chunked data
109
+ if (
110
+ !typedData ||
111
+ typeof typedData.id !== 'string' ||
112
+ typeof typedData.index !== 'number'
113
+ ) {
114
+ throw new Error('Invalid chunked trigger data format');
115
+ }
116
+
117
+ if (!events.hasOwnProperty(typedData.id)) {
118
+ events[typedData.id] = { chunks: [], receivedFinal: false };
119
+ }
120
+
121
+ const ev = events[typedData.id];
122
+ ev.chunks[typedData.index] = typedData.chunk;
123
+
124
+ if (typedData.final) ev.receivedFinal = true;
125
+
126
+ if (ev.receivedFinal && ev.chunks.length === Object.keys(ev.chunks).length) {
127
+ try {
128
+ const parsedData = JSON.parse(ev.chunks.join(''));
129
+ callback(parsedData);
130
+ } catch (parseError: unknown) {
131
+ const errorMessage =
132
+ parseError instanceof Error ? parseError.message : String(parseError);
133
+ logger.error('Failed to parse chunked data:', errorMessage);
134
+ } finally {
135
+ delete events[typedData.id];
136
+ }
137
+ }
138
+ } catch (error: unknown) {
139
+ const errorMessage = error instanceof Error ? error.message : String(error);
140
+ logger.error('Error processing chunked trigger data:', errorMessage);
141
+ // Clean up the event data to prevent memory leaks
142
+ if (data && typeof data === 'object' && 'id' in data) {
143
+ delete events[data.id as string];
144
+ }
145
+ }
146
+ });
147
+ } catch (error: unknown) {
148
+ const errorMessage = error instanceof Error ? error.message : String(error);
149
+ logger.error('Failed to bind chunked events:', error);
150
+ throw new Error(`Failed to bind chunked events: ${errorMessage}`);
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Subscribes to pusher to receive events from the server
156
+ *
157
+ * This method is used to subscribe to a Pusher channel.
158
+ * It will create a Pusher client if it doesn't exist.
159
+ *
160
+ * @param channelName - The name of the Pusher channel to subscribe to
161
+ * @param event - The event to subscribe to
162
+ * @param fn - The function to call when the event is received
163
+ */
164
+ async subscribe(fn: (data: Record<string, unknown>) => void) {
165
+ try {
166
+ logger.debug(`[PusherService] Subscribing to channel: ${this.pusherChannel}`);
167
+ const pusherClient = await this.getPusherClient();
168
+ const channel = await pusherClient.subscribe(this.pusherChannel);
169
+
170
+ // add subscription error handling
171
+ channel.bind('pusher:subscription_error', (data: Record<string, unknown>) => {
172
+ const error = data.error ? String(data.error) : 'Unknown subscription error';
173
+ throw new ComposioFailedToSubscribeToPusherChannelError(`Trigger subscription error`, {
174
+ cause: error,
175
+ });
176
+ });
177
+
178
+ // wrap the callback to handle errors
179
+ const safeCallback = (data: Record<string, unknown>) => {
180
+ try {
181
+ fn(data);
182
+ } catch (error: unknown) {
183
+ const errorMessage = error instanceof Error ? error.message : String(error);
184
+ logger.error('❌ Error in trigger callback:', errorMessage);
185
+ // don't throw here to prevent breaking the subscription
186
+ }
187
+ };
188
+
189
+ this.bindWithChunking(channel as PusherClient, 'trigger_to_client', safeCallback);
190
+
191
+ logger.info(`✅ Subscribed to triggers. You should start receiving events now.`);
192
+ } catch (error) {
193
+ throw new ComposioFailedToSubscribeToPusherChannelError(
194
+ 'Failed to subscribe to Pusher channel',
195
+ {
196
+ cause: error,
197
+ }
198
+ );
199
+ }
200
+ }
201
+
202
+ /**
203
+ * Unsubscribes from a Pusher channel
204
+ *
205
+ * This method is used to unsubscribe from a Pusher channel.
206
+ * It will create a Pusher client if it doesn't exist.
207
+ *
208
+ * @param channelName - The name of the Pusher channel to unsubscribe from
209
+ */
210
+ async unsubscribe() {
211
+ try {
212
+ logger.debug(`[PusherService] Unsubscribing from channel: ${this.pusherChannel}`);
213
+ const pusherClient = await this.getPusherClient();
214
+ await pusherClient.unsubscribe(this.pusherChannel);
215
+ logger.info(`✅ Unsubscribed from triggers.`);
216
+ } catch (error) {
217
+ throw new ComposioFailedToSubscribeToPusherChannelError(
218
+ 'Failed to unsubscribe from Pusher channel',
219
+ {
220
+ cause: error,
221
+ }
222
+ );
223
+ }
224
+ }
225
+}
packages/core/src/types/pusher.types.ts
new
+18
@@ -0,0 +1,18 @@
1
+export interface PusherClient {
2
+ subscribe: (channelName: string) => PusherChannel;
3
+ unsubscribe: (channelName: string) => void;
4
+ bind: (event: string, callback: (data: Record<string, unknown>) => void) => void;
5
+}
6
+
7
+export interface PusherChannel {
8
+ subscribe: (channelName: string) => unknown;
9
+ unsubscribe: (channelName: string) => void;
10
+ bind: (event: string, callback: (data: Record<string, unknown>) => void) => void;
11
+}
12
+
13
+export type TChunkedTriggerData = {
14
+ id: string;
15
+ index: number;
16
+ chunk: string;
17
+ final: boolean;
18
+};
packages/wrappers/.gitkeep
packages/wrappers/README.md
deleted
-154
@@ -1,154 +0,0 @@
1
-# Composio Wrappers
2
-
3
-> **Note:** This is a work in progress. The wrapper system is under active development and may change in future releases.
4
-
5
-## Overview
6
-
7
-Composio Wrappers provide runtime-specific implementations of Composio Core functionality. These wrappers adapt the core functionality to work in different environments such as:
8
-
9
-- Browser environments
10
-- Edge runtimes
11
-- Serverless environments
12
-- Node.js environments
13
-- Mobile environments
14
-
15
-## Available Interfaces
16
-
17
-### Core Components
18
-
19
-- **@composio/core**: The main package containing core functionality and interfaces
20
-- **BaseComposioProvider**: Abstract base class for creating custom providers
21
-
22
-### Telemetry
23
-
24
-Composio provides built-in telemetry capabilities that can be used in your wrappers:
25
-
26
-- **Telemetry**: Core telemetry implementation
27
-- **BaseTelemetryTransport**: Base class for creating custom telemetry transports
28
-
29
-### Models
30
-
31
-The following models are available for extension:
32
-
33
-- **Tools**: Manage and interact with tools
34
-- **Toolkits**: Handle collections of tools
35
-- **Triggers**: Manage event triggers and subscriptions
36
-- **AuthConfigs**: Handle authentication configurations
37
-- **ConnectedAccounts**: Manage connected accounts
38
-- **Session**: Handle session management
39
-
40
-## Creating a Runtime Wrapper
41
-
42
-To create a runtime-specific wrapper, you need to implement the core functionality while adapting it to your target environment:
43
-
44
-```typescript
45
-import { Composio } from '@composio/core';
46
-
47
-class BrowserRuntimeWrapper {
48
- private composio: Composio;
49
-
50
- constructor(config: ComposioConfig) {
51
- // Initialize with browser-specific configurations
52
- this.composio = new Composio({
53
- ...config,
54
- // Add browser-specific configurations
55
- allowTracking: true,
56
- telemetryTransport: new BrowserTelemetryTransport(),
57
- });
58
- }
59
-
60
- // Implement browser-specific methods
61
- async initialize() {
62
- // Browser-specific initialization
63
- }
64
-
65
- // Override or extend core methods as needed
66
- async getTools() {
67
- // Browser-specific implementation
68
- return this.composio.tools.get();
69
- }
70
-}
71
-```
72
-
73
-## Configuration
74
-
75
-Wrappers can be configured using the `ComposioConfig` interface with runtime-specific options:
76
-
77
-```typescript
78
-const config = {
79
- apiKey: 'your-api-key',
80
- baseURL: 'https://api.composio.dev',
81
- allowTracking: true,
82
- allowTracing: true,
83
- // Runtime-specific configurations
84
- runtime: 'browser',
85
- userId: 'user-id',
86
- connectedAccountIds: {},
87
- telemetryTransport: new RuntimeSpecificTelemetryTransport(),
88
-};
89
-```
90
-
91
-## Best Practices
92
-
93
-1. **Environment Detection**: Implement proper environment detection for your target runtime
94
-2. **Telemetry Integration**: Implement telemetry that works in your target environment
95
-3. **Error Handling**: Implement runtime-specific error handling
96
-4. **Type Safety**: Use TypeScript for better type safety and developer experience
97
-5. **Documentation**: Document your wrapper's functionality and usage
98
-6. **Polyfills**: Include necessary polyfills for your target environment
99
-7. **Size Optimization**: Optimize bundle size for your target environment
100
-
101
-## Example: Browser Wrapper
102
-
103
-Here's a simple example of creating a browser-specific wrapper:
104
-
105
-```typescript
106
-import { Composio } from '@composio/core';
107
-
108
-class BrowserWrapper {
109
- private composio: Composio;
110
-
111
- constructor(config: ComposioConfig) {
112
- // Initialize with browser-specific configurations
113
- this.composio = new Composio({
114
- ...config,
115
- runtime: 'browser',
116
- telemetryTransport: new BrowserTelemetryTransport(),
117
- });
118
- }
119
-
120
- async initialize() {
121
- // Check if running in browser
122
- if (typeof window === 'undefined') {
123
- throw new Error('This wrapper is only for browser environments');
124
- }
125
-
126
- // Initialize browser-specific features
127
- await this.initializeBrowserFeatures();
128
- }
129
-
130
- private async initializeBrowserFeatures() {
131
- // Initialize browser-specific features
132
- // e.g., service workers, indexedDB, etc.
133
- }
134
-
135
- // Browser-specific implementation of core methods
136
- async getTools() {
137
- // Add browser-specific caching or other optimizations
138
- return this.composio.tools.get();
139
- }
140
-}
141
-```
142
-
143
-## Contributing
144
-
145
-We welcome contributions to the wrapper system. Please follow these guidelines:
146
-
147
-1. Create a new package in the `packages/wrappers` directory
148
-2. Follow the existing code structure and patterns
149
-3. Include proper documentation and tests
150
-4. Submit a pull request with a clear description of your changes
151
-
152
-## License
153
-
154
-This project is licensed under the ISC License.