23
const COMPOSIO_DIR = '.composio';
24
const ANALYTICS_STATE_FILE_NAME = 'analytics.json';
25
const CONSUMER_SHORT_TERM_CACHE_FILE_NAME = 'consumer-short-term-cache.json';
26
-const CLI_ANALYTICS_PATH = '/api/v3/cli/analytics';
26
const CLI_CODACT_FAILURES_PATH = '/api/v3/cli/codact_failures';
27
28
+// PostHog's single-event capture endpoint expects `$create_alias` to merge an
29
+// anonymous person into an identified one (`properties.alias` -> `distinct_id`).
30
+const POSTHOG_ALIAS_EVENT = '$create_alias';
31
+const POSTHOG_LIB = 'composio-cli';
32
+
33
export type CliCodactFailureType = 'wrong_tool_slug' | 'wrong_tool_input_param';
34
35
export type CliCodactFailureToolInfo = {
102
)
103
);
104
105
+// Resolves the direct-to-PostHog transport target. Both fields fall back to the
106
+// embedded constants; env overrides exist for tests and staging. Crucially this
107
+// does NOT depend on the Composio API base URL (which is only written at login),
108
+// so pre-login install/setup events can be delivered.
109
+const getPostHogConfig = environmentProvider
110
+ .load(
111
+ Config.all({
112
+ ingestUrl: optionalString('COMPOSIO_POSTHOG_INGEST_URL'),
113
+ projectKey: optionalString('COMPOSIO_POSTHOG_KEY'),
114
+ })
115
+ )
116
+ .pipe(
117
+ Effect.map(({ ingestUrl, projectKey }) => ({
118
+ ingestUrl: configuredString(ingestUrl) ?? constants.COMPOSIO_POSTHOG_INGEST_URL,
119
+ projectKey: configuredString(projectKey) ?? constants.COMPOSIO_POSTHOG_PROJECT_KEY,
120
+ }))
121
+ );
122
+
123
const jsonFromString = Schema.parseJson();
124
const prettyJsonFromString = Schema.parseJson({ space: 2 });
125
const decodeJson = Schema.decodeUnknown(jsonFromString);
175
return (yield* decodeJson(raw)) as A;
176
}).pipe(Effect.catchAll(() => Effect.succeed(undefined)));
177
156
-const hashString = (value: string): string => djb2Hash(value).toString(16).padStart(8, '0');
178
+// Persisted `~/.composio/analytics.json`. `install_id` is the anonymous device
179
+// UUID; `apollo_user_id` (the Apollo `org_member.id`, persisted at login) becomes
180
+// the PostHog identity so CLI events join the same person as web onboarding.
181
+type AnalyticsState = {
182
+ readonly install_id?: string;
183
+ readonly apollo_user_id?: string;
184
+ readonly created_at?: string;
185
+};
186
187
const makeInstallId = Effect.sync(() => crypto.randomUUID());
188
189
+const readAnalyticsState = Effect.gen(function* () {
190
+ const paths = yield* getAnalyticsPaths;
191
+ return yield* readOptionalJson<AnalyticsState>(paths.analyticsStatePath);
192
+});
193
+
194
const getOrCreateInstallId = Effect.gen(function* () {
195
const fs = yield* FileSystem.FileSystem;
196
const paths = yield* getAnalyticsPaths;
199
.makeDirectory(paths.analyticsDir, { recursive: true })
200
.pipe(Effect.catchAll(() => Effect.void));
201
168
- const state = yield* readOptionalJson<{ install_id?: unknown }>(paths.analyticsStatePath);
202
+ const state = yield* readOptionalJson<AnalyticsState>(paths.analyticsStatePath);
203
if (typeof state?.install_id === 'string' && state.install_id.length > 0) {
204
return state.install_id;
205
}
207
const installId = yield* makeInstallId;
208
const createdAt = DateTime.formatIso(yield* DateTime.now);
209
const contents = yield* encodeJson({
210
+ ...(state ?? {}),
211
install_id: installId,
212
created_at: createdAt,
213
});
215
return installId;
216
}).pipe(Effect.catchAll(() => makeInstallId));
217
218
+const readApolloUserId = Effect.map(readAnalyticsState, state =>
219
+ typeof state?.apollo_user_id === 'string' && state.apollo_user_id.length > 0
220
+ ? state.apollo_user_id
221
+ : null
222
+);
223
+
224
+// Persists the Apollo `org_member.id` into the analytics state, preserving the
225
+// existing `install_id`/`created_at` so the anonymous device identity is kept
226
+// for the login-time alias. Best-effort: never surfaces or throws.
227
+const persistApolloUserId = (installId: string, apolloUserId: string) =>
228
+ Effect.gen(function* () {
229
+ const fs = yield* FileSystem.FileSystem;
230
+ const paths = yield* getAnalyticsPaths;
231
+
232
+ yield* fs
233
+ .makeDirectory(paths.analyticsDir, { recursive: true })
234
+ .pipe(Effect.catchAll(() => Effect.void));
235
+
236
+ const state = yield* readOptionalJson<AnalyticsState>(paths.analyticsStatePath);
237
+ const createdAt = state?.created_at ?? DateTime.formatIso(yield* DateTime.now);
238
+ const contents = yield* encodeJson({
239
+ ...(state ?? {}),
240
+ install_id: state?.install_id ?? installId,
241
+ apollo_user_id: apolloUserId,
242
+ created_at: createdAt,
243
+ });
244
+ yield* fs.writeFileString(paths.analyticsStatePath, contents);
245
+ }).pipe(Effect.catchAll(() => Effect.void));
246
+
247
const readUserConfig = Effect.gen(function* () {
248
const paths = yield* getAnalyticsPaths;
249
return yield* readOptionalJson<{ api_key?: unknown; base_url?: unknown }>(paths.userConfigPath);
263
: null;
264
});
265
266
+// Post-login events key on the Apollo `org_member.id` (persisted at login) so
267
+// they resolve to the same PostHog person as web onboarding. Pre-login, the raw
268
+// `install_id` is the distinct id (NOT wrapped as `anon_<id>` — the login-time
269
+// `$create_alias` merges this exact value into the Apollo person).
270
const getDistinctId = (installId: string) =>
203
- Effect.map(getUserApiKey, userApiKey =>
204
- userApiKey ? `user_${hashString(userApiKey)}` : `anon_${installId}`
205
- );
271
+ Effect.map(readApolloUserId, apolloUserId => apolloUserId ?? installId);
272
273
const cwdHash = (cwd: string): string => djb2Hash(cwd).toString(36);
274
322
: null;
323
}).pipe(Effect.catchAllCause(() => Effect.succeed(null)));
324
259
-const getAnalyticsEndpoint = Effect.map(readApiBaseUrl, baseUrl =>
260
- baseUrl ? `${baseUrl}${CLI_ANALYTICS_PATH}` : null
261
-);
262
-
325
const getCliCodactFailuresEndpoint = Effect.map(readApiBaseUrl, baseUrl =>
326
baseUrl ? `${baseUrl}${CLI_CODACT_FAILURES_PATH}` : null
327
);
360
);
361
});
362
301
-const captureToComposioAnalytics = (envelope: AnalyticsEnvelope) =>
363
+// Shapes an analytics envelope into a PostHog single-event capture body. The
364
+// public project write key authenticates the ingest in-band (no user API key),
365
+// which is what lets pre-login events send. Only allowlisted, already-shaped
366
+// properties from the event builders flow through here — no secrets or tool-arg
367
+// values (see events.ts).
368
+const buildPostHogBody = (envelope: AnalyticsEnvelope, projectKey: string) => ({
369
+ api_key: projectKey,
370
+ event: envelope.event,
371
+ distinct_id: envelope.distinctId,
372
+ timestamp: envelope.sentAt,
373
+ properties: {
374
+ ...(envelope.properties ?? {}),
375
+ install_id: envelope.installId,
376
+ $lib: POSTHOG_LIB,
377
+ $lib_version: constants.APP_VERSION,
378
+ },
379
+});
380
+
381
+const captureToPostHog = (envelope: AnalyticsEnvelope) =>
382
Effect.gen(function* () {
303
- const endpoint = yield* getAnalyticsEndpoint;
383
const disabled = yield* analyticsDisabled;
305
- if (!endpoint || disabled) {
306
- yield* telemetryDebugLog('delivery_skipped', {
307
- reason: disabled ? 'disabled' : 'missing_endpoint',
308
- endpoint,
384
+ const { ingestUrl, projectKey } = yield* getPostHogConfig;
385
+ if (disabled || projectKey.length === 0) {
386
+ yield* telemetryDebugLog('posthog_delivery_skipped', {
387
+ reason: disabled ? 'disabled' : 'missing_project_key',
388
+ endpoint: ingestUrl,
389
eventName: envelope.event,
390
});
391
return;
392
}
393
394
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)
395
+ const request = yield* HttpClientRequest.post(ingestUrl).pipe(
396
+ HttpClientRequest.setHeader('x-composio-analytics-source', 'cli'),
397
+ HttpClientRequest.bodyJson(buildPostHogBody(envelope, projectKey))
398
);
399
const response = yield* httpClient.execute(request);
400
const responseOk = response.status >= 200 && response.status < 300;
401
const debugEnabled = yield* telemetryDebugEnabled;
402
const responseBody = !responseOk && debugEnabled ? yield* response.text : undefined;
403
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
- });
404
+ yield* telemetryDebugLog(
405
+ responseOk ? 'posthog_delivery_succeeded' : 'posthog_delivery_failed',
406
+ {
407
+ endpoint: ingestUrl,
408
+ eventName: envelope.event,
409
+ status: response.status,
410
+ ok: responseOk,
411
+ responseBody: responseBody?.slice(0, 1000),
412
+ }
413
+ );
414
});
415
416
type CliCodactFailureBody = {
504
});
505
});
506
507
+// Encodes an envelope and hands it to the detached best-effort worker, which
508
+// delivers it directly to PostHog. Shared by event tracking and login aliasing.
509
+const enqueuePostHogEnvelope = (envelope: AnalyticsEnvelope) =>
510
+ Effect.gen(function* () {
511
+ yield* telemetryDebugLog('enqueue', { envelope });
512
+ const serializedEnvelope = yield* encodeJson(envelope);
513
+ const encodedPayload = Encoding.encodeBase64Url(serializedEnvelope);
514
+ const { command, args } = yield* getWorkerSpawnArgs(
515
+ INTERNAL_ANALYTICS_WORKER_FLAG,
516
+ encodedPayload
517
+ );
518
+ yield* spawnWorker(command, args);
519
+ });
520
+
521
export const trackCliEventEffect = (event: TrackEvent) =>
522
Effect.gen(function* () {
523
if (!event) {
524
return;
525
}
526
434
- const endpoint = yield* getAnalyticsEndpoint;
527
+ // The direct PostHog transport carries a fixed endpoint + embedded public
528
+ // key, so — unlike the old Apollo path — there is no base-URL gate here and
529
+ // pre-login install/setup events are delivered.
530
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
- });
531
+ if (disabled) {
532
+ yield* telemetryDebugLog('skip', { reason: 'disabled', eventName: event.name });
533
return;
534
}
535
550
distinctId,
551
installId,
552
};
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);
553
+ yield* enqueuePostHogEnvelope(envelope);
554
+ }).pipe(Effect.catchAllCause(() => Effect.void));
555
+
556
+// Fires a single PostHog `$create_alias` merging the anonymous `install_id`
557
+// device person into the identified Apollo `org_member.id` person. Best-effort.
558
+export const emitPostHogAlias = (installId: string, apolloUserId: string) =>
559
+ Effect.gen(function* () {
560
+ const disabled = yield* analyticsDisabled;
561
+ if (disabled) {
562
+ yield* telemetryDebugLog('alias_skip', { reason: 'disabled', installId });
563
+ return;
564
+ }
565
+
566
+ const sentAt = DateTime.formatIso(yield* DateTime.now);
567
+ const envelope: AnalyticsEnvelope = {
568
+ event: POSTHOG_ALIAS_EVENT,
569
+ properties: {
570
+ // PostHog merges `properties.alias` into the event's `distinct_id`.
571
+ distinct_id: apolloUserId,
572
+ alias: installId,
573
+ cli_version: constants.APP_VERSION,
574
+ },
575
+ sentAt,
576
+ source: 'cli',
577
+ distinctId: apolloUserId,
578
+ installId,
579
+ };
580
+ yield* enqueuePostHogEnvelope(envelope);
581
+ }).pipe(Effect.catchAllCause(() => Effect.void));
582
+
583
+// Called at login: persists the Apollo `org_member.id` as the analytics identity
584
+// and stitches the pre-login anonymous device into that person via one alias.
585
+// Fully non-fatal so login never fails on telemetry.
586
+export const linkApolloIdentityForAnalytics = (apolloUserId: string) =>
587
+ Effect.gen(function* () {
588
+ if (typeof apolloUserId !== 'string' || apolloUserId.trim().length === 0) {
589
+ return;
590
+ }
591
+
592
+ const disabled = yield* analyticsDisabled;
593
+ const installId = yield* getOrCreateInstallId;
594
+ yield* persistApolloUserId(installId, apolloUserId);
595
+ if (disabled) {
596
+ return;
597
+ }
598
+ yield* emitPostHogAlias(installId, apolloUserId);
599
}).pipe(Effect.catchAllCause(() => Effect.void));
600
601
export const trackCliCodactFailureEffect = (failure: CliCodactFailure) =>
652
if (typeof envelope?.event !== 'string' || envelope.event.length === 0) {
653
return true;
654
}
526
- yield* captureToComposioAnalytics(envelope);
655
+ yield* captureToPostHog(envelope);
656
return true;
657
}).pipe(
658
Effect.catchAllCause(cause =>