@devries-cameron20 / composio Mirror · read-only / commits / 066104d8d
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, 07:00 UTC

refactor(cli): migrate commands to Tool Router session API

Replace standard Composio API endpoints with Tool Router session-based execution for tools execute, toolkits list/info, and connected-accounts link. This eliminates the need for users to manually configure auth-configs before executing tools. - Add createToolRouterSession helper for ephemeral sessions - Rewrite ToolsExecutor to use session.execute/executeMeta - Add dual code path in connected-accounts link (--auth-config legacy vs <toolkit> Tool Router) - Migrate toolkits list/info to session.toolkits() with connection status - Remove --connected-account-id and --toolkit-version flags - Handle ToolRouterV2_NoActiveConnection error with actionable tips - Make test Tool Router mocks configurable via TestLiveInput.toolRouter - Flow tools execute tests through real ToolsExecutorLive

jkomyno committed Feb 24, 2026 at 20:26 UTC 066104d8da1cdac4621b603564b17a00b8d76644
16 files changed +818 -437
ts/packages/cli/src/bin.ts
+8 -1
@@ -10,6 +10,7 @@ import * as constants from 'src/constants';
10 import { ComposioCliConfig } from 'src/cli-config';
11 import { BaseConfigProviderLive, ConfigLive, extendConfigProvider } from 'src/services/config';
12 import {
13 + ComposioClientSingleton,
14 ComposioSessionRepository,
15 ComposioToolkitsRepository,
16 } from 'src/services/composio-clients';
@@ -73,9 +74,14 @@ export const TriggersRealtimeLive = Layer.provide(
74 Layer.mergeAll(BunFileSystem.layer, NodeOs.Default)
75 ) satisfies RequiredLayer;
76
77 +export const ComposioClientSingletonLive = Layer.provide(
78 + ComposioClientSingleton.Default,
79 + Layer.mergeAll(BunFileSystem.layer, NodeOs.Default, ConfigLive)
80 +) satisfies RequiredLayer;
81 +
82 export const ToolsExecutorLive = Layer.provide(
83 _ToolsExecutorLive,
78 - ComposioUserContextLive
84 + ComposioClientSingletonLive
85 ) satisfies RequiredLayer;
86
87 const layers = Layer.mergeAll(
@@ -85,6 +91,7 @@ const layers = Layer.mergeAll(
91 UpgradeBinaryLive,
92 ComposioUserContextLive,
93 ComposioSessionRepositoryLive,
94 + ComposioClientSingletonLive, // Expose ComposioClientSingleton for commands that use Tool Router directly
95 ComposioToolkitsRepositoryCachedLive, // Use the cached layer instead of the regular one
96 ToolsExecutorLive,
97 EnvLangDetector.Default,
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts
+168 -71
@@ -1,13 +1,20 @@
1 -import { Command, Options } from '@effect/cli';
1 +import { Args, Command, Options } from '@effect/cli';
2 import { Effect, Option, Schedule } from 'effect';
3 import open from 'open';
4 -import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 +import { ComposioClientSingleton, ComposioToolkitsRepository } from 'src/services/composio-clients';
5 import { TerminalUI } from 'src/services/terminal-ui';
6 import { requireAuth } from 'src/effects/require-auth';
7 import { handleHttpServerError } from 'src/effects/handle-http-error';
8 +import { createToolRouterSession } from 'src/effects/create-tool-router-session';
9 +
10 +const toolkit = Args.text({ name: 'toolkit' }).pipe(
11 + Args.withDescription('Toolkit slug to link (e.g. "github", "gmail")'),
12 + Args.optional
13 +);
14
15 const authConfig = Options.text('auth-config').pipe(
10 - Options.withDescription('Auth config ID (e.g. "ac_...")')
16 + Options.withDescription('Auth config ID (e.g. "ac_..."). Uses legacy flow (no Tool Router).'),
17 + Options.optional
18 );
19
20 const userId = Options.text('user-id').pipe(
@@ -21,100 +28,190 @@ const noBrowser = Options.boolean('no-browser').pipe(
28 );
29
30 /**
24 - * Link an external account by creating an OAuth redirect session.
31 + * Open the browser and poll until the connected account becomes ACTIVE.
32 + */
33 +const waitForActiveConnection = (
34 + ui: TerminalUI,
35 + repo: ComposioToolkitsRepository,
36 + connectedAccountId: string,
37 + redirectUrl: string,
38 + noBrowser: boolean
39 +) =>
40 + Effect.gen(function* () {
41 + // Display the redirect URL
42 + yield* ui.note(redirectUrl, 'Redirect URL');
43 + yield* ui.output(redirectUrl);
44 +
45 + if (!noBrowser) {
46 + yield* Effect.tryPromise(() => open(redirectUrl, { wait: false })).pipe(
47 + Effect.catchAll(error =>
48 + Effect.gen(function* () {
49 + yield* Effect.logDebug('Failed to open browser:', error);
50 + yield* ui.log.warn('Could not open the browser automatically.');
51 + yield* ui.log.info('Tip: try using `--no-browser` and open the URL manually.');
52 + })
53 + )
54 + );
55 + }
56 +
57 + // Poll until the connected account becomes ACTIVE
58 + yield* ui.useMakeSpinner('Waiting for authentication...', spinner =>
59 + Effect.retry(
60 + Effect.gen(function* () {
61 + const account = yield* repo.getConnectedAccount(connectedAccountId);
62 +
63 + if (account.status === 'ACTIVE') {
64 + return account;
65 + }
66 +
67 + return yield* Effect.fail(
68 + new Error(`Connection status is still '${account.status}', waiting for 'ACTIVE'`)
69 + );
70 + }),
71 + // Exponential backoff: start with 0.3s, max 5s, up to 15 retries
72 + Schedule.exponential('0.3 seconds').pipe(
73 + Schedule.intersect(Schedule.recurs(15)),
74 + Schedule.intersect(Schedule.spaced('5 seconds'))
75 + )
76 + ).pipe(
77 + Effect.tap(account => {
78 + return Effect.all([
79 + spinner.stop('Connection successful'),
80 + ui.log.success(
81 + `Connected account "${account.id}" is now ACTIVE (toolkit: ${account.toolkit.slug}).`
82 + ),
83 + ]);
84 + }),
85 + Effect.tapError(() => spinner.error('Connection timed out. Please try again.'))
86 + )
87 + );
88 + });
89 +
90 +/**
91 + * Link an external account via OAuth redirect.
92 *
26 - * Opens the browser to the redirect URL and polls until the connection
27 - * becomes ACTIVE.
93 + * Two modes:
94 + * - **Tool Router** (default): `composio connected-accounts link <toolkit>`
95 + * - **Legacy**: `composio connected-accounts link --auth-config <id>`
96 *
97 * @example
98 * ```bash
99 + * composio connected-accounts link github
100 + * composio connected-accounts link gmail --user-id "alice"
101 * composio connected-accounts link --auth-config "ac_..." --user-id "default"
32 - * composio connected-accounts link --auth-config "ac_..." --no-browser
102 * ```
103 */
104 export const connectedAccountsCmd$Link = Command.make(
105 'link',
37 - { authConfig, userId, noBrowser },
38 - ({ authConfig, userId, noBrowser }) =>
106 + { toolkit, authConfig, userId, noBrowser },
107 + ({ toolkit, authConfig, userId, noBrowser }) =>
108 Effect.gen(function* () {
109 if (!(yield* requireAuth)) return;
110
111 const ui = yield* TerminalUI;
112 const repo = yield* ComposioToolkitsRepository;
113
45 - // Create the link session
46 - const linkOpt = yield* ui
47 - .withSpinner(
48 - 'Creating link session...',
49 - repo.createConnectedAccountLink({
50 - auth_config_id: authConfig,
51 - user_id: userId,
52 - })
53 - )
54 - .pipe(
55 - Effect.asSome,
56 - Effect.catchTag(
57 - 'services/HttpServerError',
58 - handleHttpServerError(ui, {
59 - fallbackMessage: `Failed to create link for auth config "${authConfig}".`,
60 - hint: 'Browse available auth configs:\n> composio auth-configs list',
61 - fallbackValue: Option.none(),
62 - })
63 - )
114 + // Validate: exactly one of <toolkit> or --auth-config must be provided
115 + if (Option.isSome(toolkit) && Option.isSome(authConfig)) {
116 + yield* ui.log.error(
117 + 'Cannot use both <toolkit> and --auth-config. Choose one:\n' +
118 + ' Tool Router: composio connected-accounts link <toolkit>\n' +
119 + ' Legacy: composio connected-accounts link --auth-config <id>'
120 );
121 + return;
122 + }
123
66 - if (Option.isNone(linkOpt)) {
124 + if (Option.isNone(toolkit) && Option.isNone(authConfig)) {
125 + yield* ui.log.error(
126 + 'Missing argument. Provide a toolkit slug or --auth-config:\n' +
127 + ' composio connected-accounts link github\n' +
128 + ' composio connected-accounts link --auth-config "ac_..."'
129 + );
130 return;
131 }
132
70 - const { connected_account_id, redirect_url } = linkOpt.value;
133 + if (Option.isSome(authConfig)) {
134 + // Path A: Legacy flow — use existing client.link.create()
135 + const linkOpt = yield* ui
136 + .withSpinner(
137 + 'Creating link session...',
138 + repo.createConnectedAccountLink({
139 + auth_config_id: authConfig.value,
140 + user_id: userId,
141 + })
142 + )
143 + .pipe(
144 + Effect.asSome,
145 + Effect.catchTag(
146 + 'services/HttpServerError',
147 + handleHttpServerError(ui, {
148 + fallbackMessage: `Failed to create link for auth config "${authConfig.value}".`,
149 + hint: 'Browse available auth configs:\n> composio auth-configs list',
150 + fallbackValue: Option.none(),
151 + })
152 + )
153 + );
154
72 - // Display the redirect URL
73 - yield* ui.note(redirect_url, 'Redirect URL');
74 - yield* ui.output(redirect_url);
155 + if (Option.isNone(linkOpt)) {
156 + return;
157 + }
158 +
159 + yield* waitForActiveConnection(
160 + ui,
161 + repo,
162 + linkOpt.value.connected_account_id,
163 + linkOpt.value.redirect_url,
164 + noBrowser
165 + );
166 + } else {
167 + // Path B: Tool Router flow — toolkit is guaranteed Some (validated above)
168 + const toolkitSlug = Option.getOrThrow(toolkit);
169 + const clientSingleton = yield* ComposioClientSingleton;
170 + const client = yield* clientSingleton.get();
171
76 - if (!noBrowser) {
77 - yield* Effect.tryPromise(() => open(redirect_url, { wait: false })).pipe(
78 - Effect.catchAll(error =>
172 + const linkOpt = yield* ui
173 + .withSpinner(
174 + `Linking ${toolkitSlug}...`,
175 Effect.gen(function* () {
80 - yield* Effect.logDebug('Failed to open browser:', error);
81 - yield* ui.log.warn('Could not open the browser automatically.');
82 - yield* ui.log.info('Tip: try using `--no-browser` and open the URL manually.');
176 + const sessionId = yield* createToolRouterSession(client, userId, {
177 + manageConnections: true,
178 + });
179 + return yield* Effect.tryPromise(() =>
180 + client.toolRouter.session.link(sessionId, { toolkit: toolkitSlug })
181 + );
182 })
183 )
184 + .pipe(
185 + Effect.asSome,
186 + Effect.catchAll(error =>
187 + Effect.gen(function* () {
188 + // Surface the API error message when available
189 + const message =
190 + error instanceof Error
191 + ? error.message
192 + : typeof error === 'object' && error !== null && 'message' in error
193 + ? String((error as { message: unknown }).message)
194 + : `Failed to create link for toolkit "${toolkitSlug}".`;
195 +
196 + yield* ui.log.error(message);
197 + yield* Effect.logDebug('Link error:', error);
198 + yield* ui.log.step('Browse available toolkits:\n> composio toolkits list');
199 + return Option.none();
200 + })
201 + )
202 + );
203 +
204 + if (Option.isNone(linkOpt)) {
205 + return;
206 + }
207 +
208 + yield* waitForActiveConnection(
209 + ui,
210 + repo,
211 + linkOpt.value.connected_account_id,
212 + linkOpt.value.redirect_url,
213 + noBrowser
214 );
215 }
87 -
88 - // Poll until the connected account becomes ACTIVE
89 - yield* ui.useMakeSpinner('Waiting for authentication...', spinner =>
90 - Effect.retry(
91 - Effect.gen(function* () {
92 - const account = yield* repo.getConnectedAccount(connected_account_id);
93 -
94 - if (account.status === 'ACTIVE') {
95 - return account;
96 - }
97 -
98 - return yield* Effect.fail(
99 - new Error(`Connection status is still '${account.status}', waiting for 'ACTIVE'`)
100 - );
101 - }),
102 - // Exponential backoff: start with 0.3s, max 5s, up to 15 retries
103 - Schedule.exponential('0.3 seconds').pipe(
104 - Schedule.intersect(Schedule.recurs(15)),
105 - Schedule.intersect(Schedule.spaced('5 seconds'))
106 - )
107 - ).pipe(
108 - Effect.tap(account => {
109 - return Effect.all([
110 - spinner.stop('Connection successful'),
111 - ui.log.success(
112 - `Connected account "${account.id}" is now ACTIVE (toolkit: ${account.toolkit.slug}).`
113 - ),
114 - ]);
115 - }),
116 - Effect.tapError(() => spinner.error('Connection timed out. Please try again.'))
117 - )
118 - );
216 })
217 ).pipe(Command.withDescription('Link an external account via OAuth redirect.'));
ts/packages/cli/src/commands/toolkits/commands/toolkits.info.cmd.ts
+37 -22
@@ -1,9 +1,9 @@
1 -import { Args, Command } from '@effect/cli';
1 +import { Args, Command, Options } from '@effect/cli';
2 import { Effect, Option } from 'effect';
3 -import { ComposioToolkitsRepository } from 'src/services/composio-clients';
3 +import { ComposioClientSingleton } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { requireAuth } from 'src/effects/require-auth';
6 -import { handleHttpServerError } from 'src/effects/handle-http-error';
6 +import { createToolRouterSession } from 'src/effects/create-tool-router-session';
7 import { formatToolkitInfo } from '../format';
8
9 const slug = Args.text({ name: 'slug' }).pipe(
@@ -11,20 +11,25 @@ const slug = Args.text({ name: 'slug' }).pipe(
11 Args.optional
12 );
13
14 +const userId = Options.text('user-id').pipe(
15 + Options.withDefault('default'),
16 + Options.withDescription('User ID for connection status (default: "default")')
17 +);
18 +
19 /**
15 - * View details of a specific toolkit including auth schemes and required fields.
20 + * View details of a specific toolkit including connection status.
21 *
22 * @example
23 * ```bash
24 * composio toolkits info "gmail"
25 + * composio toolkits info "github" --user-id "alice"
26 * ```
27 */
22 -export const toolkitsCmd$Info = Command.make('info', { slug }, ({ slug }) =>
28 +export const toolkitsCmd$Info = Command.make('info', { slug, userId }, ({ slug, userId }) =>
29 Effect.gen(function* () {
30 if (!(yield* requireAuth)) return;
31
32 const ui = yield* TerminalUI;
27 - const repo = yield* ComposioToolkitsRepository;
33
34 // Missing slug guard
35 if (Option.isNone(slug)) {
@@ -35,25 +40,35 @@ export const toolkitsCmd$Info = Command.make('info', { slug }, ({ slug }) =>
40
41 const slugValue = slug.value;
42
43 + const clientSingleton = yield* ComposioClientSingleton;
44 + const client = yield* clientSingleton.get();
45 +
46 const toolkitOpt = yield* ui
39 - .withSpinner(`Fetching toolkit "${slugValue}"...`, repo.getToolkitDetailed(slugValue))
47 + .withSpinner(
48 + `Fetching toolkit "${slugValue}"...`,
49 + Effect.gen(function* () {
50 + const sessionId = yield* createToolRouterSession(client, userId);
51 + const result = yield* Effect.tryPromise(() =>
52 + client.toolRouter.session.toolkits(sessionId, {
53 + toolkits: [slugValue],
54 + })
55 + );
56 + const item = result.items[0];
57 + if (!item) {
58 + return yield* Effect.fail(new Error(`Toolkit "${slugValue}" not found.`));
59 + }
60 + return item;
61 + })
62 + )
63 .pipe(
64 Effect.asSome,
42 - Effect.catchTag(
43 - 'services/HttpServerError',
44 - handleHttpServerError(ui, {
45 - fallbackMessage: `Failed to fetch toolkit "${slugValue}".`,
46 - hint: 'Browse available toolkits:\n> composio toolkits list',
47 - fallbackValue: Option.none(),
48 - searchForSuggestions: () =>
49 - repo.searchToolkits({ search: slugValue, limit: 3 }).pipe(
50 - Effect.map(r =>
51 - r.items.map(s => ({
52 - label: `${s.slug} — ${s.meta.description}`,
53 - command: `> composio toolkits info "${s.slug}"`,
54 - }))
55 - )
56 - ),
65 + Effect.catchAll(error =>
66 + Effect.gen(function* () {
67 + const message =
68 + error instanceof Error ? error.message : `Failed to fetch toolkit "${slugValue}".`;
69 + yield* ui.log.error(message);
70 + yield* ui.log.step('Browse available toolkits:\n> composio toolkits list');
71 + return Option.none();
72 })
73 )
74 );
ts/packages/cli/src/commands/toolkits/commands/toolkits.list.cmd.ts
+58 -33
@@ -1,8 +1,9 @@
1 import { Command, Options } from '@effect/cli';
2 import { Effect, Option } from 'effect';
3 -import { ComposioToolkitsRepository } from 'src/services/composio-clients';
3 +import { ComposioClientSingleton } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { requireAuth } from 'src/effects/require-auth';
6 +import { createToolRouterSession } from 'src/effects/create-tool-router-session';
7 import { clampLimit } from 'src/ui/clamp-limit';
8 import { formatToolkitsTable, formatToolkitsJson } from '../format';
9
@@ -16,51 +17,75 @@ const limit = Options.integer('limit').pipe(
17 Options.withDescription('Number of results per page (1-1000)')
18 );
19
20 +const connected = Options.boolean('connected').pipe(
21 + Options.withDescription('Filter to connected toolkits only'),
22 + Options.optional
23 +);
24 +
25 +const userId = Options.text('user-id').pipe(
26 + Options.withDefault('default'),
27 + Options.withDescription('User ID for connection status (default: "default")')
28 +);
29 +
30 /**
20 - * List available toolkits with optional filters.
31 + * List available toolkits with connection status.
32 *
33 * @example
34 * ```bash
35 * composio toolkits list
36 * composio toolkits list --query "email"
26 - * composio toolkits list --category "messaging" --limit 10
37 + * composio toolkits list --connected
38 + * composio toolkits list --user-id "alice"
39 * ```
40 */
29 -export const toolkitsCmd$List = Command.make('list', { query, limit }, ({ query, limit }) =>
30 - Effect.gen(function* () {
31 - if (!(yield* requireAuth)) return;
41 +export const toolkitsCmd$List = Command.make(
42 + 'list',
43 + { query, limit, connected, userId },
44 + ({ query, limit, connected, userId }) =>
45 + Effect.gen(function* () {
46 + if (!(yield* requireAuth)) return;
47
33 - const ui = yield* TerminalUI;
34 - const repo = yield* ComposioToolkitsRepository;
48 + const ui = yield* TerminalUI;
49 + const clientSingleton = yield* ComposioClientSingleton;
50 + const client = yield* clientSingleton.get();
51
36 - const clampedLimit = clampLimit(limit);
52 + const clampedLimit = clampLimit(limit);
53
38 - const result = yield* ui.withSpinner(
39 - 'Fetching toolkits...',
40 - repo.searchToolkits({
41 - search: Option.getOrUndefined(query),
42 - limit: clampedLimit,
43 - })
44 - );
54 + const result = yield* ui.withSpinner(
55 + 'Fetching toolkits...',
56 + Effect.gen(function* () {
57 + const sessionId = yield* createToolRouterSession(client, userId);
58 + return yield* Effect.tryPromise(() =>
59 + client.toolRouter.session.toolkits(sessionId, {
60 + search: Option.getOrUndefined(query),
61 + limit: clampedLimit,
62 + is_connected: Option.getOrUndefined(connected),
63 + })
64 + );
65 + })
66 + );
67
46 - if (result.items.length === 0) {
47 - yield* ui.log.warn('No toolkits found. Try broadening your search.');
48 - return;
49 - }
68 + if (result.items.length === 0) {
69 + yield* ui.log.warn('No toolkits found. Try broadening your search.');
70 + yield* ui.output('[]');
71 + return;
72 + }
73
51 - const showing = result.items.length;
52 - const total = result.total_items;
74 + const showing = result.items.length;
75 + const total = result.total_items;
76
54 - yield* ui.log.info(
55 - `Listing ${showing} of ${total} toolkits\n\n${formatToolkitsTable(result.items)}`
56 - );
77 + yield* ui.log.info(
78 + `Listing ${showing} of ${total} toolkits\n\n${formatToolkitsTable(result.items)}`
79 + );
80
58 - // Next step hint
59 - const firstSlug = result.items[0]?.slug;
60 - if (firstSlug) {
61 - yield* ui.log.step(`To view details of a toolkit:\n> composio toolkits info "${firstSlug}"`);
62 - }
81 + // Next step hint
82 + const firstSlug = result.items[0]?.slug;
83 + if (firstSlug) {
84 + yield* ui.log.step(
85 + `To view details of a toolkit:\n> composio toolkits info "${firstSlug}"`
86 + );
87 + }
88
64 - yield* ui.output(formatToolkitsJson(result.items));
65 - })
66 -).pipe(Command.withDescription('List available toolkits.'));
89 + yield* ui.output(formatToolkitsJson(result.items));
90 + })
91 +).pipe(Command.withDescription('List available toolkits with connection status.'));
ts/packages/cli/src/commands/toolkits/commands/toolkits.search.cmd.ts
+6 -3
@@ -4,7 +4,7 @@ import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { requireAuth } from 'src/effects/require-auth';
6 import { clampLimit } from 'src/ui/clamp-limit';
7 -import { formatToolkitsTable, formatToolkitsJson } from '../format';
7 +import { formatLegacyToolkitsTable, formatLegacyToolkitsJson } from '../format';
8
9 const query = Args.text({ name: 'query' }).pipe(
10 Args.withDescription('Search query (e.g. "send emails")')
@@ -15,6 +15,9 @@ const limit = Options.integer('limit').pipe(
15 Options.withDescription('Number of results per page (1-1000)')
16 );
17
18 +// TODO(tool-router-migration): migrate to Tool Router when the session toolkits endpoint
19 +// supports text search. Currently SessionToolsParams has no search capability.
20 +
21 /**
22 * Search toolkits by use case.
23 *
@@ -47,7 +50,7 @@ export const toolkitsCmd$Search = Command.make('search', { query, limit }, ({ qu
50 const total = result.total_items;
51
52 yield* ui.log.info(
50 - `Found ${showing} of ${total} toolkits\n\n${formatToolkitsTable(result.items)}`
53 + `Found ${showing} of ${total} toolkits\n\n${formatLegacyToolkitsTable(result.items)}`
54 );
55
56 // Next step hint
@@ -56,6 +59,6 @@ export const toolkitsCmd$Search = Command.make('search', { query, limit }, ({ qu
59 yield* ui.log.step(`To view details:\n> composio toolkits info "${firstSlug}"`);
60 }
61
59 - yield* ui.output(formatToolkitsJson(result.items));
62 + yield* ui.output(formatLegacyToolkitsJson(result.items));
63 })
64 ).pipe(Command.withDescription('Search toolkits by use case.'));
ts/packages/cli/src/commands/toolkits/format.ts
+101 -75
@@ -1,38 +1,65 @@
1 -import type { Toolkit, ToolkitDetailed, AuthConfigDetail } from 'src/models/toolkits';
2 -import { bold, gray } from 'src/ui/colors';
1 +import type { Toolkit } from 'src/models/toolkits';
2 +import type { SessionToolkitsResponse } from '@composio/client/resources/tool-router';
3 +import { bold, gray, green, dim } from 'src/ui/colors';
4 import { truncate } from 'src/ui/truncate';
5
6 +type SessionToolkitItem = SessionToolkitsResponse.Item;
7 +
8 +// ---------- Tool Router format functions ----------
9 +
10 /**
6 - * Format a list of toolkits as a human-readable table.
11 + * Derive connection status text and color from a session toolkit item.
12 + * Returns plain text + color function so callers can pad before coloring.
13 */
8 -export function formatToolkitsTable(toolkits: ReadonlyArray<Toolkit>): string {
9 - const header = `${bold('Name'.padEnd(20))} ${bold('Slug'.padEnd(20))} ${bold('Version'.padEnd(12))} ${bold('Tools'.padEnd(7))} ${bold('Triggers'.padEnd(10))} ${bold('Description')}`;
14 +function connectionStatusParts(item: SessionToolkitItem): {
15 + text: string;
16 + color: (s: string) => string;
17 +} {
18 + if (item.is_no_auth) return { text: 'no auth', color: dim };
19 + if (item.connected_account?.status === 'ACTIVE') return { text: 'active', color: green };
20 + return { text: 'not connected', color: dim };
21 +}
22 +
23 +/**
24 + * Format a list of session toolkits as a human-readable table.
25 + */
26 +export function formatToolkitsTable(toolkits: ReadonlyArray<SessionToolkitItem>): string {
27 + const header = `${bold('Name'.padEnd(20))} ${bold('Slug'.padEnd(20))} ${bold('Connected'.padEnd(16))} ${bold('Auth Scheme'.padEnd(14))} ${bold('Description')}`;
28
29 const rows = toolkits.map(t => {
30 const name = t.name.padEnd(20);
31 const slug = t.slug.padEnd(20);
14 - const version = (t.meta.available_versions.at(-1) ?? '-').padEnd(12);
15 - const tools = String(t.meta.tools_count).padEnd(7);
16 - const triggers = String(t.meta.triggers_count).padEnd(10);
32 + // Pad plain text first, then apply color — ANSI escapes break padEnd.
33 + const { text: statusText, color: statusColor } = connectionStatusParts(t);
34 + const status = statusColor(statusText.padEnd(16));
35 + const authScheme = (t.connected_account?.auth_config?.auth_scheme ?? '-').padEnd(14);
36 const desc = gray(truncate(t.meta.description, 50));
18 - return `${name} ${slug} ${version} ${tools} ${triggers} ${desc}`;
37 + return `${name} ${slug} ${status} ${authScheme} ${desc}`;
38 });
39
40 return [header, ...rows].join('\n');
41 }
42
43 /**
25 - * Format toolkits as JSON for piped output.
44 + * Format session toolkits as JSON for piped output.
45 */
27 -export function formatToolkitsJson(toolkits: ReadonlyArray<Toolkit>): string {
46 +export function formatToolkitsJson(toolkits: ReadonlyArray<SessionToolkitItem>): string {
47 return JSON.stringify(
48 toolkits.map(t => ({
49 name: t.name,
50 slug: t.slug,
32 - latest_version: t.meta.available_versions.at(-1) ?? null,
33 - tools_count: t.meta.tools_count,
34 - triggers_count: t.meta.triggers_count,
51 description: t.meta.description,
52 + is_no_auth: t.is_no_auth,
53 + enabled: t.enabled,
54 + connected: t.connected_account
55 + ? {
56 + status: t.connected_account.status,
57 + id: t.connected_account.id,
58 + auth_scheme: t.connected_account.auth_config.auth_scheme,
59 + is_composio_managed: t.connected_account.auth_config.is_composio_managed,
60 + }
61 + : null,
62 + composio_managed_auth_schemes: t.composio_managed_auth_schemes,
63 })),
64 null,
65 2
@@ -40,78 +67,77 @@ export function formatToolkitsJson(toolkits: ReadonlyArray<Toolkit>): string {
67 }
68
69 /**
43 - * Format auth config fields for display.
70 + * Format a single session toolkit for detailed interactive display.
71 */
45 -function formatFields(group: AuthConfigDetail['fields']['auth_config_creation']) {
46 - const allFields = [
47 - ...group.required.map(f => ({ ...f, label: 'required' })),
48 - ...group.optional.map(f => ({ ...f, label: 'optional' })),
49 - ];
50 -
51 - if (allFields.length === 0) {
52 - return ' (none)';
53 - }
54 -
55 - const nameWidth = Math.max(...allFields.map(f => f.name.length));
56 - const labelWidth = Math.max(...allFields.map(f => f.label.length));
57 - const typeWidth = Math.max(...allFields.map(f => f.type.length));
58 -
59 - return allFields
60 - .map(field => {
61 - const desc = field.description ? ` ${gray(`"${field.description}"`)}` : '';
62 - return ` ${field.name.padEnd(nameWidth)} ${field.label.padEnd(labelWidth)} ${field.type.padEnd(typeWidth)}${desc}`;
63 - })
64 - .join('\n');
65 -}
66 -
67 -/**
68 - * Format a detailed toolkit for interactive display.
69 - */
70 -export function formatToolkitInfo(toolkit: ToolkitDetailed): string {
72 +export function formatToolkitInfo(toolkit: SessionToolkitItem): string {
73 const lines: string[] = [];
74
75 lines.push(`${bold('Name:')} ${toolkit.name}`);
76 lines.push(`${bold('Slug:')} ${toolkit.slug}`);
75 -
76 - const versions = toolkit.meta.available_versions;
77 - const latest = versions.at(-1);
78 - if (latest) {
79 - lines.push(`${bold('Latest Version:')} ${latest} (${versions.length} available)`);
80 - } else {
81 - lines.push(`${bold('Latest Version:')} -`);
82 - }
83 -
77 lines.push(`${bold('Description:')} ${toolkit.meta.description || '(none)'}`);
78
86 - // Derive auth schemes from auth_config_details
87 - const authSchemes = toolkit.auth_config_details.map(d => d.mode);
88 - if (toolkit.no_auth) {
79 + if (toolkit.is_no_auth) {
80 lines.push(`${bold('Auth:')} No authentication required`);
90 - } else if (authSchemes.length > 0) {
91 - lines.push(`${bold('Auth Schemes:')} ${authSchemes.join(', ')}`);
92 - if (toolkit.composio_managed_auth_schemes.length > 0) {
93 - lines.push(
94 - `${bold('Composio Managed Auth Schemes:')} ${toolkit.composio_managed_auth_schemes.join(', ')}`
95 - );
96 - }
81 + } else if (toolkit.composio_managed_auth_schemes.length > 0) {
82 + lines.push(
83 + `${bold('Composio Managed Auth Schemes:')} ${toolkit.composio_managed_auth_schemes.join(', ')}`
84 + );
85 }
86
99 - // Auth config creation fields
100 - if (toolkit.auth_config_details.length > 0) {
101 - lines.push('');
102 - lines.push(bold('Fields Required for AuthConfig creation:'));
103 - for (const detail of toolkit.auth_config_details) {
104 - lines.push(` ${detail.name} (${detail.mode}):`);
105 - lines.push(formatFields(detail.fields.auth_config_creation));
106 - }
107 -
108 - lines.push('');
109 - lines.push(bold('Fields Required for Connected Account creation:'));
110 - for (const detail of toolkit.auth_config_details) {
111 - lines.push(` ${detail.name} (${detail.mode}):`);
112 - lines.push(formatFields(detail.fields.connected_account_initiation));
113 - }
87 + // Connection status — render the actual status, not a hardcoded label
88 + lines.push('');
89 + if (toolkit.connected_account) {
90 + const ca = toolkit.connected_account;
91 + const statusDisplay = ca.status === 'ACTIVE' ? green(ca.status) : dim(ca.status);
92 + lines.push(`${bold('Connection Status:')} ${statusDisplay}`);
93 + lines.push(`${bold('Connected Account ID:')} ${ca.id}`);
94 + lines.push(`${bold('Auth Scheme:')} ${ca.auth_config.auth_scheme}`);
95 + lines.push(`${bold('Composio Managed:')} ${ca.auth_config.is_composio_managed ? 'Yes' : 'No'}`);
96 + } else if (!toolkit.is_no_auth) {
97 + lines.push(`${bold('Connection Status:')} ${dim('Not connected')}`);
98 + lines.push(
99 + `${bold('Tip:')} Link this toolkit:\n> composio connected-accounts link "${toolkit.slug}"`
100 + );
101 }
102
103 return lines.join('\n');
104 }
105 +
106 +// ---------- Legacy format functions (used by non-migrated commands) ----------
107 +
108 +/**
109 + * Format a list of toolkits as a human-readable table (legacy format).
110 + */
111 +export function formatLegacyToolkitsTable(toolkits: ReadonlyArray<Toolkit>): string {
112 + const header = `${bold('Name'.padEnd(20))} ${bold('Slug'.padEnd(20))} ${bold('Version'.padEnd(12))} ${bold('Tools'.padEnd(7))} ${bold('Triggers'.padEnd(10))} ${bold('Description')}`;
113 +
114 + const rows = toolkits.map(t => {
115 + const name = t.name.padEnd(20);
116 + const slug = t.slug.padEnd(20);
117 + const version = (t.meta.available_versions.at(-1) ?? '-').padEnd(12);
118 + const tools = String(t.meta.tools_count).padEnd(7);
119 + const triggers = String(t.meta.triggers_count).padEnd(10);
120 + const desc = gray(truncate(t.meta.description, 50));
121 + return `${name} ${slug} ${version} ${tools} ${triggers} ${desc}`;
122 + });
123 +
124 + return [header, ...rows].join('\n');
125 +}
126 +
127 +/**
128 + * Format toolkits as JSON for piped output (legacy format).
129 + */
130 +export function formatLegacyToolkitsJson(toolkits: ReadonlyArray<Toolkit>): string {
131 + return JSON.stringify(
132 + toolkits.map(t => ({
133 + name: t.name,
134 + slug: t.slug,
135 + latest_version: t.meta.available_versions.at(-1) ?? null,
136 + tools_count: t.meta.tools_count,
137 + triggers_count: t.meta.triggers_count,
138 + description: t.meta.description,
139 + })),
140 + null,
141 + 2
142 + );
143 +}
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+37 -55
@@ -2,8 +2,6 @@ import { Args, Command, Options } from '@effect/cli';
2 import util from 'node:util';
3 import { Effect, Option, Either } from 'effect';
4 import { FileSystem } from '@effect/platform';
5 -import { ComposioError } from '@composio/core';
6 -import type { ToolExecuteParams } from '@composio/core';
5 import { JSONParse } from 'src/effects/json';
6 import { redact } from 'src/ui/redact';
7 import { readStdin, readStdinIfPiped } from 'src/effects/read-stdin';
@@ -11,8 +9,10 @@ import { requireAuth } from 'src/effects/require-auth';
9 import { TerminalUI } from 'src/services/terminal-ui';
10 import {
11 ActionExecuteConnectedAccountNotFoundError,
12 + isNoConnectionSlug,
13 ToolsExecutor,
14 } from 'src/services/tools-executor';
15 +import type { ToolExecuteParams } from 'src/services/tools-executor';
16 import {
17 extractApiErrorDetails,
18 extractMessage,
@@ -35,16 +35,6 @@ const userId = Options.text('user-id').pipe(
35 Options.withDescription('User ID to execute the tool for (default: "default")')
36 );
37
38 -const connectedAccountId = Options.text('connected-account-id').pipe(
39 - Options.withDescription('Connected account ID to use for authenticated tools'),
40 - Options.optional
41 -);
42 -
43 -const toolkitVersion = Options.text('toolkit-version').pipe(
44 - Options.withDescription('Toolkit version to execute (e.g. "20250909_00")'),
45 - Options.optional
46 -);
47 -
38 const resolveInput = (input: Option.Option<string>) =>
39 Effect.gen(function* () {
40 const fs = yield* FileSystem.FileSystem;
@@ -90,15 +80,22 @@ const parseArguments = (raw: string) =>
80 return parsed as Record<string, unknown>;
81 });
82
93 -const formatPossibleFixes = (fixes: ReadonlyArray<string>) =>
94 - fixes.map(fix => `- ${fix}`).join('\n');
83 +/**
84 + * Derive the toolkit slug from a tool slug.
85 + * e.g. "GMAIL_CREATE_EMAIL_DRAFT" → "gmail", "GITHUB_GET_REPOS" → "github"
86 + */
87 +const toolkitFromToolSlug = (toolSlug: string): string => {
88 + const idx = toolSlug.indexOf('_');
89 + return idx > 0 ? toolSlug.slice(0, idx).toLowerCase() : toolSlug.toLowerCase();
90 +};
91
96 -const connectedAccountTips = [
97 - `Create or find an auth config: ${bold('composio auth-configs list --toolkits <toolkit>')}`,
98 - `Link the account: ${bold('composio connected-accounts link --auth-config <AUTH_CONFIG_ID> --user-id <USER_ID>')}`,
99 - `Verify the link: ${bold('composio connected-accounts list --toolkits <toolkit> --user-id <USER_ID>')}`,
100 - `Retry the tool or pass ${bold('--connected-account-id <ID>')}`,
101 -].join('\n');
92 +const connectionTips = (toolSlug: string, userId: string) => {
93 + const toolkit = toolkitFromToolSlug(toolSlug);
94 + return [
95 + `Link the toolkit first: ${bold(`composio connected-accounts link ${toolkit} --user-id ${userId}`)}`,
96 + `Then retry: ${bold(`composio tools execute ${toolSlug} ...`)}`,
97 + ].join('\n');
98 +};
99
100 /**
101 * JSON.stringify replacer that redacts ID-like string values in CI.
@@ -144,7 +141,7 @@ const normalizeError = (error: unknown): unknown => {
141 while (current && typeof current === 'object' && !seen.has(current)) {
142 seen.add(current);
143
147 - if (current instanceof ComposioError || current instanceof Error) {
144 + if (current instanceof Error) {
145 return current;
146 }
147
@@ -167,7 +164,11 @@ const normalizeError = (error: unknown): unknown => {
164 *
165 * Returns a structured error summary suitable for `ui.output()` in piped mode.
166 */
170 -const handleExecutionError = (ui: TerminalUI, error: unknown) =>
167 +const handleExecutionError = (
168 + ui: TerminalUI,
169 + error: unknown,
170 + context: { toolSlug: string; userId: string }
171 +) =>
172 Effect.gen(function* () {
173 const normalized = normalizeError(error);
174
@@ -187,25 +188,6 @@ const handleExecutionError = (ui: TerminalUI, error: unknown) =>
188 // Display the primary error message
189 yield* ui.log.error(message);
190
190 - // ComposioError-specific: show code, status, cause, possible fixes
191 - if (normalized instanceof ComposioError) {
192 - if (normalized.code) {
193 - yield* ui.log.message(`Code: ${normalized.code}`);
194 - }
195 - const statusCode = (normalized as { statusCode?: number }).statusCode;
196 - if (statusCode) {
197 - yield* ui.log.message(`Status: ${statusCode}`);
198 - }
199 - const cause = (normalized as { cause?: unknown }).cause;
200 - if (cause) {
201 - const causeMessage = cause instanceof Error ? cause.message : String(cause);
202 - yield* ui.log.message(`Cause: ${causeMessage}`);
203 - }
204 - if (normalized.possibleFixes && normalized.possibleFixes.length > 0) {
205 - yield* ui.note(formatPossibleFixes(normalized.possibleFixes), 'Possible fixes');
206 - }
207 - }
208 -
191 // Show API error details when available
192 const detailsObject =
193 apiDetails ??
@@ -218,9 +200,9 @@ const handleExecutionError = (ui: TerminalUI, error: unknown) =>
200 yield* ui.note(formatUnknownObject(redactRequestId(detailsObject)), 'Error details');
201 }
202
221 - // Connected-account tips
222 - if (slugValue === 'ActionExecute_ConnectedAccountNotFound') {
223 - yield* ui.note(connectedAccountTips, 'Tips');
203 + // No-connection tips — show for both legacy and Tool Router error slugs
204 + if (isNoConnectionSlug(slugValue)) {
205 + yield* ui.note(connectionTips(context.toolSlug, context.userId), 'Tips');
206 }
207
208 // Return structured summary for piped output
@@ -243,8 +225,8 @@ class ToolExecutionError {
225 */
226 export const toolsCmd$Execute = Command.make(
227 'execute',
246 - { slug, data, userId, connectedAccountId, toolkitVersion },
247 - ({ slug, data, userId, connectedAccountId, toolkitVersion }) =>
228 + { slug, data, userId },
229 + ({ slug, data, userId }) =>
230 Effect.gen(function* () {
231 if (!(yield* requireAuth)) return;
232
@@ -254,15 +236,9 @@ export const toolsCmd$Execute = Command.make(
236 const input = yield* resolveInput(data);
237 const args = yield* parseArguments(input);
238
257 - const versionValue = Option.getOrUndefined(toolkitVersion);
258 - const shouldSkipVersionCheck = !versionValue || versionValue === 'latest';
259 -
239 const params: ToolExecuteParams = {
240 userId,
241 arguments: args,
263 - connectedAccountId: Option.getOrUndefined(connectedAccountId),
264 - version: versionValue,
265 - dangerouslySkipVersionCheck: shouldSkipVersionCheck ? true : undefined,
242 };
243
244 yield* ui.useMakeSpinner(`Executing tool "${slug}"...`, spinner =>
@@ -272,7 +248,10 @@ export const toolsCmd$Execute = Command.make(
248 // Hard failure: API threw an exception
249 if (Either.isLeft(resultEither)) {
250 yield* spinner.error();
275 - const summary = yield* handleExecutionError(ui, resultEither.left);
251 + const summary = yield* handleExecutionError(ui, resultEither.left, {
252 + toolSlug: slug,
253 + userId,
254 + });
255 yield* ui.output(
256 JSON.stringify({ successful: false, ...summary }, ciRedactReplacer, 2)
257 );
@@ -281,14 +260,17 @@ export const toolsCmd$Execute = Command.make(
260
261 const result = resultEither.right;
262
284 - // Soft failure: API returned { successful: false }
263 + // Soft failure: execution returned an error
264 if (!result.successful) {
265 const logId = result.logId
266 ? ` (logId: ${redact({ value: result.logId, prefix: 'log_' })})`
267 : '';
268 yield* spinner.error(`Execution failed${logId}`);
269
291 - const summary = yield* handleExecutionError(ui, result.error ?? result);
270 + const summary = yield* handleExecutionError(ui, result.error ?? result, {
271 + toolSlug: slug,
272 + userId,
273 + });
274 yield* ui.output(JSON.stringify(result, ciRedactReplacer, 2));
275 return yield* Effect.fail(new ToolExecutionError(summary.error));
276 }
ts/packages/cli/src/effects/create-tool-router-session.ts new
+26
@@ -0,0 +1,26 @@
1 +import { Effect } from 'effect';
2 +import type { Composio } from '@composio/client';
3 +
4 +export interface CreateToolRouterSessionOptions {
5 + /** Enable auto connection management. Default: false. */
6 + readonly manageConnections?: boolean;
7 +}
8 +
9 +/**
10 + * Create an ephemeral Tool Router session for the given user ID.
11 + * Returns the session ID string.
12 + *
13 + * Accepts a pre-resolved client instance (from ComposioClientSingleton)
14 + * so callers can resolve the dependency at layer construction time.
15 + */
16 +export const createToolRouterSession = (
17 + client: Composio,
18 + userId: string,
19 + options?: CreateToolRouterSessionOptions
20 +) =>
21 + Effect.tryPromise(() =>
22 + client.toolRouter.session.create({
23 + user_id: userId,
24 + manage_connections: { enable: options?.manageConnections ?? false },
25 + })
26 + ).pipe(Effect.map(session => session.session_id));
ts/packages/cli/src/services/composio-clients.ts
+1 -1
@@ -792,7 +792,7 @@ const callClientWithPagination = <T, S extends PaginatedSchema>(
792 * Singleton service that lazily accesses `Config` only when needed, which is used to build and provide
793 * a raw (uneffectful, Promise-based) Composio client instance.
794 */
795 -class ComposioClientSingleton extends Effect.Service<ComposioClientSingleton>()(
795 +export class ComposioClientSingleton extends Effect.Service<ComposioClientSingleton>()(
796 'services/ComposioClientSingleton',
797 {
798 accessors: true,
ts/packages/cli/src/services/tools-executor.ts
+92 -39
@@ -1,13 +1,26 @@
1 -import { Composio, ComposioToolExecutionError } from '@composio/core';
2 -import { Context, Effect, Layer, Option } from 'effect';
3 -import type { ToolExecuteParams, ToolExecuteResponse } from '@composio/core';
4 -import { ComposioUserContext } from 'src/services/user-context';
1 +import { Context, Effect, Layer } from 'effect';
2 +import type {
3 + SessionExecuteResponse,
4 + SessionExecuteMetaResponse,
5 + SessionExecuteMetaParams,
6 +} from '@composio/client/resources/tool-router';
7 +import { ComposioClientSingleton } from 'src/services/composio-clients';
8 +import { createToolRouterSession } from 'src/effects/create-tool-router-session';
9 import {
10 extractMessage,
11 extractSlug,
12 extractApiErrorDetails,
13 } from 'src/utils/api-error-extraction';
14
15 +/** Error slugs that indicate a missing connected account / no active connection. */
16 +const NO_CONNECTION_SLUGS: ReadonlySet<string> = new Set([
17 + 'ActionExecute_ConnectedAccountNotFound',
18 + 'ToolRouterV2_NoActiveConnection',
19 +]);
20 +
21 +export const isNoConnectionSlug = (slug: string | undefined | null): boolean =>
22 + slug != null && NO_CONNECTION_SLUGS.has(slug);
23 +
24 export class ActionExecuteConnectedAccountNotFoundError extends Error {
25 readonly details: unknown;
26
@@ -19,28 +32,23 @@ export class ActionExecuteConnectedAccountNotFoundError extends Error {
32 }
33 }
34
22 -const hasComposioToolExecutionError = (value: unknown): boolean => {
23 - let current: unknown = value;
24 - const seen = new Set<unknown>();
25 -
26 - while (current && typeof current === 'object' && !seen.has(current)) {
27 - seen.add(current);
28 - if (current instanceof ComposioToolExecutionError) {
29 - return true;
30 - }
31 - if ('error' in current) {
32 - current = (current as { error?: unknown }).error;
33 - continue;
34 - }
35 - if ('cause' in current) {
36 - current = (current as { cause?: unknown }).cause;
37 - continue;
38 - }
39 - break;
40 - }
35 +/**
36 + * Parameters accepted by the Tool Router-based executor.
37 + */
38 +export interface ToolExecuteParams {
39 + readonly userId: string;
40 + readonly arguments: Record<string, unknown>;
41 +}
42
42 - return false;
43 -};
43 +/**
44 + * Normalized response that matches the shape consumers expect.
45 + */
46 +export interface ToolExecuteResponse {
47 + readonly successful: boolean;
48 + readonly data: Record<string, unknown>;
49 + readonly error: string | null;
50 + readonly logId: string;
51 +}
52
53 export interface ToolsExecutor {
54 readonly execute: (
@@ -51,29 +59,74 @@ export interface ToolsExecutor {
59
60 export const ToolsExecutor = Context.GenericTag<ToolsExecutor>('services/ToolsExecutor');
61
62 +/**
63 + * Meta tool slugs handled by `session.executeMeta` instead of `session.execute`.
64 + */
65 +const META_TOOL_SLUGS: ReadonlySet<string> = new Set([
66 + 'COMPOSIO_SEARCH_TOOLS',
67 + 'COMPOSIO_MULTI_EXECUTE_TOOL',
68 + 'COMPOSIO_MANAGE_CONNECTIONS',
69 + 'COMPOSIO_WAIT_FOR_CONNECTIONS',
70 + 'COMPOSIO_REMOTE_WORKBENCH',
71 + 'COMPOSIO_REMOTE_BASH_TOOL',
72 + 'COMPOSIO_GET_TOOL_SCHEMAS',
73 + 'COMPOSIO_UPSERT_RECIPE',
74 + 'COMPOSIO_GET_RECIPE',
75 +] as const);
76 +
77 +const isMetaToolSlug = (slug: string): slug is SessionExecuteMetaParams['slug'] =>
78 + META_TOOL_SLUGS.has(slug);
79 +
80 +/**
81 + * Normalize the raw Tool Router response into the shape the CLI commands expect.
82 + */
83 +const normalizeResponse = (
84 + raw: SessionExecuteResponse | SessionExecuteMetaResponse
85 +): ToolExecuteResponse => ({
86 + successful: raw.error === null,
87 + data: raw.data,
88 + error: raw.error,
89 + logId: raw.log_id,
90 +});
91 +
92 export const ToolsExecutorLive = Layer.effect(
93 ToolsExecutor,
94 Effect.gen(function* () {
57 - const ctx = yield* ComposioUserContext;
58 - const apiKey = ctx.data.apiKey.pipe(Option.getOrUndefined);
59 - const baseURL = ctx.data.baseURL;
60 -
61 - // Lazy: defer Composio SDK initialization until first execute call.
62 - // The CLI has its own `composio upgrade` command, so skip the npm version check.
63 - let composio: Composio | undefined;
64 - const getComposio = () =>
65 - (composio ??= new Composio({ apiKey, baseURL, disableVersionCheck: true }));
95 + // Resolve the client singleton at layer construction time.
96 + // The `get` instance method is an Effect.fn that lazily initializes
97 + // the raw Composio client on first call — no environment requirements.
98 + const clientSingleton = yield* ComposioClientSingleton;
99
100 return ToolsExecutor.of({
101 execute: (slug, params) =>
69 - Effect.tryPromise(() => getComposio().tools.execute(slug, params)).pipe(
102 + Effect.gen(function* () {
103 + const client = yield* clientSingleton.get();
104 + // One session per invocation — CLI runs one tool per process.
105 + const sessionId = yield* createToolRouterSession(client, params.userId, {
106 + manageConnections: true,
107 + });
108 +
109 + const raw: SessionExecuteResponse | SessionExecuteMetaResponse = yield* Effect.tryPromise(
110 + () => {
111 + if (isMetaToolSlug(slug)) {
112 + return client.toolRouter.session.executeMeta(sessionId, {
113 + slug,
114 + arguments: params.arguments,
115 + });
116 + }
117 + return client.toolRouter.session.execute(sessionId, {
118 + tool_slug: slug,
119 + arguments: params.arguments,
120 + });
121 + }
122 + );
123 +
124 + return normalizeResponse(raw);
125 + }).pipe(
126 Effect.catchAll((error): Effect.Effect<never, unknown> => {
127 const apiDetails = extractApiErrorDetails(error);
128 const slugValue = apiDetails?.slug ?? extractSlug(error);
73 - const shouldWrap =
74 - slugValue === 'ActionExecute_ConnectedAccountNotFound' &&
75 - hasComposioToolExecutionError(error);
76 - if (shouldWrap) {
129 + if (isNoConnectionSlug(slugValue)) {
130 return Effect.fail(
131 new ActionExecuteConnectedAccountNotFoundError(apiDetails ?? error)
132 );
ts/packages/cli/src/ui/colors.ts
+2
@@ -7,6 +7,8 @@ export const {
7 bgBlack,
8 bgRed,
9 gray,
10 + dim,
11 + green,
12 red,
13 redBright,
14 white,
ts/packages/cli/test/__utils__/services/test-layer.ts
+172 -23
@@ -21,6 +21,7 @@ import { TerminalUITest } from './terminal-ui-test';
21 import type { Toolkits, ToolkitDetailed } from 'src/models/toolkits';
22 import { NodeProcess } from 'src/services/node-process';
23 import {
24 + ComposioClientSingleton,
25 ComposioSessionRepository,
26 ComposioToolkitsRepository,
27 HttpServerError,
@@ -42,8 +43,20 @@ import { ComposioUserContextLive } from 'src/services/user-context';
43 import { UpgradeBinary } from 'src/services/upgrade-binary';
44 import { NodeOs } from 'src/services/node-os';
45 import { TriggersRealtime } from 'src/services/triggers-realtime';
45 -import type { ToolExecuteResponse } from '@composio/core';
46 -import { ToolsExecutor } from 'src/services/tools-executor';
46 +import { ToolsExecutor, ToolsExecutorLive } from 'src/services/tools-executor';
47 +import type { ToolExecuteResponse } from 'src/services/tools-executor';
48 +import type {
49 + SessionCreateResponse,
50 + SessionExecuteResponse,
51 + SessionExecuteMetaResponse,
52 + SessionLinkResponse,
53 + SessionToolkitsResponse,
54 + SessionCreateParams,
55 + SessionExecuteParams,
56 + SessionExecuteMetaParams,
57 + SessionLinkParams,
58 + SessionToolkitsParams,
59 +} from '@composio/client/resources/tool-router';
60 import { Stdin } from 'src/services/stdin';
61
62 export interface TestLiveInput {
@@ -111,13 +124,46 @@ export interface TestLiveInput {
124 /**
125 * Override tools executor behavior for tests.
126 *
114 - * - `failWith`: The executor rejects with this value (hard failure, e.g. API throw).
115 - * - `respondWith`: The executor resolves with this response (for soft failures like `{ successful: false }`).
127 + * When set, the `ToolsExecutor` service is replaced with a canned mock
128 + * that bypasses the real `ToolsExecutorLive` and the Tool Router entirely.
129 + * Use this only for tests that need to control the executor response directly
130 + * (e.g. soft failure tests).
131 + *
132 + * When NOT set, the real `ToolsExecutorLive` is used, which flows through
133 + * the mock `ComposioClientSingleton` → Tool Router session mocks.
134 */
135 toolsExecutor?: {
136 failWith?: unknown;
137 respondWith?: ToolExecuteResponse;
138 };
139 +
140 + /**
141 + * Override Tool Router session behavior for tests.
142 + *
143 + * Controls the mock `ComposioClientSingleton`'s `toolRouter.session.*` methods.
144 + * Each method can be overridden individually; defaults are provided for all.
145 + *
146 + * When `toolsExecutor` is also set, its mock takes precedence for `tools execute`
147 + * (the Tool Router mock is still used by `toolkits list`, `toolkits info`, etc.).
148 + */
149 + toolRouter?: {
150 + /** Override `session.create`. Receives the create params. */
151 + create?: (params: SessionCreateParams) => Promise<SessionCreateResponse>;
152 + /** Override `session.execute`. Receives sessionId and params. */
153 + execute?: (sessionId: string, params: SessionExecuteParams) => Promise<SessionExecuteResponse>;
154 + /** Override `session.executeMeta`. Receives sessionId and params. */
155 + executeMeta?: (
156 + sessionId: string,
157 + params: SessionExecuteMetaParams
158 + ) => Promise<SessionExecuteMetaResponse>;
159 + /** Override `session.link`. Receives sessionId and params. */
160 + link?: (sessionId: string, params: SessionLinkParams) => Promise<SessionLinkResponse>;
161 + /** Override `session.toolkits`. Receives sessionId and optional params. */
162 + toolkits?: (
163 + sessionId: string,
164 + params?: SessionToolkitsParams | null
165 + ) => Promise<SessionToolkitsResponse>;
166 + };
167 }
168
169 /**
@@ -676,25 +722,6 @@ export const TestLayer = (input?: TestLiveInput) =>
722 Layer.mergeAll(BunFileSystem.layer, FetchHttpClient.layer)
723 );
724
679 - const ToolsExecutorTest = Layer.succeed(
680 - ToolsExecutor,
681 - ToolsExecutor.of({
682 - execute: (slug, params) => {
683 - if (input?.toolsExecutor?.failWith) {
684 - return Effect.fail(input.toolsExecutor.failWith);
685 - }
686 - if (input?.toolsExecutor?.respondWith) {
687 - return Effect.succeed(input.toolsExecutor.respondWith);
688 - }
689 - return Effect.succeed({
690 - data: { slug, params },
691 - error: null,
692 - successful: true,
693 - });
694 - },
695 - })
696 - );
697 -
725 const StdinTest = Layer.succeed(
726 Stdin,
727 Stdin.of({
@@ -703,6 +730,127 @@ export const TestLayer = (input?: TestLiveInput) =>
730 })
731 );
732
733 + // --- Tool Router mock (ComposioClientSingleton) ---
734 + // Provides a fake `@composio/client` Composio instance with configurable
735 + // `toolRouter.session.*` methods. Each method has a sensible default that
736 + // can be overridden per-test via `input.toolRouter.<method>`.
737 +
738 + const toolRouterOverrides = input?.toolRouter;
739 +
740 + const defaultToolkitsHandler = async (
741 + _sessionId: string,
742 + params?: SessionToolkitsParams | null
743 + ): Promise<SessionToolkitsResponse> => {
744 + let results: SessionToolkitsResponse['items'] = toolkitsData.toolkits.map(t => ({
745 + slug: t.slug,
746 + name: t.name,
747 + meta: { description: t.meta.description, logo: '' },
748 + is_no_auth: t.no_auth ?? false,
749 + enabled: true,
750 + connected_account: null,
751 + composio_managed_auth_schemes: [...(t.composio_managed_auth_schemes ?? [])],
752 + }));
753 +
754 + if (params?.search) {
755 + const q = params.search.toLowerCase();
756 + results = results.filter(
757 + t =>
758 + t.name.toLowerCase().includes(q) ||
759 + t.slug.toLowerCase().includes(q) ||
760 + t.meta.description.toLowerCase().includes(q)
761 + );
762 + }
763 +
764 + if (params?.toolkits) {
765 + const slugSet = new Set(params.toolkits.map(s => s.toLowerCase()));
766 + results = results.filter(t => slugSet.has(t.slug.toLowerCase()));
767 + }
768 +
769 + const limit = params?.limit ?? 1000;
770 + const items = results.slice(0, limit);
771 + return {
772 + items,
773 + current_page: 1,
774 + total_items: results.length,
775 + total_pages: Math.ceil(results.length / limit),
776 + next_cursor: null,
777 + };
778 + };
779 +
780 + const mockComposioClient = {
781 + toolRouter: {
782 + session: {
783 + create:
784 + toolRouterOverrides?.create ??
785 + (async (params: SessionCreateParams) => ({
786 + session_id: 'trs_test_session',
787 + config: { user_id: params.user_id },
788 + mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
789 + tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MANAGE_CONNECTIONS'],
790 + })),
791 + execute:
792 + toolRouterOverrides?.execute ??
793 + (async (_sessionId: string, params: SessionExecuteParams) => ({
794 + data: { tool_slug: params.tool_slug, arguments: params.arguments },
795 + error: null,
796 + log_id: 'log_test',
797 + })),
798 + executeMeta:
799 + toolRouterOverrides?.executeMeta ??
800 + (async (_sessionId: string, params: SessionExecuteMetaParams) => ({
801 + data: { slug: params.slug, arguments: params.arguments },
802 + error: null,
803 + log_id: 'log_test',
804 + })),
805 + link:
806 + toolRouterOverrides?.link ??
807 + (async () => ({
808 + connected_account_id: 'con_test_link',
809 + link_token: 'lt_test_token',
810 + redirect_url: 'https://app.composio.dev/link?token=lt_test_token',
811 + })),
812 + toolkits: toolRouterOverrides?.toolkits ?? defaultToolkitsHandler,
813 + tools: async () => ({
814 + items: [],
815 + }),
816 + },
817 + },
818 + };
819 +
820 + const ComposioClientSingletonTest = Layer.succeed(
821 + ComposioClientSingleton,
822 + new ComposioClientSingleton({
823 + get: Effect.fn(function* () {
824 + return mockComposioClient as any;
825 + }),
826 + })
827 + );
828 +
829 + // --- ToolsExecutor ---
830 + // When `input.toolsExecutor` is set, use a canned mock (bypasses Tool Router).
831 + // Otherwise, use the real ToolsExecutorLive which flows through the mock ComposioClientSingleton.
832 + const ToolsExecutorTest = input?.toolsExecutor
833 + ? Layer.succeed(
834 + ToolsExecutor,
835 + ToolsExecutor.of({
836 + execute: (slug, params) => {
837 + if (input.toolsExecutor!.failWith) {
838 + return Effect.fail(input.toolsExecutor!.failWith);
839 + }
840 + if (input.toolsExecutor!.respondWith) {
841 + return Effect.succeed(input.toolsExecutor!.respondWith);
842 + }
843 + return Effect.succeed({
844 + data: { slug, params },
845 + error: null,
846 + successful: true,
847 + logId: 'log_test',
848 + });
849 + },
850 + })
851 + )
852 + : Layer.provide(ToolsExecutorLive, ComposioClientSingletonTest);
853 +
854 const CliConfigLive = CliConfig.layer(ComposioCliConfig);
855
856 const _console = yield* MockConsole.make;
@@ -715,6 +863,7 @@ export const TestLayer = (input?: TestLiveInput) =>
863 ComposioUserContextTest,
864 ComposioSessionRepositoryTest,
865 TriggersRealtimeTest,
866 + ComposioClientSingletonTest,
867 ComposioToolkitsRepositoryTest,
868 EnvLangDetector.Default,
869 JsPackageManagerDetector.Default,
ts/packages/cli/test/src/commands/$default.cmd.test.ts
+4 -4
@@ -86,9 +86,9 @@ describe('CLI: composio', () => {
86
87 - toolkits Discover and inspect Composio toolkits.
88
89 - - toolkits list [--query text] [--limit integer] List available toolkits.
89 + - toolkits list [--query text] [--limit integer] [--connected] [--user-id text] List available toolkits with connection status.
90
91 - - toolkits info [<slug>] View details of a specific toolkit.
91 + - toolkits info [--user-id text] [<slug>] View details of a specific toolkit.
92
93 - toolkits search [--limit integer] <query> Search toolkits by use case.
94
@@ -100,7 +100,7 @@ describe('CLI: composio', () => {
100
101 - tools search [--toolkits text] [--limit integer] <query> Search tools by use case.
102
103 - - tools execute [(-d, --data text)] [--user-id text] [--connected-account-id text] [--toolkit-version text] <slug> Execute a tool by slug with JSON arguments.
103 + - tools execute [(-d, --data text)] [--user-id text] <slug> Execute a tool by slug with JSON arguments.
104
105 - auth-configs View and manage Composio auth configs.
106
@@ -122,7 +122,7 @@ describe('CLI: composio', () => {
122
123 - connected-accounts delete [(-y, --yes)] [<id>] Delete a connected account.
124
125 - - connected-accounts link --auth-config text [--user-id text] [--no-browser] Link an external account via OAuth redirect.
125 + - connected-accounts link [--auth-config text] [--user-id text] [--no-browser] [<toolkit>] Link an external account via OAuth redirect.
126
127 - triggers Inspect and subscribe to trigger events.
128
ts/packages/cli/test/src/commands/toolkits/toolkits.info.cmd.test.ts
+27 -19
@@ -23,6 +23,23 @@ const testToolkits: Toolkits = [
23 triggers_count: 2,
24 },
25 },
26 + {
27 + name: 'Code Interpreter',
28 + slug: 'codeinterpreter',
29 + auth_schemes: [],
30 + composio_managed_auth_schemes: [],
31 + is_local_toolkit: false,
32 + no_auth: true,
33 + meta: {
34 + description: 'Execute code in a sandboxed environment',
35 + categories: [],
36 + created_at: new Date('2024-05-03T11:44:32.061Z') as any,
37 + updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
38 + available_versions: [],
39 + tools_count: 1,
40 + triggers_count: 0,
41 + },
42 + },
43 ];
44
45 const detailedToolkits: ToolkitDetailed[] = [
@@ -116,7 +133,7 @@ describe('CLI: composio toolkits info', () => {
133 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
134 '[Given] valid slug "gmail"',
135 it => {
119 - it.scoped('shows detailed info with auth schemes', () =>
136 + it.scoped('shows detailed info with connection status', () =>
137 Effect.gen(function* () {
138 yield* cli(['toolkits', 'info', 'gmail']);
139 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -125,13 +142,8 @@ describe('CLI: composio toolkits info', () => {
142 expect(output).toContain('Gmail');
143 expect(output).toContain('gmail');
144 expect(output).toContain('Email service to send and receive emails');
128 - expect(output).toContain('20250909');
129 - expect(output).toContain('3 available');
130 - expect(output).toContain('OAUTH2');
131 - expect(output).toContain('BEARER_TOKEN');
132 - expect(output).toContain('apiKey');
133 - expect(output).toContain('AuthConfig creation');
134 - expect(output).toContain('Connected Account creation');
145 + // Connection status
146 + expect(output).toContain('Not connected');
147 })
148 );
149 }
@@ -140,15 +152,13 @@ describe('CLI: composio toolkits info', () => {
152 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
153 '[Given] toolkit with no_auth=true',
154 it => {
143 - it.scoped('shows "No authentication required"', () =>
155 + it.scoped('shows "no auth"', () =>
156 Effect.gen(function* () {
157 yield* cli(['toolkits', 'info', 'codeinterpreter']);
158 const lines = yield* MockConsole.getLines({ stripAnsi: true });
159 const output = lines.join('\n');
160
161 expect(output).toContain('Code Interpreter');
150 - expect(output).toContain('Latest Version:');
151 - expect(output).toContain('-');
162 expect(output).toContain('No authentication required');
163 })
164 );
@@ -160,11 +170,11 @@ describe('CLI: composio toolkits info', () => {
170 it => {
171 it.scoped('shows error', () =>
172 Effect.gen(function* () {
163 - const result = yield* cli(['toolkits', 'info', 'gmal']).pipe(Effect.either);
173 + yield* cli(['toolkits', 'info', 'gmal']).pipe(Effect.either);
174 const lines = yield* MockConsole.getLines({ stripAnsi: true });
175 const output = lines.join('\n');
176
167 - expect(output).toContain('Failed to fetch toolkit "gmal"');
177 + expect(output).toContain('Toolkit "gmal" not found');
178 })
179 );
180 }
@@ -173,16 +183,14 @@ describe('CLI: composio toolkits info', () => {
183 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
184 '[Given] invalid slug with substring match',
185 it => {
176 - it.scoped('shows error with suggestion', () =>
186 + it.scoped('shows error with hint', () =>
187 Effect.gen(function* () {
178 - // "gma" is a substring of "gmail", so the mock will find suggestions
179 - const result = yield* cli(['toolkits', 'info', 'gma']).pipe(Effect.either);
188 + yield* cli(['toolkits', 'info', 'gma']).pipe(Effect.either);
189 const lines = yield* MockConsole.getLines({ stripAnsi: true });
190 const output = lines.join('\n');
191
183 - expect(output).toContain('Failed to fetch toolkit "gma"');
184 - expect(output).toContain('Did you mean?');
185 - expect(output).toContain('gmail');
192 + expect(output).toContain('Toolkit "gma" not found');
193 + expect(output).toContain('composio toolkits list');
194 })
195 );
196 }
ts/packages/cli/test/src/commands/toolkits/toolkits.list.cmd.test.ts
+2 -4
@@ -81,10 +81,8 @@ describe('CLI: composio toolkits list', () => {
81 expect(output).toContain('gmail');
82 expect(output).toContain('Slack');
83 expect(output).toContain('GitHub');
84 - // Version column
85 - expect(output).toContain('Version');
86 - expect(output).toContain('20250909');
87 - expect(output).toContain('20260101');
84 + // Connection status column
85 + expect(output).toContain('Connected');
86 expect(output).toContain('Listing 3 of 3 toolkits');
87 })
88 );
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+77 -87
@@ -2,7 +2,6 @@ import { describe, expect, layer } from '@effect/vitest';
2 import { vi, beforeEach, afterEach } from 'vitest';
3 import { ConfigProvider, Effect } from 'effect';
4 import { extendConfigProvider } from 'src/services/config';
5 -import { ComposioToolExecutionError } from '@composio/core';
5 import { ActionExecuteConnectedAccountNotFoundError } from 'src/services/tools-executor';
6 import * as redactModule from 'src/ui/redact';
7 import { cli, TestLive, MockConsole } from 'test/__utils__';
@@ -17,7 +16,10 @@ const parseLastJson = (lines: ReadonlyArray<string>) => {
16 if (!line) continue;
17 try {
18 return JSON.parse(line) as {
20 - data: { slug: string; params: Record<string, unknown> };
19 + successful: boolean;
20 + data: Record<string, unknown>;
21 + error: string | null;
22 + logId: string;
23 };
24 } catch {
25 // keep searching for the last JSON line
@@ -43,18 +45,18 @@ describe('CLI: composio tools execute', () => {
45 baseConfigProvider: testConfigProvider,
46 stdin: { isTTY: true, data: '' },
47 })
46 - )('[Given] -d inline JSON [Then] executes with defaults', it => {
47 - it.scoped('executes with defaults', () =>
48 + )('[Given] -d inline JSON [Then] executes via Tool Router with defaults', it => {
49 + it.scoped('executes via Tool Router with defaults', () =>
50 Effect.gen(function* () {
51 yield* cli(['tools', 'execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient":"a"}']);
52 const lines = yield* MockConsole.getLines({ stripAnsi: true });
53 const output = parseLastJson(lines);
52 - const params = output.data.params as Record<string, unknown>;
54
54 - expect(output.data.slug).toBe('GMAIL_SEND_EMAIL');
55 - expect(params.userId).toBe('default');
56 - expect(params.arguments).toEqual({ recipient: 'a' });
57 - expect(params.dangerouslySkipVersionCheck).toBe(true);
55 + // Response flows through real ToolsExecutorLive → mock session.execute
56 + expect(output.successful).toBe(true);
57 + expect(output.data.tool_slug).toBe('GMAIL_SEND_EMAIL');
58 + expect(output.data.arguments).toEqual({ recipient: 'a' });
59 + expect(output.logId).toBe('log_test');
60 })
61 );
62 });
@@ -70,9 +72,10 @@ describe('CLI: composio tools execute', () => {
72 yield* cli(['tools', 'execute', 'GITHUB_GET_REPOS']);
73 const lines = yield* MockConsole.getLines({ stripAnsi: true });
74 const output = parseLastJson(lines);
73 - const params = output.data.params as Record<string, unknown>;
75
75 - expect(params.arguments).toEqual({ owner: 'composio' });
76 + expect(output.successful).toBe(true);
77 + expect(output.data.tool_slug).toBe('GITHUB_GET_REPOS');
78 + expect(output.data.arguments).toEqual({ owner: 'composio' });
79 })
80 );
81 });
@@ -88,8 +91,8 @@ describe('CLI: composio tools execute', () => {
91 }),
92 },
93 })
91 - )('[Given] connected account not found slug [Then] prints tips', it => {
92 - it.scoped('prints connected account tips', () =>
94 + )('[Given] connected account not found slug (legacy) [Then] prints tips', it => {
95 + it.scoped('prints connected account tips for legacy slug', () =>
96 Effect.gen(function* () {
97 yield* cli([
98 'tools',
@@ -108,32 +111,75 @@ describe('CLI: composio tools execute', () => {
111 );
112 });
113
114 + // --- Tool Router error path (flows through real ToolsExecutorLive) ---
115 +
116 + layer(
117 + TestLive({
118 + baseConfigProvider: testConfigProvider,
119 + stdin: { isTTY: true, data: '' },
120 + toolRouter: {
121 + execute: async () => {
122 + throw Object.assign(new Error("No active connection found for toolkit(s) 'gmail'"), {
123 + error: {
124 + message: "No active connection found for toolkit(s) 'gmail' in this session",
125 + code: 4302,
126 + slug: 'ToolRouterV2_NoActiveConnection',
127 + status: 400,
128 + request_id: 'test-request-id',
129 + },
130 + });
131 + },
132 + },
133 + })
134 + )('[Given] Tool Router NoActiveConnection error [Then] prints connection tips', it => {
135 + it.scoped('prints connection tips with toolkit name derived from tool slug', () =>
136 + Effect.gen(function* () {
137 + yield* cli([
138 + 'tools',
139 + 'execute',
140 + 'GMAIL_CREATE_EMAIL_DRAFT',
141 + '-d',
142 + '{"recipient":"to@example.com"}',
143 + ]).pipe(Effect.catchAll(() => Effect.void));
144 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
145 + const output = lines.join('\n');
146 +
147 + expect(output).toContain('No active connection');
148 + expect(output).toContain('Tips');
149 + expect(output).toContain('composio connected-accounts link gmail');
150 + })
151 + );
152 + });
153 +
154 layer(
155 TestLive({
156 baseConfigProvider: testConfigProvider,
157 stdin: { isTTY: true, data: '' },
158 + toolRouter: {
159 + execute: async (_sessionId, params) => ({
160 + data: { tool_slug: params.tool_slug, custom: 'response' },
161 + error: null,
162 + log_id: 'log_custom',
163 + }),
164 + },
165 })
116 - )('[Given] --version override [Then] passes version and no auto-skip', it => {
117 - it.scoped('passes version and no auto-skip', () =>
166 + )('[Given] custom Tool Router execute mock [Then] returns custom response', it => {
167 + it.scoped('flows through real ToolsExecutorLive with custom mock', () =>
168 Effect.gen(function* () {
169 yield* cli([
170 'tools',
171 'execute',
122 - 'GITHUB_GET_REPOS',
172 + 'GITHUB_STAR_REPO',
173 '-d',
124 - '{"owner":"composio"}',
125 - '--user-id',
126 - 'user_123',
127 - '--toolkit-version',
128 - '20250909_00',
174 + '{"owner":"composio","repo":"composio"}',
175 ]);
176 const lines = yield* MockConsole.getLines({ stripAnsi: true });
177 const output = parseLastJson(lines);
132 - const params = output.data.params as Record<string, unknown>;
178
134 - expect(params.userId).toBe('user_123');
135 - expect(params.version).toBe('20250909_00');
136 - expect('dangerouslySkipVersionCheck' in params).toBe(false);
179 + expect(output.successful).toBe(true);
180 + expect(output.data.tool_slug).toBe('GITHUB_STAR_REPO');
181 + expect(output.data.custom).toBe('response');
182 + expect(output.logId).toBe('log_custom');
183 })
184 );
185 });
@@ -144,12 +190,9 @@ describe('CLI: composio tools execute', () => {
190 stdin: { isTTY: true, data: '' },
191 toolsExecutor: {
192 failWith: {
147 - error: new ComposioToolExecutionError(
148 - 'Error executing the tool GMAIL_CREATE_EMAIL_DRAFT',
149 - {
150 - possibleFixes: ['Ensure the tool slug is correct'],
151 - }
152 - ),
193 + error: {
194 + message: 'Error executing the tool GMAIL_CREATE_EMAIL_DRAFT',
195 + },
196 },
197 },
198 })
@@ -167,8 +210,6 @@ describe('CLI: composio tools execute', () => {
210 const output = lines.join('\n');
211
212 expect(output).toContain('Error executing the tool GMAIL_CREATE_EMAIL_DRAFT');
170 - expect(output).toContain('Possible fixes');
171 - expect(output).toContain('Ensure the tool slug is correct');
213 })
214 );
215 });
@@ -248,6 +289,7 @@ describe('CLI: composio tools execute', () => {
289 data: {},
290 error: 'Tool execution failed',
291 successful: false,
292 + logId: '',
293 },
294 },
295 })
@@ -268,7 +310,8 @@ describe('CLI: composio tools execute', () => {
310 expect(output).not.toContain('Executing tool');
311 expect(output).toContain('Execution failed');
312 expect(output).toContain('Tool execution failed');
271 - expect(output).not.toContain('logId');
313 + // logId is empty, so the spinner line should not show "(logId: ...)"
314 + expect(output).not.toContain('(logId:');
315 })
316 );
317 });
@@ -383,59 +426,6 @@ describe('CLI: composio tools execute', () => {
426 );
427 });
428
386 - layer(
387 - TestLive({
388 - baseConfigProvider: testConfigProvider,
389 - stdin: { isTTY: true, data: '' },
390 - })
391 - )('[Given] --toolkit-version latest [Then] sets dangerouslySkipVersionCheck', it => {
392 - it.scoped('skips version check for "latest"', () =>
393 - Effect.gen(function* () {
394 - yield* cli([
395 - 'tools',
396 - 'execute',
397 - 'GITHUB_GET_REPOS',
398 - '-d',
399 - '{"owner":"composio"}',
400 - '--toolkit-version',
401 - 'latest',
402 - ]);
403 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
404 - const output = parseLastJson(lines);
405 - const params = output.data.params as Record<string, unknown>;
406 -
407 - expect(params.version).toBe('latest');
408 - expect(params.dangerouslySkipVersionCheck).toBe(true);
409 - })
410 - );
411 - });
412 -
413 - layer(
414 - TestLive({
415 - baseConfigProvider: testConfigProvider,
416 - stdin: { isTTY: true, data: '' },
417 - })
418 - )('[Given] --connected-account-id [Then] passes it through', it => {
419 - it.scoped('forwards connected account id', () =>
420 - Effect.gen(function* () {
421 - yield* cli([
422 - 'tools',
423 - 'execute',
424 - 'GMAIL_SEND_EMAIL',
425 - '-d',
426 - '{"recipient":"a"}',
427 - '--connected-account-id',
428 - 'con_abc123',
429 - ]);
430 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
431 - const output = parseLastJson(lines);
432 - const params = output.data.params as Record<string, unknown>;
433 -
434 - expect(params.connectedAccountId).toBe('con_abc123');
435 - })
436 - );
437 - });
438 -
429 // --- CI redaction tests ---
430
431 layer(