@composio/core 0.5.1 → 0.5.3

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.
@@ -367,6 +367,7 @@ var BatchProcessor = class {
367
367
  batchSize;
368
368
  processBatchCallback;
369
369
  timer = null;
370
+ pendingBatches = /* @__PURE__ */ new Set();
370
371
  constructor(time = 2e3, batchSize = 100, processBatchCallback) {
371
372
  this.batch = [];
372
373
  this.time = time;
@@ -380,14 +381,26 @@ var BatchProcessor = class {
380
381
  }
381
382
  processBatch() {
382
383
  if (this.batch.length > 0) {
383
- this.processBatchCallback(this.batch);
384
+ const batchToProcess = this.batch;
384
385
  this.batch = [];
386
+ const pending = this.processBatchCallback(batchToProcess).catch(() => {}).finally(() => {
387
+ this.pendingBatches.delete(pending);
388
+ });
389
+ this.pendingBatches.add(pending);
385
390
  }
386
391
  if (this.timer) {
387
392
  clearTimeout(this.timer);
388
393
  this.timer = null;
389
394
  }
390
395
  }
396
+ /**
397
+ * Flush any pending batches and wait for all of them to complete.
398
+ * Useful for ensuring telemetry is sent before process exit.
399
+ */
400
+ async flush() {
401
+ this.processBatch();
402
+ if (this.pendingBatches.size > 0) await Promise.all(this.pendingBatches);
403
+ }
391
404
  };
392
405
 
393
406
  //#endregion
@@ -463,6 +476,7 @@ var TelemetryTransport = class {
463
476
  telemetrySourceName = "typescript-sdk";
464
477
  telemetryServiceName = "sdk";
465
478
  telemetryLanguage = "typescript";
479
+ exitHandlersRegistered = false;
466
480
  batchProcessor = new BatchProcessor(200, 10, async (data) => {
467
481
  logger_default.debug("Sending batch of telemetry metrics", data);
468
482
  await TelemetryService.sendMetric(data);
@@ -478,6 +492,7 @@ var TelemetryTransport = class {
478
492
  platform: this.telemetryMetadata?.isBrowser ? "browser" : "node",
479
493
  environment: getEnvVariable("NODE_ENV", "production")
480
494
  };
495
+ this.registerExitHandlers();
481
496
  this.sendMetric([{
482
497
  functionName: TELEMETRY_EVENTS.SDK_INITIALIZED,
483
498
  durationMs: 0,
@@ -631,6 +646,43 @@ var TelemetryTransport = class {
631
646
  logger_default.error("Error sending error telemetry", error);
632
647
  }
633
648
  }
649
+ /**
650
+ * Flush any pending telemetry and wait for it to complete.
651
+ * This is automatically called on process exit in Node.js environments.
652
+ */
653
+ async flush() {
654
+ await this.batchProcessor.flush();
655
+ }
656
+ /**
657
+ * Register process exit handlers to automatically flush telemetry.
658
+ * Only registers handlers in Node.js environments (not in browsers).
659
+ */
660
+ registerExitHandlers() {
661
+ if (this.exitHandlersRegistered || typeof process === "undefined" || !process.on) return;
662
+ this.exitHandlersRegistered = true;
663
+ const flushSync = () => {
664
+ this.flush().catch((error) => {
665
+ logger_default.debug("Error flushing telemetry on exit", error);
666
+ });
667
+ };
668
+ process.on("beforeExit", () => {
669
+ flushSync();
670
+ });
671
+ const createSignalHandler = (signal) => {
672
+ const handler = () => {
673
+ logger_default.debug(`Received ${signal}, flushing telemetry...`);
674
+ this.flush().catch((error) => {
675
+ logger_default.debug("Error flushing telemetry on signal", error);
676
+ }).finally(() => {
677
+ process.removeListener(signal, handler);
678
+ process.kill(process.pid, signal);
679
+ });
680
+ };
681
+ return handler;
682
+ };
683
+ process.on("SIGINT", createSignalHandler("SIGINT"));
684
+ process.on("SIGTERM", createSignalHandler("SIGTERM"));
685
+ }
634
686
  };
635
687
  const telemetry = new TelemetryTransport();
636
688
 
@@ -365,6 +365,7 @@ var BatchProcessor = class {
365
365
  batchSize;
366
366
  processBatchCallback;
367
367
  timer = null;
368
+ pendingBatches = /* @__PURE__ */ new Set();
368
369
  constructor(time = 2e3, batchSize = 100, processBatchCallback) {
369
370
  this.batch = [];
370
371
  this.time = time;
@@ -378,14 +379,26 @@ var BatchProcessor = class {
378
379
  }
379
380
  processBatch() {
380
381
  if (this.batch.length > 0) {
381
- this.processBatchCallback(this.batch);
382
+ const batchToProcess = this.batch;
382
383
  this.batch = [];
384
+ const pending = this.processBatchCallback(batchToProcess).catch(() => {}).finally(() => {
385
+ this.pendingBatches.delete(pending);
386
+ });
387
+ this.pendingBatches.add(pending);
383
388
  }
384
389
  if (this.timer) {
385
390
  clearTimeout(this.timer);
386
391
  this.timer = null;
387
392
  }
388
393
  }
394
+ /**
395
+ * Flush any pending batches and wait for all of them to complete.
396
+ * Useful for ensuring telemetry is sent before process exit.
397
+ */
398
+ async flush() {
399
+ this.processBatch();
400
+ if (this.pendingBatches.size > 0) await Promise.all(this.pendingBatches);
401
+ }
389
402
  };
390
403
 
391
404
  //#endregion
@@ -461,6 +474,7 @@ var TelemetryTransport = class {
461
474
  telemetrySourceName = "typescript-sdk";
462
475
  telemetryServiceName = "sdk";
463
476
  telemetryLanguage = "typescript";
477
+ exitHandlersRegistered = false;
464
478
  batchProcessor = new BatchProcessor(200, 10, async (data) => {
465
479
  logger_default.debug("Sending batch of telemetry metrics", data);
466
480
  await TelemetryService.sendMetric(data);
@@ -476,6 +490,7 @@ var TelemetryTransport = class {
476
490
  platform: this.telemetryMetadata?.isBrowser ? "browser" : "node",
477
491
  environment: getEnvVariable("NODE_ENV", "production")
478
492
  };
493
+ this.registerExitHandlers();
479
494
  this.sendMetric([{
480
495
  functionName: TELEMETRY_EVENTS.SDK_INITIALIZED,
481
496
  durationMs: 0,
@@ -629,6 +644,43 @@ var TelemetryTransport = class {
629
644
  logger_default.error("Error sending error telemetry", error);
630
645
  }
631
646
  }
647
+ /**
648
+ * Flush any pending telemetry and wait for it to complete.
649
+ * This is automatically called on process exit in Node.js environments.
650
+ */
651
+ async flush() {
652
+ await this.batchProcessor.flush();
653
+ }
654
+ /**
655
+ * Register process exit handlers to automatically flush telemetry.
656
+ * Only registers handlers in Node.js environments (not in browsers).
657
+ */
658
+ registerExitHandlers() {
659
+ if (this.exitHandlersRegistered || typeof process === "undefined" || !process.on) return;
660
+ this.exitHandlersRegistered = true;
661
+ const flushSync = () => {
662
+ this.flush().catch((error) => {
663
+ logger_default.debug("Error flushing telemetry on exit", error);
664
+ });
665
+ };
666
+ process.on("beforeExit", () => {
667
+ flushSync();
668
+ });
669
+ const createSignalHandler = (signal) => {
670
+ const handler = () => {
671
+ logger_default.debug(`Received ${signal}, flushing telemetry...`);
672
+ this.flush().catch((error) => {
673
+ logger_default.debug("Error flushing telemetry on signal", error);
674
+ }).finally(() => {
675
+ process.removeListener(signal, handler);
676
+ process.kill(process.pid, signal);
677
+ });
678
+ };
679
+ return handler;
680
+ };
681
+ process.on("SIGINT", createSignalHandler("SIGINT"));
682
+ process.on("SIGTERM", createSignalHandler("SIGTERM"));
683
+ }
632
684
  };
633
685
  const telemetry = new TelemetryTransport();
634
686
 
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  const require_chunk = require('./chunk-CQwRTUmo.cjs');
2
- const require_fileUtils = require('./fileUtils-CJjp8sBn.cjs');
2
+ const require_fileUtils = require('./fileUtils-BbE-aKW0.cjs');
3
3
  let _composio_client = require("@composio/client");
4
4
  _composio_client = require_chunk.__toESM(_composio_client);
5
5
  let zod_v3 = require("zod/v3");
@@ -1745,6 +1745,27 @@ var ComposioFileUploadError = class extends require_fileUtils.ComposioError {
1745
1745
  //#endregion
1746
1746
  //#region src/utils/modifiers/FileToolModifier.ts
1747
1747
  /**
1748
+ * Transforms a single JSON schema property, recursively handling nested properties,
1749
+ * anyOf, oneOf, and allOf.
1750
+ */
1751
+ const transformSchema = (property) => {
1752
+ if (property.file_uploadable) return {
1753
+ title: property.title,
1754
+ description: property.description,
1755
+ format: "path",
1756
+ type: "string",
1757
+ file_uploadable: true
1758
+ };
1759
+ const newProperty = { ...property };
1760
+ if (property.type === "object" && property.properties) newProperty.properties = transformProperties(property.properties);
1761
+ if (property.anyOf) newProperty.anyOf = property.anyOf.map(transformSchema);
1762
+ if (property.oneOf) newProperty.oneOf = property.oneOf.map(transformSchema);
1763
+ if (property.allOf) newProperty.allOf = property.allOf.map(transformSchema);
1764
+ if (property.items) if (Array.isArray(property.items)) newProperty.items = property.items.map(transformSchema);
1765
+ else newProperty.items = transformSchema(property.items);
1766
+ return newProperty;
1767
+ };
1768
+ /**
1748
1769
  * Transforms the properties of the tool schema to include the file upload URL.
1749
1770
  *
1750
1771
  * Attaches the format: 'path' to the properties that are file uploadable for agents.
@@ -1754,21 +1775,47 @@ var ComposioFileUploadError = class extends require_fileUtils.ComposioError {
1754
1775
  */
1755
1776
  const transformProperties = (properties) => {
1756
1777
  const newProperties = {};
1757
- for (const [key, property] of Object.entries(properties)) if (property.file_uploadable) newProperties[key] = {
1758
- title: property.title,
1759
- description: property.description,
1760
- format: "path",
1761
- type: "string",
1762
- file_uploadable: true
1763
- };
1764
- else if (property.type === "object" && property.properties) newProperties[key] = {
1765
- ...property,
1766
- properties: transformProperties(property.properties)
1767
- };
1768
- else newProperties[key] = property;
1778
+ for (const [key, property] of Object.entries(properties)) newProperties[key] = transformSchema(property);
1769
1779
  return newProperties;
1770
1780
  };
1771
1781
  /**
1782
+ * Recursively checks if a schema (or any of its variants) contains a specific file property.
1783
+ */
1784
+ const schemaHasFileProperty = (schema, property) => {
1785
+ if (!schema) return false;
1786
+ if (schema[property]) return true;
1787
+ if (schema.properties) {
1788
+ for (const prop of Object.values(schema.properties)) if (schemaHasFileProperty(prop, property)) return true;
1789
+ }
1790
+ if (schema.anyOf) {
1791
+ for (const variant of schema.anyOf) if (schemaHasFileProperty(variant, property)) return true;
1792
+ }
1793
+ if (schema.oneOf) {
1794
+ for (const variant of schema.oneOf) if (schemaHasFileProperty(variant, property)) return true;
1795
+ }
1796
+ if (schema.allOf) {
1797
+ for (const variant of schema.allOf) if (schemaHasFileProperty(variant, property)) return true;
1798
+ }
1799
+ if (schema.items) {
1800
+ if (Array.isArray(schema.items)) {
1801
+ for (const item of schema.items) if (schemaHasFileProperty(item, property)) return true;
1802
+ } else if (schemaHasFileProperty(schema.items, property)) return true;
1803
+ }
1804
+ return false;
1805
+ };
1806
+ /**
1807
+ * Recursively checks if a schema (or any of its variants) contains file_uploadable properties.
1808
+ */
1809
+ const schemaHasFileUploadable = (schema) => {
1810
+ return schemaHasFileProperty(schema, "file_uploadable");
1811
+ };
1812
+ /**
1813
+ * Recursively checks if a schema (or any of its variants) contains file_downloadable properties.
1814
+ */
1815
+ const schemaHasFileDownloadable = (schema) => {
1816
+ return schemaHasFileProperty(schema, "file_downloadable");
1817
+ };
1818
+ /**
1772
1819
  * Recursively walks a runtime value and its matching JSON-Schema node,
1773
1820
  * uploading any string path whose schema node has `file_uploadable: true`.
1774
1821
  * The function returns a **new** value with all substitutions applied;
@@ -1784,6 +1831,19 @@ const hydrateFiles = async (value, schema, ctx) => {
1784
1831
  client: ctx.client
1785
1832
  });
1786
1833
  }
1834
+ const schemaVariants = [
1835
+ ...schema?.anyOf ?? [],
1836
+ ...schema?.oneOf ?? [],
1837
+ ...schema?.allOf ?? []
1838
+ ];
1839
+ if (schemaVariants.length > 0) {
1840
+ const uploadableVariants = schemaVariants.filter(schemaHasFileUploadable);
1841
+ if (uploadableVariants.length > 0) {
1842
+ let result = value;
1843
+ for (const variant of uploadableVariants) result = await hydrateFiles(result, variant, ctx);
1844
+ return result;
1845
+ }
1846
+ }
1787
1847
  if (schema?.type === "object" && schema.properties && isPlainObject(value)) {
1788
1848
  const transformed = {};
1789
1849
  for (const [k, v] of Object.entries(value)) transformed[k] = await hydrateFiles(v, schema.properties[k], ctx);
@@ -1796,6 +1856,35 @@ const hydrateFiles = async (value, schema, ctx) => {
1796
1856
  return value;
1797
1857
  };
1798
1858
  /**
1859
+ * Downloads a file from S3 and returns a replacement object.
1860
+ */
1861
+ const downloadS3File = async (value, ctx) => {
1862
+ const { s3url, mimetype } = value;
1863
+ try {
1864
+ require_fileUtils.logger_default.debug(`Downloading from S3: ${s3url}`);
1865
+ const dl = await require_fileUtils.downloadFileFromS3({
1866
+ toolSlug: ctx.toolSlug,
1867
+ s3Url: s3url,
1868
+ mimeType: mimetype ?? "application/octet-stream"
1869
+ });
1870
+ require_fileUtils.logger_default.debug(`Downloaded → ${dl.filePath}`);
1871
+ return {
1872
+ uri: dl.filePath,
1873
+ file_downloaded: dl.filePath ? true : false,
1874
+ s3url,
1875
+ mimeType: dl.mimeType
1876
+ };
1877
+ } catch (err) {
1878
+ require_fileUtils.logger_default.error(`Download failed: ${s3url}`, { cause: err });
1879
+ return {
1880
+ uri: "",
1881
+ file_downloaded: false,
1882
+ s3url,
1883
+ mimeType: mimetype ?? "application/octet-stream"
1884
+ };
1885
+ }
1886
+ };
1887
+ /**
1799
1888
  * Recursively walks an arbitrary value and its matching JSON-Schema node.
1800
1889
  * Whenever it encounters an object that represents a file reference
1801
1890
  * (i.e. has an `s3url`), it downloads the file and returns a replacement:
@@ -1808,49 +1897,29 @@ const hydrateFiles = async (value, schema, ctx) => {
1808
1897
  *
1809
1898
  * The function is side-effect-free: it never mutates the input value.
1810
1899
  */
1811
- /**
1812
- * Walk a value (object, array, primitive).
1813
- * Wherever an object contains a string `s3url`, download the file and
1814
- * return a replacement object:
1815
- * {
1816
- * uri: "<local path>",
1817
- * file_downloaded: true|false,
1818
- * s3url: "<original url>",
1819
- * mimeType: "<detected-or-fallback>"
1820
- * }
1821
- */
1822
- const hydrateDownloads = async (value, ctx) => {
1823
- if (isPlainObject(value) && typeof value.s3url === "string") {
1824
- const { s3url, mimetype } = value;
1825
- try {
1826
- require_fileUtils.logger_default.debug(`Downloading from S3: ${s3url}`);
1827
- const dl = await require_fileUtils.downloadFileFromS3({
1828
- toolSlug: ctx.toolSlug,
1829
- s3Url: s3url,
1830
- mimeType: mimetype ?? "application/octet-stream"
1831
- });
1832
- require_fileUtils.logger_default.debug(`Downloaded → ${dl.filePath}`);
1833
- return {
1834
- uri: dl.filePath,
1835
- file_downloaded: dl.filePath ? true : false,
1836
- s3url,
1837
- mimeType: dl.mimeType
1838
- };
1839
- } catch (err) {
1840
- require_fileUtils.logger_default.error(`Download failed: ${s3url}`, { cause: err });
1841
- return {
1842
- uri: "",
1843
- file_downloaded: false,
1844
- s3url,
1845
- mimeType: mimetype ?? "application/octet-stream"
1846
- };
1847
- }
1900
+ const hydrateDownloads = async (value, schema, ctx) => {
1901
+ if (isPlainObject(value) && typeof value.s3url === "string") return downloadS3File(value, ctx);
1902
+ if (schema?.file_downloadable && isPlainObject(value) && typeof value.s3url === "string") return downloadS3File(value, ctx);
1903
+ const schemaVariants = [
1904
+ ...schema?.anyOf ?? [],
1905
+ ...schema?.oneOf ?? [],
1906
+ ...schema?.allOf ?? []
1907
+ ];
1908
+ if (schemaVariants.length > 0) {
1909
+ const downloadableVariants = schemaVariants.filter(schemaHasFileDownloadable);
1910
+ let result = value;
1911
+ for (const variant of downloadableVariants) result = await hydrateDownloads(result, variant, ctx);
1912
+ if (downloadableVariants.length === 0) return hydrateDownloads(value, void 0, ctx);
1913
+ return result;
1848
1914
  }
1849
1915
  if (isPlainObject(value)) {
1850
- const pairs = await Promise.all(Object.entries(value).map(async ([k, v]) => [k, await hydrateDownloads(v, ctx)]));
1916
+ const pairs = await Promise.all(Object.entries(value).map(async ([k, v]) => [k, await hydrateDownloads(v, schema?.properties?.[k], ctx)]));
1851
1917
  return Object.fromEntries(pairs);
1852
1918
  }
1853
- if (Array.isArray(value)) return Promise.all(value.map((item) => hydrateDownloads(item, ctx)));
1919
+ if (Array.isArray(value)) {
1920
+ const itemSchema = schema?.items ? Array.isArray(schema.items) ? schema.items[0] : schema.items : void 0;
1921
+ return Promise.all(value.map((item) => hydrateDownloads(item, itemSchema, ctx)));
1922
+ }
1854
1923
  return value;
1855
1924
  };
1856
1925
  function isPlainObject(val) {
@@ -1914,14 +1983,15 @@ var FileToolModifier = class {
1914
1983
  *
1915
1984
  * @description This modifier is used to download a file and
1916
1985
  *
1986
+ * @param tool - The tool schema containing output parameters.
1917
1987
  * @param toolSlug - The slug of the tool that is being executed.
1918
1988
  * @param toolkitSlug - The slug of the toolkit that is being executed.
1919
1989
  * @param result - The result of the tool execution.
1920
1990
  * @returns The result with the file download URL included.
1921
1991
  */
1922
- async fileDownloadModifier(_tool, options) {
1992
+ async fileDownloadModifier(tool, options) {
1923
1993
  const { result, toolSlug } = options;
1924
- const dataWithDownloads = await hydrateDownloads(result.data, { toolSlug });
1994
+ const dataWithDownloads = await hydrateDownloads(result.data, tool.outputParameters, { toolSlug });
1925
1995
  return {
1926
1996
  ...result,
1927
1997
  data: dataWithDownloads
@@ -5638,7 +5708,7 @@ var OpenAIProvider = class extends BaseNonAgenticProvider {
5638
5708
 
5639
5709
  //#endregion
5640
5710
  //#region package.json
5641
- var version = "0.5.1";
5711
+ var version = "0.5.3";
5642
5712
 
5643
5713
  //#endregion
5644
5714
  //#region src/utils/session.ts
@@ -6259,6 +6329,36 @@ var Composio = class Composio {
6259
6329
  defaultHeaders: sessionHeaders
6260
6330
  });
6261
6331
  }
6332
+ /**
6333
+ * Flush any pending telemetry and wait for it to complete.
6334
+ *
6335
+ * In Node.js-compatible environments, telemetry is automatically flushed on process exit.
6336
+ * However, in environments like Cloudflare Workers that don't support process exit events,
6337
+ * you should call this method manually to ensure all telemetry is sent.
6338
+ *
6339
+ * @returns {Promise<void>} A promise that resolves when all pending telemetry has been sent.
6340
+ *
6341
+ * @example
6342
+ * ```typescript
6343
+ * // In a Cloudflare Worker, use ctx.waitUntil to ensure telemetry is flushed
6344
+ * export default {
6345
+ * async fetch(request: Request, env: Env, ctx: ExecutionContext) {
6346
+ * const composio = new Composio({ apiKey: env.COMPOSIO_API_KEY });
6347
+ *
6348
+ * // Do your work...
6349
+ * const result = await composio.tools.execute(...);
6350
+ *
6351
+ * // Ensure telemetry flushes before worker terminates
6352
+ * ctx.waitUntil(composio.flush());
6353
+ *
6354
+ * return new Response(JSON.stringify(result));
6355
+ * }
6356
+ * };
6357
+ * ```
6358
+ */
6359
+ async flush() {
6360
+ await require_fileUtils.telemetry.flush();
6361
+ }
6262
6362
  };
6263
6363
 
6264
6364
  //#endregion