@devries-cameron20 / composio Mirror · read-only / commits / c4654159c
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 22, 00:45 UTC

Add multi-account selection and experimental CLI feature flags (#3129)

## Summary - Add connected account selection support across CLI flows, including link, tool execution, and listen/session handling. - Introduce experimental feature-tag config plumbing so CLI visibility and command help can vary by enabled features. - Expand user config, cache, and session artifacts to persist account-selection state and recent toolkit choices. - Update connected-account formatting, root command visibility typing, and installation test shell-config checks. ## Testing - `pnpm test` for the CLI package: Not run. - Added and updated unit tests for connected-account selection, CLI user config, short-term cache, and tool execution flows. - Installation workflow shell-config grep checks were adjusted to validate both zsh and bash updates more reliably. --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

Rahul Tarak committed Apr 7, 2026 at 01:49 UTC c4654159c76be5eb59c82fc7a01bb2ff200beee7
22 files changed +1703 -203
ts/packages/cli/src/analytics/dispatch.ts
+4 -1
@@ -533,7 +533,10 @@ export const runBackgroundWorkerFromArgv = async (argv: ReadonlyArray<string>):
533 try {
534 const decoded = decodeBase64Url(encodedPayload);
535 const body = JSON.parse(decoded) as ReturnType<typeof createCliCodactFailureBody>;
536 - if (body?.failure_type !== 'wrong_tool_slug' && body?.failure_type !== 'wrong_tool_input_param') {
536 + if (
537 + body?.failure_type !== 'wrong_tool_slug' &&
538 + body?.failure_type !== 'wrong_tool_input_param'
539 + ) {
540 return;
541 }
542
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts
+469 -91
@@ -10,11 +10,19 @@ import { extractMessage, extractSlug } from 'src/utils/api-error-extraction';
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")'),
@@ -41,6 +49,20 @@ const noWait = Options.boolean('no-wait').pipe(
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,
@@ -198,12 +220,400 @@ const getConsumerCacheScope = (resolvedProject: {
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* () {
@@ -244,93 +654,33 @@ const runConnectedAccountsLink = (params: {
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
@@ -357,6 +707,11 @@ const runConnectedAccountsLink = (params: {
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(
@@ -401,6 +756,21 @@ const runConnectedAccountsLink = (params: {
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);
@@ -450,14 +820,16 @@ const runConnectedAccountsLink = (params: {
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(
@@ -468,6 +840,8 @@ export const connectedAccountsCmd$Link = Command.make(
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',
@@ -478,14 +852,16 @@ export const connectedAccountsCmd$Link = Command.make(
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(
@@ -496,6 +872,8 @@ export const rootConnectedAccountsCmd$Link = Command.make(
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',
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.whoami.cmd.ts
+2
@@ -72,6 +72,8 @@ export const connectedAccountsCmd$Whoami = Command.make('whoami', { id }, ({ id
72 JSON.stringify(
73 {
74 id: item.id,
75 + alias: item.alias,
76 + word_id: item.word_id,
77 toolkit: item.toolkit.slug,
78 user_id: item.user_id,
79 status: item.status,
ts/packages/cli/src/commands/connected-accounts/format.ts
+10 -2
@@ -7,10 +7,12 @@ import { truncate } from 'src/ui/truncate';
7 * Format a list of connected accounts as a human-readable table.
8 */
9 export function formatConnectedAccountsTable(items: ReadonlyArray<ConnectedAccountItem>): string {
10 - const header = `${bold('Id'.padEnd(18))} ${bold('User Id'.padEnd(20))} ${bold('Toolkit'.padEnd(14))} ${bold('Auth Config'.padEnd(18))} ${bold('Auth Scheme'.padEnd(14))} ${bold('Status')}`;
10 + const header = `${bold('Id'.padEnd(18))} ${bold('Alias'.padEnd(14))} ${bold('Word'.padEnd(12))} ${bold('User Id'.padEnd(20))} ${bold('Toolkit'.padEnd(14))} ${bold('Auth Config'.padEnd(18))} ${bold('Auth Scheme'.padEnd(14))} ${bold('Status')}`;
11
12 const rows = items.map(item => {
13 const id = truncate(redact({ value: item.id, prefix: 'con_' }), 18).padEnd(18);
14 + const alias = truncate(item.alias || '-', 14).padEnd(14);
15 + const wordId = truncate(item.word_id || '-', 12).padEnd(12);
16 const userId = truncate(item.user_id, 20).padEnd(20);
17 const toolkit = truncate(item.toolkit.slug, 14).padEnd(14);
18 const authConfig = truncate(redact({ value: item.auth_config.id, prefix: 'ac_' }), 18).padEnd(
@@ -18,7 +20,7 @@ export function formatConnectedAccountsTable(items: ReadonlyArray<ConnectedAccou
20 );
21 const authScheme = truncate(item.auth_config.auth_scheme || '-', 14).padEnd(14);
22 const status = item.status === 'ACTIVE' ? item.status : gray(item.status);
21 - return `${id} ${userId} ${toolkit} ${authConfig} ${authScheme} ${status}`;
23 + return `${id} ${alias} ${wordId} ${userId} ${toolkit} ${authConfig} ${authScheme} ${status}`;
24 });
25
26 return [header, ...rows].join('\n');
@@ -31,6 +33,8 @@ export function formatConnectedAccountsJson(items: ReadonlyArray<ConnectedAccoun
33 return JSON.stringify(
34 items.map(item => ({
35 id: item.id,
36 + alias: item.alias,
37 + word_id: item.word_id,
38 user_id: item.user_id,
39 toolkit_slug: item.toolkit.slug,
40 auth_config_id: item.auth_config.id,
@@ -50,6 +54,8 @@ export function formatConnectedAccountInfo(item: ConnectedAccountItem): string {
54 const lines: string[] = [];
55
56 lines.push(`${bold('Id:')} ${redact({ value: item.id, prefix: 'con_' })}`);
57 + lines.push(`${bold('Alias:')} ${item.alias || '-'}`);
58 + lines.push(`${bold('Word Id:')} ${item.word_id || '-'}`);
59 lines.push(`${bold('Status:')} ${item.status === 'ACTIVE' ? item.status : gray(item.status)}`);
60
61 if (item.status_reason) {
@@ -79,6 +85,8 @@ export function formatConnectedAccountInfo(item: ConnectedAccountItem): string {
85 export function formatConnectedAccountWhoami(item: ConnectedAccountItem): string {
86 const lines: string[] = [];
87 lines.push(`${bold('Id:')} ${redact({ value: item.id, prefix: 'con_' })}`);
88 + lines.push(`${bold('Alias:')} ${item.alias || '-'}`);
89 + lines.push(`${bold('Word Id:')} ${item.word_id || '-'}`);
90 lines.push(`${bold('Status:')} ${item.status === 'ACTIVE' ? item.status : gray(item.status)}`);
91 lines.push(`${bold('Toolkit:')} ${item.toolkit.slug}`);
92 lines.push(`${bold('User Id:')} ${item.user_id}`);
ts/packages/cli/src/commands/index.ts
-1
@@ -1,7 +1,6 @@
1 import process from 'node:process';
2 import { Effect, Option } from 'effect';
3 import { Command } from '@effect/cli';
4 -import * as constants from 'src/constants';
4 import { $defaultCmd } from './$default.cmd';
5 import { getVersion } from 'src/effects/version';
6 import { versionCmd } from './version.cmd';
ts/packages/cli/src/commands/listen.cmd.ts
+119 -70
@@ -16,6 +16,10 @@ import {
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 {
20 + formatConnectedAccountChoices,
21 + resolveConnectedAccountSelection,
22 +} from 'src/services/connected-account-selection';
23 import { parseJsonIsh } from 'src/utils/parse-json-ish';
24 import { toolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug';
25 import { matchesTriggerListenFilters } from './triggers/filter';
@@ -51,6 +55,12 @@ const stream = Options.text('stream').pipe(
55 ),
56 Options.optional
57 );
58 +const account = Options.text('account').pipe(
59 + Options.withDescription(
60 + 'Connected account selector. Matches alias, word_id, or connected account id for the inferred toolkit.'
61 + ),
62 + Options.optional
63 +);
64
65 const debug = Options.boolean('debug').pipe(
66 Options.withDescription(
@@ -103,6 +113,7 @@ const resolveConnectedAccountIdForTrigger = (params: {
113 client: RawComposioClient;
114 slug: string;
115 consumerUserId: string;
116 + account: Option.Option<string>;
117 }) =>
118 Effect.gen(function* () {
119 const toolkitSlug = toolkitFromToolSlug(params.slug);
@@ -125,36 +136,29 @@ const resolveConnectedAccountIdForTrigger = (params: {
136 catch: error =>
137 new Error(`Failed to list connected accounts for "${toolkitSlug}": ${String(error)}`),
138 });
128 - const connectedAccountId = selectConnectedAccountId(connectedAccounts.items);
129 -
130 - if (!connectedAccountId) {
131 - return yield* Effect.fail(
132 - new Error(
133 - `No active connected account found for toolkit "${toolkitSlug}" and consumer user "${params.consumerUserId}". Run \`composio link ${toolkitSlug}\` first.`
134 - )
135 - );
139 + const selectedAccount = resolveConnectedAccountSelection(
140 + connectedAccounts.items as Parameters<typeof resolveConnectedAccountSelection>[0],
141 + Option.getOrUndefined(params.account)
142 + );
143 + if (selectedAccount?.id) {
144 + return selectedAccount.id;
145 }
146
138 - return connectedAccountId;
147 + const choices = formatConnectedAccountChoices(
148 + connectedAccounts.items as Parameters<typeof formatConnectedAccountChoices>[0]
149 + );
150 + const suffix =
151 + Option.isSome(params.account) && choices.length > 0
152 + ? ` Available accounts: ${choices.join(', ')}.`
153 + : '';
154 + return yield* Effect.fail(
155 + new Error(
156 + Option.isSome(params.account)
157 + ? `No connected account matched "${params.account.value}" for toolkit "${toolkitSlug}" and consumer user "${params.consumerUserId}".${suffix}`
158 + : `No active connected account found for toolkit "${toolkitSlug}" and consumer user "${params.consumerUserId}". Run \`composio link ${toolkitSlug}\` first.`
159 + )
160 + );
161 });
140 -
141 -const selectConnectedAccountId = (
142 - items: ReadonlyArray<{
143 - id: string;
144 - updated_at: string;
145 - is_disabled: boolean;
146 - }>
147 -): string | undefined => {
148 - const active = items.filter(item => !item.is_disabled);
149 - if (active.length === 0) {
150 - return undefined;
151 - }
152 -
153 - return [...active]
154 - .sort((left, right) => Date.parse(right.updated_at) - Date.parse(left.updated_at))
155 - .at(0)?.id;
156 -};
157 -
162 const emitStreamLine = (line: string, ui: TerminalUI) =>
163 Effect.gen(function* () {
164 yield* ui.log.message(line);
@@ -303,10 +307,78 @@ const parseTimeoutMs = (value: string): number => {
307 return Math.round(amount * unitMs);
308 };
309
310 +const resolveListenSetup = (params: {
311 + readonly slug: string;
312 + readonly inputParams: Option.Option<string>;
313 + readonly timeout: Option.Option<string>;
314 + readonly stream: Option.Option<string>;
315 + readonly maxEvents: Option.Option<number>;
316 + readonly account: Option.Option<string>;
317 + readonly client: RawComposioClient;
318 + readonly resolvedProject: {
319 + readonly orgId: string;
320 + readonly projectId: string;
321 + readonly consumerUserId?: string;
322 + };
323 +}) =>
324 + Effect.gen(function* () {
325 + if (!params.resolvedProject.consumerUserId) {
326 + return yield* Effect.fail(
327 + new Error('No consumer user is available in the current project context.')
328 + );
329 + }
330 +
331 + const listeningToProjectEvent = isProjectEventType(params.slug);
332 + const rawParams = Option.isSome(params.inputParams)
333 + ? (yield* resolveParamsInput(params.inputParams))?.trim() || '{}'
334 + : '{}';
335 + const createParamsInput = yield* parseCreateParams(rawParams);
336 + yield* assertSupportedListenParams({
337 + listeningToProjectEvent,
338 + slug: params.slug,
339 + createParamsInput,
340 + });
341 +
342 + const resolvedConnectedAccountId = listeningToProjectEvent
343 + ? undefined
344 + : yield* resolveConnectedAccountIdForTrigger({
345 + client: params.client,
346 + slug: params.slug,
347 + consumerUserId: params.resolvedProject.consumerUserId,
348 + account: params.account,
349 + });
350 +
351 + const createParams = listeningToProjectEvent
352 + ? undefined
353 + : ({
354 + ...createParamsInput,
355 + connected_account_id: resolvedConnectedAccountId,
356 + } as Parameters<typeof params.client.triggerInstances.upsert>[1]);
357 +
358 + return {
359 + listeningToProjectEvent,
360 + createParams,
361 + timeoutMs: Option.match(params.timeout, {
362 + onNone: () => undefined,
363 + onSome: value => parseTimeoutMs(value),
364 + }),
365 + streamPath: Option.match(params.stream, {
366 + onNone: () => undefined,
367 + onSome: value => {
368 + const trimmed = value.trim();
369 + return trimmed.length === 0 ? [] : parseStreamPath(trimmed);
370 + },
371 + }),
372 + shouldStream: Option.isSome(params.stream),
373 + maxEventsLimit: Option.getOrUndefined(params.maxEvents),
374 + consumerUserId: params.resolvedProject.consumerUserId,
375 + };
376 + });
377 +
378 export const listenCmd = Command.make(
379 'listen',
308 - { slug, params, maxEvents, timeout, stream, debug },
309 - ({ slug, params, maxEvents, timeout, stream, debug }) =>
380 + { slug, params, maxEvents, timeout, stream, account, debug },
381 + ({ slug, params, maxEvents, timeout, stream, account, debug }) =>
382 Effect.gen(function* () {
383 if (!(yield* requireAuth)) return;
384
@@ -324,50 +396,28 @@ export const listenCmd = Command.make(
396 orgId: resolvedProject.orgId,
397 projectId: resolvedProject.projectId,
398 });
327 -
328 - if (!resolvedProject.consumerUserId) {
329 - return yield* Effect.fail(
330 - new Error('No consumer user is available in the current project context.')
331 - );
332 - }
333 -
334 - const listeningToProjectEvent = isProjectEventType(slug);
335 - const rawParams = Option.isSome(params)
336 - ? (yield* resolveParamsInput(params))?.trim() || '{}'
337 - : '{}';
338 - const createParamsInput = yield* parseCreateParams(rawParams);
339 - yield* assertSupportedListenParams({ listeningToProjectEvent, slug, createParamsInput });
340 -
341 - const resolvedConnectedAccountId = listeningToProjectEvent
342 - ? undefined
343 - : yield* resolveConnectedAccountIdForTrigger({
344 - client,
345 - slug,
346 - consumerUserId: resolvedProject.consumerUserId,
347 - });
348 -
349 - const createParams = listeningToProjectEvent
350 - ? undefined
351 - : ({
352 - ...createParamsInput,
353 - connected_account_id: resolvedConnectedAccountId,
354 - } as Parameters<typeof client.triggerInstances.upsert>[1]);
355 - const timeoutMs = Option.match(timeout, {
356 - onNone: () => undefined,
357 - onSome: value => parseTimeoutMs(value),
358 - });
359 - const streamPath = Option.match(stream, {
360 - onNone: () => undefined,
361 - onSome: value => {
362 - const trimmed = value.trim();
363 - return trimmed.length === 0 ? [] : parseStreamPath(trimmed);
364 - },
399 + const {
400 + listeningToProjectEvent,
401 + createParams,
402 + timeoutMs,
403 + streamPath,
404 + shouldStream,
405 + maxEventsLimit,
406 + consumerUserId,
407 + } = yield* resolveListenSetup({
408 + slug,
409 + inputParams: params,
410 + timeout,
411 + stream,
412 + maxEvents,
413 + account,
414 + client,
415 + resolvedProject,
416 });
366 - const shouldStream = Option.isSome(stream);
417
418 const artifactsOption = yield* resolveCliSessionArtifacts({
419 orgId: resolvedProject.orgId,
370 - consumerUserId: resolvedProject.consumerUserId,
420 + consumerUserId,
421 });
422 const artifactsRoot = Option.match(artifactsOption, {
423 onNone: () => resolveFallbackArtifactsDir(),
@@ -383,7 +433,6 @@ export const listenCmd = Command.make(
433 yield* fs.makeDirectory(triggerDir, { recursive: true });
434 yield* fs.writeFileString(streamFilePath, '', { flag: 'a' });
435
386 - const maxEventsLimit = Option.getOrUndefined(maxEvents);
436 const stopWhenDone = yield* Deferred.make<'max-events' | 'timeout'>();
437 let matchingEvents = 0;
438 const seenEventIds = new Set<string>();
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+125 -3
@@ -1,4 +1,5 @@
1 import { Args, Command, Options } from '@effect/cli';
2 +import type { Composio } from '@composio/client';
3 import util from 'node:util';
4 import { Effect, Option, Either, Exit, Fiber, Cause } from 'effect';
5 import { encodingForModel } from 'js-tiktoken';
@@ -43,6 +44,10 @@ import {
44 getFreshConsumerConnectedToolkitsFromCache,
45 refreshConsumerConnectedToolkitsCache,
46 } from 'src/services/consumer-short-term-cache';
47 +import {
48 + formatConnectedAccountChoices,
49 + resolveConnectedAccountSelection,
50 +} from 'src/services/connected-account-selection';
51 import {
52 appendCliSessionHistory,
53 resolveCliSessionArtifacts,
@@ -69,6 +74,12 @@ const file = Options.text('file').pipe(
74 Options.withDescription('Inject a local file path into the single file_uploadable input'),
75 Options.optional
76 );
77 +const accountOption = Options.text('account').pipe(
78 + Options.withDescription(
79 + 'Connected account selector for the inferred toolkit. Matches alias, word_id, or connected account id.'
80 + ),
81 + Options.optional
82 +);
83
84 const userId = Options.text('user-id').pipe(
85 Options.optional,
@@ -271,6 +282,8 @@ const getExecuteOutputEncoder = () => {
282 return executeOutputEncoder;
283 };
284
285 +const shouldStoreLargeExecuteOutput = () => process.env.COMPOSIO_CLI_INVOCATION_ORIGIN !== 'run';
286 +
287 type StoredExecuteOutputSummary = {
288 readonly successful: true;
289 readonly error: null;
@@ -327,7 +340,7 @@ const prepareExecuteOutput = (
340 Effect.gen(function* () {
341 const json = serializeExecuteOutput(result);
342 const tokenCount = getExecuteOutputEncoder().encode(json).length;
330 - if (tokenCount <= EXECUTE_INLINE_OUTPUT_TOKEN_THRESHOLD) {
343 + if (tokenCount <= EXECUTE_INLINE_OUTPUT_TOKEN_THRESHOLD || !shouldStoreLargeExecuteOutput()) {
344 return {
345 kind: 'inline' as const,
346 json,
@@ -812,6 +825,7 @@ type RunToolsExecuteParams = {
825 slug: string;
826 data: Option.Option<string>;
827 file: Option.Option<string>;
828 + account: Option.Option<string>;
829 userId: Option.Option<string>;
830 projectName: Option.Option<string>;
831 surface: 'root' | 'dev';
@@ -828,6 +842,7 @@ type SharedRunToolsExecuteParams = Omit<RunToolsExecuteParams, 'slug' | 'data' |
842 type ParallelExecuteSpec = {
843 readonly slug: string;
844 readonly data: Option.Option<string>;
845 + readonly account: Option.Option<string>;
846 };
847
848 type ParsedParallelExecuteArgs = SharedRunToolsExecuteParams & {
@@ -859,6 +874,7 @@ type ResolvedExecuteContext = {
874 };
875 readonly args: Record<string, unknown>;
876 readonly resolvedUserId: string;
877 + readonly selectedConnectedAccountId?: string;
878 readonly executeParams: ToolExecuteParams;
879 readonly executeOutputDir?: string;
880 };
@@ -901,6 +917,57 @@ const emitCachedSchema = (
917 );
918 });
919
920 +const resolveExplicitConnectedAccount = (params: {
921 + readonly client: Composio;
922 + readonly toolkitSlug?: string;
923 + readonly userId: string;
924 + readonly selector: Option.Option<string>;
925 +}): Effect.Effect<string | undefined, Error> =>
926 + Effect.gen(function* () {
927 + if (!params.toolkitSlug) return undefined;
928 + const toolkitSlug = params.toolkitSlug;
929 +
930 + const accounts = yield* Effect.tryPromise({
931 + try: () =>
932 + params.client.connectedAccounts.list({
933 + toolkit_slugs: [toolkitSlug],
934 + user_ids: [params.userId],
935 + statuses: ['ACTIVE'],
936 + limit: 100,
937 + }),
938 + catch: error =>
939 + new Error(
940 + `Failed to load connected accounts for toolkit "${toolkitSlug}": ${String(error)}`
941 + ),
942 + });
943 +
944 + const selected = resolveConnectedAccountSelection(
945 + accounts.items as Parameters<typeof resolveConnectedAccountSelection>[0],
946 + Option.getOrUndefined(params.selector)
947 + );
948 +
949 + if (selected) {
950 + return selected.id;
951 + }
952 +
953 + if (Option.isNone(params.selector)) {
954 + return undefined;
955 + }
956 +
957 + const choices = formatConnectedAccountChoices(
958 + accounts.items as Parameters<typeof formatConnectedAccountChoices>[0]
959 + );
960 + const hint =
961 + choices.length > 0
962 + ? ` Available accounts: ${choices.join(', ')}.`
963 + : ' No active connected accounts were found for that toolkit.';
964 + return yield* Effect.fail(
965 + new Error(
966 + `No connected account matched "${params.selector.value}" for toolkit "${toolkitSlug}".${hint}`
967 + )
968 + );
969 + });
970 +
971 const resolveExecuteContext = (params: RunToolsExecuteParams) =>
972 Effect.gen(function* () {
973 const resolvedProject = yield* resolveCommandProject({
@@ -942,6 +1009,13 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>
1009 orgId: resolvedProject.orgId,
1010 projectId: resolvedProject.projectId,
1011 });
1012 + const toolkitSlug = toolkitFromToolSlug(params.slug);
1013 + const selectedConnectedAccountId = yield* resolveExplicitConnectedAccount({
1014 + client,
1015 + toolkitSlug,
1016 + userId: resolvedUserId.value,
1017 + selector: params.account,
1018 + });
1019 const args = Option.isSome(params.file)
1020 ? yield* getOrFetchToolInputDefinition(params.slug, {
1021 orgId: resolvedProject.orgId,
@@ -973,11 +1047,18 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>
1047 resolvedProject,
1048 args,
1049 resolvedUserId: resolvedUserId.value,
1050 + selectedConnectedAccountId,
1051 executeOutputDir,
1052 executeParams: {
1053 userId: resolvedUserId.value,
1054 arguments: args,
1055 client,
1056 + connectedAccounts:
1057 + toolkitSlug && selectedConnectedAccountId
1058 + ? {
1059 + [toolkitSlug]: selectedConnectedAccountId,
1060 + }
1061 + : undefined,
1062 cacheScope:
1063 resolvedProject.projectType === 'CONSUMER' && resolvedProject.consumerUserId
1064 ? {
@@ -1400,6 +1481,7 @@ const runToolsExecute = (params: RunToolsExecuteParams) =>
1481 toolDebugLog('execute_params', {
1482 slug: params.slug,
1483 userId: context.resolvedUserId,
1484 + connectedAccountId: context.selectedConnectedAccountId,
1485 arguments: context.args,
1486 projectId: context.resolvedProject.projectId,
1487 orgId: context.resolvedProject.orgId,
@@ -1439,6 +1521,7 @@ const parseParallelExecuteArgs = (
1521 let skipConnectionCheck = false;
1522 let skipToolParamsCheck = false;
1523 let skipChecks = false;
1524 + let account = Option.none<string>();
1525 let userId = Option.none<string>();
1526 let projectName = Option.none<string>();
1527 const specs: ParallelExecuteSpec[] = [];
@@ -1492,6 +1575,12 @@ const parseParallelExecuteArgs = (
1575 skipChecks = true;
1576 continue;
1577 }
1578 + if (token === '--account' || token.startsWith('--account=')) {
1579 + const parsed = readValue(token, i);
1580 + account = Option.some(parsed.value);
1581 + i = parsed.nextIndex;
1582 + continue;
1583 + }
1584 if (token === '--user-id' || token.startsWith('--user-id=')) {
1585 if (!config.allowUserId) {
1586 throw new Error(`${token} is not supported for this execute command.`);
@@ -1525,6 +1614,7 @@ const parseParallelExecuteArgs = (
1614 currentSpec = {
1615 slug: currentSpec.slug,
1616 data: Option.some(parsed.value),
1617 + account: currentSpec.account,
1618 };
1619 i = parsed.nextIndex;
1620 continue;
@@ -1537,6 +1627,7 @@ const parseParallelExecuteArgs = (
1627 currentSpec = {
1628 slug: token,
1629 data: Option.none(),
1630 + account,
1631 };
1632 }
1633
@@ -1559,6 +1650,7 @@ const parseParallelExecuteArgs = (
1650 skipConnectionCheck,
1651 skipToolParamsCheck,
1652 skipChecks,
1653 + account,
1654 };
1655 };
1656
@@ -1628,6 +1720,7 @@ const runParallelSchemaFetchFromParsed = (params: ParsedParallelExecuteArgs) =>
1720 params.specs,
1721 () =>
1722 resolveSchemaContext({
1723 + account: params.account,
1724 userId: params.userId,
1725 projectName: params.projectName,
1726 surface: params.surface,
@@ -1725,6 +1818,7 @@ const runParallelToolsExecuteFromParsed = (params: ParsedParallelExecuteArgs) =>
1818 slug: spec.slug,
1819 data: spec.data,
1820 file: Option.none(),
1821 + account: spec.account,
1822 userId: params.userId,
1823 projectName: params.projectName,
1824 surface: params.surface,
@@ -1906,12 +2000,33 @@ export const runParallelToolsExecuteFromArgv = (argv: ReadonlyArray<string>) =>
2000
2001 export const rootToolsCmd$Execute = Command.make(
2002 'execute',
1909 - { slug, data, file, getSchema, dryRun, skipConnectionCheck, skipToolParamsCheck, skipChecks },
1910 - ({ slug, data, file, getSchema, dryRun, skipConnectionCheck, skipToolParamsCheck, skipChecks }) =>
2003 + {
2004 + slug,
2005 + data,
2006 + file,
2007 + account: accountOption,
2008 + getSchema,
2009 + dryRun,
2010 + skipConnectionCheck,
2011 + skipToolParamsCheck,
2012 + skipChecks,
2013 + },
2014 + ({
2015 + slug,
2016 + data,
2017 + file,
2018 + account,
2019 + getSchema,
2020 + dryRun,
2021 + skipConnectionCheck,
2022 + skipToolParamsCheck,
2023 + skipChecks,
2024 + }) =>
2025 runToolsExecute({
2026 slug,
2027 data,
2028 file,
2029 + account,
2030 userId: Option.none(),
2031 projectName: Option.none(),
2032 surface: 'root',
@@ -1930,6 +2045,7 @@ export const rootToolsCmd$Execute = Command.make(
2045 '',
2046 'Examples:',
2047 ' composio execute GMAIL_SEND_EMAIL -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
2048 + ' composio execute GMAIL_SEND_EMAIL --account default -d \'{ recipient_email: "a@b.com" }\'',
2049 ' composio execute SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK --file ./image.png -d \'{ channels: "C123" }\'',
2050 ' composio execute --parallel GMAIL_SEND_EMAIL -d \'{ recipient_email: "a@b.com" }\' GITHUB_CREATE_AN_ISSUE -d \'{ owner: "acme", repo: "app", title: "Bug" }\'',
2051 " composio execute GMAIL_SEND_EMAIL --dry-run -d '{ ... }' Preview without executing",
@@ -1937,6 +2053,7 @@ export const rootToolsCmd$Execute = Command.make(
2053 '',
2054 'Flags:',
2055 ' --file <path> Inject a local file path into the single file_uploadable input',
2056 + ' --account <selector> Select connected account by alias, word_id, or account id',
2057 ' -p, --parallel Execute repeated TOOL_SLUG -d <json> groups concurrently',
2058 ' --skip-connection-check Skip the connected-account check',
2059 ' --skip-tool-params-check Skip input validation against cached schema',
@@ -1956,6 +2073,7 @@ export const devToolsCmd$Execute = Command.make(
2073 slug,
2074 data,
2075 file,
2076 + account: accountOption,
2077 userId,
2078 projectName,
2079 getSchema,
@@ -1968,6 +2086,7 @@ export const devToolsCmd$Execute = Command.make(
2086 slug,
2087 data,
2088 file,
2089 + account,
2090 userId,
2091 projectName,
2092 getSchema,
@@ -1980,6 +2099,7 @@ export const devToolsCmd$Execute = Command.make(
2099 slug,
2100 data,
2101 file,
2102 + account,
2103 userId,
2104 projectName,
2105 surface: 'dev',
@@ -1999,12 +2119,14 @@ export const devToolsCmd$Execute = Command.make(
2119 '',
2120 'Examples:',
2121 ' composio dev playground-execute GMAIL_SEND_EMAIL -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
2122 + ' composio dev playground-execute GMAIL_SEND_EMAIL --account default -d \'{ recipient_email: "a@b.com" }\'',
2123 ' composio dev playground-execute SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK --file ./image.png -d \'{ channels: "C123" }\'',
2124 ' composio dev playground-execute GMAIL_SEND_EMAIL --dry-run -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
2125 ' composio dev playground-execute GMAIL_SEND_EMAIL --get-schema',
2126 '',
2127 'Flags:',
2128 ' --file <path> Inject a local file path into the single file_uploadable input',
2129 + ' --account <selector> Select connected account by alias, word_id, or account id',
2130 ' -p, --parallel Execute repeated TOOL_SLUG -d <json> groups concurrently',
2131 ].join('\n')
2132 )
ts/packages/cli/src/effects/create-tool-router-session.ts
+38 -1
@@ -2,6 +2,7 @@ import { Effect, Option } from 'effect';
2 import type { Composio } from '@composio/client';
3 import {
4 getFreshConsumerToolRouterAuthConfigsFromCache,
5 + getFreshConsumerToolRouterConnectedAccountsFromCache,
6 writeConsumerConnectedToolkitsCache,
7 } from 'src/services/consumer-short-term-cache';
8 import { resolveToolRouterSessionConnections } from 'src/services/tool-router-session-connections';
@@ -16,6 +17,8 @@ export interface CreateToolRouterSessionOptions {
17 readonly orgId: string;
18 readonly consumerUserId: string;
19 };
20 + /** Explicit connected-account pins by toolkit slug. */
21 + readonly connectedAccounts?: Record<string, string>;
22 }
23
24 /**
@@ -32,6 +35,11 @@ export const createToolRouterSession = (
35 options?: CreateToolRouterSessionOptions
36 ) =>
37 Effect.gen(function* () {
38 + const mergeConnectedAccounts = (...mappings: Array<Record<string, string> | undefined>) => {
39 + const merged = Object.assign({}, ...mappings.filter(Boolean));
40 + return Object.keys(merged).length > 0 ? merged : undefined;
41 + };
42 +
43 const cachedAuthConfigs = options?.cacheScope
44 ? yield* getFreshConsumerToolRouterAuthConfigsFromCache({
45 orgId: options.cacheScope.orgId,
@@ -39,15 +47,39 @@ export const createToolRouterSession = (
47 toolkits: options.toolkits,
48 })
49 : Option.none();
50 + const cachedConnectedAccounts = options?.cacheScope
51 + ? yield* getFreshConsumerToolRouterConnectedAccountsFromCache({
52 + orgId: options.cacheScope.orgId,
53 + consumerUserId: options.cacheScope.consumerUserId,
54 + toolkits: options.toolkits,
55 + })
56 + : Option.none();
57
58 const connectionContext = Option.isSome(cachedAuthConfigs)
59 ? {
60 connectedToolkits: options?.toolkits ?? [],
61 authConfigs: cachedAuthConfigs.value.authConfigs,
62 + connectedAccounts: mergeConnectedAccounts(
63 + Option.isSome(cachedConnectedAccounts)
64 + ? cachedConnectedAccounts.value.connectedAccounts
65 + : undefined,
66 + options?.connectedAccounts
67 + ),
68 + availableConnectedAccounts: Option.isSome(cachedConnectedAccounts)
69 + ? cachedConnectedAccounts.value.availableConnectedAccounts
70 + : undefined,
71 }
72 : yield* resolveToolRouterSessionConnections(client, userId, {
73 toolkits: options?.toolkits,
50 - });
74 + }).pipe(
75 + Effect.map(connectionContext => ({
76 + ...connectionContext,
77 + connectedAccounts: mergeConnectedAccounts(
78 + connectionContext.connectedAccounts,
79 + options?.connectedAccounts
80 + ),
81 + }))
82 + );
83
84 if (options?.cacheScope && Option.isNone(cachedAuthConfigs)) {
85 yield* writeConsumerConnectedToolkitsCache({
@@ -57,6 +89,10 @@ export const createToolRouterSession = (
89 toolRouterAuthConfigs: {
90 authConfigs: connectionContext.authConfigs,
91 },
92 + toolRouterConnectedAccounts: {
93 + connectedAccounts: connectionContext.connectedAccounts,
94 + availableConnectedAccounts: connectionContext.availableConnectedAccounts,
95 + },
96 }).pipe(Effect.catchAll(() => Effect.void));
97 }
98
@@ -64,6 +100,7 @@ export const createToolRouterSession = (
100 client.toolRouter.session.create({
101 user_id: userId,
102 auth_configs: connectionContext.authConfigs,
103 + connected_accounts: connectionContext.connectedAccounts,
104 manage_connections: { enable: options?.manageConnections ?? false },
105 toolkits:
106 options?.toolkits && options.toolkits.length > 0
ts/packages/cli/src/models/connected-accounts.ts
+2
@@ -11,6 +11,8 @@ import { Schema } from 'effect';
11 */
12 export const ConnectedAccountItem = Schema.Struct({
13 id: Schema.String,
14 + word_id: Schema.optional(Schema.NullOr(Schema.String)),
15 + alias: Schema.optional(Schema.NullOr(Schema.String)),
16 status: Schema.Literal('INITIALIZING', 'INITIATED', 'ACTIVE', 'FAILED', 'EXPIRED', 'INACTIVE'),
17 status_reason: Schema.optionalWith(Schema.NullOr(Schema.String), { default: () => null }),
18 is_disabled: Schema.Boolean,
ts/packages/cli/src/services/connected-account-selection.ts new
+126
@@ -0,0 +1,126 @@
1 +import type { ConnectedAccountItem } from 'src/models/connected-accounts';
2 +
3 +export type CachedConnectedAccountSummary = {
4 + readonly id: string;
5 + readonly alias: string | null;
6 + readonly wordId: string | null;
7 + readonly updatedAt: string;
8 + readonly createdAt: string;
9 +};
10 +
11 +const normalizeSelector = (value: string): string => value.trim().toLowerCase();
12 +
13 +const parseTimestamp = (value: string | undefined): number => {
14 + if (!value) return 0;
15 + const parsed = Date.parse(value);
16 + return Number.isFinite(parsed) ? parsed : 0;
17 +};
18 +
19 +const compareNewestFirst = (
20 + left: Pick<ConnectedAccountItem, 'updated_at' | 'created_at'>,
21 + right: Pick<ConnectedAccountItem, 'updated_at' | 'created_at'>
22 +): number =>
23 + Math.max(parseTimestamp(right.updated_at), parseTimestamp(right.created_at)) -
24 + Math.max(parseTimestamp(left.updated_at), parseTimestamp(left.created_at));
25 +
26 +const compareSummaryNewestFirst = (
27 + left: Pick<CachedConnectedAccountSummary, 'updatedAt' | 'createdAt'>,
28 + right: Pick<CachedConnectedAccountSummary, 'updatedAt' | 'createdAt'>
29 +): number =>
30 + Math.max(parseTimestamp(right.updatedAt), parseTimestamp(right.createdAt)) -
31 + Math.max(parseTimestamp(left.updatedAt), parseTimestamp(left.createdAt));
32 +
33 +export const isUsableConnectedAccount = (
34 + item: Pick<ConnectedAccountItem, 'status' | 'is_disabled'>
35 +): boolean => item.status === 'ACTIVE' && !item.is_disabled;
36 +
37 +export const toCachedConnectedAccountSummary = (
38 + item: Pick<ConnectedAccountItem, 'id' | 'alias' | 'word_id' | 'updated_at' | 'created_at'>
39 +): CachedConnectedAccountSummary => ({
40 + id: item.id,
41 + alias: item.alias ?? null,
42 + wordId: item.word_id ?? null,
43 + updatedAt: item.updated_at,
44 + createdAt: item.created_at,
45 +});
46 +
47 +export const groupCachedConnectedAccountsByToolkit = (
48 + items: ReadonlyArray<ConnectedAccountItem>
49 +): Record<string, ReadonlyArray<CachedConnectedAccountSummary>> => {
50 + const grouped = new Map<string, CachedConnectedAccountSummary[]>();
51 +
52 + for (const item of items) {
53 + if (!isUsableConnectedAccount(item)) continue;
54 + const toolkit = item.toolkit.slug.trim().toLowerCase();
55 + if (!toolkit) continue;
56 +
57 + const next = grouped.get(toolkit) ?? [];
58 + next.push(toCachedConnectedAccountSummary(item));
59 + grouped.set(toolkit, next);
60 + }
61 +
62 + return Object.fromEntries(
63 + [...grouped.entries()].map(([toolkit, summaries]) => [
64 + toolkit,
65 + [...summaries].sort(compareSummaryNewestFirst),
66 + ])
67 + );
68 +};
69 +
70 +export const resolveDefaultConnectedAccountsByToolkit = (
71 + items: ReadonlyArray<ConnectedAccountItem>
72 +): Record<string, string> => {
73 + const grouped = new Map<string, ConnectedAccountItem[]>();
74 +
75 + for (const item of items) {
76 + if (!isUsableConnectedAccount(item)) continue;
77 + const toolkit = item.toolkit.slug.trim().toLowerCase();
78 + if (!toolkit) continue;
79 +
80 + const next = grouped.get(toolkit) ?? [];
81 + next.push(item);
82 + grouped.set(toolkit, next);
83 + }
84 +
85 + return Object.fromEntries(
86 + [...grouped.entries()]
87 + .map(([toolkit, toolkitItems]) => {
88 + const selected = resolveConnectedAccountSelection(toolkitItems);
89 + return selected ? ([toolkit, selected.id] as const) : null;
90 + })
91 + .filter((entry): entry is readonly [string, string] => entry !== null)
92 + );
93 +};
94 +
95 +export const resolveConnectedAccountSelection = (
96 + items: ReadonlyArray<ConnectedAccountItem>,
97 + selector?: string
98 +): ConnectedAccountItem | undefined => {
99 + const usable = items.filter(isUsableConnectedAccount).sort(compareNewestFirst);
100 + if (usable.length === 0) return undefined;
101 +
102 + if (!selector || selector.trim().length === 0) {
103 + return usable.find(item => normalizeSelector(item.alias ?? '') === 'default') ?? usable[0];
104 + }
105 +
106 + const normalized = normalizeSelector(selector);
107 + return (
108 + usable.find(item => normalizeSelector(item.id) === normalized) ??
109 + usable.find(item => normalizeSelector(item.alias ?? '') === normalized) ??
110 + usable.find(item => normalizeSelector(item.word_id ?? '') === normalized)
111 + );
112 +};
113 +
114 +export const formatConnectedAccountChoice = (
115 + item: Pick<ConnectedAccountItem, 'id' | 'alias' | 'word_id'>
116 +): string => {
117 + const labels = [item.alias, item.word_id].filter(
118 + (value): value is string => typeof value === 'string' && value.trim().length > 0
119 + );
120 + return labels.length > 0 ? `${labels.join(' / ')} (${item.id})` : item.id;
121 +};
122 +
123 +export const formatConnectedAccountChoices = (
124 + items: ReadonlyArray<ConnectedAccountItem>
125 +): ReadonlyArray<string> =>
126 + items.filter(isUsableConnectedAccount).sort(compareNewestFirst).map(formatConnectedAccountChoice);
ts/packages/cli/src/services/consumer-short-term-cache.ts
+153 -1
@@ -10,6 +10,7 @@ import {
10 getConsumerConnectedToolkits,
11 resolveConsumerProject,
12 } from 'src/services/composio-clients';
13 +import type { CachedConnectedAccountSummary } from 'src/services/connected-account-selection';
14 import { resolveCommandProject } from 'src/services/command-project';
15 import { resolveToolRouterSessionConnections } from 'src/services/tool-router-session-connections';
16 import { ComposioUserContext } from 'src/services/user-context';
@@ -22,10 +23,19 @@ export type ConsumerToolRouterAuthConfigMappings = {
23 readonly authConfigs?: Record<string, string>;
24 };
25
26 +export type ConsumerToolRouterConnectedAccountMappings = {
27 + readonly connectedAccounts?: Record<string, string>;
28 + readonly availableConnectedAccounts?: Record<
29 + string,
30 + ReadonlyArray<CachedConnectedAccountSummary>
31 + >;
32 +};
33 +
34 type CacheEntry = {
35 readonly toolkits: ReadonlyArray<string>;
36 readonly expiresAt: string;
37 readonly toolRouterAuthConfigs?: ConsumerToolRouterAuthConfigMappings;
38 + readonly toolRouterConnectedAccounts?: ConsumerToolRouterConnectedAccountMappings;
39 readonly probablyMyCliSessionsByCwdHash?: Record<
40 string,
41 {
@@ -164,6 +174,70 @@ const mergeAuthConfigMappings = (params: {
174 });
175 };
176
177 +const normalizeConnectedAccountMappings = (
178 + mappings?: ConsumerToolRouterConnectedAccountMappings
179 +): ConsumerToolRouterConnectedAccountMappings | undefined => {
180 + if (!mappings) return undefined;
181 +
182 + const connectedAccounts = Object.fromEntries(
183 + Object.entries(mappings.connectedAccounts ?? {})
184 + .map(([toolkit, connectedAccountId]) => [toolkit.toLowerCase(), connectedAccountId])
185 + .filter(
186 + ([, connectedAccountId]) =>
187 + typeof connectedAccountId === 'string' && connectedAccountId.length > 0
188 + )
189 + );
190 +
191 + const availableConnectedAccounts = Object.fromEntries(
192 + Object.entries(mappings.availableConnectedAccounts ?? {})
193 + .map(([toolkit, accounts]) => [
194 + toolkit.toLowerCase(),
195 + accounts.filter(
196 + account =>
197 + typeof account.id === 'string' &&
198 + account.id.length > 0 &&
199 + typeof account.updatedAt === 'string' &&
200 + typeof account.createdAt === 'string'
201 + ),
202 + ])
203 + .filter(([, accounts]) => accounts.length > 0)
204 + );
205 +
206 + if (
207 + Object.keys(connectedAccounts).length === 0 &&
208 + Object.keys(availableConnectedAccounts).length === 0
209 + ) {
210 + return undefined;
211 + }
212 +
213 + return {
214 + connectedAccounts: Object.keys(connectedAccounts).length > 0 ? connectedAccounts : undefined,
215 + availableConnectedAccounts:
216 + Object.keys(availableConnectedAccounts).length > 0 ? availableConnectedAccounts : undefined,
217 + };
218 +};
219 +
220 +const mergeConnectedAccountMappings = (params: {
221 + readonly current?: ConsumerToolRouterConnectedAccountMappings;
222 + readonly next?: ConsumerToolRouterConnectedAccountMappings;
223 +}) => {
224 + const current = normalizeConnectedAccountMappings(params.current);
225 + const next = normalizeConnectedAccountMappings(params.next);
226 + if (!current) return next;
227 + if (!next) return current;
228 +
229 + return normalizeConnectedAccountMappings({
230 + connectedAccounts: {
231 + ...(current.connectedAccounts ?? {}),
232 + ...(next.connectedAccounts ?? {}),
233 + },
234 + availableConnectedAccounts: {
235 + ...(current.availableConnectedAccounts ?? {}),
236 + ...(next.availableConnectedAccounts ?? {}),
237 + },
238 + });
239 +};
240 +
241 export const getFreshConsumerConnectedToolkitsFromCache = (params: {
242 orgId: string;
243 consumerUserId: string;
@@ -232,6 +306,65 @@ export const getFreshConsumerToolRouterAuthConfigsFromCache = (params: {
306 return filtered ? Option.some(filtered) : Option.none<ConsumerToolRouterAuthConfigMappings>();
307 });
308
309 +export const getFreshConsumerToolRouterConnectedAccountsFromCache = (params: {
310 + orgId: string;
311 + consumerUserId: string;
312 + toolkits?: ReadonlyArray<string>;
313 +}) =>
314 + Effect.gen(function* () {
315 + const disabled = yield* APP_CONFIG.DISABLE_CONNECTED_ACCOUNT_CACHE;
316 + if (disabled) {
317 + return Option.none<ConsumerToolRouterConnectedAccountMappings>();
318 + }
319 + const state = yield* readCache();
320 + const entry = state[cacheKey(params.orgId, params.consumerUserId)];
321 + if (!entry) {
322 + return Option.none<ConsumerToolRouterConnectedAccountMappings>();
323 + }
324 + const expiresAtMs = Date.parse(entry.expiresAt);
325 + if (!Number.isFinite(expiresAtMs) || expiresAtMs <= Date.now()) {
326 + return Option.none<ConsumerToolRouterConnectedAccountMappings>();
327 + }
328 +
329 + const mappings = normalizeConnectedAccountMappings(entry.toolRouterConnectedAccounts);
330 + if (!mappings) {
331 + return Option.none<ConsumerToolRouterConnectedAccountMappings>();
332 + }
333 +
334 + if (!params.toolkits || params.toolkits.length === 0) {
335 + return Option.some(mappings);
336 + }
337 +
338 + const requestedToolkits = params.toolkits.map(toolkit => toolkit.toLowerCase());
339 + const filteredConnectedAccounts = requestedToolkits.reduce<Record<string, string>>(
340 + (acc, toolkit) => {
341 + const connectedAccountId = mappings.connectedAccounts?.[toolkit];
342 + if (typeof connectedAccountId === 'string') {
343 + acc[toolkit] = connectedAccountId;
344 + }
345 + return acc;
346 + },
347 + {}
348 + );
349 + const filteredAvailableConnectedAccounts = requestedToolkits.reduce<
350 + Record<string, ReadonlyArray<CachedConnectedAccountSummary>>
351 + >((acc, toolkit) => {
352 + const accounts = mappings.availableConnectedAccounts?.[toolkit];
353 + if (Array.isArray(accounts) && accounts.length > 0) {
354 + acc[toolkit] = accounts;
355 + }
356 + return acc;
357 + }, {});
358 + const filtered = normalizeConnectedAccountMappings({
359 + connectedAccounts: filteredConnectedAccounts,
360 + availableConnectedAccounts: filteredAvailableConnectedAccounts,
361 + });
362 +
363 + return filtered
364 + ? Option.some(filtered)
365 + : Option.none<ConsumerToolRouterConnectedAccountMappings>();
366 + });
367 +
368 export const invalidateConsumerConnectedToolkitsCache = () =>
369 Effect.gen(function* () {
370 const fs = yield* FileSystem.FileSystem;
@@ -350,6 +483,15 @@ export const refreshConsumerConnectedToolkitsCache = (params?: {
483 }
484 : undefined,
485 }),
486 + toolRouterConnectedAccounts: mergeConnectedAccountMappings({
487 + current: currentEntry?.toolRouterConnectedAccounts,
488 + next: Option.isSome(directToolkits)
489 + ? {
490 + connectedAccounts: directToolkits.value.connectedAccounts,
491 + availableConnectedAccounts: directToolkits.value.availableConnectedAccounts,
492 + }
493 + : undefined,
494 + }),
495 ...searchSessionFields,
496 },
497 });
@@ -360,6 +502,7 @@ export const writeConsumerConnectedToolkitsCache = (params: {
502 readonly consumerUserId: string;
503 readonly toolkits: ReadonlyArray<string>;
504 readonly toolRouterAuthConfigs?: ConsumerToolRouterAuthConfigMappings;
505 + readonly toolRouterConnectedAccounts?: ConsumerToolRouterConnectedAccountMappings;
506 }) =>
507 Effect.gen(function* () {
508 const disabled = yield* APP_CONFIG.DISABLE_CONNECTED_ACCOUNT_CACHE;
@@ -377,12 +520,19 @@ export const writeConsumerConnectedToolkitsCache = (params: {
520 yield* writeCache({
521 ...state,
522 [key]: {
380 - toolkits: normalizeCachedToolkits(params.toolkits, noAuthToolkits),
523 + toolkits: normalizeCachedToolkits(
524 + [...(currentEntry?.toolkits ?? []), ...params.toolkits],
525 + noAuthToolkits
526 + ),
527 expiresAt: new Date(Date.now() + CACHE_TTL_MS).toISOString(),
528 toolRouterAuthConfigs: mergeAuthConfigMappings({
529 current: currentEntry?.toolRouterAuthConfigs,
530 next: params.toolRouterAuthConfigs,
531 }),
532 + toolRouterConnectedAccounts: mergeConnectedAccountMappings({
533 + current: currentEntry?.toolRouterConnectedAccounts,
534 + next: params.toolRouterConnectedAccounts,
535 + }),
536 ...searchSessionFields,
537 },
538 });
@@ -429,6 +579,8 @@ export const getOrCreateProbablyMyCliSessionIdForCurrentCwd = (params?: {
579 [key]: {
580 toolkits: currentEntry?.toolkits ?? [],
581 expiresAt: currentEntry?.expiresAt ?? new Date(Date.now() + CACHE_TTL_MS).toISOString(),
582 + toolRouterAuthConfigs: currentEntry?.toolRouterAuthConfigs,
583 + toolRouterConnectedAccounts: currentEntry?.toolRouterConnectedAccounts,
584 ...searchSessionFields,
585 },
586 });
ts/packages/cli/src/services/run-helpers-runtime.ts
+10 -3
@@ -79,7 +79,7 @@ type RunGlobalScope = typeof globalThis & {
79 z: typeof z;
80 zod: typeof z;
81 search: (query: string, options?: Record<string, unknown>) => Promise<RunCliResult>;
82 - execute: (slug: string, data?: unknown) => Promise<RunCliResult>;
82 + execute: (slug: string, data?: unknown, options?: { account?: string }) => Promise<RunCliResult>;
83 experimental_subAgent: (prompt: string, options?: Record<string, unknown>) => Promise<unknown>;
84 invokeAgent: (prompt: string, options?: Record<string, unknown>) => Promise<unknown>;
85 proxy: (
@@ -754,13 +754,20 @@ export const installRunHelpers = async ({
754 return runCliJson(args);
755 };
756
757 - runGlobals.execute = async (slug, data = {}) => {
758 - helperDebugLog('execute.prepare', { slug, hasData: data !== undefined });
757 + runGlobals.execute = async (slug, data = {}, options = {}) => {
758 + helperDebugLog('execute.prepare', {
759 + slug,
760 + hasData: data !== undefined,
761 + account: options.account ?? null,
762 + });
763 const args = ['execute', slug];
764 if (helperContext.dryRun === true) args.push('--dry-run');
765 if (helperContext.skipConnectionCheck === true) args.push('--skip-connection-check');
766 if (helperContext.skipToolParamsCheck === true) args.push('--skip-tool-params-check');
767 if (helperContext.skipChecks === true) args.push('--skip-checks');
768 + if (typeof options.account === 'string' && options.account.trim().length > 0) {
769 + args.push('--account', options.account.trim());
770 + }
771 if (data !== undefined) {
772 const preparedData = await materializeExecutePayload(data);
773 const serialized =
ts/packages/cli/src/services/tool-router-session-connections.ts
+72 -1
@@ -1,8 +1,18 @@
1 import { Effect } from 'effect';
2 import type { Composio } from '@composio/client';
3 +import {
4 + groupCachedConnectedAccountsByToolkit,
5 + resolveDefaultConnectedAccountsByToolkit,
6 +} from 'src/services/connected-account-selection';
7 +import type { ConnectedAccountItem } from 'src/models/connected-accounts';
8
9 type RawConnectedAccount = {
10 readonly id: string;
11 + readonly alias?: string | null;
12 + readonly word_id?: string | null;
13 + readonly is_disabled?: boolean | null;
14 + readonly status?: string | null;
15 + readonly user_id?: string | null;
16 readonly toolkit?: {
17 readonly slug?: string | null;
18 } | null;
@@ -17,6 +27,17 @@ type RawConnectedAccount = {
27 export type ToolRouterSessionConnectionContext = {
28 readonly connectedToolkits: ReadonlyArray<string>;
29 readonly authConfigs?: Record<string, string>;
30 + readonly connectedAccounts?: Record<string, string>;
31 + readonly availableConnectedAccounts?: Record<
32 + string,
33 + ReadonlyArray<{
34 + readonly id: string;
35 + readonly alias: string | null;
36 + readonly wordId: string | null;
37 + readonly updatedAt: string;
38 + readonly createdAt: string;
39 + }>
40 + >;
41 };
42
43 const parseTimestamp = (value?: string | null): number => {
@@ -25,6 +46,22 @@ const parseTimestamp = (value?: string | null): number => {
46 return Number.isFinite(parsed) ? parsed : 0;
47 };
48
49 +const normalizeConnectedAccountStatus = (
50 + status?: string | null
51 +): ConnectedAccountItem['status'] => {
52 + switch (status) {
53 + case 'INITIALIZING':
54 + case 'INITIATED':
55 + case 'ACTIVE':
56 + case 'FAILED':
57 + case 'EXPIRED':
58 + case 'INACTIVE':
59 + return status;
60 + default:
61 + return 'INACTIVE';
62 + }
63 +};
64 +
65 const isNewerAccount = (candidate: RawConnectedAccount, current: RawConnectedAccount): boolean => {
66 const candidateTimestamp = Math.max(
67 parseTimestamp(candidate.updated_at),
@@ -55,12 +92,36 @@ export const resolveToolRouterSessionConnections = (
92 ).pipe(
93 Effect.map(response => {
94 const items = (response.items ?? []) as ReadonlyArray<RawConnectedAccount>;
95 + const normalizedItems: ConnectedAccountItem[] = items.map(
96 + item =>
97 + ({
98 + id: item.id,
99 + alias: item.alias ?? null,
100 + word_id: item.word_id ?? null,
101 + status: normalizeConnectedAccountStatus(item.status),
102 + status_reason: null,
103 + is_disabled: item.is_disabled ?? false,
104 + user_id: item.user_id ?? '',
105 + toolkit: {
106 + slug: item.toolkit?.slug ?? '',
107 + },
108 + auth_config: {
109 + id: item.auth_config?.id ?? '',
110 + auth_scheme: '',
111 + is_composio_managed: item.auth_config?.is_composio_managed ?? true,
112 + is_disabled: false,
113 + },
114 + created_at: item.created_at ?? '',
115 + updated_at: item.updated_at ?? '',
116 + test_request_endpoint: '',
117 + }) satisfies ConnectedAccountItem
118 + );
119 const connectedToolkits = new Set<string>();
120 const explicitAccountsByToolkit = new Map<string, RawConnectedAccount>();
121
122 for (const item of items) {
123 const toolkit = item.toolkit?.slug?.toLowerCase().trim();
63 - if (!toolkit) continue;
124 + if (!toolkit || item.is_disabled) continue;
125
126 connectedToolkits.add(toolkit);
127
@@ -87,12 +148,22 @@ export const resolveToolRouterSessionConnections = (
148 return {
149 connectedToolkits: [...connectedToolkits],
150 authConfigs: Object.keys(authConfigs).length > 0 ? authConfigs : undefined,
151 + connectedAccounts: (() => {
152 + const selected = resolveDefaultConnectedAccountsByToolkit(normalizedItems);
153 + return Object.keys(selected).length > 0 ? selected : undefined;
154 + })(),
155 + availableConnectedAccounts: (() => {
156 + const grouped = groupCachedConnectedAccountsByToolkit(normalizedItems);
157 + return Object.keys(grouped).length > 0 ? grouped : undefined;
158 + })(),
159 } satisfies ToolRouterSessionConnectionContext;
160 }),
161 Effect.catchAll(() =>
162 Effect.succeed({
163 connectedToolkits: [],
164 authConfigs: undefined,
165 + connectedAccounts: undefined,
166 + availableConnectedAccounts: undefined,
167 } satisfies ToolRouterSessionConnectionContext)
168 )
169 );
ts/packages/cli/src/services/tools-executor.ts
+2
@@ -26,6 +26,7 @@ export interface ToolExecuteParams {
26 readonly userId: string;
27 readonly arguments: Record<string, unknown>;
28 readonly client?: Composio;
29 + readonly connectedAccounts?: Record<string, string>;
30 readonly cacheScope?: {
31 readonly orgId: string;
32 readonly consumerUserId: string;
@@ -137,6 +138,7 @@ export const ToolsExecutorLive = Layer.effect(
138 // One session per invocation — CLI runs one tool per process.
139 const sessionId = yield* createToolRouterSession(resolvedClient, params.userId, {
140 manageConnections: true,
141 + connectedAccounts: params.connectedAccounts,
142 cacheScope: params.cacheScope,
143 });
144 const normalizedArguments = isMetaToolSlug(slug)
ts/packages/cli/test/__utils__/services/test-layer.ts
+23
@@ -106,6 +106,7 @@ export interface TestLiveInput {
106 connectedAccountsData?: {
107 items?: ConnectedAccountItem[];
108 linkResponse?: LinkCreateResponse;
109 + onPatch?: (params: { path: string; body: Record<string, unknown> | undefined }) => void;
110 };
111
112 /**
@@ -949,6 +950,28 @@ export const TestLayer = (input?: TestLiveInput) =>
950 return response;
951 },
952 },
953 + patch: async (path: string, options?: { body?: Record<string, unknown> }) => {
954 + connectedAccountsData.onPatch?.({ path, body: options?.body });
955 +
956 + const match = path.match(/^\/api\/v3\/connected_accounts\/([^/]+)$/);
957 + if (!match) {
958 + throw new Error(`Unhandled PATCH path "${path}"`);
959 + }
960 +
961 + const connectedAccountId = match[1];
962 + const account = connectedAccountsData.items.find(item => item.id === connectedAccountId);
963 + if (!account) {
964 + throw new Error(`Connected account "${connectedAccountId}" not found`);
965 + }
966 +
967 + if (typeof options?.body?.alias === 'string') {
968 + Object.assign(account as { alias?: string | null }, {
969 + alias: options.body.alias,
970 + });
971 + }
972 +
973 + return account;
974 + },
975 connectedAccounts: {
976 list: async (params?: {
977 toolkit_slugs?: string[];
ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts
+131 -27
@@ -17,29 +17,33 @@ const extractJsonObject = (output: string): Record<string, unknown> | null => {
17 return jsonMatch ? JSON.parse(jsonMatch[0]) : null;
18 };
19
20 -const testConnectedAccounts: ConnectedAccountItem[] = [
21 - {
22 - id: 'con_test_link',
23 - status: 'ACTIVE',
24 - status_reason: null,
20 +const makeConnectedAccount = (overrides?: Partial<ConnectedAccountItem>): ConnectedAccountItem => ({
21 + id: 'con_test_link',
22 + alias: 'default',
23 + word_id: 'castle',
24 + status: 'ACTIVE',
25 + status_reason: null,
26 + is_disabled: false,
27 + user_id: 'consumer-user-org_test',
28 + toolkit: { slug: 'gmail' },
29 + auth_config: {
30 + id: 'ac_gmail_oauth',
31 + auth_scheme: 'OAUTH2',
32 + is_composio_managed: true,
33 is_disabled: false,
26 - user_id: 'default',
27 - toolkit: { slug: 'gmail' },
28 - auth_config: {
29 - id: 'ac_gmail_oauth',
30 - auth_scheme: 'OAUTH2',
31 - is_composio_managed: true,
32 - is_disabled: false,
33 - },
34 - created_at: '2026-01-01T00:00:00Z',
35 - updated_at: '2026-01-15T00:00:00Z',
36 - test_request_endpoint: '',
34 },
38 -];
35 + created_at: '2026-01-01T00:00:00Z',
36 + updated_at: '2026-01-15T00:00:00Z',
37 + test_request_endpoint: '',
38 + ...overrides,
39 +});
40
40 -const connectedAccountsData = {
41 - items: testConnectedAccounts,
42 -} satisfies TestLiveInput['connectedAccountsData'];
41 +const makeConnectedAccountsData = (
42 + overrides?: Partial<NonNullable<TestLiveInput['connectedAccountsData']>>
43 +): NonNullable<TestLiveInput['connectedAccountsData']> => ({
44 + items: [makeConnectedAccount()],
45 + ...overrides,
46 +});
47
48 const testConfigProvider = ConfigProvider.fromMap(
49 new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
@@ -76,6 +80,8 @@ const RecordingTerminalUI = TerminalUI.of({
80 });
81
82 describe('CLI: composio dev connected-accounts link', () => {
83 + const aliasPatchSpy = vi.fn();
84 +
85 afterEach(() => {
86 vi.clearAllMocks();
87 });
@@ -83,7 +89,7 @@ describe('CLI: composio dev connected-accounts link', () => {
89 layer(
90 TestLive({
91 baseConfigProvider: testConfigProvider,
86 - connectedAccountsData,
92 + connectedAccountsData: makeConnectedAccountsData(),
93 fixture: 'global-test-user-id',
94 })
95 )('[Given] valid toolkit link [Then] creates link and waits (default)', it => {
@@ -105,7 +111,51 @@ describe('CLI: composio dev connected-accounts link', () => {
111 layer(
112 TestLive({
113 baseConfigProvider: testConfigProvider,
108 - connectedAccountsData,
114 + connectedAccountsData: makeConnectedAccountsData(),
115 + fixture: 'global-test-user-id',
116 + })
117 + )('[Given] --list [Then] it shows existing accounts without opening a new link', it => {
118 + it.scoped('lists alias and word_id for existing accounts', () =>
119 + Effect.gen(function* () {
120 + yield* cli(['link', 'gmail', '--list']);
121 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
122 + const output = lines.join('\n');
123 +
124 + expect(output).toContain('default');
125 + expect(output).toContain('castle');
126 + expect(output).toContain('"toolkit": "gmail"');
127 + expect(vi.mocked(open)).not.toHaveBeenCalled();
128 + })
129 + );
130 + });
131 +
132 + layer(
133 + TestLive({
134 + baseConfigProvider: testConfigProvider,
135 + connectedAccountsData: makeConnectedAccountsData(),
136 + fixture: 'global-test-user-id',
137 + })
138 + )(
139 + '[Given] dev connected-accounts link --list without developer project context [Then] it still uses consumer resolution',
140 + it => {
141 + it.scoped('lists connected accounts instead of requiring a developer project', () =>
142 + Effect.gen(function* () {
143 + yield* cli(['dev', 'connected-accounts', 'link', 'gmail', '--list']);
144 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
145 + const output = lines.join('\n');
146 +
147 + expect(output).toContain('default');
148 + expect(output).toContain('castle');
149 + expect(output).not.toContain('MissingDeveloperProjectError');
150 + })
151 + );
152 + }
153 + );
154 +
155 + layer(
156 + TestLive({
157 + baseConfigProvider: testConfigProvider,
158 + connectedAccountsData: makeConnectedAccountsData(),
159 fixture: 'global-test-user-id',
160 terminalUI: RecordingTerminalUI,
161 })
@@ -134,7 +184,7 @@ describe('CLI: composio dev connected-accounts link', () => {
184 layer(
185 TestLive({
186 baseConfigProvider: testConfigProvider,
137 - connectedAccountsData,
187 + connectedAccountsData: makeConnectedAccountsData(),
188 fixture: 'global-test-user-id',
189 terminalUI: RecordingTerminalUI,
190 })
@@ -174,7 +224,7 @@ describe('CLI: composio dev connected-accounts link', () => {
224 layer(
225 TestLive({
226 baseConfigProvider: testConfigProvider,
177 - connectedAccountsData,
227 + connectedAccountsData: makeConnectedAccountsData(),
228 fixture: 'global-test-user-id',
229 })
230 )('[Given] composio link [Then] works for consumer toolkit linking', it => {
@@ -194,7 +244,7 @@ describe('CLI: composio dev connected-accounts link', () => {
244 layer(
245 TestLive({
246 baseConfigProvider: testConfigProvider,
197 - connectedAccountsData,
247 + connectedAccountsData: makeConnectedAccountsData(),
248 fixture: 'global-test-user-id',
249 })
250 )('[Given] --no-wait [Then] outputs valid JSON parseable by jq', it => {
@@ -215,7 +265,7 @@ describe('CLI: composio dev connected-accounts link', () => {
265 layer(
266 TestLive({
267 baseConfigProvider: testConfigProvider,
218 - connectedAccountsData,
268 + connectedAccountsData: makeConnectedAccountsData(),
269 fixture: 'global-test-user-id',
270 toolRouter: {
271 link: async () => ({
@@ -244,7 +294,7 @@ describe('CLI: composio dev connected-accounts link', () => {
294 layer(
295 TestLive({
296 baseConfigProvider: testConfigProvider,
247 - connectedAccountsData,
297 + connectedAccountsData: makeConnectedAccountsData(),
298 fixture: 'global-test-user-id',
299 })
300 )('[Given] default (wait) [Then] waits for ACTIVE and outputs success JSON for jq', it => {
@@ -263,4 +313,58 @@ describe('CLI: composio dev connected-accounts link', () => {
313 })
314 );
315 });
316 +
317 + layer(
318 + TestLive({
319 + baseConfigProvider: testConfigProvider,
320 + connectedAccountsData: makeConnectedAccountsData({
321 + items: [makeConnectedAccount({ status: 'INITIATED' })],
322 + onPatch: params => {
323 + aliasPatchSpy(params);
324 + },
325 + }),
326 + fixture: 'global-test-user-id',
327 + })
328 + )('[Given] --alias [Then] it patches the created connected account alias', it => {
329 + it.scoped('updates the connected account alias through the patch API', () =>
330 + Effect.gen(function* () {
331 + yield* cli(['link', 'gmail', '--alias', 'work', '--no-wait']);
332 +
333 + expect(aliasPatchSpy).toHaveBeenCalledWith({
334 + path: '/api/v3/connected_accounts/con_test_link',
335 + body: { alias: 'work' },
336 + });
337 + })
338 + );
339 + });
340 +
341 + layer(
342 + TestLive({
343 + baseConfigProvider: testConfigProvider,
344 + connectedAccountsData: makeConnectedAccountsData(),
345 + toolRouter: {
346 + link: async () => ({
347 + connected_account_id: 'con_second_link',
348 + link_token: 'lt_test_token',
349 + redirect_url: 'https://app.composio.dev/link?token=lt_test_token',
350 + }),
351 + },
352 + fixture: 'global-test-user-id',
353 + })
354 + )(
355 + '[Given] an existing active account and no --alias [Then] link blocks the second connected account',
356 + it => {
357 + it.scoped('fails locally and tells the user to pass --alias', () =>
358 + Effect.gen(function* () {
359 + yield* cli(['link', 'gmail']);
360 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
361 + const output = lines.join('\n');
362 +
363 + expect(output).toContain('Pass --alias to create another one');
364 + expect(output).toContain('con_test_link');
365 + expect(output).not.toContain('"status": "success"');
366 + })
367 + );
368 + }
369 + );
370 });
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+212 -1
@@ -93,6 +93,215 @@ describe('CLI: composio execute', () => {
93 );
94 });
95
96 + layer(
97 + TestLive({
98 + baseConfigProvider: testConfigProvider,
99 + fixture: 'global-test-user-id',
100 + stdin: { isTTY: true, data: '' },
101 + toolsExecutor: {
102 + respondWith: {
103 + data: {
104 + content: 'token '.repeat(20_000),
105 + },
106 + error: null,
107 + successful: true,
108 + logId: 'log_large_output',
109 + },
110 + },
111 + })
112 + )(
113 + '[Given] a large execution response during composio run [Then] it stays inline instead of storing a temp file',
114 + it => {
115 + it.scoped('returns the full JSON payload when invocation origin is run', () =>
116 + Effect.gen(function* () {
117 + vi.stubEnv('COMPOSIO_CLI_INVOCATION_ORIGIN', 'run');
118 +
119 + yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient":"a"}']);
120 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
121 + const output = parseLastJson(lines) as unknown as {
122 + successful: boolean;
123 + storedInFile?: boolean;
124 + outputFilePath?: string;
125 + data: {
126 + content: string;
127 + };
128 + };
129 +
130 + expect(output.successful).toBe(true);
131 + expect(output.storedInFile).not.toBe(true);
132 + expect(output.outputFilePath).toBeUndefined();
133 + expect(output.data.content).toContain('token token token');
134 + })
135 + );
136 + }
137 + );
138 +
139 + layer(
140 + TestLive({
141 + baseConfigProvider: testConfigProvider,
142 + fixture: 'global-test-user-id',
143 + stdin: { isTTY: true, data: '' },
144 + connectedAccountsData: {
145 + items: [
146 + {
147 + id: 'con_gmail_default',
148 + alias: 'default',
149 + word_id: 'castle',
150 + status: 'ACTIVE',
151 + status_reason: null,
152 + is_disabled: false,
153 + user_id: 'consumer-user-org_test',
154 + toolkit: { slug: 'gmail' },
155 + auth_config: {
156 + id: 'ac_gmail_oauth',
157 + auth_scheme: 'OAUTH2',
158 + is_composio_managed: true,
159 + is_disabled: false,
160 + },
161 + created_at: '2026-01-01T00:00:00.000Z',
162 + updated_at: '2026-01-01T00:00:00.000Z',
163 + test_request_endpoint: '',
164 + },
165 + {
166 + id: 'con_gmail_secondary',
167 + alias: 'work',
168 + word_id: 'forest',
169 + status: 'ACTIVE',
170 + status_reason: null,
171 + is_disabled: false,
172 + user_id: 'consumer-user-org_test',
173 + toolkit: { slug: 'gmail' },
174 + auth_config: {
175 + id: 'ac_gmail_oauth',
176 + auth_scheme: 'OAUTH2',
177 + is_composio_managed: true,
178 + is_disabled: false,
179 + },
180 + created_at: '2026-01-02T00:00:00.000Z',
181 + updated_at: '2026-01-02T00:00:00.000Z',
182 + test_request_endpoint: '',
183 + },
184 + ],
185 + },
186 + toolRouter: {
187 + create: async params => {
188 + recordedSessionCreateParams.push(params as unknown as Record<string, unknown>);
189 + return {
190 + session_id: 'trs_gmail_default_session',
191 + config: { user_id: params.user_id },
192 + mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
193 + tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MANAGE_CONNECTIONS'],
194 + };
195 + },
196 + execute: async (_sessionId, params) => ({
197 + data: { tool_slug: params.tool_slug, arguments: params.arguments },
198 + error: null,
199 + log_id: 'log_gmail_default',
200 + }),
201 + },
202 + })
203 + )('[Given] default alias exists [Then] execute pins the default connected account', it => {
204 + it.scoped('passes connected_accounts with the default alias account', () =>
205 + Effect.gen(function* () {
206 + yield* cli([
207 + 'execute',
208 + 'GMAIL_SEND_EMAIL',
209 + '--skip-connection-check',
210 + '-d',
211 + '{"recipient":"a"}',
212 + ]);
213 +
214 + expect(recordedSessionCreateParams[0]?.connected_accounts).toEqual({
215 + gmail: 'con_gmail_default',
216 + });
217 + })
218 + );
219 + });
220 +
221 + layer(
222 + TestLive({
223 + baseConfigProvider: testConfigProvider,
224 + fixture: 'global-test-user-id',
225 + stdin: { isTTY: true, data: '' },
226 + connectedAccountsData: {
227 + items: [
228 + {
229 + id: 'con_gmail_default',
230 + alias: 'default',
231 + word_id: 'castle',
232 + status: 'ACTIVE',
233 + status_reason: null,
234 + is_disabled: false,
235 + user_id: 'consumer-user-org_test',
236 + toolkit: { slug: 'gmail' },
237 + auth_config: {
238 + id: 'ac_gmail_oauth',
239 + auth_scheme: 'OAUTH2',
240 + is_composio_managed: true,
241 + is_disabled: false,
242 + },
243 + created_at: '2026-01-01T00:00:00.000Z',
244 + updated_at: '2026-01-01T00:00:00.000Z',
245 + test_request_endpoint: '',
246 + },
247 + {
248 + id: 'con_gmail_secondary',
249 + alias: 'work',
250 + word_id: 'forest',
251 + status: 'ACTIVE',
252 + status_reason: null,
253 + is_disabled: false,
254 + user_id: 'consumer-user-org_test',
255 + toolkit: { slug: 'gmail' },
256 + auth_config: {
257 + id: 'ac_gmail_oauth',
258 + auth_scheme: 'OAUTH2',
259 + is_composio_managed: true,
260 + is_disabled: false,
261 + },
262 + created_at: '2026-01-02T00:00:00.000Z',
263 + updated_at: '2026-01-02T00:00:00.000Z',
264 + test_request_endpoint: '',
265 + },
266 + ],
267 + },
268 + toolRouter: {
269 + create: async params => {
270 + recordedSessionCreateParams.push(params as unknown as Record<string, unknown>);
271 + return {
272 + session_id: 'trs_gmail_explicit_session',
273 + config: { user_id: params.user_id },
274 + mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
275 + tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MANAGE_CONNECTIONS'],
276 + };
277 + },
278 + execute: async (_sessionId, params) => ({
279 + data: { tool_slug: params.tool_slug, arguments: params.arguments },
280 + error: null,
281 + log_id: 'log_gmail_explicit',
282 + }),
283 + },
284 + })
285 + )('[Given] --account selector [Then] execute pins the matched connected account', it => {
286 + it.scoped('matches by alias, word_id, or id', () =>
287 + Effect.gen(function* () {
288 + yield* cli([
289 + 'execute',
290 + 'GMAIL_SEND_EMAIL',
291 + '--account',
292 + 'forest',
293 + '--skip-connection-check',
294 + '-d',
295 + '{"recipient":"a"}',
296 + ]);
297 +
298 + expect(recordedSessionCreateParams[0]?.connected_accounts).toEqual({
299 + gmail: 'con_gmail_secondary',
300 + });
301 + })
302 + );
303 + });
304 +
305 layer(
306 TestLive({
307 baseConfigProvider: testConfigProvider,
@@ -157,7 +366,9 @@ describe('CLI: composio execute', () => {
366 expect(recordedSessionCreateParams[0]?.auth_configs).toEqual({
367 posthog: 'ac_posthog_custom',
368 });
160 - expect(recordedSessionCreateParams[0]?.connected_accounts).toBeUndefined();
369 + expect(recordedSessionCreateParams[0]?.connected_accounts).toEqual({
370 + posthog: 'con_posthog_active',
371 + });
372 })
373 );
374 }
ts/packages/cli/test/src/services/connected-account-selection.test.ts new
+96
@@ -0,0 +1,96 @@
1 +import { describe, expect, it } from 'vitest';
2 +import {
3 + formatConnectedAccountChoices,
4 + groupCachedConnectedAccountsByToolkit,
5 + resolveConnectedAccountSelection,
6 + resolveDefaultConnectedAccountsByToolkit,
7 +} from 'src/services/connected-account-selection';
8 +import type { ConnectedAccountItem } from 'src/models/connected-accounts';
9 +
10 +const makeAccount = (overrides: Partial<ConnectedAccountItem>): ConnectedAccountItem => ({
11 + id: 'con_default',
12 + alias: null,
13 + word_id: null,
14 + status: 'ACTIVE',
15 + status_reason: null,
16 + is_disabled: false,
17 + user_id: 'default',
18 + toolkit: { slug: 'gmail' },
19 + auth_config: {
20 + id: 'ac_gmail',
21 + auth_scheme: 'OAUTH2',
22 + is_composio_managed: true,
23 + is_disabled: false,
24 + },
25 + created_at: '2026-01-01T00:00:00.000Z',
26 + updated_at: '2026-01-01T00:00:00.000Z',
27 + test_request_endpoint: '',
28 + ...overrides,
29 +});
30 +
31 +describe('connected-account-selection', () => {
32 + it('prefers alias=default when no selector is provided', () => {
33 + const selected = resolveConnectedAccountSelection([
34 + makeAccount({
35 + id: 'con_newer',
36 + updated_at: '2026-01-03T00:00:00.000Z',
37 + }),
38 + makeAccount({
39 + id: 'con_default_alias',
40 + alias: 'default',
41 + updated_at: '2026-01-02T00:00:00.000Z',
42 + }),
43 + ]);
44 +
45 + expect(selected?.id).toBe('con_default_alias');
46 + });
47 +
48 + it('matches explicit selectors by alias, word_id, and id', () => {
49 + const items = [
50 + makeAccount({ id: 'con_alpha', alias: 'work', word_id: 'castle' }),
51 + makeAccount({ id: 'con_beta', alias: 'default', word_id: 'forest' }),
52 + ];
53 +
54 + expect(resolveConnectedAccountSelection(items, 'work')?.id).toBe('con_alpha');
55 + expect(resolveConnectedAccountSelection(items, 'castle')?.id).toBe('con_alpha');
56 + expect(resolveConnectedAccountSelection(items, 'con_beta')?.id).toBe('con_beta');
57 + });
58 +
59 + it('builds default account mappings and grouped cache payloads', () => {
60 + const items = [
61 + makeAccount({ id: 'con_default_gmail', alias: 'default' }),
62 + makeAccount({
63 + id: 'con_alt_gmail',
64 + alias: 'secondary',
65 + word_id: 'castle',
66 + updated_at: '2026-01-02T00:00:00.000Z',
67 + }),
68 + makeAccount({
69 + id: 'con_default_slack',
70 + alias: 'default',
71 + toolkit: { slug: 'slack' },
72 + }),
73 + ];
74 +
75 + expect(resolveDefaultConnectedAccountsByToolkit(items)).toEqual({
76 + gmail: 'con_default_gmail',
77 + slack: 'con_default_slack',
78 + });
79 +
80 + expect(groupCachedConnectedAccountsByToolkit(items)).toMatchObject({
81 + gmail: [
82 + expect.objectContaining({ id: 'con_alt_gmail', alias: 'secondary', wordId: 'castle' }),
83 + expect.objectContaining({ id: 'con_default_gmail', alias: 'default', wordId: null }),
84 + ],
85 + slack: [expect.objectContaining({ id: 'con_default_slack', alias: 'default', wordId: null })],
86 + });
87 + });
88 +
89 + it('formats available account choices for CLI error messages', () => {
90 + expect(
91 + formatConnectedAccountChoices([
92 + makeAccount({ id: 'con_default', alias: 'default', word_id: 'castle' }),
93 + ])
94 + ).toEqual(['default / castle (con_default)']);
95 + });
96 +});
ts/packages/cli/test/src/services/consumer-short-term-cache.test.ts
+57
@@ -6,6 +6,7 @@ import * as composioClients from 'src/services/composio-clients';
6 import {
7 getFreshConsumerConnectedToolkitsFromCache,
8 getFreshConsumerToolRouterAuthConfigsFromCache,
9 + getFreshConsumerToolRouterConnectedAccountsFromCache,
10 refreshConsumerConnectedToolkitsCache,
11 writeConsumerConnectedToolkitsCache,
12 } from 'src/services/consumer-short-term-cache';
@@ -240,4 +241,60 @@ describe('consumer short-term cache', () => {
241 );
242 }
243 );
244 +
245 + layer(TestLive({ baseConfigProvider: cacheEnabledTestConfigProvider }))(
246 + '[Given] cached connected account metadata [Then] default mappings and summaries are readable',
247 + it => {
248 + it.scoped('returns cached connected account selectors by toolkit', () =>
249 + Effect.gen(function* () {
250 + yield* writeConsumerConnectedToolkitsCache({
251 + orgId: 'org_test',
252 + consumerUserId: 'consumer-user-test',
253 + toolkits: ['gmail'],
254 + toolRouterConnectedAccounts: {
255 + connectedAccounts: {
256 + gmail: 'con_default',
257 + },
258 + availableConnectedAccounts: {
259 + gmail: [
260 + {
261 + id: 'con_default',
262 + alias: 'default',
263 + wordId: 'castle',
264 + updatedAt: '2026-01-02T00:00:00.000Z',
265 + createdAt: '2026-01-01T00:00:00.000Z',
266 + },
267 + ],
268 + },
269 + },
270 + });
271 +
272 + const cached = yield* getFreshConsumerToolRouterConnectedAccountsFromCache({
273 + orgId: 'org_test',
274 + consumerUserId: 'consumer-user-test',
275 + toolkits: ['gmail'],
276 + });
277 +
278 + expect(cached).toEqual(
279 + Option.some({
280 + connectedAccounts: {
281 + gmail: 'con_default',
282 + },
283 + availableConnectedAccounts: {
284 + gmail: [
285 + {
286 + id: 'con_default',
287 + alias: 'default',
288 + wordId: 'castle',
289 + updatedAt: '2026-01-02T00:00:00.000Z',
290 + createdAt: '2026-01-01T00:00:00.000Z',
291 + },
292 + ],
293 + },
294 + })
295 + );
296 + })
297 + );
298 + }
299 + );
300 });
ts/packages/core/src/types/connectedAccounts.types.ts
+4
@@ -88,6 +88,8 @@ export type ConnectedAccountAuthConfig = z.infer<typeof ConnectedAccountAuthConf
88 export const ConnectedAccountRetrieveResponseSchema: z.ZodType<{
89 id: string;
90 authConfig: z.infer<typeof ConnectedAccountAuthConfigSchema>;
91 + wordId?: string | null;
92 + alias?: string | null;
93 /** @deprecated use connectedAccount.state instead */
94 data?: Record<string, unknown>;
95 /** @deprecated use connectedAccount.state instead */
@@ -103,6 +105,8 @@ export const ConnectedAccountRetrieveResponseSchema: z.ZodType<{
105 }> = z.object({
106 id: z.string(),
107 authConfig: ConnectedAccountAuthConfigSchema,
108 + wordId: z.string().nullable().optional(),
109 + alias: z.string().nullable().optional(),
110 /**
111 * @deprecated use connectedAccount.state instead
112 */
ts/packages/core/src/utils/transformers/connectedAccounts.ts
+12 -1
@@ -9,10 +9,17 @@ import {
9 ConnectedAccountRetrieveResponseSchema,
10 } from '../../types/connectedAccounts.types';
11 import { ConnectionDataSchema } from '../../types/connectedAccountAuthStates.types';
12 -import { ValidationError } from '../../errors';
12 import logger from '../logger';
13 import { transform } from '../transform';
14
15 +type RawConnectedAccountResponseWithLabels = (
16 + | RawConnectedAccountRetrieveResponse
17 + | RawConnectedAccountListResponse['items'][0]
18 +) & {
19 + word_id?: string | null;
20 + alias?: string | null;
21 +};
22 +
23 /**
24 * Transforms the raw connected account response from the Composio API to the SDK format.
25 *
@@ -28,6 +35,8 @@ import { transform } from '../transform';
35 export function transformConnectedAccountResponse(
36 response: RawConnectedAccountRetrieveResponse | RawConnectedAccountListResponse['items'][0]
37 ): ConnectedAccountRetrieveResponse {
38 + const responseWithLabels = response as RawConnectedAccountResponseWithLabels;
39 +
40 // Safely parse the state field, filtering out unsupported auth schemes
41 const parseState = (state: unknown) => {
42 try {
@@ -51,6 +60,8 @@ export function transformConnectedAccountResponse(
60 isComposioManaged: response.auth_config.is_composio_managed,
61 isDisabled: response.auth_config.is_disabled,
62 },
63 + wordId: responseWithLabels.word_id ?? null,
64 + alias: responseWithLabels.alias ?? null,
65 data: (response as unknown as ConnectedAccountRetrieveResponse).data ?? undefined,
66 state: parseState(response.state),
67 status: response.status,
ts/packages/core/test/connectedAccounts/connectedAccounts.test.ts
+36
@@ -479,6 +479,8 @@ describe('ConnectedAccounts', () => {
479 isComposioManaged: true,
480 isDisabled: false,
481 },
482 + wordId: null,
483 + alias: null,
484 state: {
485 authScheme: AuthSchemeTypes.OAUTH2,
486 val: {
@@ -499,6 +501,35 @@ describe('ConnectedAccounts', () => {
501 testRequestEndpoint: undefined,
502 });
503 });
504 +
505 + it('should preserve alias and wordId when the API returns them', async () => {
506 + const nanoid = 'conn_456';
507 + const mockResponse = {
508 + id: nanoid,
509 + status: 'ACTIVE',
510 + word_id: 'castle',
511 + alias: 'Work Gmail',
512 + auth_config: {
513 + id: 'test-auth-config',
514 + is_composio_managed: true,
515 + is_disabled: false,
516 + },
517 + is_disabled: false,
518 + created_at: '2023-01-01T00:00:00Z',
519 + updated_at: '2023-01-01T00:00:00Z',
520 + status_reason: null,
521 + toolkit: {
522 + slug: 'gmail',
523 + },
524 + };
525 +
526 + extendedMockClient.connectedAccounts.retrieve.mockResolvedValueOnce(mockResponse);
527 +
528 + const result = await connectedAccounts.get(nanoid);
529 +
530 + expect(result.wordId).toBe('castle');
531 + expect(result.alias).toBe('Work Gmail');
532 + });
533 });
534
535 describe('delete', () => {
@@ -713,6 +744,7 @@ describe('ConnectedAccounts', () => {
744 expect(result).toEqual({
745 id: nanoid,
746 status: ConnectedAccountStatuses.ACTIVE,
747 + alias: null,
748 authConfig: {
749 id: 'auth_config_123',
750 authScheme: AuthSchemeTypes.OAUTH2,
@@ -737,6 +769,7 @@ describe('ConnectedAccounts', () => {
769 slug: 'test-toolkit',
770 },
771 testRequestEndpoint: undefined,
772 + wordId: null,
773 });
774 });
775
@@ -808,8 +841,10 @@ describe('ConnectedAccounts', () => {
841 expect(result).toEqual({
842 id: nanoid,
843 status: ConnectedAccountStatuses.ACTIVE,
844 + alias: null,
845 authConfig: {
846 id: 'auth_config_123',
847 + authScheme: undefined,
848 isComposioManaged: true,
849 isDisabled: false,
850 },
@@ -831,6 +866,7 @@ describe('ConnectedAccounts', () => {
866 slug: 'test-toolkit',
867 },
868 testRequestEndpoint: undefined,
869 + wordId: null,
870 });
871 });
872 });