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

next
ts 246 lines 8.4 KB
Raw
1 import { Data, Effect } from 'effect';
2 import { ExpectedFailure } from 'src/effects/expected-failure';
3 import colors from 'picocolors';
4 import { S_BAR, unicodeOr } from '@clack/prompts';
5 import { TerminalUI } from 'src/services/terminal-ui';
6 import type { ComposioToolkitsRepositoryShape } from 'src/services/composio-clients';
7 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
8 import type { InvalidVersionDetail } from 'src/services/toolkit-version-validation';
9 import type { ToolkitVersionOverrides } from './toolkit-version-overrides';
10
11 /**
12 * Custom error class for invalid toolkit versions that preserves structured data.
13 * This allows consumers to access both the human-readable message and the machine-readable data.
14 */
15 export class InvalidToolkitVersionsValidationError extends Data.TaggedError(
16 'effects/InvalidToolkitVersionsValidationError'
17 )<{
18 readonly invalidVersions: ReadonlyArray<InvalidVersionDetail>;
19 readonly message: string;
20 }> {
21 constructor(invalidVersions: ReadonlyArray<InvalidVersionDetail>) {
22 super({
23 invalidVersions,
24 message: formatInvalidVersionsError(invalidVersions),
25 });
26 }
27
28 get [ExpectedFailure]() {
29 return true;
30 }
31
32 /**
33 * Returns a JSON-serializable representation of the error for programmatic access.
34 */
35 toJSON(): { error: string; invalidVersions: ReadonlyArray<InvalidVersionDetail> } {
36 return {
37 error: 'InvalidToolkitVersionsValidationError',
38 invalidVersions: this.invalidVersions,
39 };
40 }
41 }
42
43 export class ToolkitVersionValidationError extends Data.TaggedError(
44 'effects/ToolkitVersionValidationError'
45 )<{
46 readonly cause?: unknown;
47 readonly message: string;
48 readonly reason: 'invalid-toolkit' | 'request' | 'decode' | 'client-unavailable';
49 }> {
50 /** Only an override naming an unknown toolkit; request, decoding, and client failures are defects. */
51 get [ExpectedFailure]() {
52 return this.reason === 'invalid-toolkit';
53 }
54 }
55
56 const MAX_VERSIONS_TO_SHOW = 5;
57 const S_CORNER_BOTTOM_LEFT = unicodeOr('╰', '+');
58 const S_STEP_ERROR = unicodeOr('▲', 'x');
59
60 /**
61 * Formats an InvalidToolkitVersionsError into a user-friendly error message.
62 *
63 * NOTE: We avoid using `: ` (colon-space) in the error message because effect-errors
64 * splits on that pattern and converts the result to an array, which then renders
65 * with commas instead of colons when converted back to string.
66 */
67 export function formatInvalidVersionsError(
68 invalidVersions: ReadonlyArray<InvalidVersionDetail>
69 ): string {
70 const lines: string[] = [];
71
72 // Header
73 lines.push(
74 `${colors.red(S_STEP_ERROR)} ${colors.red('Invalid toolkit version override')}${invalidVersions.length > 1 ? 's' : ''}`
75 );
76 lines.push('');
77
78 for (let i = 0; i < invalidVersions.length; i++) {
79 const { toolkit, requestedVersion, availableVersions } = invalidVersions[i];
80 const isLast = i === invalidVersions.length - 1;
81 const connector = isLast ? S_CORNER_BOTTOM_LEFT : S_BAR;
82
83 // Toolkit header with version
84 lines.push(
85 `${colors.gray(connector)} ${colors.cyan(toolkit.toUpperCase())} ${colors.dim('→')} version ${colors.yellow(`"${requestedVersion}"`)} ${colors.red('not found')}`
86 );
87
88 // Available versions (use → instead of : to avoid effect-errors split issue)
89 if (availableVersions.length === 0) {
90 lines.push(
91 `${colors.gray(isLast ? ' ' : S_BAR)} ${colors.dim('No versions available (toolkit may not support versioning)')}`
92 );
93 } else {
94 const versionsToShow = availableVersions.slice(0, MAX_VERSIONS_TO_SHOW);
95 const remaining = availableVersions.length - MAX_VERSIONS_TO_SHOW;
96
97 let versionList = versionsToShow.map(v => colors.green(v)).join(colors.dim(', '));
98 if (remaining > 0) {
99 versionList += colors.dim(` (+${remaining} more)`);
100 }
101
102 lines.push(
103 `${colors.gray(isLast ? ' ' : S_BAR)} ${colors.dim('Available →')} ${versionList}`
104 );
105 }
106
107 // Tip (use → instead of : to avoid effect-errors split issue)
108 const envVarName = `COMPOSIO_TOOLKIT_VERSION_${toolkit.toUpperCase()}`;
109 lines.push(
110 `${colors.gray(isLast ? ' ' : S_BAR)} ${colors.dim('Tip →')} Use ${colors.cyan('"latest"')} or unset ${colors.cyan(envVarName)}`
111 );
112
113 // Add spacing between toolkits (except for the last one)
114 if (!isLast) {
115 lines.push(colors.gray(S_BAR));
116 }
117 }
118
119 return lines.join('\n');
120 }
121
122 /**
123 * Options for validateToolkitVersionOverrides
124 */
125 export interface ValidateVersionsOptions {
126 /** Map of toolkit slug to requested version */
127 readonly versionOverrides: ToolkitVersionOverrides;
128 /** Optional array of toolkit slugs to filter (from --toolkits flag) */
129 readonly toolkitSlugsFilter: ReadonlyArray<string> | null;
130 /** The ComposioToolkitsRepository client */
131 readonly client: ComposioToolkitsRepositoryShape;
132 }
133
134 /**
135 * Result of version validation
136 */
137 export interface ValidateVersionsResult {
138 /** The validated overrides (only includes relevant toolkits) */
139 readonly validatedOverrides: ToolkitVersionOverrides;
140 }
141
142 /**
143 * Validates toolkit version overrides before fetching data.
144 *
145 * This function should be called early in the generate command flow,
146 * before any tool/trigger data is fetched. It will:
147 * 1. Log detected version overrides
148 * 2. Validate versions against the API's available_versions
149 * 3. Warn about unused overrides (when --toolkits filter excludes them)
150 * 4. Fail with a descriptive error if any versions are invalid
151 *
152 * @example
153 * ```typescript
154 * const { validatedOverrides } = yield* validateToolkitVersionOverrides({
155 * versionOverrides,
156 * toolkitSlugsFilter,
157 * client,
158 * });
159 * ```
160 */
161 export const validateToolkitVersionOverrides = ({
162 versionOverrides,
163 toolkitSlugsFilter,
164 client,
165 }: ValidateVersionsOptions): Effect.Effect<
166 ValidateVersionsResult,
167 InvalidToolkitVersionsValidationError | ToolkitVersionValidationError,
168 TerminalUI
169 > =>
170 Effect.gen(function* () {
171 const ui = yield* TerminalUI;
172
173 // Skip if no overrides
174 if (versionOverrides.size === 0) {
175 return { validatedOverrides: versionOverrides };
176 }
177
178 // Log detected overrides
179 const overrideLines = [...versionOverrides]
180 .map(([toolkit, version]) => ` ${toolkit}: ${version}`)
181 .join('\n');
182 yield* ui.log.info(`Detected toolkit version overrides:\n${overrideLines}`);
183
184 const { validatedOverrides, warnings } = yield* client
185 .validateToolkitVersions(versionOverrides, toolkitSlugsFilter ?? undefined)
186 .pipe(
187 Effect.catchTag('services/InvalidToolkitVersionsError', error =>
188 Effect.fail(new InvalidToolkitVersionsValidationError(error.invalidVersions))
189 ),
190 Effect.catchTag('services/InvalidToolkitsError', error =>
191 Effect.fail(
192 new ToolkitVersionValidationError({
193 cause: error,
194 message:
195 `Invalid toolkit(s) in version overrides: ${error.invalidToolkits.join(', ')}. ` +
196 `Check that the toolkit slug is correct (e.g., COMPOSIO_TOOLKIT_VERSION_GMAIL, not COMPOSIO_TOOLKIT_VERSION_GMAL).`,
197 reason: 'invalid-toolkit',
198 })
199 )
200 ),
201 Effect.catchTag(CLIENT_API_ERROR_TAGS, error =>
202 Effect.fail(
203 new ToolkitVersionValidationError({
204 cause: error,
205 message: 'Failed to validate toolkit versions',
206 reason: 'request',
207 })
208 )
209 ),
210 Effect.catchTag('services/HttpDecodingError', error =>
211 Effect.fail(
212 new ToolkitVersionValidationError({
213 cause: error,
214 message: 'Failed to decode toolkit response',
215 reason: 'decode',
216 })
217 )
218 ),
219 Effect.catchTag('NoSuchElementError', () =>
220 Effect.fail(
221 new ToolkitVersionValidationError({
222 message: 'API client not initialized',
223 reason: 'client-unavailable',
224 })
225 )
226 ),
227 Effect.catchTag(
228 ['services/ComposioClientConfigurationError', '@composio/client/ConfigurationError'],
229 error =>
230 Effect.fail(
231 new ToolkitVersionValidationError({
232 cause: error,
233 message: error.message,
234 reason: 'client-unavailable',
235 })
236 )
237 )
238 );
239
240 // Log warnings for unused overrides
241 for (const warning of warnings) {
242 yield* ui.log.warn(`${warning}`);
243 }
244
245 return { validatedOverrides };
246 });