@devries-cameron20 / composio Mirror · read-only / commits / ce44d22b6
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 23, 04:15 UTC

Add telemetry and logging

haxzie committed Apr 17, 2025 at 15:21 UTC ce44d22b647f7f2f2ab317dcdc45b88e88997a43
25 files changed +657 -25
packages/core/src/composio.ts
+64 -10
@@ -3,22 +3,28 @@ import { Tools } from "./models/Tools";
3 import { Toolkits } from "./models/Toolkits";
4 import { Triggers } from "./models/Triggers";
5 import { ComposioToolset } from "./toolset/ComposioToolset";
6 -import { WrappedTool } from "./types/toolset.types.";
7 -import { Tool } from "./types/tool.types";
6 import { AuthConfigs } from "./models/AuthConfigs";
7 import { ConnectedAccounts } from "./models/ConnectedAccounts";
8 import { ToolListParams } from "@composio/client/resources/tools";
9 import { BaseComposioToolset } from "./toolset/BaseToolset";
10 +import { Telemetry } from "./telemetry/Telemetry";
11 +import { BaseTelemetryTransport, ConsoleTelemetryTransport } from "./telemetry/TelemetryTransport";
12 +import type { InstrumentedInstance } from "./types/telemetry.types";
13 +import { getSDKConfig } from "./utils/sdk";
14 +import logger from "./utils/logger";
15 +import { IS_DEVELOPMENT_OR_CI } from "./utils/constants";
16 +import { checkForLatestVersionFromNPM } from "./utils/version";
17
18
19 export type ComposioConfig<TToolCollection, TTool, TToolset extends BaseComposioToolset<TToolCollection, TTool>> = {
20 apiKey?: string;
16 - baseURL?: string;
21 + baseUrl?: string;
22 allowTracking?: boolean;
23 allowTracing?: boolean;
24 toolset?: TToolset;
25 userId?: string;
26 connectedAccountIds?: Record<string, string>;
27 + telemetryTransport?: BaseTelemetryTransport;
28 };
29
30 /**
@@ -28,7 +34,7 @@ export type ComposioConfig<TToolCollection, TTool, TToolset extends BaseComposio
34 export class Composio<TToolCollection, TTool, TToolset extends BaseComposioToolset<TToolCollection, TTool>> {
35
36 private readonly DEFAULT_USER_ID = "default";
31 - private static readonly FILE_NAME = "core/composio.ts";
37 + readonly FILE_NAME = "core/composio.ts";
38
39 /**
40 * The Composio API client.
@@ -42,12 +48,15 @@ export class Composio<TToolCollection, TTool, TToolset extends BaseComposioTools
48 */
49 private config: ComposioConfig<TToolCollection, TTool, TToolset>;
50
51 + private telemetry: Telemetry<InstrumentedInstance> | undefined;
52 +
53 /**
54 * Context variables for the Composio SDK.
55 */
56 userId?: string;
57 connectedAccountIds?: Record<string, string>;
58
59 +
60 /**
61 * Core models for Composio.
62 */
@@ -67,27 +76,41 @@ export class Composio<TToolCollection, TTool, TToolset extends BaseComposioTools
76 * @param {boolean} config.allowTracing Whether to allow tracing. Defaults to true.
77 * @param {TS} config.toolset The toolset to use for this Composio instance.
78 */
70 - constructor(config: ComposioConfig<TToolCollection,TTool,TToolset>) {
79 + constructor(config: ComposioConfig<TToolCollection, TTool, TToolset>) {
80 +
81 + const { baseURL: baseURLParsed, apiKey: apiKeyParsed } = getSDKConfig(
82 + config?.baseUrl,
83 + config?.apiKey
84 + );
85 +
86 + if (IS_DEVELOPMENT_OR_CI) {
87 + logger.info(
88 + `Initializing Composio w API Key: [REDACTED] and baseURL: ${baseURLParsed}`
89 + );
90 + }
91 /**
92 * Initialize the Composio SDK client.
93 * The client is used to make API calls to the Composio API.
94 */
95 this.client = new ComposioClient({
76 - apiKey: config.apiKey,
77 - baseURL: config.baseURL,
96 + apiKey: apiKeyParsed,
97 + baseURL: baseURLParsed,
98 });
99
100 /**
101 * Keep a reference to the config object.
102 * This is useful for creating a builder pattern, debugging and logging.
103 */
84 - this.config = config;
104 + this.config = {
105 + ...config,
106 + allowTracking: config.allowTracking ?? true
107 + };
108
109 /**
110 * Set the context variables for the Composio SDK.
111 */
89 - this.userId = config.userId?? this.DEFAULT_USER_ID; // entity id of the user
90 - this.connectedAccountIds = config.connectedAccountIds?? {}; // app name -> account id of the connected account
112 + this.userId = config.userId ?? this.DEFAULT_USER_ID; // entity id of the user
113 + this.connectedAccountIds = config.connectedAccountIds ?? {}; // app name -> account id of the connected account
114
115 /**
116 * Set the default toolset, if not provided by the user.
@@ -103,6 +126,37 @@ export class Composio<TToolCollection, TTool, TToolset extends BaseComposioTools
126 this.triggers = new Triggers(this.client);
127 this.authConfigs = new AuthConfigs(this.client);
128 this.connectedAccounts = new ConnectedAccounts(this.client);
129 +
130 + /**
131 + * Initialize the client telemetry.
132 + */
133 + if (this.config.allowTracking) {
134 +
135 + this.telemetry = new Telemetry({
136 + apiKey: apiKeyParsed ?? "",
137 + baseUrl: baseURLParsed ?? "",
138 + frameworkRuntime: "node",
139 + source: "node", // @TODO: get the source
140 + sessionId: this.userId,
141 + composioVersion: require('../package.json').version,
142 + isBrowser: typeof window !== "undefined",
143 + }, config.telemetryTransport ?? new ConsoleTelemetryTransport());
144 +
145 +
146 + /**
147 + * Instrument the client telemetry.
148 + */
149 + this.telemetry.instrumentTelemetry(this);
150 + this.telemetry.instrumentTelemetry(this.tools);
151 + this.telemetry.instrumentTelemetry(this.toolkits);
152 + this.telemetry.instrumentTelemetry(this.triggers);
153 + this.telemetry.instrumentTelemetry(this.authConfigs);
154 + this.telemetry.instrumentTelemetry(this.connectedAccounts);
155 + this.telemetry.instrumentTelemetry(this.toolset);
156 +
157 + // Check for the latest version of the Composio SDK from NPM.
158 + checkForLatestVersionFromNPM();
159 + }
160 }
161
162 /**
packages/core/src/index.ts
+17 -2
@@ -6,6 +6,21 @@ import type { Tool, ToolListParamsSchema, ToolListParams } from "./types/tool.ty
6 import type { Toolset } from "./types/toolset.types.";
7
8 // Utils exports
9 -import { jsonSchemaToModel } from "./utils/JsonSchema";
9 +import { jsonSchemaToModel } from "./utils/jsonSchema";
10
11 -export { Composio, ComposioToolset, BaseComposioToolset, Tool, ToolListParamsSchema, ToolListParams, Toolset, jsonSchemaToModel };
11 +// telemetry exports
12 +import type { InstrumentedInstance } from "./types/telemetry.types";
13 +import { BaseTelemetryTransport } from "./telemetry/TelemetryTransport";
14 +
15 +export {
16 + Composio,
17 + ComposioToolset,
18 + BaseComposioToolset,
19 + Tool,
20 + ToolListParamsSchema,
21 + ToolListParams,
22 + Toolset,
23 + jsonSchemaToModel,
24 + InstrumentedInstance,
25 + BaseTelemetryTransport
26 +};
packages/core/src/models/AuthConfigs.ts
+6 -1
@@ -12,6 +12,10 @@ import {
12 AuthConfigUpdateStatusParams,
13 AuthConfigUpdateStatusResponse,
14 } from "@composio/client/resources/auth-configs";
15 +import { InstrumentedInstance } from "../types/telemetry.types";
16 +
17 +
18 +
19
20 /**
21 * AuthConfigs class
@@ -19,7 +23,8 @@ import {
23 * This class is used to manage authentication configurations in the Composio SDK.
24 * Auth configs are used to configure authentication providers and settings.
25 */
22 -export class AuthConfigs {
26 +export class AuthConfigs implements InstrumentedInstance {
27 + readonly FILE_NAME: string = "core/models/AuthConfigs.ts";
28 private client: ComposioSDK;
29
30 constructor(client: ComposioSDK) {
packages/core/src/models/ConnectedAccounts.ts
+6 -1
@@ -11,6 +11,10 @@ import {
11 ConnectedAccountUpdateStatusParams,
12 ConnectedAccountUpdateStatusResponse,
13 } from "@composio/client/resources/connected-accounts";
14 +import { InstrumentedInstance } from "../types/telemetry.types";
15 +
16 +
17 +
18
19 /**
20 * ConnectedAccounts class
@@ -18,7 +22,8 @@ import {
22 * This class is used to manage connected accounts in the Composio SDK.
23 * Connected accounts are used to authenticate with third-party services.
24 */
21 -export class ConnectedAccounts {
25 +export class ConnectedAccounts implements InstrumentedInstance {
26 + readonly FILE_NAME: string = "core/models/ConnectedAccounts.ts";
27 private client: ComposioSDK;
28
29 constructor(client: ComposioSDK) {
packages/core/src/models/Toolkits.ts
+6 -1
@@ -6,6 +6,10 @@ import {
6 ToolkitRetrieveCategoriesResponse,
7 ToolkitRetrieveResponse,
8 } from "@composio/client/resources/toolkits";
9 +import { InstrumentedInstance } from "../types/telemetry.types";
10 +
11 +
12 +
13
14 /**
15 * Toolkits class
@@ -13,7 +17,8 @@ import {
17 * Toolkits are a collection of tools that can be used to perform various tasks.
18 * This is similar/replacement of `apps` in the Composio API.
19 */
16 -export class Toolkits {
20 +export class Toolkits implements InstrumentedInstance {
21 + readonly FILE_NAME: string = "core/models/Toolkits.ts";
22 private client: ComposioSDK;
23
24 constructor(client: ComposioSDK) {
packages/core/src/models/Tools.ts
+5 -2
@@ -9,14 +9,17 @@ import {
9 ToolListResponse,
10 ToolRetrieveEnumResponse,
11 } from "@composio/client/resources/tools";
12 +import { InstrumentedInstance } from "../types/telemetry.types";
13 +
14
15 /**
16 * This class is used to manage tools in the Composio SDK.
17 * It provides methods to list, get, and execute tools.
18 */
17 -export class Tools {
19 +export class Tools implements InstrumentedInstance {
20 + readonly FILE_NAME: string = "core/models/Tools.ts";
21 private client: ComposioSDK;
19 -
22 +
23 constructor(client: ComposioSDK) {
24 this.client = client;
25 }
packages/core/src/models/Triggers.ts
+6 -1
@@ -12,13 +12,18 @@ import {
12 TriggersTypeRetrieveResponse,
13 } from "@composio/client/resources/index";
14 import { TriggerStatusEnum } from "../types/triggers.types";
15 +import { InstrumentedInstance } from "../types/telemetry.types";
16 +
17 +
18 +
19
20 /**
21 * Trigger (Instance) class
22 * /api/v3/trigger_instances
23 *
24 */
21 -export class Triggers {
25 +export class Triggers implements InstrumentedInstance {
26 + readonly FILE_NAME: string = "core/models/Triggers.ts";
27 private client: ComposioSDK;
28
29 constructor(client: ComposioSDK) {
packages/core/src/telemetry/BatchProcessor.ts new
+39
@@ -0,0 +1,39 @@
1 +export class BatchProcessor {
2 + private batch: unknown[] = [];
3 + private time: number;
4 + private batchSize: number;
5 + private processBatchCallback: (data: unknown[]) => void;
6 + private timer: NodeJS.Timeout | null = null;
7 +
8 + constructor(
9 + time: number = 2000,
10 + batchSize: number = 100,
11 + processBatchCallback: (data: unknown[]) => void
12 + ) {
13 + this.batch = [];
14 + this.time = time;
15 + this.batchSize = batchSize;
16 + this.processBatchCallback = processBatchCallback;
17 + }
18 +
19 + pushItem(item: unknown) {
20 + this.batch.push(item);
21 + if (this.batch.length >= this.batchSize) {
22 + this.processBatch();
23 + } else if (!this.timer) {
24 + this.timer = setTimeout(() => this.processBatch(), this.time);
25 + }
26 + }
27 +
28 + processBatch() {
29 + if (this.batch.length > 0) {
30 + this.processBatchCallback(this.batch);
31 + this.batch = [];
32 + }
33 + if (this.timer) {
34 + clearTimeout(this.timer);
35 + this.timer = null;
36 + }
37 + }
38 + }
39 +
\ No newline at end of file
packages/core/src/telemetry/Telemetry.ts new
+125
@@ -0,0 +1,125 @@
1 +import { InstrumentedInstance, TELEMETRY_EVENTS, TelemetryMetadata, TelemetryPayload } from "../types/telemetry.types";
2 +import { TELEMETRY_URL } from "../utils/constants";
3 +import { getEnvVariable } from "../utils/env";
4 +import { BatchProcessor } from "./BatchProcessor";
5 +import { BaseTelemetryTransport } from "./TelemetryTransport";
6 +import { BrowserTelemetryTransport } from "./transports/BrowserTransport";
7 +import { ProcessTelemetryTransport } from "./transports/ProcessTransport";
8 +/**
9 + * The Telemetry class is used to log the telemetry for any given instance which extends InstrumentedInstance.
10 + *
11 + * This class is used to instrument the telemetry for the given instance and send the telemetry to the server.
12 + *
13 + * @example
14 + *
15 + * const telemetry = new Telemetry({...});
16 + * const composio = new Composio({...})
17 + *
18 + * telemetry.instrumentTelemetry(composio);
19 + * telemetry.instrumentTelemetry(composio.tools);
20 + * telemetry.instrumentTelemetry(composio.toolkits);
21 + * telemetry.instrumentTelemetry(composio.triggers);
22 + *
23 + */
24 +export class Telemetry<U extends InstrumentedInstance> {
25 +
26 + private telemetryMetadata: TelemetryMetadata;
27 + private transport: BaseTelemetryTransport;
28 +
29 + private batchProcessor = new BatchProcessor(100, 10, async (data) => {
30 + await this.sendTelemetry(data as TelemetryPayload[]);
31 + });
32 +
33 + constructor(metadata: TelemetryMetadata, transport?: BaseTelemetryTransport) {
34 + this.telemetryMetadata = metadata;
35 +
36 + const isBrowser = typeof window !== "undefined";
37 + if (transport) {
38 + this.transport = transport;
39 + } else if (isBrowser) {
40 + this.transport = new BrowserTelemetryTransport();
41 + } else {
42 + this.transport = new ProcessTelemetryTransport();
43 + }
44 +
45 + // send telemetry event for SDK initialization
46 + this.sendTelemetry([{
47 + eventName: TELEMETRY_EVENTS.SDK_INITIALIZED,
48 + data: {},
49 + sdk_meta: this.telemetryMetadata,
50 + }]);
51 + }
52 +
53 + /**
54 + * Instrument the telemetry for the given instance.
55 + *
56 + * You can pass the instance and the file name of the instance to instrument the telemetry.
57 + * This will instrument all the methods of the instance and log the telemetry for each method call.
58 + * @param instance - any instance that extends InstrumentedInstance
59 + * @param fileName - the file name of the instance
60 + * @returns
61 + */
62 + instrumentTelemetry(instance: U, fileName?: string) {
63 + const proto = Object.getPrototypeOf(instance);
64 + const methodNames = Object.getOwnPropertyNames(proto).filter((key) => {
65 + const descriptor = Object.getOwnPropertyDescriptor(proto, key);
66 + return (
67 + key !== "constructor" &&
68 + descriptor &&
69 + typeof descriptor.value === "function" &&
70 + descriptor.value.constructor.name === "AsyncFunction"
71 + );
72 + });
73 +
74 + for (const name of methodNames) {
75 + const originalMethod = (instance as any)[name];
76 + (instance as any)[name] = async (...args: any[]) => {
77 + const telemetryPayload: TelemetryPayload = {
78 + eventName: TELEMETRY_EVENTS.SDK_METHOD_INVOKED,
79 + data: {
80 + fileName: instance.FILE_NAME ?? fileName ?? "unknown",
81 + method: name,
82 + params: args,
83 + },
84 + sdk_meta: this.telemetryMetadata,
85 + }
86 +
87 + this.batchProcessor.pushItem(telemetryPayload);
88 +
89 + console.log("telemetryPayload", telemetryPayload);
90 +
91 + return await originalMethod.apply(instance, args);
92 + };
93 + }
94 +
95 + return instance;
96 + }
97 +
98 + /**
99 + * Send the telemetry payload to the server.
100 + * @param payload - the telemetry payload to send
101 + * @returns
102 + */
103 + async sendTelemetry(payload: TelemetryPayload[]) {
104 + const isTelemetryDisabled =
105 + getEnvVariable("TELEMETRY_DISABLED", "false") === "true";
106 +
107 + if (isTelemetryDisabled) {
108 + return;
109 + }
110 +
111 + const url = `${TELEMETRY_URL}/api/sdk_metrics/telemetry`;
112 +
113 + const reqPayload = {
114 + data: payload,
115 + url,
116 + method: "POST",
117 + headers: { "Content-Type": "application/json" },
118 + };
119 +
120 + console.log("reqPayload", reqPayload);
121 +
122 + this.transport.send(reqPayload);
123 + }
124 +
125 +}
packages/core/src/telemetry/TelemetryTransport.ts new
+20
@@ -0,0 +1,20 @@
1 +import { TelemetryTransportParams } from "../types/telemetry.types";
2 +
3 +export abstract class BaseTelemetryTransport {
4 + /**
5 + * Send the payload to the telemetry service.
6 + * @param payload - The payload to send.
7 + */
8 + abstract send(payload: TelemetryTransportParams): Promise<void>;
9 +}
10 +
11 +/**
12 + * A telemetry transport that logs to the console.
13 + * This is just for testing purposes.
14 + */
15 +export class ConsoleTelemetryTransport implements BaseTelemetryTransport {
16 + send(payload: TelemetryTransportParams): Promise<void> {
17 + console.log("payload", payload);
18 + return Promise.resolve();
19 + }
20 +}
\ No newline at end of file
packages/core/src/telemetry/transports/BrowserTransport.ts new
+42
@@ -0,0 +1,42 @@
1 +import { TelemetryTransportParams } from "../../types/telemetry.types";
2 +import { BaseTelemetryTransport } from "../TelemetryTransport";
3 +
4 +export class BrowserTelemetryTransport implements BaseTelemetryTransport {
5 + send(payload: TelemetryTransportParams): Promise<void> {
6 + if (typeof window === 'undefined') {
7 + return Promise.reject(new Error('BrowserTelemetryTransport can only be used in browser environments'));
8 + }
9 +
10 + console.log("Sending telemetry to", payload.url);
11 +
12 + return new Promise((resolve) => {
13 + try {
14 + // Create a new XMLHttpRequest object
15 + const xhr = new XMLHttpRequest();
16 + // Open a new POST request to the telemetry server
17 + xhr.open(payload.method, payload.url, true);
18 + // Set the request header to indicate JSON content
19 + xhr.setRequestHeader("Content-Type", "application/json");
20 + Object.entries(payload.headers || {}).forEach(([key, value]) => {
21 + xhr.setRequestHeader(key, value);
22 + });
23 +
24 + // Define the onload event handler
25 + xhr.onload = function () {
26 + // Log the response if the request was successful
27 + // if (xhr.status === 200) {
28 + // logger.debug(xhr.response);
29 + // }
30 + resolve();
31 + };
32 +
33 + // Send the reporting payload as a JSON string
34 + xhr.send(JSON.stringify(payload.data));
35 + } catch (error) {
36 + // logger.debug("Error sending error to telemetry", error);
37 + // DO NOTHING
38 + resolve();
39 + }
40 + });
41 + }
42 +}
packages/core/src/telemetry/transports/ProcessTransport.ts new
+56
@@ -0,0 +1,56 @@
1 +import { TelemetryTransportParams } from "../../types/telemetry.types";
2 +import { BaseTelemetryTransport } from "../TelemetryTransport";
3 +
4 +export class ProcessTelemetryTransport implements BaseTelemetryTransport {
5 + send(payload: TelemetryTransportParams): Promise<void> {
6 + if (typeof window !== 'undefined') {
7 + return Promise.reject(new Error('ProcessTelemetryTransport can only be used in Node.js environments'));
8 + }
9 +
10 + return new Promise((resolve) => {
11 + try {
12 + const url = new URL(payload.url);
13 + const protocol = url.protocol === "https:" ? "https" : "http";
14 + const port = url.port || (url.protocol === "https:" ? 443 : 80);
15 +
16 + const args = [
17 + "-e",
18 + `
19 + const http = require('${protocol}');
20 + const options = {
21 + hostname: '${url.hostname}',
22 + path: '${url.pathname}${url.search}',
23 + port: ${port},
24 + method: '${payload.method}',
25 + headers: ${JSON.stringify(payload.headers)}
26 + };
27 +
28 + const req = http.request(options, (res) => {
29 + res.on('data', () => {});
30 + res.on('end', () => {
31 + process.exit(0);
32 + });
33 + });
34 +
35 + req.on('error', () => {
36 + process.exit(0);
37 + });
38 +
39 + req.write(JSON.stringify(${JSON.stringify(payload.data)}));
40 + req.end();
41 + `,
42 + ];
43 +
44 + const { spawn } = require("child_process");
45 + spawn("node", args, {
46 + stdio: "ignore",
47 + detached: true,
48 + shell: false,
49 + }).unref();
50 + resolve();
51 + } catch (error) {
52 + resolve();
53 + }
54 + });
55 + }
56 +}
\ No newline at end of file
packages/core/src/toolset/BaseToolset.ts
+2 -1
@@ -15,7 +15,8 @@ import { Composio } from "../composio";
15 */
16 export abstract class BaseComposioToolset<TToolCollection, TTool = BaseTool> implements Toolset<TTool, TToolCollection> {
17 protected client: Composio<TToolCollection, TTool, this> | undefined;
18 -
18 + abstract FILE_NAME: string;
19 +
20 /**
21 * Set the client for the toolset. This is automatically done by the Composio class.
22 * @param client - The Composio client.
packages/core/src/toolset/ComposioToolset.ts
+2 -1
@@ -12,7 +12,8 @@ interface CustomTool {
12 name: string;
13 }
14 export class ComposioToolset extends BaseComposioToolset<Array<CustomTool>, CustomTool> {
15 -
15 + readonly FILE_NAME: string = "core/toolset/ComposioToolset.ts";
16 +
17 _wrapTool = (tool: Tool): CustomTool => {
18 return tool as CustomTool;
19 };
packages/core/src/types/Toolset.types..ts
+3 -1
@@ -1,11 +1,13 @@
1 import { Composio } from "../composio";
2 +import { InstrumentedInstance } from "./telemetry.types";
3 import { Tool, BaseTool, ToolListParams } from "./tool.types";
4
5 /**
6 * Base toolset implementation, which needs to be implemented by the extended class.
7 * This class is used to create a base toolset by implementing this class.
8 + * This class also extends InstrumentedInstance, so that the telemetry can be instrumented for the toolset.
9 */
8 -export interface Toolset<TTool = BaseTool, TToolCollection = TTool[]> {
10 +export interface Toolset<TTool = BaseTool, TToolCollection = TTool[]> extends InstrumentedInstance {
11 _wrapTool: (tool: Tool) => TTool;
12 getTools: (params?: ToolListParams) => Promise<TToolCollection>;
13 }
packages/core/src/types/telemetry.types.ts new
+53
@@ -0,0 +1,53 @@
1 +
2 +export const TELEMETRY_EVENTS = {
3 + SDK_INITIALIZED: "SDK_INITIALIZED",
4 + SDK_METHOD_INVOKED: "SDK_METHOD_INVOKED",
5 + CLI_INVOKED: "CLI_INVOKED",
6 +} as const;
7 +
8 +export type TelemetryEvent = typeof TELEMETRY_EVENTS[keyof typeof TELEMETRY_EVENTS];
9 +
10 +
11 +/**
12 + * Interface for any instance that extends InstrumentedInstance.
13 + * Classess implementing this interface will be instrumented for telemetry.
14 + */
15 +export interface InstrumentedInstance {
16 + FILE_NAME: string;
17 +}
18 +
19 +/**
20 + * Metadata for the telemetry.
21 + */
22 +export type TelemetryMetadata = {
23 + apiKey: string;
24 + baseUrl: string;
25 + composioVersion: string;
26 + frameworkRuntime: string;
27 + source: string;
28 + sessionId: string;
29 + isBrowser?: boolean;
30 +}
31 +
32 +export type TelemetryPayload = {
33 + eventName: TelemetryEvent;
34 + data: Record<string, unknown>;
35 + sdk_meta: TelemetryMetadata;
36 +}
37 +
38 +
39 +type AcceptableJSONValue =
40 + | Record<string, unknown>
41 + | Array<Record<string, unknown>>
42 + | string
43 + | number
44 + | boolean
45 + | null
46 + | undefined;
47 +
48 +export interface TelemetryTransportParams {
49 + url: string;
50 + method: string;
51 + headers: Record<string, string>;
52 + data: AcceptableJSONValue;
53 +}
packages/core/src/utils/constants.ts new
+10
@@ -0,0 +1,10 @@
1 +// Constants
2 +export const COMPOSIO_DIR = ".composio";
3 +export const USER_DATA_FILE_NAME = "user_data.json";
4 +export const TEMP_FILES_DIRECTORY_NAME = "files";
5 +export const DEFAULT_BASE_URL = "https://backend.composio.dev";
6 +
7 +export const TELEMETRY_URL = "https://app.composio.dev";
8 +
9 +export const IS_DEVELOPMENT_OR_CI =
10 + process.env.DEVELOPMENT || process.env.CI || false;
packages/core/src/utils/env.ts new
+10
@@ -0,0 +1,10 @@
1 +export const getEnvVariable = (
2 + name: string,
3 + defaultValue: string | undefined = undefined
4 + ): string | undefined => {
5 + try {
6 + return process.env[name] || defaultValue;
7 + } catch (_e) {
8 + return defaultValue;
9 + }
10 + };
\ No newline at end of file
packages/core/src/utils/logger.ts new
+89
@@ -0,0 +1,89 @@
1 +import { getEnvVariable } from "./env";
2 +
3 +// Define log levels with corresponding priorities
4 +export const LOG_LEVELS = {
5 + silent: -1, // No logs
6 + error: 0, // Highest priority - critical errors
7 + warn: 1, // Warning messages
8 + info: 2, // General information
9 + debug: 3, // Debug information
10 +} as const;
11 +
12 +export type LogLevel = keyof typeof LOG_LEVELS;
13 +
14 +/**
15 + * Get the current log level from environment variables.
16 + * Defaults to 'info' if not set or invalid.
17 + * @returns {LogLevel} The current log level
18 + */
19 +export const getLogLevel = (): LogLevel => {
20 + const envLevel = getEnvVariable(
21 + "COMPOSIO_LOGGING_LEVEL",
22 + "info"
23 + )?.toLowerCase();
24 + return envLevel && envLevel in LOG_LEVELS
25 + ? (envLevel as LogLevel)
26 + : "info";
27 +};
28 +
29 +interface LoggerOptions {
30 + level?: LogLevel;
31 + includeTimestamp?: boolean;
32 +}
33 +
34 +class Logger {
35 + private readonly level: LogLevel;
36 + private readonly includeTimestamp: boolean;
37 + private readonly console: Console;
38 +
39 + constructor(options: LoggerOptions = {}) {
40 + this.level = options.level ?? getLogLevel();
41 + this.includeTimestamp = options.includeTimestamp ?? true;
42 + this.console = console;
43 + }
44 +
45 + private formatMessage(args: unknown[]): string {
46 + const formattedArgs = args
47 + .map((arg) => (typeof arg === "object" ? JSON.stringify(arg) : String(arg)))
48 + .join(" ");
49 +
50 + if (!this.includeTimestamp) {
51 + return formattedArgs;
52 + }
53 +
54 + const timestamp = new Date().toISOString();
55 + return `${timestamp} - ${formattedArgs}`;
56 + }
57 +
58 + private shouldLog(level: LogLevel): boolean {
59 + return LOG_LEVELS[level] <= LOG_LEVELS[this.level];
60 + }
61 +
62 + error(...args: unknown[]): void {
63 + if (this.shouldLog("error")) {
64 + this.console.error(this.formatMessage(args));
65 + }
66 + }
67 +
68 + warn(...args: unknown[]): void {
69 + if (this.shouldLog("warn")) {
70 + this.console.warn(this.formatMessage(args));
71 + }
72 + }
73 +
74 + info(...args: unknown[]): void {
75 + if (this.shouldLog("info")) {
76 + this.console.info(this.formatMessage(args));
77 + }
78 + }
79 +
80 + debug(...args: unknown[]): void {
81 + if (this.shouldLog("debug")) {
82 + this.console.debug(this.formatMessage(args));
83 + }
84 + }
85 +}
86 +
87 +// Create and export a default logger instance
88 +const logger = new Logger();
89 +export default logger;
packages/core/src/utils/sdk.ts new
+43
@@ -0,0 +1,43 @@
1 +import { COMPOSIO_DIR, DEFAULT_BASE_URL, USER_DATA_FILE_NAME } from "./constants";
2 +import { getEnvVariable } from "./env";
3 +
4 +// File path helpers
5 +export const userDataPath = () => {
6 + try {
7 + // eslint-disable-next-line @typescript-eslint/no-require-imports
8 + const path = require("path");
9 + // eslint-disable-next-line @typescript-eslint/no-require-imports
10 + const os = require("os");
11 + return path.join(os.homedir(), COMPOSIO_DIR, USER_DATA_FILE_NAME);
12 + } catch (_error) {
13 + return null;
14 + }
15 +};
16 +
17 +export const getUserDataJson = () => {
18 + try {
19 + // eslint-disable-next-line @typescript-eslint/no-require-imports
20 + const fs = require("fs");
21 + const data = fs.readFileSync(userDataPath(), "utf8");
22 + return JSON.parse(data);
23 + } catch (_error) {
24 + return {};
25 + }
26 +};
27 +
28 +// Client configuration functions
29 +export function getSDKConfig(baseUrl?: string, apiKey?: string) {
30 + const userData = getUserDataJson();
31 + const { api_key: apiKeyFromUserConfig, base_url: baseURLFromUserConfig } =
32 + userData;
33 +
34 + const baseURLParsed =
35 + baseUrl ||
36 + getEnvVariable("COMPOSIO_BASE_URL") ||
37 + baseURLFromUserConfig ||
38 + DEFAULT_BASE_URL;
39 + const apiKeyParsed =
40 + apiKey || getEnvVariable("COMPOSIO_API_KEY") || apiKeyFromUserConfig || "";
41 +
42 + return { baseURL: baseURLParsed, apiKey: apiKeyParsed };
43 +}
\ No newline at end of file
packages/core/src/utils/version.ts new
+48
@@ -0,0 +1,48 @@
1 +import logger from "./logger";
2 +import { IS_DEVELOPMENT_OR_CI } from "./constants";
3 +
4 +/**
5 + * Compares two semantic versions and returns true if the first version is newer than the second.
6 + * @param version1 The first version to compare
7 + * @param version2 The second version to compare
8 + * @returns boolean indicating if version1 is newer than version2
9 + */
10 +export function isNewerVersion(version1: string, version2: string): boolean {
11 + const v1 = version1.split('.').map(Number);
12 + const v2 = version2.split('.').map(Number);
13 +
14 + for (let i = 0; i < 3; i++) {
15 + if (v1[i] > v2[i]) return true;
16 + if (v1[i] < v2[i]) return false;
17 + }
18 + return false;
19 +}
20 +
21 +/**
22 + * Checks for the latest version of the Composio SDK from NPM.
23 + * If a newer version is available, it logs a warning to the console.
24 + */
25 +export async function checkForLatestVersionFromNPM() {
26 + try {
27 + const packageName = "composio-core";
28 + const currentVersionFromPackageJson = require("../../package.json").version;
29 +
30 + // @TODO: Check if fetch is available, if not use node-fetch
31 + const response = await fetch(
32 + `https://registry.npmjs.org/${packageName}/latest`
33 + );
34 + const data = await response.json();
35 + const latestVersion = data.version;
36 +
37 + if (
38 + isNewerVersion(latestVersion, currentVersionFromPackageJson) &&
39 + !IS_DEVELOPMENT_OR_CI
40 + ) {
41 + logger.info(
42 + `🚀 Upgrade available! Your composio-core version (${currentVersionFromPackageJson}) is behind. Latest version: ${latestVersion}.`
43 + );
44 + }
45 + } catch (_error) {
46 + // Ignore and do nothing
47 + }
48 +}
\ No newline at end of file
packages/toolsets/cloudflare/src/index.ts
+2 -1
@@ -4,9 +4,10 @@ import { BaseComposioToolset, Tool, ToolListParams } from "@composio/core";
4 type AiToolCollection = Record<string, AiTextGenerationToolInput>;
5
6 export class CloudflareToolset extends BaseComposioToolset<AiToolCollection, AiTextGenerationToolInput> {
7 + readonly FILE_NAME: string = "toolsets/cloudflare/src/index.ts";
8 +
9 static FRAMEWORK_NAME = "cloudflare";
10 private DEFAULT_ENTITY_ID = "default";
9 - static fileName: string = "toolsets/cloudflare/src/index.ts";
11
12 /**
13 * Abstract method to wrap a tool in the toolset.
packages/toolsets/langchain/src/index.ts
+1 -1
@@ -6,7 +6,7 @@ import { DynamicStructuredTool } from "@langchain/core/tools";
6 export class LangchainToolset extends BaseComposioToolset<Array<DynamicStructuredTool>, DynamicStructuredTool> {
7 static FRAMEWORK_NAME = "langchain";
8 private DEFAULT_ENTITY_ID = "default";
9 - static fileName: string = "toolsets/langchain/src/index.ts";
9 + readonly FILE_NAME: string = "toolsets/langchain/src/index.ts";
10
11 /**
12 * Abstract method to wrap a tool in the toolset.
packages/toolsets/openai/src/index.ts
+1 -1
@@ -6,7 +6,7 @@ import { Stream } from "openai/streaming";
6 type OpenAiToolCollection = Array<OpenAI.ChatCompletionTool>;
7 export class OpenAIToolset extends BaseComposioToolset<OpenAiToolCollection, OpenAI.ChatCompletionTool> {
8 static readonly FRAMEWORK_NAME = "openai";
9 - private static readonly FILE_NAME = "toolsets/openai/src/index.ts";
9 + readonly FILE_NAME = "toolsets/openai/src/index.ts";
10
11 constructor() {
12 super();
packages/toolsets/vercel/src/index.ts
+1 -1
@@ -5,7 +5,7 @@ import { jsonSchema, tool } from "ai";
5 type VercelToolCollection = Record<string, VercelTool>;
6 export class VercelToolset extends BaseComposioToolset<VercelToolCollection, VercelTool> {
7
8 - private static readonly FILE_NAME = "toolsets/vercel/src/index.ts";
8 + readonly FILE_NAME = "toolsets/vercel/src/index.ts";
9 static readonly FRAMEWORK_NAME = "vercel";
10
11 /**