@devries-cameron20 / composio-1 / commits / 28446d5a7
Fork 0

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

feat(cli): add realtime triggers listen with forward and file options

Add `composio triggers listen` with realtime channel auth, filtering, raw JSON output, and optional webhook forwarding/output file sinks so trigger events can be inspected and integrated locally with signed verification headers. Co-authored-by: Cursor <cursoragent@cursor.com>

haxzie committed Feb 23, 2026 at 16:29 UTC 28446d5a79603e048bdb4bd380721ee04eed19b3
15 files changed +1216 -44
pnpm-lock.yaml
+69 -14
@@ -680,16 +680,16 @@ importers:
680 version: link:../../packages/providers/llamaindex
681 '@llamaindex/openai':
682 specifier: ^0.4.20
683 - version: 0.4.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(ws@8.19.0)(zod@4.3.6)
683 + version: 0.4.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(ws@8.19.0)(zod@3.25.76)
684 '@llamaindex/workflow':
685 specifier: ^1.1.24
686 - version: 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)
686 + version: 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)
687 dotenv:
688 specifier: ^16.4.1
689 version: 16.6.1
690 llamaindex:
691 specifier: ^0.12.0
692 - version: 0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6)
692 + version: 0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@3.25.76)
693 devDependencies:
694 '@types/bun':
695 specifier: ^1.2.9
@@ -1059,6 +1059,9 @@ importers:
1059 picocolors:
1060 specifier: ^1.1.1
1061 version: 1.1.1
1062 + pusher-js:
1063 + specifier: ^8.4.0
1064 + version: 8.4.0
1065 semver:
1066 specifier: ^7.7.2
1067 version: 7.7.4
@@ -1286,7 +1289,7 @@ importers:
1289 dependencies:
1290 llamaindex:
1291 specifier: ^0.12.0
1289 - version: 0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6)
1292 + version: 0.12.1(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6)
1293 devDependencies:
1294 '@composio/core':
1295 specifier: workspace:*
@@ -7548,26 +7551,43 @@ snapshots:
7551 tree-sitter: 0.22.4
7552 web-tree-sitter: 0.24.7
7553
7551 - '@llamaindex/openai@0.4.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(ws@8.19.0)(zod@4.3.6)':
7554 + '@llamaindex/openai@0.4.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(ws@8.19.0)(zod@3.25.76)':
7555 dependencies:
7556 '@llamaindex/core': 0.6.22
7557 '@llamaindex/env': 0.1.30
7555 - openai: 5.23.2(ws@8.19.0)(zod@4.3.6)
7558 + openai: 5.23.2(ws@8.19.0)(zod@3.25.76)
7559 transitivePeerDependencies:
7560 - ws
7561 - zod
7562
7560 - '@llamaindex/workflow-core@1.3.3(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)':
7563 + '@llamaindex/workflow-core@1.3.3(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)':
7564 optionalDependencies:
7562 - '@modelcontextprotocol/sdk': 1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6)
7565 + '@modelcontextprotocol/sdk': 1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76)
7566 hono: 4.11.9
7567 + zod: 3.25.76
7568 +
7569 + '@llamaindex/workflow-core@1.3.3(zod@4.3.6)':
7570 + optionalDependencies:
7571 zod: 4.3.6
7572
7566 - '@llamaindex/workflow@1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)':
7573 + '@llamaindex/workflow@1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)':
7574 dependencies:
7575 '@llamaindex/core': 0.6.22
7576 '@llamaindex/env': 0.1.30
7570 - '@llamaindex/workflow-core': 1.3.3(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)
7577 + '@llamaindex/workflow-core': 1.3.3(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)
7578 + transitivePeerDependencies:
7579 + - '@modelcontextprotocol/sdk'
7580 + - hono
7581 + - next
7582 + - p-retry
7583 + - rxjs
7584 + - zod
7585 +
7586 + '@llamaindex/workflow@1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(zod@4.3.6)':
7587 + dependencies:
7588 + '@llamaindex/core': 0.6.22
7589 + '@llamaindex/env': 0.1.30
7590 + '@llamaindex/workflow-core': 1.3.3(zod@4.3.6)
7591 transitivePeerDependencies:
7592 - '@modelcontextprotocol/sdk'
7593 - hono
@@ -8552,6 +8572,14 @@ snapshots:
8572 optionalDependencies:
8573 vite: 7.3.1(@types/node@22.19.11)(tsx@4.21.0)(yaml@2.8.2)
8574
8575 + '@vitest/mocker@3.2.4(vite@7.3.1(@types/node@24.10.13)(tsx@4.21.0)(yaml@2.8.2))':
8576 + dependencies:
8577 + '@vitest/spy': 3.2.4
8578 + estree-walker: 3.0.3
8579 + magic-string: 0.30.21
8580 + optionalDependencies:
8581 + vite: 7.3.1(@types/node@24.10.13)(tsx@4.21.0)(yaml@2.8.2)
8582 +
8583 '@vitest/pretty-format@3.2.4':
8584 dependencies:
8585 tinyrainbow: 2.0.0
@@ -8581,7 +8609,7 @@ snapshots:
8609 sirv: 3.0.2
8610 tinyglobby: 0.2.15
8611 tinyrainbow: 2.0.0
8584 - vitest: 3.2.4(@types/node@22.19.11)(@vitest/ui@3.2.4)(tsx@4.21.0)(yaml@2.8.2)
8612 + vitest: 3.2.4(@types/node@24.10.13)(@vitest/ui@3.2.4)(tsx@4.21.0)(yaml@2.8.2)
8613
8614 '@vitest/utils@3.2.4':
8615 dependencies:
@@ -9948,12 +9976,34 @@ snapshots:
9976 rfdc: 1.4.1
9977 wrap-ansi: 9.0.2
9978
9951 - llamaindex@0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6):
9979 + llamaindex@0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@3.25.76):
9980 + dependencies:
9981 + '@llamaindex/core': 0.6.22
9982 + '@llamaindex/env': 0.1.30
9983 + '@llamaindex/node-parser': 2.0.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)
9984 + '@llamaindex/workflow': 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)
9985 + '@types/lodash': 4.17.23
9986 + '@types/node': 24.10.13
9987 + lodash: 4.17.23
9988 + magic-bytes.js: 1.13.0
9989 + transitivePeerDependencies:
9990 + - '@huggingface/transformers'
9991 + - '@modelcontextprotocol/sdk'
9992 + - gpt-tokenizer
9993 + - hono
9994 + - next
9995 + - p-retry
9996 + - rxjs
9997 + - tree-sitter
9998 + - web-tree-sitter
9999 + - zod
10000 +
10001 + llamaindex@0.12.1(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6):
10002 dependencies:
10003 '@llamaindex/core': 0.6.22
10004 '@llamaindex/env': 0.1.30
10005 '@llamaindex/node-parser': 2.0.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)
9956 - '@llamaindex/workflow': 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)
10006 + '@llamaindex/workflow': 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(zod@4.3.6)
10007 '@types/lodash': 4.17.23
10008 '@types/node': 24.10.13
10009 lodash: 4.17.23
@@ -10233,6 +10283,11 @@ snapshots:
10283 is-inside-container: 1.0.0
10284 wsl-utils: 0.1.0
10285
10286 + openai@5.23.2(ws@8.19.0)(zod@3.25.76):
10287 + optionalDependencies:
10288 + ws: 8.19.0
10289 + zod: 3.25.76
10290 +
10291 openai@5.23.2(ws@8.19.0)(zod@4.3.6):
10292 optionalDependencies:
10293 ws: 8.19.0
@@ -11330,7 +11385,7 @@ snapshots:
11385 dependencies:
11386 '@types/chai': 5.2.3
11387 '@vitest/expect': 3.2.4
11333 - '@vitest/mocker': 3.2.4(vite@7.3.1(@types/node@22.19.11)(tsx@4.21.0)(yaml@2.8.2))
11388 + '@vitest/mocker': 3.2.4(vite@7.3.1(@types/node@24.10.13)(tsx@4.21.0)(yaml@2.8.2))
11389 '@vitest/pretty-format': 3.2.4
11390 '@vitest/runner': 3.2.4
11391 '@vitest/snapshot': 3.2.4
ts/packages/cli/package.json
+1
@@ -78,6 +78,7 @@
78 "open": "^10.2.0",
79 "openapi-typescript": "^7.8.0",
80 "picocolors": "^1.1.1",
81 + "pusher-js": "^8.4.0",
82 "semver": "^7.7.2",
83 "source-map-js": "^1.2.1",
84 "superjson": "^2.2.2",
ts/packages/cli/src/bin.ts
+7
@@ -21,6 +21,7 @@ import { JsPackageManagerDetector } from 'src/services/js-package-manager-detect
21 import { ComposioUserContextLive as _ComposioUserContextLive } from 'src/services/user-context';
22 import { UpgradeBinary } from 'src/services/upgrade-binary';
23 import { TerminalUILive } from 'src/services/terminal-ui';
24 +import { TriggersRealtime } from 'src/services/triggers-realtime';
25
26 /**
27 * Concrete Effect layer compositions for the Composio CLI runtime.
@@ -65,6 +66,11 @@ export const UpgradeBinaryLive = Layer.provide(
66 Layer.mergeAll(BunFileSystem.layer, FetchHttpClient.layer)
67 ) satisfies RequiredLayer;
68
69 +export const TriggersRealtimeLive = Layer.provide(
70 + TriggersRealtime.Default,
71 + Layer.mergeAll(BunFileSystem.layer, NodeOs.Default)
72 +) satisfies RequiredLayer;
73 +
74 const layers = Layer.mergeAll(
75 CliConfigLive.pipe(Layer.provide(ConfigLive)),
76 NodeOs.Default,
@@ -75,6 +81,7 @@ const layers = Layer.mergeAll(
81 ComposioToolkitsRepositoryCachedLive, // Use the cached layer instead of the regular one
82 EnvLangDetector.Default,
83 JsPackageManagerDetector.Default,
84 + TriggersRealtimeLive,
85 BunContext.layer,
86 BunFileSystem.layer,
87 TerminalUILive,
ts/packages/cli/src/commands/index.ts
+2
@@ -15,6 +15,7 @@ import { toolkitsCmd } from './toolkits/toolkits.cmd';
15 import { toolsCmd } from './tools/tools.cmd';
16 import { authConfigsCmd } from './auth-configs/auth-configs.cmd';
17 import { connectedAccountsCmd } from './connected-accounts/connected-accounts.cmd';
18 +import { triggersCmd } from './triggers/triggers.cmd';
19
20 const $cmd = $defaultCmd.pipe(
21 Command.withSubcommands([
@@ -30,6 +31,7 @@ const $cmd = $defaultCmd.pipe(
31 toolsCmd,
32 authConfigsCmd,
33 connectedAccountsCmd,
34 + triggersCmd,
35 ])
36 );
37
ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts new
+304
@@ -0,0 +1,304 @@
1 +import { Command, Options } from '@effect/cli';
2 +import { Deferred, Effect, Option, Runtime } from 'effect';
3 +import path from 'node:path';
4 +import { promises as fs } from 'node:fs';
5 +import { requireAuth } from 'src/effects/require-auth';
6 +import { TerminalUI } from 'src/services/terminal-ui';
7 +import { TriggersRealtime } from 'src/services/triggers-realtime';
8 +import { matchesTriggerListenFilters } from '../filter';
9 +import { formatTriggerListenSummary } from '../format';
10 +import { parseTriggerListenEvent } from '../parse';
11 +import type { TriggerListenFilters } from '../types';
12 +
13 +const toolkits = Options.text('toolkits').pipe(
14 + Options.withDescription(
15 + 'Filter by toolkit slugs, comma-separated (e.g. "gmail" or "gmail,slack")'
16 + ),
17 + Options.optional
18 +);
19 +
20 +const triggerId = Options.text('trigger-id').pipe(
21 + Options.withDescription('Filter by trigger id'),
22 + Options.optional
23 +);
24 +
25 +const connectedAccountId = Options.text('connected-account-id').pipe(
26 + Options.withDescription('Filter by connected account id'),
27 + Options.optional
28 +);
29 +
30 +const triggerSlug = Options.text('trigger-slug').pipe(
31 + Options.withDescription(
32 + 'Filter by trigger slug, comma-separated (e.g. "GMAIL_NEW_GMAIL_MESSAGE")'
33 + ),
34 + Options.optional
35 +);
36 +
37 +const userId = Options.text('user-id').pipe(
38 + Options.withDescription('Filter by user id'),
39 + Options.optional
40 +);
41 +
42 +const json = Options.boolean('json').pipe(
43 + Options.withDefault(false),
44 + Options.withDescription('Show raw event payload as JSON in interactive mode')
45 +);
46 +
47 +const maxEvents = Options.integer('max-events').pipe(
48 + Options.withDescription('Stop after receiving N matching events'),
49 + Options.optional
50 +);
51 +
52 +const forward = Options.text('forward').pipe(
53 + Options.withDescription(
54 + 'Forward each matching event to the given URL (signed with COMPOSIO_WEBHOOK_SECRET)'
55 + ),
56 + Options.optional
57 +);
58 +
59 +const out = Options.text('out').pipe(
60 + Options.withDescription('Append each matching event to this file'),
61 + Options.optional
62 +);
63 +
64 +const parseCsv = (value: string): ReadonlyArray<string> =>
65 + value
66 + .split(',')
67 + .map(item => item.trim())
68 + .filter(Boolean);
69 +
70 +const randomUUID = () => crypto.randomUUID();
71 +
72 +const signWebhookPayload = async ({
73 + secret,
74 + webhookId,
75 + webhookTimestamp,
76 + payload,
77 +}: {
78 + secret: string;
79 + webhookId: string;
80 + webhookTimestamp: string;
81 + payload: string;
82 +}) => {
83 + const toSign = `${webhookId}.${webhookTimestamp}.${payload}`;
84 + const key = await crypto.subtle.importKey(
85 + 'raw',
86 + new TextEncoder().encode(secret),
87 + { name: 'HMAC', hash: 'SHA-256' },
88 + false,
89 + ['sign']
90 + );
91 + const signature = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(toSign));
92 + const bytes = new Uint8Array(signature);
93 + const digest = btoa(String.fromCharCode(...bytes));
94 + return `v1,${digest}`;
95 +};
96 +
97 +const detectWebhookPayloadVersion = (eventData: Record<string, unknown>): 'V1' | 'V2' | 'V3' => {
98 + if (
99 + typeof eventData.id === 'string' &&
100 + typeof eventData.type === 'string' &&
101 + typeof eventData.timestamp === 'string' &&
102 + typeof eventData.metadata === 'object' &&
103 + eventData.metadata !== null &&
104 + typeof eventData.data === 'object' &&
105 + eventData.data !== null
106 + ) {
107 + return 'V3';
108 + }
109 +
110 + if (
111 + typeof eventData.type === 'string' &&
112 + typeof eventData.timestamp === 'string' &&
113 + typeof eventData.log_id === 'string' &&
114 + typeof eventData.data === 'object' &&
115 + eventData.data !== null
116 + ) {
117 + return 'V2';
118 + }
119 +
120 + return 'V1';
121 +};
122 +
123 +export const triggersCmd$Listen = Command.make(
124 + 'listen',
125 + {
126 + toolkits,
127 + triggerId,
128 + connectedAccountId,
129 + triggerSlug,
130 + userId,
131 + json,
132 + maxEvents,
133 + forward,
134 + out,
135 + },
136 + ({
137 + toolkits,
138 + triggerId,
139 + connectedAccountId,
140 + triggerSlug,
141 + userId,
142 + json,
143 + maxEvents,
144 + forward,
145 + out,
146 + }) =>
147 + Effect.gen(function* () {
148 + if (!(yield* requireAuth)) return;
149 +
150 + const ui = yield* TerminalUI;
151 + const realtime = yield* TriggersRealtime;
152 + const runtime = yield* Effect.runtime<never>();
153 + const forwardUrl = Option.getOrUndefined(forward);
154 + const generatedWebhookSecret = `composio-forward-secret-${randomUUID()}`;
155 + const webhookSecret = process.env.COMPOSIO_WEBHOOK_SECRET ?? generatedWebhookSecret;
156 + const outputFilePathOption = Option.getOrUndefined(out);
157 + const outputFilePath = outputFilePathOption ? path.resolve(outputFilePathOption) : undefined;
158 +
159 + if (outputFilePath) {
160 + // Ensure output directory exists before listening.
161 + yield* Effect.tryPromise({
162 + try: async () => {
163 + await fs.mkdir(path.dirname(outputFilePath), { recursive: true });
164 + },
165 + catch: error => new Error(`Failed to prepare output file directory: ${String(error)}`),
166 + }).pipe(
167 + Effect.catchAll(error =>
168 + Effect.gen(function* () {
169 + yield* ui.log.error(String(error));
170 + return yield* Effect.fail(error);
171 + })
172 + )
173 + );
174 + }
175 +
176 + const filters: TriggerListenFilters = {
177 + toolkits: Option.isSome(toolkits) ? parseCsv(toolkits.value) : undefined,
178 + triggerId: Option.getOrUndefined(triggerId),
179 + connectedAccountId: Option.getOrUndefined(connectedAccountId),
180 + triggerSlug: Option.isSome(triggerSlug) ? parseCsv(triggerSlug.value) : undefined,
181 + userId: Option.getOrUndefined(userId),
182 + };
183 +
184 + const maxEventsLimit = Option.getOrUndefined(maxEvents);
185 + const stopWhenDone = yield* Deferred.make<void>();
186 + let matchingEvents = 0;
187 +
188 + yield* ui.intro('composio triggers listen');
189 + if (forwardUrl) {
190 + if (process.env.COMPOSIO_WEBHOOK_SECRET) {
191 + yield* ui.note(
192 + `Forward URL: ${forwardUrl}\nSigning secret: ${webhookSecret}`,
193 + 'Forwarding'
194 + );
195 + } else {
196 + yield* ui.log.warn(
197 + 'No COMPOSIO_WEBHOOK_SECRET found. Generating a signing secret for this session.'
198 + );
199 + yield* ui.note(
200 + `Forward URL: ${forwardUrl}\nGenerated signing secret: ${webhookSecret}`,
201 + 'Forwarding'
202 + );
203 + }
204 + }
205 + yield* ui.log.info('Listening for realtime trigger events. Press Ctrl+C to stop.');
206 + if (outputFilePath) {
207 + yield* ui.log.info(`Writing matching events to: ${outputFilePath}`);
208 + }
209 + if (forwardUrl) {
210 + yield* ui.log.info(`Forwarding matching events to: ${forwardUrl}`);
211 + }
212 +
213 + if (maxEventsLimit !== undefined) {
214 + yield* ui.log.info(`Auto-stop after ${maxEventsLimit} matching events.`);
215 + }
216 +
217 + const onEvent = (eventData: Record<string, unknown>) => {
218 + Runtime.runFork(runtime)(
219 + Effect.gen(function* () {
220 + const parsed = parseTriggerListenEvent(eventData);
221 + if (!matchesTriggerListenFilters(filters, parsed)) {
222 + return;
223 + }
224 +
225 + matchingEvents += 1;
226 + yield* ui.note(formatTriggerListenSummary(parsed), `Event #${matchingEvents}`);
227 +
228 + if (json) {
229 + yield* ui.log.message(JSON.stringify(eventData, null, 2));
230 + } else {
231 + yield* ui.log.message(JSON.stringify(parsed.payload, null, 2));
232 + }
233 + yield* ui.output(JSON.stringify(eventData));
234 +
235 + const payloadForForwarding = JSON.stringify(eventData);
236 + const logLine = `${payloadForForwarding}\n`;
237 +
238 + if (outputFilePath) {
239 + yield* Effect.tryPromise({
240 + try: () => fs.appendFile(outputFilePath, logLine, 'utf8'),
241 + catch: error => new Error(`Failed writing to ${outputFilePath}: ${String(error)}`),
242 + }).pipe(Effect.catchAll(error => ui.log.warn(String(error))));
243 + }
244 +
245 + if (forwardUrl && webhookSecret) {
246 + const webhookId =
247 + typeof eventData.id === 'string' && eventData.id.length > 0
248 + ? eventData.id
249 + : randomUUID();
250 + const webhookTimestamp = `${Math.floor(Date.now() / 1000)}`;
251 + const webhookSignature = yield* Effect.tryPromise(() =>
252 + signWebhookPayload({
253 + secret: webhookSecret,
254 + webhookId,
255 + webhookTimestamp,
256 + payload: payloadForForwarding,
257 + })
258 + );
259 + const webhookVersion = detectWebhookPayloadVersion(eventData);
260 +
261 + yield* Effect.tryPromise({
262 + try: async () => {
263 + const response = await fetch(forwardUrl, {
264 + method: 'POST',
265 + headers: {
266 + 'content-type': 'application/json',
267 + 'webhook-id': webhookId,
268 + 'webhook-timestamp': webhookTimestamp,
269 + 'webhook-signature': webhookSignature,
270 + 'x-composio-webhook-version': webhookVersion,
271 + },
272 + body: payloadForForwarding,
273 + });
274 + if (!response.ok) {
275 + throw new Error(`Forwarding failed with HTTP ${response.status}`);
276 + }
277 + },
278 + catch: error =>
279 + new Error(`Failed forwarding event to ${forwardUrl}: ${String(error)}`),
280 + }).pipe(Effect.catchAll(error => ui.log.warn(String(error))));
281 + }
282 +
283 + if (maxEventsLimit !== undefined && matchingEvents >= maxEventsLimit) {
284 + yield* Deferred.succeed(stopWhenDone, undefined).pipe(Effect.ignore);
285 + }
286 + })
287 + );
288 + };
289 +
290 + const listenEffect = realtime
291 + .listen(onEvent)
292 + .pipe(
293 + Effect.onInterrupt(() => ui.log.info('Stopped listening for realtime trigger events.'))
294 + );
295 +
296 + if (maxEventsLimit === undefined) {
297 + yield* listenEffect;
298 + return;
299 + }
300 +
301 + yield* Effect.raceFirst(listenEffect, Deferred.await(stopWhenDone));
302 + yield* ui.outro(`Stopped after receiving ${matchingEvents} matching events.`);
303 + })
304 +).pipe(Command.withDescription('Listen to realtime trigger events for your project.'));
ts/packages/cli/src/commands/triggers/filter.ts new
+37
@@ -0,0 +1,37 @@
1 +import type { TriggerListenEvent, TriggerListenFilters } from './types';
2 +
3 +export const matchesTriggerListenFilters = (
4 + filters: TriggerListenFilters,
5 + data: TriggerListenEvent
6 +): boolean => {
7 + if (
8 + filters.toolkits?.length &&
9 + !filters.toolkits.map(x => x.toLowerCase()).includes(data.toolkitSlug.toLowerCase())
10 + ) {
11 + return false;
12 + }
13 +
14 + if (filters.triggerId && filters.triggerId !== data.id) {
15 + return false;
16 + }
17 +
18 + if (
19 + filters.connectedAccountId &&
20 + filters.connectedAccountId !== data.metadata.connectedAccount.id
21 + ) {
22 + return false;
23 + }
24 +
25 + if (
26 + filters.triggerSlug?.length &&
27 + !filters.triggerSlug.map(x => x.toLowerCase()).includes(data.triggerSlug.toLowerCase())
28 + ) {
29 + return false;
30 + }
31 +
32 + if (filters.userId && filters.userId !== data.metadata.connectedAccount.userId) {
33 + return false;
34 + }
35 +
36 + return true;
37 +};
ts/packages/cli/src/commands/triggers/format.ts new
+13
@@ -0,0 +1,13 @@
1 +import type { TriggerListenEvent } from './types';
2 +
3 +export const formatTriggerListenSummary = (event: TriggerListenEvent): string => {
4 + const userId = event.userId || '-';
5 + const connectedAccountId = event.metadata.connectedAccount.id || '-';
6 + return [
7 + `Trigger: ${event.triggerSlug}`,
8 + `Toolkit: ${event.toolkitSlug}`,
9 + `Trigger Id: ${event.id}`,
10 + `Connected Account: ${connectedAccountId}`,
11 + `User Id: ${userId}`,
12 + ].join('\n');
13 +};
ts/packages/cli/src/commands/triggers/parse.ts new
+204
@@ -0,0 +1,204 @@
1 +import type { TriggerListenEvent } from './types';
2 +
3 +const toStringOrDefault = (value: unknown, defaultValue: string): string => {
4 + if (value === null || value === undefined) {
5 + return defaultValue;
6 + }
7 + const str = String(value);
8 + return str.length > 0 ? str : defaultValue;
9 +};
10 +
11 +const asRecord = (value: unknown): Record<string, unknown> =>
12 + typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : {};
13 +
14 +export const parseTriggerListenEvent = (data: Record<string, unknown>): TriggerListenEvent => {
15 + // V3 payload (trigger event)
16 + if (
17 + data.type === 'composio.trigger.message' &&
18 + typeof data.id === 'string' &&
19 + typeof data.metadata === 'object' &&
20 + data.metadata !== null
21 + ) {
22 + const metadata = asRecord(data.metadata);
23 + if (typeof metadata.trigger_slug === 'string') {
24 + const triggerSlug = metadata.trigger_slug;
25 + const toolkitSlug = triggerSlug.split('_')[0]?.toUpperCase() || 'UNKNOWN';
26 +
27 + return {
28 + id: toStringOrDefault(metadata.trigger_id, data.id),
29 + uuid: toStringOrDefault(metadata.trigger_id, data.id),
30 + triggerSlug,
31 + toolkitSlug,
32 + userId: toStringOrDefault(metadata.user_id, ''),
33 + payload: asRecord(data.data),
34 + originalPayload: asRecord(data),
35 + metadata: {
36 + id: toStringOrDefault(metadata.trigger_id, data.id),
37 + uuid: toStringOrDefault(metadata.trigger_id, data.id),
38 + toolkitSlug,
39 + triggerSlug,
40 + triggerConfig: {},
41 + connectedAccount: {
42 + id: toStringOrDefault(metadata.connected_account_id, ''),
43 + uuid: toStringOrDefault(metadata.connected_account_id, ''),
44 + authConfigId: toStringOrDefault(metadata.auth_config_id, ''),
45 + authConfigUUID: toStringOrDefault(metadata.auth_config_id, ''),
46 + userId: toStringOrDefault(metadata.user_id, ''),
47 + status: 'ACTIVE',
48 + },
49 + },
50 + };
51 + }
52 + }
53 +
54 + // V2 payload
55 + if (
56 + typeof data.type === 'string' &&
57 + typeof data.data === 'object' &&
58 + data.data !== null &&
59 + typeof asRecord(data.data).trigger_nano_id === 'string'
60 + ) {
61 + const v2 = asRecord(data.data);
62 + const triggerSlug = data.type.toUpperCase();
63 + const toolkitSlug = triggerSlug.split('_')[0] || 'UNKNOWN';
64 + const payload = { ...v2 };
65 + delete payload.connection_id;
66 + delete payload.connection_nano_id;
67 + delete payload.trigger_nano_id;
68 + delete payload.trigger_id;
69 + delete payload.user_id;
70 +
71 + return {
72 + id: toStringOrDefault(v2.trigger_nano_id, ''),
73 + uuid: toStringOrDefault(v2.trigger_id, toStringOrDefault(v2.trigger_nano_id, '')),
74 + triggerSlug,
75 + toolkitSlug,
76 + userId: toStringOrDefault(v2.user_id, ''),
77 + payload,
78 + originalPayload: asRecord(data),
79 + metadata: {
80 + id: toStringOrDefault(v2.trigger_nano_id, ''),
81 + uuid: toStringOrDefault(v2.trigger_id, toStringOrDefault(v2.trigger_nano_id, '')),
82 + toolkitSlug,
83 + triggerSlug,
84 + triggerConfig: {},
85 + connectedAccount: {
86 + id: toStringOrDefault(v2.connection_nano_id, ''),
87 + uuid: toStringOrDefault(v2.connection_id, ''),
88 + authConfigId: '',
89 + authConfigUUID: '',
90 + userId: toStringOrDefault(v2.user_id, ''),
91 + status: 'ACTIVE',
92 + },
93 + },
94 + };
95 + }
96 +
97 + // V1 payload
98 + if (
99 + typeof data.trigger_name === 'string' &&
100 + typeof data.connection_id === 'string' &&
101 + typeof data.trigger_id === 'string'
102 + ) {
103 + const triggerSlug = data.trigger_name;
104 + const toolkitSlug = triggerSlug.split('_')[0]?.toUpperCase() || 'UNKNOWN';
105 + return {
106 + id: data.trigger_id,
107 + uuid: data.trigger_id,
108 + triggerSlug,
109 + toolkitSlug,
110 + userId: '',
111 + payload: asRecord(data.payload),
112 + originalPayload: asRecord(data),
113 + metadata: {
114 + id: data.trigger_id,
115 + uuid: data.trigger_id,
116 + toolkitSlug,
117 + triggerSlug,
118 + triggerConfig: {},
119 + connectedAccount: {
120 + id: data.connection_id,
121 + uuid: data.connection_id,
122 + authConfigId: '',
123 + authConfigUUID: '',
124 + userId: '',
125 + status: 'ACTIVE',
126 + },
127 + },
128 + };
129 + }
130 +
131 + // Legacy payload
132 + if (
133 + typeof data.appName === 'string' &&
134 + typeof data.metadata === 'object' &&
135 + data.metadata !== null &&
136 + typeof asRecord(data.metadata).nanoId === 'string'
137 + ) {
138 + const metadata = asRecord(data.metadata);
139 + const connection = asRecord(metadata.connection);
140 + return {
141 + id: toStringOrDefault(metadata.nanoId, toStringOrDefault(metadata.id, 'unknown')),
142 + uuid: toStringOrDefault(metadata.id, toStringOrDefault(metadata.nanoId, 'unknown')),
143 + triggerSlug: toStringOrDefault(metadata.triggerName, 'UNKNOWN'),
144 + toolkitSlug: toStringOrDefault(data.appName, 'UNKNOWN'),
145 + userId: toStringOrDefault(connection.clientUniqueUserId, ''),
146 + payload: asRecord(data.payload),
147 + originalPayload: asRecord(data.originalPayload ?? data.payload),
148 + metadata: {
149 + id: toStringOrDefault(metadata.nanoId, toStringOrDefault(metadata.id, 'unknown')),
150 + uuid: toStringOrDefault(metadata.id, toStringOrDefault(metadata.nanoId, 'unknown')),
151 + toolkitSlug: toStringOrDefault(data.appName, 'UNKNOWN'),
152 + triggerSlug: toStringOrDefault(metadata.triggerName, 'UNKNOWN'),
153 + triggerData: toStringOrDefault(metadata.triggerData, ''),
154 + triggerConfig: asRecord(metadata.triggerConfig),
155 + connectedAccount: {
156 + id: toStringOrDefault(connection.connectedAccountNanoId, ''),
157 + uuid: toStringOrDefault(connection.id, ''),
158 + authConfigId: toStringOrDefault(connection.authConfigNanoId, ''),
159 + authConfigUUID: toStringOrDefault(connection.integrationId, ''),
160 + userId: toStringOrDefault(connection.clientUniqueUserId, ''),
161 + status: toStringOrDefault(connection.status, 'ACTIVE'),
162 + },
163 + },
164 + };
165 + }
166 +
167 + // Fallback
168 + const id = toStringOrDefault(data.id, toStringOrDefault(data.trigger_id, 'unknown'));
169 + const uuid = toStringOrDefault(data.uuid, id);
170 + const triggerSlug = toStringOrDefault(
171 + data.triggerSlug,
172 + toStringOrDefault(data.trigger_name, 'UNKNOWN')
173 + );
174 + const toolkitSlug = toStringOrDefault(
175 + data.toolkitSlug,
176 + toStringOrDefault(data.appName, 'UNKNOWN')
177 + );
178 + const userId = toStringOrDefault(data.userId, '');
179 +
180 + return {
181 + id,
182 + uuid,
183 + triggerSlug,
184 + toolkitSlug,
185 + userId,
186 + payload: asRecord(data.payload ?? data),
187 + originalPayload: asRecord(data.originalPayload ?? data),
188 + metadata: {
189 + id,
190 + uuid,
191 + toolkitSlug,
192 + triggerSlug,
193 + triggerConfig: {},
194 + connectedAccount: {
195 + id: '',
196 + uuid: '',
197 + authConfigId: '',
198 + authConfigUUID: '',
199 + userId: '',
200 + status: 'ACTIVE',
201 + },
202 + },
203 + };
204 +};
ts/packages/cli/src/commands/triggers/triggers.cmd.ts new
+15
@@ -0,0 +1,15 @@
1 +import { Command } from '@effect/cli';
2 +import { triggersCmd$Listen } from './commands/triggers.listen.cmd';
3 +
4 +/**
5 + * CLI entry point for realtime trigger commands.
6 + *
7 + * @example
8 + * ```bash
9 + * composio triggers <command>
10 + * ```
11 + */
12 +export const triggersCmd = Command.make('triggers').pipe(
13 + Command.withDescription('Subscribe to realtime trigger events.'),
14 + Command.withSubcommands([triggersCmd$Listen])
15 +);
ts/packages/cli/src/commands/triggers/types.ts new
+33
@@ -0,0 +1,33 @@
1 +export type TriggerListenEvent = {
2 + id: string;
3 + uuid: string;
4 + triggerSlug: string;
5 + toolkitSlug: string;
6 + userId: string;
7 + payload: Record<string, unknown>;
8 + originalPayload: Record<string, unknown>;
9 + metadata: {
10 + id: string;
11 + uuid: string;
12 + toolkitSlug: string;
13 + triggerSlug: string;
14 + triggerData?: string;
15 + triggerConfig: Record<string, unknown>;
16 + connectedAccount: {
17 + id: string;
18 + uuid: string;
19 + authConfigId: string;
20 + authConfigUUID: string;
21 + userId: string;
22 + status: string;
23 + };
24 + };
25 +};
26 +
27 +export type TriggerListenFilters = {
28 + toolkits?: ReadonlyArray<string>;
29 + triggerId?: string;
30 + connectedAccountId?: string;
31 + triggerSlug?: ReadonlyArray<string>;
32 + userId?: string;
33 +};
ts/packages/cli/src/services/composio-clients.ts
+34
@@ -221,6 +221,21 @@ export type CliCreateSessionResponse = Schema.Schema.Type<typeof CliCreateSessio
221 export const CliGetSessionResponse = RetrievedSession;
222 export type CliRetrieveSessionResponse = Schema.Schema.Type<typeof CliGetSessionResponse>;
223
224 +export const CliRealtimeCredentialsResponse = Schema.Struct({
225 + project_id: Schema.String,
226 + pusher_key: Schema.String,
227 + pusher_cluster: Schema.String,
228 +}).annotations({ identifier: 'CliRealtimeCredentialsResponse' });
229 +export type CliRealtimeCredentialsResponse = Schema.Schema.Type<
230 + typeof CliRealtimeCredentialsResponse
231 +>;
232 +
233 +export const CliRealtimeAuthResponse = Schema.Struct({
234 + auth: Schema.String,
235 + channel_data: Schema.optional(Schema.String),
236 +}).annotations({ identifier: 'CliRealtimeAuthResponse' });
237 +export type CliRealtimeAuthResponse = Schema.Schema.Type<typeof CliRealtimeAuthResponse>;
238 +
239 export const ToolkitsResponse = Schema.Struct({
240 items: Toolkits,
241 total_pages: Schema.Int,
@@ -1110,6 +1125,22 @@ export class ComposioClientLive extends Effect.Service<ComposioClientLive>()(
1125 CliGetSessionResponse
1126 )
1127 ),
1128 + getRealtimeCredentials: () =>
1129 + withMetrics(
1130 + callClient(
1131 + clientSingleton,
1132 + client => client.cli.realtime.credentials(),
1133 + CliRealtimeCredentialsResponse
1134 + )
1135 + ),
1136 + authRealtimeChannel: (params: { channel_name: string; socket_id: string }) =>
1137 + withMetrics(
1138 + callClient(
1139 + clientSingleton,
1140 + client => client.cli.realtime.auth(params),
1141 + CliRealtimeAuthResponse
1142 + )
1143 + ),
1144 },
1145 authConfigs: buildAuthConfigsNamespace(clientSingleton, withMetrics),
1146 connectedAccounts: buildConnectedAccountsNamespace(clientSingleton, withMetrics),
@@ -1375,6 +1406,9 @@ export class ComposioSessionRepository extends Effect.Service<ComposioSessionRep
1406 return {
1407 createSession: () => client.cli.createSession(),
1408 getSession: (session: { id: string }) => client.cli.getSession({ id: session.id }),
1409 + getRealtimeCredentials: () => client.cli.getRealtimeCredentials(),
1410 + authRealtimeChannel: (params: { channel_name: string; socket_id: string }) =>
1411 + client.cli.authRealtimeChannel(params),
1412 };
1413 }),
1414 dependencies: [ComposioClientLive.Default],
ts/packages/cli/src/services/triggers-realtime.ts new
+183
@@ -0,0 +1,183 @@
1 +import { Data, Effect } from 'effect';
2 +import { ComposioSessionRepository } from 'src/services/composio-clients';
3 +
4 +type RawRealtimeEvent = Record<string, unknown>;
5 +
6 +type PusherAuthOptions = {
7 + params?: {
8 + channel_name?: string;
9 + socket_id?: string;
10 + channelName?: string;
11 + socketId?: string;
12 + };
13 + channel_name?: string;
14 + socket_id?: string;
15 + channelName?: string;
16 + socketId?: string;
17 +};
18 +
19 +type PusherAuthCallback = (error: unknown, data?: unknown) => void;
20 +
21 +type PusherChannel = {
22 + bind: (event: string, callback: (data: unknown) => void) => void;
23 + bind_global?: (callback: (eventName: string, data: unknown) => void) => void;
24 + unbind?: (event?: string, callback?: (data: unknown) => void) => void;
25 +};
26 +
27 +type PusherClient = {
28 + subscribe: (channelName: string) => PusherChannel;
29 + unsubscribe: (channelName: string) => void;
30 + disconnect: () => void;
31 + connection?: {
32 + bind?: (event: string, callback: (data: unknown) => void) => void;
33 + };
34 +};
35 +
36 +type PusherCtor = new (
37 + key: string,
38 + options: {
39 + cluster: string;
40 + channelAuthorization: {
41 + customHandler: (
42 + authOptions: PusherAuthOptions,
43 + callback?: PusherAuthCallback
44 + ) => Promise<unknown> | void;
45 + };
46 + }
47 +) => PusherClient;
48 +
49 +type ChunkedRealtimeEvent = {
50 + id: string;
51 + index: number;
52 + chunk: string;
53 + final: boolean;
54 +};
55 +
56 +export class TriggerRealtimeSubscriptionError extends Data.TaggedError(
57 + 'services/TriggerRealtimeSubscriptionError'
58 +)<{
59 + readonly cause?: unknown;
60 +}> {}
61 +
62 +/**
63 + * Service for listening to trigger events over Composio CLI realtime channels.
64 + * Uses:
65 + * - `cli.realtime.credentials` to fetch Pusher credentials + project nano id
66 + * - `cli.realtime.auth` for private channel auth callbacks
67 + */
68 +export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
69 + 'services/TriggersRealtime',
70 + {
71 + effect: Effect.gen(function* () {
72 + const sessionRepo = yield* ComposioSessionRepository;
73 +
74 + const listen = (onEvent: (data: RawRealtimeEvent) => void) =>
75 + Effect.acquireUseRelease(
76 + Effect.gen(function* () {
77 + const creds = yield* sessionRepo.getRealtimeCredentials();
78 + const channelName = `private-cli-${creds.project_id}`;
79 +
80 + const pusherModule = yield* Effect.tryPromise({
81 + try: () => import('pusher-js'),
82 + catch: cause => new TriggerRealtimeSubscriptionError({ cause }),
83 + });
84 +
85 + const Pusher = pusherModule.default as unknown as PusherCtor;
86 +
87 + const pusher = new Pusher(creds.pusher_key, {
88 + cluster: creds.pusher_cluster,
89 + channelAuthorization: {
90 + customHandler: (authOptions: PusherAuthOptions, callback?: PusherAuthCallback) => {
91 + const params = authOptions.params ?? authOptions;
92 + const channel_name = params.channel_name ?? params.channelName;
93 + const socket_id = params.socket_id ?? params.socketId;
94 +
95 + const doAuth = async () => {
96 + if (!channel_name || !socket_id) {
97 + throw new Error('Missing channel_name or socket_id for realtime auth');
98 + }
99 +
100 + const response = await Effect.runPromise(
101 + sessionRepo.authRealtimeChannel({
102 + channel_name,
103 + socket_id,
104 + })
105 + );
106 + // Pusher private channels verify signatures without channel_data.
107 + // Some auth endpoints may still return channel_data, which can cause
108 + // "Invalid signature" if included in the verification input.
109 + const normalizedResponse = channel_name.startsWith('private-')
110 + ? { auth: response.auth }
111 + : response;
112 + return normalizedResponse;
113 + };
114 +
115 + if (callback) {
116 + void doAuth()
117 + .then(data => callback(null, data))
118 + .catch(error => callback(error));
119 + return;
120 + }
121 +
122 + return doAuth();
123 + },
124 + },
125 + });
126 +
127 + const channel = pusher.subscribe(channelName);
128 + const chunkedEvents = new Map<string, { chunks: string[]; receivedFinal: boolean }>();
129 +
130 + channel.bind('trigger_to_client', eventData => {
131 + onEvent((eventData ?? {}) as RawRealtimeEvent);
132 + });
133 +
134 + channel.bind('chunked-trigger_to_client', data => {
135 + const typed = data as ChunkedRealtimeEvent;
136 + if (!typed || typeof typed.id !== 'string' || typeof typed.index !== 'number') {
137 + return;
138 + }
139 +
140 + if (!chunkedEvents.has(typed.id)) {
141 + chunkedEvents.set(typed.id, { chunks: [], receivedFinal: false });
142 + }
143 +
144 + const current = chunkedEvents.get(typed.id)!;
145 + current.chunks[typed.index] = typed.chunk;
146 + if (typed.final) {
147 + current.receivedFinal = true;
148 + }
149 +
150 + if (
151 + current.receivedFinal &&
152 + current.chunks.length === Object.keys(current.chunks).length
153 + ) {
154 + try {
155 + const parsed = JSON.parse(current.chunks.join('')) as RawRealtimeEvent;
156 + onEvent(parsed);
157 + } finally {
158 + chunkedEvents.delete(typed.id);
159 + }
160 + }
161 + });
162 +
163 + return {
164 + shutdown: async () => {
165 + channel.unbind?.();
166 + pusher.unsubscribe(channelName);
167 + pusher.disconnect();
168 + },
169 + };
170 + }),
171 + () => Effect.never,
172 + resource =>
173 + Effect.tryPromise({
174 + try: () => resource.shutdown(),
175 + catch: cause => new TriggerRealtimeSubscriptionError({ cause }),
176 + }).pipe(Effect.catchAll(() => Effect.void))
177 + );
178 +
179 + return { listen };
180 + }),
181 + dependencies: [ComposioSessionRepository.Default],
182 + }
183 +) {}
ts/packages/cli/test/__utils__/services/test-layer.ts
+38
@@ -40,6 +40,7 @@ import type { ToolkitVersionSpec } from 'src/effects/toolkit-version-overrides';
40 import { ComposioUserContextLive } from 'src/services/user-context';
41 import { UpgradeBinary } from 'src/services/upgrade-binary';
42 import { NodeOs } from 'src/services/node-os';
43 +import { TriggersRealtime } from 'src/services/triggers-realtime';
44
45 export interface TestLiveInput {
46 /**
@@ -80,6 +81,13 @@ export interface TestLiveInput {
81 items?: ConnectedAccountItem[];
82 linkResponse?: LinkCreateResponse;
83 };
84 +
85 + /**
86 + * Mock realtime trigger data to use in test.
87 + */
88 + realtimeData?: {
89 + events?: ReadonlyArray<Record<string, unknown>>;
90 + };
91 }
92
93 /**
@@ -133,6 +141,14 @@ export const TestLayer = (input?: TestLiveInput) =>
141 ...(input?.connectedAccountsData ?? {}),
142 };
143
144 + const defaultRealtimeData = {
145 + events: [] as ReadonlyArray<Record<string, unknown>>,
146 + } satisfies TestLiveInput['realtimeData'];
147 + const realtimeData = {
148 + ...defaultRealtimeData,
149 + ...(input?.realtimeData ?? {}),
150 + };
151 +
152 const tempDir = tempy.temporaryDirectory({ prefix: 'test' });
153 const cwd = (yield* setupFixtureFolder({ fixture, tempDir })) ?? tempDir;
154
@@ -501,6 +517,16 @@ export const TestLayer = (input?: TestLiveInput) =>
517 })
518 );
519 const ComposioSessionRepositoryTest = yield* setupComposioSessionRepository();
520 + const TriggersRealtimeTest = Layer.succeed(
521 + TriggersRealtime,
522 + new TriggersRealtime({
523 + listen: onEvent =>
524 + Effect.gen(function* () {
525 + yield* Effect.forEach(realtimeData.events, event => Effect.sync(() => onEvent(event)));
526 + return yield* Effect.never;
527 + }),
528 + })
529 + );
530
531 // Mock `node:os`
532 const NodeOsTest = Layer.succeed(
@@ -543,6 +569,7 @@ export const TestLayer = (input?: TestLiveInput) =>
569 UpgradeBinaryTest,
570 ComposioUserContextTest,
571 ComposioSessionRepositoryTest,
572 + TriggersRealtimeTest,
573 ComposioToolkitsRepositoryTest,
574 EnvLangDetector.Default,
575 JsPackageManagerDetector.Default,
@@ -747,6 +774,17 @@ function setupComposioSessionRepository() {
774 status: 'pending',
775 api_key: null,
776 }),
777 + getRealtimeCredentials: () =>
778 + Effect.succeed({
779 + project_id: 'proj_test',
780 + pusher_key: 'pusher_test_key',
781 + pusher_cluster: 'mt1',
782 + }),
783 + authRealtimeChannel: () =>
784 + Effect.succeed({
785 + auth: 'mock:auth',
786 + channel_data: undefined,
787 + }),
788 });
789 const ComposioSessionRepositoryTest = Layer.succeed(
790 ComposioSessionRepository,
ts/packages/cli/test/src/commands/$default.cmd.test.ts
+34 -30
@@ -15,7 +15,7 @@ describe('CLI: composio', () => {
15 expect(result).toEqual(
16 ValidationError.commandMismatch(
17 HelpDoc.p(
18 - "Invalid subcommand for composio - use one of 'version', 'upgrade', 'whoami', 'login', 'logout', 'generate', 'py', 'ts', 'toolkits', 'tools', 'auth-configs', 'connected-accounts'"
18 + "Invalid subcommand for composio - use one of 'version', 'upgrade', 'whoami', 'login', 'logout', 'generate', 'py', 'ts', 'toolkits', 'tools', 'auth-configs', 'connected-accounts', 'triggers'"
19 )
20 )
21 );
@@ -56,71 +56,75 @@ describe('CLI: composio', () => {
56
57 COMMANDS
58
59 - - version Display the current Composio CLI version.
59 + - version Display the current Composio CLI version.
60
61 - - upgrade Upgrade your Composio CLI to the latest available version.
61 + - upgrade Upgrade your Composio CLI to the latest available version.
62
63 - - whoami Display your account information.
63 + - whoami Display your account information.
64
65 - - login [--no-browser] Log in to the Composio SDK.
65 + - login [--no-browser] Log in to the Composio SDK.
66
67 - - logout Log out from the Composio SDK.
67 + - logout Log out from the Composio SDK.
68
69 - - generate [(-o, --output-dir directory)] [--type-tools] --toolkits text... Generate type stubs for toolkits, tools, and triggers, auto-detecting project language (TypeScript | Python)
69 + - generate [(-o, --output-dir directory)] [--type-tools] --toolkits text... Generate type stubs for toolkits, tools, and triggers, auto-detecting project language (TypeScript | Python)
70
71 - - py Handle Python projects.
71 + - py Handle Python projects.
72
73 - - py generate [(-o, --output-dir directory)] --toolkits text... Generate Python type stubs for toolkits, tools, and triggers from the Composio API.
73 + - py generate [(-o, --output-dir directory)] --toolkits text... Generate Python type stubs for toolkits, tools, and triggers from the Composio API.
74
75 Environment Variables:
76 COMPOSIO_TOOLKIT_VERSION_<TOOLKIT> Override toolkit version (e.g., COMPOSIO_TOOLKIT_VERSION_GMAIL=20250901_00)
77 Use "latest" or unset to use the latest version.
78
79 - - ts Handle TypeScript projects.
79 + - ts Handle TypeScript projects.
80
81 - - ts generate [(-o, --output-dir directory)] [--compact] [--transpiled] [--type-tools] --toolkits text... Generate TypeScript types for toolkits, tools, and triggers from the Composio API.
81 + - ts generate [(-o, --output-dir directory)] [--compact] [--transpiled] [--type-tools] --toolkits text... Generate TypeScript types for toolkits, tools, and triggers from the Composio API.
82
83 Environment Variables:
84 COMPOSIO_TOOLKIT_VERSION_<TOOLKIT> Override toolkit version (e.g., COMPOSIO_TOOLKIT_VERSION_GMAIL=20250901_00)
85 Use "latest" or unset to use the latest version.
86
87 - - toolkits Discover and inspect Composio toolkits.
87 + - toolkits Discover and inspect Composio toolkits.
88
89 - - toolkits list [--query text] [--limit integer] List available toolkits.
89 + - toolkits list [--query text] [--limit integer] List available toolkits.
90
91 - - toolkits info [<slug>] View details of a specific toolkit.
91 + - toolkits info [<slug>] View details of a specific toolkit.
92
93 - - toolkits search [--limit integer] <query> Search toolkits by use case.
93 + - toolkits search [--limit integer] <query> Search toolkits by use case.
94
95 - - tools Discover and inspect Composio tools.
95 + - tools Discover and inspect Composio tools.
96
97 - - tools list [--query text] [--toolkits text] [--tags text] [--limit integer] List available tools.
97 + - tools list [--query text] [--toolkits text] [--tags text] [--limit integer] List available tools.
98
99 - - tools info [<slug>] View details of a specific tool.
99 + - tools info [<slug>] View details of a specific tool.
100
101 - - tools search [--toolkits text] [--limit integer] <query> Search tools by use case.
101 + - tools search [--toolkits text] [--limit integer] <query> Search tools by use case.
102
103 - - auth-configs View and manage Composio auth configs.
103 + - auth-configs View and manage Composio auth configs.
104
105 - - auth-configs list [--toolkits text] [--query text] [--limit integer] List auth configs.
105 + - auth-configs list [--toolkits text] [--query text] [--limit integer] List auth configs.
106
107 - - auth-configs info [<id>] View details of a specific auth config.
107 + - auth-configs info [<id>] View details of a specific auth config.
108
109 - - auth-configs create --toolkit text [--auth-scheme text] [--scopes text] [--custom-credentials text] [<name>] Create a new auth config.
109 + - auth-configs create --toolkit text [--auth-scheme text] [--scopes text] [--custom-credentials text] [<name>] Create a new auth config.
110
111 - - auth-configs delete [(-y, --yes)] [<id>] Delete an auth config.
111 + - auth-configs delete [(-y, --yes)] [<id>] Delete an auth config.
112
113 - - connected-accounts View and manage Composio connected accounts.
113 + - connected-accounts View and manage Composio connected accounts.
114
115 - - connected-accounts list [--toolkits text] [--user-id text] [--status INITIALIZING | INITIATED | ACTIVE | FAILED | EXPIRED | INACTIVE] [--limit integer] List connected accounts.
115 + - connected-accounts list [--toolkits text] [--user-id text] [--status INITIALIZING | INITIATED | ACTIVE | FAILED | EXPIRED | INACTIVE] [--limit integer] List connected accounts.
116
117 - - connected-accounts info [<id>] View details of a specific connected account.
117 + - connected-accounts info [<id>] View details of a specific connected account.
118
119 - - connected-accounts whoami [<id>] Show the external account profile for a connected account.
119 + - connected-accounts whoami [<id>] Show the external account profile for a connected account.
120
121 - - connected-accounts delete [(-y, --yes)] [<id>] Delete a connected account.
121 + - connected-accounts delete [(-y, --yes)] [<id>] Delete a connected account.
122
123 - - connected-accounts link --auth-config text [--user-id text] [--no-browser] Link an external account via OAuth redirect.
123 + - connected-accounts link --auth-config text [--user-id text] [--no-browser] Link an external account via OAuth redirect.
124 +
125 + - triggers Subscribe to realtime trigger events.
126 +
127 + - triggers listen [--toolkits text] [--trigger-id text] [--connected-account-id text] [--trigger-slug text] [--user-id text] [--json] [--max-events integer] [--forward text] [--out text] Listen to realtime trigger events for your project.
128 "
129 `);
130 })
ts/packages/cli/test/src/commands/triggers/triggers.listen.cmd.test.ts new
+242
@@ -0,0 +1,242 @@
1 +import { describe, expect, layer } from '@effect/vitest';
2 +import { ConfigProvider, Effect } from 'effect';
3 +import { extendConfigProvider } from 'src/services/config';
4 +import { cli, MockConsole, TestLive } from 'test/__utils__';
5 +import { createServer, type IncomingMessage } from 'node:http';
6 +import { Composio } from '@composio/core';
7 +
8 +const testConfigProvider = ConfigProvider.fromMap(
9 + new Map([['COMPOSIO_API_KEY', 'test_api_key']])
10 +).pipe(extendConfigProvider);
11 +
12 +const mockV3TriggerEvent = {
13 + id: 'msg-123',
14 + timestamp: '2026-02-23T12:00:00Z',
15 + type: 'composio.trigger.message',
16 + metadata: {
17 + log_id: 'log-123',
18 + trigger_slug: 'GMAIL_NEW_GMAIL_MESSAGE',
19 + trigger_id: 'trg_123',
20 + connected_account_id: 'con_123',
21 + auth_config_id: 'ac_123',
22 + user_id: 'user_123',
23 + },
24 + data: {
25 + subject: 'Hello',
26 + from: 'hello@example.com',
27 + },
28 +} as const;
29 +
30 +type CapturedWebhookRequest = {
31 + body: string;
32 + headers: {
33 + webhookId: string;
34 + webhookTimestamp: string;
35 + webhookSignature: string;
36 + webhookVersion: string;
37 + };
38 +};
39 +
40 +const startWebhookServer = async (): Promise<{
41 + url: string;
42 + waitForRequest: Promise<CapturedWebhookRequest>;
43 + close: () => Promise<void>;
44 +}> => {
45 + let resolveRequest: ((value: CapturedWebhookRequest) => void) | undefined;
46 + let rejectRequest: ((reason?: unknown) => void) | undefined;
47 +
48 + const waitForRequest = new Promise<CapturedWebhookRequest>((resolve, reject) => {
49 + resolveRequest = resolve;
50 + rejectRequest = reject;
51 + });
52 +
53 + const readBody = (req: IncomingMessage): Promise<string> =>
54 + new Promise((resolve, reject) => {
55 + const chunks: Buffer[] = [];
56 + req.on('data', chunk => {
57 + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
58 + });
59 + req.on('end', () => {
60 + resolve(Buffer.concat(chunks).toString('utf8'));
61 + });
62 + req.on('error', reject);
63 + });
64 +
65 + const server = createServer(async (req, res) => {
66 + try {
67 + const body = await readBody(req);
68 + resolveRequest?.({
69 + body,
70 + headers: {
71 + webhookId: (req.headers['webhook-id'] as string | undefined) ?? '',
72 + webhookTimestamp: (req.headers['webhook-timestamp'] as string | undefined) ?? '',
73 + webhookSignature: (req.headers['webhook-signature'] as string | undefined) ?? '',
74 + webhookVersion: (req.headers['x-composio-webhook-version'] as string | undefined) ?? '',
75 + },
76 + });
77 + res.statusCode = 200;
78 + res.end('ok');
79 + } catch (error) {
80 + rejectRequest?.(error);
81 + res.statusCode = 500;
82 + res.end('error');
83 + }
84 + });
85 +
86 + await new Promise<void>((resolve, reject) => {
87 + server.listen(0, '127.0.0.1', () => resolve());
88 + server.on('error', reject);
89 + });
90 +
91 + const address = server.address();
92 + if (!address || typeof address === 'string') {
93 + throw new Error('Failed to bind webhook test server');
94 + }
95 +
96 + return {
97 + url: `http://127.0.0.1:${address.port}/webhook`,
98 + waitForRequest,
99 + close: () =>
100 + new Promise((resolve, reject) => {
101 + server.close(error => {
102 + if (error) reject(error);
103 + else resolve();
104 + });
105 + }),
106 + };
107 +};
108 +
109 +describe('CLI: composio triggers listen', () => {
110 + layer(
111 + TestLive({
112 + baseConfigProvider: testConfigProvider,
113 + realtimeData: {
114 + events: [mockV3TriggerEvent],
115 + },
116 + })
117 + )('[Given] one realtime event [Then] prints normalized event output', it => {
118 + it.scoped('prints event summary and payload', () =>
119 + Effect.gen(function* () {
120 + yield* cli(['triggers', 'listen', '--max-events', '1']);
121 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
122 + const output = lines.join('\n');
123 +
124 + expect(output).toContain('Listening for realtime trigger events');
125 + expect(output).not.toContain('Writing matching events to:');
126 + expect(output).toContain('GMAIL_NEW_GMAIL_MESSAGE');
127 + expect(output).toContain('"subject":"Hello"');
128 + expect(output).toContain('Stopped after receiving 1 matching events');
129 + })
130 + );
131 + });
132 +
133 + layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
134 + it.scoped('warns user to login', () =>
135 + Effect.gen(function* () {
136 + yield* cli(['triggers', 'listen']);
137 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
138 + const output = lines.join('\n');
139 + expect(output).toContain('not logged in');
140 + })
141 + );
142 + });
143 +
144 + layer(
145 + TestLive({
146 + baseConfigProvider: testConfigProvider,
147 + realtimeData: { events: [mockV3TriggerEvent] },
148 + })
149 + )(
150 + '[Given] --forward without COMPOSIO_WEBHOOK_SECRET [Then] generates session signing secret',
151 + it => {
152 + it.scoped('shows generated signing secret for forward mode', () =>
153 + Effect.gen(function* () {
154 + delete process.env.COMPOSIO_WEBHOOK_SECRET;
155 + yield* cli([
156 + 'triggers',
157 + 'listen',
158 + '--forward',
159 + 'http://localhost:8080/webhook',
160 + '--max-events',
161 + '1',
162 + ]);
163 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
164 + const output = lines.join('\n');
165 + expect(output).toContain('No COMPOSIO_WEBHOOK_SECRET found');
166 + expect(output).toContain('Forward URL: http://localhost:8080/webhook');
167 + expect(output).toContain('Generated signing secret: composio-forward-secret-');
168 + })
169 + );
170 + }
171 + );
172 +
173 + layer(
174 + TestLive({
175 + baseConfigProvider: testConfigProvider,
176 + realtimeData: { events: [mockV3TriggerEvent] },
177 + })
178 + )('[Given] --forward [Then] sends signed webhook verifiable by composio/core', it => {
179 + it.scoped('forwards request with headers and valid signature', () => {
180 + const previousSecret = process.env.COMPOSIO_WEBHOOK_SECRET;
181 + const restoreWebhookSecret = () => {
182 + if (previousSecret === undefined) {
183 + delete process.env.COMPOSIO_WEBHOOK_SECRET;
184 + return;
185 + }
186 + process.env.COMPOSIO_WEBHOOK_SECRET = previousSecret;
187 + };
188 +
189 + return Effect.gen(function* () {
190 + process.env.COMPOSIO_WEBHOOK_SECRET = 'test-webhook-secret';
191 +
192 + const server = yield* Effect.acquireRelease(
193 + Effect.tryPromise(() => startWebhookServer()),
194 + resource =>
195 + Effect.tryPromise(() => resource.close()).pipe(Effect.catchAll(() => Effect.void))
196 + );
197 +
198 + yield* cli(['triggers', 'listen', '--forward', server.url, '--max-events', '1']);
199 +
200 + const request = yield* Effect.tryPromise({
201 + try: () =>
202 + Promise.race([
203 + server.waitForRequest,
204 + new Promise<never>((_, reject) =>
205 + setTimeout(() => reject(new Error('Timed out waiting for forwarded webhook')), 3000)
206 + ),
207 + ]),
208 + catch: error => new Error(String(error)),
209 + });
210 +
211 + expect(request.headers.webhookId).not.toEqual('');
212 + expect(request.headers.webhookTimestamp).not.toEqual('');
213 + expect(request.headers.webhookSignature).toContain('v1,');
214 + expect(request.headers.webhookVersion).toEqual('V3');
215 +
216 + const composio = new Composio({
217 + apiKey: 'test-api-key',
218 + disableVersionCheck: true,
219 + allowTracking: false,
220 + });
221 +
222 + const verification = yield* Effect.tryPromise(() =>
223 + composio.triggers.verifyWebhook({
224 + payload: request.body,
225 + id: request.headers.webhookId,
226 + timestamp: request.headers.webhookTimestamp,
227 + signature: request.headers.webhookSignature,
228 + secret: 'test-webhook-secret',
229 + })
230 + );
231 +
232 + expect(verification.rawPayload).toEqual(mockV3TriggerEvent);
233 + }).pipe(
234 + Effect.ensuring(
235 + Effect.sync(() => {
236 + restoreWebhookSecret();
237 + })
238 + )
239 + );
240 + });
241 + });
242 +});