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

Add `composio listen` and top-level `composio triggers` CLI commands (#3115)

## Summary - Add `composio listen` command for real-time trigger event streaming with interactive setup flow (toolkit/trigger selection, account connection, listener subscription). - Add top-level `composio triggers list` and `composio triggers info` entrypoints alongside the existing `dev` commands. - Update root help, command hints, and README examples to advertise the new trigger and listen commands. - Refactor trigger list/info command construction so the `dev` and root variants share the same implementation with different hints and empty-state guidance. - Extend tests to cover the new root-level trigger commands, command-hint examples, and CI fixes. ## Test plan - [x] CLI unit tests for `composio triggers list` and `composio triggers info` - [x] CLI unit tests for command-hints covering trigger examples - [x] E2E tests updated for toolkit list/info/search - [ ] Manual test of `composio listen` interactive flow 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

Rahul Tarak committed Apr 6, 2026 at 00:48 UTC 91a7d044ded271dff5577bd3a2f3460cb3374c08
18 files changed +948 -132
ts/packages/cli/README.md
+1
@@ -36,6 +36,7 @@ composio [--log-level all|trace|debug|info|warning|error|fatal|none]
36 - `composio run <code> [-- ...args]` or `composio run --file <path> [-- ...args]`: Run inline or file-based TS/JS workflows with Composio helpers injected.
37 - `composio proxy <url> --toolkit <toolkit> [-X method] [-H header]... [-d data]`: Call a toolkit API directly through Composio using a connected account.
38 - `composio tools list|info`: Inspect available tools and their cached schemas.
39 +- `composio triggers list <toolkit>|info`: Inspect toolkit-scoped trigger types and their schemas.
40 - `composio artifacts cwd`: Print the cwd-scoped CLI session artifacts directory.
41 - `composio dev <subcommand>`: Developer workflows for init, playground execution, logs, toolkits, auth configs, accounts, triggers, orgs, and projects.
42 - `composio generate [-o, --output-dir <directory>] [--toolkits <toolkit>] [--type-tools]`: Auto-detect the project language (Python or TypeScript) and generate type stubs for toolkits, tools, and triggers.
ts/packages/cli/skills/composio-cli/SKILL.md
+23 -1
@@ -1,6 +1,6 @@
1 ---
2 name: composio-cli
3 -description: Help users operate the published Composio CLI to find the right tool, connect accounts, inspect schemas, execute tools, script workflows with `composio run`, and call authenticated app APIs with `composio proxy`. Use when the user asks how to do something with `composio`, wants to run a known tool slug, needs to discover a slug with `composio search`, fix a missing connection with `composio link`, inspect tool inputs with `--get-schema` or `--dry-run`, troubleshoot top-level CLI flows, or explicitly needs `composio dev` guidance.
3 +description: Help users operate the published Composio CLI to find the right tool, connect accounts, inspect schemas, execute tools, subscribe to trigger events with `composio listen`, script workflows with `composio run`, and call authenticated app APIs with `composio proxy`. Use when the user asks how to do something with `composio`, wants to run a known tool slug, needs to discover a slug with `composio search`, fix a missing connection with `composio link`, inspect tool inputs with `--get-schema` or `--dry-run`, troubleshoot top-level CLI flows, or explicitly needs `composio dev` guidance.
4 ---
5
6 # Composio CLI
@@ -78,6 +78,28 @@ composio link googlecalendar --no-browser
78
79 After linking, retry the original `execute` command.
80
81 +## `listen` — Subscribe To Trigger Events
82 +
83 +Use `composio listen` when the user wants a temporary subscription for consumer-project events, especially for background agents that should consume new emails, Slack messages, or similar trigger payloads from artifact files.
84 +
85 +The command creates a temporary trigger, subscribes to it, writes each event to the artifact folder, and disables the trigger on cleanup.
86 +
87 +```bash
88 +composio listen GMAIL_NEW_GMAIL_MESSAGE
89 +composio listen SLACK_RECEIVE_MESSAGE -p '{ trigger_config: { channel: "C123" } }'
90 +composio listen GMAIL_NEW_GMAIL_MESSAGE --stream
91 +composio listen GMAIL_NEW_GMAIL_MESSAGE --stream '.data.threadId'
92 +composio listen GMAIL_NEW_GMAIL_MESSAGE --timeout 5m
93 +composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --max-events 5
94 +```
95 +
96 +Key points:
97 +
98 +- `-p/--params` is only for trigger config fields; the connected account is resolved automatically.
99 +- `--stream` prints each event inline, and `--stream '.path.here'` prints only the selected field.
100 +- `--timeout` and `--max-events` are the normal ways to stop long-running listeners cleanly.
101 +- `composio artifacts cwd` shows the current artifact root when the user needs to inspect saved event payloads.
102 +
103 ## `proxy` — Raw API Access
104
105 Use `composio proxy` when the toolkit supports a raw API operation that is easier than finding a dedicated tool.
ts/packages/cli/src/commands/artifacts.cmd.ts
+5 -2
@@ -1,7 +1,10 @@
1 import process from 'node:process';
2 import { Command } from '@effect/cli';
3 import { Effect, Option } from 'effect';
4 -import { resolveCliSessionArtifacts } from 'src/services/cli-session-artifacts';
4 +import {
5 + resolveArtifactsRoot,
6 + resolveCliSessionArtifacts,
7 +} from 'src/services/cli-session-artifacts';
8
9 const cwdCmd = Command.make('cwd').pipe(
10 Command.withDescription('Print the cwd-scoped session artifact directory.'),
@@ -9,7 +12,7 @@ const cwdCmd = Command.make('cwd').pipe(
12 Effect.gen(function* () {
13 const artifacts = yield* resolveCliSessionArtifacts();
14 const directoryPath = Option.match(artifacts, {
12 - onNone: () => '/tmp/composio',
15 + onNone: () => resolveArtifactsRoot(),
16 onSome: value => value.directoryPath,
17 });
18 process.stdout.write(`${directoryPath}\n`);
ts/packages/cli/src/commands/index.ts
+36 -4
@@ -8,6 +8,7 @@ import { versionCmd } from './version.cmd';
8 import { upgradeCmd } from './upgrade.cmd';
9 import { whoamiCmd } from './whoami.cmd';
10 import { loginCmd } from './login.cmd';
11 +import { listenCmd } from './listen.cmd';
12 import { logoutCmd } from './logout.cmd';
13 import { runCmd } from './run.cmd';
14 import { proxyCmd } from './proxy.cmd';
@@ -23,6 +24,7 @@ import { printRootHelp, matchSubcommandHelp, printSubcommandHelp } from './root-
24 import { rootToolsCmd$Search } from './tools/commands/tools.search.cmd';
25 import { rootToolsCmd$Execute } from './tools/commands/tools.execute.cmd';
26 import { rootToolsCmd } from './tools/tools.cmd';
27 +import { rootTriggersCmd } from './triggers/root-triggers.cmd';
28 import { rootConnectedAccountsCmd$Link } from './connected-accounts/commands/connected-accounts.link.cmd';
29 import { orgsCmd } from './orgs/orgs.cmd';
30 import { renderCommandHintGraph } from 'src/services/command-hints';
@@ -41,6 +43,7 @@ const $cmd = $defaultCmd.pipe(
43 upgradeCmd,
44 whoamiCmd,
45 loginCmd,
46 + listenCmd,
47 logoutCmd,
48 runCmd,
49 proxyCmd,
@@ -48,6 +51,7 @@ const $cmd = $defaultCmd.pipe(
51 installCmd,
52 devCmd,
53 rootToolsCmd,
54 + rootTriggersCmd,
55 rootToolsCmd$Search,
56 rootConnectedAccountsCmd$Link,
57 rootToolsCmd$Execute,
@@ -125,6 +129,34 @@ const normalizeVersionShortFlag = (argv: ReadonlyArray<string>): ReadonlyArray<s
129 return argv;
130 };
131
132 +const normalizeListenStreamFlag = (argv: ReadonlyArray<string>): ReadonlyArray<string> => {
133 + const head = argv.slice(0, 2);
134 + const args = argv.slice(2);
135 + const isListen = args[0] === 'listen';
136 + if (!isListen) {
137 + return argv;
138 + }
139 +
140 + const normalized: string[] = [...head];
141 + for (let i = 0; i < args.length; i += 1) {
142 + const token = args[i];
143 + if (token !== '--stream') {
144 + normalized.push(token ?? '');
145 + continue;
146 + }
147 +
148 + const next = args[i + 1];
149 + if (next === undefined || next.startsWith('-')) {
150 + normalized.push('--stream=');
151 + continue;
152 + }
153 +
154 + normalized.push(token);
155 + }
156 +
157 + return normalized;
158 +};
159 +
160 const normalizeHiddenDebugFlags = (argv: ReadonlyArray<string>): ReadonlyArray<string> => {
161 const normalized: string[] = [...argv.slice(0, 2)];
162 const args = argv.slice(2);
@@ -188,9 +220,7 @@ const normalizeHiddenDebugFlags = (argv: ReadonlyArray<string>): ReadonlyArray<s
220
221 const isRootHelp = (argv: ReadonlyArray<string>): boolean => {
222 const args = argv.slice(2);
191 - return (
192 - args.length === 0 || (args.length === 1 && (args[0] === '--help' || args[0] === '-h'))
193 - );
223 + return args.length === 0 || (args.length === 1 && (args[0] === '--help' || args[0] === '-h'));
224 };
225
226 const isGenerateGraph = (argv: ReadonlyArray<string>): boolean => {
@@ -217,7 +247,9 @@ export const runWithConfig = Effect.gen(function* () {
247 });
248
249 return (argv: ReadonlyArray<string>) => {
220 - const normalizedArgv = normalizeHiddenDebugFlags(normalizeVersionShortFlag(argv));
250 + const normalizedArgv = normalizeHiddenDebugFlags(
251 + normalizeListenStreamFlag(normalizeVersionShortFlag(argv))
252 + );
253 if (isRootHelp(normalizedArgv)) {
254 return printRootHelp();
255 }
ts/packages/cli/src/commands/listen.cmd.ts new
+473
@@ -0,0 +1,473 @@
1 +import { Args, 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';
5 +import { requireAuth } from 'src/effects/require-auth';
6 +import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';
7 +import { ComposioClientSingleton } from 'src/services/composio-clients';
8 +import {
9 + formatResolveCommandProjectError,
10 + resolveCommandProject,
11 +} from 'src/services/command-project';
12 +import {
13 + resolveArtifactsRoot,
14 + resolveCliSessionArtifacts,
15 +} from 'src/services/cli-session-artifacts';
16 +import { TerminalUI } from 'src/services/terminal-ui';
17 +import { TriggersRealtime } from 'src/services/triggers-realtime';
18 +import { parseJsonIsh } from 'src/utils/parse-json-ish';
19 +import { toolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug';
20 +import { matchesTriggerListenFilters } from './triggers/filter';
21 +import { parseTriggerListenEvent } from './triggers/parse';
22 +
23 +const slug = Args.text({ name: 'slug' }).pipe(
24 + Args.withDescription('Trigger slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")')
25 +);
26 +
27 +const params = Options.text('params').pipe(
28 + Options.withAlias('p'),
29 + Options.withDescription('Trigger create params as JSON/JS object, @file, or - for stdin'),
30 + Options.optional
31 +);
32 +
33 +const maxEvents = Options.integer('max-events').pipe(
34 + Options.withDescription('Stop after receiving N events for this temporary trigger'),
35 + Options.optional
36 +);
37 +
38 +const timeout = Options.text('timeout').pipe(
39 + Options.withDescription('Stop after a duration such as "5m", "1hr", or "30s"'),
40 + Options.optional
41 +);
42 +
43 +const stream = Options.text('stream').pipe(
44 + Options.withDescription(
45 + 'Also stream each event payload inline. Pass an optional jq-like path such as ".thread.id" or ".data[0].id".'
46 + ),
47 + Options.optional
48 +);
49 +
50 +const debug = Options.boolean('debug').pipe(
51 + Options.withDescription(
52 + 'Print verbose debug information (raw events, filter results, Pusher state)'
53 + ),
54 + Options.withDefault(false)
55 +);
56 +
57 +const sanitizePathPart = (value: string): string =>
58 + value.replace(/[^A-Z0-9._-]+/gi, '-').replace(/^-+|-+$/g, '') || 'unknown';
59 +
60 +const resolveParamsInput = (input: Option.Option<string>) =>
61 + resolveOptionalTextInput(input, { missingValue: '{}' });
62 +
63 +const parseCreateParams = (raw: string) =>
64 + Effect.gen(function* () {
65 + const parsed = yield* Effect.try({
66 + try: () => parseJsonIsh(raw),
67 + catch: () =>
68 + new Error(
69 + "Invalid --params input. Provide JSON or a JS-style object literal, e.g. -p '{ trigger_config: { ... } }'."
70 + ),
71 + });
72 +
73 + if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
74 + return yield* Effect.fail(
75 + new Error("Expected --params to be an object, e.g. -p '{ trigger_config: { ... } }'.")
76 + );
77 + }
78 +
79 + return parsed as Record<string, unknown>;
80 + });
81 +
82 +const selectConnectedAccountId = (
83 + items: ReadonlyArray<{
84 + id: string;
85 + updated_at: string;
86 + is_disabled: boolean;
87 + }>
88 +): string | undefined => {
89 + const active = items.filter(item => !item.is_disabled);
90 + if (active.length === 0) {
91 + return undefined;
92 + }
93 +
94 + return [...active]
95 + .sort((left, right) => Date.parse(right.updated_at) - Date.parse(left.updated_at))
96 + .at(0)?.id;
97 +};
98 +
99 +const emitStreamLine = (line: string, ui: TerminalUI) =>
100 + Effect.gen(function* () {
101 + yield* ui.log.message(line);
102 + yield* ui.output(line, { force: true });
103 + });
104 +
105 +const extractEventFileId = (eventData: Record<string, unknown>): string => {
106 + const candidates = [
107 + eventData.id,
108 + eventData.log_id,
109 + typeof eventData.metadata === 'object' && eventData.metadata !== null
110 + ? (eventData.metadata as Record<string, unknown>).id
111 + : undefined,
112 + ];
113 +
114 + for (const candidate of candidates) {
115 + if (typeof candidate === 'string' && candidate.length > 0) {
116 + return sanitizePathPart(candidate);
117 + }
118 + }
119 +
120 + return `${Date.now()}-${crypto.randomUUID().slice(0, 8)}`;
121 +};
122 +
123 +const resolveFallbackArtifactsDir = () => resolveArtifactsRoot();
124 +
125 +const parseStreamPath = (expression: string): ReadonlyArray<string | number> => {
126 + const trimmed = expression.trim();
127 + if (!trimmed.startsWith('.')) {
128 + throw new Error('Expected --stream to contain a jq-like path starting with "."');
129 + }
130 +
131 + const pathTokens: Array<string | number> = [];
132 + const tokenPattern = /(?:\.([A-Za-z0-9_-]+))|(?:\[(\d+)\])/g;
133 + let lastIndex = 0;
134 +
135 + for (const match of trimmed.matchAll(tokenPattern)) {
136 + if ((match.index ?? -1) !== lastIndex) {
137 + throw new Error(
138 + 'Unsupported --stream expression. Use a jq-like path such as ".foo.bar" or ".items[0].id".'
139 + );
140 + }
141 +
142 + if (match[1]) pathTokens.push(match[1]);
143 + if (match[2]) pathTokens.push(Number(match[2]));
144 + lastIndex += match[0].length;
145 + }
146 +
147 + if (lastIndex !== trimmed.length) {
148 + throw new Error(
149 + 'Unsupported --stream expression. Use a jq-like path such as ".foo.bar" or ".items[0].id".'
150 + );
151 + }
152 +
153 + return pathTokens;
154 +};
155 +
156 +const applyStreamPath = (value: unknown, pathTokens: ReadonlyArray<string | number>): unknown => {
157 + let current = value;
158 + for (const token of pathTokens) {
159 + if (typeof token === 'number') {
160 + if (!Array.isArray(current) || token < 0 || token >= current.length) {
161 + return undefined;
162 + }
163 + current = current[token];
164 + continue;
165 + }
166 +
167 + if (typeof current !== 'object' || current === null || Array.isArray(current)) {
168 + return undefined;
169 + }
170 +
171 + current = (current as Record<string, unknown>)[token];
172 + }
173 +
174 + return current;
175 +};
176 +
177 +const formatStreamValue = (value: unknown): string => {
178 + if (value === undefined) return 'null';
179 + if (typeof value === 'string') return value;
180 + return JSON.stringify(value);
181 +};
182 +
183 +const TIMEOUT_UNITS_MS: Record<string, number> = {
184 + ms: 1,
185 + millisecond: 1,
186 + milliseconds: 1,
187 + s: 1_000,
188 + sec: 1_000,
189 + secs: 1_000,
190 + second: 1_000,
191 + seconds: 1_000,
192 + m: 60_000,
193 + min: 60_000,
194 + mins: 60_000,
195 + minute: 60_000,
196 + minutes: 60_000,
197 + h: 3_600_000,
198 + hr: 3_600_000,
199 + hrs: 3_600_000,
200 + hour: 3_600_000,
201 + hours: 3_600_000,
202 + d: 86_400_000,
203 + day: 86_400_000,
204 + days: 86_400_000,
205 +};
206 +
207 +const parseTimeoutMs = (value: string): number => {
208 + const trimmed = value.trim().toLowerCase();
209 + const match = /^(\d+(?:\.\d+)?)\s*([a-z]+)$/.exec(trimmed);
210 + if (!match) {
211 + throw new Error(
212 + 'Invalid --timeout value. Use a duration such as "30s", "5m", "1hr", or "1day".'
213 + );
214 + }
215 +
216 + const amount = Number(match[1]);
217 + const unitMs = TIMEOUT_UNITS_MS[match[2]];
218 + if (!Number.isFinite(amount) || amount <= 0 || unitMs === undefined) {
219 + throw new Error(
220 + 'Invalid --timeout value. Use a duration such as "30s", "5m", "1hr", or "1day".'
221 + );
222 + }
223 +
224 + return Math.round(amount * unitMs);
225 +};
226 +
227 +export const listenCmd = Command.make(
228 + 'listen',
229 + { slug, params, maxEvents, timeout, stream, debug },
230 + ({ slug, params, maxEvents, timeout, stream, debug }) =>
231 + Effect.gen(function* () {
232 + if (!(yield* requireAuth)) return;
233 +
234 + const ui = yield* TerminalUI;
235 + const fs = yield* FileSystem.FileSystem;
236 + const runtime = yield* Effect.runtime<never>();
237 + const clientSingleton = yield* ComposioClientSingleton;
238 + const realtime = yield* TriggersRealtime;
239 +
240 + const resolvedProject = yield* resolveCommandProject({ mode: 'consumer' }).pipe(
241 + Effect.mapError(formatResolveCommandProjectError)
242 + );
243 +
244 + const client = yield* clientSingleton.getFor({
245 + orgId: resolvedProject.orgId,
246 + projectId: resolvedProject.projectId,
247 + });
248 +
249 + if (!resolvedProject.consumerUserId) {
250 + return yield* Effect.fail(
251 + new Error('No consumer user is available in the current project context.')
252 + );
253 + }
254 +
255 + const rawParams = Option.isSome(params)
256 + ? (yield* resolveParamsInput(params))?.trim() || '{}'
257 + : '{}';
258 + const createParamsInput = yield* parseCreateParams(rawParams);
259 + const toolkitSlug = toolkitFromToolSlug(slug);
260 + if (!toolkitSlug) {
261 + return yield* Effect.fail(
262 + new Error(
263 + `Could not infer a toolkit from trigger slug "${slug}". Use a standard trigger slug such as "GMAIL_NEW_GMAIL_MESSAGE".`
264 + )
265 + );
266 + }
267 +
268 + const connectedAccounts = yield* Effect.tryPromise({
269 + try: () =>
270 + client.connectedAccounts.list({
271 + toolkit_slugs: [toolkitSlug],
272 + user_ids: resolvedProject.consumerUserId ? [resolvedProject.consumerUserId] : undefined,
273 + statuses: ['ACTIVE'],
274 + limit: 100,
275 + }),
276 + catch: error =>
277 + new Error(`Failed to list connected accounts for "${toolkitSlug}": ${String(error)}`),
278 + });
279 + const resolvedConnectedAccountId = selectConnectedAccountId(connectedAccounts.items);
280 +
281 + if (!resolvedConnectedAccountId) {
282 + return yield* Effect.fail(
283 + new Error(
284 + `No active connected account found for toolkit "${toolkitSlug}" and consumer user "${resolvedProject.consumerUserId}". Run \`composio link ${toolkitSlug}\` first.`
285 + )
286 + );
287 + }
288 +
289 + const createParams = {
290 + ...createParamsInput,
291 + connected_account_id: resolvedConnectedAccountId,
292 + } as Parameters<typeof client.triggerInstances.upsert>[1];
293 + const timeoutMs = Option.match(timeout, {
294 + onNone: () => undefined,
295 + onSome: value => parseTimeoutMs(value),
296 + });
297 + const streamPath = Option.match(stream, {
298 + onNone: () => undefined,
299 + onSome: value => {
300 + const trimmed = value.trim();
301 + return trimmed.length === 0 ? [] : parseStreamPath(trimmed);
302 + },
303 + });
304 + const shouldStream = Option.isSome(stream);
305 +
306 + const artifactsOption = yield* resolveCliSessionArtifacts({
307 + orgId: resolvedProject.orgId,
308 + consumerUserId: resolvedProject.consumerUserId,
309 + });
310 + const artifactsRoot = Option.match(artifactsOption, {
311 + onNone: () => resolveFallbackArtifactsDir(),
312 + onSome: value => value.directoryPath,
313 + });
314 + const triggerDir = path.join(artifactsRoot, 'triggers', sanitizePathPart(slug));
315 + const streamFilePath = path.join(triggerDir, 'events.jsonl');
316 +
317 + yield* fs.makeDirectory(triggerDir, { recursive: true });
318 + yield* fs.writeFileString(streamFilePath, '', { flag: 'a' });
319 +
320 + const maxEventsLimit = Option.getOrUndefined(maxEvents);
321 + const stopWhenDone = yield* Deferred.make<'max-events' | 'timeout'>();
322 + let matchingEvents = 0;
323 + const seenEventIds = new Set<string>();
324 +
325 + yield* Effect.acquireUseRelease(
326 + Effect.tryPromise({
327 + try: () => client.triggerInstances.upsert(slug, createParams),
328 + catch: error =>
329 + new Error(`Failed to create temporary trigger "${slug}": ${String(error)}`),
330 + }),
331 + createdTrigger =>
332 + Effect.gen(function* () {
333 + yield* emitStreamLine(`listening for events ${slug} (tail at ${streamFilePath})`, ui);
334 + if (debug) {
335 + const debugMsg = `[debug] trigger_id=${createdTrigger.trigger_id} project=${resolvedProject.projectId} org=${resolvedProject.orgId} createParams=${JSON.stringify(createParams)}`;
336 + yield* emitStreamLine(debugMsg, ui);
337 + yield* emitStreamLine(
338 + `[debug] upsert response: ${JSON.stringify(createdTrigger)}`,
339 + ui
340 + );
341 + }
342 +
343 + const onEvent = (eventData: Record<string, unknown>) => {
344 + Runtime.runFork(runtime)(
345 + Effect.gen(function* () {
346 + if (debug) {
347 + yield* emitStreamLine(
348 + `[debug] raw event keys: ${Object.keys(eventData).join(', ')}`,
349 + ui
350 + );
351 + yield* emitStreamLine(
352 + `[debug] raw event (truncated): ${JSON.stringify(eventData).slice(0, 500)}`,
353 + ui
354 + );
355 + }
356 + const parsed = parseTriggerListenEvent(eventData);
357 + const filterResult = matchesTriggerListenFilters(
358 + { triggerId: createdTrigger.trigger_id },
359 + parsed
360 + );
361 + if (debug) {
362 + yield* emitStreamLine(
363 + `[debug] parsed.id=${parsed.id} triggerSlug=${parsed.triggerSlug} trigger_id=${createdTrigger.trigger_id} match=${filterResult}`,
364 + ui
365 + );
366 + }
367 + if (!filterResult) {
368 + return;
369 + }
370 +
371 + const eventFileId = extractEventFileId(eventData);
372 + if (seenEventIds.has(eventFileId)) {
373 + if (debug) {
374 + yield* emitStreamLine(`[debug] skipping duplicate event ${eventFileId}`, ui);
375 + }
376 + return;
377 + }
378 + seenEventIds.add(eventFileId);
379 +
380 + matchingEvents += 1;
381 + const eventFilePath = path.join(triggerDir, `${eventFileId}-payload.json`);
382 + const eventJson = JSON.stringify(eventData, null, 2);
383 + const streamEntry = JSON.stringify({
384 + event_id: eventFileId,
385 + trigger_id: createdTrigger.trigger_id,
386 + trigger_slug: slug,
387 + file_path: eventFilePath,
388 + received_at: new Date().toISOString(),
389 + });
390 +
391 + yield* fs.writeFileString(eventFilePath, `${eventJson}\n`);
392 + yield* fs.writeFileString(streamFilePath, `${streamEntry}\n`, { flag: 'a' });
393 + yield* emitStreamLine(`event: ${eventFilePath}`, ui);
394 +
395 + if (shouldStream) {
396 + const streamValue =
397 + streamPath === undefined
398 + ? eventData
399 + : streamPath.length === 0
400 + ? eventData
401 + : applyStreamPath(eventData, streamPath);
402 + yield* emitStreamLine(`stream: ${formatStreamValue(streamValue)}`, ui);
403 + }
404 +
405 + if (maxEventsLimit !== undefined && matchingEvents >= maxEventsLimit) {
406 + yield* Deferred.succeed(stopWhenDone, 'max-events').pipe(Effect.ignore);
407 + }
408 + }).pipe(
409 + Effect.catchAll(error =>
410 + ui.log.warn(error instanceof Error ? error.message : String(error))
411 + )
412 + )
413 + );
414 + };
415 +
416 + const listenEffect = realtime
417 + .listenInProject(
418 + {
419 + orgId: resolvedProject.orgId,
420 + projectId: resolvedProject.projectId,
421 + },
422 + onEvent
423 + )
424 + .pipe(Effect.onInterrupt(() => ui.log.info(`Stopped listening for events ${slug}.`)));
425 +
426 + if (timeoutMs !== undefined) {
427 + yield* Effect.forkScoped(
428 + Effect.sleep(timeoutMs).pipe(
429 + Effect.andThen(Deferred.succeed(stopWhenDone, 'timeout')),
430 + Effect.ignore
431 + )
432 + );
433 + }
434 +
435 + if (maxEventsLimit === undefined && timeoutMs === undefined) {
436 + yield* listenEffect;
437 + return;
438 + }
439 +
440 + const stopReason = yield* Effect.raceFirst(listenEffect, Deferred.await(stopWhenDone));
441 + if (stopReason === 'max-events') {
442 + yield* ui.outro(
443 + `Stopped after receiving ${matchingEvents} events. Temporary trigger disabled.`
444 + );
445 + return;
446 + }
447 +
448 + if (stopReason === 'timeout') {
449 + yield* ui.outro(
450 + `Stopped after timeout with ${matchingEvents} matching event${matchingEvents === 1 ? '' : 's'}. Temporary trigger disabled.`
451 + );
452 + }
453 + }),
454 + created =>
455 + Effect.tryPromise({
456 + try: () =>
457 + client.triggerInstances.manage.update(created.trigger_id, { status: 'disable' }),
458 + catch: error =>
459 + new Error(
460 + `Failed to disable temporary trigger "${created.trigger_id}": ${String(error)}`
461 + ),
462 + }).pipe(
463 + Effect.catchAll(error =>
464 + ui.log.warn(error instanceof Error ? error.message : String(error))
465 + )
466 + )
467 + );
468 + })
469 +).pipe(
470 + Command.withDescription(
471 + 'Create a temporary subscription for consumer-project events and write each event to artifacts for easy background-agent consumption.'
472 + )
473 +);
ts/packages/cli/src/commands/root-help.ts
+96 -5
@@ -72,6 +72,35 @@ const CORE_COMMANDS: ReadonlyArray<DetailedCommand> = [
72 { name: '--dry-run', description: 'Preview execute() calls without running remote actions' },
73 ],
74 },
75 + {
76 + name: 'listen',
77 + description:
78 + 'Create a temporary subscription for consumer-project events and persist each payload into the session artifact folder.',
79 + usage:
80 + 'listen <slug> [-p, --params text] [--max-events integer] [--timeout text] [--stream [text]]',
81 + options: [
82 + { name: '<slug>', description: 'Trigger slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")' },
83 + {
84 + name: '-p, --params',
85 + description:
86 + "Trigger create params as JSON or JS-style object, e.g. -p '{ trigger_config: { ... } }'.",
87 + },
88 + {
89 + name: '--max-events',
90 + description: 'Stop after receiving N events, then disable the temporary trigger',
91 + },
92 + {
93 + name: '--timeout',
94 + description:
95 + 'Stop after a duration such as 30s, 5m, or 1hr, then disable the temporary trigger',
96 + },
97 + {
98 + name: '--stream',
99 + description:
100 + 'Also print each payload inline as a single-line stream value. Optionally pass a jq-like path such as ".thread.id".',
101 + },
102 + ],
103 + },
104 {
105 name: 'proxy',
106 description:
@@ -92,6 +121,14 @@ const CORE_COMMANDS: ReadonlyArray<DetailedCommand> = [
121 const OTHER_COMMANDS: ReadonlyArray<CompactCommand> = [
122 { name: 'composio tools info <slug>', description: 'Print tool summary and cache its schema' },
123 { name: 'composio tools list <toolkit>', description: 'List tools available in a toolkit' },
124 + {
125 + name: 'composio triggers info <slug>',
126 + description: 'Print trigger type details and schema summaries',
127 + },
128 + {
129 + name: 'composio triggers list <toolkit>',
130 + description: 'List available trigger types in a toolkit',
131 + },
132 {
133 name: 'composio artifacts cwd',
134 description: 'Print the cwd-scoped session artifact directory',
@@ -264,6 +301,47 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {
301 'composio artifacts cwd Print the current session artifact directory',
302 ],
303 },
304 + listen: {
305 + usage:
306 + 'composio listen <slug> [-p, --params text] [--max-events integer] [--timeout text] [--stream [text]]',
307 + description:
308 + 'Create a temporary subscription for consumer-project events so background agents can easily consume new emails, Slack messages, and other trigger payloads from artifacts.',
309 + args: [{ name: '<slug>', description: 'Trigger slug to create and listen to' }],
310 + options: [
311 + {
312 + name: '-p, --params <text>',
313 + description:
314 + 'Trigger create params as JSON/JS object, @file, or - for stdin. Pass optional trigger config fields only.',
315 + },
316 + {
317 + name: '--max-events <integer>',
318 + description: 'Stop after N events for this temporary trigger and disable it',
319 + },
320 + {
321 + name: '--timeout <text>',
322 + description: 'Stop after a duration such as "30s", "5m", or "1hr" and disable the trigger',
323 + },
324 + {
325 + name: '--stream [text]',
326 + description:
327 + 'Also print each event payload inline. Optionally pass a jq-like path such as ".thread.id" or ".data[0].id".',
328 + },
329 + ],
330 + examples: [
331 + 'composio listen GMAIL_NEW_GMAIL_MESSAGE',
332 + 'composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --max-events 5',
333 + 'composio listen GMAIL_NEW_GMAIL_MESSAGE --timeout 5m',
334 + "composio listen GMAIL_NEW_GMAIL_MESSAGE --timeout 1hr --stream '.data.threadId'",
335 + 'composio listen SLACK_RECEIVE_MESSAGE -p \'{ trigger_config: { channel: "C123" } }\'',
336 + 'composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --stream',
337 + "composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --stream '.data.threadId'",
338 + ],
339 + seeAlso: [
340 + 'composio artifacts cwd Print the current session artifact directory',
341 + 'composio triggers info <slug> Inspect trigger type details before listening',
342 + 'composio link <toolkit> Connect the required account before creating the trigger',
343 + ],
344 + },
345 link: {
346 usage: 'composio link [<toolkit>] [--no-wait]',
347 description:
@@ -511,6 +589,19 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {
589 'View a brief summary of a tool and show the CLI-facing schema used by `composio execute --get-schema`.',
590 args: [{ name: '<slug>', description: 'Tool slug (e.g. "GMAIL_SEND_EMAIL")' }],
591 },
592 + 'triggers list': {
593 + usage: 'composio triggers list <toolkit> [--limit integer]',
594 + description: 'List available trigger types for a toolkit.',
595 + args: [
596 + { name: '<toolkit>', description: 'Toolkit slug to list trigger types for (e.g. "gmail")' },
597 + ],
598 + options: [{ name: '--limit <integer>', description: 'Number of results' }],
599 + },
600 + 'triggers info': {
601 + usage: 'composio triggers info [<slug>]',
602 + description: 'View details of a specific trigger type.',
603 + args: [{ name: '<slug>', description: 'Trigger slug' }],
604 + },
605
606 // ── Generate commands ─────────────────────────────────────────────────
607
@@ -722,12 +813,12 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {
813 flags: [{ name: '-y, --yes', description: 'Skip confirmation prompt' }],
814 },
815 'dev triggers list': {
725 - usage: 'composio dev triggers list [--toolkits text] [--limit integer]',
726 - description: 'List available trigger types.',
727 - options: [
728 - { name: '--toolkits <text>', description: 'Filter by toolkit slugs' },
729 - { name: '--limit <integer>', description: 'Number of results' },
816 + usage: 'composio dev triggers list <toolkit> [--limit integer]',
817 + description: 'List available trigger types for a toolkit.',
818 + args: [
819 + { name: '<toolkit>', description: 'Toolkit slug to list trigger types for (e.g. "gmail")' },
820 ],
821 + options: [{ name: '--limit <integer>', description: 'Number of results' }],
822 },
823 'dev triggers info': {
824 usage: 'composio dev triggers info [<slug>]',
ts/packages/cli/src/commands/triggers/commands/triggers.info.cmd.ts
+61 -38
@@ -6,6 +6,12 @@ import { ComposioToolkitsRepository } from 'src/services/composio-clients';
6 import { TerminalUI } from 'src/services/terminal-ui';
7 import { formatTriggerTypeInfo } from '../format';
8
9 +type TriggersInfoCommandConfig = {
10 + readonly exampleCommand: string;
11 + readonly listCommand: string;
12 + readonly listCommandPlaceholder: string;
13 +};
14 +
15 const slug = Args.text({ name: 'slug' }).pipe(
16 Args.withDescription('Trigger slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")'),
17 Args.optional
@@ -19,50 +25,67 @@ const slug = Args.text({ name: 'slug' }).pipe(
25 * composio dev triggers info "GMAIL_NEW_GMAIL_MESSAGE"
26 * ```
27 */
22 -export const triggersCmd$Info = Command.make('info', { slug }, ({ slug }) =>
23 - Effect.gen(function* () {
24 - if (!(yield* requireAuth)) return;
28 +const makeTriggersInfoCommand = ({
29 + exampleCommand,
30 + listCommand,
31 + listCommandPlaceholder,
32 +}: TriggersInfoCommandConfig) =>
33 + Command.make('info', { slug }, ({ slug }) =>
34 + Effect.gen(function* () {
35 + if (!(yield* requireAuth)) return;
36 +
37 + const ui = yield* TerminalUI;
38 + const repo = yield* ComposioToolkitsRepository;
39 +
40 + if (Option.isNone(slug)) {
41 + yield* ui.log.warn('Missing required argument: <slug>');
42 + yield* ui.log.step(
43 + `Try specifying a trigger slug, e.g.:\n> ${exampleCommand} "GMAIL_NEW_GMAIL_MESSAGE"`
44 + );
45 + return;
46 + }
47
26 - const ui = yield* TerminalUI;
27 - const repo = yield* ComposioToolkitsRepository;
48 + const slugValue = slug.value;
49
29 - if (Option.isNone(slug)) {
30 - yield* ui.log.warn('Missing required argument: <slug>');
31 - yield* ui.log.step(
32 - 'Try specifying a trigger slug, e.g.:\n> composio dev triggers info "GMAIL_NEW_GMAIL_MESSAGE"'
33 - );
34 - return;
35 - }
50 + const triggerTypeOpt = yield* ui
51 + .withSpinner('Fetching trigger type details...', repo.getTriggerTypeDetailed(slugValue))
52 + .pipe(
53 + Effect.asSome,
54 + Effect.catchTag(
55 + 'services/HttpServerError',
56 + handleHttpServerError(ui, {
57 + fallbackMessage: `Trigger "${slugValue}" not found.`,
58 + hint: `Browse available trigger types:\n> ${listCommandPlaceholder}`,
59 + fallbackValue: Option.none(),
60 + })
61 + )
62 + );
63
37 - const slugValue = slug.value;
64 + if (Option.isNone(triggerTypeOpt)) return;
65
39 - const triggerTypeOpt = yield* ui
40 - .withSpinner('Fetching trigger type details...', repo.getTriggerTypeDetailed(slugValue))
41 - .pipe(
42 - Effect.asSome,
43 - Effect.catchTag(
44 - 'services/HttpServerError',
45 - handleHttpServerError(ui, {
46 - fallbackMessage: `Trigger "${slugValue}" not found.`,
47 - hint: 'Browse available trigger types:\n> composio dev triggers list',
48 - fallbackValue: Option.none(),
49 - })
50 - )
51 - );
66 + const triggerType = triggerTypeOpt.value;
67
53 - if (Option.isNone(triggerTypeOpt)) return;
68 + yield* ui.note(formatTriggerTypeInfo(triggerType), `Trigger: ${triggerType.name}`);
69
55 - const triggerType = triggerTypeOpt.value;
70 + const toolkitSlug = triggerType.toolkit?.slug?.toLowerCase();
71 + if (toolkitSlug) {
72 + yield* ui.log.step(
73 + `To list more trigger types in this toolkit:\n> ${listCommand} "${toolkitSlug}"`
74 + );
75 + }
76
57 - yield* ui.note(formatTriggerTypeInfo(triggerType), `Trigger: ${triggerType.name}`);
77 + yield* ui.output(JSON.stringify(triggerType, null, 2));
78 + })
79 + ).pipe(Command.withDescription('View details of a specific trigger type.'));
80
59 - const toolkitSlug = triggerType.toolkit?.slug?.toLowerCase();
60 - if (toolkitSlug) {
61 - yield* ui.log.step(
62 - `To list more trigger types in this toolkit:\n> composio dev triggers list --toolkits "${toolkitSlug}"`
63 - );
64 - }
81 +export const triggersCmd$Info = makeTriggersInfoCommand({
82 + exampleCommand: 'composio dev triggers info',
83 + listCommand: 'composio dev triggers list',
84 + listCommandPlaceholder: 'composio dev triggers list "<toolkit>"',
85 +});
86
66 - yield* ui.output(JSON.stringify(triggerType, null, 2));
67 - })
68 -).pipe(Command.withDescription('View details of a specific trigger type.'));
87 +export const rootTriggersCmd$Info = makeTriggersInfoCommand({
88 + exampleCommand: 'composio triggers info',
89 + listCommand: 'composio triggers list',
90 + listCommandPlaceholder: 'composio triggers list "<toolkit>"',
91 +});
ts/packages/cli/src/commands/triggers/commands/triggers.list.cmd.ts
+66 -43
@@ -1,17 +1,18 @@
1 -import { Command, Options } from '@effect/cli';
2 -import { Effect, Option } from 'effect';
1 +import { Args, Command, Options } from '@effect/cli';
2 +import { Effect } from 'effect';
3 import { requireAuth } from 'src/effects/require-auth';
4 -import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 +import { ComposioToolkitsRepository, InvalidToolkitsError } from 'src/services/composio-clients';
5 import { TerminalUI } from 'src/services/terminal-ui';
6 import { clampLimit } from 'src/ui/clamp-limit';
7 import { formatTriggerTypesJson, formatTriggerTypesTable } from '../format';
8 -import { parseCsv } from '../parse-csv';
8
10 -const toolkits = Options.text('toolkits').pipe(
11 - Options.withDescription(
12 - 'Filter by toolkit slugs, comma-separated (e.g. "gmail" or "gmail,slack")'
13 - ),
14 - Options.optional
9 +type TriggersListCommandConfig = {
10 + readonly noResultsCommand: string;
11 + readonly infoCommand: string;
12 +};
13 +
14 +const toolkit = Args.text({ name: 'toolkit' }).pipe(
15 + Args.withDescription('Toolkit slug to list trigger types for (e.g. "gmail")')
16 );
17
18 const limit = Options.integer('limit').pipe(
@@ -24,46 +25,68 @@ const limit = Options.integer('limit').pipe(
25 *
26 * @example
27 * ```bash
27 - * composio dev triggers list
28 - * composio dev triggers list --toolkits "gmail"
29 - * composio dev triggers list --toolkits "gmail,slack"
28 + * composio dev triggers list gmail
29 + * composio dev triggers list slack --limit 10
30 * ```
31 */
32 -export const triggersCmd$List = Command.make('list', { toolkits, limit }, ({ toolkits, limit }) =>
33 - Effect.gen(function* () {
34 - if (!(yield* requireAuth)) return;
32 +const makeTriggersListCommand = ({ noResultsCommand, infoCommand }: TriggersListCommandConfig) =>
33 + Command.make('list', { toolkit, limit }, ({ toolkit, limit }) =>
34 + Effect.gen(function* () {
35 + if (!(yield* requireAuth)) return;
36
36 - const ui = yield* TerminalUI;
37 - const repo = yield* ComposioToolkitsRepository;
38 - const toolkitFilters = Option.isSome(toolkits) ? parseCsv(toolkits.value) : undefined;
39 - const clampedLimit = clampLimit(limit);
37 + const ui = yield* TerminalUI;
38 + const repo = yield* ComposioToolkitsRepository;
39 + const clampedLimit = clampLimit(limit);
40
41 - const allTriggerTypes = yield* ui.withSpinner(
42 - 'Fetching trigger types...',
43 - repo.getTriggerTypes(toolkitFilters)
44 - );
45 - const triggerTypes = allTriggerTypes.slice(0, clampedLimit);
41 + yield* repo.validateToolkits([toolkit]).pipe(
42 + Effect.catchTag('services/InvalidToolkitsError', (error: InvalidToolkitsError) =>
43 + Effect.gen(function* () {
44 + const availableExample = error.availableToolkits.slice(0, 8).join(', ');
45 + yield* ui.log.error(
46 + `Toolkit "${toolkit}" is not available. ${availableExample ? `Examples: ${availableExample}` : ''}`
47 + );
48 + yield* ui.log.step(`List valid toolkits with:\n> ${noResultsCommand}`);
49 + return yield* Effect.fail(
50 + new Error(`Invalid toolkit slug "${toolkit}" for trigger listing.`)
51 + );
52 + })
53 + )
54 + );
55
47 - if (triggerTypes.length === 0) {
48 - const hint = Option.isSome(toolkits)
49 - ? `No trigger types found in toolkit "${toolkits.value}". Verify the toolkit slug with:\n> composio dev toolkits list`
50 - : 'No trigger types found.';
51 - yield* ui.log.warn(hint);
52 - return;
53 - }
56 + const allTriggerTypes = yield* ui.withSpinner(
57 + 'Fetching trigger types...',
58 + repo.getTriggerTypes([toolkit])
59 + );
60 + const triggerTypes = allTriggerTypes.slice(0, clampedLimit);
61
55 - const count = triggerTypes.length;
56 - yield* ui.log.info(
57 - `Listing ${count} trigger type${count === 1 ? '' : 's'}\n\n${formatTriggerTypesTable(triggerTypes)}`
58 - );
62 + if (triggerTypes.length === 0) {
63 + yield* ui.log.warn(
64 + `No trigger types found in toolkit "${toolkit}". Verify the toolkit slug with:\n> ${noResultsCommand}`
65 + );
66 + return;
67 + }
68
60 - const firstSlug = triggerTypes[0]?.slug;
61 - if (firstSlug) {
62 - yield* ui.log.step(
63 - `To view details of a trigger type:\n> composio dev triggers info "${firstSlug}"`
69 + const count = triggerTypes.length;
70 + yield* ui.note(
71 + formatTriggerTypesTable(triggerTypes),
72 + `Listing ${count} trigger type${count === 1 ? '' : 's'}`
73 );
65 - }
74
67 - yield* ui.output(formatTriggerTypesJson(triggerTypes));
68 - })
69 -).pipe(Command.withDescription('List available trigger types.'));
75 + const firstSlug = triggerTypes[0]?.slug;
76 + if (firstSlug) {
77 + yield* ui.log.step(`To view details of a trigger type:\n> ${infoCommand} "${firstSlug}"`);
78 + }
79 +
80 + yield* ui.output(formatTriggerTypesJson(triggerTypes));
81 + })
82 + ).pipe(Command.withDescription('List available trigger types.'));
83 +
84 +export const triggersCmd$List = makeTriggersListCommand({
85 + noResultsCommand: 'composio dev toolkits list',
86 + infoCommand: 'composio dev triggers info',
87 +});
88 +
89 +export const rootTriggersCmd$List = makeTriggersListCommand({
90 + noResultsCommand: 'composio toolkits list',
91 + infoCommand: 'composio triggers info',
92 +});
ts/packages/cli/src/commands/triggers/root-triggers.cmd.ts new
+8
@@ -0,0 +1,8 @@
1 +import { Command } from '@effect/cli';
2 +import { rootTriggersCmd$Info } from './commands/triggers.info.cmd';
3 +import { rootTriggersCmd$List } from './commands/triggers.list.cmd';
4 +
5 +export const rootTriggersCmd = Command.make('triggers').pipe(
6 + Command.withDescription('Browse and inspect trigger types before creating subscriptions.'),
7 + Command.withSubcommands([rootTriggersCmd$List, rootTriggersCmd$Info])
8 +);
ts/packages/cli/src/services/cli-session-artifacts.ts
+1 -1
@@ -4,7 +4,7 @@ import path from 'node:path';
4 import { Effect, Option } from 'effect';
5 import { getOrCreateProbablyMyCliSessionIdForCurrentCwd } from 'src/services/consumer-short-term-cache';
6
7 -const resolveArtifactsRoot = (): string =>
7 +export const resolveArtifactsRoot = (): string =>
8 process.env.COMPOSIO_SESSION_DIR?.trim() ||
9 process.env.COMPOSIO_CACHE_DIR?.trim() ||
10 path.join(os.tmpdir(), 'composio');
ts/packages/cli/src/services/command-hints.ts
+10
@@ -7,6 +7,8 @@ export type CommandHintId =
7 | 'root.search'
8 | 'root.tools.list'
9 | 'root.tools.info'
10 + | 'root.triggers.list'
11 + | 'root.triggers.info'
12 | 'root.execute'
13 | 'root.execute.getSchema'
14 | 'root.link'
@@ -40,6 +42,14 @@ export const COMMAND_HINTS: Record<CommandHintId, CommandHintNode> = {
42 example: params => `composio tools info "${getParam(params, 'slug', '<slug>')}"`,
43 links: ['root.execute.getSchema', 'root.execute'],
44 },
45 + 'root.triggers.list': {
46 + example: params => `composio triggers list "${getParam(params, 'toolkit', '<toolkit>')}"`,
47 + links: ['root.triggers.info'],
48 + },
49 + 'root.triggers.info': {
50 + example: params => `composio triggers info "${getParam(params, 'slug', '<slug>')}"`,
51 + links: ['root.triggers.list'],
52 + },
53 'root.execute': {
54 example: params =>
55 `composio execute "${getParam(params, 'slug', '<slug>')}" ${getParam(params, 'data', "-d '{}'")}`.trim(),
ts/packages/cli/src/services/run-subagent-acp.ts
+3
@@ -422,6 +422,9 @@ export const createStructuredOutputMcpContext = ({
422
423 let tempDirectory: string | null = null;
424 try {
425 + // Keep this on an OS temp dir for now. Repointing MCP schema/result files into
426 + // session artifacts needs a broader bundling + run-companion test pass so we
427 + // don't break structured sub-agent output in packaged CLI builds.
428 tempDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-subagent-output-mcp-'));
429 const schemaFilePath = path.join(tempDirectory, 'schema.json');
430 const resultFilePath = path.join(tempDirectory, 'result.json');
ts/packages/cli/src/services/triggers-realtime.ts
+56 -11
@@ -1,5 +1,10 @@
1 import { Data, Effect, Runtime } from 'effect';
2 -import { ComposioSessionRepository } from 'src/services/composio-clients';
2 +import {
3 + ComposioClientSingleton,
4 + ComposioSessionRepository,
5 + type CliRealtimeAuthResponse,
6 + type CliRealtimeCredentialsResponse,
7 +} from 'src/services/composio-clients';
8
9 type RawRealtimeEvent = Record<string, unknown>;
10
@@ -71,12 +76,20 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
76 {
77 effect: Effect.gen(function* () {
78 const sessionRepo = yield* ComposioSessionRepository;
79 + const clientSingleton = yield* ComposioClientSingleton;
80 const runtime = yield* Effect.runtime<never>();
81
76 - const listen = (onEvent: (data: RawRealtimeEvent) => void) =>
82 + const listenWith = (params: {
83 + getRealtimeCredentials: () => Effect.Effect<CliRealtimeCredentialsResponse>;
84 + authRealtimeChannel: (params: {
85 + channel_name: string;
86 + socket_id: string;
87 + }) => Effect.Effect<CliRealtimeAuthResponse>;
88 + onEvent: (data: RawRealtimeEvent) => void;
89 + }) =>
90 Effect.acquireUseRelease(
91 Effect.gen(function* () {
79 - const creds = yield* sessionRepo.getRealtimeCredentials();
92 + const creds = yield* params.getRealtimeCredentials();
93 const channelName = `private-cli-${creds.project_id}`;
94
95 const pusherModule = yield* Effect.tryPromise({
@@ -90,9 +103,9 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
103 cluster: creds.pusher_cluster,
104 channelAuthorization: {
105 customHandler: (authOptions: PusherAuthOptions, callback?: PusherAuthCallback) => {
93 - const params = authOptions.params ?? authOptions;
94 - const channel_name = params.channel_name ?? params.channelName;
95 - const socket_id = params.socket_id ?? params.socketId;
106 + const authParams = authOptions.params ?? authOptions;
107 + const channel_name = authParams.channel_name ?? authParams.channelName;
108 + const socket_id = authParams.socket_id ?? authParams.socketId;
109
110 const doAuth = async () => {
111 if (!channel_name || !socket_id) {
@@ -100,7 +113,7 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
113 }
114
115 const response = await Runtime.runPromise(runtime)(
103 - sessionRepo.authRealtimeChannel({
116 + params.authRealtimeChannel({
117 channel_name,
118 socket_id,
119 })
@@ -167,7 +180,7 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
180 }, CHUNK_TTL_MS);
181
182 channel.bind('trigger_to_client', eventData => {
170 - onEvent((eventData ?? {}) as RawRealtimeEvent);
183 + params.onEvent((eventData ?? {}) as RawRealtimeEvent);
184 });
185
186 channel.bind('chunked-trigger_to_client', data => {
@@ -217,7 +230,7 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
230 ) {
231 try {
232 const parsed = JSON.parse(current.chunks.join('')) as RawRealtimeEvent;
220 - onEvent(parsed);
233 + params.onEvent(parsed);
234 } catch {
235 // Silently discard events that fail to parse after chunk reassembly
236 } finally {
@@ -243,8 +256,40 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
256 }).pipe(Effect.catchAll(() => Effect.void))
257 );
258
246 - return { listen };
259 + const listen = (onEvent: (data: RawRealtimeEvent) => void) =>
260 + listenWith({
261 + getRealtimeCredentials: () => sessionRepo.getRealtimeCredentials().pipe(Effect.orDie),
262 + authRealtimeChannel: params => sessionRepo.authRealtimeChannel(params).pipe(Effect.orDie),
263 + onEvent,
264 + });
265 +
266 + const listenInProject = (
267 + scope: { orgId: string; projectId: string },
268 + onEvent: (data: RawRealtimeEvent) => void
269 + ) =>
270 + Effect.gen(function* () {
271 + const client = yield* clientSingleton.getFor({
272 + orgId: scope.orgId,
273 + projectId: scope.projectId,
274 + });
275 +
276 + return yield* listenWith({
277 + getRealtimeCredentials: () =>
278 + Effect.tryPromise({
279 + try: () => client.cli.realtime.credentials(),
280 + catch: cause => new TriggerRealtimeSubscriptionError({ cause }),
281 + }).pipe(Effect.orDie),
282 + authRealtimeChannel: params =>
283 + Effect.tryPromise({
284 + try: () => client.cli.realtime.auth(params),
285 + catch: cause => new TriggerRealtimeSubscriptionError({ cause }),
286 + }).pipe(Effect.orDie),
287 + onEvent,
288 + });
289 + });
290 +
291 + return { listen, listenInProject };
292 }),
248 - dependencies: [ComposioSessionRepository.Default],
293 + dependencies: [ComposioSessionRepository.Default, ComposioClientSingleton.Default],
294 }
295 ) {}
ts/packages/cli/test/__utils__/services/test-layer.ts
+5
@@ -765,6 +765,11 @@ export const TestLayer = (input?: TestLiveInput) =>
765 yield* Effect.forEach(realtimeData.events, event => Effect.sync(() => onEvent(event)));
766 return yield* Effect.never;
767 }),
768 + listenInProject: (_scope, onEvent) =>
769 + Effect.gen(function* () {
770 + yield* Effect.forEach(realtimeData.events, event => Effect.sync(() => onEvent(event)));
771 + return yield* Effect.never;
772 + }),
773 })
774 );
775
ts/packages/cli/test/src/commands/$default.cmd.test.ts
+3 -1
@@ -1,3 +1,5 @@
1 +import os from 'node:os';
2 +import path from 'node:path';
3 import { describe, expect, layer } from '@effect/vitest';
4 import { Effect } from 'effect';
5 import { ValidationError, HelpDoc } from '@effect/cli';
@@ -116,7 +118,7 @@ describe('CLI: composio', () => {
118 .join('\n')
119 .trim();
120
119 - expect(output).toContain('/tmp/composio');
121 + expect(output).toContain(path.join(os.tmpdir(), 'composio'));
122 })
123 );
124 });
ts/packages/cli/test/src/commands/triggers/triggers.info.cmd.test.ts
+18 -2
@@ -55,6 +55,22 @@ const testConfigProvider = ConfigProvider.fromMap(
55 ).pipe(extendConfigProvider);
56
57 describe('CLI: composio dev triggers info', () => {
58 + layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
59 + '[Given] root triggers info [Then] displays trigger info with root-level hint',
60 + it => {
61 + it.scoped('supports the top-level triggers info entrypoint', () =>
62 + Effect.gen(function* () {
63 + yield* cli(['triggers', 'info', 'GMAIL_NEW_GMAIL_MESSAGE']);
64 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
65 + const output = lines.join('\n');
66 +
67 + expect(output).toContain('GMAIL_NEW_GMAIL_MESSAGE');
68 + expect(output).toContain('composio triggers list "gmail"');
69 + })
70 + );
71 + }
72 + );
73 +
74 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
75 '[Given] valid slug [Then] displays trigger type info',
76 it => {
@@ -73,7 +89,7 @@ describe('CLI: composio dev triggers info', () => {
89 expect(output).toContain('subject');
90 expect(output).toContain('default:');
91 expect(output).toContain('false');
76 - expect(output).toContain('composio dev triggers list --toolkits "gmail"');
92 + expect(output).toContain('composio dev triggers list "gmail"');
93 })
94 );
95 }
@@ -104,7 +120,7 @@ describe('CLI: composio dev triggers info', () => {
120 const output = lines.join('\n');
121
122 expect(output).toContain('not found');
107 - expect(output).toContain('composio dev triggers list');
123 + expect(output).toContain('composio dev triggers list "<toolkit>"');
124 })
125 );
126 }
ts/packages/cli/test/src/commands/triggers/triggers.list.cmd.test.ts
+79 -24
@@ -4,6 +4,7 @@ import { extendConfigProvider } from 'src/services/config';
4 import { cli, MockConsole, TestLive } from 'test/__utils__';
5 import type { TriggerTypes } from 'src/models/trigger-types';
6 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
7 +import { makeTestToolkits } from 'test/__utils__/models/toolkits';
8
9 const testTriggerTypes: TriggerTypes = [
10 {
@@ -38,7 +39,13 @@ const testTriggerTypes: TriggerTypes = [
39 },
40 ];
41
42 +const testToolkits = makeTestToolkits([
43 + { name: 'Gmail', slug: 'gmail' },
44 + { name: 'Slack', slug: 'slack' },
45 +]);
46 +
47 const toolkitsData = {
48 + toolkits: testToolkits,
49 triggerTypes: testTriggerTypes,
50 } satisfies TestLiveInput['toolkitsData'];
51
@@ -47,29 +54,75 @@ const testConfigProvider = ConfigProvider.fromMap(
54 ).pipe(extendConfigProvider);
55
56 describe('CLI: composio dev triggers list', () => {
57 + layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
58 + '[Given] root triggers list [Then] lists trigger types with root-level hint',
59 + it => {
60 + it.scoped('supports the top-level triggers list entrypoint', () =>
61 + Effect.gen(function* () {
62 + yield* cli(['triggers', 'list', 'gmail']);
63 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
64 + const output = lines.join('\n');
65 +
66 + expect(output).toContain('GMAIL_NEW_GMAIL_MESSAGE');
67 + expect(output).toContain('Listing 2 trigger types');
68 + expect(output).toContain('composio triggers info');
69 + })
70 + );
71 + }
72 + );
73 +
74 + layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
75 + '[Given] root triggers list with nonexistent toolkit [Then] shows root toolkit hint',
76 + it => {
77 + it.scoped('uses root toolkit command in the no-results hint', () =>
78 + Effect.gen(function* () {
79 + yield* cli(['triggers', 'list', 'nonexistent']).pipe(Effect.ignore);
80 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
81 + const output = lines.join('\n');
82 +
83 + expect(output).toContain('not available');
84 + expect(output).toContain('composio toolkits list');
85 + expect(output).not.toContain('composio dev toolkits list');
86 + })
87 + );
88 + }
89 + );
90 +
91 + layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
92 + '[Given] no toolkit [Then] parse fails because toolkit is required',
93 + it => {
94 + it.scoped('requires a toolkit positional argument', () =>
95 + Effect.gen(function* () {
96 + const exit = yield* cli(['triggers', 'list']).pipe(Effect.exit);
97 + expect(JSON.stringify(exit)).toContain('toolkit');
98 + })
99 + );
100 + }
101 + );
102 +
103 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
104 '[Given] no flags [Then] lists all trigger types',
105 it => {
106 it.scoped('lists all trigger types', () =>
107 Effect.gen(function* () {
55 - yield* cli(['dev', 'triggers', 'list']);
108 + yield* cli(['dev', 'triggers', 'list', 'gmail']);
109 const lines = yield* MockConsole.getLines({ stripAnsi: true });
110 const output = lines.join('\n');
111
112 expect(output).toContain('GMAIL_NEW_GMAIL_MESSAGE');
60 - expect(output).toContain('SLACK_NEW_MESSAGE');
61 - expect(output).toContain('Listing 3 trigger types');
113 + expect(output).not.toContain('SLACK_NEW_MESSAGE');
114 + expect(output).toContain('Listing 2 trigger types');
115 })
116 );
117 }
118 );
119
120 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
68 - '[Given] --toolkits "gmail" [Then] lists only gmail trigger types',
121 + '[Given] toolkit "gmail" [Then] lists only gmail trigger types',
122 it => {
123 it.scoped('filters by toolkit', () =>
124 Effect.gen(function* () {
72 - yield* cli(['dev', 'triggers', 'list', '--toolkits', 'gmail']);
125 + yield* cli(['dev', 'triggers', 'list', 'gmail']);
126 const lines = yield* MockConsole.getLines({ stripAnsi: true });
127 const output = lines.join('\n');
128
@@ -87,7 +140,7 @@ describe('CLI: composio dev triggers list', () => {
140 it => {
141 it.scoped('uses singular form for one result', () =>
142 Effect.gen(function* () {
90 - yield* cli(['dev', 'triggers', 'list', '--limit', '1']);
143 + yield* cli(['dev', 'triggers', 'list', 'gmail', '--limit', '1']);
144 const lines = yield* MockConsole.getLines({ stripAnsi: true });
145 const output = lines.join('\n');
146
@@ -103,7 +156,7 @@ describe('CLI: composio dev triggers list', () => {
156 it => {
157 it.scoped('shows hint to view trigger details', () =>
158 Effect.gen(function* () {
106 - yield* cli(['dev', 'triggers', 'list']);
159 + yield* cli(['dev', 'triggers', 'list', 'gmail']);
160 const lines = yield* MockConsole.getLines({ stripAnsi: true });
161 const output = lines.join('\n');
162
@@ -116,7 +169,7 @@ describe('CLI: composio dev triggers list', () => {
169 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
170 it.scoped('warns user to login', () =>
171 Effect.gen(function* () {
119 - yield* cli(['dev', 'triggers', 'list']);
172 + yield* cli(['dev', 'triggers', 'list', 'gmail']);
173 const lines = yield* MockConsole.getLines({ stripAnsi: true });
174 const output = lines.join('\n');
175
@@ -125,31 +178,33 @@ describe('CLI: composio dev triggers list', () => {
178 );
179 });
180
128 - layer(TestLive({ baseConfigProvider: testConfigProvider }))(
129 - '[Given] empty results [Then] shows no trigger types found',
130 - it => {
131 - it.scoped('shows no trigger types found', () =>
132 - Effect.gen(function* () {
133 - yield* cli(['dev', 'triggers', 'list']);
134 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
135 - const output = lines.join('\n');
181 + layer(
182 + TestLive({
183 + baseConfigProvider: testConfigProvider,
184 + toolkitsData: { toolkits: makeTestToolkits([{ name: 'Gmail', slug: 'gmail' }]) },
185 + })
186 + )('[Given] empty results [Then] shows no trigger types found', it => {
187 + it.scoped('shows no trigger types found', () =>
188 + Effect.gen(function* () {
189 + yield* cli(['dev', 'triggers', 'list', 'gmail']);
190 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
191 + const output = lines.join('\n');
192
137 - expect(output).toContain('No trigger types found');
138 - })
139 - );
140 - }
141 - );
193 + expect(output).toContain('No trigger types found');
194 + })
195 + );
196 + });
197
198 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
144 - '[Given] --toolkits "nonexistent" [Then] shows no trigger types found with hint',
199 + '[Given] toolkit "nonexistent" [Then] shows invalid toolkit error with hint',
200 it => {
201 it.scoped('shows hint about verifying toolkit slug', () =>
202 Effect.gen(function* () {
148 - yield* cli(['dev', 'triggers', 'list', '--toolkits', 'nonexistent']);
203 + yield* cli(['dev', 'triggers', 'list', 'nonexistent']).pipe(Effect.ignore);
204 const lines = yield* MockConsole.getLines({ stripAnsi: true });
205 const output = lines.join('\n');
206
152 - expect(output).toContain('No trigger types found');
207 + expect(output).toContain('not available');
208 expect(output).toContain('composio dev toolkits list');
209 })
210 );
ts/packages/cli/test/src/services/command-hints.test.ts
+4
@@ -20,6 +20,10 @@ describe('command-hints', () => {
20
21 it('renders examples from the registry', () => {
22 expect(commandHintExample('root.tools.list')).toContain('composio tools list');
23 + expect(commandHintExample('root.triggers.list')).toContain('composio triggers list');
24 + expect(commandHintExample('root.triggers.info', { slug: 'GMAIL_NEW_GMAIL_MESSAGE' })).toContain(
25 + 'GMAIL_NEW_GMAIL_MESSAGE'
26 + );
27 expect(commandHintExample('root.execute', { slug: 'GMAIL_SEND_EMAIL' })).toContain(
28 'GMAIL_SEND_EMAIL'
29 );