@devries-cameron20 / composio-1 / commits / 2a6e73b20
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.

fix(cli): address review findings for triggers listen command

- Use Runtime.runPromise(runtime) instead of Effect.runPromise for Pusher auth callback so it runs within the CLI's Effect runtime - Wrap sign+forward in Effect.gen with catchAll so signing failures don't crash the fiber or skip the max-events check - Fix --user-id filter to compare against top-level data.userId instead of metadata.connectedAccount.userId (empty in fallback paths) - Add catch block to chunked event JSON.parse to prevent unhandled exceptions in Pusher callbacks - Add guard-rails to chunked event reassembly: index bounds check, TTL-based eviction of stale entries, cap on pending reassemblies - Replace direct process.stderr.write with TerminalUI abstraction - Use @effect/platform FileSystem instead of node:fs - Simplify directory-creation error handling with tapError - Remove redundant forward URL log message - Add JSDoc with @example to triggersCmd$Listen export - Update $default.cmd.test.ts snapshot for tools execute ordering

jkomyno committed Feb 24, 2026 at 13:06 UTC 2a6e73b2012706aaef7e1a167d566931053c5ac0
4 files changed +130 -69
ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts
+57 -62
@@ -1,8 +1,7 @@
1 import { Command, Options } from '@effect/cli';
2 +import { FileSystem } from '@effect/platform';
3 import { Deferred, Effect, Option, Runtime } from 'effect';
4 import path from 'node:path';
4 -import process from 'node:process';
5 -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';
@@ -134,15 +133,20 @@ const detectWebhookPayloadVersion = (eventData: Record<string, unknown>): 'V1' |
133
134 const emitTableLine = (line: string, ui: TerminalUI): Effect.Effect<void> =>
135 Effect.gen(function* () {
137 - if (process.stdout.isTTY) {
138 - yield* Effect.sync(() => {
139 - process.stderr.write(`${line}\n`);
140 - });
141 - return;
142 - }
136 + yield* ui.log.message(line);
137 yield* ui.output(line);
138 });
139
140 +/**
141 + * Listen to realtime trigger events for your project.
142 + *
143 + * @example
144 + * ```bash
145 + * composio triggers listen --toolkits gmail --table
146 + * composio triggers listen --trigger-slug GMAIL_NEW_GMAIL_MESSAGE --json --max-events 5
147 + * composio triggers listen --forward "http://localhost:8080/webhook" --out events.jsonl
148 + * ```
149 + */
150 export const triggersCmd$Listen = Command.make(
151 'listen',
152 {
@@ -173,6 +177,7 @@ export const triggersCmd$Listen = Command.make(
177 if (!(yield* requireAuth)) return;
178
179 const ui = yield* TerminalUI;
180 + const fs = yield* FileSystem.FileSystem;
181 const realtime = yield* TriggersRealtime;
182 const runtime = yield* Effect.runtime<never>();
183 const forwardUrl = Option.getOrUndefined(forward);
@@ -183,19 +188,9 @@ export const triggersCmd$Listen = Command.make(
188
189 if (outputFilePath) {
190 // Ensure output directory exists before listening.
186 - yield* Effect.tryPromise({
187 - try: async () => {
188 - await fs.mkdir(path.dirname(outputFilePath), { recursive: true });
189 - },
190 - catch: error => new Error(`Failed to prepare output file directory: ${String(error)}`),
191 - }).pipe(
192 - Effect.catchAll(error =>
193 - Effect.gen(function* () {
194 - yield* ui.log.error(String(error));
195 - return yield* Effect.fail(error);
196 - })
197 - )
198 - );
191 + yield* fs
192 + .makeDirectory(path.dirname(outputFilePath), { recursive: true })
193 + .pipe(Effect.tapError(error => ui.log.error(String(error))));
194 }
195
196 const filters: TriggerListenFilters = {
@@ -232,9 +227,6 @@ export const triggersCmd$Listen = Command.make(
227 if (outputFilePath) {
228 yield* ui.log.info(`Writing matching events to: ${outputFilePath}`);
229 }
235 - if (forwardUrl) {
236 - yield* ui.log.info(`Forwarding matching events to: ${forwardUrl}`);
237 - }
230
231 if (maxEventsLimit !== undefined) {
232 yield* ui.log.info(`Auto-stop after ${maxEventsLimit} matching events.`);
@@ -278,47 +270,50 @@ export const triggersCmd$Listen = Command.make(
270 const logLine = `${payloadForForwarding}\n`;
271
272 if (outputFilePath) {
281 - yield* Effect.tryPromise({
282 - try: () => fs.appendFile(outputFilePath, logLine, 'utf8'),
283 - catch: error => new Error(`Failed writing to ${outputFilePath}: ${String(error)}`),
284 - }).pipe(Effect.catchAll(error => ui.log.warn(String(error))));
273 + yield* fs
274 + .writeFileString(outputFilePath, logLine, { flag: 'a' })
275 + .pipe(Effect.catchAll(error => ui.log.warn(String(error))));
276 }
277
278 if (forwardUrl && webhookSecret) {
288 - const webhookId =
289 - typeof eventData.id === 'string' && eventData.id.length > 0
290 - ? eventData.id
291 - : randomUUID();
292 - const webhookTimestamp = `${Math.floor(Date.now() / 1000)}`;
293 - const webhookSignature = yield* Effect.tryPromise(() =>
294 - signWebhookPayload({
295 - secret: webhookSecret,
296 - webhookId,
297 - webhookTimestamp,
298 - payload: payloadForForwarding,
299 - })
300 - );
301 - const webhookVersion = detectWebhookPayloadVersion(eventData);
302 -
303 - yield* Effect.tryPromise({
304 - try: async () => {
305 - const response = await fetch(forwardUrl, {
306 - method: 'POST',
307 - headers: {
308 - 'content-type': 'application/json',
309 - 'webhook-id': webhookId,
310 - 'webhook-timestamp': webhookTimestamp,
311 - 'webhook-signature': webhookSignature,
312 - 'x-composio-webhook-version': webhookVersion,
313 - },
314 - body: payloadForForwarding,
315 - });
316 - if (!response.ok) {
317 - throw new Error(`Forwarding failed with HTTP ${response.status}`);
318 - }
319 - },
320 - catch: error =>
321 - new Error(`Failed forwarding event to ${forwardUrl}: ${String(error)}`),
279 + yield* Effect.gen(function* () {
280 + const webhookId =
281 + typeof eventData.id === 'string' && eventData.id.length > 0
282 + ? eventData.id
283 + : randomUUID();
284 + const webhookTimestamp = `${Math.floor(Date.now() / 1000)}`;
285 + const webhookSignature = yield* Effect.tryPromise({
286 + try: () =>
287 + signWebhookPayload({
288 + secret: webhookSecret,
289 + webhookId,
290 + webhookTimestamp,
291 + payload: payloadForForwarding,
292 + }),
293 + catch: error => new Error(`Failed to sign webhook payload: ${String(error)}`),
294 + });
295 + const webhookVersion = detectWebhookPayloadVersion(eventData);
296 +
297 + yield* Effect.tryPromise({
298 + try: async () => {
299 + const response = await fetch(forwardUrl, {
300 + method: 'POST',
301 + headers: {
302 + 'content-type': 'application/json',
303 + 'webhook-id': webhookId,
304 + 'webhook-timestamp': webhookTimestamp,
305 + 'webhook-signature': webhookSignature,
306 + 'x-composio-webhook-version': webhookVersion,
307 + },
308 + body: payloadForForwarding,
309 + });
310 + if (!response.ok) {
311 + throw new Error(`Forwarding failed with HTTP ${response.status}`);
312 + }
313 + },
314 + catch: error =>
315 + new Error(`Failed forwarding event to ${forwardUrl}: ${String(error)}`),
316 + });
317 }).pipe(Effect.catchAll(error => ui.log.warn(String(error))));
318 }
319
ts/packages/cli/src/commands/triggers/filter.ts
+1 -1
@@ -29,7 +29,7 @@ export const matchesTriggerListenFilters = (
29 return false;
30 }
31
32 - if (filters.userId && filters.userId !== data.metadata.connectedAccount.userId) {
32 + if (filters.userId && filters.userId !== data.userId) {
33 return false;
34 }
35
ts/packages/cli/src/services/triggers-realtime.ts
+70 -4
@@ -1,4 +1,4 @@
1 -import { Data, Effect } from 'effect';
1 +import { Data, Effect, Runtime } from 'effect';
2 import { ComposioSessionRepository } from 'src/services/composio-clients';
3
4 type RawRealtimeEvent = Record<string, unknown>;
@@ -70,6 +70,7 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
70 {
71 effect: Effect.gen(function* () {
72 const sessionRepo = yield* ComposioSessionRepository;
73 + const runtime = yield* Effect.runtime<never>();
74
75 const listen = (onEvent: (data: RawRealtimeEvent) => void) =>
76 Effect.acquireUseRelease(
@@ -97,7 +98,7 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
98 throw new Error('Missing channel_name or socket_id for realtime auth');
99 }
100
100 - const response = await Effect.runPromise(
101 + const response = await Runtime.runPromise(runtime)(
102 sessionRepo.authRealtimeChannel({
103 channel_name,
104 socket_id,
@@ -125,7 +126,44 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
126 });
127
128 const channel = pusher.subscribe(channelName);
128 - const chunkedEvents = new Map<string, { chunks: string[]; receivedFinal: boolean }>();
129 +
130 + // Pusher has a 10 KB per-message limit. When the Composio backend
131 + // produces a trigger payload that exceeds this, it splits the JSON
132 + // into numbered chunks sent as separate `chunked-trigger_to_client`
133 + // events. We reassemble them here by accumulating chunks keyed by
134 + // event id, then joining once the final chunk arrives and every
135 + // intermediate index is present.
136 + //
137 + // Guard-rails:
138 + // - Reject chunk indices outside [0, MAX_CHUNK_INDEX] to prevent a
139 + // single malformed event from allocating a huge sparse array.
140 + // - Evict incomplete entries older than CHUNK_TTL_MS so that lost
141 + // chunks don't leak memory over long-running sessions.
142 + // - Cap the total number of in-flight reassemblies to bound memory
143 + // usage even under pathological input.
144 + const MAX_CHUNK_INDEX = 1_000;
145 + const CHUNK_TTL_MS = 60_000;
146 + const MAX_PENDING_CHUNKS = 100;
147 +
148 + type PendingChunkedEvent = {
149 + chunks: string[];
150 + receivedFinal: boolean;
151 + createdAt: number;
152 + };
153 +
154 + const chunkedEvents = new Map<string, PendingChunkedEvent>();
155 +
156 + // Periodic sweep: drop entries that have been sitting incomplete for
157 + // longer than CHUNK_TTL_MS. Runs every CHUNK_TTL_MS and is cleared
158 + // on shutdown.
159 + const cleanupInterval = setInterval(() => {
160 + const now = Date.now();
161 + for (const [id, entry] of chunkedEvents) {
162 + if (now - entry.createdAt > CHUNK_TTL_MS) {
163 + chunkedEvents.delete(id);
164 + }
165 + }
166 + }, CHUNK_TTL_MS);
167
168 channel.bind('trigger_to_client', eventData => {
169 onEvent((eventData ?? {}) as RawRealtimeEvent);
@@ -137,8 +175,29 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
175 return;
176 }
177
178 + // Reject non-integer or out-of-range indices to prevent a single
179 + // malformed event from creating a massive sparse array.
180 + if (
181 + !Number.isInteger(typed.index) ||
182 + typed.index < 0 ||
183 + typed.index > MAX_CHUNK_INDEX
184 + ) {
185 + return;
186 + }
187 +
188 if (!chunkedEvents.has(typed.id)) {
141 - chunkedEvents.set(typed.id, { chunks: [], receivedFinal: false });
189 + // If we already have too many in-flight reassemblies, drop the
190 + // oldest one to make room.
191 + if (chunkedEvents.size >= MAX_PENDING_CHUNKS) {
192 + const oldestId = chunkedEvents.keys().next().value;
193 + if (oldestId !== undefined) chunkedEvents.delete(oldestId);
194 + }
195 +
196 + chunkedEvents.set(typed.id, {
197 + chunks: [],
198 + receivedFinal: false,
199 + createdAt: Date.now(),
200 + });
201 }
202
203 const current = chunkedEvents.get(typed.id)!;
@@ -147,6 +206,10 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
206 current.receivedFinal = true;
207 }
208
209 + // Completeness check: for a dense array, .length equals the
210 + // number of defined keys. For a sparse array (missing chunks),
211 + // .length is highestIndex + 1 but Object.keys only counts the
212 + // indices that were actually assigned, so the two diverge.
213 if (
214 current.receivedFinal &&
215 current.chunks.length === Object.keys(current.chunks).length
@@ -154,6 +217,8 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
217 try {
218 const parsed = JSON.parse(current.chunks.join('')) as RawRealtimeEvent;
219 onEvent(parsed);
220 + } catch {
221 + // Silently discard events that fail to parse after chunk reassembly
222 } finally {
223 chunkedEvents.delete(typed.id);
224 }
@@ -162,6 +227,7 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
227
228 return {
229 shutdown: async () => {
230 + clearInterval(cleanupInterval);
231 channel.unbind?.();
232 pusher.unsubscribe(channelName);
233 pusher.disconnect();
ts/packages/cli/test/src/commands/$default.cmd.test.ts
+2 -2
@@ -96,12 +96,12 @@ describe('CLI: composio', () => {
96
97 - tools list [--query text] [--toolkits text] [--tags text] [--limit integer] List available tools.
98
99 - - tools execute [(-d, --data text)] [--user-id text] [--connected-account-id text] [--toolkit-version text] <slug> Execute a tool by slug with JSON arguments.
100 -
99 - tools info [<slug>] View details of a specific tool.
100
101 - tools search [--toolkits text] [--limit integer] <query> Search tools by use case.
102
103 + - tools execute [(-d, --data text)] [--user-id text] [--connected-account-id text] [--toolkit-version text] <slug> Execute a tool by slug with JSON arguments.
104 +
105 - auth-configs View and manage Composio auth configs.
106
107 - auth-configs list [--toolkits text] [--query text] [--limit integer] List auth configs.