1
-// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
2
-import fs from 'node:fs';
3
-// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
4
-import os from 'node:os';
5
-// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
6
-import path from 'node:path';
1
import process from 'node:process';
8
-// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
9
-import { spawn } from 'node:child_process';
10
-import { Effect } from 'effect';
11
-import type { AnalyticsEnvelope, TrackEvent } from './types';
2
+import { FileSystem, HttpClient, HttpClientRequest, Path } from '@effect/platform';
3
+import {
4
+ Cause,
5
+ Clock,
6
+ Config,
7
+ ConfigProvider,
8
+ DateTime,
9
+ Effect,
10
+ Encoding,
11
+ Option,
12
+ Schema,
13
+} from 'effect';
14
import * as constants from 'src/constants';
15
+import { spawnDetached } from 'src/services/detached-process';
16
+import { djb2Hash } from 'src/utils/djb2';
17
+import { NodeOs } from 'src/services/node-os';
18
+import { TerminalUI } from 'src/services/terminal-ui';
19
+import type { AnalyticsEnvelope, TrackEvent } from './types';
20
21
const INTERNAL_ANALYTICS_WORKER_FLAG = '__analytics-worker';
22
const INTERNAL_CODACT_FAILURE_WORKER_FLAG = '__codact-failure-worker';
25
const CONSUMER_SHORT_TERM_CACHE_FILE_NAME = 'consumer-short-term-cache.json';
26
const CLI_ANALYTICS_PATH = '/api/v3/cli/analytics';
27
const CLI_CODACT_FAILURES_PATH = '/api/v3/cli/codact_failures';
21
-const TELEMETRY_DEBUG_ENV_VAR = 'COMPOSIO_CLI_TELEMETRY_DEBUG';
28
29
export type CliCodactFailureType = 'wrong_tool_slug' | 'wrong_tool_input_param';
30
44
readonly requestId?: string;
45
};
46
41
-const truthy = (value: string | undefined): boolean =>
42
- value === '1' || value === 'true' || value === 'yes' || value === 'on';
43
-
44
-const isTelemetryDebugEnabled = (): boolean => truthy(process.env[TELEMETRY_DEBUG_ENV_VAR]);
45
-
46
-const telemetryDebugLog = (label: string, payload: Record<string, unknown>) => {
47
- if (!isTelemetryDebugEnabled()) {
48
- return;
49
- }
50
-
51
- process.stderr.write(
52
- `[telemetry-debug] ${JSON.stringify(
53
- {
54
- label,
55
- ...payload,
56
- },
57
- null,
58
- 2
59
- )}\n`
60
- );
61
-};
62
-
63
-const analyticsDir = () => path.join(os.homedir(), COMPOSIO_DIR);
64
-const analyticsStatePath = () => path.join(analyticsDir(), ANALYTICS_STATE_FILE_NAME);
65
-const userConfigPath = () => path.join(analyticsDir(), constants.USER_CONFIG_FILE_NAME);
66
-const cacheDir = () =>
67
- process.env.COMPOSIO_CACHE_DIR?.trim() ||
68
- process.env.CACHE_DIR?.trim() ||
69
- path.join(os.homedir(), constants.USER_COMPOSIO_DIR);
70
-const consumerShortTermCachePath = () => path.join(cacheDir(), CONSUMER_SHORT_TERM_CACHE_FILE_NAME);
71
-
47
type ConsumerShortTermCacheState = Record<
48
string,
49
{
57
}
58
>;
59
85
-const ensureAnalyticsDir = () => {
86
- try {
87
- fs.mkdirSync(analyticsDir(), { recursive: true });
88
- } catch {
89
- // Non-fatal — analytics directory creation may fail in sandboxed environments.
90
- }
91
-};
60
+// Workers start before the CLI's prefixed ConfigProvider is assembled, so this
61
+// module names and reads the actual environment variables from a raw provider.
62
+const environmentProvider = ConfigProvider.fromEnv();
63
+const optionalString = (name: string) => Config.option(Config.string(name));
64
+const booleanWithDefault = (name: string) => Config.boolean(name).pipe(Config.withDefault(false));
65
+const configuredString = (value: Option.Option<string>): string | undefined =>
66
+ value.pipe(
67
+ Option.map(value => value.trim()),
68
+ Option.filter(value => value.length > 0),
69
+ Option.getOrUndefined
70
+ );
71
93
-const encodeBase64Url = (value: string): string => {
94
- const bytes = new TextEncoder().encode(value);
95
- let binary = '';
96
- for (const byte of bytes) {
97
- binary += String.fromCharCode(byte);
98
- }
99
- return btoa(binary).replace(/\+/gu, '-').replace(/\//gu, '_').replace(/=+$/u, '');
100
-};
72
+const telemetryDebugEnabled = environmentProvider.load(
73
+ booleanWithDefault('COMPOSIO_CLI_TELEMETRY_DEBUG')
74
+);
75
+
76
+const analyticsDisabled = environmentProvider.load(
77
+ Config.all({
78
+ cliTelemetryDisabled: booleanWithDefault('COMPOSIO_CLI_TELEMETRY_DISABLED'),
79
+ telemetryDisabled: booleanWithDefault('TELEMETRY_DISABLED'),
80
+ composioTelemetryDisabled: booleanWithDefault('COMPOSIO_DISABLE_TELEMETRY'),
81
+ nodeEnvironment: Config.string('NODE_ENV').pipe(Config.withDefault('')),
82
+ ci: booleanWithDefault('CI'),
83
+ }).pipe(
84
+ Config.map(
85
+ ({
86
+ cliTelemetryDisabled,
87
+ telemetryDisabled,
88
+ composioTelemetryDisabled,
89
+ nodeEnvironment,
90
+ ci,
91
+ }) =>
92
+ cliTelemetryDisabled ||
93
+ telemetryDisabled ||
94
+ composioTelemetryDisabled ||
95
+ nodeEnvironment === 'test' ||
96
+ ci
97
+ )
98
+ )
99
+);
100
+
101
+const jsonFromString = Schema.parseJson();
102
+const prettyJsonFromString = Schema.parseJson({ space: 2 });
103
+const decodeJson = Schema.decodeUnknown(jsonFromString);
104
+const encodeJson = Schema.encode(jsonFromString);
105
+const encodePrettyJson = Schema.encode(prettyJsonFromString);
106
+
107
+const telemetryDebugLog = (label: string, payload: Record<string, unknown>) =>
108
+ Effect.gen(function* () {
109
+ if (!(yield* telemetryDebugEnabled)) {
110
+ return;
111
+ }
112
102
-const decodeBase64Url = (value: string): string => {
103
- const normalized = value.replace(/-/gu, '+').replace(/_/gu, '/');
104
- const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=');
105
- const binary = atob(padded);
106
- const bytes = Uint8Array.from(binary, char => char.charCodeAt(0));
107
- return new TextDecoder().decode(bytes);
113
+ const body = yield* encodePrettyJson({ label, ...payload });
114
+ const ui = yield* TerminalUI;
115
+ yield* ui.error(`[telemetry-debug] ${body}`);
116
+ }).pipe(Effect.ignore);
117
+
118
+const telemetryErrorDetails = (cause: Cause.Cause<unknown>): Record<string, string> => {
119
+ const squashed = Cause.squash(cause);
120
+ const error = Cause.isUnknownException(squashed) ? squashed.error : squashed;
121
+ return error instanceof Error
122
+ ? { name: error.name, message: error.message }
123
+ : { message: String(error) };
124
};
125
110
-const djb2Hash = (value: string): number => {
111
- let hash = 5381;
112
- for (let index = 0; index < value.length; index += 1) {
113
- hash = (hash * 33) ^ value.charCodeAt(index);
114
- }
115
- return Math.abs(hash >>> 0);
116
-};
126
+const getAnalyticsPaths = Effect.gen(function* () {
127
+ const path = yield* Path.Path;
128
+ const os = yield* NodeOs;
129
+ const cacheDirectories = yield* environmentProvider.load(
130
+ Config.all({
131
+ composio: optionalString('COMPOSIO_CACHE_DIR'),
132
+ legacy: optionalString('CACHE_DIR'),
133
+ })
134
+ );
135
+ const analyticsDir = path.join(os.homedir, COMPOSIO_DIR);
136
+ const cacheDir =
137
+ configuredString(cacheDirectories.composio) ??
138
+ configuredString(cacheDirectories.legacy) ??
139
+ path.join(os.homedir, constants.USER_COMPOSIO_DIR);
140
+
141
+ return {
142
+ analyticsDir,
143
+ analyticsStatePath: path.join(analyticsDir, ANALYTICS_STATE_FILE_NAME),
144
+ userConfigPath: path.join(analyticsDir, constants.USER_CONFIG_FILE_NAME),
145
+ consumerShortTermCachePath: path.join(cacheDir, CONSUMER_SHORT_TERM_CACHE_FILE_NAME),
146
+ };
147
+});
148
+
149
+const readOptionalJson = <A>(filePath: string) =>
150
+ Effect.gen(function* () {
151
+ const fs = yield* FileSystem.FileSystem;
152
+ const raw = yield* fs.readFileString(filePath, 'utf8');
153
+ return (yield* decodeJson(raw)) as A;
154
+ }).pipe(Effect.catchAll(() => Effect.succeed(undefined)));
155
156
const hashString = (value: string): string => djb2Hash(value).toString(16).padStart(8, '0');
157
120
-const getOrCreateInstallId = (): string => {
121
- try {
122
- ensureAnalyticsDir();
123
- const filePath = analyticsStatePath();
124
- if (fs.existsSync(filePath)) {
125
- const raw = fs.readFileSync(filePath, 'utf8');
126
- const parsed = JSON.parse(raw) as { install_id?: unknown };
127
- if (typeof parsed.install_id === 'string' && parsed.install_id.length > 0) {
128
- return parsed.install_id;
129
- }
130
- }
131
- const installId = crypto.randomUUID();
132
- fs.writeFileSync(
133
- filePath,
134
- JSON.stringify(
135
- {
136
- install_id: installId,
137
- created_at: new Date().toISOString(),
138
- },
139
- null,
140
- 2
141
- ),
142
- 'utf8'
143
- );
144
- return installId;
145
- } catch {
146
- return crypto.randomUUID();
147
- }
148
-};
158
+const makeInstallId = Effect.sync(() => crypto.randomUUID());
159
150
-const getHashedApiKeyDistinctId = (): string | null => {
151
- const envApiKey = process.env.COMPOSIO_USER_API_KEY?.trim();
152
- if (envApiKey) {
153
- return `user_${hashString(envApiKey)}`;
154
- }
160
+const getOrCreateInstallId = Effect.gen(function* () {
161
+ const fs = yield* FileSystem.FileSystem;
162
+ const paths = yield* getAnalyticsPaths;
163
156
- try {
157
- const raw = fs.readFileSync(userConfigPath(), 'utf8');
158
- const parsed = JSON.parse(raw) as { api_key?: unknown };
159
- if (typeof parsed.api_key === 'string' && parsed.api_key.trim().length > 0) {
160
- return `user_${hashString(parsed.api_key.trim())}`;
161
- }
162
- } catch {
163
- // Ignore user config read failures.
164
+ yield* fs
165
+ .makeDirectory(paths.analyticsDir, { recursive: true })
166
+ .pipe(Effect.catchAll(() => Effect.void));
167
+
168
+ const state = yield* readOptionalJson<{ install_id?: unknown }>(paths.analyticsStatePath);
169
+ if (typeof state?.install_id === 'string' && state.install_id.length > 0) {
170
+ return state.install_id;
171
}
172
166
- return null;
167
-};
173
+ const installId = yield* makeInstallId;
174
+ const createdAt = DateTime.formatIso(yield* DateTime.now);
175
+ const contents = yield* encodeJson({
176
+ install_id: installId,
177
+ created_at: createdAt,
178
+ });
179
+ yield* fs.writeFileString(paths.analyticsStatePath, contents);
180
+ return installId;
181
+}).pipe(Effect.catchAll(() => makeInstallId));
182
169
-const getDistinctId = (): string => getHashedApiKeyDistinctId() ?? `anon_${getOrCreateInstallId()}`;
183
+const readUserConfig = Effect.gen(function* () {
184
+ const paths = yield* getAnalyticsPaths;
185
+ return yield* readOptionalJson<{ api_key?: unknown; base_url?: unknown }>(paths.userConfigPath);
186
+});
187
171
-const getUserApiKey = (): string | null => {
172
- const envApiKey = process.env.COMPOSIO_USER_API_KEY?.trim();
188
+const getUserApiKey = Effect.gen(function* () {
189
+ const envApiKey = configuredString(
190
+ yield* environmentProvider.load(optionalString('COMPOSIO_USER_API_KEY'))
191
+ );
192
if (envApiKey) {
193
return envApiKey;
194
}
195
177
- try {
178
- const raw = fs.readFileSync(userConfigPath(), 'utf8');
179
- const parsed = JSON.parse(raw) as { api_key?: unknown };
180
- if (typeof parsed.api_key === 'string' && parsed.api_key.trim().length > 0) {
181
- return parsed.api_key.trim();
182
- }
183
- } catch {
184
- // Ignore user config read failures.
185
- }
196
+ const userConfig = yield* readUserConfig;
197
+ return typeof userConfig?.api_key === 'string' && userConfig.api_key.trim().length > 0
198
+ ? userConfig.api_key.trim()
199
+ : null;
200
+});
201
187
- return null;
188
-};
202
+const getDistinctId = (installId: string) =>
203
+ Effect.map(getUserApiKey, userApiKey =>
204
+ userApiKey ? `user_${hashString(userApiKey)}` : `anon_${installId}`
205
+ );
206
207
const cwdHash = (cwd: string): string => djb2Hash(cwd).toString(36);
208
192
-export const getCurrentCwdSessionId = (): string | undefined => {
193
- try {
194
- const raw = fs.readFileSync(consumerShortTermCachePath(), 'utf8');
195
- const parsed = JSON.parse(raw) as ConsumerShortTermCacheState;
196
- const currentCwdHash = cwdHash(process.cwd());
197
- const now = Date.now();
209
+export const getCurrentCwdSessionId = (cwd = process.cwd()) =>
210
+ Effect.gen(function* () {
211
+ const paths = yield* getAnalyticsPaths;
212
+ const state = yield* readOptionalJson<ConsumerShortTermCacheState>(
213
+ paths.consumerShortTermCachePath
214
+ );
215
+ if (!state) {
216
+ return undefined;
217
+ }
218
+
219
+ const currentCwdHash = cwdHash(cwd);
220
+ const now = yield* Clock.currentTimeMillis;
221
let best: { id: string; expiresAtMs: number } | undefined;
222
200
- for (const entry of Object.values(parsed)) {
223
+ for (const entry of Object.values(state)) {
224
const session = entry.probablyMyCliSessionsByCwdHash?.[currentCwdHash];
225
if (!session?.id) continue;
226
const expiresAtMs = Date.parse(session.expiresAt);
231
}
232
233
return best?.id;
211
- } catch {
212
- return undefined;
213
- }
214
-};
215
-
216
-const withCliSessionId = (event: TrackEvent): TrackEvent => {
217
- if (!event) return event;
218
- const cliSessionId = getCurrentCwdSessionId();
219
- return {
220
- ...event,
221
- properties: {
222
- ...(event.properties ?? {}),
223
- cli_version: event.properties?.cli_version ?? constants.APP_VERSION,
224
- ...(cliSessionId ? { cli_session_id: cliSessionId } : {}),
225
- },
226
- };
227
-};
234
+ }).pipe(Effect.catchAllCause(() => Effect.succeed(undefined)));
235
+
236
+const withCliSessionId = (event: NonNullable<TrackEvent>, cliSessionId?: string): TrackEvent => ({
237
+ ...event,
238
+ properties: {
239
+ ...(event.properties ?? {}),
240
+ cli_version: event.properties?.cli_version ?? constants.APP_VERSION,
241
+ ...(cliSessionId ? { cli_session_id: cliSessionId } : {}),
242
+ },
243
+});
244
229
-export const readApiBaseUrl = (): string | null => {
230
- const envBaseUrl = process.env.COMPOSIO_BASE_URL?.trim();
245
+export const readApiBaseUrl = Effect.gen(function* () {
246
+ const envBaseUrl = configuredString(
247
+ yield* environmentProvider.load(optionalString('COMPOSIO_BASE_URL'))
248
+ );
249
if (envBaseUrl) {
250
return envBaseUrl.replace(/\/+$/u, '');
251
}
252
235
- try {
236
- const raw = fs.readFileSync(userConfigPath(), 'utf8');
237
- const parsed = JSON.parse(raw) as { base_url?: unknown };
238
- if (typeof parsed.base_url === 'string' && parsed.base_url.trim().length > 0) {
239
- return parsed.base_url.trim().replace(/\/+$/u, '');
240
- }
241
- } catch {
242
- // Ignore user config read failures.
243
- }
244
-
245
- return null;
246
-};
253
+ const userConfig = yield* readUserConfig;
254
+ return typeof userConfig?.base_url === 'string' && userConfig.base_url.trim().length > 0
255
+ ? userConfig.base_url.trim().replace(/\/+$/u, '')
256
+ : null;
257
+}).pipe(Effect.catchAllCause(() => Effect.succeed(null)));
258
+
259
+const getAnalyticsEndpoint = Effect.map(readApiBaseUrl, baseUrl =>
260
+ baseUrl ? `${baseUrl}${CLI_ANALYTICS_PATH}` : null
261
+);
262
+
263
+const getCliCodactFailuresEndpoint = Effect.map(readApiBaseUrl, baseUrl =>
264
+ baseUrl ? `${baseUrl}${CLI_CODACT_FAILURES_PATH}` : null
265
+);
266
+
267
+const getWorkerSpawnArgs = (workerFlag: string, encodedPayload: string) =>
268
+ Effect.gen(function* () {
269
+ const fs = yield* FileSystem.FileSystem;
270
+ const maybeScriptPath = process.argv[1];
271
+ const scriptPathExists =
272
+ typeof maybeScriptPath === 'string' && maybeScriptPath.length > 0
273
+ ? yield* fs.exists(maybeScriptPath).pipe(Effect.catchAll(() => Effect.succeed(false)))
274
+ : false;
275
+ const scriptPathLooksReal =
276
+ scriptPathExists && /\.(?:[cm]?[jt]s|mjs|mts|cts)$/u.test(maybeScriptPath ?? '');
277
+
278
+ return scriptPathLooksReal
279
+ ? {
280
+ command: process.execPath,
281
+ args: [maybeScriptPath as string, workerFlag, encodedPayload],
282
+ }
283
+ : {
284
+ command: process.execPath,
285
+ args: [workerFlag, encodedPayload],
286
+ };
287
+ });
288
248
-const getAnalyticsEndpoint = (): string | null => {
249
- const baseUrl = readApiBaseUrl();
250
- return baseUrl ? `${baseUrl}${CLI_ANALYTICS_PATH}` : null;
251
-};
289
+// Effect's Command processes are scoped and die with their scope; telemetry
290
+// workers intentionally outlive the CLI process, so they go through the
291
+// sanctioned detached-spawn boundary in src/services/detached-process.
292
+// Delivery is best effort: a failed spawn is swallowed, never surfaced.
293
+const spawnWorker = (command: string, args: ReadonlyArray<string>) =>
294
+ Effect.gen(function* () {
295
+ const debugEnabled = yield* telemetryDebugEnabled;
296
+ yield* spawnDetached(command, args, { inheritStderr: debugEnabled }).pipe(
297
+ Effect.catchTag('services/DetachedProcessSpawnError', () => Effect.void)
298
+ );
299
+ });
300
253
-const getCliCodactFailuresEndpoint = (): string | null => {
254
- const baseUrl = readApiBaseUrl();
255
- return baseUrl ? `${baseUrl}${CLI_CODACT_FAILURES_PATH}` : null;
256
-};
301
+const captureToComposioAnalytics = (envelope: AnalyticsEnvelope) =>
302
+ Effect.gen(function* () {
303
+ const endpoint = yield* getAnalyticsEndpoint;
304
+ const disabled = yield* analyticsDisabled;
305
+ if (!endpoint || disabled) {
306
+ yield* telemetryDebugLog('delivery_skipped', {
307
+ reason: disabled ? 'disabled' : 'missing_endpoint',
308
+ endpoint,
309
+ eventName: envelope.event,
310
+ });
311
+ return;
312
+ }
313
258
-export const shouldDisableAnalytics = (): boolean =>
259
- truthy(process.env.COMPOSIO_CLI_TELEMETRY_DISABLED) ||
260
- truthy(process.env.TELEMETRY_DISABLED) ||
261
- truthy(process.env.COMPOSIO_DISABLE_TELEMETRY) ||
262
- process.env.NODE_ENV === 'test' ||
263
- process.env.CI === 'true';
264
-
265
-const getWorkerSpawnArgs = (encodedPayload: string): { command: string; args: string[] } => {
266
- const maybeScriptPath = process.argv[1];
267
- const scriptPathLooksReal =
268
- typeof maybeScriptPath === 'string' &&
269
- maybeScriptPath.length > 0 &&
270
- fs.existsSync(maybeScriptPath) &&
271
- /\.(?:[cm]?[jt]s|mjs|mts|cts)$/u.test(maybeScriptPath);
272
-
273
- return scriptPathLooksReal
274
- ? {
275
- command: process.execPath,
276
- args: [maybeScriptPath, INTERNAL_ANALYTICS_WORKER_FLAG, encodedPayload],
277
- }
278
- : {
279
- command: process.execPath,
280
- args: [INTERNAL_ANALYTICS_WORKER_FLAG, encodedPayload],
281
- };
282
-};
314
+ const httpClient = yield* HttpClient.HttpClient;
315
+ const userApiKey = yield* getUserApiKey;
316
+ const request = yield* HttpClientRequest.post(endpoint).pipe(
317
+ HttpClientRequest.setHeaders({
318
+ 'x-composio-analytics-source': 'cli',
319
+ ...(userApiKey ? { 'x-user-api-key': userApiKey } : {}),
320
+ }),
321
+ HttpClientRequest.bodyJson(envelope)
322
+ );
323
+ const response = yield* httpClient.execute(request);
324
+ const responseOk = response.status >= 200 && response.status < 300;
325
+ const debugEnabled = yield* telemetryDebugEnabled;
326
+ const responseBody = !responseOk && debugEnabled ? yield* response.text : undefined;
327
284
-const captureToComposioAnalytics = async (envelope: AnalyticsEnvelope): Promise<void> => {
285
- const endpoint = getAnalyticsEndpoint();
286
- if (!endpoint || shouldDisableAnalytics()) {
287
- telemetryDebugLog('delivery_skipped', {
288
- reason: shouldDisableAnalytics() ? 'disabled' : 'missing_endpoint',
328
+ yield* telemetryDebugLog(responseOk ? 'delivery_succeeded' : 'delivery_failed', {
329
endpoint,
330
eventName: envelope.event,
331
+ status: response.status,
332
+ ok: responseOk,
333
+ responseBody: responseBody?.slice(0, 1000),
334
});
292
- return;
293
- }
294
-
295
- const userApiKey = getUserApiKey();
296
- const response = await fetch(endpoint, {
297
- method: 'POST',
298
- headers: {
299
- 'Content-Type': 'application/json',
300
- 'x-composio-analytics-source': 'cli',
301
- ...(userApiKey ? { 'x-user-api-key': userApiKey } : {}),
302
- },
303
- body: JSON.stringify(envelope),
335
});
305
- const responseBody =
306
- !response.ok && isTelemetryDebugEnabled() ? await response.text() : undefined;
307
-
308
- telemetryDebugLog(response.ok ? 'delivery_succeeded' : 'delivery_failed', {
309
- endpoint,
310
- eventName: envelope.event,
311
- status: response.status,
312
- ok: response.ok,
313
- responseBody: responseBody?.slice(0, 1000),
314
- });
315
-};
336
317
-export const createCliCodactFailureBody = (
318
- failure: CliCodactFailure
319
-): {
337
+type CliCodactFailureBody = {
338
failure_type: CliCodactFailureType;
339
tool_info?: CliCodactFailureToolInfo;
340
ctx: Record<string, unknown>;
341
session: Record<string, unknown>;
342
request_id?: string;
325
-} => ({
343
+};
344
+
345
+type CliInvocationContext = {
346
+ readonly origin?: string;
347
+ readonly parentRunId?: string;
348
+};
349
+
350
+const getCliInvocationContext = environmentProvider
351
+ .load(
352
+ Config.all({
353
+ origin: optionalString('COMPOSIO_CLI_INVOCATION_ORIGIN'),
354
+ parentRunId: optionalString('COMPOSIO_CLI_PARENT_RUN_ID'),
355
+ })
356
+ )
357
+ .pipe(
358
+ Effect.map(({ origin, parentRunId }) => ({
359
+ origin: configuredString(origin),
360
+ parentRunId: configuredString(parentRunId),
361
+ }))
362
+ );
363
+
364
+export const createCliCodactFailureBody = (
365
+ failure: CliCodactFailure,
366
+ cliSessionId?: string,
367
+ invocation: CliInvocationContext = {}
368
+): CliCodactFailureBody => ({
369
failure_type: failure.failureType,
370
...(failure.toolInfo ? { tool_info: failure.toolInfo } : {}),
371
ctx: failure.ctx,
372
session: {
373
source: 'cli',
331
- id: getCurrentCwdSessionId(),
374
+ id: cliSessionId,
375
cli_version: constants.APP_VERSION,
333
- invocation_origin: process.env.COMPOSIO_CLI_INVOCATION_ORIGIN ?? 'cli',
334
- parent_run_id: process.env.COMPOSIO_CLI_PARENT_RUN_ID,
376
+ invocation_origin: invocation.origin ?? 'cli',
377
+ parent_run_id: invocation.parentRunId,
378
...(failure.session ?? {}),
379
},
380
...(failure.requestId ? { request_id: failure.requestId } : {}),
381
});
382
340
-const captureToComposioCodactFailures = async (failure: CliCodactFailure): Promise<void> => {
341
- const endpoint = getCliCodactFailuresEndpoint();
342
- if (!endpoint || shouldDisableAnalytics()) {
343
- telemetryDebugLog('codact_delivery_skipped', {
344
- reason: shouldDisableAnalytics() ? 'disabled' : 'missing_endpoint',
345
- endpoint,
346
- failureType: failure.failureType,
347
- });
348
- return;
349
- }
383
+const captureToComposioCodactFailures = (failure: CliCodactFailure) =>
384
+ Effect.gen(function* () {
385
+ const endpoint = yield* getCliCodactFailuresEndpoint;
386
+ const disabled = yield* analyticsDisabled;
387
+ if (!endpoint || disabled) {
388
+ yield* telemetryDebugLog('codact_delivery_skipped', {
389
+ reason: disabled ? 'disabled' : 'missing_endpoint',
390
+ endpoint,
391
+ failureType: failure.failureType,
392
+ });
393
+ return;
394
+ }
395
+
396
+ const userApiKey = yield* getUserApiKey;
397
+ if (!userApiKey) {
398
+ yield* telemetryDebugLog('codact_delivery_skipped', {
399
+ reason: 'missing_user_api_key',
400
+ endpoint,
401
+ failureType: failure.failureType,
402
+ });
403
+ return;
404
+ }
405
351
- const userApiKey = getUserApiKey();
352
- if (!userApiKey) {
353
- telemetryDebugLog('codact_delivery_skipped', {
354
- reason: 'missing_user_api_key',
406
+ const httpClient = yield* HttpClient.HttpClient;
407
+ const cliSessionId = yield* getCurrentCwdSessionId();
408
+ const invocation = yield* getCliInvocationContext;
409
+ const body = createCliCodactFailureBody(failure, cliSessionId, invocation);
410
+ const request = yield* HttpClientRequest.post(endpoint).pipe(
411
+ HttpClientRequest.setHeader('x-user-api-key', userApiKey),
412
+ HttpClientRequest.bodyJson(body)
413
+ );
414
+ const response = yield* httpClient.execute(request);
415
+ const responseOk = response.status >= 200 && response.status < 300;
416
+ const debugEnabled = yield* telemetryDebugEnabled;
417
+ const responseBody = !responseOk && debugEnabled ? yield* response.text : undefined;
418
+
419
+ yield* telemetryDebugLog(responseOk ? 'codact_delivery_succeeded' : 'codact_delivery_failed', {
420
endpoint,
421
failureType: failure.failureType,
422
+ status: response.status,
423
+ ok: responseOk,
424
+ responseBody: responseBody?.slice(0, 1000),
425
});
358
- return;
359
- }
360
-
361
- const response = await fetch(endpoint, {
362
- method: 'POST',
363
- headers: {
364
- 'Content-Type': 'application/json',
365
- 'x-user-api-key': userApiKey,
366
- },
367
- body: JSON.stringify(createCliCodactFailureBody(failure)),
368
- });
369
- const responseBody =
370
- !response.ok && isTelemetryDebugEnabled() ? await response.text() : undefined;
371
-
372
- telemetryDebugLog(response.ok ? 'codact_delivery_succeeded' : 'codact_delivery_failed', {
373
- endpoint,
374
- failureType: failure.failureType,
375
- status: response.status,
376
- ok: response.ok,
377
- responseBody: responseBody?.slice(0, 1000),
426
});
379
-};
427
381
-export const trackCliEvent = (event: TrackEvent): void => {
382
- const endpoint = getAnalyticsEndpoint();
383
- if (!event) {
384
- return;
385
- }
428
+export const trackCliEventEffect = (event: TrackEvent) =>
429
+ Effect.gen(function* () {
430
+ if (!event) {
431
+ return;
432
+ }
433
387
- if (shouldDisableAnalytics() || !endpoint) {
388
- telemetryDebugLog('skip', {
389
- reason: shouldDisableAnalytics() ? 'disabled' : 'missing_endpoint',
390
- eventName: event.name,
391
- endpoint,
392
- });
393
- return;
394
- }
434
+ const endpoint = yield* getAnalyticsEndpoint;
435
+ const disabled = yield* analyticsDisabled;
436
+ if (disabled || !endpoint) {
437
+ yield* telemetryDebugLog('skip', {
438
+ reason: disabled ? 'disabled' : 'missing_endpoint',
439
+ eventName: event.name,
440
+ endpoint,
441
+ });
442
+ return;
443
+ }
444
396
- try {
397
- const enrichedEvent = withCliSessionId(event);
445
+ const cliSessionId = yield* getCurrentCwdSessionId();
446
+ const enrichedEvent = withCliSessionId(event, cliSessionId);
447
if (!enrichedEvent) {
448
return;
449
}
401
- const installId = getOrCreateInstallId();
402
- const distinctId = getDistinctId();
450
+
451
+ const installId = yield* getOrCreateInstallId;
452
+ const distinctId = yield* getDistinctId(installId);
453
+ const sentAt = DateTime.formatIso(yield* DateTime.now);
454
const envelope: AnalyticsEnvelope = {
455
event: enrichedEvent.name,
456
...(enrichedEvent.properties ? { properties: enrichedEvent.properties } : {}),
406
- sentAt: new Date().toISOString(),
457
+ sentAt,
458
source: 'cli',
459
distinctId,
460
installId,
461
};
411
- telemetryDebugLog('enqueue', {
412
- endpoint,
413
- envelope,
414
- });
415
- const encodedPayload = encodeBase64Url(JSON.stringify(envelope));
416
- const { command, args } = getWorkerSpawnArgs(encodedPayload);
417
- const child = spawn(command, args, {
418
- detached: true,
419
- stdio: isTelemetryDebugEnabled() ? ['ignore', 'ignore', 'inherit'] : 'ignore',
420
- env: {
421
- ...process.env,
422
- COMPOSIO_CLI_ANALYTICS_WORKER: '1',
423
- },
424
- });
425
- child.unref();
426
- } catch {
427
- // Analytics must never break CLI execution.
428
- }
429
-};
462
+ yield* telemetryDebugLog('enqueue', { endpoint, envelope });
463
+ const serializedEnvelope = yield* encodeJson(envelope);
464
+ const encodedPayload = Encoding.encodeBase64Url(serializedEnvelope);
465
+ const { command, args } = yield* getWorkerSpawnArgs(
466
+ INTERNAL_ANALYTICS_WORKER_FLAG,
467
+ encodedPayload
468
+ );
469
+ yield* spawnWorker(command, args);
470
+ }).pipe(Effect.catchAllCause(() => Effect.void));
471
431
-export const trackCliEventEffect = (event: TrackEvent) => Effect.sync(() => trackCliEvent(event));
432
-
433
-export const trackCliCodactFailure = (failure: CliCodactFailure): void => {
434
- const endpoint = getCliCodactFailuresEndpoint();
435
- const userApiKey = getUserApiKey();
436
- if (shouldDisableAnalytics() || !endpoint || !userApiKey) {
437
- telemetryDebugLog('codact_skip', {
438
- reason: shouldDisableAnalytics()
439
- ? 'disabled'
440
- : !endpoint
441
- ? 'missing_endpoint'
442
- : 'missing_user_api_key',
443
- failureType: failure.failureType,
444
- endpoint,
445
- });
446
- return;
447
- }
472
+export const trackCliCodactFailureEffect = (failure: CliCodactFailure) =>
473
+ Effect.gen(function* () {
474
+ const endpoint = yield* getCliCodactFailuresEndpoint;
475
+ const userApiKey = yield* getUserApiKey;
476
+ const disabled = yield* analyticsDisabled;
477
+ if (disabled || !endpoint || !userApiKey) {
478
+ yield* telemetryDebugLog('codact_skip', {
479
+ reason: disabled ? 'disabled' : !endpoint ? 'missing_endpoint' : 'missing_user_api_key',
480
+ failureType: failure.failureType,
481
+ endpoint,
482
+ });
483
+ return;
484
+ }
485
449
- try {
450
- const encodedPayload = encodeBase64Url(JSON.stringify(createCliCodactFailureBody(failure)));
451
- const { command, args } = getWorkerSpawnArgsForFlag(
486
+ const cliSessionId = yield* getCurrentCwdSessionId();
487
+ const invocation = yield* getCliInvocationContext;
488
+ const body = yield* encodeJson(createCliCodactFailureBody(failure, cliSessionId, invocation));
489
+ const encodedPayload = Encoding.encodeBase64Url(body);
490
+ const { command, args } = yield* getWorkerSpawnArgs(
491
INTERNAL_CODACT_FAILURE_WORKER_FLAG,
492
encodedPayload
493
);
455
- const child = spawn(command, args, {
456
- detached: true,
457
- stdio: isTelemetryDebugEnabled() ? ['ignore', 'ignore', 'inherit'] : 'ignore',
458
- env: {
459
- ...process.env,
460
- COMPOSIO_CLI_ANALYTICS_WORKER: '1',
461
- },
462
- });
463
- child.unref();
464
- } catch {
465
- // Best-effort — codact failure tracking must never break CLI execution.
466
- }
467
-};
468
-
469
-export const trackCliCodactFailureEffect = (failure: CliCodactFailure) =>
470
- Effect.sync(() => trackCliCodactFailure(failure));
471
-
472
-const getWorkerSpawnArgsForFlag = (
473
- workerFlag: string,
474
- encodedPayload: string
475
-): { command: string; args: string[] } => {
476
- const maybeScriptPath = process.argv[1];
477
- const scriptPathLooksReal =
478
- typeof maybeScriptPath === 'string' &&
479
- maybeScriptPath.length > 0 &&
480
- fs.existsSync(maybeScriptPath) &&
481
- /\.(?:[cm]?[jt]s|mjs|mts|cts)$/u.test(maybeScriptPath);
482
-
483
- return scriptPathLooksReal
484
- ? {
485
- command: process.execPath,
486
- args: [maybeScriptPath, workerFlag, encodedPayload],
487
- }
488
- : {
489
- command: process.execPath,
490
- args: [workerFlag, encodedPayload],
491
- };
492
-};
494
+ yield* spawnWorker(command, args);
495
+ }).pipe(Effect.catchAllCause(() => Effect.void));
496
497
const getWorkerFlagIndex = (argv: ReadonlyArray<string>, flag: string): number =>
498
argv.findIndex(token => token === flag);
501
getWorkerFlagIndex(argv, INTERNAL_ANALYTICS_WORKER_FLAG) >= 0 ||
502
getWorkerFlagIndex(argv, INTERNAL_CODACT_FAILURE_WORKER_FLAG) >= 0;
503
501
-export const runBackgroundWorkerFromArgv = async (argv: ReadonlyArray<string>): Promise<void> => {
502
- const analyticsFlagIndex = getWorkerFlagIndex(argv, INTERNAL_ANALYTICS_WORKER_FLAG);
503
- if (analyticsFlagIndex >= 0) {
504
- const encodedPayload = argv[analyticsFlagIndex + 1];
505
- if (!encodedPayload) {
506
- return;
507
- }
504
+const decodeWorkerPayload = <A>(encodedPayload: string) =>
505
+ Effect.gen(function* () {
506
+ const serialized = yield* Encoding.decodeBase64UrlString(encodedPayload);
507
+ return (yield* decodeJson(serialized)) as A;
508
+ });
509
509
- try {
510
- const decoded = decodeBase64Url(encodedPayload);
511
- const envelope = JSON.parse(decoded) as AnalyticsEnvelope;
512
- if (typeof envelope?.event !== 'string' || envelope.event.length === 0) {
513
- return;
514
- }
515
- await captureToComposioAnalytics(envelope);
516
- } catch (error) {
517
- telemetryDebugLog('delivery_error', {
518
- error:
519
- error instanceof Error
520
- ? { name: error.name, message: error.message }
521
- : { message: String(error) },
522
- });
523
- }
524
- return;
510
+const runAnalyticsWorker = (argv: ReadonlyArray<string>) => {
511
+ const flagIndex = getWorkerFlagIndex(argv, INTERNAL_ANALYTICS_WORKER_FLAG);
512
+ if (flagIndex < 0) {
513
+ return Effect.succeed(false);
514
+ }
515
+
516
+ const encodedPayload = argv[flagIndex + 1];
517
+ if (!encodedPayload) {
518
+ return Effect.succeed(true);
519
}
520
527
- const codactFlagIndex = getWorkerFlagIndex(argv, INTERNAL_CODACT_FAILURE_WORKER_FLAG);
528
- if (codactFlagIndex < 0) {
529
- return;
521
+ return Effect.gen(function* () {
522
+ const envelope = yield* decodeWorkerPayload<AnalyticsEnvelope>(encodedPayload);
523
+ if (typeof envelope?.event !== 'string' || envelope.event.length === 0) {
524
+ return true;
525
+ }
526
+ yield* captureToComposioAnalytics(envelope);
527
+ return true;
528
+ }).pipe(
529
+ Effect.catchAllCause(cause =>
530
+ telemetryDebugLog('delivery_error', { error: telemetryErrorDetails(cause) }).pipe(
531
+ Effect.as(true)
532
+ )
533
+ )
534
+ );
535
+};
536
+
537
+const runCodactFailureWorker = (argv: ReadonlyArray<string>) => {
538
+ const flagIndex = getWorkerFlagIndex(argv, INTERNAL_CODACT_FAILURE_WORKER_FLAG);
539
+ if (flagIndex < 0) {
540
+ return Effect.void;
541
}
542
532
- const encodedPayload = argv[codactFlagIndex + 1];
543
+ const encodedPayload = argv[flagIndex + 1];
544
if (!encodedPayload) {
534
- return;
545
+ return Effect.void;
546
}
547
537
- try {
538
- const decoded = decodeBase64Url(encodedPayload);
539
- const body = JSON.parse(decoded) as ReturnType<typeof createCliCodactFailureBody>;
548
+ return Effect.gen(function* () {
549
+ const body =
550
+ yield* decodeWorkerPayload<ReturnType<typeof createCliCodactFailureBody>>(encodedPayload);
551
if (
552
body?.failure_type !== 'wrong_tool_slug' &&
553
body?.failure_type !== 'wrong_tool_input_param'
555
return;
556
}
557
547
- await captureToComposioCodactFailures({
558
+ yield* captureToComposioCodactFailures({
559
failureType: body.failure_type,
560
toolInfo: body.tool_info,
561
ctx: body.ctx,
562
session: body.session,
563
requestId: body.request_id,
564
});
554
- } catch (error) {
555
- telemetryDebugLog('codact_delivery_error', {
556
- error:
557
- error instanceof Error
558
- ? { name: error.name, message: error.message }
559
- : { message: String(error) },
560
- });
561
- }
565
+ }).pipe(
566
+ Effect.catchAllCause(cause =>
567
+ telemetryDebugLog('codact_delivery_error', { error: telemetryErrorDetails(cause) })
568
+ )
569
+ );
570
};
571
+
572
+export const runBackgroundWorkerFromArgv = (argv: ReadonlyArray<string>) =>
573
+ Effect.gen(function* () {
574
+ const handledAnalytics = yield* runAnalyticsWorker(argv);
575
+ if (!handledAnalytics) {
576
+ yield* runCodactFailureWorker(argv);
577
+ }
578
+ }).pipe(Effect.catchAllCause(() => Effect.void));