@composio/core 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/dist/BaseProvider-BBnsv9kS.d.mts +29425 -0
  2. package/dist/{BaseProvider-CVbQxTNa.d.cts → BaseProvider-Brb3o86-.d.mts} +91 -44
  3. package/dist/CustomTool-D9qwyMrv.mjs +468 -0
  4. package/dist/{CustomTool-C-IUByoU.d.cts → CustomTool-Dmi6ti3I.d.mts} +2 -4
  5. package/dist/{CustomTool-CChQSp44.d.mts → CustomTool-DrJpOhY2.d.mts} +2 -4
  6. package/dist/{FileModifierErrors-C7z16Dfi.mjs → FileModifierErrors-3fSwIWoa.mjs} +35 -36
  7. package/dist/{Telemetry-DQax33Gh.mjs → Telemetry-DhGI_J4G.mjs} +15 -15
  8. package/dist/{composio-pcA13w87.d.cts → composio-DHIKRdeG.d.mts} +641 -380
  9. package/dist/{composio-BlASKqjQ.d.mts → composio-vMwhASRc.d.mts} +1390 -1129
  10. package/dist/{customTool.types-QtkAZQma.d.cts → customTool.types-CKH2R2ia.d.mts} +487 -189
  11. package/dist/{customTool.types-DLIORcYN.d.mts → customTool.types-DXin7Cfc.d.mts} +924 -626
  12. package/dist/docs/error-consistency.md +97 -0
  13. package/dist/docs/reference/sdk-reference/typescript/auth-configs.mdx +306 -0
  14. package/dist/docs/reference/sdk-reference/typescript/composio.mdx +205 -0
  15. package/dist/docs/reference/sdk-reference/typescript/connected-accounts.mdx +488 -0
  16. package/dist/docs/reference/sdk-reference/typescript/experimental.mdx +94 -0
  17. package/dist/docs/reference/sdk-reference/typescript/index.mdx +67 -0
  18. package/dist/docs/reference/sdk-reference/typescript/mcp.mdx +304 -0
  19. package/dist/docs/reference/sdk-reference/typescript/meta.json +17 -0
  20. package/dist/docs/reference/sdk-reference/typescript/remote-file.mdx +107 -0
  21. package/dist/docs/reference/sdk-reference/typescript/session-files.mdx +163 -0
  22. package/dist/docs/reference/sdk-reference/typescript/session.mdx +229 -0
  23. package/dist/docs/reference/sdk-reference/typescript/sessions.mdx +131 -0
  24. package/dist/docs/reference/sdk-reference/typescript/toolkits.mdx +169 -0
  25. package/dist/docs/reference/sdk-reference/typescript/tools.mdx +453 -0
  26. package/dist/docs/reference/sdk-reference/typescript/triggers.mdx +434 -0
  27. package/dist/{CustomTool-D5s-aADw.mjs → errors-DSIlYfl5.mjs} +72 -459
  28. package/dist/experimental/index.d.mts +2 -3
  29. package/dist/experimental/index.mjs +1 -3
  30. package/dist/{fileUtils.node-Dq7ebZPC.mjs → fileUtils.node-BiO1JQsJ.mjs} +26 -25
  31. package/dist/index.d.mts +1708 -2400
  32. package/dist/index.mjs +2632 -2006
  33. package/dist/jsonSchema-CFKdONpP.mjs +251 -0
  34. package/dist/models/Files.node.d.mts +1 -2
  35. package/dist/models/Files.node.mjs +3 -4
  36. package/dist/models/Files.workerd.d.mts +0 -1
  37. package/dist/platform/node.d.mts +1 -2
  38. package/dist/platform/workerd.d.mts +1 -2
  39. package/dist/{chunk-CWQeghP5.mjs → rolldown-runtime-w6R9maHv.mjs} +3 -5
  40. package/dist/{types-J2KCXP8R.d.mts → types-D4Id3wXA.d.mts} +2 -3
  41. package/dist/{types-DRG5qLxI.d.cts → types-qTbYYBJw.d.mts} +2 -3
  42. package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -4
  43. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -4
  44. package/dist/utils/config-defaults/ConfigDefaults.workerd.mjs +3 -0
  45. package/dist/utils/json-schema.d.mts +2 -0
  46. package/dist/utils/json-schema.mjs +3 -0
  47. package/dist/utils/modifiers/FileToolModifier.node.d.mts +3 -1
  48. package/dist/utils/modifiers/FileToolModifier.node.mjs +44 -24
  49. package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +3 -1
  50. package/dist/utils/modifiers/FileToolModifier.workerd.mjs +1 -1
  51. package/docs/error-consistency.md +97 -0
  52. package/package.json +40 -88
  53. package/src/composio.ts +509 -0
  54. package/src/errors/AuthConfigErrors.ts +23 -0
  55. package/src/errors/ComposioError.ts +408 -0
  56. package/src/errors/ConnectedAccountsErrors.ts +158 -0
  57. package/src/errors/ConnectionRequestErrors.ts +32 -0
  58. package/src/errors/FileModifierErrors.ts +100 -0
  59. package/src/errors/PusherErrors.ts +28 -0
  60. package/src/errors/RemoteFileErrors.ts +62 -0
  61. package/src/errors/SDKErrors.ts +92 -0
  62. package/src/errors/ToolErrors.ts +244 -0
  63. package/src/errors/ToolkitErrors.ts +39 -0
  64. package/src/errors/TriggerErrors.ts +120 -0
  65. package/src/errors/ValidationErrors.ts +99 -0
  66. package/src/errors/index.ts +41 -0
  67. package/src/experimental/index.ts +28 -0
  68. package/src/index.ts +64 -0
  69. package/src/lib/toolRouterConstants.ts +1 -0
  70. package/src/lib/toolRouterParams.ts +306 -0
  71. package/src/models/AuthConfigs.ts +398 -0
  72. package/src/models/AuthScheme.ts +206 -0
  73. package/src/models/ConnectedAccounts.ts +735 -0
  74. package/src/models/ConnectionRequest.ts +150 -0
  75. package/src/models/CustomTool.ts +676 -0
  76. package/src/models/Experimental.ts +202 -0
  77. package/src/models/Files.node.ts +93 -0
  78. package/src/models/Files.workerd.ts +49 -0
  79. package/src/models/MCP.ts +478 -0
  80. package/src/models/RemoteFile.ts +172 -0
  81. package/src/models/SessionContext.ts +147 -0
  82. package/src/models/Sessions.ts +21 -0
  83. package/src/models/ToolRouter.ts +391 -0
  84. package/src/models/ToolRouterSession.ts +827 -0
  85. package/src/models/ToolRouterSessionFileMount.ts +389 -0
  86. package/src/models/Toolkits.ts +412 -0
  87. package/src/models/Tools.ts +1260 -0
  88. package/src/models/Triggers.ts +1381 -0
  89. package/src/models/customToolExecution.ts +118 -0
  90. package/src/models/inlineCustomToolsPayload.ts +17 -0
  91. package/src/models/proxyParamsTransform.ts +26 -0
  92. package/src/provider/BaseProvider.ts +138 -0
  93. package/src/provider/ComposioProvider.ts +29 -0
  94. package/src/provider/OpenAIProvider.ts +547 -0
  95. package/src/services/internal/InternalService.ts +50 -0
  96. package/src/services/internal/InternalService.types.ts +14 -0
  97. package/src/services/pusher/Pusher.ts +230 -0
  98. package/src/services/telemetry/TelemetryService.ts +48 -0
  99. package/src/services/telemetry/TelemetryService.types.ts +67 -0
  100. package/src/telemetry/BatchProcessor.ts +77 -0
  101. package/src/telemetry/README.md +123 -0
  102. package/src/telemetry/Telemetry.ts +356 -0
  103. package/src/types/ToolRouterSessionFilesMount.types.ts +96 -0
  104. package/src/types/authConfigs.types.ts +174 -0
  105. package/src/types/composio.types.ts +1 -0
  106. package/src/types/connectedAccountAuthStates.types.ts +852 -0
  107. package/src/types/connectedAccounts.types.ts +395 -0
  108. package/src/types/connectionRequest.types.ts +16 -0
  109. package/src/types/customTool.types.ts +261 -0
  110. package/{dist/files.types-lo4zZd87.d.cts → src/types/files.types.ts} +3 -5
  111. package/src/types/mcp.experimental.types.ts +163 -0
  112. package/src/types/mcp.types.ts +362 -0
  113. package/src/types/modifiers.types.ts +663 -0
  114. package/src/types/org.types.ts +0 -0
  115. package/src/types/provider.types.ts +41 -0
  116. package/src/types/pusher.types.ts +18 -0
  117. package/src/types/requestOptions.types.ts +62 -0
  118. package/src/types/telemetry.types.ts +89 -0
  119. package/src/types/tool.types.ts +408 -0
  120. package/src/types/toolRouter.types.ts +761 -0
  121. package/src/types/toolkit.types.ts +130 -0
  122. package/src/types/triggers.types.ts +401 -0
  123. package/src/types/webhookEvents.types.ts +219 -0
  124. package/src/utils/buffer.ts +30 -0
  125. package/src/utils/cancellation.ts +22 -0
  126. package/src/utils/config-defaults/ConfigDefaults.node.ts +7 -0
  127. package/src/utils/config-defaults/ConfigDefaults.workerd.ts +10 -0
  128. package/src/utils/config-defaults/index.ts +1 -0
  129. package/src/utils/config-defaults/types.ts +14 -0
  130. package/src/utils/constants.ts +22 -0
  131. package/src/utils/crypto.ts +34 -0
  132. package/src/utils/env.ts +34 -0
  133. package/src/utils/fileDirs.ts +81 -0
  134. package/src/utils/fileUtils.node.ts +458 -0
  135. package/src/utils/json-schema.ts +1 -0
  136. package/src/utils/jsonSchema.ts +355 -0
  137. package/src/utils/logger.ts +99 -0
  138. package/src/utils/mime.ts +75 -0
  139. package/src/utils/modifiers/FileToolModifier.node.ts +477 -0
  140. package/src/utils/modifiers/FileToolModifier.utils.neutral.ts +132 -0
  141. package/src/utils/modifiers/FileToolModifier.workerd.ts +51 -0
  142. package/src/utils/pagination.ts +73 -0
  143. package/src/utils/pusher.ts +286 -0
  144. package/src/utils/schemaPropertyKeys.ts +433 -0
  145. package/src/utils/sdk.ts +110 -0
  146. package/src/utils/sensitiveFileUploadPaths.node.ts +105 -0
  147. package/src/utils/session.ts +114 -0
  148. package/src/utils/toolArguments.ts +73 -0
  149. package/src/utils/toolkitVersion.ts +26 -0
  150. package/src/utils/transform.ts +42 -0
  151. package/src/utils/transformers/authConfigs.ts +107 -0
  152. package/src/utils/transformers/connectedAccounts.ts +119 -0
  153. package/src/utils/transformers/mcp.ts +164 -0
  154. package/src/utils/transformers/toolRouterResponseTransform.ts +160 -0
  155. package/src/utils/transformers/toolkits.ts +100 -0
  156. package/src/utils/transformers/triggers.ts +118 -0
  157. package/src/utils/uploadDirAllowlist.node.ts +178 -0
  158. package/src/utils/uuid.ts +7 -0
  159. package/src/utils/version.ts +58 -0
  160. package/src/utils/zodSchema.ts +90 -0
  161. package/dist/BaseProvider-BvHvJLXc.d.mts +0 -29378
  162. package/dist/CustomTool-D3-NreIm.cjs +0 -1341
  163. package/dist/FileModifierErrors-BYJBHiay.cjs +0 -554
  164. package/dist/FileToolModifier.utils.neutral-DSBQs9-i.cjs +0 -96
  165. package/dist/Telemetry-BQ_pl5AK.cjs +0 -360
  166. package/dist/buffer-BjWptbNH.cjs +0 -63
  167. package/dist/chunk-CQwRTUmo.cjs +0 -53
  168. package/dist/experimental/index.cjs +0 -5
  169. package/dist/experimental/index.d.cts +0 -3
  170. package/dist/fileUtils.node-DtnSRMWa.cjs +0 -462
  171. package/dist/index.cjs +0 -8523
  172. package/dist/index.d.cts +0 -6065
  173. package/dist/models/Files.node.cjs +0 -55
  174. package/dist/models/Files.node.d.cts +0 -56
  175. package/dist/models/Files.workerd.cjs +0 -29
  176. package/dist/models/Files.workerd.d.cts +0 -13
  177. package/dist/platform/node.cjs +0 -55
  178. package/dist/platform/node.d.cts +0 -11
  179. package/dist/platform/workerd.cjs +0 -42
  180. package/dist/platform/workerd.d.cts +0 -12
  181. package/dist/types-pDNm1lYs.d.cts +0 -69
  182. package/dist/utils/config-defaults/ConfigDefaults.node.cjs +0 -10
  183. package/dist/utils/config-defaults/ConfigDefaults.node.d.cts +0 -7
  184. package/dist/utils/config-defaults/ConfigDefaults.workerd.cjs +0 -10
  185. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.cts +0 -7
  186. package/dist/utils/modifiers/FileToolModifier.node.cjs +0 -224
  187. package/dist/utils/modifiers/FileToolModifier.node.d.cts +0 -22
  188. package/dist/utils/modifiers/FileToolModifier.workerd.cjs +0 -27
  189. package/dist/utils/modifiers/FileToolModifier.workerd.d.cts +0 -20
  190. /package/dist/{FileToolModifier.utils.neutral-BpSceNK8.mjs → FileToolModifier.utils.neutral-B5rT711M.mjs} +0 -0
  191. /package/dist/{buffer-yOtEsT4J.mjs → buffer-PcbMMsgm.mjs} +0 -0
  192. /package/dist/{files.types-BXDWA_zS.d.mts → files.types-DeMC_mAW.d.mts} +0 -0
  193. /package/dist/{types-HpJQ8K9l.d.mts → types-DdoCRzLj.d.mts} +0 -0
@@ -0,0 +1,230 @@
1
+ import ComposioClient from '@composio/client';
2
+ import { PusherClient, TChunkedTriggerData } from '../../types/pusher.types';
3
+ import { InternalService } from '../internal/InternalService';
4
+ import { SDKRealtimeCredentialsResponse } from '../internal/InternalService.types';
5
+ import {
6
+ ComposioFailedToCreatePusherClientError,
7
+ ComposioFailedToGetSDKRealtimeCredentialsError,
8
+ ComposioFailedToSubscribeToPusherChannelError,
9
+ } from '../../errors/TriggerErrors';
10
+ import logger from '../../utils/logger';
11
+ import { telemetry } from '../../telemetry/Telemetry';
12
+
13
+ export class PusherService {
14
+ // these values are set via the Apollo API `/internal/sdk/realtime/credentials` endpoint
15
+ private clientId!: string;
16
+ private pusherKey!: string;
17
+ private pusherCluster!: string;
18
+ private pusherChannel!: string;
19
+ // these details are set via the client SDK
20
+ private pusherBaseURL!: string;
21
+ private apiKey!: string;
22
+ private pusherClient!: PusherClient;
23
+ private composioClient!: ComposioClient;
24
+
25
+ constructor(client: ComposioClient) {
26
+ this.composioClient = client;
27
+ this.pusherBaseURL = client.baseURL;
28
+ this.apiKey = client.apiKey ?? process.env.COMPOSIO_API_KEY ?? '';
29
+ telemetry.instrument(this, 'PusherService');
30
+ }
31
+
32
+ /**
33
+ * Creates a Pusher client
34
+ *
35
+ * This method is called when the Pusher client is first used.
36
+ * It will fetch the SDK realtime credentials from the Apollo API and create a Pusher client.
37
+ */
38
+ private async getPusherClient() {
39
+ if (!this.pusherClient) {
40
+ const internalService = new InternalService(this.composioClient);
41
+ let sdkRealtimeCredentials: SDKRealtimeCredentialsResponse;
42
+ try {
43
+ sdkRealtimeCredentials = await internalService.getSDKRealtimeCredentials();
44
+ } catch (error) {
45
+ throw new ComposioFailedToGetSDKRealtimeCredentialsError(
46
+ 'Failed to get SDK realtime credentials',
47
+ {
48
+ cause: error,
49
+ }
50
+ );
51
+ }
52
+
53
+ this.clientId = sdkRealtimeCredentials.projectId;
54
+ this.pusherKey = sdkRealtimeCredentials.pusherKey;
55
+ this.pusherCluster = sdkRealtimeCredentials.pusherCluster;
56
+ this.pusherChannel = `private-${this.clientId}_triggers`;
57
+
58
+ logger.debug(
59
+ `[PusherService] Creating Pusher client for client ID: ${this.clientId} in cluster ${this.pusherCluster}`
60
+ );
61
+
62
+ // create the Pusher client
63
+ try {
64
+ const { default: Pusher } = await import('pusher-js');
65
+ this.pusherClient = new Pusher(this.pusherKey, {
66
+ cluster: this.pusherCluster,
67
+ channelAuthorization: {
68
+ endpoint: `${this.pusherBaseURL}/api/v3/internal/sdk/realtime/auth`,
69
+ headers: {
70
+ 'x-api-key': this.apiKey,
71
+ },
72
+ transport: 'ajax',
73
+ },
74
+ });
75
+ } catch (error) {
76
+ throw new ComposioFailedToCreatePusherClientError('Failed to create Pusher client', {
77
+ cause: error,
78
+ });
79
+ }
80
+ }
81
+
82
+ return this.pusherClient;
83
+ }
84
+
85
+ /**
86
+ * Binds a chunked event to a Pusher client
87
+ *
88
+ *
89
+ * @param channel - The Pusher client to bind the event to
90
+ * @param event - The event to bind to
91
+ * @param callback - The function to call when the event is received
92
+ */
93
+ private bindWithChunking(
94
+ channel: PusherClient,
95
+ event: string,
96
+ callback: (data: Record<string, unknown>) => void
97
+ ): void {
98
+ try {
99
+ channel.bind(event, callback);
100
+
101
+ // Now the chunked variation. Allows arbitrarily long messages.
102
+ const events: {
103
+ [key: string]: { chunks: string[]; receivedFinal: boolean };
104
+ } = {};
105
+
106
+ channel.bind('chunked-' + event, data => {
107
+ try {
108
+ const typedData = data as TChunkedTriggerData;
109
+
110
+ // Validate chunked data
111
+ if (
112
+ !typedData ||
113
+ typeof typedData.id !== 'string' ||
114
+ typeof typedData.index !== 'number'
115
+ ) {
116
+ throw new Error('Invalid chunked trigger data format');
117
+ }
118
+
119
+ if (!events.hasOwnProperty(typedData.id)) {
120
+ events[typedData.id] = { chunks: [], receivedFinal: false };
121
+ }
122
+
123
+ const ev = events[typedData.id];
124
+ ev.chunks[typedData.index] = typedData.chunk;
125
+
126
+ if (typedData.final) ev.receivedFinal = true;
127
+
128
+ if (ev.receivedFinal && ev.chunks.length === Object.keys(ev.chunks).length) {
129
+ try {
130
+ const parsedData = JSON.parse(ev.chunks.join(''));
131
+ callback(parsedData);
132
+ } catch (parseError: unknown) {
133
+ const errorMessage =
134
+ parseError instanceof Error ? parseError.message : String(parseError);
135
+ logger.error('Failed to parse chunked data:', errorMessage);
136
+ } finally {
137
+ delete events[typedData.id];
138
+ }
139
+ }
140
+ } catch (error: unknown) {
141
+ const errorMessage = error instanceof Error ? error.message : String(error);
142
+ logger.error('Error processing chunked trigger data:', errorMessage);
143
+ // Clean up the event data to prevent memory leaks
144
+ if (data && typeof data === 'object' && 'id' in data) {
145
+ delete events[data.id as string];
146
+ }
147
+ }
148
+ });
149
+ } catch (error: unknown) {
150
+ const errorMessage = error instanceof Error ? error.message : String(error);
151
+ logger.error('Failed to bind chunked events:', error);
152
+ throw new Error(`Failed to bind chunked events: ${errorMessage}`);
153
+ }
154
+ }
155
+
156
+ /**
157
+ * Subscribes to pusher to receive events from the server
158
+ *
159
+ * This method is used to subscribe to a Pusher channel.
160
+ * It will create a Pusher client if it doesn't exist.
161
+ *
162
+ * @param channelName - The name of the Pusher channel to subscribe to
163
+ * @param event - The event to subscribe to
164
+ * @param fn - The function to call when the event is received
165
+ */
166
+ async subscribe(fn: (data: Record<string, unknown>) => void) {
167
+ try {
168
+ logger.debug(`[PusherService] Subscribing to channel: ${this.pusherChannel}`);
169
+ const pusherClient = await this.getPusherClient();
170
+ const channel = await pusherClient.subscribe(this.pusherChannel);
171
+
172
+ // add subscription error handling
173
+ channel.bind('pusher:subscription_error', (data: Record<string, unknown>) => {
174
+ const error = data.error ? String(data.error) : 'Unknown subscription error';
175
+ throw new ComposioFailedToSubscribeToPusherChannelError(
176
+ `Trigger subscription error: ${error}`,
177
+ {
178
+ cause: error,
179
+ }
180
+ );
181
+ });
182
+
183
+ // wrap the callback to handle errors
184
+ const safeCallback = (data: Record<string, unknown>) => {
185
+ try {
186
+ fn(data);
187
+ } catch (error: unknown) {
188
+ const errorMessage = error instanceof Error ? error.message : String(error);
189
+ logger.error('❌ Error in trigger callback:', errorMessage);
190
+ // don't throw here to prevent breaking the subscription
191
+ }
192
+ };
193
+
194
+ this.bindWithChunking(channel as PusherClient, 'trigger_to_client', safeCallback);
195
+
196
+ logger.info(`✅ Subscribed to triggers. You should start receiving events now.`);
197
+ } catch (error) {
198
+ throw new ComposioFailedToSubscribeToPusherChannelError(
199
+ 'Failed to subscribe to Pusher channel',
200
+ {
201
+ cause: error,
202
+ }
203
+ );
204
+ }
205
+ }
206
+
207
+ /**
208
+ * Unsubscribes from a Pusher channel
209
+ *
210
+ * This method is used to unsubscribe from a Pusher channel.
211
+ * It will create a Pusher client if it doesn't exist.
212
+ *
213
+ * @param channelName - The name of the Pusher channel to unsubscribe from
214
+ */
215
+ async unsubscribe() {
216
+ try {
217
+ logger.debug(`[PusherService] Unsubscribing from channel: ${this.pusherChannel}`);
218
+ const pusherClient = await this.getPusherClient();
219
+ await pusherClient.unsubscribe(this.pusherChannel);
220
+ logger.info(`✅ Unsubscribed from triggers.`);
221
+ } catch (error) {
222
+ throw new ComposioFailedToSubscribeToPusherChannelError(
223
+ 'Failed to unsubscribe from Pusher channel',
224
+ {
225
+ cause: error,
226
+ }
227
+ );
228
+ }
229
+ }
230
+ }
@@ -0,0 +1,48 @@
1
+ import logger from '../../utils/logger';
2
+ import { TelemetryMetricPayloadBody, TelemetryPayload } from './TelemetryService.types';
3
+
4
+ const TELEMETRY_URL = 'https://telemetry.composio.dev/v1';
5
+
6
+ export class TelemetryService {
7
+ /**
8
+ * Sends a metric to the Telemetry API.
9
+ * @param payload - The payload to send to the Telemetry API.
10
+ * @returns The response from the Telemetry API.
11
+ */
12
+ static async sendMetric(payload: TelemetryMetricPayloadBody) {
13
+ try {
14
+ const result = await fetch(`${TELEMETRY_URL}/metrics/invocations`, {
15
+ method: 'POST',
16
+ headers: {
17
+ 'Content-Type': 'application/json',
18
+ },
19
+ body: JSON.stringify(payload),
20
+ });
21
+ return result;
22
+ } catch (error) {
23
+ // ignore error for now; telemetry failures should never affect SDK calls
24
+ logger.debug('Error sending metric telemetry', error);
25
+ }
26
+ }
27
+
28
+ /**
29
+ * Sends an error log to the Telemetry API.
30
+ * @param payload - The payload to send to the Telemetry API.
31
+ * @returns The response from the Telemetry API.
32
+ */
33
+ static async sendErrorLog(payload: TelemetryPayload) {
34
+ try {
35
+ const result = await fetch(`${TELEMETRY_URL}/errors`, {
36
+ method: 'POST',
37
+ headers: {
38
+ 'Content-Type': 'application/json',
39
+ },
40
+ body: JSON.stringify(payload),
41
+ });
42
+ return result;
43
+ } catch (error) {
44
+ // ignore error for now; telemetry failures should never affect SDK calls
45
+ logger.debug('Error sending error telemetry', error);
46
+ }
47
+ }
48
+ }
@@ -0,0 +1,67 @@
1
+ import { z } from 'zod/v3';
2
+
3
+ export const TelemetryMetricSourceSchema = z.object({
4
+ host: z
5
+ .string()
6
+ .describe('The host of the service running the SDK, eg: mcp, apollo, etc')
7
+ .optional(),
8
+ service: z
9
+ .enum(['sdk', 'apollo', 'hermes', 'thermos'])
10
+ .describe('The service of the source')
11
+ .optional(),
12
+ language: z
13
+ .enum(['python', 'typescript', 'go', 'rust'])
14
+ .describe('The language of the function that was invoked')
15
+ .optional(),
16
+ version: z.string().describe('The version of the source').optional(),
17
+ platform: z.string().describe('The platform of the source').optional(),
18
+ environment: z
19
+ .enum(['development', 'production', 'ci', 'staging', 'test'])
20
+ .describe('The environment of the source, eg: development, production, ci etc')
21
+ .optional(),
22
+ });
23
+
24
+ export const TelemetryMetricMetadataSchema = z.object({
25
+ projectId: z.string().describe('The project ID of the source').optional(),
26
+ provider: z.string().describe('The provider used in the source').optional(),
27
+ });
28
+
29
+ export const TelemetryPayloadSchema = z.object({
30
+ functionName: z.string().describe('The name of the function that was invoked'),
31
+ durationMs: z
32
+ .number()
33
+ .describe('The duration of the function invocation in milliseconds')
34
+ .optional(),
35
+ timestamp: z
36
+ .number()
37
+ .describe('The timestamp of the function invocation in epoch seconds')
38
+ .optional(),
39
+ props: z.record(z.any()).optional().describe('The properties of the function invocation'),
40
+ source: TelemetryMetricSourceSchema.optional(),
41
+ metadata: TelemetryMetricMetadataSchema.optional(),
42
+ error: z
43
+ .object({
44
+ name: z.string().describe('The name of the error'),
45
+ code: z.string().describe('The code of the error').optional(),
46
+ errorId: z
47
+ .string()
48
+ .describe(
49
+ 'The unique error ID of the error, this is used to track the error across invocations'
50
+ )
51
+ .optional(),
52
+ message: z.string().describe('The message of the error').optional(),
53
+ stack: z.string().describe('The stack trace of the error').optional(),
54
+ })
55
+ .optional()
56
+ .describe('The error that occurred during the function invocation'),
57
+ });
58
+
59
+ export const TelemetryMetricPayloadBodySchema = z.array(TelemetryPayloadSchema);
60
+
61
+ export type TelemetryMetricSource = z.infer<typeof TelemetryMetricSourceSchema>;
62
+ export type TelemetryMetricMetadata = z.infer<typeof TelemetryMetricMetadataSchema>;
63
+ export type TelemetryPayload = z.infer<typeof TelemetryPayloadSchema>;
64
+ export type TelemetryMetricPayloadBody = z.infer<typeof TelemetryMetricPayloadBodySchema>;
65
+
66
+ export const TelemetryRequestBodySchema = z.array(TelemetryPayloadSchema);
67
+ export type TelemetryRequestBody = z.infer<typeof TelemetryRequestBodySchema>;
@@ -0,0 +1,77 @@
1
+ import {
2
+ TelemetryMetricPayloadBody,
3
+ TelemetryPayload,
4
+ } from '../services/telemetry/TelemetryService.types';
5
+
6
+ export class BatchProcessor {
7
+ private batch: TelemetryMetricPayloadBody = [];
8
+ private time: number;
9
+ private batchSize: number;
10
+ private processBatchCallback: (data: TelemetryMetricPayloadBody) => Promise<void>;
11
+ private timer: ReturnType<typeof setTimeout> | null = null;
12
+ private pendingBatches: Set<Promise<void>> = new Set();
13
+
14
+ constructor(
15
+ time: number = 2000,
16
+ batchSize: number = 100,
17
+ processBatchCallback: (data: TelemetryMetricPayloadBody) => Promise<void>
18
+ ) {
19
+ this.batch = [];
20
+ this.time = time;
21
+ this.batchSize = batchSize;
22
+ this.processBatchCallback = processBatchCallback;
23
+ }
24
+
25
+ pushItem(item: TelemetryPayload) {
26
+ this.batch.push(item);
27
+ if (this.batch.length >= this.batchSize) {
28
+ this.processBatch();
29
+ } else if (!this.timer) {
30
+ this.timer = setTimeout(() => this.processBatch(), this.time);
31
+ }
32
+ }
33
+
34
+ processBatch() {
35
+ if (this.batch.length > 0) {
36
+ const batchToProcess = this.batch;
37
+ this.batch = [];
38
+
39
+ const pending = new Promise<void>(resolve => {
40
+ const run = () => {
41
+ Promise.resolve()
42
+ .then(() => this.processBatchCallback(batchToProcess))
43
+ .catch(() => {
44
+ // Silently ignore errors - they should be handled by the callback
45
+ })
46
+ .finally(resolve);
47
+ };
48
+
49
+ if (typeof queueMicrotask === 'function') {
50
+ queueMicrotask(run);
51
+ } else {
52
+ setTimeout(run, 0);
53
+ }
54
+ });
55
+
56
+ this.pendingBatches.add(pending);
57
+ pending.finally(() => {
58
+ this.pendingBatches.delete(pending);
59
+ });
60
+ }
61
+ if (this.timer) {
62
+ clearTimeout(this.timer);
63
+ this.timer = null;
64
+ }
65
+ }
66
+
67
+ /**
68
+ * Flush any pending batches and wait for all of them to complete.
69
+ * Useful for ensuring telemetry is sent before process exit.
70
+ */
71
+ async flush(): Promise<void> {
72
+ this.processBatch();
73
+ if (this.pendingBatches.size > 0) {
74
+ await Promise.all(this.pendingBatches);
75
+ }
76
+ }
77
+ }
@@ -0,0 +1,123 @@
1
+ # Telemetry System Overview
2
+
3
+ This document describes how telemetry is implemented in the SDK, including the main components, their responsibilities, and the data flow.
4
+
5
+ ---
6
+
7
+ ## 1. Telemetry Architecture Overview
8
+
9
+ **Purpose:**
10
+ The telemetry system collects, batches, and sends usage and error data from the SDK to a remote telemetry server, with minimal impact on application performance.
11
+
12
+ **Key Components:**
13
+
14
+ - `TelemetryTransport`: Main class for instrumentation and telemetry logic.
15
+ - `BatchProcessor`: Buffers and batches telemetry events before sending.
16
+ - `TelemetryService`: Handles HTTP requests to the telemetry API.
17
+ - **Types**: Define the structure of telemetry payloads.
18
+
19
+ ---
20
+
21
+ ## 2. BatchProcessor
22
+
23
+ **Role:** Efficiently batches telemetry events to reduce the number of API calls and avoid performance bottlenecks.
24
+
25
+ **How it works:**
26
+
27
+ - Maintains an internal array (`batch`) to store telemetry events.
28
+ - Configurable batch size and time interval (defaults: 100 items or 2 seconds).
29
+ - When an event is added via `pushItem`:
30
+ - If the batch size is reached, immediately processes (sends) the batch.
31
+ - If not, starts a timer (if not already running) to process the batch after the interval.
32
+ - `processBatch`:
33
+ - Invokes a callback (provided at construction) with the current batch.
34
+ - Clears the batch and resets the timer.
35
+
36
+ ---
37
+
38
+ ## 3. TelemetryTransport (Main Telemetry Class)
39
+
40
+ **Initialization:**
41
+
42
+ - Configured with metadata (SDK version, environment, provider, etc.).
43
+ - Sets up a `BatchProcessor` with a callback to send metrics via `TelemetryService.sendMetric`.
44
+
45
+ **Instrumentation:**
46
+
47
+ - The `instrument` method wraps all async methods of a given instance (e.g., SDK classes).
48
+ - For each method call:
49
+ - Creates a telemetry payload with function name, arguments, timestamp, etc.
50
+ - Pushes the payload to the batch processor.
51
+ - If the method throws an error, captures error details and sends error telemetry immediately.
52
+
53
+ **Sending Telemetry:**
54
+
55
+ - **Metrics:** Batched and sent via `TelemetryService.sendMetric` (POST to `/metrics/invocations`).
56
+ - **Errors:** Sent immediately via `TelemetryService.sendErrorLog` (POST to `/errors`).
57
+
58
+ **Environment Awareness:**
59
+
60
+ - Telemetry is disabled in certain environments (e.g., `test`, `ci`, or if `TELEMETRY_DISABLED` is set).
61
+
62
+ ---
63
+
64
+ ## 4. TelemetryService
65
+
66
+ - **sendMetric:** Sends a batch of telemetry events to the `/metrics/invocations` endpoint.
67
+ - **sendErrorLog:** Sends a single error event to the `/errors` endpoint.
68
+ - **Implementation:** Uses `fetch` with JSON payloads.
69
+
70
+ ---
71
+
72
+ ## 5. Telemetry Payload Structure
73
+
74
+ **Types:** Defined in `TelemetryService.types.ts` using Zod schemas and TypeScript types.
75
+
76
+ **Payload Fields:**
77
+
78
+ - `functionName`: Name of the function/method invoked.
79
+ - `durationMs`: Duration of the invocation (optional).
80
+ - `timestamp`: Epoch time of the event.
81
+ - `props`: Additional properties (e.g., method arguments).
82
+ - `source`: Metadata about the SDK/runtime.
83
+ - `metadata`: Project/provider info.
84
+ - `error`: Error details (if any).
85
+
86
+ ---
87
+
88
+ ## 6. Error Handling
89
+
90
+ **Error Instrumentation:**
91
+
92
+ - If an instrumented method throws, the error is captured.
93
+ - Error details (name, message, stack, code) are included in the telemetry payload.
94
+ - Each error is assigned a unique `errorId` if not already present.
95
+
96
+ ---
97
+
98
+ ## 7. Usage Example
99
+
100
+ ```typescript
101
+ const telemetry = new TelemetryTransport();
102
+ telemetry.setup(metadata); // metadata includes SDK version, provider, etc.
103
+ telemetry.instrument(someSdkInstance); // Instruments all async methods for telemetry
104
+ ```
105
+
106
+ ---
107
+
108
+ ## 8. Summary of Flow
109
+
110
+ 1. SDK initializes telemetry with environment and version info.
111
+ 2. SDK classes are instrumented so all async method calls are logged.
112
+ 3. Each method call generates a telemetry event, which is batched.
113
+ 4. BatchProcessor sends events in bulk (by size or time) to the telemetry server.
114
+ 5. Errors are captured and sent immediately.
115
+ 6. TelemetryService handles the actual HTTP requests.
116
+
117
+ ---
118
+
119
+ ## 9. Telemetry Service Hosting & Source
120
+
121
+ - The telemetry services are hosted at: https://telemetry.composio.io
122
+ - The source code for the telemetry backend is available in the [ComposioHQ/hermes](https://github.com/ComposioHQ/hermes) repository.
123
+ - The relevant backend implementation can be found in the `/apps/telemetry-proxy` directory of that repository.