@devries-cameron20 / composio Mirror · read-only / commits / 3b41c475b
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, 02:00 UTC

feat(cli): add telemetry worker and improve tool execution UX (#2993)

## Summary - Add a detached analytics worker and richer CLI event metadata for commands, execute/search/link, run, and tool validation failures. - Expand `tools execute` and `run` flows with better input validation, schema refresh behavior, and clearer error handling. - Improve command UX across help text, hinting, hidden-debug cleanup, and consumer command behavior. - Update CLI tests and snapshots to cover the new telemetry and execution paths. ## Testing - `pnpm test -- ts/packages/cli/test/src/commands/run.cmd.test.ts` - `pnpm test -- ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts` - `pnpm test -- ts/packages/cli/test/src/services/command-hints.test.ts` - Not run: full repository build and lint --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

Rahul Tarak committed Mar 24, 2026 at 17:13 UTC 3b41c475b3672d0a99840186813c9991c5f64646
8 files changed +1393 -249
ts/packages/cli/src/analytics/dispatch.ts new
+365
@@ -0,0 +1,365 @@
1 +import fs from 'node:fs';
2 +import os from 'node:os';
3 +import path from 'node:path';
4 +import process from 'node:process';
5 +import { spawn } from 'node:child_process';
6 +import { Effect } from 'effect';
7 +import type { AnalyticsEnvelope, TrackEvent } from './types';
8 +import * as constants from 'src/constants';
9 +
10 +const INTERNAL_ANALYTICS_WORKER_FLAG = '__analytics-worker';
11 +const COMPOSIO_DIR = '.composio';
12 +const ANALYTICS_STATE_FILE_NAME = 'analytics.json';
13 +const CONSUMER_SHORT_TERM_CACHE_FILE_NAME = 'consumer-short-term-cache.json';
14 +const CLI_ANALYTICS_PATH = '/api/v3/cli/analytics';
15 +const TELEMETRY_DEBUG_ENV_VAR = 'COMPOSIO_CLI_TELEMETRY_DEBUG';
16 +
17 +const truthy = (value: string | undefined): boolean =>
18 + value === '1' || value === 'true' || value === 'yes' || value === 'on';
19 +
20 +const isTelemetryDebugEnabled = (): boolean => truthy(process.env[TELEMETRY_DEBUG_ENV_VAR]);
21 +
22 +const telemetryDebugLog = (label: string, payload: Record<string, unknown>) => {
23 + if (!isTelemetryDebugEnabled()) {
24 + return;
25 + }
26 +
27 + process.stderr.write(
28 + `[telemetry-debug] ${JSON.stringify(
29 + {
30 + label,
31 + ...payload,
32 + },
33 + null,
34 + 2
35 + )}\n`
36 + );
37 +};
38 +
39 +const analyticsDir = () => path.join(os.homedir(), COMPOSIO_DIR);
40 +const analyticsStatePath = () => path.join(analyticsDir(), ANALYTICS_STATE_FILE_NAME);
41 +const userConfigPath = () => path.join(analyticsDir(), constants.USER_CONFIG_FILE_NAME);
42 +const cacheDir = () =>
43 + process.env.COMPOSIO_CACHE_DIR?.trim() ||
44 + process.env.CACHE_DIR?.trim() ||
45 + path.join(os.homedir(), constants.USER_COMPOSIO_DIR);
46 +const consumerShortTermCachePath = () => path.join(cacheDir(), CONSUMER_SHORT_TERM_CACHE_FILE_NAME);
47 +
48 +type ConsumerShortTermCacheState = Record<
49 + string,
50 + {
51 + readonly probablyMyCliSessionsByCwdHash?: Record<
52 + string,
53 + {
54 + readonly id: string;
55 + readonly expiresAt: string;
56 + }
57 + >;
58 + }
59 +>;
60 +
61 +const ensureAnalyticsDir = () => {
62 + fs.mkdirSync(analyticsDir(), { recursive: true });
63 +};
64 +
65 +const encodeBase64Url = (value: string): string => {
66 + const bytes = new TextEncoder().encode(value);
67 + let binary = '';
68 + for (const byte of bytes) {
69 + binary += String.fromCharCode(byte);
70 + }
71 + return btoa(binary).replace(/\+/gu, '-').replace(/\//gu, '_').replace(/=+$/u, '');
72 +};
73 +
74 +const decodeBase64Url = (value: string): string => {
75 + const normalized = value.replace(/-/gu, '+').replace(/_/gu, '/');
76 + const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=');
77 + const binary = atob(padded);
78 + const bytes = Uint8Array.from(binary, char => char.charCodeAt(0));
79 + return new TextDecoder().decode(bytes);
80 +};
81 +
82 +const djb2Hash = (value: string): number => {
83 + let hash = 5381;
84 + for (let index = 0; index < value.length; index += 1) {
85 + hash = (hash * 33) ^ value.charCodeAt(index);
86 + }
87 + return Math.abs(hash >>> 0);
88 +};
89 +
90 +const hashString = (value: string): string => djb2Hash(value).toString(16).padStart(8, '0');
91 +
92 +const getOrCreateInstallId = (): string => {
93 + try {
94 + ensureAnalyticsDir();
95 + const filePath = analyticsStatePath();
96 + if (fs.existsSync(filePath)) {
97 + const raw = fs.readFileSync(filePath, 'utf8');
98 + const parsed = JSON.parse(raw) as { install_id?: unknown };
99 + if (typeof parsed.install_id === 'string' && parsed.install_id.length > 0) {
100 + return parsed.install_id;
101 + }
102 + }
103 + const installId = crypto.randomUUID();
104 + fs.writeFileSync(
105 + filePath,
106 + JSON.stringify(
107 + {
108 + install_id: installId,
109 + created_at: new Date().toISOString(),
110 + },
111 + null,
112 + 2
113 + ),
114 + 'utf8'
115 + );
116 + return installId;
117 + } catch {
118 + return crypto.randomUUID();
119 + }
120 +};
121 +
122 +const getHashedApiKeyDistinctId = (): string | null => {
123 + const envApiKey = process.env.COMPOSIO_USER_API_KEY?.trim();
124 + if (envApiKey) {
125 + return `user_${hashString(envApiKey)}`;
126 + }
127 +
128 + try {
129 + const raw = fs.readFileSync(userConfigPath(), 'utf8');
130 + const parsed = JSON.parse(raw) as { api_key?: unknown };
131 + if (typeof parsed.api_key === 'string' && parsed.api_key.trim().length > 0) {
132 + return `user_${hashString(parsed.api_key.trim())}`;
133 + }
134 + } catch {
135 + // Ignore user config read failures.
136 + }
137 +
138 + return null;
139 +};
140 +
141 +const getDistinctId = (): string => getHashedApiKeyDistinctId() ?? `anon_${getOrCreateInstallId()}`;
142 +
143 +const getUserApiKey = (): string | null => {
144 + const envApiKey = process.env.COMPOSIO_USER_API_KEY?.trim();
145 + if (envApiKey) {
146 + return envApiKey;
147 + }
148 +
149 + try {
150 + const raw = fs.readFileSync(userConfigPath(), 'utf8');
151 + const parsed = JSON.parse(raw) as { api_key?: unknown };
152 + if (typeof parsed.api_key === 'string' && parsed.api_key.trim().length > 0) {
153 + return parsed.api_key.trim();
154 + }
155 + } catch {
156 + // Ignore user config read failures.
157 + }
158 +
159 + return null;
160 +};
161 +
162 +const cwdHash = (cwd: string): string => djb2Hash(cwd).toString(36);
163 +
164 +const getCurrentCwdSessionId = (): string | undefined => {
165 + try {
166 + const raw = fs.readFileSync(consumerShortTermCachePath(), 'utf8');
167 + const parsed = JSON.parse(raw) as ConsumerShortTermCacheState;
168 + const currentCwdHash = cwdHash(process.cwd());
169 + const now = Date.now();
170 + let best: { id: string; expiresAtMs: number } | undefined;
171 +
172 + for (const entry of Object.values(parsed)) {
173 + const session = entry.probablyMyCliSessionsByCwdHash?.[currentCwdHash];
174 + if (!session?.id) continue;
175 + const expiresAtMs = Date.parse(session.expiresAt);
176 + if (!Number.isFinite(expiresAtMs) || expiresAtMs <= now) continue;
177 + if (!best || expiresAtMs > best.expiresAtMs) {
178 + best = { id: session.id, expiresAtMs };
179 + }
180 + }
181 +
182 + return best?.id;
183 + } catch {
184 + return undefined;
185 + }
186 +};
187 +
188 +const withCliSessionId = (event: TrackEvent): TrackEvent => {
189 + if (!event) return event;
190 + const cliSessionId = getCurrentCwdSessionId();
191 + if (!cliSessionId) return event;
192 + return {
193 + ...event,
194 + properties: {
195 + ...(event.properties ?? {}),
196 + cli_session_id: cliSessionId,
197 + },
198 + };
199 +};
200 +
201 +const readApiBaseUrl = (): string | null => {
202 + const envBaseUrl = process.env.COMPOSIO_BASE_URL?.trim();
203 + if (envBaseUrl) {
204 + return envBaseUrl.replace(/\/+$/u, '');
205 + }
206 +
207 + try {
208 + const raw = fs.readFileSync(userConfigPath(), 'utf8');
209 + const parsed = JSON.parse(raw) as { base_url?: unknown };
210 + if (typeof parsed.base_url === 'string' && parsed.base_url.trim().length > 0) {
211 + return parsed.base_url.trim().replace(/\/+$/u, '');
212 + }
213 + } catch {
214 + // Ignore user config read failures.
215 + }
216 +
217 + return null;
218 +};
219 +
220 +const getAnalyticsEndpoint = (): string | null => {
221 + const baseUrl = readApiBaseUrl();
222 + return baseUrl ? `${baseUrl}${CLI_ANALYTICS_PATH}` : null;
223 +};
224 +
225 +const shouldDisableAnalytics = (): boolean =>
226 + truthy(process.env.COMPOSIO_CLI_TELEMETRY_DISABLED) ||
227 + truthy(process.env.TELEMETRY_DISABLED) ||
228 + truthy(process.env.COMPOSIO_DISABLE_TELEMETRY) ||
229 + process.env.NODE_ENV === 'test' ||
230 + process.env.CI === 'true';
231 +
232 +const getWorkerSpawnArgs = (encodedPayload: string): { command: string; args: string[] } => {
233 + const maybeScriptPath = process.argv[1];
234 + const scriptPathLooksReal =
235 + typeof maybeScriptPath === 'string' &&
236 + maybeScriptPath.length > 0 &&
237 + fs.existsSync(maybeScriptPath) &&
238 + /\.(?:[cm]?[jt]s|mjs|mts|cts)$/u.test(maybeScriptPath);
239 +
240 + return scriptPathLooksReal
241 + ? {
242 + command: process.execPath,
243 + args: [maybeScriptPath, INTERNAL_ANALYTICS_WORKER_FLAG, encodedPayload],
244 + }
245 + : {
246 + command: process.execPath,
247 + args: [INTERNAL_ANALYTICS_WORKER_FLAG, encodedPayload],
248 + };
249 +};
250 +
251 +const captureToComposioAnalytics = async (envelope: AnalyticsEnvelope): Promise<void> => {
252 + const endpoint = getAnalyticsEndpoint();
253 + if (!endpoint || shouldDisableAnalytics()) {
254 + telemetryDebugLog('delivery_skipped', {
255 + reason: shouldDisableAnalytics() ? 'disabled' : 'missing_endpoint',
256 + endpoint,
257 + eventName: envelope.event,
258 + });
259 + return;
260 + }
261 +
262 + const userApiKey = getUserApiKey();
263 + const response = await fetch(endpoint, {
264 + method: 'POST',
265 + headers: {
266 + 'Content-Type': 'application/json',
267 + 'x-composio-analytics-source': 'cli',
268 + ...(userApiKey ? { 'x-user-api-key': userApiKey } : {}),
269 + },
270 + body: JSON.stringify(envelope),
271 + });
272 + const responseBody =
273 + !response.ok && isTelemetryDebugEnabled() ? await response.text() : undefined;
274 +
275 + telemetryDebugLog(response.ok ? 'delivery_succeeded' : 'delivery_failed', {
276 + endpoint,
277 + eventName: envelope.event,
278 + status: response.status,
279 + ok: response.ok,
280 + responseBody: responseBody?.slice(0, 1000),
281 + });
282 +};
283 +
284 +export const trackCliEvent = (event: TrackEvent): void => {
285 + const endpoint = getAnalyticsEndpoint();
286 + if (!event) {
287 + return;
288 + }
289 +
290 + if (shouldDisableAnalytics() || !endpoint) {
291 + telemetryDebugLog('skip', {
292 + reason: shouldDisableAnalytics() ? 'disabled' : 'missing_endpoint',
293 + eventName: event.name,
294 + endpoint,
295 + });
296 + return;
297 + }
298 +
299 + try {
300 + const enrichedEvent = withCliSessionId(event);
301 + if (!enrichedEvent) {
302 + return;
303 + }
304 + const installId = getOrCreateInstallId();
305 + const distinctId = getDistinctId();
306 + const envelope: AnalyticsEnvelope = {
307 + event: enrichedEvent.name,
308 + ...(enrichedEvent.properties ? { properties: enrichedEvent.properties } : {}),
309 + sentAt: new Date().toISOString(),
310 + source: 'cli',
311 + distinctId,
312 + installId,
313 + };
314 + telemetryDebugLog('enqueue', {
315 + endpoint,
316 + envelope,
317 + });
318 + const encodedPayload = encodeBase64Url(JSON.stringify(envelope));
319 + const { command, args } = getWorkerSpawnArgs(encodedPayload);
320 + const child = spawn(command, args, {
321 + detached: true,
322 + stdio: isTelemetryDebugEnabled() ? ['ignore', 'ignore', 'inherit'] : 'ignore',
323 + env: {
324 + ...process.env,
325 + COMPOSIO_CLI_ANALYTICS_WORKER: '1',
326 + },
327 + });
328 + child.unref();
329 + } catch {
330 + // Analytics must never break CLI execution.
331 + }
332 +};
333 +
334 +export const trackCliEventEffect = (event: TrackEvent) => Effect.sync(() => trackCliEvent(event));
335 +
336 +const getAnalyticsWorkerFlagIndex = (argv: ReadonlyArray<string>): number =>
337 + argv.findIndex(token => token === INTERNAL_ANALYTICS_WORKER_FLAG);
338 +
339 +export const isAnalyticsWorkerInvocation = (argv: ReadonlyArray<string>): boolean =>
340 + getAnalyticsWorkerFlagIndex(argv) >= 0;
341 +
342 +export const runAnalyticsWorkerFromArgv = async (argv: ReadonlyArray<string>): Promise<void> => {
343 + const flagIndex = getAnalyticsWorkerFlagIndex(argv);
344 + const encodedPayload = flagIndex >= 0 ? argv[flagIndex + 1] : undefined;
345 + if (!encodedPayload) {
346 + return;
347 + }
348 +
349 + try {
350 + const decoded = decodeBase64Url(encodedPayload);
351 + const envelope = JSON.parse(decoded) as AnalyticsEnvelope;
352 + if (typeof envelope?.event !== 'string' || envelope.event.length === 0) {
353 + return;
354 + }
355 + await captureToComposioAnalytics(envelope);
356 + } catch (error) {
357 + telemetryDebugLog('delivery_error', {
358 + error:
359 + error instanceof Error
360 + ? { name: error.name, message: error.message }
361 + : { message: String(error) },
362 + });
363 + // Analytics must never break CLI execution.
364 + }
365 +};
ts/packages/cli/src/analytics/events.ts new
+581
@@ -0,0 +1,581 @@
1 +import type { CliCommandTelemetryContext, TrackEvent } from './types';
2 +import { ToolInputValidationError } from 'src/services/tool-input-validation';
3 +import { toolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug';
4 +
5 +export const CLI_ANALYTICS_EVENTS = {
6 + CLI_COMMAND_INVOKED: 'CLI_COMMAND_INVOKED',
7 + CLI_COMMAND_SUCCEEDED: 'CLI_COMMAND_SUCCEEDED',
8 + CLI_COMMAND_FAILED: 'CLI_COMMAND_FAILED',
9 + CLI_EXECUTE_INVOKED: 'CLI_EXECUTE_INVOKED',
10 + CLI_EXECUTE_SUCCEEDED: 'CLI_EXECUTE_SUCCEEDED',
11 + CLI_EXECUTE_FAILED: 'CLI_EXECUTE_FAILED',
12 + CLI_SEARCH_INVOKED: 'CLI_SEARCH_INVOKED',
13 + CLI_SEARCH_SUCCEEDED: 'CLI_SEARCH_SUCCEEDED',
14 + CLI_SEARCH_FAILED: 'CLI_SEARCH_FAILED',
15 + CLI_LINK_INVOKED: 'CLI_LINK_INVOKED',
16 + CLI_LINK_SUCCEEDED: 'CLI_LINK_SUCCEEDED',
17 + CLI_LINK_FAILED: 'CLI_LINK_FAILED',
18 + CLI_LOGIN_INVOKED: 'CLI_LOGIN_INVOKED',
19 + CLI_LOGIN_SUCCEEDED: 'CLI_LOGIN_SUCCEEDED',
20 + CLI_LOGIN_FAILED: 'CLI_LOGIN_FAILED',
21 + CLI_LOGOUT_INVOKED: 'CLI_LOGOUT_INVOKED',
22 + CLI_LOGOUT_SUCCEEDED: 'CLI_LOGOUT_SUCCEEDED',
23 + CLI_LOGOUT_FAILED: 'CLI_LOGOUT_FAILED',
24 + CLI_PROXY_INVOKED: 'CLI_PROXY_INVOKED',
25 + CLI_PROXY_SUCCEEDED: 'CLI_PROXY_SUCCEEDED',
26 + CLI_PROXY_FAILED: 'CLI_PROXY_FAILED',
27 + CLI_RUN_INVOKED: 'CLI_RUN_INVOKED',
28 + CLI_RUN_SUCCEEDED: 'CLI_RUN_SUCCEEDED',
29 + CLI_RUN_FAILED: 'CLI_RUN_FAILED',
30 + CLI_TOOL_INVOCATION_VALIDATION_FAILED: 'CLI_TOOL_INVOCATION_VALIDATION_FAILED',
31 + CLI_TOOL_INVOCATION_TOOL_NOT_FOUND: 'CLI_TOOL_INVOCATION_TOOL_NOT_FOUND',
32 + CLI_TOOL_INVOCATION_FAILED: 'CLI_TOOL_INVOCATION_FAILED',
33 +} as const;
34 +
35 +const KNOWN_COMMAND_TOKENS = new Set([
36 + 'version',
37 + 'upgrade',
38 + 'whoami',
39 + 'login',
40 + 'logout',
41 + 'run',
42 + 'install',
43 + 'dev',
44 + 'generate',
45 + 'manage',
46 + 'tools',
47 + 'toolkits',
48 + 'toolkit',
49 + 'search',
50 + 'execute',
51 + 'link',
52 + 'proxy',
53 + 'artifacts',
54 + 'cwd',
55 + 'connected-accounts',
56 + 'auth-configs',
57 + 'triggers',
58 + 'logs',
59 + 'orgs',
60 + 'projects',
61 + 'info',
62 + 'list',
63 + 'create',
64 + 'delete',
65 + 'enable',
66 + 'disable',
67 + 'status',
68 + 'listen',
69 + 'switch',
70 + 'py',
71 + 'ts',
72 +]);
73 +
74 +const TOOL_NOT_FOUND_PATTERN = /\btool\b.*\bnot found\b/i;
75 +const getInvocationOrigin = (): string => process.env.COMPOSIO_CLI_INVOCATION_ORIGIN ?? 'cli';
76 +const getParentRunId = (): string | undefined => process.env.COMPOSIO_CLI_PARENT_RUN_ID;
77 +
78 +const extractCommandPath = (argv: ReadonlyArray<string>): string => {
79 + const commandTokens: string[] = [];
80 +
81 + for (const token of argv.slice(2)) {
82 + if (!token || token.startsWith('-') || !KNOWN_COMMAND_TOKENS.has(token)) {
83 + break;
84 + }
85 + commandTokens.push(token);
86 + }
87 +
88 + return commandTokens.length > 0 ? commandTokens.join(' ') : 'composio';
89 +};
90 +
91 +const extractFlagNames = (argv: ReadonlyArray<string>): ReadonlyArray<string> =>
92 + [
93 + ...new Set(
94 + argv
95 + .slice(2)
96 + .filter(token => token.startsWith('-'))
97 + .map(token => token.split('=')[0]!)
98 + ),
99 + ].sort();
100 +
101 +const argumentShape = (args: Record<string, unknown>) => {
102 + const keys = Object.keys(args).sort();
103 + return {
104 + argument_key_count: keys.length,
105 + argument_keys: keys.slice(0, 50),
106 + };
107 +};
108 +
109 +const extractIssueLocations = (issues: ReadonlyArray<string>): ReadonlyArray<string> =>
110 + [
111 + ...new Set(
112 + issues
113 + .map(issue => issue.match(/^([^:]+):/u)?.[1]?.trim())
114 + .filter((value): value is string => typeof value === 'string' && value.length > 0)
115 + ),
116 + ].slice(0, 20);
117 +
118 +const extractUnknownKeys = (issues: ReadonlyArray<string>): ReadonlyArray<string> =>
119 + [
120 + ...new Set(
121 + issues
122 + .map(issue => issue.match(/Unknown key "([^"]+)"/u)?.[1])
123 + .filter((value): value is string => typeof value === 'string' && value.length > 0)
124 + ),
125 + ].slice(0, 20);
126 +
127 +const errorNameOf = (error: unknown): string =>
128 + error instanceof Error && error.name ? error.name : 'UnknownError';
129 +
130 +const errorMessageOf = (error: unknown): string => {
131 + if (error instanceof Error && error.message) return error.message.slice(0, 500);
132 + if (typeof error === 'string') return error.slice(0, 500);
133 + return 'Unknown error';
134 +};
135 +
136 +const isFlagPresent = (argv: ReadonlyArray<string>, ...flags: string[]): boolean =>
137 + argv.slice(2).some(token => {
138 + if (flags.includes(token)) return true;
139 + return flags.some(flag => token.startsWith(`${flag}=`));
140 + });
141 +
142 +const getFlagValue = (argv: ReadonlyArray<string>, ...flags: string[]): string | undefined => {
143 + const args = argv.slice(2);
144 + for (let index = 0; index < args.length; index += 1) {
145 + const token = args[index];
146 + if (!token) continue;
147 +
148 + for (const flag of flags) {
149 + if (token === flag) {
150 + const next = args[index + 1];
151 + return next && !next.startsWith('-') ? next : undefined;
152 + }
153 + if (token.startsWith(`${flag}=`)) {
154 + return token.slice(flag.length + 1);
155 + }
156 + }
157 + }
158 + return undefined;
159 +};
160 +
161 +const getTrailingPositionals = (context: CliCommandTelemetryContext): ReadonlyArray<string> => {
162 + const commandTokenCount =
163 + context.commandPath === 'composio' ? 0 : context.commandPath.split(' ').length;
164 + const args = context.argv.slice(2 + commandTokenCount);
165 + const positionals: string[] = [];
166 +
167 + for (let index = 0; index < args.length; index += 1) {
168 + const token = args[index];
169 + if (!token) continue;
170 +
171 + if (token === '--') {
172 + break;
173 + }
174 +
175 + if (token.startsWith('-')) {
176 + const expectsValue = [
177 + '--data',
178 + '-d',
179 + '--toolkits',
180 + '--limit',
181 + '--user-id',
182 + '--project-name',
183 + '--auth-config',
184 + '--file',
185 + '-f',
186 + ].includes(token);
187 + if (expectsValue) {
188 + index += 1;
189 + }
190 + continue;
191 + }
192 +
193 + positionals.push(token);
194 + }
195 +
196 + return positionals;
197 +};
198 +
199 +const getExecuteCommandProperties = (context: CliCommandTelemetryContext) => {
200 + const slug = getTrailingPositionals(context)[0];
201 + return {
202 + source: 'cli',
203 + invocation_origin: getInvocationOrigin(),
204 + parent_run_id: getParentRunId(),
205 + parent_command: getParentRunId() ? 'run' : undefined,
206 + cli_version: context.cliVersion,
207 + command_path: context.commandPath,
208 + duration_ms: Date.now() - context.startedAt,
209 + surface: context.commandPath === 'execute' ? 'root' : 'manage',
210 + tool_slug: slug,
211 + tool_name: slug,
212 + toolkit_slug: typeof slug === 'string' ? toolkitFromToolSlug(slug) : undefined,
213 + dry_run: isFlagPresent(context.argv, '--dry-run'),
214 + get_schema: isFlagPresent(context.argv, '--get-schema'),
215 + has_data: isFlagPresent(context.argv, '--data', '-d'),
216 + skip_connection_check: isFlagPresent(context.argv, '--skip-connection-check'),
217 + skip_tool_params_check: isFlagPresent(context.argv, '--skip-tool-params-check'),
218 + no_verify: isFlagPresent(context.argv, '--no-verify'),
219 + };
220 +};
221 +
222 +const getSearchCommandProperties = (context: CliCommandTelemetryContext) => ({
223 + source: 'cli',
224 + invocation_origin: getInvocationOrigin(),
225 + parent_run_id: getParentRunId(),
226 + parent_command: getParentRunId() ? 'run' : undefined,
227 + cli_version: context.cliVersion,
228 + command_path: context.commandPath,
229 + duration_ms: Date.now() - context.startedAt,
230 + query: getTrailingPositionals(context)[0],
231 + search_query: getTrailingPositionals(context)[0],
232 + toolkits: getFlagValue(context.argv, '--toolkits'),
233 + limit: getFlagValue(context.argv, '--limit'),
234 +});
235 +
236 +const getLinkCommandProperties = (context: CliCommandTelemetryContext) => {
237 + const firstPositional = getTrailingPositionals(context)[0];
238 + return {
239 + source: 'cli',
240 + invocation_origin: getInvocationOrigin(),
241 + parent_run_id: getParentRunId(),
242 + parent_command: getParentRunId() ? 'run' : undefined,
243 + cli_version: context.cliVersion,
244 + command_path: context.commandPath,
245 + duration_ms: Date.now() - context.startedAt,
246 + toolkit: getFlagValue(context.argv, '--toolkit') ?? firstPositional,
247 + no_browser: isFlagPresent(context.argv, '--no-browser'),
248 + no_wait: isFlagPresent(context.argv, '--no-wait'),
249 + has_auth_config: isFlagPresent(context.argv, '--auth-config'),
250 + };
251 +};
252 +
253 +const getRunCommandProperties = (context: CliCommandTelemetryContext) => ({
254 + source: 'cli',
255 + invocation_origin: getInvocationOrigin(),
256 + run_id: context.runId,
257 + cli_version: context.cliVersion,
258 + command_path: context.commandPath,
259 + duration_ms: Date.now() - context.startedAt,
260 + debug: isFlagPresent(context.argv, '--debug'),
261 + dry_run: isFlagPresent(context.argv, '--dry-run'),
262 + skip_connection_check: isFlagPresent(context.argv, '--skip-connection-check'),
263 + skip_tool_params_check: isFlagPresent(context.argv, '--skip-tool-params-check'),
264 + no_verify: isFlagPresent(context.argv, '--no-verify'),
265 + file_mode: isFlagPresent(context.argv, '--file', '-f'),
266 + arg_count: Math.max(0, context.argv.length - 3),
267 +});
268 +
269 +const getLoginCommandProperties = (context: CliCommandTelemetryContext) => ({
270 + source: 'cli',
271 + invocation_origin: getInvocationOrigin(),
272 + cli_version: context.cliVersion,
273 + command_path: context.commandPath,
274 + duration_ms: Date.now() - context.startedAt,
275 + no_browser: isFlagPresent(context.argv, '--no-browser'),
276 + no_wait: isFlagPresent(context.argv, '--no-wait'),
277 + has_key: isFlagPresent(context.argv, '--key'),
278 + skip_org_picker: isFlagPresent(context.argv, '--yes', '-y'),
279 +});
280 +
281 +const getLogoutCommandProperties = (context: CliCommandTelemetryContext) => ({
282 + source: 'cli',
283 + invocation_origin: getInvocationOrigin(),
284 + cli_version: context.cliVersion,
285 + command_path: context.commandPath,
286 + duration_ms: Date.now() - context.startedAt,
287 +});
288 +
289 +const getProxyCommandProperties = (context: CliCommandTelemetryContext) => ({
290 + source: 'cli',
291 + invocation_origin: getInvocationOrigin(),
292 + cli_version: context.cliVersion,
293 + command_path: context.commandPath,
294 + duration_ms: Date.now() - context.startedAt,
295 + endpoint: getTrailingPositionals(context)[0],
296 + toolkit: getFlagValue(context.argv, '--toolkit', '-t'),
297 + method: getFlagValue(context.argv, '--method', '-X') ?? 'GET',
298 + has_data: isFlagPresent(context.argv, '--data', '-d'),
299 + header_count: context.argv.slice(2).filter(token => token === '--header' || token === '-H')
300 + .length,
301 + skip_connection_check: isFlagPresent(context.argv, '--skip-connection-check'),
302 +});
303 +
304 +const isExecuteCommand = (commandPath: string): boolean =>
305 + commandPath === 'execute' || commandPath === 'manage tools execute';
306 +
307 +const isSearchCommand = (commandPath: string): boolean =>
308 + commandPath === 'search' || commandPath === 'manage tools search';
309 +
310 +const isLinkCommand = (commandPath: string): boolean =>
311 + commandPath === 'link' || commandPath === 'manage connected-accounts link';
312 +
313 +const isLoginCommand = (commandPath: string): boolean => commandPath === 'login';
314 +
315 +const isLogoutCommand = (commandPath: string): boolean => commandPath === 'logout';
316 +
317 +const isProxyCommand = (commandPath: string): boolean => commandPath === 'proxy';
318 +
319 +const isRunCommand = (commandPath: string): boolean => commandPath === 'run';
320 +
321 +const isGenericOnlyCommand = (commandPath: string): boolean =>
322 + commandPath === 'composio' || commandPath.startsWith('dev');
323 +
324 +export const createCliCommandTelemetryContext = (
325 + argv: ReadonlyArray<string>,
326 + cliVersion: string
327 +): CliCommandTelemetryContext => ({
328 + argv,
329 + cliVersion,
330 + commandPath: extractCommandPath(argv),
331 + flagNames: extractFlagNames(argv),
332 + startedAt: Date.now(),
333 + runId:
334 + extractCommandPath(argv) === 'run'
335 + ? (process.env.COMPOSIO_CLI_PARENT_RUN_ID ?? crypto.randomUUID())
336 + : undefined,
337 +});
338 +
339 +const getCliCommandInvokedEvent = (context: CliCommandTelemetryContext): TrackEvent => ({
340 + name: CLI_ANALYTICS_EVENTS.CLI_COMMAND_INVOKED,
341 + properties: {
342 + source: 'cli',
343 + invocation_origin: getInvocationOrigin(),
344 + cli_version: context.cliVersion,
345 + command_path: context.commandPath,
346 + flag_names: context.flagNames,
347 + arg_count: Math.max(0, context.argv.length - 2),
348 + stdout_is_tty: Boolean(process.stdout.isTTY),
349 + stderr_is_tty: Boolean(process.stderr.isTTY),
350 + },
351 +});
352 +
353 +const getCliCommandSucceededEvent = (context: CliCommandTelemetryContext): TrackEvent => ({
354 + name: CLI_ANALYTICS_EVENTS.CLI_COMMAND_SUCCEEDED,
355 + properties: {
356 + source: 'cli',
357 + invocation_origin: getInvocationOrigin(),
358 + cli_version: context.cliVersion,
359 + command_path: context.commandPath,
360 + duration_ms: Date.now() - context.startedAt,
361 + flag_names: context.flagNames,
362 + },
363 +});
364 +
365 +const getCliCommandFailedEvent = (
366 + context: CliCommandTelemetryContext,
367 + error: unknown
368 +): TrackEvent => ({
369 + name: CLI_ANALYTICS_EVENTS.CLI_COMMAND_FAILED,
370 + properties: {
371 + source: 'cli',
372 + invocation_origin: getInvocationOrigin(),
373 + cli_version: context.cliVersion,
374 + command_path: context.commandPath,
375 + duration_ms: Date.now() - context.startedAt,
376 + flag_names: context.flagNames,
377 + error_name: errorNameOf(error),
378 + error_message: errorMessageOf(error),
379 + },
380 +});
381 +
382 +type SpecialLifecycleFamily = {
383 + readonly match: (commandPath: string) => boolean;
384 + readonly invokedEventName: string;
385 + readonly succeededEventName: string;
386 + readonly failedEventName: string;
387 + readonly getProperties: (context: CliCommandTelemetryContext) => Record<string, unknown>;
388 +};
389 +
390 +const SPECIAL_LIFECYCLE_FAMILIES: ReadonlyArray<SpecialLifecycleFamily> = [
391 + {
392 + match: isExecuteCommand,
393 + invokedEventName: CLI_ANALYTICS_EVENTS.CLI_EXECUTE_INVOKED,
394 + succeededEventName: CLI_ANALYTICS_EVENTS.CLI_EXECUTE_SUCCEEDED,
395 + failedEventName: CLI_ANALYTICS_EVENTS.CLI_EXECUTE_FAILED,
396 + getProperties: getExecuteCommandProperties,
397 + },
398 + {
399 + match: isSearchCommand,
400 + invokedEventName: CLI_ANALYTICS_EVENTS.CLI_SEARCH_INVOKED,
401 + succeededEventName: CLI_ANALYTICS_EVENTS.CLI_SEARCH_SUCCEEDED,
402 + failedEventName: CLI_ANALYTICS_EVENTS.CLI_SEARCH_FAILED,
403 + getProperties: getSearchCommandProperties,
404 + },
405 + {
406 + match: isLinkCommand,
407 + invokedEventName: CLI_ANALYTICS_EVENTS.CLI_LINK_INVOKED,
408 + succeededEventName: CLI_ANALYTICS_EVENTS.CLI_LINK_SUCCEEDED,
409 + failedEventName: CLI_ANALYTICS_EVENTS.CLI_LINK_FAILED,
410 + getProperties: getLinkCommandProperties,
411 + },
412 + {
413 + match: isLoginCommand,
414 + invokedEventName: CLI_ANALYTICS_EVENTS.CLI_LOGIN_INVOKED,
415 + succeededEventName: CLI_ANALYTICS_EVENTS.CLI_LOGIN_SUCCEEDED,
416 + failedEventName: CLI_ANALYTICS_EVENTS.CLI_LOGIN_FAILED,
417 + getProperties: getLoginCommandProperties,
418 + },
419 + {
420 + match: isLogoutCommand,
421 + invokedEventName: CLI_ANALYTICS_EVENTS.CLI_LOGOUT_INVOKED,
422 + succeededEventName: CLI_ANALYTICS_EVENTS.CLI_LOGOUT_SUCCEEDED,
423 + failedEventName: CLI_ANALYTICS_EVENTS.CLI_LOGOUT_FAILED,
424 + getProperties: getLogoutCommandProperties,
425 + },
426 + {
427 + match: isProxyCommand,
428 + invokedEventName: CLI_ANALYTICS_EVENTS.CLI_PROXY_INVOKED,
429 + succeededEventName: CLI_ANALYTICS_EVENTS.CLI_PROXY_SUCCEEDED,
430 + failedEventName: CLI_ANALYTICS_EVENTS.CLI_PROXY_FAILED,
431 + getProperties: getProxyCommandProperties,
432 + },
433 + {
434 + match: isRunCommand,
435 + invokedEventName: CLI_ANALYTICS_EVENTS.CLI_RUN_INVOKED,
436 + succeededEventName: CLI_ANALYTICS_EVENTS.CLI_RUN_SUCCEEDED,
437 + failedEventName: CLI_ANALYTICS_EVENTS.CLI_RUN_FAILED,
438 + getProperties: getRunCommandProperties,
439 + },
440 +];
441 +
442 +const getSpecialLifecycleFamily = (commandPath: string): SpecialLifecycleFamily | undefined =>
443 + SPECIAL_LIFECYCLE_FAMILIES.find(family => family.match(commandPath));
444 +
445 +export const getPrimaryLifecycleInvokedEvent = (
446 + context: CliCommandTelemetryContext
447 +): TrackEvent => {
448 + const family = getSpecialLifecycleFamily(context.commandPath);
449 + if (!family || isGenericOnlyCommand(context.commandPath)) {
450 + return getCliCommandInvokedEvent(context);
451 + }
452 + return {
453 + name: family.invokedEventName,
454 + properties: family.getProperties(context),
455 + };
456 +};
457 +
458 +export const getPrimaryLifecycleSucceededEvent = (
459 + context: CliCommandTelemetryContext
460 +): TrackEvent => {
461 + const family = getSpecialLifecycleFamily(context.commandPath);
462 + if (!family || isGenericOnlyCommand(context.commandPath)) {
463 + return getCliCommandSucceededEvent(context);
464 + }
465 + return {
466 + name: family.succeededEventName,
467 + properties: family.getProperties(context),
468 + };
469 +};
470 +
471 +export const getPrimaryLifecycleFailedEvent = (
472 + context: CliCommandTelemetryContext,
473 + error: unknown
474 +): TrackEvent => {
475 + const family = getSpecialLifecycleFamily(context.commandPath);
476 + if (!family || isGenericOnlyCommand(context.commandPath)) {
477 + return getCliCommandFailedEvent(context, error);
478 + }
479 + return {
480 + name: family.failedEventName,
481 + properties: {
482 + ...family.getProperties(context),
483 + error_name: errorNameOf(error),
484 + error_message: errorMessageOf(error),
485 + },
486 + };
487 +};
488 +
489 +export const getToolExecuteValidationFailedEvent = (params: {
490 + readonly toolSlug: string;
491 + readonly args: Record<string, unknown>;
492 + readonly error: ToolInputValidationError;
493 + readonly surface: 'root' | 'manage' | 'dev';
494 + readonly projectMode: 'consumer' | 'developer';
495 + readonly stage: 'dry_run' | 'validation' | 'execution';
496 +}): TrackEvent => ({
497 + name: CLI_ANALYTICS_EVENTS.CLI_TOOL_INVOCATION_VALIDATION_FAILED,
498 + properties: {
499 + source: 'cli',
500 + invocation_origin: getInvocationOrigin(),
501 + tool_slug: params.toolSlug,
502 + toolkit_slug: toolkitFromToolSlug(params.toolSlug),
503 + surface: params.surface,
504 + project_mode: params.projectMode,
505 + stage: params.stage,
506 + issue_count: params.error.issues.length,
507 + issue_locations: extractIssueLocations(params.error.issues),
508 + unknown_keys: extractUnknownKeys(params.error.issues),
509 + schema_path: params.error.schemaPath,
510 + ...argumentShape(params.args),
511 + },
512 +});
513 +
514 +export const isMaybeToolNotFoundError = (params: {
515 + readonly message?: string;
516 + readonly errorSlug?: string;
517 + readonly status?: number;
518 +}): boolean =>
519 + params.status === 404 ||
520 + params.errorSlug?.toLowerCase().includes('notfound') === true ||
521 + TOOL_NOT_FOUND_PATTERN.test(params.message ?? '');
522 +
523 +export const getToolExecuteToolNotFoundEvent = (params: {
524 + readonly toolSlug: string;
525 + readonly args: Record<string, unknown>;
526 + readonly surface: 'root' | 'manage' | 'dev';
527 + readonly projectMode: 'consumer' | 'developer';
528 + readonly stage: 'schema_fetch' | 'dry_run' | 'execution';
529 + readonly errorSlug?: string;
530 + readonly status?: number;
531 + readonly apiCode?: number;
532 + readonly message?: string;
533 +}): TrackEvent => ({
534 + name: CLI_ANALYTICS_EVENTS.CLI_TOOL_INVOCATION_TOOL_NOT_FOUND,
535 + properties: {
536 + source: 'cli',
537 + invocation_origin: getInvocationOrigin(),
538 + tool_slug: params.toolSlug,
539 + toolkit_slug: toolkitFromToolSlug(params.toolSlug),
540 + surface: params.surface,
541 + project_mode: params.projectMode,
542 + stage: params.stage,
543 + error_slug: params.errorSlug,
544 + http_status: params.status,
545 + api_error_code: params.apiCode,
546 + error_message: params.message?.slice(0, 500),
547 + ...argumentShape(params.args),
548 + },
549 +});
550 +
551 +export const getToolExecuteFailedEvent = (params: {
552 + readonly toolSlug: string;
553 + readonly args: Record<string, unknown>;
554 + readonly surface: 'root' | 'manage' | 'dev';
555 + readonly projectMode: 'consumer' | 'developer';
556 + readonly stage: 'schema_fetch' | 'dry_run' | 'execution';
557 + readonly errorSlug?: string;
558 + readonly status?: number;
559 + readonly apiCode?: number;
560 + readonly message?: string;
561 + readonly errorName?: string;
562 + readonly isNoConnectionError?: boolean;
563 +}): TrackEvent => ({
564 + name: CLI_ANALYTICS_EVENTS.CLI_TOOL_INVOCATION_FAILED,
565 + properties: {
566 + source: 'cli',
567 + invocation_origin: getInvocationOrigin(),
568 + tool_slug: params.toolSlug,
569 + toolkit_slug: toolkitFromToolSlug(params.toolSlug),
570 + surface: params.surface,
571 + project_mode: params.projectMode,
572 + stage: params.stage,
573 + error_slug: params.errorSlug,
574 + http_status: params.status,
575 + api_error_code: params.apiCode,
576 + error_name: params.errorName,
577 + error_message: params.message?.slice(0, 500),
578 + is_no_connection_error: Boolean(params.isNoConnectionError),
579 + ...argumentShape(params.args),
580 + },
581 +});
ts/packages/cli/src/analytics/types.ts new
+22
@@ -0,0 +1,22 @@
1 +export type TrackEvent = {
2 + readonly name: string;
3 + readonly properties?: Record<string, unknown>;
4 +} | null;
5 +
6 +export type AnalyticsEnvelope = {
7 + readonly event: NonNullable<TrackEvent>['name'];
8 + readonly properties?: NonNullable<TrackEvent>['properties'];
9 + readonly sentAt: string;
10 + readonly source: 'cli';
11 + readonly distinctId: string;
12 + readonly installId: string;
13 +};
14 +
15 +export type CliCommandTelemetryContext = {
16 + readonly argv: ReadonlyArray<string>;
17 + readonly cliVersion: string;
18 + readonly commandPath: string;
19 + readonly flagNames: ReadonlyArray<string>;
20 + readonly startedAt: number;
21 + readonly runId?: string;
22 +};
ts/packages/cli/src/bin.ts
+20 -237
@@ -1,243 +1,26 @@
1 import process from 'node:process';
2 -import { Cause, Console, Effect, Exit, HashMap, Layer, Logger, Option } from 'effect';
3 -import { captureErrors, prettyPrintFromCapturedErrors } from 'effect-errors/index';
4 -import { CliConfig, CommandDescriptor, HelpDoc, Usage, ValidationError } from '@effect/cli';
5 -import { FetchHttpClient } from '@effect/platform';
6 -import { BunContext, BunRuntime, BunFileSystem } from '@effect/platform-bun';
7 -import type { Teardown } from '@effect/platform/Runtime';
8 -import { rootCommand, runWithConfig } from 'src/commands';
9 -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';
17 -import { ComposioToolkitsRepositoryCached } from 'src/services/composio-clients-cached';
18 -import { NodeOs } from 'src/services/node-os';
19 -import { NodeProcess } from 'src/services/node-process';
20 -import { JsPackageManagerDetector } from 'src/services/js-package-manager-detector';
21 -import { ComposioUserContextLive as _ComposioUserContextLive } from 'src/services/user-context';
22 -import { UpgradeBinary } from 'src/services/upgrade-binary';
23 -import { TerminalUILive } from 'src/services/terminal-ui';
24 -import { TriggersRealtime } from 'src/services/triggers-realtime';
25 -import { ToolsExecutorLive as _ToolsExecutorLive } from 'src/services/tools-executor';
26 -import { ProjectContext } from 'src/services/project-context';
27 -import { ProjectEnvironmentDetector } from 'src/services/project-environment-detector';
28 -import { CommandRunner } from 'src/services/command-runner';
29 -import { StdinLive } from 'src/services/stdin';
30 -import { showUpdateNotice, checkForUpdateInBackground } from 'src/services/update-check';
31 -import { mapOnlyComposioOverrideError } from 'src/services/composio-error-overrides';
2 +import { isAnalyticsWorkerInvocation, runAnalyticsWorkerFromArgv } from 'src/analytics/dispatch';
3
33 -/**
34 - * Concrete Effect layer compositions for the Composio CLI runtime.
35 - *
36 - * ┌─── The service to be created
37 - * │ ┌─── The possible error
38 - * │ │ ┌─── The required dependencies
39 - * ▼ ▼ ▼
40 - * Layer<RequirementsOut, Error, RequirementsIn>
41 - */
4 +const TELEMETRY_DEBUG_FLAG = '--telemetry-debug';
5 +const CLI_TELEMETRY_DEBUG_ENV_VAR = 'COMPOSIO_CLI_TELEMETRY_DEBUG';
6
43 -// eslint-disable-next-line @typescript-eslint/no-explicit-any
44 -type RequiredLayer = Layer.Layer<any, any, never>;
45 -
46 -/**
47 - * Service layer that configures the CLI appearance and default command options.
48 - */
49 -export const CliConfigLive = CliConfig.layer(ComposioCliConfig) satisfies RequiredLayer;
50 -
51 -export const ComposioUserContextLive = Layer.provide(
52 - _ComposioUserContextLive,
53 - Layer.mergeAll(BunFileSystem.layer, NodeOs.Default)
54 -) satisfies RequiredLayer;
55 -
56 -export const ComposioSessionRepositoryLive = Layer.provide(
57 - ComposioSessionRepository.Default,
58 - Layer.mergeAll(BunFileSystem.layer, NodeOs.Default)
59 -) satisfies RequiredLayer;
60 -
61 -export const ComposioToolkitsRepositoryLive = Layer.provide(
62 - ComposioToolkitsRepository.Default,
63 - Layer.mergeAll(BunFileSystem.layer, NodeOs.Default, ConfigLive)
64 -) satisfies RequiredLayer;
65 -
66 -export const ComposioToolkitsRepositoryCachedLive = Layer.provide(
67 - ComposioToolkitsRepositoryCached,
68 - ComposioToolkitsRepositoryLive
69 -) satisfies RequiredLayer;
70 -
71 -export const UpgradeBinaryLive = Layer.provide(
72 - UpgradeBinary.Default,
73 - Layer.mergeAll(BunFileSystem.layer, FetchHttpClient.layer)
74 -) satisfies RequiredLayer;
75 -
76 -export const TriggersRealtimeLive = Layer.provide(
77 - TriggersRealtime.Default,
78 - Layer.mergeAll(BunFileSystem.layer, NodeOs.Default)
79 -) satisfies RequiredLayer;
80 -
81 -export const ComposioClientSingletonLive = Layer.provide(
82 - ComposioClientSingleton.Default,
83 - Layer.mergeAll(BunFileSystem.layer, NodeOs.Default, ConfigLive)
84 -) satisfies RequiredLayer;
85 -
86 -export const ToolsExecutorLive = Layer.provide(
87 - _ToolsExecutorLive,
88 - ComposioClientSingletonLive
89 -) satisfies RequiredLayer;
90 -
91 -export const ProjectContextLive = Layer.provide(
92 - ProjectContext.Default,
93 - Layer.mergeAll(BunFileSystem.layer, NodeOs.Default, NodeProcess.Default)
94 -) satisfies RequiredLayer;
95 -
96 -const layers = Layer.mergeAll(
97 - CliConfigLive.pipe(Layer.provide(ConfigLive)),
98 - NodeOs.Default,
99 - NodeProcess.Default,
100 - UpgradeBinaryLive,
101 - ComposioUserContextLive,
102 - ComposioSessionRepositoryLive,
103 - ComposioClientSingletonLive, // Expose ComposioClientSingleton for commands that use Tool Router directly
104 - ComposioToolkitsRepositoryCachedLive, // Use the cached layer instead of the regular one
105 - ToolsExecutorLive,
106 - JsPackageManagerDetector.Default,
107 - ProjectEnvironmentDetector.Default,
108 - CommandRunner.Default,
109 - TriggersRealtimeLive,
110 - ProjectContextLive,
111 - BunContext.layer,
112 - BunFileSystem.layer,
113 - StdinLive,
114 - TerminalUILive,
115 - Logger.pretty
116 -) satisfies RequiredLayer;
117 -
118 -export const teardown: Teardown = <E, A>(exit: Exit.Exit<E, A>, onExit: (code: number) => void) => {
119 - const shouldFail = Exit.isFailure(exit) && !Cause.isInterruptedOnly(exit.cause);
120 - const errorCode = Number(process.exitCode ?? 1);
121 - onExit(shouldFail ? errorCode : 0);
122 -};
123 -
124 -const runWithArgs = Effect.flatMap(runWithConfig, run => run(process.argv)) satisfies Effect.Effect<
125 - void,
126 - unknown,
127 - unknown
128 ->;
129 -
130 -const collectValueOptionNamesFromUsage = (usage: Usage.Usage, acc: Set<string>) => {
131 - switch (usage._tag) {
132 - case 'Named': {
133 - if (Option.isSome(usage.acceptedValues)) {
134 - for (const name of usage.names) {
135 - if (name.startsWith('-')) {
136 - acc.add(name);
137 - }
138 - }
139 - }
140 - return;
141 - }
142 - case 'Optional':
143 - case 'Repeated': {
144 - collectValueOptionNamesFromUsage(usage.usage, acc);
145 - return;
146 - }
147 - case 'Alternation':
148 - case 'Concat': {
149 - collectValueOptionNamesFromUsage(usage.left, acc);
150 - collectValueOptionNamesFromUsage(usage.right, acc);
151 - return;
152 - }
153 - case 'Mixed':
154 - case 'Empty': {
155 - return;
156 - }
7 +const stripTelemetryDebugFlag = (argv: ReadonlyArray<string>): string[] => {
8 + const normalizedArgv = [...argv];
9 + const flagIndex = normalizedArgv.indexOf(TELEMETRY_DEBUG_FLAG);
10 + if (flagIndex < 0) {
11 + return normalizedArgv;
12 }
158 -};
159 -
160 -const valueOptionNames = (() => {
161 - const names = new Set<string>();
162 - const visited = new Set<CommandDescriptor.Command<unknown>>();
163 - const visit = (command: CommandDescriptor.Command<unknown>) => {
164 - if (visited.has(command)) {
165 - return;
166 - }
167 - visited.add(command);
168 - collectValueOptionNamesFromUsage(CommandDescriptor.getUsage(command), names);
169 - for (const [, subcommand] of HashMap.toEntries(CommandDescriptor.getSubcommands(command))) {
170 - visit(subcommand);
171 - }
172 - };
173 - visit(rootCommand.descriptor);
174 - return names;
175 -})();
176 -
177 -/**
178 - * Upgrade hint — runs outside the Effect runtime, never blocks or throws.
179 - * showUpdateNotice() reads a cached file (~1 ms) and prints to stderr.
180 - * checkForUpdateInBackground() fires a non-blocking fetch to GitHub.
181 - */
182 -showUpdateNotice();
183 -checkForUpdateInBackground();
13
185 -/**
186 - * CLI entrypoint, which:
187 - * - runs the Effect runtime and sets up its runtime environment
188 - * - collects and displays errors
189 - */
190 -runWithArgs.pipe(
191 - Effect.scoped,
192 - Effect.mapError(error =>
193 - ValidationError.isValidationError(error) ? error : mapOnlyComposioOverrideError({ error })
194 - ),
195 - // @effect/cli already prints validation errors (missing args, invalid flags, etc.)
196 - // via its own printDocs before re-failing. Swallow the re-thrown error to avoid
197 - // routing it through the generic error box which would dump raw JSON.
198 - // When a flag is passed without its required value (e.g. `--query` instead of
199 - // `--query "text"`), @effect/cli reports it as "unknown argument" — add a tip.
200 - Effect.catchIf(ValidationError.isValidationError, error => {
201 - const text = HelpDoc.toAnsiText(error.error).trim();
202 - const flagMatch = text.match(/Received unknown argument: '(-{1,2}[\w-]+)'/);
203 - if (flagMatch && valueOptionNames.has(flagMatch[1])) {
204 - return Console.error(`Tip: ${flagMatch[1]} requires a value, e.g. ${flagMatch[1]} "value"`);
205 - }
206 - return Effect.void;
207 - }),
208 - Effect.withSpan('composio-cli', {
209 - attributes: {
210 - name: constants.APP_NAME,
211 - filename: 'src/bin.ts',
212 - },
213 - }),
214 - Effect.sandbox,
215 - Effect.catchAll(
216 - Effect.fn(function* (cause) {
217 - const captured = yield* captureErrors(cause, {
218 - stripCwd: true,
219 - });
220 - const filteredErrors = captured.errors.filter(
221 - error => error.errorType !== 'ToolExecutionError'
222 - );
223 -
224 - if (captured.interrupted || filteredErrors.length > 0) {
225 - const message = prettyPrintFromCapturedErrors(
226 - { ...captured, errors: filteredErrors },
227 - {
228 - hideStackTrace: true,
229 - stripCwd: true,
230 - enabled: true,
231 - }
232 - );
14 + normalizedArgv.splice(flagIndex, 1);
15 + process.env[CLI_TELEMETRY_DEBUG_ENV_VAR] = 'true';
16 + return normalizedArgv;
17 +};
18
234 - yield* Console.error(message);
235 - process.exitCode = 1;
236 - }
237 - })
238 - ),
239 - Effect.provide(layers),
240 - Effect.withConfigProvider(extendConfigProvider(BaseConfigProviderLive)),
241 - effect =>
242 - (BunRuntime.runMain({ teardown }) as (e: Effect.Effect<void, unknown, unknown>) => void)(effect)
243 -);
19 +if (isAnalyticsWorkerInvocation(process.argv)) {
20 + void runAnalyticsWorkerFromArgv(process.argv).finally(() => {
21 + process.exit(0);
22 + });
23 +} else {
24 + process.argv = stripTelemetryDebugFlag(process.argv);
25 + void import('./cli-main');
26 +}
ts/packages/cli/src/cli-main.ts new
+237
@@ -0,0 +1,237 @@
1 +import process from 'node:process';
2 +import { Cause, Console, Effect, Exit, HashMap, Layer, Logger, Option } from 'effect';
3 +import { captureErrors, prettyPrintFromCapturedErrors } from 'effect-errors/index';
4 +import { CliConfig, CommandDescriptor, HelpDoc, Usage, ValidationError } from '@effect/cli';
5 +import { FetchHttpClient } from '@effect/platform';
6 +import { BunContext, BunRuntime, BunFileSystem } from '@effect/platform-bun';
7 +import type { Teardown } from '@effect/platform/Runtime';
8 +import { rootCommand, runWithConfig } from 'src/commands';
9 +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';
17 +import { ComposioToolkitsRepositoryCached } from 'src/services/composio-clients-cached';
18 +import { NodeOs } from 'src/services/node-os';
19 +import { NodeProcess } from 'src/services/node-process';
20 +import { JsPackageManagerDetector } from 'src/services/js-package-manager-detector';
21 +import { ComposioUserContextLive as _ComposioUserContextLive } from 'src/services/user-context';
22 +import { UpgradeBinary } from 'src/services/upgrade-binary';
23 +import { TerminalUILive } from 'src/services/terminal-ui';
24 +import { TriggersRealtime } from 'src/services/triggers-realtime';
25 +import { ToolsExecutorLive as _ToolsExecutorLive } from 'src/services/tools-executor';
26 +import { ProjectContext } from 'src/services/project-context';
27 +import { ProjectEnvironmentDetector } from 'src/services/project-environment-detector';
28 +import { CommandRunner } from 'src/services/command-runner';
29 +import { StdinLive } from 'src/services/stdin';
30 +import { showUpdateNotice, checkForUpdateInBackground } from 'src/services/update-check';
31 +import {
32 + createCliCommandTelemetryContext,
33 + getPrimaryLifecycleFailedEvent,
34 + getPrimaryLifecycleInvokedEvent,
35 + getPrimaryLifecycleSucceededEvent,
36 +} from 'src/analytics/events';
37 +import { trackCliEvent, trackCliEventEffect } from 'src/analytics/dispatch';
38 +import { mapOnlyComposioOverrideError } from 'src/services/composio-error-overrides';
39 +
40 +// eslint-disable-next-line @typescript-eslint/no-explicit-any
41 +type RequiredLayer = Layer.Layer<any, any, never>;
42 +
43 +export const CliConfigLive = CliConfig.layer(ComposioCliConfig) satisfies RequiredLayer;
44 +
45 +export const ComposioUserContextLive = Layer.provide(
46 + _ComposioUserContextLive,
47 + Layer.mergeAll(BunFileSystem.layer, NodeOs.Default)
48 +) satisfies RequiredLayer;
49 +
50 +export const ComposioSessionRepositoryLive = Layer.provide(
51 + ComposioSessionRepository.Default,
52 + Layer.mergeAll(BunFileSystem.layer, NodeOs.Default)
53 +) satisfies RequiredLayer;
54 +
55 +export const ComposioToolkitsRepositoryLive = Layer.provide(
56 + ComposioToolkitsRepository.Default,
57 + Layer.mergeAll(BunFileSystem.layer, NodeOs.Default, ConfigLive)
58 +) satisfies RequiredLayer;
59 +
60 +export const ComposioToolkitsRepositoryCachedLive = Layer.provide(
61 + ComposioToolkitsRepositoryCached,
62 + ComposioToolkitsRepositoryLive
63 +) satisfies RequiredLayer;
64 +
65 +export const UpgradeBinaryLive = Layer.provide(
66 + UpgradeBinary.Default,
67 + Layer.mergeAll(BunFileSystem.layer, FetchHttpClient.layer)
68 +) satisfies RequiredLayer;
69 +
70 +export const TriggersRealtimeLive = Layer.provide(
71 + TriggersRealtime.Default,
72 + Layer.mergeAll(BunFileSystem.layer, NodeOs.Default)
73 +) satisfies RequiredLayer;
74 +
75 +export const ComposioClientSingletonLive = Layer.provide(
76 + ComposioClientSingleton.Default,
77 + Layer.mergeAll(BunFileSystem.layer, NodeOs.Default, ConfigLive)
78 +) satisfies RequiredLayer;
79 +
80 +export const ToolsExecutorLive = Layer.provide(
81 + _ToolsExecutorLive,
82 + ComposioClientSingletonLive
83 +) satisfies RequiredLayer;
84 +
85 +export const ProjectContextLive = Layer.provide(
86 + ProjectContext.Default,
87 + Layer.mergeAll(BunFileSystem.layer, NodeOs.Default, NodeProcess.Default)
88 +) satisfies RequiredLayer;
89 +
90 +const layers = Layer.mergeAll(
91 + CliConfigLive.pipe(Layer.provide(ConfigLive)),
92 + NodeOs.Default,
93 + NodeProcess.Default,
94 + UpgradeBinaryLive,
95 + ComposioUserContextLive,
96 + ComposioSessionRepositoryLive,
97 + ComposioClientSingletonLive,
98 + ComposioToolkitsRepositoryCachedLive,
99 + ToolsExecutorLive,
100 + JsPackageManagerDetector.Default,
101 + ProjectEnvironmentDetector.Default,
102 + CommandRunner.Default,
103 + TriggersRealtimeLive,
104 + ProjectContextLive,
105 + BunContext.layer,
106 + BunFileSystem.layer,
107 + StdinLive,
108 + TerminalUILive,
109 + Logger.pretty
110 +) satisfies RequiredLayer;
111 +
112 +export const teardown: Teardown = <E, A>(exit: Exit.Exit<E, A>, onExit: (code: number) => void) => {
113 + const shouldFail = Exit.isFailure(exit) && !Cause.isInterruptedOnly(exit.cause);
114 + const errorCode = Number(process.exitCode ?? 1);
115 + onExit(shouldFail ? errorCode : 0);
116 +};
117 +
118 +const runWithArgs = Effect.flatMap(runWithConfig, run => run(process.argv)) satisfies Effect.Effect<
119 + void,
120 + unknown,
121 + unknown
122 +>;
123 +
124 +const commandTelemetryContext = createCliCommandTelemetryContext(
125 + process.argv,
126 + constants.APP_VERSION
127 +);
128 +if (commandTelemetryContext.commandPath === 'run' && commandTelemetryContext.runId) {
129 + process.env.COMPOSIO_CLI_PARENT_RUN_ID = commandTelemetryContext.runId;
130 +}
131 +
132 +const collectValueOptionNamesFromUsage = (usage: Usage.Usage, acc: Set<string>) => {
133 + switch (usage._tag) {
134 + case 'Named': {
135 + if (Option.isSome(usage.acceptedValues)) {
136 + for (const name of usage.names) {
137 + if (name.startsWith('-')) {
138 + acc.add(name);
139 + }
140 + }
141 + }
142 + return;
143 + }
144 + case 'Optional':
145 + case 'Repeated': {
146 + collectValueOptionNamesFromUsage(usage.usage, acc);
147 + return;
148 + }
149 + case 'Alternation':
150 + case 'Concat': {
151 + collectValueOptionNamesFromUsage(usage.left, acc);
152 + collectValueOptionNamesFromUsage(usage.right, acc);
153 + return;
154 + }
155 + case 'Mixed':
156 + case 'Empty': {
157 + return;
158 + }
159 + }
160 +};
161 +
162 +const valueOptionNames = (() => {
163 + const names = new Set<string>();
164 + const visited = new Set<CommandDescriptor.Command<unknown>>();
165 + const visit = (command: CommandDescriptor.Command<unknown>) => {
166 + if (visited.has(command)) {
167 + return;
168 + }
169 + visited.add(command);
170 + collectValueOptionNamesFromUsage(CommandDescriptor.getUsage(command), names);
171 + for (const [, subcommand] of HashMap.toEntries(CommandDescriptor.getSubcommands(command))) {
172 + visit(subcommand);
173 + }
174 + };
175 + visit(rootCommand.descriptor);
176 + return names;
177 +})();
178 +
179 +showUpdateNotice();
180 +checkForUpdateInBackground();
181 +trackCliEvent(getPrimaryLifecycleInvokedEvent(commandTelemetryContext));
182 +
183 +runWithArgs.pipe(
184 + Effect.scoped,
185 + Effect.mapError(error =>
186 + ValidationError.isValidationError(error) ? error : mapOnlyComposioOverrideError({ error })
187 + ),
188 + Effect.tap(() => trackCliEventEffect(getPrimaryLifecycleSucceededEvent(commandTelemetryContext))),
189 + Effect.tapErrorCause(cause =>
190 + trackCliEventEffect(
191 + getPrimaryLifecycleFailedEvent(commandTelemetryContext, Cause.squash(cause))
192 + )
193 + ),
194 + Effect.catchIf(ValidationError.isValidationError, error => {
195 + const text = HelpDoc.toAnsiText(error.error).trim();
196 + const flagMatch = text.match(/Received unknown argument: '(-{1,2}[\w-]+)'/);
197 + if (flagMatch && valueOptionNames.has(flagMatch[1])) {
198 + return Console.error(`Tip: ${flagMatch[1]} requires a value, e.g. ${flagMatch[1]} "value"`);
199 + }
200 + return Effect.void;
201 + }),
202 + Effect.withSpan('composio-cli', {
203 + attributes: {
204 + name: constants.APP_NAME,
205 + filename: 'src/bin.ts',
206 + },
207 + }),
208 + Effect.sandbox,
209 + Effect.catchAll(
210 + Effect.fn(function* (cause) {
211 + const captured = yield* captureErrors(cause, {
212 + stripCwd: true,
213 + });
214 + const filteredErrors = captured.errors.filter(
215 + error => error.errorType !== 'ToolExecutionError'
216 + );
217 + if (captured.interrupted || filteredErrors.length > 0) {
218 + const message = prettyPrintFromCapturedErrors(
219 + { ...captured, errors: filteredErrors },
220 + {
221 + hideStackTrace: true,
222 + stripCwd: true,
223 + enabled: true,
224 + }
225 + ).trim();
226 + if (message.length > 0) {
227 + yield* Console.error(message);
228 + process.exitCode = 1;
229 + }
230 + }
231 + })
232 + ),
233 + Effect.provide(layers),
234 + Effect.withConfigProvider(extendConfigProvider(BaseConfigProviderLive)),
235 + effect =>
236 + (BunRuntime.runMain({ teardown }) as (e: Effect.Effect<void, unknown, unknown>) => void)(effect)
237 +);
ts/packages/cli/src/commands/run.cmd.ts
+6
@@ -160,6 +160,7 @@ type RunHelperContext = {
160 readonly baseURL?: string;
161 readonly webURL?: string;
162 readonly orgId?: string;
163 + readonly runId?: string;
164 readonly consumerUserId?: string;
165 readonly consumerProjectId?: string;
166 readonly consumerProjectName?: string;
@@ -484,6 +485,8 @@ const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [
485 ' ...(helperContext.apiKey ? { COMPOSIO_USER_API_KEY: helperContext.apiKey } : {}),',
486 ' ...(helperContext.baseURL ? { COMPOSIO_BASE_URL: helperContext.baseURL } : {}),',
487 ' ...(helperContext.webURL ? { COMPOSIO_WEB_URL: helperContext.webURL } : {}),',
488 + ' COMPOSIO_CLI_INVOCATION_ORIGIN: "run",',
489 + ' ...(helperContext.runId ? { COMPOSIO_CLI_PARENT_RUN_ID: helperContext.runId } : {}),',
490 ' ...(sharedRunOutputDir ? { COMPOSIO_RUN_OUTPUT_DIR: sharedRunOutputDir } : {}),',
491 ' ...(perfDebugEnabled ? { COMPOSIO_PERF_DEBUG: "1" } : {}),',
492 ' ...(toolDebugEnabled ? { COMPOSIO_TOOL_DEBUG: "1" } : {}),',
@@ -891,6 +894,7 @@ export const runCmd = Command.make('run', {
894 Command.withHandler(
895 ({ file, dryRun, debug, skipConnectionCheck, skipToolParamsCheck, noVerify, args }) =>
896 Effect.gen(function* () {
897 + const runId = process.env.COMPOSIO_CLI_PARENT_RUN_ID ?? crypto.randomUUID();
898 const perfDebug = isPerfDebugEnabled();
899 const toolDebug = isToolDebugEnabled();
900 if (Option.isNone(file)) {
@@ -906,6 +910,7 @@ export const runCmd = Command.make('run', {
910
911 const helperContext: RunHelperContext = {
912 ...(yield* resolveRunHelperContext()),
913 + runId,
914 master: detectMaster(),
915 perfDebug,
916 toolDebug,
@@ -941,6 +946,7 @@ export const runCmd = Command.make('run', {
946 env: {
947 ...process.env,
948 BUN_BE_BUN: '1',
949 + COMPOSIO_CLI_PARENT_RUN_ID: runId,
950 ...(perfDebug ? { COMPOSIO_PERF_DEBUG: '1' } : {}),
951 ...(toolDebug ? { COMPOSIO_TOOL_DEBUG: '1' } : {}),
952 },
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+156 -12
@@ -4,6 +4,7 @@ import { Effect, Option, Either, Exit, Fiber, Cause } from 'effect';
4 import { encodingForModel } from 'js-tiktoken';
5 import { redact } from 'src/ui/redact';
6 import { parseJsonIsh } from 'src/utils/parse-json-ish';
7 +import { toolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug';
8 import { requireAuth } from 'src/effects/require-auth';
9 import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';
10 import {
@@ -21,6 +22,13 @@ import type { ToolExecuteParams, ToolExecuteResponse } from 'src/services/tools-
22 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
23 import { ComposioUserContext } from 'src/services/user-context';
24 import { ProjectContext } from 'src/services/project-context';
25 +import { trackCliEventEffect } from 'src/analytics/dispatch';
26 +import {
27 + getToolExecuteFailedEvent,
28 + getToolExecuteToolNotFoundEvent,
29 + getToolExecuteValidationFailedEvent,
30 + isMaybeToolNotFoundError,
31 +} from 'src/analytics/events';
32 import { handleHttpServerError } from 'src/effects/handle-http-error';
33 import { formatToolInputParameters } from '../format';
34 import { ComposioClientSingleton } from 'src/services/composio-clients';
@@ -42,6 +50,7 @@ import { storeCliSessionArtifact } from 'src/services/cli-session-artifacts';
50 import {
51 ComposioNoActiveConnectionError,
52 mapComposioError,
53 + normalizeCliError,
54 } from 'src/services/composio-error-overrides';
55
56 const slug = Args.text({ name: 'slug' }).pipe(
@@ -108,14 +117,6 @@ const parseArguments = (raw: string) =>
117 return parsed as Record<string, unknown>;
118 });
119
111 -const toolkitFromToolSlug = (toolSlug: string): string | undefined => {
112 - const idx = toolSlug.indexOf('_');
113 - if (idx <= 0) return toolSlug.toLowerCase();
114 - const prefix = toolSlug.slice(0, idx).toLowerCase();
115 - if (prefix === 'composio') return undefined;
116 - return prefix;
117 -};
118 -
120 const connectionTips = (toolSlug: string, surface: 'root' | 'manage' | 'dev') => {
121 const toolkit = toolkitFromToolSlug(toolSlug);
122 const executeStep =
@@ -253,6 +254,79 @@ const prepareExecuteOutput = (
254 };
255 });
256
257 +const emitExecuteFailureTelemetry = (params: {
258 + readonly toolSlug: string;
259 + readonly args: Record<string, unknown>;
260 + readonly error: unknown;
261 + readonly surface: 'root' | 'manage' | 'dev';
262 + readonly projectMode: 'consumer' | 'developer';
263 + readonly stage: 'schema_fetch' | 'dry_run' | 'validation' | 'execution';
264 + readonly mappedError?: ReturnType<typeof mapComposioError>;
265 +}) =>
266 + Effect.gen(function* () {
267 + const normalized = params.mappedError?.normalized ?? normalizeCliError(params.error);
268 +
269 + if (normalized instanceof ToolInputValidationError) {
270 + yield* trackCliEventEffect(
271 + getToolExecuteValidationFailedEvent({
272 + toolSlug: params.toolSlug,
273 + args: params.args,
274 + error: normalized,
275 + surface: params.surface,
276 + projectMode: params.projectMode,
277 + stage: params.stage === 'dry_run' ? 'dry_run' : 'validation',
278 + })
279 + );
280 + return;
281 + }
282 +
283 + const mapped =
284 + params.mappedError ??
285 + mapComposioError({
286 + error: params.error,
287 + toolSlug: params.toolSlug,
288 + });
289 + const apiDetails = mapped.apiDetails;
290 + const message = mapped.message;
291 + const errorSlug = mapped.slugValue;
292 + const status = apiDetails?.status;
293 + const apiCode = apiDetails?.code;
294 + const isNoConnectionError =
295 + normalized instanceof ComposioNoActiveConnectionError || Boolean(mapped.override);
296 +
297 + const event = isMaybeToolNotFoundError({
298 + message,
299 + errorSlug,
300 + status,
301 + })
302 + ? getToolExecuteToolNotFoundEvent({
303 + toolSlug: params.toolSlug,
304 + args: params.args,
305 + surface: params.surface,
306 + projectMode: params.projectMode,
307 + stage: params.stage === 'validation' ? 'execution' : params.stage,
308 + errorSlug,
309 + status,
310 + apiCode,
311 + message,
312 + })
313 + : getToolExecuteFailedEvent({
314 + toolSlug: params.toolSlug,
315 + args: params.args,
316 + surface: params.surface,
317 + projectMode: params.projectMode,
318 + stage: params.stage === 'validation' ? 'execution' : params.stage,
319 + errorSlug,
320 + status,
321 + apiCode,
322 + message,
323 + errorName: normalized instanceof Error ? normalized.name : undefined,
324 + isNoConnectionError,
325 + });
326 +
327 + yield* trackCliEventEffect(event);
328 + });
329 +
330 export const showToolsExecuteInputHelp = (toolSlug: string) =>
331 Effect.gen(function* () {
332 if (!(yield* requireAuth)) return;
@@ -299,12 +373,26 @@ export const showToolsExecuteInputHelp = (toolSlug: string) =>
373 const handleExecutionError = (
374 ui: TerminalUI,
375 error: unknown,
302 - context: { toolSlug: string; surface: 'root' | 'manage' | 'dev' }
376 + context: {
377 + toolSlug: string;
378 + args: Record<string, unknown>;
379 + surface: 'root' | 'manage' | 'dev';
380 + projectMode: 'consumer' | 'developer';
381 + stage: 'schema_fetch' | 'dry_run' | 'validation' | 'execution';
382 + }
383 ) =>
384 Effect.gen(function* () {
385 const mapped = mapComposioError({ error, toolSlug: context.toolSlug });
386 const normalized = mapped.normalized;
387 if (normalized instanceof ToolInputValidationError) {
388 + yield* emitExecuteFailureTelemetry({
389 + toolSlug: context.toolSlug,
390 + args: context.args,
391 + error: normalized,
392 + surface: context.surface,
393 + projectMode: context.projectMode,
394 + stage: context.stage,
395 + });
396 yield* ui.log.error(`Input validation failed for ${context.toolSlug}`);
397 yield* ui.note(
398 [`Schema: ${normalized.schemaPath}`, ...normalized.issues.map(issue => `- ${issue}`)].join(
@@ -318,6 +406,16 @@ const handleExecutionError = (
406 const apiDetails = mapped.apiDetails;
407 const slugValue = mapped.slugValue;
408
409 + yield* emitExecuteFailureTelemetry({
410 + toolSlug: context.toolSlug,
411 + args: context.args,
412 + error,
413 + surface: context.surface,
414 + projectMode: context.projectMode,
415 + stage: context.stage,
416 + mappedError: mapped,
417 + });
418 +
419 if (normalized instanceof ComposioNoActiveConnectionError) {
420 yield* ui.log.error(mapped.message);
421 if (toolkitFromToolSlug(context.toolSlug)) {
@@ -709,9 +807,11 @@ const runConnectedToolkitFailFast = (params: {
807 }
808 });
809
810 +// eslint-disable-next-line max-lines-per-function
811 const runExecuteWithSpinner = (params: {
812 readonly slug: string;
813 readonly surface: 'root' | 'manage' | 'dev';
814 + readonly projectMode: 'consumer' | 'developer';
815 readonly dryRun: boolean;
816 readonly ui: TerminalUI;
817 readonly executor: ToolsExecutor;
@@ -759,9 +859,35 @@ const runExecuteWithSpinner = (params: {
859 (yield* getOrFetchToolInputDefinition(params.slug, {
860 orgId: params.resolvedProject.orgId,
861 projectId: params.resolvedProject.projectId,
762 - })));
862 + }).pipe(
863 + Effect.tapError(error =>
864 + emitExecuteFailureTelemetry({
865 + toolSlug: params.slug,
866 + args: params.args,
867 + error,
868 + surface: params.surface,
869 + projectMode: params.projectMode,
870 + stage: 'dry_run',
871 + })
872 + )
873 + )));
874 if (definition) {
764 - yield* validateToolInputArgumentsWithDefinition(params.slug, params.args, definition);
875 + yield* validateToolInputArgumentsWithDefinition(
876 + params.slug,
877 + params.args,
878 + definition
879 + ).pipe(
880 + Effect.tapError(error =>
881 + emitExecuteFailureTelemetry({
882 + toolSlug: params.slug,
883 + args: params.args,
884 + error,
885 + surface: params.surface,
886 + projectMode: params.projectMode,
887 + stage: 'dry_run',
888 + })
889 + )
890 + );
891 }
892 const summary: DryRunSummary = {
893 successful: true,
@@ -819,7 +945,10 @@ const runExecuteWithSpinner = (params: {
945 yield* spinner.error();
946 const summary = yield* handleExecutionError(params.ui, resultEither.left, {
947 toolSlug: params.slug,
948 + args: params.args,
949 surface: params.surface,
950 + projectMode: params.projectMode,
951 + stage: 'execution',
952 });
953 yield* params.ui.output(
954 JSON.stringify({ successful: false, ...summary }, ciRedactReplacer, 2)
@@ -865,7 +994,10 @@ const runExecuteWithSpinner = (params: {
994
995 const summary = yield* handleExecutionError(params.ui, result.error ?? result, {
996 toolSlug: params.slug,
997 + args: params.args,
998 surface: params.surface,
999 + projectMode: params.projectMode,
1000 + stage: 'execution',
1001 });
1002 yield* params.ui.output(JSON.stringify(result, ciRedactReplacer, 2));
1003 return yield* Effect.fail(new ToolExecutionError(summary.error));
@@ -937,7 +1069,18 @@ const runToolsExecute = (params: RunToolsExecuteParams) =>
1069 const definition = yield* getOrFetchToolInputDefinition(params.slug, {
1070 orgId: context.resolvedProject.orgId,
1071 projectId: context.resolvedProject.projectId,
940 - });
1072 + }).pipe(
1073 + Effect.tapError(error =>
1074 + emitExecuteFailureTelemetry({
1075 + toolSlug: params.slug,
1076 + args: context.args,
1077 + error,
1078 + surface: params.surface,
1079 + projectMode: params.projectMode,
1080 + stage: 'schema_fetch',
1081 + })
1082 + )
1083 + );
1084 yield* emitCachedSchema(context.ui, params.slug, definition);
1085 return;
1086 }
@@ -966,6 +1109,7 @@ const runToolsExecute = (params: RunToolsExecuteParams) =>
1109 yield* runExecuteWithSpinner({
1110 slug: params.slug,
1111 surface: params.surface,
1112 + projectMode: params.projectMode,
1113 dryRun: params.dryRun,
1114 ui: context.ui,
1115 executor: context.executor,
ts/packages/cli/src/utils/toolkit-from-tool-slug.ts new
+6
@@ -0,0 +1,6 @@
1 +export const toolkitFromToolSlug = (toolSlug: string): string | undefined => {
2 + const idx = toolSlug.indexOf('_');
3 + if (idx <= 0) return toolSlug.toLowerCase();
4 + const prefix = toolSlug.slice(0, idx).toLowerCase();
5 + return prefix === 'composio' ? undefined : prefix;
6 +};