10
import { ProjectContext } from 'src/services/project-context';
11
import { ComposioClientSingleton, getSessionInfoByUserApiKey } from 'src/services/composio-clients';
12
import {
13
- resolveCommandProject,
13
formatResolveCommandProjectError,
14
+ resolveCommandProject,
15
} from 'src/services/command-project';
16
-import { invalidateConsumerConnectedToolkitsCache } from 'src/services/consumer-short-term-cache';
16
+import {
17
+ invalidateConsumerConnectedToolkitsCache,
18
+ writeConsumerConnectedToolkitsCache,
19
+} from 'src/services/consumer-short-term-cache';
20
import { appendCliSessionHistory } from 'src/services/cli-session-artifacts';
21
+import { formatConnectedAccountsTable } from '../format';
22
+import {
23
+ groupCachedConnectedAccountsByToolkit,
24
+ resolveDefaultConnectedAccountsByToolkit,
25
+} from 'src/services/connected-account-selection';
26
27
const toolkit = Args.text({ name: 'toolkit' }).pipe(
28
Args.withDescription('Toolkit slug to link (e.g. "github", "gmail")'),
49
Options.withDescription('Do not wait for authorization; only print link info')
50
);
51
52
+const alias = Options.text('alias').pipe(
53
+ Options.withDescription(
54
+ 'Alias to assign to the connected account. Required when creating an additional account for the same toolkit/auth config.'
55
+ ),
56
+ Options.optional
57
+);
58
+
59
+const list = Options.boolean('list').pipe(
60
+ Options.withDefault(false),
61
+ Options.withDescription(
62
+ 'List existing connected accounts for the toolkit instead of creating a new link'
63
+ )
64
+);
65
+
66
const showRedirectUrl = (
67
ui: TerminalUI,
68
redirectUrl: string,
220
}
221
: undefined;
222
223
+const normalizeAlias = (rawAlias: string) => rawAlias.trim();
224
+
225
+const listActiveConnectedAccounts = (params: {
226
+ readonly client: RawComposioClient;
227
+ readonly userId: string;
228
+ readonly toolkitSlug?: string;
229
+ readonly authConfigId?: string;
230
+}) =>
231
+ Effect.tryPromise(() =>
232
+ params.client.connectedAccounts.list({
233
+ user_ids: [params.userId],
234
+ toolkit_slugs: params.toolkitSlug ? [params.toolkitSlug] : undefined,
235
+ auth_config_ids: params.authConfigId ? [params.authConfigId] : undefined,
236
+ statuses: ['ACTIVE'],
237
+ limit: 100,
238
+ })
239
+ );
240
+
241
+const formatExistingAccountLabels = (
242
+ items: ReadonlyArray<{
243
+ readonly id: string;
244
+ readonly alias?: string | null;
245
+ readonly word_id?: string | null;
246
+ }>
247
+) =>
248
+ items
249
+ .map(item => {
250
+ const labels = [item.alias, item.word_id].filter(
251
+ (value): value is string => typeof value === 'string' && value.trim().length > 0
252
+ );
253
+ return labels.length > 0 ? `${item.id} (${labels.join(', ')})` : item.id;
254
+ })
255
+ .join(', ');
256
+
257
+const ensureAliasForAdditionalAccount = (params: {
258
+ readonly ui: TerminalUI;
259
+ readonly alias: Option.Option<string>;
260
+ readonly connectedAccountId: string;
261
+ readonly existingAccounts: {
262
+ readonly items: ReadonlyArray<{
263
+ readonly id: string;
264
+ readonly alias?: string | null;
265
+ readonly word_id?: string | null;
266
+ }>;
267
+ };
268
+ readonly scopeDescription: string;
269
+}) =>
270
+ Effect.gen(function* () {
271
+ if (Option.isSome(params.alias)) {
272
+ return true as const;
273
+ }
274
+
275
+ const existingIds = new Set(params.existingAccounts.items.map(item => item.id));
276
+ if (params.existingAccounts.items.length === 0 || existingIds.has(params.connectedAccountId)) {
277
+ return true as const;
278
+ }
279
+
280
+ yield* params.ui.log.error(
281
+ `A connected account already exists for ${params.scopeDescription}. Pass --alias to create another one.`
282
+ );
283
+ yield* params.ui.note(
284
+ formatExistingAccountLabels(params.existingAccounts.items),
285
+ 'Existing accounts'
286
+ );
287
+ return false as const;
288
+ });
289
+
290
+const patchConnectedAccountAlias = (params: {
291
+ readonly ui: TerminalUI;
292
+ readonly client: RawComposioClient;
293
+ readonly connectedAccountId: string;
294
+ readonly alias: Option.Option<string>;
295
+}) =>
296
+ Effect.gen(function* () {
297
+ if (Option.isNone(params.alias)) {
298
+ return;
299
+ }
300
+
301
+ const normalizedAlias = normalizeAlias(params.alias.value);
302
+ if (normalizedAlias.length === 0) {
303
+ return yield* Effect.fail(new Error('`--alias` cannot be empty.'));
304
+ }
305
+
306
+ yield* params.ui.withSpinner(
307
+ `Assigning alias "${normalizedAlias}"...`,
308
+ Effect.tryPromise(() =>
309
+ params.client.patch(`/api/v3/connected_accounts/${params.connectedAccountId}`, {
310
+ body: { alias: normalizedAlias },
311
+ })
312
+ )
313
+ );
314
+ });
315
+
316
+const resolveLinkUserId = (params: {
317
+ readonly resolvedProject: {
318
+ readonly projectType: 'CONSUMER' | 'DEVELOPER';
319
+ readonly consumerUserId?: string;
320
+ };
321
+ readonly requestedUserId: Option.Option<string>;
322
+ readonly projectContext: {
323
+ readonly resolve: Effect.Effect<
324
+ Option.Option<{ readonly testUserId: Option.Option<string> }>,
325
+ unknown
326
+ >;
327
+ };
328
+ readonly userContext: {
329
+ readonly data: {
330
+ readonly testUserId: Option.Option<string>;
331
+ };
332
+ };
333
+}) =>
334
+ Effect.gen(function* () {
335
+ const resolvedProjectContext = yield* params.projectContext.resolve.pipe(
336
+ Effect.catchAll(() => Effect.succeed(Option.none()))
337
+ );
338
+ const localTestUserId = Option.flatMap(resolvedProjectContext, keys => keys.testUserId);
339
+
340
+ const resolvedUserId =
341
+ params.resolvedProject.projectType === 'CONSUMER'
342
+ ? Option.fromNullable(params.resolvedProject.consumerUserId)
343
+ : Option.match(params.requestedUserId, {
344
+ onSome: value => Option.some(value),
345
+ onNone: () => Option.orElse(localTestUserId, () => params.userContext.data.testUserId),
346
+ });
347
+
348
+ return {
349
+ resolvedUserId,
350
+ resolvedProjectContext,
351
+ localTestUserId,
352
+ };
353
+ });
354
+
355
+const handleListConnectedAccounts = (params: {
356
+ readonly toolkit: Option.Option<string>;
357
+ readonly authConfig: Option.Option<string>;
358
+ readonly rootOnly: boolean;
359
+ readonly projectName: Option.Option<string>;
360
+ readonly userId: Option.Option<string>;
361
+ readonly ui: TerminalUI;
362
+ readonly clientSingleton: {
363
+ readonly getFor: (params: {
364
+ readonly orgId: string;
365
+ readonly projectId: string;
366
+ }) => Effect.Effect<RawComposioClient, unknown>;
367
+ };
368
+ readonly projectContext: {
369
+ readonly resolve: Effect.Effect<
370
+ Option.Option<{ readonly testUserId: Option.Option<string> }>,
371
+ unknown
372
+ >;
373
+ };
374
+ readonly userContext: {
375
+ readonly data: {
376
+ readonly testUserId: Option.Option<string>;
377
+ };
378
+ };
379
+}) =>
380
+ Effect.gen(function* () {
381
+ if (Option.isNone(params.toolkit)) {
382
+ yield* params.ui.log.error(
383
+ '`--list` requires a toolkit slug, e.g. `composio link gmail --list`.'
384
+ );
385
+ return;
386
+ }
387
+ if (Option.isSome(params.authConfig)) {
388
+ yield* params.ui.log.error('`--list` cannot be combined with `--auth-config`.');
389
+ return;
390
+ }
391
+
392
+ const toolkitSlug = params.toolkit.value;
393
+ const resolvedProject = yield* resolveCommandProject({
394
+ mode: 'consumer',
395
+ projectName: params.rootOnly ? undefined : Option.getOrUndefined(params.projectName),
396
+ }).pipe(Effect.mapError(formatResolveCommandProjectError));
397
+ const client = yield* params.clientSingleton.getFor({
398
+ orgId: resolvedProject.orgId,
399
+ projectId: resolvedProject.projectId,
400
+ });
401
+ const { resolvedUserId } = yield* resolveLinkUserId({
402
+ resolvedProject,
403
+ requestedUserId: params.userId,
404
+ projectContext: params.projectContext,
405
+ userContext: params.userContext,
406
+ });
407
+
408
+ if (Option.isNone(resolvedUserId)) {
409
+ return yield* Effect.fail(
410
+ new Error('Missing user id. Provide --user-id or run composio dev init/login first.')
411
+ );
412
+ }
413
+
414
+ const accounts = yield* params.ui.withSpinner(
415
+ `Listing connected accounts for "${toolkitSlug}"...`,
416
+ Effect.tryPromise(() =>
417
+ client.connectedAccounts.list({
418
+ toolkit_slugs: [toolkitSlug],
419
+ user_ids: [resolvedUserId.value],
420
+ statuses: ['ACTIVE'],
421
+ limit: 100,
422
+ })
423
+ )
424
+ );
425
+
426
+ if (resolvedProject.projectType === 'CONSUMER' && resolvedProject.consumerUserId) {
427
+ yield* writeConsumerConnectedToolkitsCache({
428
+ orgId: resolvedProject.orgId,
429
+ consumerUserId: resolvedProject.consumerUserId,
430
+ toolkits: [toolkitSlug],
431
+ toolRouterConnectedAccounts: {
432
+ connectedAccounts: resolveDefaultConnectedAccountsByToolkit(
433
+ accounts.items as Parameters<typeof resolveDefaultConnectedAccountsByToolkit>[0]
434
+ ),
435
+ availableConnectedAccounts: groupCachedConnectedAccountsByToolkit(
436
+ accounts.items as Parameters<typeof groupCachedConnectedAccountsByToolkit>[0]
437
+ ),
438
+ },
439
+ }).pipe(Effect.catchAll(() => Effect.void));
440
+ }
441
+
442
+ if (accounts.items.length === 0) {
443
+ yield* params.ui.log.warn(`No active connected accounts found for "${toolkitSlug}".`);
444
+ yield* params.ui.output(
445
+ JSON.stringify({ toolkit: toolkitSlug, items: [], total: 0 }, null, 2),
446
+ { force: true }
447
+ );
448
+ return;
449
+ }
450
+
451
+ yield* params.ui.note(
452
+ formatConnectedAccountsTable(
453
+ accounts.items as Parameters<typeof formatConnectedAccountsTable>[0]
454
+ ),
455
+ `${toolkitSlug}: connected accounts`
456
+ );
457
+ yield* params.ui.output(
458
+ JSON.stringify(
459
+ {
460
+ toolkit: toolkitSlug,
461
+ total: accounts.items.length,
462
+ items: accounts.items,
463
+ },
464
+ null,
465
+ 2
466
+ ),
467
+ { force: true }
468
+ );
469
+ });
470
+
471
+const handleLegacyAuthConfigLink = (params: {
472
+ readonly authConfigId: string;
473
+ readonly requestedUserId: Option.Option<string>;
474
+ readonly projectName: Option.Option<string>;
475
+ readonly noWait: boolean;
476
+ readonly alias: Option.Option<string>;
477
+ readonly ui: TerminalUI;
478
+ readonly clientSingleton: {
479
+ readonly getFor: (params: {
480
+ readonly orgId: string;
481
+ readonly projectId: string;
482
+ }) => Effect.Effect<RawComposioClient, unknown>;
483
+ };
484
+ readonly projectContext: {
485
+ readonly resolve: Effect.Effect<
486
+ Option.Option<{ readonly testUserId: Option.Option<string> }>,
487
+ unknown
488
+ >;
489
+ };
490
+ readonly userContext: {
491
+ readonly data: {
492
+ readonly testUserId: Option.Option<string>;
493
+ };
494
+ };
495
+}) =>
496
+ Effect.gen(function* () {
497
+ const resolvedProjectContext = yield* params.projectContext.resolve.pipe(
498
+ Effect.catchAll(() => Effect.succeed(Option.none()))
499
+ );
500
+ const localTestUserId = Option.flatMap(resolvedProjectContext, keys => keys.testUserId);
501
+ const globalTestUserId = params.userContext.data.testUserId;
502
+ const resolvedUserId = Option.match(params.requestedUserId, {
503
+ onSome: value => Option.some(value),
504
+ onNone: () => Option.orElse(localTestUserId, () => globalTestUserId),
505
+ });
506
+
507
+ if (Option.isNone(resolvedUserId)) {
508
+ return yield* Effect.fail(
509
+ new Error(
510
+ 'Missing user id. Provide --user-id or run composio dev init to set test_user_id.'
511
+ )
512
+ );
513
+ }
514
+ if (Option.isNone(params.projectName) && Option.isNone(resolvedProjectContext)) {
515
+ yield* params.ui.log.error(
516
+ '`--auth-config` is developer-project scoped. Pass `--project-name <name>` or run from a directory initialized with `composio dev init`.'
517
+ );
518
+ return;
519
+ }
520
+ if (Option.isNone(params.requestedUserId) && Option.isSome(localTestUserId)) {
521
+ yield* params.ui.log.warn(`Using test user id "${localTestUserId.value}"`);
522
+ } else if (Option.isNone(params.requestedUserId) && Option.isSome(globalTestUserId)) {
523
+ yield* params.ui.log.warn(`Using global test user id "${globalTestUserId.value}"`);
524
+ }
525
+
526
+ const resolvedProject = yield* resolveCommandProject({
527
+ mode: 'developer',
528
+ projectName: Option.getOrUndefined(params.projectName),
529
+ }).pipe(Effect.mapError(formatResolveCommandProjectError));
530
+ const client = yield* params.clientSingleton.getFor({
531
+ orgId: resolvedProject.orgId,
532
+ projectId: resolvedProject.projectId,
533
+ });
534
+ const existingAccounts = yield* listActiveConnectedAccounts({
535
+ client,
536
+ userId: resolvedUserId.value,
537
+ authConfigId: params.authConfigId,
538
+ }).pipe(Effect.catchAll(() => Effect.succeed({ items: [] })));
539
+ const linkOpt = yield* params.ui
540
+ .withSpinner(
541
+ 'Creating link session...',
542
+ Effect.tryPromise(() =>
543
+ client.link.create({
544
+ auth_config_id: params.authConfigId,
545
+ user_id: resolvedUserId.value,
546
+ })
547
+ )
548
+ )
549
+ .pipe(
550
+ Effect.asSome,
551
+ Effect.catchAll(error =>
552
+ Effect.gen(function* () {
553
+ const message =
554
+ extractMessage(error) ??
555
+ `Failed to create link for auth config "${params.authConfigId}".`;
556
+ yield* params.ui.log.error(message);
557
+ yield* params.ui.log.step(
558
+ 'Browse available auth configs:\n> composio dev auth-configs list'
559
+ );
560
+ return Option.none();
561
+ })
562
+ )
563
+ );
564
+
565
+ if (Option.isNone(linkOpt)) return;
566
+
567
+ const validatedLink = yield* validateLinkResponse(params.ui, linkOpt.value);
568
+ if (Option.isNone(validatedLink)) return;
569
+
570
+ const { connectedAccountId, redirectUrl } = validatedLink.value;
571
+ const canContinue = yield* ensureAliasForAdditionalAccount({
572
+ ui: params.ui,
573
+ alias: params.alias,
574
+ connectedAccountId,
575
+ existingAccounts,
576
+ scopeDescription: `user "${resolvedUserId.value}" in auth config "${params.authConfigId}"`,
577
+ });
578
+ if (!canContinue) return;
579
+
580
+ yield* patchConnectedAccountAlias({
581
+ ui: params.ui,
582
+ client,
583
+ connectedAccountId,
584
+ alias: params.alias,
585
+ });
586
+
587
+ if (params.noWait) {
588
+ yield* showRedirectUrl(params.ui, redirectUrl);
589
+ yield* params.ui.output(
590
+ JSON.stringify(
591
+ {
592
+ status: 'pending',
593
+ message: 'Complete authorization by opening the URL',
594
+ connected_account_id: connectedAccountId,
595
+ redirect_url: redirectUrl,
596
+ project_type: resolvedProject.projectType,
597
+ },
598
+ null,
599
+ 2
600
+ ),
601
+ { force: true }
602
+ );
603
+ return;
604
+ }
605
+
606
+ yield* waitForActiveConnection(params.ui, client, connectedAccountId, redirectUrl);
607
+ });
608
+
609
const runConnectedAccountsLink = (params: {
610
toolkit: Option.Option<string>;
611
authConfig: Option.Option<string>;
612
userId: Option.Option<string>;
613
projectName: Option.Option<string>;
614
noWait: boolean;
615
+ alias: Option.Option<string>;
616
+ list: boolean;
617
rootOnly: boolean;
618
}) =>
619
Effect.gen(function* () {
654
return;
655
}
656
247
- if (Option.isSome(params.authConfig)) {
248
- const authConfigId = params.authConfig.value;
249
- const resolvedProjectContext = yield* projectContext.resolve.pipe(
250
- Effect.catchAll(() => Effect.succeed(Option.none()))
251
- );
252
- const localTestUserId = Option.flatMap(resolvedProjectContext, keys => keys.testUserId);
253
- const globalTestUserId = userContext.data.testUserId;
254
- const resolvedUserId = Option.match(params.userId, {
255
- onSome: value => Option.some(value),
256
- onNone: () => Option.orElse(localTestUserId, () => globalTestUserId),
257
- });
258
- if (Option.isNone(resolvedUserId)) {
259
- return yield* Effect.fail(
260
- new Error(
261
- 'Missing user id. Provide --user-id or run composio dev init to set test_user_id.'
262
- )
263
- );
264
- }
265
- if (Option.isNone(params.projectName) && Option.isNone(resolvedProjectContext)) {
266
- yield* ui.log.error(
267
- '`--auth-config` is developer-project scoped. Pass `--project-name <name>` or run from a directory initialized with `composio dev init`.'
268
- );
269
- return;
270
- }
271
- if (Option.isNone(params.userId) && Option.isSome(localTestUserId)) {
272
- yield* ui.log.warn(`Using test user id "${localTestUserId.value}"`);
273
- } else if (Option.isNone(params.userId) && Option.isSome(globalTestUserId)) {
274
- yield* ui.log.warn(`Using global test user id "${globalTestUserId.value}"`);
275
- }
276
- const resolvedProject = yield* resolveCommandProject({
277
- mode: 'developer',
278
- projectName: Option.getOrUndefined(params.projectName),
279
- }).pipe(Effect.mapError(formatResolveCommandProjectError));
280
- const client = yield* clientSingleton.getFor({
281
- orgId: resolvedProject.orgId,
282
- projectId: resolvedProject.projectId,
657
+ if (params.list) {
658
+ yield* handleListConnectedAccounts({
659
+ toolkit: params.toolkit,
660
+ authConfig: params.authConfig,
661
+ rootOnly: params.rootOnly,
662
+ projectName: params.projectName,
663
+ userId: params.userId,
664
+ ui,
665
+ clientSingleton,
666
+ projectContext,
667
+ userContext,
668
});
284
- const linkOpt = yield* ui
285
- .withSpinner(
286
- 'Creating link session...',
287
- Effect.tryPromise(() =>
288
- client.link.create({
289
- auth_config_id: authConfigId,
290
- user_id: resolvedUserId.value,
291
- })
292
- )
293
- )
294
- .pipe(
295
- Effect.asSome,
296
- Effect.catchAll(error =>
297
- Effect.gen(function* () {
298
- const message =
299
- extractMessage(error) ?? `Failed to create link for auth config "${authConfigId}".`;
300
- yield* ui.log.error(message);
301
- yield* ui.log.step(
302
- 'Browse available auth configs:\n> composio dev auth-configs list'
303
- );
304
- return Option.none();
305
- })
306
- )
307
- );
669
+ return;
670
+ }
671
309
- if (Option.isNone(linkOpt)) return;
310
-
311
- const validatedLink = yield* validateLinkResponse(ui, linkOpt.value);
312
- if (Option.isNone(validatedLink)) return;
313
-
314
- const { connectedAccountId: connId, redirectUrl } = validatedLink.value;
315
- if (params.noWait) {
316
- yield* showRedirectUrl(ui, redirectUrl);
317
- yield* ui.output(
318
- JSON.stringify(
319
- {
320
- status: 'pending',
321
- message: 'Complete authorization by opening the URL',
322
- connected_account_id: connId,
323
- redirect_url: redirectUrl,
324
- project_type: resolvedProject.projectType,
325
- },
326
- null,
327
- 2
328
- ),
329
- { force: true }
330
- );
331
- } else {
332
- yield* waitForActiveConnection(ui, client, connId, redirectUrl);
333
- }
672
+ if (Option.isSome(params.authConfig)) {
673
+ yield* handleLegacyAuthConfigLink({
674
+ authConfigId: params.authConfig.value,
675
+ requestedUserId: params.userId,
676
+ projectName: params.projectName,
677
+ noWait: params.noWait,
678
+ alias: params.alias,
679
+ ui,
680
+ clientSingleton,
681
+ projectContext,
682
+ userContext,
683
+ });
684
return;
685
}
686
707
orgId: resolvedProject.orgId,
708
projectId: resolvedProject.projectId,
709
});
710
+ const existingAccounts = yield* listActiveConnectedAccounts({
711
+ client,
712
+ userId: resolvedUserId.value,
713
+ toolkitSlug,
714
+ }).pipe(Effect.catchAll(() => Effect.succeed({ items: [] })));
715
716
const linkOpt = yield* ui
717
.withSpinner(
756
if (Option.isNone(validatedLink)) return;
757
758
const { connectedAccountId: connAccountId, redirectUrl } = validatedLink.value;
759
+ const canContinue = yield* ensureAliasForAdditionalAccount({
760
+ ui,
761
+ alias: params.alias,
762
+ connectedAccountId: connAccountId,
763
+ existingAccounts,
764
+ scopeDescription: `user "${resolvedUserId.value}" in toolkit "${toolkitSlug}"`,
765
+ });
766
+ if (!canContinue) return;
767
+
768
+ yield* patchConnectedAccountAlias({
769
+ ui,
770
+ client,
771
+ connectedAccountId: connAccountId,
772
+ alias: params.alias,
773
+ });
774
775
if (params.noWait) {
776
yield* showRedirectUrl(ui, redirectUrl);
820
821
export const connectedAccountsCmd$Link = Command.make(
822
'link',
453
- { toolkit, authConfig, userId, projectName, noWait },
454
- ({ toolkit, authConfig, userId, projectName, noWait }) =>
823
+ { toolkit, authConfig, userId, projectName, noWait, alias, list },
824
+ ({ toolkit, authConfig, userId, projectName, noWait, alias, list }) =>
825
runConnectedAccountsLink({
826
toolkit,
827
authConfig,
828
userId,
829
projectName,
830
noWait,
831
+ alias,
832
+ list,
833
rootOnly: false,
834
})
835
).pipe(
840
'',
841
'Examples:',
842
' composio link github',
843
+ ' composio link gmail --alias work',
844
+ ' composio link github --list',
845
'',
846
'See also:',
847
' composio search "<query>" Find tools to use after linking',
852
853
export const rootConnectedAccountsCmd$Link = Command.make(
854
'link',
481
- { toolkit, noWait },
482
- ({ toolkit, noWait }) =>
855
+ { toolkit, noWait, alias, list },
856
+ ({ toolkit, noWait, alias, list }) =>
857
runConnectedAccountsLink({
858
toolkit,
859
authConfig: Option.none(),
860
userId: Option.none(),
861
projectName: Option.none(),
862
noWait,
863
+ alias,
864
+ list,
865
rootOnly: true,
866
})
867
).pipe(
872
'',
873
'Examples:',
874
' composio link github',
875
+ ' composio link gmail --alias work',
876
+ ' composio link github --list',
877
'',
878
'See also:',
879
' composio search "<query>" Find tools to use after linking',