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.

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

Rahul Tarak91a7d044ded2
diff --git a/ts/packages/cli/README.md b/ts/packages/cli/README.md
index 00c83b35a..00fe13037 100644
--- a/ts/packages/cli/README.md
+++ b/ts/packages/cli/README.md
@@ -36,6 +36,7 @@ composio [--log-level all|trace|debug|info|warning|error|fatal|none]
- `composio run <code> [-- ...args]` or `composio run --file <path> [-- ...args]`: Run inline or file-based TS/JS workflows with Composio helpers injected.
- `composio proxy <url> --toolkit <toolkit> [-X method] [-H header]... [-d data]`: Call a toolkit API directly through Composio using a connected account.
- `composio tools list|info`: Inspect available tools and their cached schemas.
+- `composio triggers list <toolkit>|info`: Inspect toolkit-scoped trigger types and their schemas.
- `composio artifacts cwd`: Print the cwd-scoped CLI session artifacts directory.
- `composio dev <subcommand>`: Developer workflows for init, playground execution, logs, toolkits, auth configs, accounts, triggers, orgs, and projects.
- `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.
diff --git a/ts/packages/cli/skills/composio-cli/SKILL.md b/ts/packages/cli/skills/composio-cli/SKILL.md
index 7169bb9c5..b6240aa93 100644
--- a/ts/packages/cli/skills/composio-cli/SKILL.md
+++ b/ts/packages/cli/skills/composio-cli/SKILL.md
@@ -1,6 +1,6 @@
---
name: composio-cli
-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.
+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.
---
# Composio CLI
@@ -78,6 +78,28 @@ composio link googlecalendar --no-browser
After linking, retry the original `execute` command.
+## `listen` — Subscribe To Trigger Events
+
+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.
+
+The command creates a temporary trigger, subscribes to it, writes each event to the artifact folder, and disables the trigger on cleanup.
+
+```bash
+composio listen GMAIL_NEW_GMAIL_MESSAGE
+composio listen SLACK_RECEIVE_MESSAGE -p '{ trigger_config: { channel: "C123" } }'
+composio listen GMAIL_NEW_GMAIL_MESSAGE --stream
+composio listen GMAIL_NEW_GMAIL_MESSAGE --stream '.data.threadId'
+composio listen GMAIL_NEW_GMAIL_MESSAGE --timeout 5m
+composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --max-events 5
+```
+
+Key points:
+
+- `-p/--params` is only for trigger config fields; the connected account is resolved automatically.
+- `--stream` prints each event inline, and `--stream '.path.here'` prints only the selected field.
+- `--timeout` and `--max-events` are the normal ways to stop long-running listeners cleanly.
+- `composio artifacts cwd` shows the current artifact root when the user needs to inspect saved event payloads.
+
## `proxy` — Raw API Access
Use `composio proxy` when the toolkit supports a raw API operation that is easier than finding a dedicated tool.
diff --git a/ts/packages/cli/src/commands/artifacts.cmd.ts b/ts/packages/cli/src/commands/artifacts.cmd.ts
index 2923cd8b5..575df594e 100644
--- a/ts/packages/cli/src/commands/artifacts.cmd.ts
+++ b/ts/packages/cli/src/commands/artifacts.cmd.ts
@@ -1,7 +1,10 @@
import process from 'node:process';
import { Command } from '@effect/cli';
import { Effect, Option } from 'effect';
-import { resolveCliSessionArtifacts } from 'src/services/cli-session-artifacts';
+import {
+ resolveArtifactsRoot,
+ resolveCliSessionArtifacts,
+} from 'src/services/cli-session-artifacts';
const cwdCmd = Command.make('cwd').pipe(
Command.withDescription('Print the cwd-scoped session artifact directory.'),
@@ -9,7 +12,7 @@ const cwdCmd = Command.make('cwd').pipe(
Effect.gen(function* () {
const artifacts = yield* resolveCliSessionArtifacts();
const directoryPath = Option.match(artifacts, {
- onNone: () => '/tmp/composio',
+ onNone: () => resolveArtifactsRoot(),
onSome: value => value.directoryPath,
});
process.stdout.write(`${directoryPath}\n`);
diff --git a/ts/packages/cli/src/commands/index.ts b/ts/packages/cli/src/commands/index.ts
index f85e8ab95..28ffcf3ed 100644
--- a/ts/packages/cli/src/commands/index.ts
+++ b/ts/packages/cli/src/commands/index.ts
@@ -8,6 +8,7 @@ import { versionCmd } from './version.cmd';
import { upgradeCmd } from './upgrade.cmd';
import { whoamiCmd } from './whoami.cmd';
import { loginCmd } from './login.cmd';
+import { listenCmd } from './listen.cmd';
import { logoutCmd } from './logout.cmd';
import { runCmd } from './run.cmd';
import { proxyCmd } from './proxy.cmd';
@@ -23,6 +24,7 @@ import { printRootHelp, matchSubcommandHelp, printSubcommandHelp } from './root-
import { rootToolsCmd$Search } from './tools/commands/tools.search.cmd';
import { rootToolsCmd$Execute } from './tools/commands/tools.execute.cmd';
import { rootToolsCmd } from './tools/tools.cmd';
+import { rootTriggersCmd } from './triggers/root-triggers.cmd';
import { rootConnectedAccountsCmd$Link } from './connected-accounts/commands/connected-accounts.link.cmd';
import { orgsCmd } from './orgs/orgs.cmd';
import { renderCommandHintGraph } from 'src/services/command-hints';
@@ -41,6 +43,7 @@ const $cmd = $defaultCmd.pipe(
upgradeCmd,
whoamiCmd,
loginCmd,
+ listenCmd,
logoutCmd,
runCmd,
proxyCmd,
@@ -48,6 +51,7 @@ const $cmd = $defaultCmd.pipe(
installCmd,
devCmd,
rootToolsCmd,
+ rootTriggersCmd,
rootToolsCmd$Search,
rootConnectedAccountsCmd$Link,
rootToolsCmd$Execute,
@@ -125,6 +129,34 @@ const normalizeVersionShortFlag = (argv: ReadonlyArray<string>): ReadonlyArray<s
return argv;
};
+const normalizeListenStreamFlag = (argv: ReadonlyArray<string>): ReadonlyArray<string> => {
+ const head = argv.slice(0, 2);
+ const args = argv.slice(2);
+ const isListen = args[0] === 'listen';
+ if (!isListen) {
+ return argv;
+ }
+
+ const normalized: string[] = [...head];
+ for (let i = 0; i < args.length; i += 1) {
+ const token = args[i];
+ if (token !== '--stream') {
+ normalized.push(token ?? '');
+ continue;
+ }
+
+ const next = args[i + 1];
+ if (next === undefined || next.startsWith('-')) {
+ normalized.push('--stream=');
+ continue;
+ }
+
+ normalized.push(token);
+ }
+
+ return normalized;
+};
+
const normalizeHiddenDebugFlags = (argv: ReadonlyArray<string>): ReadonlyArray<string> => {
const normalized: string[] = [...argv.slice(0, 2)];
const args = argv.slice(2);
@@ -188,9 +220,7 @@ const normalizeHiddenDebugFlags = (argv: ReadonlyArray<string>): ReadonlyArray<s
const isRootHelp = (argv: ReadonlyArray<string>): boolean => {
const args = argv.slice(2);
- return (
- args.length === 0 || (args.length === 1 && (args[0] === '--help' || args[0] === '-h'))
- );
+ return args.length === 0 || (args.length === 1 && (args[0] === '--help' || args[0] === '-h'));
};
const isGenerateGraph = (argv: ReadonlyArray<string>): boolean => {
@@ -217,7 +247,9 @@ export const runWithConfig = Effect.gen(function* () {
});
return (argv: ReadonlyArray<string>) => {
- const normalizedArgv = normalizeHiddenDebugFlags(normalizeVersionShortFlag(argv));
+ const normalizedArgv = normalizeHiddenDebugFlags(
+ normalizeListenStreamFlag(normalizeVersionShortFlag(argv))
+ );
if (isRootHelp(normalizedArgv)) {
return printRootHelp();
}
diff --git a/ts/packages/cli/src/commands/listen.cmd.ts b/ts/packages/cli/src/commands/listen.cmd.ts
new file mode 100644
index 000000000..956705489
--- /dev/null
+++ b/ts/packages/cli/src/commands/listen.cmd.ts
@@ -0,0 +1,473 @@
+import { Args, Command, Options } from '@effect/cli';
+import { FileSystem } from '@effect/platform';
+import { Deferred, Effect, Option, Runtime } from 'effect';
+import path from 'node:path';
+import { requireAuth } from 'src/effects/require-auth';
+import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';
+import { ComposioClientSingleton } from 'src/services/composio-clients';
+import {
+ formatResolveCommandProjectError,
+ resolveCommandProject,
+} from 'src/services/command-project';
+import {
+ resolveArtifactsRoot,
+ resolveCliSessionArtifacts,
+} from 'src/services/cli-session-artifacts';
+import { TerminalUI } from 'src/services/terminal-ui';
+import { TriggersRealtime } from 'src/services/triggers-realtime';
+import { parseJsonIsh } from 'src/utils/parse-json-ish';
+import { toolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug';
+import { matchesTriggerListenFilters } from './triggers/filter';
+import { parseTriggerListenEvent } from './triggers/parse';
+
+const slug = Args.text({ name: 'slug' }).pipe(
+ Args.withDescription('Trigger slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")')
+);
+
+const params = Options.text('params').pipe(
+ Options.withAlias('p'),
+ Options.withDescription('Trigger create params as JSON/JS object, @file, or - for stdin'),
+ Options.optional
+);
+
+const maxEvents = Options.integer('max-events').pipe(
+ Options.withDescription('Stop after receiving N events for this temporary trigger'),
+ Options.optional
+);
+
+const timeout = Options.text('timeout').pipe(
+ Options.withDescription('Stop after a duration such as "5m", "1hr", or "30s"'),
+ Options.optional
+);
+
+const stream = Options.text('stream').pipe(
+ Options.withDescription(
+ 'Also stream each event payload inline. Pass an optional jq-like path such as ".thread.id" or ".data[0].id".'
+ ),
+ Options.optional
+);
+
+const debug = Options.boolean('debug').pipe(
+ Options.withDescription(
+ 'Print verbose debug information (raw events, filter results, Pusher state)'
+ ),
+ Options.withDefault(false)
+);
+
+const sanitizePathPart = (value: string): string =>
+ value.replace(/[^A-Z0-9._-]+/gi, '-').replace(/^-+|-+$/g, '') || 'unknown';
+
+const resolveParamsInput = (input: Option.Option<string>) =>
+ resolveOptionalTextInput(input, { missingValue: '{}' });
+
+const parseCreateParams = (raw: string) =>
+ Effect.gen(function* () {
+ const parsed = yield* Effect.try({
+ try: () => parseJsonIsh(raw),
+ catch: () =>
+ new Error(
+ "Invalid --params input. Provide JSON or a JS-style object literal, e.g. -p '{ trigger_config: { ... } }'."
+ ),
+ });
+
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
+ return yield* Effect.fail(
+ new Error("Expected --params to be an object, e.g. -p '{ trigger_config: { ... } }'.")
+ );
+ }
+
+ return parsed as Record<string, unknown>;
+ });
+
+const selectConnectedAccountId = (
+ items: ReadonlyArray<{
+ id: string;
+ updated_at: string;
+ is_disabled: boolean;
+ }>
+): string | undefined => {
+ const active = items.filter(item => !item.is_disabled);
+ if (active.length === 0) {
+ return undefined;
+ }
+
+ return [...active]
+ .sort((left, right) => Date.parse(right.updated_at) - Date.parse(left.updated_at))
+ .at(0)?.id;
+};
+
+const emitStreamLine = (line: string, ui: TerminalUI) =>
+ Effect.gen(function* () {
+ yield* ui.log.message(line);
+ yield* ui.output(line, { force: true });
+ });
+
+const extractEventFileId = (eventData: Record<string, unknown>): string => {
+ const candidates = [
+ eventData.id,
+ eventData.log_id,
+ typeof eventData.metadata === 'object' && eventData.metadata !== null
+ ? (eventData.metadata as Record<string, unknown>).id
+ : undefined,
+ ];
+
+ for (const candidate of candidates) {
+ if (typeof candidate === 'string' && candidate.length > 0) {
+ return sanitizePathPart(candidate);
+ }
+ }
+
+ return `${Date.now()}-${crypto.randomUUID().slice(0, 8)}`;
+};
+
+const resolveFallbackArtifactsDir = () => resolveArtifactsRoot();
+
+const parseStreamPath = (expression: string): ReadonlyArray<string | number> => {
+ const trimmed = expression.trim();
+ if (!trimmed.startsWith('.')) {
+ throw new Error('Expected --stream to contain a jq-like path starting with "."');
+ }
+
+ const pathTokens: Array<string | number> = [];
+ const tokenPattern = /(?:\.([A-Za-z0-9_-]+))|(?:\[(\d+)\])/g;
+ let lastIndex = 0;
+
+ for (const match of trimmed.matchAll(tokenPattern)) {
+ if ((match.index ?? -1) !== lastIndex) {
+ throw new Error(
+ 'Unsupported --stream expression. Use a jq-like path such as ".foo.bar" or ".items[0].id".'
+ );
+ }
+
+ if (match[1]) pathTokens.push(match[1]);
+ if (match[2]) pathTokens.push(Number(match[2]));
+ lastIndex += match[0].length;
+ }
+
+ if (lastIndex !== trimmed.length) {
+ throw new Error(
+ 'Unsupported --stream expression. Use a jq-like path such as ".foo.bar" or ".items[0].id".'
+ );
+ }
+
+ return pathTokens;
+};
+
+const applyStreamPath = (value: unknown, pathTokens: ReadonlyArray<string | number>): unknown => {
+ let current = value;
+ for (const token of pathTokens) {
+ if (typeof token === 'number') {
+ if (!Array.isArray(current) || token < 0 || token >= current.length) {
+ return undefined;
+ }
+ current = current[token];
+ continue;
+ }
+
+ if (typeof current !== 'object' || current === null || Array.isArray(current)) {
+ return undefined;
+ }
+
+ current = (current as Record<string, unknown>)[token];
+ }
+
+ return current;
+};
+
+const formatStreamValue = (value: unknown): string => {
+ if (value === undefined) return 'null';
+ if (typeof value === 'string') return value;
+ return JSON.stringify(value);
+};
+
+const TIMEOUT_UNITS_MS: Record<string, number> = {
+ ms: 1,
+ millisecond: 1,
+ milliseconds: 1,
+ s: 1_000,
+ sec: 1_000,
+ secs: 1_000,
+ second: 1_000,
+ seconds: 1_000,
+ m: 60_000,
+ min: 60_000,
+ mins: 60_000,
+ minute: 60_000,
+ minutes: 60_000,
+ h: 3_600_000,
+ hr: 3_600_000,
+ hrs: 3_600_000,
+ hour: 3_600_000,
+ hours: 3_600_000,
+ d: 86_400_000,
+ day: 86_400_000,
+ days: 86_400_000,
+};
+
+const parseTimeoutMs = (value: string): number => {
+ const trimmed = value.trim().toLowerCase();
+ const match = /^(\d+(?:\.\d+)?)\s*([a-z]+)$/.exec(trimmed);
+ if (!match) {
+ throw new Error(
+ 'Invalid --timeout value. Use a duration such as "30s", "5m", "1hr", or "1day".'
+ );
+ }
+
+ const amount = Number(match[1]);
+ const unitMs = TIMEOUT_UNITS_MS[match[2]];
+ if (!Number.isFinite(amount) || amount <= 0 || unitMs === undefined) {
+ throw new Error(
+ 'Invalid --timeout value. Use a duration such as "30s", "5m", "1hr", or "1day".'
+ );
+ }
+
+ return Math.round(amount * unitMs);
+};
+
+export const listenCmd = Command.make(
+ 'listen',
+ { slug, params, maxEvents, timeout, stream, debug },
+ ({ slug, params, maxEvents, timeout, stream, debug }) =>
+ Effect.gen(function* () {
+ if (!(yield* requireAuth)) return;
+
+ const ui = yield* TerminalUI;
+ const fs = yield* FileSystem.FileSystem;
+ const runtime = yield* Effect.runtime<never>();
+ const clientSingleton = yield* ComposioClientSingleton;
+ const realtime = yield* TriggersRealtime;
+
+ const resolvedProject = yield* resolveCommandProject({ mode: 'consumer' }).pipe(
+ Effect.mapError(formatResolveCommandProjectError)
+ );
+
+ const client = yield* clientSingleton.getFor({
+ orgId: resolvedProject.orgId,
+ projectId: resolvedProject.projectId,
+ });
+
+ if (!resolvedProject.consumerUserId) {
+ return yield* Effect.fail(
+ new Error('No consumer user is available in the current project context.')
+ );
+ }
+
+ const rawParams = Option.isSome(params)
+ ? (yield* resolveParamsInput(params))?.trim() || '{}'
+ : '{}';
+ const createParamsInput = yield* parseCreateParams(rawParams);
+ const toolkitSlug = toolkitFromToolSlug(slug);
+ if (!toolkitSlug) {
+ return yield* Effect.fail(
+ new Error(
+ `Could not infer a toolkit from trigger slug "${slug}". Use a standard trigger slug such as "GMAIL_NEW_GMAIL_MESSAGE".`
+ )
+ );
+ }
+
+ const connectedAccounts = yield* Effect.tryPromise({
+ try: () =>
+ client.connectedAccounts.list({
+ toolkit_slugs: [toolkitSlug],
+ user_ids: resolvedProject.consumerUserId ? [resolvedProject.consumerUserId] : undefined,
+ statuses: ['ACTIVE'],
+ limit: 100,
+ }),
+ catch: error =>
+ new Error(`Failed to list connected accounts for "${toolkitSlug}": ${String(error)}`),
+ });
+ const resolvedConnectedAccountId = selectConnectedAccountId(connectedAccounts.items);
+
+ if (!resolvedConnectedAccountId) {
+ return yield* Effect.fail(
+ new Error(
+ `No active connected account found for toolkit "${toolkitSlug}" and consumer user "${resolvedProject.consumerUserId}". Run \`composio link ${toolkitSlug}\` first.`
+ )
+ );
+ }
+
+ const createParams = {
+ ...createParamsInput,
+ connected_account_id: resolvedConnectedAccountId,
+ } as Parameters<typeof client.triggerInstances.upsert>[1];
+ const timeoutMs = Option.match(timeout, {
+ onNone: () => undefined,
+ onSome: value => parseTimeoutMs(value),
+ });
+ const streamPath = Option.match(stream, {
+ onNone: () => undefined,
+ onSome: value => {
+ const trimmed = value.trim();
+ return trimmed.length === 0 ? [] : parseStreamPath(trimmed);
+ },
+ });
+ const shouldStream = Option.isSome(stream);
+
+ const artifactsOption = yield* resolveCliSessionArtifacts({
+ orgId: resolvedProject.orgId,
+ consumerUserId: resolvedProject.consumerUserId,
+ });
+ const artifactsRoot = Option.match(artifactsOption, {
+ onNone: () => resolveFallbackArtifactsDir(),
+ onSome: value => value.directoryPath,
+ });
+ const triggerDir = path.join(artifactsRoot, 'triggers', sanitizePathPart(slug));
+ const streamFilePath = path.join(triggerDir, 'events.jsonl');
+
+ yield* fs.makeDirectory(triggerDir, { recursive: true });
+ yield* fs.writeFileString(streamFilePath, '', { flag: 'a' });
+
+ const maxEventsLimit = Option.getOrUndefined(maxEvents);
+ const stopWhenDone = yield* Deferred.make<'max-events' | 'timeout'>();
+ let matchingEvents = 0;
+ const seenEventIds = new Set<string>();
+
+ yield* Effect.acquireUseRelease(
+ Effect.tryPromise({
+ try: () => client.triggerInstances.upsert(slug, createParams),
+ catch: error =>
+ new Error(`Failed to create temporary trigger "${slug}": ${String(error)}`),
+ }),
+ createdTrigger =>
+ Effect.gen(function* () {
+ yield* emitStreamLine(`listening for events ${slug} (tail at ${streamFilePath})`, ui);
+ if (debug) {
+ const debugMsg = `[debug] trigger_id=${createdTrigger.trigger_id} project=${resolvedProject.projectId} org=${resolvedProject.orgId} createParams=${JSON.stringify(createParams)}`;
+ yield* emitStreamLine(debugMsg, ui);
+ yield* emitStreamLine(
+ `[debug] upsert response: ${JSON.stringify(createdTrigger)}`,
+ ui
+ );
+ }
+
+ const onEvent = (eventData: Record<string, unknown>) => {
+ Runtime.runFork(runtime)(
+ Effect.gen(function* () {
+ if (debug) {
+ yield* emitStreamLine(
+ `[debug] raw event keys: ${Object.keys(eventData).join(', ')}`,
+ ui
+ );
+ yield* emitStreamLine(
+ `[debug] raw event (truncated): ${JSON.stringify(eventData).slice(0, 500)}`,
+ ui
+ );
+ }
+ const parsed = parseTriggerListenEvent(eventData);
+ const filterResult = matchesTriggerListenFilters(
+ { triggerId: createdTrigger.trigger_id },
+ parsed
+ );
+ if (debug) {
+ yield* emitStreamLine(
+ `[debug] parsed.id=${parsed.id} triggerSlug=${parsed.triggerSlug} trigger_id=${createdTrigger.trigger_id} match=${filterResult}`,
+ ui
+ );
+ }
+ if (!filterResult) {
+ return;
+ }
+
+ const eventFileId = extractEventFileId(eventData);
+ if (seenEventIds.has(eventFileId)) {
+ if (debug) {
+ yield* emitStreamLine(`[debug] skipping duplicate event ${eventFileId}`, ui);
+ }
+ return;
+ }
+ seenEventIds.add(eventFileId);
+
+ matchingEvents += 1;
+ const eventFilePath = path.join(triggerDir, `${eventFileId}-payload.json`);
+ const eventJson = JSON.stringify(eventData, null, 2);
+ const streamEntry = JSON.stringify({
+ event_id: eventFileId,
+ trigger_id: createdTrigger.trigger_id,
+ trigger_slug: slug,
+ file_path: eventFilePath,
+ received_at: new Date().toISOString(),
+ });
+
+ yield* fs.writeFileString(eventFilePath, `${eventJson}\n`);
+ yield* fs.writeFileString(streamFilePath, `${streamEntry}\n`, { flag: 'a' });
+ yield* emitStreamLine(`event: ${eventFilePath}`, ui);
+
+ if (shouldStream) {
+ const streamValue =
+ streamPath === undefined
+ ? eventData
+ : streamPath.length === 0
+ ? eventData
+ : applyStreamPath(eventData, streamPath);
+ yield* emitStreamLine(`stream: ${formatStreamValue(streamValue)}`, ui);
+ }
+
+ if (maxEventsLimit !== undefined && matchingEvents >= maxEventsLimit) {
+ yield* Deferred.succeed(stopWhenDone, 'max-events').pipe(Effect.ignore);
+ }
+ }).pipe(
+ Effect.catchAll(error =>
+ ui.log.warn(error instanceof Error ? error.message : String(error))
+ )
+ )
+ );
+ };
+
+ const listenEffect = realtime
+ .listenInProject(
+ {
+ orgId: resolvedProject.orgId,
+ projectId: resolvedProject.projectId,
+ },
+ onEvent
+ )
+ .pipe(Effect.onInterrupt(() => ui.log.info(`Stopped listening for events ${slug}.`)));
+
+ if (timeoutMs !== undefined) {
+ yield* Effect.forkScoped(
+ Effect.sleep(timeoutMs).pipe(
+ Effect.andThen(Deferred.succeed(stopWhenDone, 'timeout')),
+ Effect.ignore
+ )
+ );
+ }
+
+ if (maxEventsLimit === undefined && timeoutMs === undefined) {
+ yield* listenEffect;
+ return;
+ }
+
+ const stopReason = yield* Effect.raceFirst(listenEffect, Deferred.await(stopWhenDone));
+ if (stopReason === 'max-events') {
+ yield* ui.outro(
+ `Stopped after receiving ${matchingEvents} events. Temporary trigger disabled.`
+ );
+ return;
+ }
+
+ if (stopReason === 'timeout') {
+ yield* ui.outro(
+ `Stopped after timeout with ${matchingEvents} matching event${matchingEvents === 1 ? '' : 's'}. Temporary trigger disabled.`
+ );
+ }
+ }),
+ created =>
+ Effect.tryPromise({
+ try: () =>
+ client.triggerInstances.manage.update(created.trigger_id, { status: 'disable' }),
+ catch: error =>
+ new Error(
+ `Failed to disable temporary trigger "${created.trigger_id}": ${String(error)}`
+ ),
+ }).pipe(
+ Effect.catchAll(error =>
+ ui.log.warn(error instanceof Error ? error.message : String(error))
+ )
+ )
+ );
+ })
+).pipe(
+ Command.withDescription(
+ 'Create a temporary subscription for consumer-project events and write each event to artifacts for easy background-agent consumption.'
+ )
+);
diff --git a/ts/packages/cli/src/commands/root-help.ts b/ts/packages/cli/src/commands/root-help.ts
index 27b7bead8..f9f95fb89 100644
--- a/ts/packages/cli/src/commands/root-help.ts
+++ b/ts/packages/cli/src/commands/root-help.ts
@@ -72,6 +72,35 @@ const CORE_COMMANDS: ReadonlyArray<DetailedCommand> = [
{ name: '--dry-run', description: 'Preview execute() calls without running remote actions' },
],
},
+ {
+ name: 'listen',
+ description:
+ 'Create a temporary subscription for consumer-project events and persist each payload into the session artifact folder.',
+ usage:
+ 'listen <slug> [-p, --params text] [--max-events integer] [--timeout text] [--stream [text]]',
+ options: [
+ { name: '<slug>', description: 'Trigger slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")' },
+ {
+ name: '-p, --params',
+ description:
+ "Trigger create params as JSON or JS-style object, e.g. -p '{ trigger_config: { ... } }'.",
+ },
+ {
+ name: '--max-events',
+ description: 'Stop after receiving N events, then disable the temporary trigger',
+ },
+ {
+ name: '--timeout',
+ description:
+ 'Stop after a duration such as 30s, 5m, or 1hr, then disable the temporary trigger',
+ },
+ {
+ name: '--stream',
+ description:
+ 'Also print each payload inline as a single-line stream value. Optionally pass a jq-like path such as ".thread.id".',
+ },
+ ],
+ },
{
name: 'proxy',
description:
@@ -92,6 +121,14 @@ const CORE_COMMANDS: ReadonlyArray<DetailedCommand> = [
const OTHER_COMMANDS: ReadonlyArray<CompactCommand> = [
{ name: 'composio tools info <slug>', description: 'Print tool summary and cache its schema' },
{ name: 'composio tools list <toolkit>', description: 'List tools available in a toolkit' },
+ {
+ name: 'composio triggers info <slug>',
+ description: 'Print trigger type details and schema summaries',
+ },
+ {
+ name: 'composio triggers list <toolkit>',
+ description: 'List available trigger types in a toolkit',
+ },
{
name: 'composio artifacts cwd',
description: 'Print the cwd-scoped session artifact directory',
@@ -264,6 +301,47 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {
'composio artifacts cwd Print the current session artifact directory',
],
},
+ listen: {
+ usage:
+ 'composio listen <slug> [-p, --params text] [--max-events integer] [--timeout text] [--stream [text]]',
+ description:
+ 'Create a temporary subscription for consumer-project events so background agents can easily consume new emails, Slack messages, and other trigger payloads from artifacts.',
+ args: [{ name: '<slug>', description: 'Trigger slug to create and listen to' }],
+ options: [
+ {
+ name: '-p, --params <text>',
+ description:
+ 'Trigger create params as JSON/JS object, @file, or - for stdin. Pass optional trigger config fields only.',
+ },
+ {
+ name: '--max-events <integer>',
+ description: 'Stop after N events for this temporary trigger and disable it',
+ },
+ {
+ name: '--timeout <text>',
+ description: 'Stop after a duration such as "30s", "5m", or "1hr" and disable the trigger',
+ },
+ {
+ name: '--stream [text]',
+ description:
+ 'Also print each event payload inline. Optionally pass a jq-like path such as ".thread.id" or ".data[0].id".',
+ },
+ ],
+ examples: [
+ 'composio listen GMAIL_NEW_GMAIL_MESSAGE',
+ 'composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --max-events 5',
+ 'composio listen GMAIL_NEW_GMAIL_MESSAGE --timeout 5m',
+ "composio listen GMAIL_NEW_GMAIL_MESSAGE --timeout 1hr --stream '.data.threadId'",
+ 'composio listen SLACK_RECEIVE_MESSAGE -p \'{ trigger_config: { channel: "C123" } }\'',
+ 'composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --stream',
+ "composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --stream '.data.threadId'",
+ ],
+ seeAlso: [
+ 'composio artifacts cwd Print the current session artifact directory',
+ 'composio triggers info <slug> Inspect trigger type details before listening',
+ 'composio link <toolkit> Connect the required account before creating the trigger',
+ ],
+ },
link: {
usage: 'composio link [<toolkit>] [--no-wait]',
description:
@@ -511,6 +589,19 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {
'View a brief summary of a tool and show the CLI-facing schema used by `composio execute --get-schema`.',
args: [{ name: '<slug>', description: 'Tool slug (e.g. "GMAIL_SEND_EMAIL")' }],
},
+ 'triggers list': {
+ usage: 'composio triggers list <toolkit> [--limit integer]',
+ description: 'List available trigger types for a toolkit.',
+ args: [
+ { name: '<toolkit>', description: 'Toolkit slug to list trigger types for (e.g. "gmail")' },
+ ],
+ options: [{ name: '--limit <integer>', description: 'Number of results' }],
+ },
+ 'triggers info': {
+ usage: 'composio triggers info [<slug>]',
+ description: 'View details of a specific trigger type.',
+ args: [{ name: '<slug>', description: 'Trigger slug' }],
+ },
// ── Generate commands ─────────────────────────────────────────────────
@@ -722,12 +813,12 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {
flags: [{ name: '-y, --yes', description: 'Skip confirmation prompt' }],
},
'dev triggers list': {
- usage: 'composio dev triggers list [--toolkits text] [--limit integer]',
- description: 'List available trigger types.',
- options: [
- { name: '--toolkits <text>', description: 'Filter by toolkit slugs' },
- { name: '--limit <integer>', description: 'Number of results' },
+ usage: 'composio dev triggers list <toolkit> [--limit integer]',
+ description: 'List available trigger types for a toolkit.',
+ args: [
+ { name: '<toolkit>', description: 'Toolkit slug to list trigger types for (e.g. "gmail")' },
],
+ options: [{ name: '--limit <integer>', description: 'Number of results' }],
},
'dev triggers info': {
usage: 'composio dev triggers info [<slug>]',
diff --git a/ts/packages/cli/src/commands/triggers/commands/triggers.info.cmd.ts b/ts/packages/cli/src/commands/triggers/commands/triggers.info.cmd.ts
index d05c1d98c..eafa2a7eb 100644
--- a/ts/packages/cli/src/commands/triggers/commands/triggers.info.cmd.ts
+++ b/ts/packages/cli/src/commands/triggers/commands/triggers.info.cmd.ts
@@ -6,6 +6,12 @@ import { ComposioToolkitsRepository } from 'src/services/composio-clients';
import { TerminalUI } from 'src/services/terminal-ui';
import { formatTriggerTypeInfo } from '../format';
+type TriggersInfoCommandConfig = {
+ readonly exampleCommand: string;
+ readonly listCommand: string;
+ readonly listCommandPlaceholder: string;
+};
+
const slug = Args.text({ name: 'slug' }).pipe(
Args.withDescription('Trigger slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")'),
Args.optional
@@ -19,50 +25,67 @@ const slug = Args.text({ name: 'slug' }).pipe(
* composio dev triggers info "GMAIL_NEW_GMAIL_MESSAGE"
* ```
*/
-export const triggersCmd$Info = Command.make('info', { slug }, ({ slug }) =>
- Effect.gen(function* () {
- if (!(yield* requireAuth)) return;
+const makeTriggersInfoCommand = ({
+ exampleCommand,
+ listCommand,
+ listCommandPlaceholder,
+}: TriggersInfoCommandConfig) =>
+ Command.make('info', { slug }, ({ slug }) =>
+ Effect.gen(function* () {
+ if (!(yield* requireAuth)) return;
+
+ const ui = yield* TerminalUI;
+ const repo = yield* ComposioToolkitsRepository;
+
+ if (Option.isNone(slug)) {
+ yield* ui.log.warn('Missing required argument: <slug>');
+ yield* ui.log.step(
+ `Try specifying a trigger slug, e.g.:\n> ${exampleCommand} "GMAIL_NEW_GMAIL_MESSAGE"`
+ );
+ return;
+ }
- const ui = yield* TerminalUI;
- const repo = yield* ComposioToolkitsRepository;
+ const slugValue = slug.value;
- if (Option.isNone(slug)) {
- yield* ui.log.warn('Missing required argument: <slug>');
- yield* ui.log.step(
- 'Try specifying a trigger slug, e.g.:\n> composio dev triggers info "GMAIL_NEW_GMAIL_MESSAGE"'
- );
- return;
- }
+ const triggerTypeOpt = yield* ui
+ .withSpinner('Fetching trigger type details...', repo.getTriggerTypeDetailed(slugValue))
+ .pipe(
+ Effect.asSome,
+ Effect.catchTag(
+ 'services/HttpServerError',
+ handleHttpServerError(ui, {
+ fallbackMessage: `Trigger "${slugValue}" not found.`,
+ hint: `Browse available trigger types:\n> ${listCommandPlaceholder}`,
+ fallbackValue: Option.none(),
+ })
+ )
+ );
- const slugValue = slug.value;
+ if (Option.isNone(triggerTypeOpt)) return;
- const triggerTypeOpt = yield* ui
- .withSpinner('Fetching trigger type details...', repo.getTriggerTypeDetailed(slugValue))
- .pipe(
- Effect.asSome,
- Effect.catchTag(
- 'services/HttpServerError',
- handleHttpServerError(ui, {
- fallbackMessage: `Trigger "${slugValue}" not found.`,
- hint: 'Browse available trigger types:\n> composio dev triggers list',
- fallbackValue: Option.none(),
- })
- )
- );
+ const triggerType = triggerTypeOpt.value;
- if (Option.isNone(triggerTypeOpt)) return;
+ yield* ui.note(formatTriggerTypeInfo(triggerType), `Trigger: ${triggerType.name}`);
- const triggerType = triggerTypeOpt.value;
+ const toolkitSlug = triggerType.toolkit?.slug?.toLowerCase();
+ if (toolkitSlug) {
+ yield* ui.log.step(
+ `To list more trigger types in this toolkit:\n> ${listCommand} "${toolkitSlug}"`
+ );
+ }
- yield* ui.note(formatTriggerTypeInfo(triggerType), `Trigger: ${triggerType.name}`);
+ yield* ui.output(JSON.stringify(triggerType, null, 2));
+ })
+ ).pipe(Command.withDescription('View details of a specific trigger type.'));
- const toolkitSlug = triggerType.toolkit?.slug?.toLowerCase();
- if (toolkitSlug) {
- yield* ui.log.step(
- `To list more trigger types in this toolkit:\n> composio dev triggers list --toolkits "${toolkitSlug}"`
- );
- }
+export const triggersCmd$Info = makeTriggersInfoCommand({
+ exampleCommand: 'composio dev triggers info',
+ listCommand: 'composio dev triggers list',
+ listCommandPlaceholder: 'composio dev triggers list "<toolkit>"',
+});
- yield* ui.output(JSON.stringify(triggerType, null, 2));
- })
-).pipe(Command.withDescription('View details of a specific trigger type.'));
+export const rootTriggersCmd$Info = makeTriggersInfoCommand({
+ exampleCommand: 'composio triggers info',
+ listCommand: 'composio triggers list',
+ listCommandPlaceholder: 'composio triggers list "<toolkit>"',
+});
diff --git a/ts/packages/cli/src/commands/triggers/commands/triggers.list.cmd.ts b/ts/packages/cli/src/commands/triggers/commands/triggers.list.cmd.ts
index 48f1b5e73..93808cc32 100644
--- a/ts/packages/cli/src/commands/triggers/commands/triggers.list.cmd.ts
+++ b/ts/packages/cli/src/commands/triggers/commands/triggers.list.cmd.ts
@@ -1,17 +1,18 @@
-import { Command, Options } from '@effect/cli';
-import { Effect, Option } from 'effect';
+import { Args, Command, Options } from '@effect/cli';
+import { Effect } from 'effect';
import { requireAuth } from 'src/effects/require-auth';
-import { ComposioToolkitsRepository } from 'src/services/composio-clients';
+import { ComposioToolkitsRepository, InvalidToolkitsError } from 'src/services/composio-clients';
import { TerminalUI } from 'src/services/terminal-ui';
import { clampLimit } from 'src/ui/clamp-limit';
import { formatTriggerTypesJson, formatTriggerTypesTable } from '../format';
-import { parseCsv } from '../parse-csv';
-const toolkits = Options.text('toolkits').pipe(
- Options.withDescription(
- 'Filter by toolkit slugs, comma-separated (e.g. "gmail" or "gmail,slack")'
- ),
- Options.optional
+type TriggersListCommandConfig = {
+ readonly noResultsCommand: string;
+ readonly infoCommand: string;
+};
+
+const toolkit = Args.text({ name: 'toolkit' }).pipe(
+ Args.withDescription('Toolkit slug to list trigger types for (e.g. "gmail")')
);
const limit = Options.integer('limit').pipe(
@@ -24,46 +25,68 @@ const limit = Options.integer('limit').pipe(
*
* @example
* ```bash
- * composio dev triggers list
- * composio dev triggers list --toolkits "gmail"
- * composio dev triggers list --toolkits "gmail,slack"
+ * composio dev triggers list gmail
+ * composio dev triggers list slack --limit 10
* ```
*/
-export const triggersCmd$List = Command.make('list', { toolkits, limit }, ({ toolkits, limit }) =>
- Effect.gen(function* () {
- if (!(yield* requireAuth)) return;
+const makeTriggersListCommand = ({ noResultsCommand, infoCommand }: TriggersListCommandConfig) =>
+ Command.make('list', { toolkit, limit }, ({ toolkit, limit }) =>
+ Effect.gen(function* () {
+ if (!(yield* requireAuth)) return;
- const ui = yield* TerminalUI;
- const repo = yield* ComposioToolkitsRepository;
- const toolkitFilters = Option.isSome(toolkits) ? parseCsv(toolkits.value) : undefined;
- const clampedLimit = clampLimit(limit);
+ const ui = yield* TerminalUI;
+ const repo = yield* ComposioToolkitsRepository;
+ const clampedLimit = clampLimit(limit);
- const allTriggerTypes = yield* ui.withSpinner(
- 'Fetching trigger types...',
- repo.getTriggerTypes(toolkitFilters)
- );
- const triggerTypes = allTriggerTypes.slice(0, clampedLimit);
+ yield* repo.validateToolkits([toolkit]).pipe(
+ Effect.catchTag('services/InvalidToolkitsError', (error: InvalidToolkitsError) =>
+ Effect.gen(function* () {
+ const availableExample = error.availableToolkits.slice(0, 8).join(', ');
+ yield* ui.log.error(
+ `Toolkit "${toolkit}" is not available. ${availableExample ? `Examples: ${availableExample}` : ''}`
+ );
+ yield* ui.log.step(`List valid toolkits with:\n> ${noResultsCommand}`);
+ return yield* Effect.fail(
+ new Error(`Invalid toolkit slug "${toolkit}" for trigger listing.`)
+ );
+ })
+ )
+ );
- if (triggerTypes.length === 0) {
- const hint = Option.isSome(toolkits)
- ? `No trigger types found in toolkit "${toolkits.value}". Verify the toolkit slug with:\n> composio dev toolkits list`
- : 'No trigger types found.';
- yield* ui.log.warn(hint);
- return;
- }
+ const allTriggerTypes = yield* ui.withSpinner(
+ 'Fetching trigger types...',
+ repo.getTriggerTypes([toolkit])
+ );
+ const triggerTypes = allTriggerTypes.slice(0, clampedLimit);
- const count = triggerTypes.length;
- yield* ui.log.info(
- `Listing ${count} trigger type${count === 1 ? '' : 's'}\n\n${formatTriggerTypesTable(triggerTypes)}`
- );
+ if (triggerTypes.length === 0) {
+ yield* ui.log.warn(
+ `No trigger types found in toolkit "${toolkit}". Verify the toolkit slug with:\n> ${noResultsCommand}`
+ );
+ return;
+ }
- const firstSlug = triggerTypes[0]?.slug;
- if (firstSlug) {
- yield* ui.log.step(
- `To view details of a trigger type:\n> composio dev triggers info "${firstSlug}"`
+ const count = triggerTypes.length;
+ yield* ui.note(
+ formatTriggerTypesTable(triggerTypes),
+ `Listing ${count} trigger type${count === 1 ? '' : 's'}`
);
- }
- yield* ui.output(formatTriggerTypesJson(triggerTypes));
- })
-).pipe(Command.withDescription('List available trigger types.'));
+ const firstSlug = triggerTypes[0]?.slug;
+ if (firstSlug) {
+ yield* ui.log.step(`To view details of a trigger type:\n> ${infoCommand} "${firstSlug}"`);
+ }
+
+ yield* ui.output(formatTriggerTypesJson(triggerTypes));
+ })
+ ).pipe(Command.withDescription('List available trigger types.'));
+
+export const triggersCmd$List = makeTriggersListCommand({
+ noResultsCommand: 'composio dev toolkits list',
+ infoCommand: 'composio dev triggers info',
+});
+
+export const rootTriggersCmd$List = makeTriggersListCommand({
+ noResultsCommand: 'composio toolkits list',
+ infoCommand: 'composio triggers info',
+});
diff --git a/ts/packages/cli/src/commands/triggers/root-triggers.cmd.ts b/ts/packages/cli/src/commands/triggers/root-triggers.cmd.ts
new file mode 100644
index 000000000..0451f2e15
--- /dev/null
+++ b/ts/packages/cli/src/commands/triggers/root-triggers.cmd.ts
@@ -0,0 +1,8 @@
+import { Command } from '@effect/cli';
+import { rootTriggersCmd$Info } from './commands/triggers.info.cmd';
+import { rootTriggersCmd$List } from './commands/triggers.list.cmd';
+
+export const rootTriggersCmd = Command.make('triggers').pipe(
+ Command.withDescription('Browse and inspect trigger types before creating subscriptions.'),
+ Command.withSubcommands([rootTriggersCmd$List, rootTriggersCmd$Info])
+);
diff --git a/ts/packages/cli/src/services/cli-session-artifacts.ts b/ts/packages/cli/src/services/cli-session-artifacts.ts
index 6cd127b0c..921c7b55f 100644
--- a/ts/packages/cli/src/services/cli-session-artifacts.ts
+++ b/ts/packages/cli/src/services/cli-session-artifacts.ts
@@ -4,7 +4,7 @@ import path from 'node:path';
import { Effect, Option } from 'effect';
import { getOrCreateProbablyMyCliSessionIdForCurrentCwd } from 'src/services/consumer-short-term-cache';
-const resolveArtifactsRoot = (): string =>
+export const resolveArtifactsRoot = (): string =>
process.env.COMPOSIO_SESSION_DIR?.trim() ||
process.env.COMPOSIO_CACHE_DIR?.trim() ||
path.join(os.tmpdir(), 'composio');
diff --git a/ts/packages/cli/src/services/command-hints.ts b/ts/packages/cli/src/services/command-hints.ts
index fa9ad1c97..147b4b718 100644
--- a/ts/packages/cli/src/services/command-hints.ts
+++ b/ts/packages/cli/src/services/command-hints.ts
@@ -7,6 +7,8 @@ export type CommandHintId =
| 'root.search'
| 'root.tools.list'
| 'root.tools.info'
+ | 'root.triggers.list'
+ | 'root.triggers.info'
| 'root.execute'
| 'root.execute.getSchema'
| 'root.link'
@@ -40,6 +42,14 @@ export const COMMAND_HINTS: Record<CommandHintId, CommandHintNode> = {
example: params => `composio tools info "${getParam(params, 'slug', '<slug>')}"`,
links: ['root.execute.getSchema', 'root.execute'],
},
+ 'root.triggers.list': {
+ example: params => `composio triggers list "${getParam(params, 'toolkit', '<toolkit>')}"`,
+ links: ['root.triggers.info'],
+ },
+ 'root.triggers.info': {
+ example: params => `composio triggers info "${getParam(params, 'slug', '<slug>')}"`,
+ links: ['root.triggers.list'],
+ },
'root.execute': {
example: params =>
`composio execute "${getParam(params, 'slug', '<slug>')}" ${getParam(params, 'data', "-d '{}'")}`.trim(),
diff --git a/ts/packages/cli/src/services/run-subagent-acp.ts b/ts/packages/cli/src/services/run-subagent-acp.ts
index c9b7eb1eb..5b7a7a31f 100644
--- a/ts/packages/cli/src/services/run-subagent-acp.ts
+++ b/ts/packages/cli/src/services/run-subagent-acp.ts
@@ -422,6 +422,9 @@ export const createStructuredOutputMcpContext = ({
let tempDirectory: string | null = null;
try {
+ // Keep this on an OS temp dir for now. Repointing MCP schema/result files into
+ // session artifacts needs a broader bundling + run-companion test pass so we
+ // don't break structured sub-agent output in packaged CLI builds.
tempDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-subagent-output-mcp-'));
const schemaFilePath = path.join(tempDirectory, 'schema.json');
const resultFilePath = path.join(tempDirectory, 'result.json');
diff --git a/ts/packages/cli/src/services/triggers-realtime.ts b/ts/packages/cli/src/services/triggers-realtime.ts
index 502a8ef8b..20266b58b 100644
--- a/ts/packages/cli/src/services/triggers-realtime.ts
+++ b/ts/packages/cli/src/services/triggers-realtime.ts
@@ -1,5 +1,10 @@
import { Data, Effect, Runtime } from 'effect';
-import { ComposioSessionRepository } from 'src/services/composio-clients';
+import {
+ ComposioClientSingleton,
+ ComposioSessionRepository,
+ type CliRealtimeAuthResponse,
+ type CliRealtimeCredentialsResponse,
+} from 'src/services/composio-clients';
type RawRealtimeEvent = Record<string, unknown>;
@@ -71,12 +76,20 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
{
effect: Effect.gen(function* () {
const sessionRepo = yield* ComposioSessionRepository;
+ const clientSingleton = yield* ComposioClientSingleton;
const runtime = yield* Effect.runtime<never>();
- const listen = (onEvent: (data: RawRealtimeEvent) => void) =>
+ const listenWith = (params: {
+ getRealtimeCredentials: () => Effect.Effect<CliRealtimeCredentialsResponse>;
+ authRealtimeChannel: (params: {
+ channel_name: string;
+ socket_id: string;
+ }) => Effect.Effect<CliRealtimeAuthResponse>;
+ onEvent: (data: RawRealtimeEvent) => void;
+ }) =>
Effect.acquireUseRelease(
Effect.gen(function* () {
- const creds = yield* sessionRepo.getRealtimeCredentials();
+ const creds = yield* params.getRealtimeCredentials();
const channelName = `private-cli-${creds.project_id}`;
const pusherModule = yield* Effect.tryPromise({
@@ -90,9 +103,9 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
cluster: creds.pusher_cluster,
channelAuthorization: {
customHandler: (authOptions: PusherAuthOptions, callback?: PusherAuthCallback) => {
- const params = authOptions.params ?? authOptions;
- const channel_name = params.channel_name ?? params.channelName;
- const socket_id = params.socket_id ?? params.socketId;
+ const authParams = authOptions.params ?? authOptions;
+ const channel_name = authParams.channel_name ?? authParams.channelName;
+ const socket_id = authParams.socket_id ?? authParams.socketId;
const doAuth = async () => {
if (!channel_name || !socket_id) {
@@ -100,7 +113,7 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
}
const response = await Runtime.runPromise(runtime)(
- sessionRepo.authRealtimeChannel({
+ params.authRealtimeChannel({
channel_name,
socket_id,
})
@@ -167,7 +180,7 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
}, CHUNK_TTL_MS);
channel.bind('trigger_to_client', eventData => {
- onEvent((eventData ?? {}) as RawRealtimeEvent);
+ params.onEvent((eventData ?? {}) as RawRealtimeEvent);
});
channel.bind('chunked-trigger_to_client', data => {
@@ -217,7 +230,7 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
) {
try {
const parsed = JSON.parse(current.chunks.join('')) as RawRealtimeEvent;
- onEvent(parsed);
+ params.onEvent(parsed);
} catch {
// Silently discard events that fail to parse after chunk reassembly
} finally {
@@ -243,8 +256,40 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
}).pipe(Effect.catchAll(() => Effect.void))
);
- return { listen };
+ const listen = (onEvent: (data: RawRealtimeEvent) => void) =>
+ listenWith({
+ getRealtimeCredentials: () => sessionRepo.getRealtimeCredentials().pipe(Effect.orDie),
+ authRealtimeChannel: params => sessionRepo.authRealtimeChannel(params).pipe(Effect.orDie),
+ onEvent,
+ });
+
+ const listenInProject = (
+ scope: { orgId: string; projectId: string },
+ onEvent: (data: RawRealtimeEvent) => void
+ ) =>
+ Effect.gen(function* () {
+ const client = yield* clientSingleton.getFor({
+ orgId: scope.orgId,
+ projectId: scope.projectId,
+ });
+
+ return yield* listenWith({
+ getRealtimeCredentials: () =>
+ Effect.tryPromise({
+ try: () => client.cli.realtime.credentials(),
+ catch: cause => new TriggerRealtimeSubscriptionError({ cause }),
+ }).pipe(Effect.orDie),
+ authRealtimeChannel: params =>
+ Effect.tryPromise({
+ try: () => client.cli.realtime.auth(params),
+ catch: cause => new TriggerRealtimeSubscriptionError({ cause }),
+ }).pipe(Effect.orDie),
+ onEvent,
+ });
+ });
+
+ return { listen, listenInProject };
}),
- dependencies: [ComposioSessionRepository.Default],
+ dependencies: [ComposioSessionRepository.Default, ComposioClientSingleton.Default],
}
) {}
diff --git a/ts/packages/cli/test/__utils__/services/test-layer.ts b/ts/packages/cli/test/__utils__/services/test-layer.ts
index 8bcd81f9e..725ee9fa4 100644
--- a/ts/packages/cli/test/__utils__/services/test-layer.ts
+++ b/ts/packages/cli/test/__utils__/services/test-layer.ts
@@ -765,6 +765,11 @@ export const TestLayer = (input?: TestLiveInput) =>
yield* Effect.forEach(realtimeData.events, event => Effect.sync(() => onEvent(event)));
return yield* Effect.never;
}),
+ listenInProject: (_scope, onEvent) =>
+ Effect.gen(function* () {
+ yield* Effect.forEach(realtimeData.events, event => Effect.sync(() => onEvent(event)));
+ return yield* Effect.never;
+ }),
})
);
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 3773638a6..b5de659a3 100644
--- a/ts/packages/cli/test/src/commands/$default.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/$default.cmd.test.ts
@@ -1,3 +1,5 @@
+import os from 'node:os';
+import path from 'node:path';
import { describe, expect, layer } from '@effect/vitest';
import { Effect } from 'effect';
import { ValidationError, HelpDoc } from '@effect/cli';
@@ -116,7 +118,7 @@ describe('CLI: composio', () => {
.join('\n')
.trim();
- expect(output).toContain('/tmp/composio');
+ expect(output).toContain(path.join(os.tmpdir(), 'composio'));
})
);
});
diff --git a/ts/packages/cli/test/src/commands/triggers/triggers.info.cmd.test.ts b/ts/packages/cli/test/src/commands/triggers/triggers.info.cmd.test.ts
index 138c5ab2c..1fd0b4797 100644
--- a/ts/packages/cli/test/src/commands/triggers/triggers.info.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/triggers/triggers.info.cmd.test.ts
@@ -55,6 +55,22 @@ const testConfigProvider = ConfigProvider.fromMap(
).pipe(extendConfigProvider);
describe('CLI: composio dev triggers info', () => {
+ layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
+ '[Given] root triggers info [Then] displays trigger info with root-level hint',
+ it => {
+ it.scoped('supports the top-level triggers info entrypoint', () =>
+ Effect.gen(function* () {
+ yield* cli(['triggers', 'info', 'GMAIL_NEW_GMAIL_MESSAGE']);
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
+ const output = lines.join('\n');
+
+ expect(output).toContain('GMAIL_NEW_GMAIL_MESSAGE');
+ expect(output).toContain('composio triggers list "gmail"');
+ })
+ );
+ }
+ );
+
layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
'[Given] valid slug [Then] displays trigger type info',
it => {
@@ -73,7 +89,7 @@ describe('CLI: composio dev triggers info', () => {
expect(output).toContain('subject');
expect(output).toContain('default:');
expect(output).toContain('false');
- expect(output).toContain('composio dev triggers list --toolkits "gmail"');
+ expect(output).toContain('composio dev triggers list "gmail"');
})
);
}
@@ -104,7 +120,7 @@ describe('CLI: composio dev triggers info', () => {
const output = lines.join('\n');
expect(output).toContain('not found');
- expect(output).toContain('composio dev triggers list');
+ expect(output).toContain('composio dev triggers list "<toolkit>"');
})
);
}
diff --git a/ts/packages/cli/test/src/commands/triggers/triggers.list.cmd.test.ts b/ts/packages/cli/test/src/commands/triggers/triggers.list.cmd.test.ts
index 4d5283f97..b9389dbe7 100644
--- a/ts/packages/cli/test/src/commands/triggers/triggers.list.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/triggers/triggers.list.cmd.test.ts
@@ -4,6 +4,7 @@ import { extendConfigProvider } from 'src/services/config';
import { cli, MockConsole, TestLive } from 'test/__utils__';
import type { TriggerTypes } from 'src/models/trigger-types';
import type { TestLiveInput } from 'test/__utils__/services/test-layer';
+import { makeTestToolkits } from 'test/__utils__/models/toolkits';
const testTriggerTypes: TriggerTypes = [
{
@@ -38,7 +39,13 @@ const testTriggerTypes: TriggerTypes = [
},
];
+const testToolkits = makeTestToolkits([
+ { name: 'Gmail', slug: 'gmail' },
+ { name: 'Slack', slug: 'slack' },
+]);
+
const toolkitsData = {
+ toolkits: testToolkits,
triggerTypes: testTriggerTypes,
} satisfies TestLiveInput['toolkitsData'];
@@ -47,29 +54,75 @@ const testConfigProvider = ConfigProvider.fromMap(
).pipe(extendConfigProvider);
describe('CLI: composio dev triggers list', () => {
+ layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
+ '[Given] root triggers list [Then] lists trigger types with root-level hint',
+ it => {
+ it.scoped('supports the top-level triggers list entrypoint', () =>
+ Effect.gen(function* () {
+ yield* cli(['triggers', 'list', 'gmail']);
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
+ const output = lines.join('\n');
+
+ expect(output).toContain('GMAIL_NEW_GMAIL_MESSAGE');
+ expect(output).toContain('Listing 2 trigger types');
+ expect(output).toContain('composio triggers info');
+ })
+ );
+ }
+ );
+
+ layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
+ '[Given] root triggers list with nonexistent toolkit [Then] shows root toolkit hint',
+ it => {
+ it.scoped('uses root toolkit command in the no-results hint', () =>
+ Effect.gen(function* () {
+ yield* cli(['triggers', 'list', 'nonexistent']).pipe(Effect.ignore);
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
+ const output = lines.join('\n');
+
+ expect(output).toContain('not available');
+ expect(output).toContain('composio toolkits list');
+ expect(output).not.toContain('composio dev toolkits list');
+ })
+ );
+ }
+ );
+
+ layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
+ '[Given] no toolkit [Then] parse fails because toolkit is required',
+ it => {
+ it.scoped('requires a toolkit positional argument', () =>
+ Effect.gen(function* () {
+ const exit = yield* cli(['triggers', 'list']).pipe(Effect.exit);
+ expect(JSON.stringify(exit)).toContain('toolkit');
+ })
+ );
+ }
+ );
+
layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
'[Given] no flags [Then] lists all trigger types',
it => {
it.scoped('lists all trigger types', () =>
Effect.gen(function* () {
- yield* cli(['dev', 'triggers', 'list']);
+ yield* cli(['dev', 'triggers', 'list', 'gmail']);
const lines = yield* MockConsole.getLines({ stripAnsi: true });
const output = lines.join('\n');
expect(output).toContain('GMAIL_NEW_GMAIL_MESSAGE');
- expect(output).toContain('SLACK_NEW_MESSAGE');
- expect(output).toContain('Listing 3 trigger types');
+ expect(output).not.toContain('SLACK_NEW_MESSAGE');
+ expect(output).toContain('Listing 2 trigger types');
})
);
}
);
layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
- '[Given] --toolkits "gmail" [Then] lists only gmail trigger types',
+ '[Given] toolkit "gmail" [Then] lists only gmail trigger types',
it => {
it.scoped('filters by toolkit', () =>
Effect.gen(function* () {
- yield* cli(['dev', 'triggers', 'list', '--toolkits', 'gmail']);
+ yield* cli(['dev', 'triggers', 'list', 'gmail']);
const lines = yield* MockConsole.getLines({ stripAnsi: true });
const output = lines.join('\n');
@@ -87,7 +140,7 @@ describe('CLI: composio dev triggers list', () => {
it => {
it.scoped('uses singular form for one result', () =>
Effect.gen(function* () {
- yield* cli(['dev', 'triggers', 'list', '--limit', '1']);
+ yield* cli(['dev', 'triggers', 'list', 'gmail', '--limit', '1']);
const lines = yield* MockConsole.getLines({ stripAnsi: true });
const output = lines.join('\n');
@@ -103,7 +156,7 @@ describe('CLI: composio dev triggers list', () => {
it => {
it.scoped('shows hint to view trigger details', () =>
Effect.gen(function* () {
- yield* cli(['dev', 'triggers', 'list']);
+ yield* cli(['dev', 'triggers', 'list', 'gmail']);
const lines = yield* MockConsole.getLines({ stripAnsi: true });
const output = lines.join('\n');
@@ -116,7 +169,7 @@ describe('CLI: composio dev triggers list', () => {
layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
it.scoped('warns user to login', () =>
Effect.gen(function* () {
- yield* cli(['dev', 'triggers', 'list']);
+ yield* cli(['dev', 'triggers', 'list', 'gmail']);
const lines = yield* MockConsole.getLines({ stripAnsi: true });
const output = lines.join('\n');
@@ -125,31 +178,33 @@ describe('CLI: composio dev triggers list', () => {
);
});
- layer(TestLive({ baseConfigProvider: testConfigProvider }))(
- '[Given] empty results [Then] shows no trigger types found',
- it => {
- it.scoped('shows no trigger types found', () =>
- Effect.gen(function* () {
- yield* cli(['dev', 'triggers', 'list']);
- const lines = yield* MockConsole.getLines({ stripAnsi: true });
- const output = lines.join('\n');
+ layer(
+ TestLive({
+ baseConfigProvider: testConfigProvider,
+ toolkitsData: { toolkits: makeTestToolkits([{ name: 'Gmail', slug: 'gmail' }]) },
+ })
+ )('[Given] empty results [Then] shows no trigger types found', it => {
+ it.scoped('shows no trigger types found', () =>
+ Effect.gen(function* () {
+ yield* cli(['dev', 'triggers', 'list', 'gmail']);
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
+ const output = lines.join('\n');
- expect(output).toContain('No trigger types found');
- })
- );
- }
- );
+ expect(output).toContain('No trigger types found');
+ })
+ );
+ });
layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
- '[Given] --toolkits "nonexistent" [Then] shows no trigger types found with hint',
+ '[Given] toolkit "nonexistent" [Then] shows invalid toolkit error with hint',
it => {
it.scoped('shows hint about verifying toolkit slug', () =>
Effect.gen(function* () {
- yield* cli(['dev', 'triggers', 'list', '--toolkits', 'nonexistent']);
+ yield* cli(['dev', 'triggers', 'list', 'nonexistent']).pipe(Effect.ignore);
const lines = yield* MockConsole.getLines({ stripAnsi: true });
const output = lines.join('\n');
- expect(output).toContain('No trigger types found');
+ expect(output).toContain('not available');
expect(output).toContain('composio dev toolkits list');
})
);
diff --git a/ts/packages/cli/test/src/services/command-hints.test.ts b/ts/packages/cli/test/src/services/command-hints.test.ts
index b9b8d4715..77cf2e6b6 100644
--- a/ts/packages/cli/test/src/services/command-hints.test.ts
+++ b/ts/packages/cli/test/src/services/command-hints.test.ts
@@ -20,6 +20,10 @@ describe('command-hints', () => {
it('renders examples from the registry', () => {
expect(commandHintExample('root.tools.list')).toContain('composio tools list');
+ expect(commandHintExample('root.triggers.list')).toContain('composio triggers list');
+ expect(commandHintExample('root.triggers.info', { slug: 'GMAIL_NEW_GMAIL_MESSAGE' })).toContain(
+ 'GMAIL_NEW_GMAIL_MESSAGE'
+ );
expect(commandHintExample('root.execute', { slug: 'GMAIL_SEND_EMAIL' })).toContain(
'GMAIL_SEND_EMAIL'
);