Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Add trigger subscription with pusher

haxziecfb5ad72328b
diff --git a/README.md b/README.md
index 35eae696d..bcb7767ee 100644
--- a/README.md
+++ b/README.md
@@ -51,5 +51,8 @@ What's not included from @composio/client
- [ ] CLI
- [ ] MCP
- [ ] Team Members
+- [ ] File uploads/user files
+- [ ] Trigger Subscriptions
+- [ ] Tests
These models can be still be accessed via the SDK explicitly by using the `@composio/client`.
\ No newline at end of file
diff --git a/packages/core/package.json b/packages/core/package.json
index 5526ae567..8e0df7881 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -18,7 +18,7 @@
"typescript": "^5.8.3"
},
"dependencies": {
- "@composio/client": "0.1.0-alpha.1",
+ "@composio/client": "0.1.0-alpha.7",
"zod": "^3.24.2"
}
}
diff --git a/packages/core/src/composio.ts b/packages/core/src/composio.ts
index b5fa9e11a..794672d57 100644
--- a/packages/core/src/composio.ts
+++ b/packages/core/src/composio.ts
@@ -18,7 +18,7 @@ import { checkForLatestVersionFromNPM } from "./utils/version";
export type ComposioConfig<TToolCollection, TTool, TToolset extends BaseComposioToolset<TToolCollection, TTool>> = {
apiKey?: string;
- baseUrl?: string;
+ baseURL?: string;
allowTracking?: boolean;
allowTracing?: boolean;
toolset?: TToolset;
@@ -79,7 +79,7 @@ export class Composio<TToolCollection, TTool, TToolset extends BaseComposioTools
constructor(config: ComposioConfig<TToolCollection, TTool, TToolset>) {
const { baseURL: baseURLParsed, apiKey: apiKeyParsed } = getSDKConfig(
- config?.baseUrl,
+ config?.baseURL,
config?.apiKey
);
@@ -97,6 +97,7 @@ export class Composio<TToolCollection, TTool, TToolset extends BaseComposioTools
baseURL: baseURLParsed,
});
+ this.client
/**
* Keep a reference to the config object.
* This is useful for creating a builder pattern, debugging and logging.
diff --git a/packages/core/src/models/Session.ts b/packages/core/src/models/Session.ts
new file mode 100644
index 000000000..148b32150
--- /dev/null
+++ b/packages/core/src/models/Session.ts
@@ -0,0 +1,21 @@
+import { SessionGetInfoResponse } from "@composio/client/resources/auth/session";
+import { InstrumentedInstance } from "../types/telemetry.types";
+import ComposioSDK from "@composio/client";
+
+
+export class Session implements InstrumentedInstance {
+ readonly FILE_NAME: string = "core/models/Session.ts";
+ private client: ComposioSDK;
+
+ constructor(client: ComposioSDK) {
+ this.client = client;
+ }
+
+ /**
+ * Get the active session info
+ * @returns {Promise<SessionGetInfoResponse>} Session info
+ */
+ async getInfo(): Promise<SessionGetInfoResponse> {
+ return this.client.auth.session.getInfo();
+ }
+}
\ No newline at end of file
diff --git a/packages/core/src/models/Triggers.ts b/packages/core/src/models/Triggers.ts
index 57a79d69a..05d200a00 100644
--- a/packages/core/src/models/Triggers.ts
+++ b/packages/core/src/models/Triggers.ts
@@ -11,8 +11,11 @@ import {
TriggersTypeRetrieveEnumResponse,
TriggersTypeRetrieveResponse,
} from "@composio/client/resources/index";
-import { TriggerStatusEnum } from "../types/triggers.types";
+import { TriggerStatusEnum, TriggerSubscribeParams } from "../types/triggers.types";
import { InstrumentedInstance } from "../types/telemetry.types";
+import { PusherUtils, TriggerData } from "../utils/pusher";
+import logger from "../utils/logger";
+import { Session } from "./Session";
@@ -162,4 +165,66 @@ export class Triggers implements InstrumentedInstance {
async listEnum(options?: RequestOptions): Promise<TriggersTypeRetrieveEnumResponse> {
return this.client.triggersTypes.retrieveEnum(options);
}
+
+ async subscribe(
+ fn: (data: TriggerData) => void,
+ filters: TriggerSubscribeParams = {}
+ ) {
+
+ if (!fn) throw new Error("Function is required for trigger subscription");
+
+ // @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");
+
+ await PusherUtils.getPusherClient(
+ this.client.baseURL,
+ this.client.apiKey
+ );
+
+ const shouldSendTrigger = (data: TriggerData) => {
+ if (Object.keys(filters).length === 0) return true;
+ else {
+ return (
+ (!filters.appName ||
+ data.appName.toLowerCase() === filters.appName.toLowerCase()) &&
+ (!filters.triggerId ||
+ data.metadata.id.toLowerCase() ===
+ filters.triggerId.toLowerCase()) &&
+ (!filters.connectionId ||
+ data.metadata.connectionId.toLowerCase() ===
+ filters.connectionId.toLowerCase()) &&
+ (!filters.triggerName ||
+ data.metadata.triggerName.toLowerCase() ===
+ filters.triggerName.toLowerCase()) &&
+ (!filters.entityId ||
+ data.metadata.connection.clientUniqueUserId.toLowerCase() ===
+ filters.entityId.toLowerCase()) &&
+ (!filters.integrationId ||
+ data.metadata.connection.integrationId.toLowerCase() ===
+ filters.integrationId.toLowerCase())
+ );
+ }
+ };
+
+ logger.debug("Subscribing to triggers", filters);
+ PusherUtils.triggerSubscribe(clientId, (data: TriggerData) => {
+ if (shouldSendTrigger(data)) {
+ fn(data);
+ }
+ });
+ }
+
+ 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);
+ }
}
diff --git a/packages/core/src/types/triggers.types.ts b/packages/core/src/types/triggers.types.ts
index 45eb6121b..8c8c39512 100644
--- a/packages/core/src/types/triggers.types.ts
+++ b/packages/core/src/types/triggers.types.ts
@@ -1 +1,14 @@
-export type TriggerStatusEnum = "enable" | "disable";
\ No newline at end of file
+import { z } from "zod";
+
+export type TriggerStatusEnum = "enable" | "disable";
+
+export const ZTriggerSubscribeParam = z.object({
+ appName: z.string().optional(),
+ triggerId: z.string().optional(),
+ connectionId: z.string().optional(),
+ integrationId: z.string().optional(),
+ triggerName: z.string().optional(),
+ triggerData: z.string().optional(),
+ entityId: z.string().optional(),
+});
+export type TriggerSubscribeParams = z.infer<typeof ZTriggerSubscribeParam>;
\ No newline at end of file
diff --git a/packages/core/src/utils/pusher.ts b/packages/core/src/utils/pusher.ts
new file mode 100644
index 000000000..62fbd0862
--- /dev/null
+++ b/packages/core/src/utils/pusher.ts
@@ -0,0 +1,164 @@
+import logger from "./logger";
+
+const PUSHER_KEY = process.env.CLIENT_PUSHER_KEY || "ff9f18c208855d77a152";
+const PUSHER_CLUSTER = "mt1";
+
+type Channel = {
+ subscribe: (channelName: string) => unknown;
+ unsubscribe: (channelName: string) => unknown;
+ bind: (
+ event: string,
+ callback: (data: Record<string, unknown>) => void
+ ) => unknown;
+};
+
+type PusherClient = {
+ subscribe: (channelName: string) => Channel;
+ unsubscribe: (channelName: string) => unknown;
+ bind: (
+ event: string,
+ callback: (data: Record<string, unknown>) => void
+ ) => unknown;
+};
+
+type TChunkedTriggerData = {
+ id: string;
+ index: number;
+ chunk: string;
+ final: boolean;
+};
+
+export type TriggerData = {
+ appName: string;
+ clientId: number;
+ payload: Record<string, unknown>;
+ originalPayload: Record<string, unknown>;
+ metadata: {
+ id: string;
+ connectionId: string;
+ triggerName: string;
+ triggerData: string;
+ triggerConfig: Record<string, unknown>;
+ connection: {
+ id: string;
+ integrationId: string;
+ clientUniqueUserId: string;
+ status: string;
+ };
+ };
+};
+
+export class PusherUtils {
+ static pusherClient: PusherClient;
+
+ static getPusherClient(baseURL: string, apiKey: string): PusherClient {
+ if (!PusherUtils.pusherClient) {
+ // Dynamic import not available, using require for now
+ // TODO: Update to use dynamic import when available
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const PusherClient = require("pusher-js");
+ PusherUtils.pusherClient = new PusherClient(PUSHER_KEY, {
+ cluster: PUSHER_CLUSTER,
+ channelAuthorization: {
+ endpoint: `${baseURL}/api/v1/client/auth/pusher_auth`,
+ headers: {
+ "x-api-key": apiKey,
+ },
+ transport: "ajax",
+ },
+ });
+ }
+ return PusherUtils.pusherClient;
+ }
+ /**
+ * Subscribes to a Pusher channel and binds an event to a callback function.
+ * @param {string} channelName - The name of the channel to subscribe to.
+ * @param {string} event - The event to bind to the channel.
+ * @param {(data: Record<string, unknown>) => void} fn - The callback function to execute when the event is triggered.
+ * @returns {PusherClient} The Pusher client instance.
+ */
+ static async subscribe(
+ channelName: string,
+ event: string,
+ fn: (data: Record<string, unknown>) => void
+ ): Promise<void> {
+ try {
+ await PusherUtils.pusherClient.subscribe(channelName).bind(event, fn);
+ } catch (error) {
+ logger.error(
+ `Error subscribing to ${channelName} with event ${event}: ${error}`
+ );
+ }
+ }
+
+ /**
+ * Unsubscribes from a Pusher channel.
+ * @param {string} channelName - The name of the channel to unsubscribe from.
+ * @returns {void}
+ */
+ static async unsubscribe(channelName: string): Promise<void> {
+ PusherUtils.pusherClient.unsubscribe(channelName);
+ }
+
+ /**
+ * Binds an event to a channel with support for chunked messages.
+ * @param {PusherClient} channel - The Pusher channel to bind the event to.
+ * @param {string} event - The event to bind to the channel.
+ * @param {(data: unknown) => void} callback - The callback function to execute when the event is triggered.
+ */
+ private static bindWithChunking(
+ channel: PusherClient,
+ event: string,
+ callback: (data: Record<string, unknown>) => void
+ ): void {
+ channel.bind(event, callback); // Allow normal unchunked events.
+
+ // Now the chunked variation. Allows arbitrarily long messages.
+ const events: {
+ [key: string]: { chunks: string[]; receivedFinal: boolean };
+ } = {};
+ channel.bind("chunked-" + event, (data) => {
+ const typedData = data as TChunkedTriggerData;
+ 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
+ ) {
+ callback(JSON.parse(ev.chunks.join("")));
+ delete events[typedData.id];
+ }
+ });
+ }
+
+ /**
+ * Subscribes to a trigger channel for a client and handles chunked data.
+ * @param {string} clientId - The unique identifier for the client subscribing to the events.
+ * @param {(data: TriggerData) => void} fn - The callback function to execute when trigger data is received.
+ */
+ static triggerSubscribe(
+ clientId: string,
+ fn: (data: TriggerData) => void
+ ): void {
+ const channel = PusherUtils.pusherClient.subscribe(
+ `private-${clientId}_triggers`
+ );
+ PusherUtils.bindWithChunking(
+ channel as PusherClient,
+ "trigger_to_client",
+ fn as (data: unknown) => void
+ );
+
+ logger.info(
+ `Subscribed to triggers. You should start receiving events now.`
+ );
+ }
+
+ static triggerUnsubscribe(clientId: string): void {
+ PusherUtils.pusherClient.unsubscribe(`${clientId}_triggers`);
+ }
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 209b17b42..884c33fa5 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -34,11 +34,8 @@ importers:
packages/core:
dependencies:
'@composio/client':
- specifier: 0.1.0-alpha.1
- version: 0.1.0-alpha.1
- '@composio/openai-toolset':
- specifier: workspace:^
- version: link:../toolsets/openai
+ specifier: 0.1.0-alpha.7
+ version: 0.1.0-alpha.7
zod:
specifier: ^3.24.2
version: 3.24.2
@@ -154,8 +151,8 @@ packages:
'@cloudflare/[email protected]':
resolution: {integrity: sha512-i37TX0Clp+MrPdXMBdvKZM7JghCrWD9GtG7E+8ANOAPmtZjUkZfEy9qq46IG3XlNpagPaWDkY3SgJ3s01gPxCw==}
- '@composio/[email protected]':
- resolution: {integrity: sha512-cWN3Kffl1zkJ9LVHXtIAZplyUP1fktNIXgPhKL9RMRrUlQyuwpA8k2so4nlxg4f1C77NZSM+9/gbNOLNRWx21g==}
+ '@composio/[email protected]':
+ resolution: {integrity: sha512-2KYo7mloXf6vplX+6cMjnuaS/Hia74HwPZd7/3RCehVptqTzaqgQFBEAGfnQ3zMBtTkLt+S7JQsZc9RE0SIMoA==}
'@emnapi/[email protected]':
resolution: {integrity: sha512-H+N/FqT07NmLmt6OFFtDfwe8PNygprzBikrEMyQfgqSmT0vzE515Pz7R8izwB9q/zsH/MA64AKoul3sA6/CzVg==}
@@ -1252,7 +1249,7 @@ snapshots:
'@cloudflare/[email protected]': {}
- '@composio/[email protected]': {}
+ '@composio/[email protected]': {}
'@emnapi/[email protected]':
dependencies: