1
-import { withCommandMeta } from 'src/invocation/command-identity';
2
-import { reportFailure } from 'src/effects/report-failure';
3
-import { eventCount, finishAcceptedEvents, makeSinkFailures } from './triggers/sink-failures';
4
-import { commandInputError } from 'src/commands/errors';
5
-import { Argument, Command, Flag } from 'effect/cli';
6
-import * as FileSystem from 'effect/FileSystem';
7
-import * as Path from 'effect/Path';
8
-import type { ComposioClientShape } from '@composio/client/effect';
9
-import { Data, Deferred, Effect, FiberSet, Result, Option, Predicate } from 'effect';
10
-import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';
11
-import { ComposioClientSingleton, type ToolkitProjectScope } from 'src/services/composio-clients';
12
-import { actingUser } from 'src/commands/surface';
13
-import {
14
- resolveArtifactsRoot,
15
- resolveCliSessionArtifacts,
16
-} from 'src/services/cli-session-artifacts';
17
-import { TerminalUI } from 'src/services/terminal-ui';
18
-import { TriggersRealtime } from 'src/services/triggers-realtime';
19
-import { LISTENER_STOP, ShutdownSignal } from 'src/services/shutdown-signal';
20
-import { resolveConnectedAccountForToolkit } from 'src/services/connected-account-selection';
21
-import { parseJsonRecord } from 'src/utils/parse-json';
22
-import { toolkitFromToolSlug } from 'src/effects/toolkit-from-tool-slug';
23
-import { matchesTriggerListenFilters } from './triggers/filter';
24
-import { parseTriggerListenEvent } from './triggers/parse';
25
-import { idempotent } from 'src/services/composio-request';
26
-
27
-type TriggerCreateParams = NonNullable<
28
- Parameters<ComposioClientShape['triggerInstances']['upsert']>[1]
29
->;
30
-
31
-export class ListenCommandError extends Data.TaggedError('commands/ListenCommandError')<{
32
- readonly reason:
33
- 'connected_account_not_found' | 'unknown_trigger' | 'create_trigger' | 'disable_trigger';
34
- readonly message: string;
35
- readonly slug?: string;
36
- readonly toolkitSlug?: string;
37
- readonly cause?: unknown;
38
-}> {}
39
-
40
-const invalidOptionValue = commandInputError('listen');
41
-
42
-const errorMessage = (error: unknown): string =>
43
- Predicate.isError(error) ? error.message : String(error);
44
-
45
-const slug = Argument.String('slug').pipe(
46
- Argument.withDescription(
47
- 'Trigger slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE") or project event type (e.g. "composio.connected_account.expired")'
48
- )
49
-);
50
-
51
-const params = Flag.String('params').pipe(
52
- Flag.withAlias('p'),
53
- Flag.withDescription(
54
- 'Trigger create params as JSON/JS object, @file, or - for stdin. Only valid for trigger slugs.'
55
- ),
56
- Flag.optional
57
-);
58
-
59
-const maxEvents = Flag.Int('max-events').pipe(
60
- Flag.withDescription('Stop after receiving N matching events'),
61
- Flag.optional
62
-);
63
-
64
-const timeout = Flag.String('timeout').pipe(
65
- Flag.withDescription('Stop after a duration such as "5m", "1hr", or "30s"'),
66
- Flag.optional
67
-);
68
-
69
-const stream = Flag.String('stream').pipe(
70
- Flag.withDescription(
71
- 'Also stream each event payload inline. Pass an optional jq-like path such as ".thread.id" or ".data[0].id".'
72
- ),
73
- Flag.optional
74
-);
75
-const account = Flag.String('account').pipe(
76
- Flag.withDescription(
77
- 'Connected account selector. Matches alias, word_id, or connected account id for the inferred toolkit.'
78
- ),
79
- Flag.optional
80
-);
81
-
82
-const failFast = Flag.Boolean('fail-fast').pipe(
83
- Flag.withDescription('Stop at the first event that fails to save, and exit 1'),
84
- Flag.withDefault(false)
85
-);
86
-
87
-const debug = Flag.Boolean('debug').pipe(
88
- Flag.withDescription(
89
- 'Print verbose debug information (raw events, filter results, Pusher state)'
90
- ),
91
- Flag.withDefault(false)
92
-);
93
-
94
-const sanitizePathPart = (value: string): string =>
95
- value.replace(/[^A-Z0-9._-]+/gi, '-').replace(/^-+|-+$/g, '') || 'unknown';
96
-
97
-const disableTemporaryTrigger = (params: {
98
- client: ComposioClientShape;
99
- ui: TerminalUI;
100
- slug: string;
101
- triggerId: string;
102
-}) =>
103
- params.client.triggerInstances.manage.update(params.triggerId, { status: 'disable' }).pipe(
104
- Effect.mapError(
105
- cause =>
106
- new ListenCommandError({
107
- reason: 'disable_trigger',
108
- // "Error: " is how these messages have always introduced the client's failure.
109
- message: `Failed to disable temporary trigger "${params.triggerId}": Error: ${cause.message}`,
110
- slug: params.slug,
111
- cause,
112
- })
113
- ),
114
- Effect.tapError(error => params.ui.log.warn(error.message)),
115
- Effect.ignore
116
- );
117
-
118
-const isProjectEventType = (value: string): boolean => value.startsWith('composio.');
119
-
120
-const resolveParamsInput = (input: Option.Option<string>) =>
121
- resolveOptionalTextInput(input, { missingValue: '{}' });
122
-
123
-const parseCreateParams = (raw: string) =>
124
- parseJsonRecord(raw).pipe(
125
- Result.mapError(error =>
126
- invalidOptionValue(
127
- error.reason === 'not-a-record'
128
- ? "Expected --params to be an object, e.g. -p '{ trigger_config: { ... } }'."
129
- : "Invalid --params input. Provide JSON or a JS-style object literal, e.g. -p '{ trigger_config: { ... } }'.",
130
- '--params'
131
- )
132
- )
133
- );
134
-
135
-const assertSupportedListenParams = (params: {
136
- listeningToProjectEvent: boolean;
137
- slug: string;
138
- createParamsInput: Record<string, unknown>;
139
-}) =>
140
- params.listeningToProjectEvent && Object.keys(params.createParamsInput).length > 0
141
- ? Effect.fail(
142
- invalidOptionValue(
143
- `--params is only supported for trigger slugs. "${params.slug}" is a project-level composio.* event type and does not create a temporary trigger.`,
144
- '--params'
145
- )
146
- )
147
- : Effect.void;
148
-
149
-/**
150
- * Fails with an `unknown_trigger` error when `slug` is not a known trigger type.
151
- *
152
- * Called when the toolkit has no active connected account, and when creating the temporary trigger
153
- * fails, so a mistyped slug is reported as such instead of as a missing connection or a generic
154
- * creation failure. Neither call site is on the happy path, which makes no additional request.
155
- */
156
-const assertTriggerTypeExists = (params: {
157
- client: ComposioClientShape;
158
- slug: string;
159
- toolkitSlug?: string;
160
-}) =>
161
- params.client.triggersTypes.retrieve(params.slug, undefined, idempotent).pipe(
162
- Effect.catchTag(
163
- '@composio/client/NotFoundError',
164
- cause =>
165
- new ListenCommandError({
166
- reason: 'unknown_trigger',
167
- message: `Unknown trigger slug "${params.slug}". List available slugs with \`composio triggers list <toolkit>\`.`,
168
- slug: params.slug,
169
- toolkitSlug: params.toolkitSlug,
170
- cause,
171
- }),
172
- // A found trigger type, or any failure other than 404, is inconclusive here: fall through to
173
- // the caller's own error.
174
- () => Effect.void
175
- ),
176
- Effect.asVoid
177
- );
178
-
179
-const resolveConnectedAccountIdForTrigger = (params: {
180
- client: ComposioClientShape;
181
- slug: string;
182
- consumerUserId: string;
183
- account: Option.Option<string>;
184
- projectScope: ToolkitProjectScope;
185
-}) =>
186
- Effect.gen(function* () {
187
- const toolkitSlug = yield* toolkitFromToolSlug(params.slug, params.projectScope);
188
- if (!toolkitSlug) {
189
- return yield* Effect.fail(
190
- invalidOptionValue(
191
- `Could not infer a toolkit from trigger slug "${params.slug}". Use a standard trigger slug such as "GMAIL_NEW_GMAIL_MESSAGE", or a project event type such as "composio.connected_account.expired".`,
192
- '<slug>'
193
- )
194
- );
195
- }
196
-
197
- // The resolver `composio execute` and `composio proxy` use, so all three pick the same
198
- // account for the same `--account` (or its absence) and fail the same way when they cannot.
199
- const connectedAccountId = yield* resolveConnectedAccountForToolkit({
200
- client: params.client,
201
- toolkitSlug,
202
- userId: params.consumerUserId,
203
- selector: params.account,
204
- });
205
- if (connectedAccountId) {
206
- return connectedAccountId;
207
- }
208
-
209
- yield* assertTriggerTypeExists({ client: params.client, slug: params.slug, toolkitSlug });
210
-
211
- return yield* new ListenCommandError({
212
- reason: 'connected_account_not_found',
213
- message: `No active connected account found for toolkit "${toolkitSlug}" and consumer user "${params.consumerUserId}". Run \`composio link ${toolkitSlug}\` first.`,
214
- slug: params.slug,
215
- toolkitSlug,
216
- });
217
- });
218
-const emitStreamLine = (line: string, ui: TerminalUI) =>
219
- Effect.gen(function* () {
220
- yield* ui.log.message(line);
221
- yield* ui.output(line, { force: true });
222
- });
223
-
224
-const eventTypeOf = (eventData: Record<string, unknown>): string | undefined =>
225
- typeof eventData.type === 'string' && eventData.type.length > 0 ? eventData.type : undefined;
226
-
227
-const extractEventFileId = (eventData: Record<string, unknown>): string => {
228
- const metadata = Predicate.isObject(eventData.metadata) ? eventData.metadata : undefined;
229
- const candidates = [eventData.id, eventData.log_id, metadata?.id];
230
-
231
- for (const candidate of candidates) {
232
- if (typeof candidate === 'string' && candidate.length > 0) {
233
- return sanitizePathPart(candidate);
234
- }
235
- }
236
-
237
- return `${Date.now()}-${crypto.randomUUID().slice(0, 8)}`;
238
-};
239
-
240
-const parseStreamPath = (expression: string) =>
241
- Effect.gen(function* () {
242
- const trimmed = expression.trim();
243
- const pathTokens: Array<string | number> = [];
244
- // An empty --stream streams the whole event.
245
- if (trimmed.length === 0) return pathTokens;
246
- if (!trimmed.startsWith('.')) {
247
- return yield* Effect.fail(
248
- invalidOptionValue(
249
- 'Expected --stream to contain a jq-like path starting with "."',
250
- '--stream'
251
- )
252
- );
253
- }
254
-
255
- const tokenPattern = /(?:\.([A-Za-z0-9_-]+))|(?:\[(\d+)\])/g;
256
- let lastIndex = 0;
257
-
258
- for (const match of trimmed.matchAll(tokenPattern)) {
259
- if ((match.index ?? -1) !== lastIndex) {
260
- return yield* Effect.fail(
261
- invalidOptionValue(
262
- 'Unsupported --stream expression. Use a jq-like path such as ".foo.bar" or ".items[0].id".',
263
- '--stream'
264
- )
265
- );
266
- }
267
-
268
- if (match[1]) pathTokens.push(match[1]);
269
- if (match[2]) pathTokens.push(Number(match[2]));
270
- lastIndex += match[0].length;
271
- }
272
-
273
- if (lastIndex !== trimmed.length) {
274
- return yield* Effect.fail(
275
- invalidOptionValue(
276
- 'Unsupported --stream expression. Use a jq-like path such as ".foo.bar" or ".items[0].id".',
277
- '--stream'
278
- )
279
- );
280
- }
281
-
282
- return pathTokens;
283
- });
284
-
285
-const applyStreamPath = (value: unknown, pathTokens: ReadonlyArray<string | number>): unknown => {
286
- let current = value;
287
- for (const token of pathTokens) {
288
- if (typeof token === 'number') {
289
- if (!Array.isArray(current) || token < 0 || token >= current.length) {
290
- return undefined;
291
- }
292
- current = current[token];
293
- continue;
294
- }
295
-
296
- if (!Predicate.isObject(current)) {
297
- return undefined;
298
- }
299
-
300
- current = current[token];
301
- }
302
-
303
- return current;
304
-};
305
-
306
-const formatStreamValue = (value: unknown): string => {
307
- if (value === undefined) return 'null';
308
- if (typeof value === 'string') return value;
309
- return JSON.stringify(value);
310
-};
311
-
312
-/**
313
- * Saves one matched event: its payload file, its line in the stream file, then the `event:` line
314
- * and, when streaming (`streamPath` set), the `stream:` line.
315
- */
316
-const saveListenEvent = (params: {
317
- readonly fs: FileSystem.FileSystem;
318
- readonly ui: TerminalUI;
319
- readonly eventData: Record<string, unknown>;
320
- readonly eventFilePath: string;
321
- readonly streamFilePath: string;
322
- readonly streamEntry: string;
323
- readonly streamPath: ReadonlyArray<string | number> | undefined;
324
-}) =>
325
- Effect.gen(function* () {
326
- const { fs, ui, eventFilePath, streamPath } = params;
327
- yield* fs.writeFileString(eventFilePath, `${JSON.stringify(params.eventData, null, 2)}\n`);
328
- yield* fs.writeFileString(params.streamFilePath, `${params.streamEntry}\n`, { flag: 'a' });
329
- yield* emitStreamLine(`event: ${eventFilePath}`, ui);
330
- if (streamPath !== undefined) {
331
- const streamValue = applyStreamPath(params.eventData, streamPath);
332
- yield* emitStreamLine(`stream: ${formatStreamValue(streamValue)}`, ui);
333
- }
334
- });
335
-
336
-const formatStopMessage = (params: {
337
- matchingEvents: number;
338
- timedOut: boolean;
339
- temporaryTriggerDisabled: boolean;
340
-}): string => {
341
- const eventLabel = `event${params.matchingEvents === 1 ? '' : 's'}`;
342
- if (params.timedOut) {
343
- return params.temporaryTriggerDisabled
344
- ? `Stopped after timeout with ${params.matchingEvents} matching ${eventLabel}. Temporary trigger disabled.`
345
- : `Stopped after timeout with ${params.matchingEvents} matching ${eventLabel}.`;
346
- }
347
-
348
- return params.temporaryTriggerDisabled
349
- ? `Stopped after receiving ${params.matchingEvents} ${eventLabel}. Temporary trigger disabled.`
350
- : `Stopped after receiving ${params.matchingEvents} ${eventLabel}.`;
351
-};
352
-
353
-const TIMEOUT_UNITS_MS: Record<string, number> = {
354
- ms: 1,
355
- millisecond: 1,
356
- milliseconds: 1,
357
- s: 1_000,
358
- sec: 1_000,
359
- secs: 1_000,
360
- second: 1_000,
361
- seconds: 1_000,
362
- m: 60_000,
363
- min: 60_000,
364
- mins: 60_000,
365
- minute: 60_000,
366
- minutes: 60_000,
367
- h: 3_600_000,
368
- hr: 3_600_000,
369
- hrs: 3_600_000,
370
- hour: 3_600_000,
371
- hours: 3_600_000,
372
- d: 86_400_000,
373
- day: 86_400_000,
374
- days: 86_400_000,
375
-};
376
-
377
-const parseTimeoutMs = (value: string) =>
378
- Effect.gen(function* () {
379
- const trimmed = value.trim().toLowerCase();
380
- const match = /^(\d+(?:\.\d+)?)\s*([a-z]+)$/.exec(trimmed);
381
- const amount = Number(match?.[1]);
382
- const unit = match?.[2];
383
- const unitMs = unit === undefined ? undefined : TIMEOUT_UNITS_MS[unit];
384
- if (!match || !Number.isFinite(amount) || amount <= 0 || unitMs === undefined) {
385
- return yield* Effect.fail(
386
- invalidOptionValue(
387
- 'Invalid --timeout value. Use a duration such as "30s", "5m", "1hr", or "1day".',
388
- '--timeout'
389
- )
390
- );
391
- }
392
-
393
- return Math.round(amount * unitMs);
394
- });
395
-
396
-const resolveListenSetup = (params: {
397
- readonly slug: string;
398
- readonly inputParams: Option.Option<string>;
399
- readonly timeout: Option.Option<string>;
400
- readonly stream: Option.Option<string>;
401
- readonly maxEvents: Option.Option<number>;
402
- readonly account: Option.Option<string>;
403
- readonly client: ComposioClientShape;
404
- readonly resolvedProject: {
405
- readonly orgId: string;
406
- readonly projectId: string;
407
- };
408
- readonly consumerUserId: string;
409
-}) =>
410
- Effect.gen(function* () {
411
- const consumerUserId = params.consumerUserId;
412
- const listeningToProjectEvent = isProjectEventType(params.slug);
413
- const rawParams = Option.isSome(params.inputParams)
414
- ? (yield* resolveParamsInput(params.inputParams))?.trim() || '{}'
415
- : '{}';
416
- const createParamsInput = yield* Effect.fromResult(parseCreateParams(rawParams));
417
- yield* assertSupportedListenParams({
418
- listeningToProjectEvent,
419
- slug: params.slug,
420
- createParamsInput,
421
- });
422
-
423
- const resolvedConnectedAccountId = listeningToProjectEvent
424
- ? undefined
425
- : yield* resolveConnectedAccountIdForTrigger({
426
- client: params.client,
427
- slug: params.slug,
428
- consumerUserId,
429
- account: params.account,
430
- projectScope: {
431
- orgId: params.resolvedProject.orgId,
432
- projectId: params.resolvedProject.projectId,
433
- },
434
- });
435
-
436
- const createParams: TriggerCreateParams | undefined = listeningToProjectEvent
437
- ? undefined
438
- : {
439
- ...createParamsInput,
440
- connected_account_id: resolvedConnectedAccountId,
441
- };
442
-
443
- const timeoutMs = Option.isSome(params.timeout)
444
- ? yield* parseTimeoutMs(params.timeout.value)
445
- : undefined;
446
- const streamPath = Option.isSome(params.stream)
447
- ? yield* parseStreamPath(params.stream.value)
448
- : undefined;
449
-
450
- return {
451
- listeningToProjectEvent,
452
- createParams,
453
- timeoutMs,
454
- streamPath,
455
- shouldStream: Option.isSome(params.stream),
456
- maxEventsLimit: Option.getOrUndefined(params.maxEvents),
457
- consumerUserId,
458
- };
459
- });
460
-
461
-export const listenCmd = Command.make(
462
- 'listen',
463
- { slug, params, maxEvents, timeout, stream, account, failFast, debug },
464
- ({ slug, params, maxEvents, timeout, stream, account, failFast, debug }) =>
465
- Effect.gen(function* () {
466
- const ui = yield* TerminalUI;
467
- const fs = yield* FileSystem.FileSystem;
468
- const path = yield* Path.Path;
469
- const clientSingleton = yield* ComposioClientSingleton;
470
- const realtime = yield* TriggersRealtime;
471
- const shutdown = yield* ShutdownSignal;
472
-
473
- const { userId: actingUserId, project: resolvedProject } = yield* actingUser();
474
-
475
- const client = yield* clientSingleton.getFor({
476
- orgId: resolvedProject.orgId,
477
- projectId: resolvedProject.projectId,
478
- });
479
- const {
480
- listeningToProjectEvent,
481
- createParams,
482
- timeoutMs,
483
- streamPath,
484
- shouldStream,
485
- maxEventsLimit,
486
- consumerUserId,
487
- } = yield* resolveListenSetup({
488
- slug,
489
- inputParams: params,
490
- timeout,
491
- stream,
492
- maxEvents,
493
- account,
494
- client,
495
- resolvedProject,
496
- consumerUserId: actingUserId,
497
- });
498
-
499
- const artifactsOption = yield* resolveCliSessionArtifacts({
500
- orgId: resolvedProject.orgId,
501
- consumerUserId,
502
- });
503
- const artifactsRoot = Option.isSome(artifactsOption)
504
- ? artifactsOption.value.directoryPath
505
- : yield* resolveArtifactsRoot;
506
- const triggerDir = path.join(
507
- artifactsRoot,
508
- listeningToProjectEvent ? 'events' : 'triggers',
509
- sanitizePathPart(slug)
510
- );
511
- const streamFilePath = path.join(triggerDir, 'events.jsonl');
512
-
513
- yield* fs.makeDirectory(triggerDir, { recursive: true });
514
- yield* fs.writeFileString(streamFilePath, '', { flag: 'a' });
515
-
516
- const stopWhenDone = yield* Deferred.make<'max-events' | 'timeout' | 'failed'>();
517
- // Its own signal, so a --fail-fast failure also ends finishAcceptedEvents' wait.
518
- const failed = yield* Deferred.make<void>();
519
- let matchingEvents = 0;
520
- const writeFailures = makeSinkFailures({
521
- ui,
522
- failFast,
523
- stop: Effect.andThen(
524
- Deferred.succeed(failed, undefined),
525
- Deferred.succeed(stopWhenDone, 'failed')
526
- ).pipe(Effect.asVoid),
527
- summary: count => `${eventCount(count)} failed to write while listening.`,
528
- });
529
- const recordWriteFailure = (error: unknown) => writeFailures.record(errorMessage(error));
530
- const seenEventIds = new Set<string>();
531
-
532
- yield* Effect.acquireUseRelease(
533
- listeningToProjectEvent
534
- ? Effect.succeed<null | { trigger_id: string }>(null)
535
- : client.triggerInstances.upsert(slug, createParams).pipe(
536
- Effect.mapError(
537
- cause =>
538
- new ListenCommandError({
539
- reason: 'create_trigger',
540
- message: `Failed to create temporary trigger "${slug}": Error: ${cause.message}`,
541
- slug,
542
- cause,
543
- })
544
- ),
545
- // An active account for the inferred toolkit skips the lookup in
546
- // resolveConnectedAccountIdForTrigger, so a mistyped slug with a valid toolkit prefix
547
- // only surfaces here. The lookup's unknown_trigger failure replaces the create_trigger
548
- // error; any other outcome re-fails with the original error.
549
- Effect.catch(error =>
550
- assertTriggerTypeExists({ client, slug }).pipe(Effect.andThen(Effect.fail(error)))
551
- )
552
- ),
553
- createdTrigger =>
554
- Effect.gen(function* () {
555
- // Scoped below: a stop other than --max-events or --timeout interrupts the event
556
- // callbacks still running before the release hook sums up.
557
- const events = yield* FiberSet.make();
558
- const runEvent = yield* FiberSet.runtime(events)();
559
- yield* emitStreamLine(`listening for events ${slug} (tail at ${streamFilePath})`, ui);
560
- if (debug) {
561
- const debugMsg =
562
- createdTrigger === null
563
- ? `[debug] event_type=${slug} project=${resolvedProject.projectId} org=${resolvedProject.orgId}`
564
- : `[debug] trigger_id=${createdTrigger.trigger_id} project=${resolvedProject.projectId} org=${resolvedProject.orgId} createParams=${JSON.stringify(createParams)}`;
565
- yield* emitStreamLine(debugMsg, ui);
566
- if (createdTrigger !== null) {
567
- yield* emitStreamLine(
568
- `[debug] upsert response: ${JSON.stringify(createdTrigger)}`,
569
- ui
570
- );
571
- }
572
- }
573
-
574
- const onEvent = (eventData: Record<string, unknown>) => {
575
- runEvent(
576
- Effect.gen(function* () {
577
- if (debug) {
578
- yield* emitStreamLine(
579
- `[debug] raw event keys: ${Object.keys(eventData).join(', ')}`,
580
- ui
581
- );
582
- yield* emitStreamLine(
583
- `[debug] raw event (truncated): ${JSON.stringify(eventData).slice(0, 500)}`,
584
- ui
585
- );
586
- }
587
- const parsedTriggerEvent =
588
- createdTrigger === null ? undefined : parseTriggerListenEvent(eventData);
589
- const filterResult =
590
- createdTrigger === null
591
- ? eventTypeOf(eventData) === slug
592
- : parsedTriggerEvent !== undefined &&
593
- matchesTriggerListenFilters(
594
- { triggerId: createdTrigger.trigger_id },
595
- parsedTriggerEvent
596
- );
597
- if (debug) {
598
- yield* emitStreamLine(
599
- createdTrigger === null
600
- ? `[debug] event.type=${eventTypeOf(eventData) ?? '<missing>'} match=${filterResult}`
601
- : `[debug] parsed.id=${parsedTriggerEvent?.id ?? '<missing>'} triggerSlug=${parsedTriggerEvent?.triggerSlug ?? '<missing>'} trigger_id=${createdTrigger.trigger_id} match=${filterResult}`,
602
- ui
603
- );
604
- }
605
- if (!filterResult) {
606
- return;
607
- }
608
-
609
- const eventFileId = extractEventFileId(eventData);
610
- if (seenEventIds.has(eventFileId)) {
611
- if (debug) {
612
- yield* emitStreamLine(`[debug] skipping duplicate event ${eventFileId}`, ui);
613
- }
614
- return;
615
- }
616
- seenEventIds.add(eventFileId);
617
-
618
- matchingEvents += 1;
619
- const eventFilePath = path.join(triggerDir, `${eventFileId}-payload.json`);
620
- const streamEntry = JSON.stringify({
621
- event_id: eventFileId,
622
- event_type: eventTypeOf(eventData),
623
- trigger_id: createdTrigger?.trigger_id,
624
- trigger_slug: createdTrigger ? slug : undefined,
625
- file_path: eventFilePath,
626
- received_at: new Date().toISOString(),
627
- });
628
-
629
- // A matched event counts toward --max-events even when saving it fails.
630
- yield* saveListenEvent({
631
- fs,
632
- ui,
633
- eventData,
634
- eventFilePath,
635
- streamFilePath,
636
- streamEntry,
637
- streamPath: shouldStream ? (streamPath ?? []) : undefined,
638
- }).pipe(Effect.catch(recordWriteFailure));
639
-
640
- if (maxEventsLimit !== undefined && matchingEvents >= maxEventsLimit) {
641
- yield* Deferred.succeed(stopWhenDone, 'max-events').pipe(Effect.ignore);
642
- }
643
- }).pipe(Effect.catch(recordWriteFailure))
644
- );
645
- };
646
-
647
- const listenEffect = realtime
648
- .listenInProject(
649
- { orgId: resolvedProject.orgId, projectId: resolvedProject.projectId },
650
- onEvent,
651
- { onSubscribed: shutdown.cooperate(LISTENER_STOP) }
652
- )
653
- .pipe(Effect.onInterrupt(() => ui.log.info(`Stopped listening for events ${slug}.`)));
654
-
655
- if (timeoutMs !== undefined) {
656
- yield* Effect.forkScoped(
657
- Effect.sleep(timeoutMs).pipe(
658
- Effect.andThen(Deferred.succeed(stopWhenDone, 'timeout')),
659
- Effect.ignore
660
- )
661
- );
662
- }
663
-
664
- // Ctrl-C or SIGTERM after the subscription is a clean stop: exit 0 after the release.
665
- const stopReason = yield* Effect.raceAllFirst([
666
- listenEffect,
667
- Deferred.await(stopWhenDone),
668
- Effect.as(shutdown.requested, 'signal' as const),
669
- ]);
670
- if (stopReason === 'max-events' || stopReason === 'timeout') {
671
- yield* finishAcceptedEvents(events, failed);
672
- }
673
- if (stopReason === 'max-events') {
674
- yield* ui.outro(
675
- formatStopMessage({
676
- matchingEvents,
677
- timedOut: false,
678
- temporaryTriggerDisabled: createdTrigger !== null,
679
- })
680
- );
681
- return;
682
- }
683
-
684
- if (stopReason === 'timeout') {
685
- yield* ui.outro(
686
- formatStopMessage({
687
- matchingEvents,
688
- timedOut: true,
689
- temporaryTriggerDisabled: createdTrigger !== null,
690
- })
691
- );
692
- }
693
- }).pipe(Effect.scoped),
694
- created =>
695
- Effect.gen(function* () {
696
- if (created !== null) {
697
- yield* disableTemporaryTrigger({ client, ui, slug, triggerId: created.trigger_id });
698
- }
699
- // Runs on every stop of the use phase — max-events, timeout, --fail-fast, Ctrl+C or
700
- // SIGTERM, and an interruption — so a piped caller always gets the count.
701
- yield* writeFailures.report;
702
- })
703
- ).pipe(
704
- Effect.catchTag('services/TriggerRealtimeSubscriptionError', error =>
705
- reportFailure(
706
- ui,
707
- `Could not subscribe to realtime trigger events: ${error.message}. Check your network connection or run \`composio login\`.`
708
- )
709
- )
710
- );
711
- })
712
-).pipe(
713
- Command.withDescription(
714
- 'Listen to consumer-project realtime events. Trigger slugs create a temporary trigger; top-level composio.* event types subscribe directly.'
715
- ),
716
- Command.withExamples([
717
- {
718
- command: 'composio listen GMAIL_NEW_GMAIL_MESSAGE',
719
- },
720
- {
721
- command: 'composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --max-events 5',
722
- },
723
- {
724
- command: 'composio listen GMAIL_NEW_GMAIL_MESSAGE --account work --timeout 5m',
725
- },
726
- {
727
- command: 'composio listen GMAIL_NEW_GMAIL_MESSAGE --max-events 5 --fail-fast',
728
- },
729
- {
730
- command: "composio listen GMAIL_NEW_GMAIL_MESSAGE --timeout 1hr --stream '.data.threadId'",
731
- },
732
- {
733
- command:
734
- 'composio listen SLACK_CHANNEL_MESSAGE_RECEIVED -p \'{ trigger_config: { channel_id: "C123" } }\'',
735
- },
736
- {
737
- command: 'composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --stream',
738
- },
739
- {
740
- command: "composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --stream '.data.threadId'",
741
- },
742
- ]),
743
- withCommandMeta({ requiresLogin: true })
744
-);