@devries-cameron20 / composio Mirror · read-only / commits / 4bdbaecc1
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 21, 18:30 UTC

fix(cli): simplify analytics identity dispatch

Kshitij Jhunjhunwala committed Jul 29, 2026 at 18:07 UTC 4bdbaecc10f5d3e2e17a1f7ab2a986615dd8130c
5 files changed +263 -267
mise.lock
+8 -12
@@ -89,23 +89,23 @@ version = "3.12.13"
89 backend = "core:python"
90
91 [tools.python."platforms.linux-arm64"]
92 -checksum = "sha256:e125d3e75034fe75d49ae8577b53758b0bb7d7817fadde2c020ad2cf7afe64c4"
93 -url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260728/cpython-3.12.13+20260728-aarch64-unknown-linux-gnu-install_only_stripped.tar.gz"
92 +checksum = "sha256:f226576b91491ffa5739aa85726521e9031f4d87f80627d64ed348ac77cb31e9"
93 +url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260718/cpython-3.12.13+20260718-aarch64-unknown-linux-gnu-install_only_stripped.tar.gz"
94 provenance = "github-attestations"
95
96 [tools.python."platforms.linux-x64"]
97 -checksum = "sha256:7ceaf4360f4b4ab44f31d8217cfdc70df8e12b61d9561b4900ee7af87176e50d"
98 -url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260728/cpython-3.12.13+20260728-x86_64-unknown-linux-gnu-install_only_stripped.tar.gz"
97 +checksum = "sha256:5854aa6ec71cad00334d5065633c210b2e7feb40956767a59a91791cadcf0b79"
98 +url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260718/cpython-3.12.13+20260718-x86_64-unknown-linux-gnu-install_only_stripped.tar.gz"
99 provenance = "github-attestations"
100
101 [tools.python."platforms.macos-arm64"]
102 -checksum = "sha256:2f18cdef4125ca1440dd1ba00ebcb267526efb532138c0860438f755ea4eebac"
103 -url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260728/cpython-3.12.13+20260728-aarch64-apple-darwin-install_only_stripped.tar.gz"
102 +checksum = "sha256:9a1e9e06175c10efd8378b904b07fa21bd791ab3345d7cdffeb4a76c9ff55903"
103 +url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260718/cpython-3.12.13+20260718-aarch64-apple-darwin-install_only_stripped.tar.gz"
104 provenance = "github-attestations"
105
106 [tools.python."platforms.macos-x64"]
107 -checksum = "sha256:e654c21d0ba53e2c671868d4112fac5874deca4c35226d36c5cfe53bc5c9cd71"
108 -url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260728/cpython-3.12.13+20260728-x86_64-apple-darwin-install_only_stripped.tar.gz"
107 +checksum = "sha256:8e6b7e6533bdf746287008edf91102e7bee0a6ca1d24f16c4514237cafd706c5"
108 +url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260718/cpython-3.12.13+20260718-x86_64-apple-darwin-install_only_stripped.tar.gz"
109 provenance = "github-attestations"
110
111 [[tools.uv]]
@@ -115,19 +115,15 @@ backend = "aqua:astral-sh/uv"
115 [tools.uv."platforms.linux-arm64"]
116 checksum = "sha256:87925376fa1e59de23582e1cbd81d6aabd16611e871ad085e09be2c2fa12689d"
117 url = "https://github.com/astral-sh/uv/releases/download/0.8.19/uv-aarch64-unknown-linux-musl.tar.gz"
118 -url_api = "https://api.github.com/repos/astral-sh/uv/releases/assets/295160192"
118
119 [tools.uv."platforms.linux-x64"]
120 checksum = "sha256:6a37f712ae90c7b8cf364fe751144d7acc2479d6b336378111e74cc7fb14fa7b"
121 url = "https://github.com/astral-sh/uv/releases/download/0.8.19/uv-x86_64-unknown-linux-musl.tar.gz"
123 -url_api = "https://api.github.com/repos/astral-sh/uv/releases/assets/295160235"
122
123 [tools.uv."platforms.macos-arm64"]
124 checksum = "sha256:bb63d43c40a301d889a985223ee8ce540be199e98b3f27ed8477823869a0a605"
125 url = "https://github.com/astral-sh/uv/releases/download/0.8.19/uv-aarch64-apple-darwin.tar.gz"
128 -url_api = "https://api.github.com/repos/astral-sh/uv/releases/assets/295160180"
126
127 [tools.uv."platforms.macos-x64"]
128 checksum = "sha256:b5f91770e55761b32c9618757ef23ded6671bb9ca0ddf5737eea60dddd493fe9"
129 url = "https://github.com/astral-sh/uv/releases/download/0.8.19/uv-x86_64-apple-darwin.tar.gz"
133 -url_api = "https://api.github.com/repos/astral-sh/uv/releases/assets/295160227"
ts/packages/cli/src/analytics/dispatch.ts
+117 -113
@@ -13,7 +13,8 @@ import {
13 Schema,
14 } from 'effect';
15 import * as constants from 'src/constants';
16 -import { spawnDetached } from 'src/services/detached-process';
16 +import { getDetachedWorkerSpawnArgs, spawnDetached } from 'src/services/detached-process';
17 +import { sha256Hex } from 'src/utils/checksums';
18 import { djb2Hash } from 'src/utils/djb2';
19 import { NodeOs } from 'src/services/node-os';
20 import { TerminalUI } from 'src/services/terminal-ui';
@@ -26,7 +27,8 @@ const ANALYTICS_STATE_FILE_NAME = 'analytics.json';
27 const ANALYTICS_STATE_LOCK_FILE_NAME = `${ANALYTICS_STATE_FILE_NAME}.lock`;
28 const ANALYTICS_STATE_LOCK_STALE_MS = 30_000;
29 const ANALYTICS_STATE_LOCK_RETRY_MS = 10;
29 -const ANALYTICS_STATE_LOCK_TIMEOUT_MS = ANALYTICS_STATE_LOCK_STALE_MS + 5_000;
30 +const ANALYTICS_STATE_LOCK_TIMEOUT_MS = 500;
31 +const PENDING_ALIAS_RETRY_MS = 5 * 60 * 1000;
32 const CONSUMER_SHORT_TERM_CACHE_FILE_NAME = 'consumer-short-term-cache.json';
33 const CLI_CODACT_FAILURES_PATH = '/api/v3/cli/codact_failures';
34
@@ -119,6 +121,14 @@ const getPostHogConfig = environmentProvider
121 }))
122 );
123
124 +const postHogEnabled = Effect.gen(function* () {
125 + if (yield* analyticsDisabled) {
126 + return false;
127 + }
128 + const { projectKey } = yield* getPostHogConfig;
129 + return projectKey.length > 0;
130 +});
131 +
132 const jsonFromString = Schema.parseJson();
133 const prettyJsonFromString = Schema.parseJson({ space: 2 });
134 const decodeJson = Schema.decodeUnknown(jsonFromString);
@@ -182,9 +192,10 @@ type AnalyticsState = {
192 readonly install_id?: string;
193 readonly apollo_user_id?: string;
194 readonly aliased_apollo_user_id?: string;
195 + readonly pending_alias_apollo_user_id?: string;
196 + readonly pending_alias_install_id?: string;
197 + readonly pending_alias_attempted_at?: string;
198 readonly api_key_fingerprint?: string;
186 - readonly stitch_attempted_at?: string;
187 - readonly stitch_attempted_api_key_fingerprint?: string;
199 readonly created_at?: string;
200 };
201
@@ -224,6 +235,9 @@ const acquireAnalyticsStateLock = Effect.gen(function* () {
235
236 yield* fs.makeDirectory(paths.analyticsDir, { recursive: true });
237
238 + // Lock contention is wall-clock coordination between OS processes. Keeping
239 + // the retry on the platform timer also prevents Effect's TestClock from
240 + // freezing concurrent lock tests.
241 const waitBeforeRetry = Effect.promise(
242 () =>
243 new Promise<void>(resolve => {
@@ -354,11 +368,11 @@ const getUserApiKey = Effect.gen(function* () {
368 : null;
369 });
370
357 -const fingerprintApiKey = (apiKey: string): string =>
358 - `${djb2Hash(apiKey).toString(36)}.${apiKey.length.toString(36)}`;
371 +const fingerprintApiKey = (apiKey: string) =>
372 + Effect.promise(() => sha256Hex(new TextEncoder().encode(apiKey)));
373
360 -const getApiKeyFingerprint = Effect.map(getUserApiKey, apiKey =>
361 - apiKey ? fingerprintApiKey(apiKey) : null
374 +const getApiKeyFingerprint = Effect.flatMap(getUserApiKey, apiKey =>
375 + apiKey ? fingerprintApiKey(apiKey) : Effect.succeed(null)
376 );
377
378 // The keychain* security modes strip the api key from user_data.json, so no
@@ -388,7 +402,11 @@ const getDistinctId = (installId: string) =>
402 }
403 }
404
391 - if (typeof state?.aliased_apollo_user_id !== 'string') {
405 + const installIdMayBeAliased =
406 + typeof state?.aliased_apollo_user_id === 'string' ||
407 + (state?.pending_alias_install_id === installId &&
408 + typeof state.pending_alias_apollo_user_id === 'string');
409 + if (!installIdMayBeAliased) {
410 return installId;
411 }
412 return fingerprint !== null ? `user_${fingerprint}` : `anon_${installId}`;
@@ -498,28 +516,6 @@ const getCliCodactFailuresEndpoint = Effect.map(readApiBaseUrl, baseUrl =>
516 baseUrl ? `${baseUrl}${CLI_CODACT_FAILURES_PATH}` : null
517 );
518
501 -const getWorkerSpawnArgs = (workerFlag: string, encodedPayload: string) =>
502 - Effect.gen(function* () {
503 - const fs = yield* FileSystem.FileSystem;
504 - const maybeScriptPath = process.argv[1];
505 - const scriptPathExists =
506 - typeof maybeScriptPath === 'string' && maybeScriptPath.length > 0
507 - ? yield* fs.exists(maybeScriptPath).pipe(Effect.catchAll(() => Effect.succeed(false)))
508 - : false;
509 - const scriptPathLooksReal =
510 - scriptPathExists && /\.(?:[cm]?[jt]s|mjs|mts|cts)$/u.test(maybeScriptPath ?? '');
511 -
512 - return scriptPathLooksReal
513 - ? {
514 - command: process.execPath,
515 - args: [maybeScriptPath as string, workerFlag, encodedPayload],
516 - }
517 - : {
518 - command: process.execPath,
519 - args: [workerFlag, encodedPayload],
520 - };
521 - });
522 -
519 // Effect's Command processes are scoped and die with their scope; telemetry
520 // workers intentionally outlive the CLI process, so they go through the
521 // sanctioned detached-spawn boundary in src/services/detached-process.
@@ -556,7 +552,7 @@ const captureToPostHog = (envelope: AnalyticsEnvelope) =>
552 endpoint: ingestUrl,
553 eventName: envelope.event,
554 });
559 - return;
555 + return false;
556 }
557
558 const httpClient = yield* HttpClient.HttpClient;
@@ -579,6 +575,7 @@ const captureToPostHog = (envelope: AnalyticsEnvelope) =>
575 responseBody: responseBody?.slice(0, 1000),
576 }
577 );
578 + return responseOk;
579 });
580
581 type CliCodactFailureBody = {
@@ -686,7 +683,7 @@ const enqueuePostHogEnvelope = (envelope: AnalyticsEnvelope) =>
683 yield* telemetryDebugLog('enqueue', { envelope });
684 const serializedEnvelope = yield* encodeJson(envelope);
685 const encodedPayload = Encoding.encodeBase64Url(serializedEnvelope);
689 - const { command, args } = yield* getWorkerSpawnArgs(
686 + const { command, args } = yield* getDetachedWorkerSpawnArgs(
687 INTERNAL_ANALYTICS_WORKER_FLAG,
688 encodedPayload
689 );
@@ -699,9 +696,11 @@ export const trackCliEventEffect = (event: TrackEvent) =>
696 return;
697 }
698
702 - const disabled = yield* analyticsDisabled;
703 - if (disabled) {
704 - yield* telemetryDebugLog('skip', { reason: 'disabled', eventName: event.name });
699 + if (!(yield* postHogEnabled)) {
700 + yield* telemetryDebugLog('skip', {
701 + reason: (yield* analyticsDisabled) ? 'disabled' : 'missing_project_key',
702 + eventName: event.name,
703 + });
704 return;
705 }
706
@@ -732,9 +731,8 @@ export const trackCliEventEffect = (event: TrackEvent) =>
731
732 export const emitPostHogAlias = (installId: string, apolloUserId: string) =>
733 Effect.gen(function* () {
735 - const disabled = yield* analyticsDisabled;
736 - if (disabled) {
737 - yield* telemetryDebugLog('alias_skip', { reason: 'disabled', installId });
734 + if (!(yield* postHogEnabled)) {
735 + yield* telemetryDebugLog('alias_skip', { reason: 'disabled_or_missing_key', installId });
736 return false;
737 }
738
@@ -761,20 +759,22 @@ export const linkApolloIdentityForAnalytics = (apolloUserId: string, apiKey?: st
759 return;
760 }
761
764 - const disabled = yield* analyticsDisabled;
765 - if (disabled) {
766 - yield* telemetryDebugLog('alias_skip', { reason: 'disabled' });
762 + if (!(yield* postHogEnabled)) {
763 + yield* telemetryDebugLog('alias_skip', { reason: 'disabled_or_missing_key' });
764 return;
765 }
766
770 - yield* withAnalyticsStateLock(
767 + const aliasToEmit = yield* withAnalyticsStateLock(
768 Effect.gen(function* () {
769 let state = yield* readAnalyticsState;
770 let installId = yield* getOrCreateInstallIdUnlocked;
771
772 // A second user on this machine must not merge into the previous user's
773 // PostHog person: rotate to a fresh install_id before linking.
777 - const previousIdentity = state?.apollo_user_id ?? state?.aliased_apollo_user_id;
774 + const previousIdentity =
775 + state?.apollo_user_id ??
776 + state?.pending_alias_apollo_user_id ??
777 + state?.aliased_apollo_user_id;
778 const identityChanged =
779 typeof previousIdentity === 'string' &&
780 previousIdentity.length > 0 &&
@@ -785,6 +785,9 @@ export const linkApolloIdentityForAnalytics = (apolloUserId: string, apiKey?: st
785 install_id: installId,
786 apollo_user_id: undefined,
787 aliased_apollo_user_id: undefined,
788 + pending_alias_apollo_user_id: undefined,
789 + pending_alias_install_id: undefined,
790 + pending_alias_attempted_at: undefined,
791 api_key_fingerprint: undefined,
792 });
793 state = yield* readAnalyticsState;
@@ -792,7 +795,7 @@ export const linkApolloIdentityForAnalytics = (apolloUserId: string, apiKey?: st
795
796 const fingerprint =
797 typeof apiKey === 'string' && apiKey.length > 0
795 - ? fingerprintApiKey(apiKey)
798 + ? yield* fingerprintApiKey(apiKey)
799 : yield* getApiKeyFingerprint;
800 if (state?.apollo_user_id !== resolved || state?.api_key_fingerprint !== fingerprint) {
801 yield* mergeAnalyticsStateUnlocked(installId, {
@@ -801,77 +804,51 @@ export const linkApolloIdentityForAnalytics = (apolloUserId: string, apiKey?: st
804 });
805 }
806
804 - if (typeof state?.aliased_apollo_user_id === 'string') {
805 - return;
807 + state = yield* readAnalyticsState;
808 + if (state?.aliased_apollo_user_id === resolved) {
809 + return undefined;
810 }
807 - if (yield* emitPostHogAlias(installId, resolved)) {
808 - yield* mergeAnalyticsStateUnlocked(installId, { aliased_apollo_user_id: resolved });
809 - }
810 - })
811 - );
812 - }).pipe(Effect.catchAllCause(() => Effect.void));
813 -
814 -const STITCH_ATTEMPT_INTERVAL_MS = 24 * 60 * 60 * 1000;
815 -const STITCH_SESSION_INFO_TIMEOUT = '1500 millis';
816 -
817 -type AnalyticsSessionInfoFetcher = (params: {
818 - baseURL: string;
819 - userApiKey: string;
820 -}) => Effect.Effect<{ readonly org_member: { readonly id: string } }, unknown>;
821 -
822 -// Repairs a missing/stale persisted identity for already-logged-in installs
823 -// (e.g. keyring-stored keys that predate identity stitching). The session-info
824 -// fetcher is injected because composio-clients already imports this module.
825 -export const ensureAnalyticsIdentity = (params: {
826 - apiKey: string;
827 - baseURL: string;
828 - fetchSessionInfo: AnalyticsSessionInfoFetcher;
829 -}) =>
830 - Effect.gen(function* () {
831 - if ((yield* analyticsDisabled) || params.apiKey.trim().length === 0) {
832 - return;
833 - }
834 -
835 - const fingerprint = fingerprintApiKey(params.apiKey);
836 - const shouldAttempt = yield* withAnalyticsStateLock(
837 - Effect.gen(function* () {
838 - const state = yield* readAnalyticsState;
839 - const identityLinked =
840 - typeof state?.apollo_user_id === 'string' &&
841 - state.apollo_user_id.length > 0 &&
842 - state.api_key_fingerprint === fingerprint;
843 - if (identityLinked) {
844 - return false;
845 - }
846 -
847 - const lastAttemptMs = Date.parse(state?.stitch_attempted_at ?? '');
848 - const nowMs = yield* Clock.currentTimeMillis;
849 - const sameCredentialAttempt = state?.stitch_attempted_api_key_fingerprint === fingerprint;
811 if (
851 - sameCredentialAttempt &&
852 - Number.isFinite(lastAttemptMs) &&
853 - nowMs - lastAttemptMs < STITCH_ATTEMPT_INTERVAL_MS
812 + state?.pending_alias_apollo_user_id === resolved &&
813 + state.pending_alias_install_id === installId
814 ) {
855 - return false;
815 + const attemptedAt = Date.parse(state.pending_alias_attempted_at ?? '');
816 + const now = yield* Clock.currentTimeMillis;
817 + if (Number.isFinite(attemptedAt) && now - attemptedAt < PENDING_ALIAS_RETRY_MS) {
818 + return undefined;
819 + }
820 }
821
858 - // Persisted before the network attempt so failures cannot retry-storm.
859 - const installId = yield* getOrCreateInstallIdUnlocked;
822 yield* mergeAnalyticsStateUnlocked(installId, {
861 - stitch_attempted_at: DateTime.formatIso(yield* DateTime.now),
862 - stitch_attempted_api_key_fingerprint: fingerprint,
823 + pending_alias_apollo_user_id: resolved,
824 + pending_alias_install_id: installId,
825 + pending_alias_attempted_at: DateTime.formatIso(yield* DateTime.now),
826 });
864 - return true;
827 + return { installId, apolloUserId: resolved };
828 })
829 );
867 - if (!shouldAttempt) {
830 + if (!aliasToEmit) {
831 return;
832 }
833
871 - const info = yield* params
872 - .fetchSessionInfo({ baseURL: params.baseURL, userApiKey: params.apiKey })
873 - .pipe(Effect.timeout(STITCH_SESSION_INFO_TIMEOUT));
874 - yield* linkApolloIdentityForAnalytics(info.org_member.id, params.apiKey);
834 + if (!(yield* emitPostHogAlias(aliasToEmit.installId, aliasToEmit.apolloUserId))) {
835 + yield* withAnalyticsStateLock(
836 + Effect.gen(function* () {
837 + const state = yield* readAnalyticsState;
838 + if (
839 + state?.pending_alias_install_id !== aliasToEmit.installId ||
840 + state.pending_alias_apollo_user_id !== aliasToEmit.apolloUserId
841 + ) {
842 + return;
843 + }
844 + yield* mergeAnalyticsStateUnlocked(aliasToEmit.installId, {
845 + pending_alias_apollo_user_id: undefined,
846 + pending_alias_install_id: undefined,
847 + pending_alias_attempted_at: undefined,
848 + });
849 + })
850 + );
851 + }
852 }).pipe(Effect.catchAllCause(() => Effect.void));
853
854 export const clearApolloIdentityForAnalytics = withAnalyticsStateLock(
@@ -905,7 +882,7 @@ export const trackCliCodactFailureEffect = (failure: CliCodactFailure) =>
882 const invocation = yield* getCliInvocationContext;
883 const body = yield* encodeJson(createCliCodactFailureBody(failure, cliSessionId, invocation));
884 const encodedPayload = Encoding.encodeBase64Url(body);
908 - const { command, args } = yield* getWorkerSpawnArgs(
885 + const { command, args } = yield* getDetachedWorkerSpawnArgs(
886 INTERNAL_CODACT_FAILURE_WORKER_FLAG,
887 encodedPayload
888 );
@@ -925,6 +902,32 @@ const decodeWorkerPayload = <A>(encodedPayload: string) =>
902 return (yield* decodeJson(serialized)) as A;
903 });
904
905 +const settlePostHogAlias = (envelope: AnalyticsEnvelope, delivered: boolean) => {
906 + if (envelope.event !== POSTHOG_ALIAS_EVENT) {
907 + return Effect.void;
908 + }
909 +
910 + return withAnalyticsStateLock(
911 + Effect.gen(function* () {
912 + const state = yield* readAnalyticsState;
913 + if (
914 + state?.install_id !== envelope.installId ||
915 + state.pending_alias_install_id !== envelope.installId ||
916 + state.pending_alias_apollo_user_id !== envelope.distinctId
917 + ) {
918 + return;
919 + }
920 +
921 + yield* mergeAnalyticsStateUnlocked(envelope.installId, {
922 + ...(delivered ? { aliased_apollo_user_id: envelope.distinctId } : {}),
923 + pending_alias_apollo_user_id: undefined,
924 + pending_alias_install_id: undefined,
925 + pending_alias_attempted_at: undefined,
926 + });
927 + })
928 + ).pipe(Effect.catchAllCause(() => Effect.void));
929 +};
930 +
931 const runAnalyticsWorker = (argv: ReadonlyArray<string>) => {
932 const flagIndex = getWorkerFlagIndex(argv, INTERNAL_ANALYTICS_WORKER_FLAG);
933 if (flagIndex < 0) {
@@ -941,15 +944,16 @@ const runAnalyticsWorker = (argv: ReadonlyArray<string>) => {
944 if (typeof envelope?.event !== 'string' || envelope.event.length === 0) {
945 return true;
946 }
944 - yield* captureToPostHog(envelope);
945 - return true;
946 - }).pipe(
947 - Effect.catchAllCause(cause =>
948 - telemetryDebugLog('delivery_error', { error: telemetryErrorDetails(cause) }).pipe(
949 - Effect.as(true)
947 + const delivered = yield* captureToPostHog(envelope).pipe(
948 + Effect.catchAllCause(cause =>
949 + telemetryDebugLog('delivery_error', { error: telemetryErrorDetails(cause) }).pipe(
950 + Effect.as(false)
951 + )
952 )
951 - )
952 - );
953 + );
954 + yield* settlePostHogAlias(envelope, delivered);
955 + return true;
956 + }).pipe(Effect.catchAllCause(() => Effect.succeed(true)));
957 };
958
959 const runCodactFailureWorker = (argv: ReadonlyArray<string>) => {
ts/packages/cli/src/cli-main.ts
+3 -19
@@ -1,5 +1,5 @@
1 import process from 'node:process';
2 -import { Cause, Effect, Exit, Layer, Logger, Option } from 'effect';
2 +import { Cause, Effect, Exit, Layer, Logger } from 'effect';
3 import { captureErrors, prettyPrintFromCapturedErrors } from 'effect-errors/index';
4 import { CliConfig, HelpDoc, ValidationError } from '@effect/cli';
5 import { FetchHttpClient } from '@effect/platform';
@@ -15,17 +15,13 @@ import {
15 ComposioClientSingleton,
16 ComposioSessionRepository,
17 ComposioToolkitsRepository,
18 - getSessionInfoByUserApiKey,
18 } from 'src/services/composio-clients';
19 import { ComposioToolkitsRepositoryCached } from 'src/services/composio-clients-cached';
20 import { NodeOs } from 'src/services/node-os';
21 import { NodeProcess } from 'src/services/node-process';
22 import { JsPackageManagerDetector } from 'src/services/js-package-manager-detector';
23 import { ComposioCliUserConfigLive, ComposioCliUserConfig } from 'src/services/cli-user-config';
25 -import {
26 - ComposioUserContext,
27 - ComposioUserContextLive as _ComposioUserContextLive,
28 -} from 'src/services/user-context';
24 +import { ComposioUserContextLive as _ComposioUserContextLive } from 'src/services/user-context';
25 import { UpgradeBinary } from 'src/services/upgrade-binary';
26 import { TerminalUI, TerminalUILive } from 'src/services/terminal-ui';
27 import { TriggersRealtime } from 'src/services/triggers-realtime';
@@ -41,7 +37,7 @@ import {
37 getPrimaryLifecycleInvokedEvent,
38 getPrimaryLifecycleSucceededEvent,
39 } from 'src/analytics/events';
44 -import { ensureAnalyticsIdentity, trackCliEventEffect } from 'src/analytics/dispatch';
40 +import { trackCliEventEffect } from 'src/analytics/dispatch';
41 import { mapOnlyComposioOverrideError } from 'src/services/composio-error-overrides';
42 import { SetupSkillInstaller } from 'src/services/setup-skill-installer';
43 import { SetupCommandError } from 'src/services/setup';
@@ -149,18 +145,6 @@ const runWithTelemetry = Effect.gen(function* () {
145 const ui = yield* TerminalUI;
146 const terminal = yield* ui.capabilities;
147
152 - // Stitch the analytics identity for installs whose credential (env or
153 - // keyring) resolved without ever passing through a login-time link.
154 - const userContext = yield* ComposioUserContext;
155 - const resolvedApiKey = Option.getOrUndefined(userContext.data.apiKey);
156 - if (resolvedApiKey) {
157 - yield* ensureAnalyticsIdentity({
158 - apiKey: resolvedApiKey,
159 - baseURL: userContext.data.baseURL,
160 - fetchSessionInfo: getSessionInfoByUserApiKey,
161 - });
162 - }
163 -
148 const commandTelemetryContext = createCliCommandTelemetryContext(
149 process.argv,
150 constants.APP_VERSION,
ts/packages/cli/src/services/detached-process.ts
+28
@@ -1,5 +1,7 @@
1 // eslint-disable-next-line no-restricted-imports -- This Effect helper is the sole detached-spawn boundary for CLI source: @effect/platform Command processes are scope-bound and are killed when their scope closes, while these children must outlive the CLI process.
2 import { spawn } from 'node:child_process';
3 +import process from 'node:process';
4 +import { FileSystem } from '@effect/platform';
5 import { Data, Effect } from 'effect';
6
7 export class DetachedProcessSpawnError extends Data.TaggedError(
@@ -62,3 +64,29 @@ export const spawnDetached = (
64 })
65 )
66 );
67 +
68 +/**
69 + * Resolve the executable/argument shape for a detached worker in both compiled
70 + * binaries and source-driven development.
71 + */
72 +export const getDetachedWorkerSpawnArgs = (workerFlag: string, encodedPayload: string) =>
73 + Effect.gen(function* () {
74 + const fs = yield* FileSystem.FileSystem;
75 + const maybeScriptPath = process.argv[1];
76 + const scriptPathExists =
77 + typeof maybeScriptPath === 'string' && maybeScriptPath.length > 0
78 + ? yield* fs.exists(maybeScriptPath).pipe(Effect.catchAll(() => Effect.succeed(false)))
79 + : false;
80 + const scriptPathLooksReal =
81 + scriptPathExists && /\.(?:[cm]?[jt]s|mjs|mts|cts)$/u.test(maybeScriptPath ?? '');
82 +
83 + return scriptPathLooksReal
84 + ? {
85 + command: process.execPath,
86 + args: [maybeScriptPath as string, workerFlag, encodedPayload],
87 + }
88 + : {
89 + command: process.execPath,
90 + args: [workerFlag, encodedPayload],
91 + };
92 + });
ts/packages/cli/test/src/analytics.dispatch.test.ts
+107 -123
@@ -9,7 +9,6 @@ import * as tempy from 'tempy';
9 import {
10 clearApolloIdentityForAnalytics,
11 emitPostHogAlias,
12 - ensureAnalyticsIdentity,
12 getCurrentCwdSessionId,
13 linkApolloIdentityForAnalytics,
14 readApiBaseUrl,
@@ -264,6 +263,7 @@ describe('CLI analytics dispatch', () => {
263 yield* trackCliEventEffect({ name: 'producer_event', properties: { sample: 'value' } });
264
265 expect(childProcessMocks.spawn).not.toHaveBeenCalled();
266 + expect(yield* fs.exists(path.join(home, '.composio', 'analytics.json'))).toBe(false);
267 }).pipe(Effect.provide(makePlatformLayer(home)));
268 });
269
@@ -484,6 +484,35 @@ describe('CLI analytics dispatch', () => {
484 );
485 });
486
487 + it.effect('bounds the delay when another process leaves a live state lock behind', () => {
488 + const home = tempy.temporaryDirectory();
489 + const scriptPath = path.join(home, 'composio.ts');
490 + const composioDir = path.join(home, '.composio');
491 + const lockPath = path.join(composioDir, 'analytics.json.lock');
492 + enableTelemetry('');
493 + process.argv[1] = scriptPath;
494 + mkdirSync(composioDir, { recursive: true });
495 + writeFileSync(scriptPath, '');
496 + writeFileSync(lockPath, 'other-process');
497 +
498 + return Effect.gen(function* () {
499 + const completedBeforeDeadline = yield* Effect.race(
500 + trackCliEventEffect({ name: CLI_ANALYTICS_EVENTS.CLI_SETUP_SUCCEEDED }).pipe(
501 + Effect.as(true)
502 + ),
503 + Effect.promise(
504 + () =>
505 + new Promise<boolean>(resolve => {
506 + setTimeout(() => resolve(false), 1_500);
507 + })
508 + )
509 + );
510 +
511 + expect(completedBeforeDeadline).toBe(true);
512 + expect(childProcessMocks.spawn).toHaveBeenCalledTimes(1);
513 + }).pipe(Effect.provide(makePlatformLayer(home)));
514 + });
515 +
516 it.effect('keys post-login events on the persisted apollo_user_id', () => {
517 const home = tempy.temporaryDirectory();
518 const scriptPath = `${home}/composio.ts`;
@@ -544,19 +573,81 @@ describe('CLI analytics dispatch', () => {
573 alias: 'install_login',
574 });
575
547 - // The Apollo id is persisted while keeping the original install_id/created_at.
576 + // The Apollo id and pending alias are persisted while keeping the
577 + // original install_id/created_at.
578 const persisted = JSON.parse(
579 yield* fs.readFileString(path.join(composioDir, 'analytics.json'), 'utf8')
550 - ) as { install_id: string; apollo_user_id: string; created_at: string };
580 + ) as {
581 + install_id: string;
582 + apollo_user_id: string;
583 + pending_alias_apollo_user_id: string;
584 + created_at: string;
585 + };
586 expect(persisted).toMatchObject({
587 install_id: 'install_login',
588 apollo_user_id: 'om_apollo_login',
589 + pending_alias_apollo_user_id: 'om_apollo_login',
590 created_at: '2026-01-01T00:00:00.000Z',
591 });
592
557 - // A repeat login with the same Apollo id does not re-emit the alias.
593 + // A repeat login while delivery is pending does not re-emit the alias.
594 yield* linkApolloIdentityForAnalytics('om_apollo_login');
595 expect(childProcessMocks.spawn).toHaveBeenCalledTimes(1);
596 +
597 + vi.stubEnv('COMPOSIO_POSTHOG_INGEST_URL', 'https://posthog.example.test/i/v0/e/');
598 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 200 }));
599 + yield* runBackgroundWorkerFromArgv([
600 + process.execPath,
601 + 'composio',
602 + '__analytics-worker',
603 + args[2]!,
604 + ]).pipe(Effect.provide(makePlatformLayer(home)));
605 +
606 + const acknowledged = JSON.parse(
607 + yield* fs.readFileString(path.join(composioDir, 'analytics.json'), 'utf8')
608 + ) as {
609 + aliased_apollo_user_id?: string;
610 + pending_alias_apollo_user_id?: string;
611 + };
612 + expect(acknowledged.aliased_apollo_user_id).toBe('om_apollo_login');
613 + expect(acknowledged.pending_alias_apollo_user_id).toBeUndefined();
614 + }).pipe(Effect.provide(makePlatformLayer(home)));
615 + });
616 +
617 + it.effect('retries an alias after the worker reports a failed delivery', () => {
618 + const home = tempy.temporaryDirectory();
619 + const scriptPath = `${home}/composio.ts`;
620 + enableTelemetry('');
621 + process.argv[1] = scriptPath;
622 +
623 + return Effect.gen(function* () {
624 + const fs = yield* FileSystem.FileSystem;
625 + yield* fs.writeFileString(scriptPath, '');
626 +
627 + yield* linkApolloIdentityForAnalytics('om_alias_retry');
628 + expect(childProcessMocks.spawn).toHaveBeenCalledTimes(1);
629 + const args = childProcessMocks.spawn.mock.calls[0]![1] as string[];
630 +
631 + vi.stubEnv('COMPOSIO_POSTHOG_INGEST_URL', 'https://posthog.example.test/i/v0/e/');
632 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 500 }));
633 + yield* runBackgroundWorkerFromArgv([
634 + process.execPath,
635 + 'composio',
636 + '__analytics-worker',
637 + args[2]!,
638 + ]).pipe(Effect.provide(makePlatformLayer(home)));
639 +
640 + const afterFailure = JSON.parse(
641 + yield* fs.readFileString(path.join(home, '.composio', 'analytics.json'), 'utf8')
642 + ) as {
643 + aliased_apollo_user_id?: string;
644 + pending_alias_apollo_user_id?: string;
645 + };
646 + expect(afterFailure.aliased_apollo_user_id).toBeUndefined();
647 + expect(afterFailure.pending_alias_apollo_user_id).toBeUndefined();
648 +
649 + yield* linkApolloIdentityForAnalytics('om_alias_retry');
650 + expect(childProcessMocks.spawn).toHaveBeenCalledTimes(2);
651 }).pipe(Effect.provide(makePlatformLayer(home)));
652 });
653
@@ -583,11 +674,11 @@ describe('CLI analytics dispatch', () => {
674 yield* fs.readFileString(path.join(home, '.composio', 'analytics.json'), 'utf8')
675 ) as {
676 apollo_user_id: string;
586 - aliased_apollo_user_id: string;
677 + pending_alias_apollo_user_id: string;
678 api_key_fingerprint: string;
679 };
680 expect(persisted.apollo_user_id).toBe('om_concurrent');
590 - expect(persisted.aliased_apollo_user_id).toBe('om_concurrent');
681 + expect(persisted.pending_alias_apollo_user_id).toBe('om_concurrent');
682 expect(persisted.api_key_fingerprint.length).toBeGreaterThan(0);
683 }).pipe(Effect.provide(makePlatformLayer(home)));
684 });
@@ -604,14 +695,10 @@ describe('CLI analytics dispatch', () => {
695 const path = yield* Path.Path;
696 yield* fs.writeFileString(scriptPath, '');
697
607 - // No key -> nothing enqueued, so the alias must not be marked as sent.
698 + // No key -> no analytics state or worker is created.
699 yield* linkApolloIdentityForAnalytics('om_apollo_retry');
700 expect(childProcessMocks.spawn).not.toHaveBeenCalled();
610 - const afterSkip = JSON.parse(
611 - yield* fs.readFileString(path.join(home, '.composio', 'analytics.json'), 'utf8')
612 - ) as { apollo_user_id?: string; aliased_apollo_user_id?: string };
613 - expect(afterSkip.apollo_user_id).toBe('om_apollo_retry');
614 - expect(afterSkip.aliased_apollo_user_id).toBeUndefined();
701 + expect(yield* fs.exists(path.join(home, '.composio', 'analytics.json'))).toBe(false);
702
703 // Once a key is configured the alias is attempted again.
704 vi.stubEnv('COMPOSIO_POSTHOG_PROJECT_API_KEY', 'phc_test_key');
@@ -619,8 +706,8 @@ describe('CLI analytics dispatch', () => {
706 expect(childProcessMocks.spawn).toHaveBeenCalledTimes(1);
707 const afterRetry = JSON.parse(
708 yield* fs.readFileString(path.join(home, '.composio', 'analytics.json'), 'utf8')
622 - ) as { aliased_apollo_user_id?: string };
623 - expect(afterRetry.aliased_apollo_user_id).toBe('om_apollo_retry');
709 + ) as { pending_alias_apollo_user_id?: string };
710 + expect(afterRetry.pending_alias_apollo_user_id).toBe('om_apollo_retry');
711 }).pipe(Effect.provide(makePlatformLayer(home)));
712 });
713
@@ -930,10 +1017,14 @@ describe('CLI analytics dispatch', () => {
1017
1018 const persisted = JSON.parse(
1019 yield* fs.readFileString(path.join(home, '.composio', 'analytics.json'), 'utf8')
933 - ) as { install_id: string; apollo_user_id: string; aliased_apollo_user_id: string };
1020 + ) as {
1021 + install_id: string;
1022 + apollo_user_id: string;
1023 + pending_alias_apollo_user_id: string;
1024 + };
1025 expect(persisted.install_id).toBe(secondPayload.installId);
1026 expect(persisted.apollo_user_id).toBe('om_second_user');
936 - expect(persisted.aliased_apollo_user_id).toBe('om_second_user');
1027 + expect(persisted.pending_alias_apollo_user_id).toBe('om_second_user');
1028 }).pipe(Effect.provide(makePlatformLayer(home)));
1029 });
1030
@@ -1048,112 +1139,5 @@ describe('CLI analytics dispatch', () => {
1139 expect(payload.properties.duration_ms).toBe(42);
1140 }).pipe(Effect.provide(makePlatformLayer(home)));
1141 });
1051 -
1052 - it.effect('bootstrap stitch links a missing identity through session info', () => {
1053 - const home = tempy.temporaryDirectory();
1054 - const scriptPath = `${home}/composio.ts`;
1055 - enableTelemetry('uak_stitch');
1056 - process.argv[1] = scriptPath;
1057 - const fetchSessionInfo = vi.fn(() => Effect.succeed({ org_member: { id: 'om_stitched' } }));
1058 -
1059 - return Effect.gen(function* () {
1060 - const fs = yield* FileSystem.FileSystem;
1061 - yield* fs.writeFileString(scriptPath, '');
1062 -
1063 - yield* ensureAnalyticsIdentity({
1064 - apiKey: 'uak_stitch',
1065 - baseURL: 'https://backend.example.test',
1066 - fetchSessionInfo,
1067 - });
1068 -
1069 - expect(fetchSessionInfo).toHaveBeenCalledTimes(1);
1070 - expect(childProcessMocks.spawn).toHaveBeenCalledTimes(1);
1071 - const args = childProcessMocks.spawn.mock.calls[0]![1] as string[];
1072 - const payload = decodeWorkerPayload<{ event: string; distinctId: string }>(args[2]!);
1073 - expect(payload.event).toBe('$create_alias');
1074 - expect(payload.distinctId).toBe('om_stitched');
1075 -
1076 - // Once linked under this credential, later runs make no network attempt.
1077 - yield* ensureAnalyticsIdentity({
1078 - apiKey: 'uak_stitch',
1079 - baseURL: 'https://backend.example.test',
1080 - fetchSessionInfo,
1081 - });
1082 - expect(fetchSessionInfo).toHaveBeenCalledTimes(1);
1083 - }).pipe(Effect.provide(makePlatformLayer(home)));
1084 - });
1085 -
1086 - it.effect('bootstrap stitch attempts at most once per day after a failure', () => {
1087 - const home = tempy.temporaryDirectory();
1088 - const scriptPath = `${home}/composio.ts`;
1089 - enableTelemetry('uak_stitch');
1090 - process.argv[1] = scriptPath;
1091 - const fetchSessionInfo = vi.fn(() => Effect.fail(new Error('offline')));
1092 -
1093 - return Effect.gen(function* () {
1094 - const fs = yield* FileSystem.FileSystem;
1095 - const path = yield* Path.Path;
1096 - yield* fs.writeFileString(scriptPath, '');
1097 -
1098 - yield* ensureAnalyticsIdentity({
1099 - apiKey: 'uak_stitch',
1100 - baseURL: 'https://backend.example.test',
1101 - fetchSessionInfo,
1102 - });
1103 - expect(fetchSessionInfo).toHaveBeenCalledTimes(1);
1104 -
1105 - const persisted = JSON.parse(
1106 - yield* fs.readFileString(path.join(home, '.composio', 'analytics.json'), 'utf8')
1107 - ) as {
1108 - stitch_attempted_at?: string;
1109 - stitch_attempted_api_key_fingerprint?: string;
1110 - };
1111 - expect(typeof persisted.stitch_attempted_at).toBe('string');
1112 - expect(typeof persisted.stitch_attempted_api_key_fingerprint).toBe('string');
1113 -
1114 - // Identity is still unlinked, but the attempt is throttled for 24h.
1115 - yield* ensureAnalyticsIdentity({
1116 - apiKey: 'uak_stitch',
1117 - baseURL: 'https://backend.example.test',
1118 - fetchSessionInfo,
1119 - });
1120 - expect(fetchSessionInfo).toHaveBeenCalledTimes(1);
1121 - }).pipe(Effect.provide(makePlatformLayer(home)));
1122 - });
1123 -
1124 - it.effect('bootstrap stitch retries immediately when the credential changes', () => {
1125 - const home = tempy.temporaryDirectory();
1126 - const scriptPath = `${home}/composio.ts`;
1127 - enableTelemetry('uak_first');
1128 - process.argv[1] = scriptPath;
1129 - const failedFetch = vi.fn(() => Effect.fail(new Error('offline')));
1130 - const changedCredentialFetch = vi.fn(() =>
1131 - Effect.succeed({ org_member: { id: 'om_changed' } })
1132 - );
1133 -
1134 - return Effect.gen(function* () {
1135 - const fs = yield* FileSystem.FileSystem;
1136 - yield* fs.writeFileString(scriptPath, '');
1137 -
1138 - yield* ensureAnalyticsIdentity({
1139 - apiKey: 'uak_first',
1140 - baseURL: 'https://backend.example.test',
1141 - fetchSessionInfo: failedFetch,
1142 - });
1143 - yield* ensureAnalyticsIdentity({
1144 - apiKey: 'uak_second',
1145 - baseURL: 'https://backend.example.test',
1146 - fetchSessionInfo: changedCredentialFetch,
1147 - });
1148 -
1149 - expect(failedFetch).toHaveBeenCalledTimes(1);
1150 - expect(changedCredentialFetch).toHaveBeenCalledTimes(1);
1151 - expect(childProcessMocks.spawn).toHaveBeenCalledTimes(1);
1152 - const args = childProcessMocks.spawn.mock.calls[0]![1] as string[];
1153 - const payload = decodeWorkerPayload<{ event: string; distinctId: string }>(args[2]!);
1154 - expect(payload.event).toBe('$create_alias');
1155 - expect(payload.distinctId).toBe('om_changed');
1156 - }).pipe(Effect.provide(makePlatformLayer(home)));
1157 - });
1142 });
1143 });