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.

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

jkomyno2a6e73b20127
diff --git a/ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts b/ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts
index 0e384eb85..3fc41f724 100644
--- a/ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts
+++ b/ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts
@@ -1,8 +1,7 @@
import { Command, Options } from '@effect/cli';
+import { FileSystem } from '@effect/platform';
import { Deferred, Effect, Option, Runtime } from 'effect';
import path from 'node:path';
-import process from 'node:process';
-import { promises as fs } from 'node:fs';
import { requireAuth } from 'src/effects/require-auth';
import { TerminalUI } from 'src/services/terminal-ui';
import { TriggersRealtime } from 'src/services/triggers-realtime';
@@ -134,15 +133,20 @@ const detectWebhookPayloadVersion = (eventData: Record<string, unknown>): 'V1' |
const emitTableLine = (line: string, ui: TerminalUI): Effect.Effect<void> =>
Effect.gen(function* () {
- if (process.stdout.isTTY) {
- yield* Effect.sync(() => {
- process.stderr.write(`${line}\n`);
- });
- return;
- }
+ yield* ui.log.message(line);
yield* ui.output(line);
});
+/**
+ * Listen to realtime trigger events for your project.
+ *
+ * @example
+ * ```bash
+ * composio triggers listen --toolkits gmail --table
+ * composio triggers listen --trigger-slug GMAIL_NEW_GMAIL_MESSAGE --json --max-events 5
+ * composio triggers listen --forward "http://localhost:8080/webhook" --out events.jsonl
+ * ```
+ */
export const triggersCmd$Listen = Command.make(
'listen',
{
@@ -173,6 +177,7 @@ export const triggersCmd$Listen = Command.make(
if (!(yield* requireAuth)) return;
const ui = yield* TerminalUI;
+ const fs = yield* FileSystem.FileSystem;
const realtime = yield* TriggersRealtime;
const runtime = yield* Effect.runtime<never>();
const forwardUrl = Option.getOrUndefined(forward);
@@ -183,19 +188,9 @@ export const triggersCmd$Listen = Command.make(
if (outputFilePath) {
// Ensure output directory exists before listening.
- yield* Effect.tryPromise({
- try: async () => {
- await fs.mkdir(path.dirname(outputFilePath), { recursive: true });
- },
- catch: error => new Error(`Failed to prepare output file directory: ${String(error)}`),
- }).pipe(
- Effect.catchAll(error =>
- Effect.gen(function* () {
- yield* ui.log.error(String(error));
- return yield* Effect.fail(error);
- })
- )
- );
+ yield* fs
+ .makeDirectory(path.dirname(outputFilePath), { recursive: true })
+ .pipe(Effect.tapError(error => ui.log.error(String(error))));
}
const filters: TriggerListenFilters = {
@@ -232,9 +227,6 @@ export const triggersCmd$Listen = Command.make(
if (outputFilePath) {
yield* ui.log.info(`Writing matching events to: ${outputFilePath}`);
}
- if (forwardUrl) {
- yield* ui.log.info(`Forwarding matching events to: ${forwardUrl}`);
- }
if (maxEventsLimit !== undefined) {
yield* ui.log.info(`Auto-stop after ${maxEventsLimit} matching events.`);
@@ -278,47 +270,50 @@ export const triggersCmd$Listen = Command.make(
const logLine = `${payloadForForwarding}\n`;
if (outputFilePath) {
- yield* Effect.tryPromise({
- try: () => fs.appendFile(outputFilePath, logLine, 'utf8'),
- catch: error => new Error(`Failed writing to ${outputFilePath}: ${String(error)}`),
- }).pipe(Effect.catchAll(error => ui.log.warn(String(error))));
+ yield* fs
+ .writeFileString(outputFilePath, logLine, { flag: 'a' })
+ .pipe(Effect.catchAll(error => ui.log.warn(String(error))));
}
if (forwardUrl && webhookSecret) {
- const webhookId =
- typeof eventData.id === 'string' && eventData.id.length > 0
- ? eventData.id
- : randomUUID();
- const webhookTimestamp = `${Math.floor(Date.now() / 1000)}`;
- const webhookSignature = yield* Effect.tryPromise(() =>
- signWebhookPayload({
- secret: webhookSecret,
- webhookId,
- webhookTimestamp,
- payload: payloadForForwarding,
- })
- );
- const webhookVersion = detectWebhookPayloadVersion(eventData);
-
- yield* Effect.tryPromise({
- try: async () => {
- const response = await fetch(forwardUrl, {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- 'webhook-id': webhookId,
- 'webhook-timestamp': webhookTimestamp,
- 'webhook-signature': webhookSignature,
- 'x-composio-webhook-version': webhookVersion,
- },
- body: payloadForForwarding,
- });
- if (!response.ok) {
- throw new Error(`Forwarding failed with HTTP ${response.status}`);
- }
- },
- catch: error =>
- new Error(`Failed forwarding event to ${forwardUrl}: ${String(error)}`),
+ yield* Effect.gen(function* () {
+ const webhookId =
+ typeof eventData.id === 'string' && eventData.id.length > 0
+ ? eventData.id
+ : randomUUID();
+ const webhookTimestamp = `${Math.floor(Date.now() / 1000)}`;
+ const webhookSignature = yield* Effect.tryPromise({
+ try: () =>
+ signWebhookPayload({
+ secret: webhookSecret,
+ webhookId,
+ webhookTimestamp,
+ payload: payloadForForwarding,
+ }),
+ catch: error => new Error(`Failed to sign webhook payload: ${String(error)}`),
+ });
+ const webhookVersion = detectWebhookPayloadVersion(eventData);
+
+ yield* Effect.tryPromise({
+ try: async () => {
+ const response = await fetch(forwardUrl, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ 'webhook-id': webhookId,
+ 'webhook-timestamp': webhookTimestamp,
+ 'webhook-signature': webhookSignature,
+ 'x-composio-webhook-version': webhookVersion,
+ },
+ body: payloadForForwarding,
+ });
+ if (!response.ok) {
+ throw new Error(`Forwarding failed with HTTP ${response.status}`);
+ }
+ },
+ catch: error =>
+ new Error(`Failed forwarding event to ${forwardUrl}: ${String(error)}`),
+ });
}).pipe(Effect.catchAll(error => ui.log.warn(String(error))));
}
diff --git a/ts/packages/cli/src/commands/triggers/filter.ts b/ts/packages/cli/src/commands/triggers/filter.ts
index 6e11540bf..462d07158 100644
--- a/ts/packages/cli/src/commands/triggers/filter.ts
+++ b/ts/packages/cli/src/commands/triggers/filter.ts
@@ -29,7 +29,7 @@ export const matchesTriggerListenFilters = (
return false;
}
- if (filters.userId && filters.userId !== data.metadata.connectedAccount.userId) {
+ if (filters.userId && filters.userId !== data.userId) {
return false;
}
diff --git a/ts/packages/cli/src/services/triggers-realtime.ts b/ts/packages/cli/src/services/triggers-realtime.ts
index 60bf6b905..88e7d44e9 100644
--- a/ts/packages/cli/src/services/triggers-realtime.ts
+++ b/ts/packages/cli/src/services/triggers-realtime.ts
@@ -1,4 +1,4 @@
-import { Data, Effect } from 'effect';
+import { Data, Effect, Runtime } from 'effect';
import { ComposioSessionRepository } from 'src/services/composio-clients';
type RawRealtimeEvent = Record<string, unknown>;
@@ -70,6 +70,7 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
{
effect: Effect.gen(function* () {
const sessionRepo = yield* ComposioSessionRepository;
+ const runtime = yield* Effect.runtime<never>();
const listen = (onEvent: (data: RawRealtimeEvent) => void) =>
Effect.acquireUseRelease(
@@ -97,7 +98,7 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
throw new Error('Missing channel_name or socket_id for realtime auth');
}
- const response = await Effect.runPromise(
+ const response = await Runtime.runPromise(runtime)(
sessionRepo.authRealtimeChannel({
channel_name,
socket_id,
@@ -125,7 +126,44 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
});
const channel = pusher.subscribe(channelName);
- const chunkedEvents = new Map<string, { chunks: string[]; receivedFinal: boolean }>();
+
+ // Pusher has a 10 KB per-message limit. When the Composio backend
+ // produces a trigger payload that exceeds this, it splits the JSON
+ // into numbered chunks sent as separate `chunked-trigger_to_client`
+ // events. We reassemble them here by accumulating chunks keyed by
+ // event id, then joining once the final chunk arrives and every
+ // intermediate index is present.
+ //
+ // Guard-rails:
+ // - Reject chunk indices outside [0, MAX_CHUNK_INDEX] to prevent a
+ // single malformed event from allocating a huge sparse array.
+ // - Evict incomplete entries older than CHUNK_TTL_MS so that lost
+ // chunks don't leak memory over long-running sessions.
+ // - Cap the total number of in-flight reassemblies to bound memory
+ // usage even under pathological input.
+ const MAX_CHUNK_INDEX = 1_000;
+ const CHUNK_TTL_MS = 60_000;
+ const MAX_PENDING_CHUNKS = 100;
+
+ type PendingChunkedEvent = {
+ chunks: string[];
+ receivedFinal: boolean;
+ createdAt: number;
+ };
+
+ const chunkedEvents = new Map<string, PendingChunkedEvent>();
+
+ // Periodic sweep: drop entries that have been sitting incomplete for
+ // longer than CHUNK_TTL_MS. Runs every CHUNK_TTL_MS and is cleared
+ // on shutdown.
+ const cleanupInterval = setInterval(() => {
+ const now = Date.now();
+ for (const [id, entry] of chunkedEvents) {
+ if (now - entry.createdAt > CHUNK_TTL_MS) {
+ chunkedEvents.delete(id);
+ }
+ }
+ }, CHUNK_TTL_MS);
channel.bind('trigger_to_client', eventData => {
onEvent((eventData ?? {}) as RawRealtimeEvent);
@@ -137,8 +175,29 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
return;
}
+ // Reject non-integer or out-of-range indices to prevent a single
+ // malformed event from creating a massive sparse array.
+ if (
+ !Number.isInteger(typed.index) ||
+ typed.index < 0 ||
+ typed.index > MAX_CHUNK_INDEX
+ ) {
+ return;
+ }
+
if (!chunkedEvents.has(typed.id)) {
- chunkedEvents.set(typed.id, { chunks: [], receivedFinal: false });
+ // If we already have too many in-flight reassemblies, drop the
+ // oldest one to make room.
+ if (chunkedEvents.size >= MAX_PENDING_CHUNKS) {
+ const oldestId = chunkedEvents.keys().next().value;
+ if (oldestId !== undefined) chunkedEvents.delete(oldestId);
+ }
+
+ chunkedEvents.set(typed.id, {
+ chunks: [],
+ receivedFinal: false,
+ createdAt: Date.now(),
+ });
}
const current = chunkedEvents.get(typed.id)!;
@@ -147,6 +206,10 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
current.receivedFinal = true;
}
+ // Completeness check: for a dense array, .length equals the
+ // number of defined keys. For a sparse array (missing chunks),
+ // .length is highestIndex + 1 but Object.keys only counts the
+ // indices that were actually assigned, so the two diverge.
if (
current.receivedFinal &&
current.chunks.length === Object.keys(current.chunks).length
@@ -154,6 +217,8 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
try {
const parsed = JSON.parse(current.chunks.join('')) as RawRealtimeEvent;
onEvent(parsed);
+ } catch {
+ // Silently discard events that fail to parse after chunk reassembly
} finally {
chunkedEvents.delete(typed.id);
}
@@ -162,6 +227,7 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
return {
shutdown: async () => {
+ clearInterval(cleanupInterval);
channel.unbind?.();
pusher.unsubscribe(channelName);
pusher.disconnect();
diff --git a/ts/packages/cli/test/src/commands/$default.cmd.test.ts b/ts/packages/cli/test/src/commands/$default.cmd.test.ts
index d6f2662c0..f12f0a284 100644
--- a/ts/packages/cli/test/src/commands/$default.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/$default.cmd.test.ts
@@ -96,12 +96,12 @@ describe('CLI: composio', () => {
- tools list [--query text] [--toolkits text] [--tags text] [--limit integer] List available tools.
- - tools execute [(-d, --data text)] [--user-id text] [--connected-account-id text] [--toolkit-version text] <slug> Execute a tool by slug with JSON arguments.
-
- tools info [<slug>] View details of a specific tool.
- tools search [--toolkits text] [--limit integer] <query> Search tools by use case.
+ - tools execute [(-d, --data text)] [--user-id text] [--connected-account-id text] [--toolkit-version text] <slug> Execute a tool by slug with JSON arguments.
+
- auth-configs View and manage Composio auth configs.
- auth-configs list [--toolkits text] [--query text] [--limit integer] List auth configs.