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 23, 01:45 UTC
Add telemetry tests
haxzie committed
May 21, 2025 at 18:52 UTC
37591a0b9c81475bdc72f7d4fc75a363e8bda860
20 files changed
+813
-26
examples/telemetry/.env.example
new
+2
@@ -0,0 +1,2 @@
1
+COMPOSIO_API_KEY=
2
+OPENAI_API_KEY=
\ No newline at end of file
examples/telemetry/README.md
new
+75
@@ -0,0 +1,75 @@
1
+# Vercel Example with Composio SDK
2
+
3
+This example demonstrates how to use the Composio SDK with Vercel's AI SDK to create an AI-powered application that can interact with HackerNews data.
4
+
5
+## Features
6
+
7
+- Integration with Composio SDK and Vercel AI SDK
8
+- HackerNews front page summarization using GPT-4
9
+- Streaming AI responses
10
+- TypeScript support
11
+
12
+## Prerequisites
13
+
14
+- [Node.js](https://nodejs.org/) (Latest LTS version recommended)
15
+- [pnpm](https://pnpm.io/) (v10.8.0 or later)
16
+- Composio API Key
17
+- OpenAI API Key
18
+
19
+## Getting Started
20
+
21
+1. Clone the repository and navigate to the example directory:
22
+
23
+```bash
24
+cd examples/vercel
25
+```
26
+
27
+2. Install dependencies:
28
+
29
+```bash
30
+pnpm install
31
+```
32
+
33
+3. Copy the `.env.example` file to `.env` and fill in your API keys:
34
+
35
+```bash
36
+cp .env.example .env
37
+```
38
+
39
+4. Update the `.env` file with your credentials:
40
+
41
+```env
42
+COMPOSIO_API_KEY=your_composio_api_key
43
+OPENAI_API_KEY=your_openai_api_key
44
+```
45
+
46
+5. Start the development server:
47
+
48
+```bash
49
+pnpm start
50
+```
51
+
52
+## How It Works
53
+
54
+This example showcases how to:
55
+
56
+1. Initialize the Composio SDK with the Vercel provider
57
+2. Use the HackerNews tool to fetch front page data
58
+3. Generate AI responses using OpenAI's GPT-4
59
+4. Handle tool calls and results in a chat-like interface
60
+
61
+## Dependencies
62
+
63
+- `@composio/core`: Core Composio SDK
64
+- `@composio/vercel`: Vercel integration for Composio
65
+- `@ai-sdk/openai`: OpenAI integration
66
+- `ai`: Vercel's AI SDK
67
+- TypeScript for type safety
68
+
69
+## License
70
+
71
+ISC
72
+
73
+## Support
74
+
75
+For questions and support, please refer to the [Composio documentation](https://docs.composio.dev) or open an issue in the repository.
examples/telemetry/package.json
new
+25
@@ -0,0 +1,25 @@
1
+{
2
+ "name": "telemetry-example",
3
+ "private": true,
4
+ "version": "0.1.10-alpha.0",
5
+ "description": "",
6
+ "main": "src/index.ts",
7
+ "scripts": {
8
+ "start": "COMPOSIO_LOG_LEVEL=debug bun src/index.ts",
9
+ "test": "echo \"Error: no test specified\" && exit 1"
10
+ },
11
+ "keywords": [],
12
+ "author": "",
13
+ "license": "ISC",
14
+ "packageManager": "pnpm@10.8.0",
15
+ "dependencies": {
16
+ "@ai-sdk/openai": "^1.3.16",
17
+ "@composio/core": "workspace:*",
18
+ "@composio/vercel": "workspace:*",
19
+ "ai": "^4.3.8"
20
+ },
21
+ "devDependencies": {
22
+ "@types/bun": "^1.2.9",
23
+ "typescript": "^5.8.3"
24
+ }
25
+}
examples/telemetry/src/index.ts
new
+12
@@ -0,0 +1,12 @@
1
+import { Composio, ConsoleTelemetryTransport } from '@composio/core';
2
+
3
+/**
4
+ * Non agentic provider
5
+ */
6
+const composio = new Composio({
7
+ apiKey: process.env.COMPOSIO_API_KEY,
8
+});
9
+
10
+const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER');
11
+
12
+console.log(tools);
examples/telemetry/tsconfig.json
new
+15
@@ -0,0 +1,15 @@
1
+{
2
+ "compilerOptions": {
3
+ "target": "ESNext",
4
+ "module": "ESNext",
5
+ "declaration": true,
6
+ "declarationDir": "./dist",
7
+ "outDir": "./dist",
8
+ "rootDir": "./src",
9
+ "strict": true,
10
+ "esModuleInterop": true,
11
+ "moduleResolution": "node",
12
+ "skipLibCheck": true
13
+ },
14
+ "include": ["src"]
15
+}
packages/core/package.json
+1
@@ -37,6 +37,7 @@
37
},
38
"dependencies": {
39
"@composio/client": "^0.1.0-alpha.10",
40
+ "chalk": "^5.4.1",
41
"openai": "^4.94.0",
42
"pusher-js": "^8.4.0",
43
"semver": "^7.7.2",
packages/core/src/composio.ts
+7
-3
@@ -90,6 +90,7 @@ export class Composio<TProvider extends BaseComposioProvider<unknown, unknown> =
90
this.config = {
91
...config,
92
allowTracking: config.allowTracking ?? true,
93
+ allowTracing: config.allowTracing ?? true,
94
};
95
96
/**
@@ -108,17 +109,20 @@ export class Composio<TProvider extends BaseComposioProvider<unknown, unknown> =
109
/**
110
* Initialize the client telemetry.
111
*/
111
- if (this.config.allowTracking ?? true) {
112
+ if (this.config.allowTracking) {
113
telemetry.setup(
114
{
115
apiKey: apiKeyParsed ?? '',
116
baseUrl: baseURLParsed ?? '',
117
framework: this.provider?.name || 'unknown',
118
isAgentic: this.provider?._isAgentic || false,
118
- source: 'node', // @TODO: get the source
119
+ source: 'javascript',
120
version: version,
121
+ sdkType: 'Typescript-V3',
122
isBrowser: typeof window !== 'undefined',
121
- sessionId: getRandomUUID(), // @TODO: get the session id
123
+ // @TODO: Users might want to pass their own session id
124
+ // @TODO: We shouldn't be doing this as people might always have one session id throughout the process in server
125
+ sessionId: this.config.allowTracing ? getRandomUUID() : undefined, // @TODO: get the session id
126
},
127
config.telemetryTransport
128
);
packages/core/src/index.ts
+1
-1
@@ -4,7 +4,7 @@ export { ComposioProvider } from './provider/ComposioProvider';
4
export { BaseAgenticProvider, BaseNonAgenticProvider } from './provider/BaseProvider';
5
export type { BaseComposioProvider } from './provider/BaseProvider';
6
export { OpenAIProvider } from './provider/OpenAIProvider';
7
-export { BaseTelemetryTransport } from './telemetry/TelemetryTransport';
7
+export { BaseTelemetryTransport, ConsoleTelemetryTransport } from './telemetry/TelemetryTransport';
8
export { jsonSchemaToModel } from './utils/jsonSchema';
9
export { ToolListParamsSchema } from './types/tool.types';
10
export type { Tool, ToolListParams, ToolExecuteParams } from './types/tool.types';
packages/core/src/telemetry/Telemetry.ts
+13
-7
@@ -1,4 +1,9 @@
1
-import { TELEMETRY_EVENTS, TelemetryMetadata, TelemetryPayload } from '../types/telemetry.types';
1
+import {
2
+ TELEMETRY_EVENTS,
3
+ TELEMETRY_TYPES,
4
+ TelemetryMetadata,
5
+ TelemetryPayload,
6
+} from '../types/telemetry.types';
7
import { TELEMETRY_URL } from '../utils/constants';
8
import { getEnvVariable } from '../utils/env';
9
import { BatchProcessor } from './BatchProcessor';
@@ -25,6 +30,7 @@ import { ProcessTelemetryTransport } from './transports/ProcessTransport';
30
export class TelemetryService {
31
private telemetryMetadata!: TelemetryMetadata;
32
private transport!: BaseTelemetryTransport;
33
+ private isTelemetryDisabled: boolean = true;
34
35
private batchProcessor = new BatchProcessor(100, 10, async data => {
36
await this.sendTelemetry(data as TelemetryPayload[]);
@@ -32,14 +38,17 @@ export class TelemetryService {
38
39
setup(metadata: TelemetryMetadata, transport?: BaseTelemetryTransport) {
40
this.telemetryMetadata = metadata;
41
+ this.isTelemetryDisabled = false;
42
43
const isBrowser = typeof window !== 'undefined';
44
if (transport) {
45
this.transport = transport;
46
} else if (isBrowser) {
47
this.transport = new BrowserTelemetryTransport();
48
+ this.telemetryMetadata.transport = 'browser';
49
} else {
50
this.transport = new ProcessTelemetryTransport();
51
+ this.telemetryMetadata.transport = 'process';
52
}
53
54
// send telemetry event for SDK initialization
@@ -121,13 +130,10 @@ export class TelemetryService {
130
* @returns
131
*/
132
async sendTelemetry(payload: TelemetryPayload[]) {
124
- if (!this.transport) {
125
- return;
126
- }
127
-
128
- const isTelemetryDisabled = getEnvVariable('TELEMETRY_DISABLED', 'false') === 'true';
133
+ const isTelemetryDisabled =
134
+ this.isTelemetryDisabled || getEnvVariable('TELEMETRY_DISABLED', 'false') === 'true';
135
130
- if (isTelemetryDisabled) {
136
+ if (!this.transport || isTelemetryDisabled) {
137
return;
138
}
139
packages/core/src/telemetry/TelemetryTransport.ts
+2
-1
@@ -1,3 +1,4 @@
1
+import chalk from 'chalk';
2
import { TelemetryTransportParams } from '../types/telemetry.types';
3
import logger from '../utils/logger';
4
@@ -15,7 +16,7 @@ export abstract class BaseTelemetryTransport {
16
*/
17
export class ConsoleTelemetryTransport implements BaseTelemetryTransport {
18
send(payload: TelemetryTransportParams): Promise<void> {
18
- logger.info('payload', payload);
19
+ logger.debug(chalk.yellow('telemetry'), JSON.stringify(payload, null, 2));
20
return Promise.resolve();
21
}
22
}
packages/core/src/telemetry/transports/BrowserTransport.ts
-4
@@ -1,11 +1,7 @@
1
import { TelemetryTransportParams } from '../../types/telemetry.types';
2
import logger from '../../utils/logger';
3
import { BaseTelemetryTransport } from '../TelemetryTransport';
4
-import { telemetry } from '../Telemetry';
4
export class BrowserTelemetryTransport implements BaseTelemetryTransport {
6
- constructor() {
7
- telemetry.instrument(this);
8
- }
5
send(payload: TelemetryTransportParams): Promise<void> {
6
if (typeof window === 'undefined') {
7
return Promise.reject(
packages/core/src/telemetry/transports/ProcessTransport.ts
+2
-5
@@ -1,12 +1,8 @@
1
+import chalk from 'chalk';
2
import { TelemetryTransportParams } from '../../types/telemetry.types';
3
import logger from '../../utils/logger';
4
import { BaseTelemetryTransport } from '../TelemetryTransport';
4
-import { telemetry } from '../Telemetry';
5
export class ProcessTelemetryTransport implements BaseTelemetryTransport {
6
- constructor() {
7
- telemetry.instrument(this);
8
- }
9
-
6
send(payload: TelemetryTransportParams): Promise<void> {
7
if (typeof window !== 'undefined') {
8
return Promise.reject(
@@ -60,6 +56,7 @@ export class ProcessTelemetryTransport implements BaseTelemetryTransport {
56
.catch(() => {
57
resolve();
58
});
59
+ logger.debug(chalk.yellow('Process telemetry'), JSON.stringify(payload, null, 2));
60
} catch (error) {
61
logger.error('Error sending telemetry', error);
62
resolve();
packages/core/src/types/telemetry.types.ts
+10
-1
@@ -17,7 +17,9 @@ export type TelemetryMetadata = {
17
framework: string;
18
isAgentic: boolean;
19
source: string;
20
- sessionId: string;
20
+ transport?: string;
21
+ sdkType?: string;
22
+ sessionId?: string;
23
isBrowser?: boolean;
24
};
25
@@ -36,6 +38,13 @@ type AcceptableJSONValue =
38
| null
39
| undefined;
40
41
+export const TELEMETRY_TYPES = {
42
+ SDK_USAGE: 'SDK_USAGE',
43
+ SDK_ERROR: 'SDK_ERROR',
44
+} as const;
45
+
46
+export type TelemetryType = (typeof TELEMETRY_TYPES)[keyof typeof TELEMETRY_TYPES];
47
+
48
export interface TelemetryTransportParams {
49
url: string;
50
method: string;
packages/core/src/utils/env.ts
-3
@@ -1,5 +1,3 @@
1
-import logger from './logger';
2
-
1
export const getEnvVariable = (
2
name: string,
3
defaultValue: string | undefined = undefined
@@ -7,7 +5,6 @@ export const getEnvVariable = (
5
try {
6
return process.env[name] || defaultValue;
7
} catch (_e) {
10
- logger.error(`Error getting environment variable ${name}:`, _e);
8
return defaultValue;
9
}
10
};
packages/core/src/utils/logger.ts
+2
-1
@@ -1,3 +1,4 @@
1
+import chalk from 'chalk';
2
import { getEnvVariable } from './env';
3
4
// Define log levels with corresponding priorities
@@ -47,7 +48,7 @@ class Logger {
48
}
49
50
const timestamp = new Date().toISOString();
50
- return `${timestamp} - ${formattedArgs}`;
51
+ return `${chalk.gray(timestamp)} - ${formattedArgs}`;
52
}
53
54
private shouldLog(level: LogLevel): boolean {
packages/core/test/telemetry/BatchProcessor.test.ts
new
+119
@@ -0,0 +1,119 @@
1
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
+import { BatchProcessor } from '../../src/telemetry/BatchProcessor';
3
+
4
+describe('BatchProcessor', () => {
5
+ // Mock timer functions
6
+ vi.useFakeTimers();
7
+
8
+ let batchProcessor: BatchProcessor;
9
+ let processBatchCallback: ReturnType<typeof vi.fn>;
10
+
11
+ beforeEach(() => {
12
+ processBatchCallback = vi.fn().mockResolvedValue(undefined);
13
+ batchProcessor = new BatchProcessor(1000, 3, processBatchCallback);
14
+ });
15
+
16
+ afterEach(() => {
17
+ vi.clearAllTimers();
18
+ vi.clearAllMocks();
19
+ });
20
+
21
+ it('should create an instance with default parameters', () => {
22
+ const defaultProcessor = new BatchProcessor(undefined, undefined, processBatchCallback);
23
+ expect(defaultProcessor).toBeInstanceOf(BatchProcessor);
24
+ });
25
+
26
+ it('should batch items and not process until batch size is reached', () => {
27
+ batchProcessor.pushItem('item1');
28
+ batchProcessor.pushItem('item2');
29
+
30
+ expect(processBatchCallback).not.toHaveBeenCalled();
31
+ });
32
+
33
+ it('should process batch when the batch size is reached', () => {
34
+ batchProcessor.pushItem('item1');
35
+ batchProcessor.pushItem('item2');
36
+ batchProcessor.pushItem('item3');
37
+
38
+ expect(processBatchCallback).toHaveBeenCalledWith(['item1', 'item2', 'item3']);
39
+ expect(processBatchCallback).toHaveBeenCalledTimes(1);
40
+ });
41
+
42
+ it('should process batch after the specified time', () => {
43
+ batchProcessor.pushItem('item1');
44
+ batchProcessor.pushItem('item2');
45
+
46
+ expect(processBatchCallback).not.toHaveBeenCalled();
47
+
48
+ // Fast-forward time by 1 second
49
+ vi.advanceTimersByTime(1000);
50
+
51
+ expect(processBatchCallback).toHaveBeenCalledWith(['item1', 'item2']);
52
+ expect(processBatchCallback).toHaveBeenCalledTimes(1);
53
+ });
54
+
55
+ it('should reset the timer after processing batch due to size limit', () => {
56
+ batchProcessor.pushItem('item1');
57
+ batchProcessor.pushItem('item2');
58
+ batchProcessor.pushItem('item3');
59
+
60
+ expect(processBatchCallback).toHaveBeenCalledTimes(1);
61
+ processBatchCallback.mockClear();
62
+
63
+ // Add a new item, which should start a new timer
64
+ batchProcessor.pushItem('item4');
65
+
66
+ // Fast-forward time by 1 second
67
+ vi.advanceTimersByTime(1000);
68
+
69
+ expect(processBatchCallback).toHaveBeenCalledWith(['item4']);
70
+ expect(processBatchCallback).toHaveBeenCalledTimes(1);
71
+ });
72
+
73
+ it('should not process an empty batch', () => {
74
+ // No items added
75
+ batchProcessor.processBatch();
76
+
77
+ expect(processBatchCallback).not.toHaveBeenCalled();
78
+ });
79
+
80
+ it('should clear timer after manual processBatch call', () => {
81
+ // Spy on setTimeout
82
+ const setTimeoutSpy = vi.spyOn(global, 'setTimeout');
83
+
84
+ batchProcessor.pushItem('item1');
85
+
86
+ // A timer should be set
87
+ expect(setTimeoutSpy).toHaveBeenCalled();
88
+
89
+ // Clear the spy call history
90
+ setTimeoutSpy.mockClear();
91
+
92
+ // Process the batch manually
93
+ batchProcessor.processBatch();
94
+
95
+ // Add a new item, which should start a new timer
96
+ batchProcessor.pushItem('item2');
97
+
98
+ // setTimeout should be called again
99
+ expect(setTimeoutSpy).toHaveBeenCalled();
100
+ });
101
+
102
+ it('should handle batches efficiently', () => {
103
+ // Create a batch processor with a moderate batch size
104
+ const processor = new BatchProcessor(1000, 20, processBatchCallback);
105
+
106
+ // Add 19 items
107
+ for (let i = 0; i < 19; i++) {
108
+ processor.pushItem(`item${i}`);
109
+ }
110
+
111
+ expect(processBatchCallback).not.toHaveBeenCalled();
112
+
113
+ // Add the 20th item to trigger batch processing
114
+ processor.pushItem('item-last');
115
+
116
+ expect(processBatchCallback).toHaveBeenCalledTimes(1);
117
+ expect(processBatchCallback.mock.calls[0][0].length).toBe(20);
118
+ });
119
+});
packages/core/test/telemetry/BrowserTransport.test.ts
new
+117
@@ -0,0 +1,117 @@
1
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
+import { BrowserTelemetryTransport } from '../../src/telemetry/transports/BrowserTransport';
3
+import { TelemetryTransportParams } from '../../src/types/telemetry.types';
4
+
5
+describe('BrowserTelemetryTransport', () => {
6
+ let transport: BrowserTelemetryTransport;
7
+
8
+ // Define the mock XHR class
9
+ const mockXHR = {
10
+ open: vi.fn(),
11
+ send: vi.fn(),
12
+ setRequestHeader: vi.fn(),
13
+ onload: null as Function | null,
14
+ };
15
+
16
+ // Save original globals
17
+ const originalWindow = global.window;
18
+ const originalXMLHttpRequest = global.XMLHttpRequest;
19
+
20
+ beforeEach(() => {
21
+ // Setup mock window and XMLHttpRequest
22
+ global.window = global.window || ({} as any);
23
+ global.XMLHttpRequest = vi.fn(() => mockXHR) as any;
24
+
25
+ // Reset mock functions and state
26
+ mockXHR.open.mockReset();
27
+ mockXHR.send.mockReset();
28
+ mockXHR.setRequestHeader.mockReset();
29
+ mockXHR.onload = null;
30
+
31
+ // Create new transport instance
32
+ transport = new BrowserTelemetryTransport();
33
+ });
34
+
35
+ afterEach(() => {
36
+ // Restore globals
37
+ global.window = originalWindow;
38
+ global.XMLHttpRequest = originalXMLHttpRequest;
39
+ });
40
+
41
+ it('should create an instance successfully', () => {
42
+ expect(transport).toBeInstanceOf(BrowserTelemetryTransport);
43
+ });
44
+
45
+ it('should send telemetry data via XMLHttpRequest', async () => {
46
+ const payload: TelemetryTransportParams = {
47
+ url: 'https://example.com/telemetry',
48
+ method: 'POST',
49
+ headers: {
50
+ 'Content-Type': 'application/json',
51
+ 'X-Custom-Header': 'test-value',
52
+ },
53
+ data: { key: 'value' },
54
+ };
55
+
56
+ // Start sending the data
57
+ const promise = transport.send(payload);
58
+
59
+ // Verify XHR was configured correctly
60
+ expect(mockXHR.open).toHaveBeenCalledWith('POST', 'https://example.com/telemetry', true);
61
+ expect(mockXHR.setRequestHeader).toHaveBeenCalledWith('Content-Type', 'application/json');
62
+ expect(mockXHR.setRequestHeader).toHaveBeenCalledWith('X-Custom-Header', 'test-value');
63
+ expect(mockXHR.send).toHaveBeenCalledWith(JSON.stringify({ key: 'value' }));
64
+
65
+ // Trigger the onload callback if it was set
66
+ if (mockXHR.onload) {
67
+ (mockXHR.onload as Function)();
68
+ }
69
+
70
+ // Verify promise resolves
71
+ await expect(promise).resolves.toBeUndefined();
72
+ });
73
+
74
+ it('should reject if not running in a browser environment', async () => {
75
+ // Temporarily remove window to simulate non-browser environment
76
+ const tempWindow = global.window;
77
+ global.window = undefined as any;
78
+
79
+ // Expect rejection when sending in non-browser env
80
+ await expect(
81
+ transport.send({
82
+ url: 'https://example.com/telemetry',
83
+ method: 'POST',
84
+ headers: {},
85
+ data: {},
86
+ })
87
+ ).rejects.toThrow('BrowserTelemetryTransport can only be used in browser environments');
88
+
89
+ // Restore window for other tests
90
+ global.window = tempWindow;
91
+ });
92
+
93
+ it('should handle errors gracefully', async () => {
94
+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
95
+
96
+ const payload: TelemetryTransportParams = {
97
+ url: 'https://example.com/telemetry',
98
+ method: 'POST',
99
+ headers: {},
100
+ data: {},
101
+ };
102
+
103
+ // Make the send method throw an error
104
+ mockXHR.send.mockImplementation(() => {
105
+ throw new Error('Network error');
106
+ });
107
+
108
+ // Should resolve despite the error
109
+ const promise = transport.send(payload);
110
+ await expect(promise).resolves.toBeUndefined();
111
+
112
+ // Should log the error
113
+ expect(consoleSpy).toHaveBeenCalled();
114
+
115
+ consoleSpy.mockRestore();
116
+ });
117
+});
packages/core/test/telemetry/ProcessTransport.test.ts
new
+91
@@ -0,0 +1,91 @@
1
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
+import { ProcessTelemetryTransport } from '../../src/telemetry/transports/ProcessTransport';
3
+import { TelemetryTransportParams } from '../../src/types/telemetry.types';
4
+
5
+describe('ProcessTelemetryTransport', () => {
6
+ let transport: ProcessTelemetryTransport;
7
+ const originalWindow = global.window;
8
+
9
+ // Spy on console.error to validate error handling
10
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
11
+
12
+ beforeEach(() => {
13
+ // Reset window to simulate Node.js environment
14
+ delete (global as any).window;
15
+
16
+ // Reset mocks and spies
17
+ vi.clearAllMocks();
18
+
19
+ // Create transport instance
20
+ transport = new ProcessTelemetryTransport();
21
+ });
22
+
23
+ afterEach(() => {
24
+ // Restore window
25
+ global.window = originalWindow;
26
+ });
27
+
28
+ it('should create an instance successfully', () => {
29
+ expect(transport).toBeInstanceOf(ProcessTelemetryTransport);
30
+ });
31
+
32
+ it('should reject if running in a browser environment', async () => {
33
+ // Set window to simulate browser environment
34
+ global.window = {} as any;
35
+
36
+ await expect(
37
+ transport.send({
38
+ url: 'https://example.com/telemetry',
39
+ method: 'POST',
40
+ headers: {},
41
+ data: {},
42
+ })
43
+ ).rejects.toThrow('ProcessTelemetryTransport can only be used in Node.js environments');
44
+ });
45
+
46
+ // Since we're running in a test environment and can't easily mock dynamic imports,
47
+ // we'll focus on testing the URL handling and error handling aspects
48
+
49
+ it('should handle errors gracefully', async () => {
50
+ // Force an error by making URL constructor throw
51
+ const originalURL = global.URL;
52
+ global.URL = vi.fn().mockImplementation(() => {
53
+ throw new Error('Invalid URL');
54
+ }) as any;
55
+
56
+ const payload: TelemetryTransportParams = {
57
+ url: 'invalid:///url',
58
+ method: 'POST',
59
+ headers: {},
60
+ data: {},
61
+ };
62
+
63
+ // Test that the promise still resolves despite the error
64
+ await expect(transport.send(payload)).resolves.toBeUndefined();
65
+
66
+ // Verify error was logged
67
+ expect(consoleErrorSpy).toHaveBeenCalled();
68
+
69
+ // Restore URL
70
+ global.URL = originalURL;
71
+ });
72
+
73
+ // For these tests, we can't easily verify the spawn call since it's dynamically imported
74
+ // and would require more complex mocking. Instead, we'll focus on ensuring the method
75
+ // runs without throwing errors.
76
+
77
+ it('should handle telemetry requests without throwing errors', async () => {
78
+ const payload: TelemetryTransportParams = {
79
+ url: 'https://example.com/telemetry',
80
+ method: 'POST',
81
+ headers: {
82
+ 'Content-Type': 'application/json',
83
+ 'X-Custom-Header': 'test-value',
84
+ },
85
+ data: { key: 'value' },
86
+ };
87
+
88
+ // The test passes if no exception is thrown
89
+ await expect(transport.send(payload)).resolves.toBeUndefined();
90
+ });
91
+});
packages/core/test/telemetry/TelemetryService.test.ts
new
+294
@@ -0,0 +1,294 @@
1
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
+import { TelemetryService } from '../../src/telemetry/Telemetry';
3
+import { BaseTelemetryTransport } from '../../src/telemetry/TelemetryTransport';
4
+import { BrowserTelemetryTransport } from '../../src/telemetry/transports/BrowserTransport';
5
+import { ProcessTelemetryTransport } from '../../src/telemetry/transports/ProcessTransport';
6
+import { TELEMETRY_EVENTS, TelemetryMetadata } from '../../src/types/telemetry.types';
7
+import * as envUtils from '../../src/utils/env';
8
+
9
+describe('TelemetryService', () => {
10
+ let telemetryService: TelemetryService;
11
+ let mockTransport: BaseTelemetryTransport;
12
+ let testMetadata: TelemetryMetadata;
13
+
14
+ // Save original window
15
+ const originalWindow = global.window;
16
+
17
+ beforeEach(() => {
18
+ // Create a new instance for each test
19
+ telemetryService = new TelemetryService();
20
+
21
+ // Create mock transport
22
+ mockTransport = {
23
+ send: vi.fn().mockResolvedValue(undefined),
24
+ };
25
+
26
+ // Test metadata
27
+ testMetadata = {
28
+ apiKey: 'test-api-key',
29
+ baseUrl: 'https://api.test.com',
30
+ version: '1.0.0',
31
+ framework: 'test-framework',
32
+ isAgentic: false,
33
+ source: 'test',
34
+ sessionId: 'test-session-id',
35
+ isBrowser: false,
36
+ };
37
+
38
+ // Reset window to simulate Node.js environment by default
39
+ delete (global as any).window;
40
+
41
+ // Mock environment variable
42
+ vi.spyOn(envUtils, 'getEnvVariable').mockImplementation((key, defaultValue) =>
43
+ key === 'TELEMETRY_DISABLED' ? 'false' : defaultValue || ''
44
+ );
45
+ });
46
+
47
+ afterEach(() => {
48
+ vi.clearAllMocks();
49
+
50
+ // Restore window
51
+ if (originalWindow !== undefined) {
52
+ global.window = originalWindow;
53
+ }
54
+ });
55
+
56
+ describe('setup', () => {
57
+ it('should set up telemetry metadata', () => {
58
+ telemetryService.setup(testMetadata, mockTransport);
59
+
60
+ expect(mockTransport.send).toHaveBeenCalledWith(
61
+ expect.objectContaining({
62
+ data: expect.arrayContaining([
63
+ expect.objectContaining({
64
+ eventName: TELEMETRY_EVENTS.SDK_INITIALIZED,
65
+ sdk_meta: testMetadata,
66
+ }),
67
+ ]),
68
+ })
69
+ );
70
+ });
71
+
72
+ it('should use BrowserTelemetryTransport in browser environment', () => {
73
+ // Mock window to simulate browser environment
74
+ global.window = {} as any;
75
+
76
+ // Mock BrowserTelemetryTransport constructor
77
+ const browserTransportSpy = vi
78
+ .spyOn(BrowserTelemetryTransport.prototype, 'send')
79
+ .mockImplementation(() => Promise.resolve());
80
+
81
+ telemetryService.setup(testMetadata);
82
+
83
+ // Send a test event to verify the transport
84
+ telemetryService['sendTelemetry']([
85
+ {
86
+ eventName: TELEMETRY_EVENTS.SDK_METHOD_INVOKED,
87
+ data: {},
88
+ sdk_meta: testMetadata,
89
+ },
90
+ ]);
91
+
92
+ expect(browserTransportSpy).toHaveBeenCalled();
93
+ });
94
+
95
+ it('should use ProcessTelemetryTransport in Node.js environment', () => {
96
+ // Mock ProcessTelemetryTransport constructor
97
+ const processTransportSpy = vi
98
+ .spyOn(ProcessTelemetryTransport.prototype, 'send')
99
+ .mockImplementation(() => Promise.resolve());
100
+
101
+ telemetryService.setup(testMetadata);
102
+
103
+ // Send a test event to verify the transport
104
+ telemetryService['sendTelemetry']([
105
+ {
106
+ eventName: TELEMETRY_EVENTS.SDK_METHOD_INVOKED,
107
+ data: {},
108
+ sdk_meta: testMetadata,
109
+ },
110
+ ]);
111
+
112
+ expect(processTransportSpy).toHaveBeenCalled();
113
+ });
114
+
115
+ it('should use custom transport when provided', () => {
116
+ telemetryService.setup(testMetadata, mockTransport);
117
+
118
+ // Send a test event to verify the transport
119
+ telemetryService['sendTelemetry']([
120
+ {
121
+ eventName: TELEMETRY_EVENTS.SDK_METHOD_INVOKED,
122
+ data: {},
123
+ sdk_meta: testMetadata,
124
+ },
125
+ ]);
126
+
127
+ expect(mockTransport.send).toHaveBeenCalledTimes(2); // Once during setup and once for the test
128
+ });
129
+ });
130
+
131
+ describe('instrument', () => {
132
+ class TestClass {
133
+ constructor() {}
134
+
135
+ async testMethod(param1: string, param2: number) {
136
+ return { result: `${param1}-${param2}` };
137
+ }
138
+
139
+ async failingMethod() {
140
+ throw new Error('Test error');
141
+ }
142
+
143
+ synchronousMethod() {
144
+ return 'sync result';
145
+ }
146
+ }
147
+
148
+ beforeEach(() => {
149
+ telemetryService.setup(testMetadata, mockTransport);
150
+ });
151
+
152
+ it('should instrument async methods of an object', async () => {
153
+ const testInstance = new TestClass();
154
+ telemetryService.instrument(testInstance);
155
+
156
+ // Reset the mock to clear the SDK_INITIALIZED call
157
+ vi.clearAllMocks();
158
+
159
+ await testInstance.testMethod('test', 123);
160
+
161
+ // Manually process the batch
162
+ (telemetryService as any).batchProcessor.processBatch();
163
+
164
+ expect(mockTransport.send).toHaveBeenCalledWith(
165
+ expect.objectContaining({
166
+ data: expect.arrayContaining([
167
+ expect.objectContaining({
168
+ eventName: TELEMETRY_EVENTS.SDK_METHOD_INVOKED,
169
+ data: expect.objectContaining({
170
+ fileName: 'TestClass',
171
+ method: 'testMethod',
172
+ params: ['test', 123],
173
+ }),
174
+ sdk_meta: testMetadata,
175
+ }),
176
+ ]),
177
+ })
178
+ );
179
+ });
180
+
181
+ it('should not instrument synchronous methods', () => {
182
+ const testInstance = new TestClass();
183
+ const instrumentedInstance = telemetryService.instrument(testInstance);
184
+
185
+ // The synchronous method should remain unchanged
186
+ const originalMethod = TestClass.prototype.synchronousMethod;
187
+ expect(instrumentedInstance.synchronousMethod).toBe(originalMethod);
188
+ });
189
+
190
+ it('should capture errors from instrumented methods', async () => {
191
+ const testInstance = new TestClass();
192
+ telemetryService.instrument(testInstance);
193
+
194
+ // Reset the mock to clear the SDK_INITIALIZED call
195
+ vi.clearAllMocks();
196
+
197
+ await expect(testInstance.failingMethod()).rejects.toThrow('Test error');
198
+
199
+ // Manually process the batch
200
+ (telemetryService as any).batchProcessor.processBatch();
201
+
202
+ expect(mockTransport.send).toHaveBeenCalledWith(
203
+ expect.objectContaining({
204
+ data: expect.arrayContaining([
205
+ expect.objectContaining({
206
+ eventName: TELEMETRY_EVENTS.SDK_METHOD_ERROR,
207
+ data: expect.objectContaining({
208
+ fileName: 'TestClass',
209
+ method: 'failingMethod',
210
+ error: expect.objectContaining({
211
+ message: 'Test error',
212
+ }),
213
+ }),
214
+ sdk_meta: testMetadata,
215
+ }),
216
+ ]),
217
+ })
218
+ );
219
+ });
220
+
221
+ it('should use the filename if constructor name is not available', () => {
222
+ const anonymousObject = {
223
+ async testMethod() {
224
+ return 'result';
225
+ },
226
+ };
227
+
228
+ telemetryService.instrument(anonymousObject, 'custom-filename');
229
+
230
+ // Verify the instrumentation works with the custom filename
231
+ expect(anonymousObject.testMethod).not.toBe(undefined);
232
+ expect(typeof anonymousObject.testMethod).toBe('function');
233
+ });
234
+ });
235
+
236
+ describe('sendTelemetry', () => {
237
+ beforeEach(() => {
238
+ telemetryService.setup(testMetadata, mockTransport);
239
+ });
240
+
241
+ it('should not send telemetry if transport is not set', async () => {
242
+ // Create a new instance without setting up transport
243
+ const newTelemetryService = new TelemetryService();
244
+
245
+ // Reset the mock to clear any previous calls
246
+ vi.clearAllMocks();
247
+
248
+ await newTelemetryService['sendTelemetry']([
249
+ {
250
+ eventName: TELEMETRY_EVENTS.SDK_METHOD_INVOKED,
251
+ data: {},
252
+ sdk_meta: testMetadata,
253
+ },
254
+ ]);
255
+
256
+ expect(mockTransport.send).not.toHaveBeenCalled();
257
+ });
258
+
259
+ it('should not send telemetry if telemetry is disabled', async () => {
260
+ // Mock environment variable to disable telemetry
261
+ vi.spyOn(envUtils, 'getEnvVariable').mockImplementation(() => 'true');
262
+
263
+ await telemetryService['sendTelemetry']([
264
+ {
265
+ eventName: TELEMETRY_EVENTS.SDK_METHOD_INVOKED,
266
+ data: {},
267
+ sdk_meta: testMetadata,
268
+ },
269
+ ]);
270
+
271
+ // We expect only the SDK_INITIALIZED call during setup
272
+ expect(mockTransport.send).toHaveBeenCalledTimes(1);
273
+ });
274
+
275
+ it('should send telemetry with correct payload format', async () => {
276
+ const testPayload = [
277
+ {
278
+ eventName: TELEMETRY_EVENTS.SDK_METHOD_INVOKED,
279
+ data: { test: 'data' },
280
+ sdk_meta: testMetadata,
281
+ },
282
+ ];
283
+
284
+ await telemetryService['sendTelemetry'](testPayload);
285
+
286
+ expect(mockTransport.send).toHaveBeenLastCalledWith({
287
+ data: testPayload,
288
+ url: expect.stringContaining('/api/sdk_metrics/telemetry'),
289
+ method: 'POST',
290
+ headers: { 'Content-Type': 'application/json' },
291
+ });
292
+ });
293
+ });
294
+});
pnpm-lock.yaml
+25
@@ -136,6 +136,28 @@ importers:
136
specifier: ^5.8.3
137
version: 5.8.3
138
139
+ examples/telemetry:
140
+ dependencies:
141
+ '@ai-sdk/openai':
142
+ specifier: ^1.3.16
143
+ version: 1.3.22(zod@3.24.4)
144
+ '@composio/core':
145
+ specifier: workspace:*
146
+ version: link:../../packages/core
147
+ '@composio/vercel':
148
+ specifier: workspace:*
149
+ version: link:../../packages/providers/vercel
150
+ ai:
151
+ specifier: ^4.3.8
152
+ version: 4.3.15(react@19.1.0)(zod@3.24.4)
153
+ devDependencies:
154
+ '@types/bun':
155
+ specifier: ^1.2.9
156
+ version: 1.2.13
157
+ typescript:
158
+ specifier: ^5.8.3
159
+ version: 5.8.3
160
+
161
examples/toolkits:
162
dependencies:
163
'@ai-sdk/openai':
@@ -188,6 +210,9 @@ importers:
210
'@composio/client':
211
specifier: ^0.1.0-alpha.10
212
version: 0.1.0-alpha.10
213
+ chalk:
214
+ specifier: ^5.4.1
215
+ version: 5.4.1
216
openai:
217
specifier: ^4.94.0
218
version: 4.98.0(encoding@0.1.13)(zod@3.24.4)