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.

refactor(cli): address review findings for trigger commands

jkomyno069dc1eff6e8
diff --git a/ts/packages/cli/src/commands/triggers/commands/triggers.create.cmd.ts b/ts/packages/cli/src/commands/triggers/commands/triggers.create.cmd.ts
index 3dcda05d2..44aced60b 100644
--- a/ts/packages/cli/src/commands/triggers/commands/triggers.create.cmd.ts
+++ b/ts/packages/cli/src/commands/triggers/commands/triggers.create.cmd.ts
@@ -44,7 +44,14 @@ export const triggersCmd$Create = Command.make(
let parsedTriggerConfig: Record<string, unknown> | undefined;
if (Option.isSome(triggerConfig)) {
try {
- parsedTriggerConfig = JSON.parse(triggerConfig.value) as Record<string, unknown>;
+ const parsed: unknown = JSON.parse(triggerConfig.value);
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
+ yield* ui.log.error(
+ '--trigger-config must be a JSON object (e.g. \'{"key":"value"}\').'
+ );
+ return;
+ }
+ parsedTriggerConfig = parsed as Record<string, unknown>;
} catch {
yield* ui.log.error('Invalid JSON in --trigger-config. Please provide valid JSON.');
yield* ui.log.step(
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..7ec20902c 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';
@@ -12,6 +11,7 @@ import {
formatTriggerListenTableHeader,
formatTriggerListenTableRow,
} from '../format';
+import { parseCsv } from '../parse-csv';
import { parseTriggerListenEvent } from '../parse';
import type { TriggerListenFilters } from '../types';
@@ -73,12 +73,6 @@ const out = Options.text('out').pipe(
Options.optional
);
-const parseCsv = (value: string): ReadonlyArray<string> =>
- value
- .split(',')
- .map(item => item.trim())
- .filter(Boolean);
-
const randomUUID = () => crypto.randomUUID();
const signWebhookPayload = async ({
@@ -134,15 +128,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 +172,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,26 +183,20 @@ 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 = {
- toolkits: Option.isSome(toolkits) ? parseCsv(toolkits.value) : undefined,
+ toolkits: Option.isSome(toolkits)
+ ? parseCsv(toolkits.value).map(x => x.toLowerCase())
+ : undefined,
triggerId: Option.getOrUndefined(triggerId),
connectedAccountId: Option.getOrUndefined(connectedAccountId),
- triggerSlug: Option.isSome(triggerSlug) ? parseCsv(triggerSlug.value) : undefined,
+ triggerSlug: Option.isSome(triggerSlug)
+ ? parseCsv(triggerSlug.value).map(x => x.toLowerCase())
+ : undefined,
userId: Option.getOrUndefined(userId),
};
@@ -232,9 +226,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 +269,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/commands/triggers.status.cmd.ts b/ts/packages/cli/src/commands/triggers/commands/triggers.status.cmd.ts
index e1c7cc5c8..1eda09463 100644
--- a/ts/packages/cli/src/commands/triggers/commands/triggers.status.cmd.ts
+++ b/ts/packages/cli/src/commands/triggers/commands/triggers.status.cmd.ts
@@ -10,6 +10,7 @@ import {
formatTriggersStatusTable,
toolkitSlugFromTriggerName,
} from '../format';
+import { parseCsv } from '../parse-csv';
const userIds = Options.text('user-ids').pipe(
Options.withDescription('Filter by user IDs, comma-separated'),
@@ -45,36 +46,13 @@ const showDisabled = Options.boolean('show-disabled').pipe(
Options.withDescription('Include disabled triggers in the response')
);
-const deprecatedConnectedAccountUuids = Options.text('deprecated-connected-account-uuids').pipe(
- Options.withDescription(
- 'DEPRECATED: Use --connected-account-ids instead. Filter by connected account UUIDs, comma-separated'
- ),
- Options.optional
-);
-
const limit = Options.integer('limit').pipe(
Options.withDefault(30),
Options.withDescription('Number of results per page (1-1000)')
);
-const parseCsv = (value: string): string[] =>
- value
- .split(',')
- .map(item => item.trim())
- .filter(Boolean);
-
const csvOption = (opt: Option.Option<string>): string[] | undefined =>
- Option.isSome(opt) ? parseCsv(opt.value) : undefined;
-
-const mergeCsvOptions = (
- preferred: Option.Option<string>,
- deprecated: Option.Option<string>
-): string[] | undefined => {
- const preferredValues = csvOption(preferred) ?? [];
- const deprecatedValues = csvOption(deprecated) ?? [];
- const merged = [...preferredValues, ...deprecatedValues];
- return merged.length > 0 ? merged : undefined;
-};
+ Option.isSome(opt) ? [...parseCsv(opt.value)] : undefined;
/**
* Display active trigger instances with optional filters.
@@ -88,29 +66,16 @@ export const triggersCmd$Status = Command.make(
triggerIds,
triggerNames,
showDisabled,
- deprecatedConnectedAccountUuids,
limit,
},
- ({
- userIds,
- connectedAccountIds,
- toolkits,
- triggerIds,
- triggerNames,
- showDisabled,
- deprecatedConnectedAccountUuids,
- limit,
- }) =>
+ ({ userIds, connectedAccountIds, toolkits, triggerIds, triggerNames, showDisabled, limit }) =>
Effect.gen(function* () {
if (!(yield* requireAuth)) return;
const ui = yield* TerminalUI;
const repo = yield* ComposioToolkitsRepository;
- const connectedAccountIdsList = mergeCsvOptions(
- connectedAccountIds,
- deprecatedConnectedAccountUuids
- );
+ const connectedAccountIdsList = csvOption(connectedAccountIds);
const triggerNamesList = csvOption(triggerNames)?.map(name => name.toUpperCase());
const toolkitsList = csvOption(toolkits)?.map(slug => slug.toLowerCase());
diff --git a/ts/packages/cli/src/commands/triggers/filter.ts b/ts/packages/cli/src/commands/triggers/filter.ts
index 6e11540bf..cf296703b 100644
--- a/ts/packages/cli/src/commands/triggers/filter.ts
+++ b/ts/packages/cli/src/commands/triggers/filter.ts
@@ -1,13 +1,17 @@
import type { TriggerListenEvent, TriggerListenFilters } from './types';
+/**
+ * Check if a trigger event matches the provided filters.
+ *
+ * IMPORTANT: `filters.toolkits` and `filters.triggerSlug` must be pre-normalized
+ * to lowercase at construction time. This avoids per-event allocation from
+ * repeated `.map(x => x.toLowerCase())` calls in long-running listen sessions.
+ */
export const matchesTriggerListenFilters = (
filters: TriggerListenFilters,
data: TriggerListenEvent
): boolean => {
- if (
- filters.toolkits?.length &&
- !filters.toolkits.map(x => x.toLowerCase()).includes(data.toolkitSlug.toLowerCase())
- ) {
+ if (filters.toolkits?.length && !filters.toolkits.includes(data.toolkitSlug.toLowerCase())) {
return false;
}
@@ -24,12 +28,12 @@ export const matchesTriggerListenFilters = (
if (
filters.triggerSlug?.length &&
- !filters.triggerSlug.map(x => x.toLowerCase()).includes(data.triggerSlug.toLowerCase())
+ !filters.triggerSlug.includes(data.triggerSlug.toLowerCase())
) {
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/test/src/commands/triggers/triggers.mutations.cmd.test.ts b/ts/packages/cli/test/src/commands/triggers/triggers.mutations.cmd.test.ts
index a95012134..3e181203f 100644
--- a/ts/packages/cli/test/src/commands/triggers/triggers.mutations.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/triggers/triggers.mutations.cmd.test.ts
@@ -87,6 +87,37 @@ describe('CLI: composio triggers mutations', () => {
}
);
+ layer(TestLive({ baseConfigProvider: testConfigProvider }))(
+ '[Given] create with non-object JSON config [Then] shows type validation error',
+ it => {
+ it.scoped('rejects array JSON in --trigger-config', () =>
+ Effect.gen(function* () {
+ yield* cli([
+ 'triggers',
+ 'create',
+ 'GMAIL_NEW_GMAIL_MESSAGE',
+ '--trigger-config',
+ '[1,2,3]',
+ ]);
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
+ const output = lines.join('\n');
+
+ expect(output).toContain('--trigger-config must be a JSON object');
+ })
+ );
+
+ it.scoped('rejects number JSON in --trigger-config', () =>
+ Effect.gen(function* () {
+ yield* cli(['triggers', 'create', 'GMAIL_NEW_GMAIL_MESSAGE', '--trigger-config', '42']);
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
+ const output = lines.join('\n');
+
+ expect(output).toContain('--trigger-config must be a JSON object');
+ })
+ );
+ }
+ );
+
layer(TestLive({ baseConfigProvider: testConfigProvider }))(
'[Given] missing ID for enable [Then] warns about missing argument',
it => {
@@ -100,4 +131,32 @@ describe('CLI: composio triggers mutations', () => {
);
}
);
+
+ layer(TestLive({ baseConfigProvider: testConfigProvider }))(
+ '[Given] missing ID for disable [Then] warns about missing argument',
+ it => {
+ it.scoped('shows missing id warning', () =>
+ Effect.gen(function* () {
+ yield* cli(['triggers', 'disable']);
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
+ const output = lines.join('\n');
+ expect(output).toContain('Missing required argument');
+ })
+ );
+ }
+ );
+
+ layer(TestLive({ baseConfigProvider: testConfigProvider }))(
+ '[Given] missing ID for delete [Then] warns about missing argument',
+ it => {
+ it.scoped('shows missing id warning', () =>
+ Effect.gen(function* () {
+ yield* cli(['triggers', 'delete']);
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
+ const output = lines.join('\n');
+ expect(output).toContain('Missing required argument');
+ })
+ );
+ }
+ );
});