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
+);