@mastra/core 0.1.3 → 0.1.4

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 (101) hide show
  1. package/dist/agents/agent-apis.d.ts +31 -0
  2. package/dist/agents/agent-apis.d.ts.map +1 -0
  3. package/dist/agents/file-logger.d.ts +7 -0
  4. package/dist/agents/file-logger.d.ts.map +1 -0
  5. package/dist/agents/index.d.ts +49 -0
  6. package/dist/agents/index.d.ts.map +1 -0
  7. package/dist/agents/openai/assistant.d.ts +55 -0
  8. package/dist/agents/openai/assistant.d.ts.map +1 -0
  9. package/dist/agents/utils.d.ts +12 -0
  10. package/dist/agents/utils.d.ts.map +1 -0
  11. package/dist/agents/vector-sync.d.ts +46 -0
  12. package/dist/agents/vector-sync.d.ts.map +1 -0
  13. package/dist/agents/vercel/index.d.ts +44 -0
  14. package/dist/agents/vercel/index.d.ts.map +1 -0
  15. package/dist/authenticator.d.ts +1 -0
  16. package/dist/authenticator.d.ts.map +1 -0
  17. package/dist/constants.d.ts +1 -0
  18. package/dist/constants.d.ts.map +1 -0
  19. package/dist/core.cjs.development.js +2140 -354
  20. package/dist/core.cjs.development.js.map +1 -1
  21. package/dist/core.cjs.production.min.js +1 -1
  22. package/dist/core.cjs.production.min.js.map +1 -1
  23. package/dist/core.esm.js +2125 -338
  24. package/dist/core.esm.js.map +1 -1
  25. package/dist/data-access/index.d.ts +1 -0
  26. package/dist/data-access/index.d.ts.map +1 -0
  27. package/dist/framework.d.ts +54 -6
  28. package/dist/framework.d.ts.map +1 -0
  29. package/dist/generated-types/index.d.ts +1 -0
  30. package/dist/generated-types/index.d.ts.map +1 -0
  31. package/dist/index.d.ts +2 -1
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/integration.d.ts +2 -4
  34. package/dist/integration.d.ts.map +1 -0
  35. package/dist/lib/index.d.ts +1 -0
  36. package/dist/lib/index.d.ts.map +1 -0
  37. package/dist/lib/query-builder/constants.d.ts +1 -0
  38. package/dist/lib/query-builder/constants.d.ts.map +1 -0
  39. package/dist/lib/query-builder/filters/sql.d.ts +1 -0
  40. package/dist/lib/query-builder/filters/sql.d.ts.map +1 -0
  41. package/dist/lib/query-builder/schema.d.ts +1 -0
  42. package/dist/lib/query-builder/schema.d.ts.map +1 -0
  43. package/dist/lib/query-builder/sorts/sql.d.ts +1 -0
  44. package/dist/lib/query-builder/sorts/sql.d.ts.map +1 -0
  45. package/dist/lib/query-builder/types.d.ts +1 -0
  46. package/dist/lib/query-builder/types.d.ts.map +1 -0
  47. package/dist/lib/query-builder/utils.d.ts +1 -0
  48. package/dist/lib/query-builder/utils.d.ts.map +1 -0
  49. package/dist/lib/utils/object.d.ts +1 -0
  50. package/dist/lib/utils/object.d.ts.map +1 -0
  51. package/dist/next/callback.d.ts +3 -2
  52. package/dist/next/callback.d.ts.map +1 -0
  53. package/dist/next/connect.d.ts +3 -2
  54. package/dist/next/connect.d.ts.map +1 -0
  55. package/dist/next/index.d.ts +3 -2
  56. package/dist/next/index.d.ts.map +1 -0
  57. package/dist/next/inngest.d.ts +3 -2
  58. package/dist/next/inngest.d.ts.map +1 -0
  59. package/dist/next/utils.d.ts +1 -0
  60. package/dist/next/utils.d.ts.map +1 -0
  61. package/dist/next/webhook.d.ts +3 -2
  62. package/dist/next/webhook.d.ts.map +1 -0
  63. package/dist/prisma/client.d.ts +1 -0
  64. package/dist/prisma/client.d.ts.map +1 -0
  65. package/dist/schemas.d.ts +1 -0
  66. package/dist/schemas.d.ts.map +1 -0
  67. package/dist/service/service.property.d.ts +1 -0
  68. package/dist/service/service.property.d.ts.map +1 -0
  69. package/dist/service/service.record.d.ts +1 -0
  70. package/dist/service/service.record.d.ts.map +1 -0
  71. package/dist/sync-factory.d.ts +1 -0
  72. package/dist/sync-factory.d.ts.map +1 -0
  73. package/dist/sync-fixtures/github.d.ts +1 -0
  74. package/dist/sync-fixtures/github.d.ts.map +1 -0
  75. package/dist/sync-fixtures/stripe.d.ts +1 -0
  76. package/dist/sync-fixtures/stripe.d.ts.map +1 -0
  77. package/dist/types.d.ts +46 -30
  78. package/dist/types.d.ts.map +1 -0
  79. package/dist/utils/errors.d.ts +1 -0
  80. package/dist/utils/errors.d.ts.map +1 -0
  81. package/dist/utils/index.d.ts +1 -0
  82. package/dist/utils/index.d.ts.map +1 -0
  83. package/dist/utils/inngest.d.ts +1 -0
  84. package/dist/utils/inngest.d.ts.map +1 -0
  85. package/dist/vector-access/index.d.ts +7 -0
  86. package/dist/vector-access/index.d.ts.map +1 -0
  87. package/dist/workflows/conditions/constants.d.ts +1 -0
  88. package/dist/workflows/conditions/constants.d.ts.map +1 -0
  89. package/dist/workflows/conditions/types.d.ts +1 -0
  90. package/dist/workflows/conditions/types.d.ts.map +1 -0
  91. package/dist/workflows/handler.d.ts +1 -0
  92. package/dist/workflows/handler.d.ts.map +1 -0
  93. package/dist/workflows/runner.d.ts +1 -0
  94. package/dist/workflows/runner.d.ts.map +1 -0
  95. package/dist/workflows/schemas.d.ts +1 -0
  96. package/dist/workflows/schemas.d.ts.map +1 -0
  97. package/dist/workflows/types.d.ts +1 -0
  98. package/dist/workflows/types.d.ts.map +1 -0
  99. package/dist/workflows/utils.d.ts +1 -0
  100. package/dist/workflows/utils.d.ts.map +1 -0
  101. package/package.json +6 -1
@@ -2,7 +2,7 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var client$1 = require('@prisma-app/client');
5
+ var client$2 = require('@prisma-app/client');
6
6
  var utc = require('@date-fns/utc');
7
7
  var dateFns = require('date-fns');
8
8
  var library = require('@prisma/client/runtime/library');
@@ -18,6 +18,11 @@ var last = require('lodash/last');
18
18
  var inngest = require('inngest');
19
19
  var oauth2Client = require('@badgateway/oauth2-client');
20
20
  var _ = require('lodash');
21
+ var openai = require('@ai-sdk/openai');
22
+ var ai = require('ai');
23
+ var pinecone = require('@pinecone-database/pinecone');
24
+ var OpenAI = require('openai');
25
+ var anthropic = require('@ai-sdk/anthropic');
21
26
 
22
27
  function _interopNamespaceDefault(e) {
23
28
  var n = Object.create(null);
@@ -529,7 +534,7 @@ var prisma = function prisma(url) {
529
534
  console.log('Reusing Global Prisma Client...');
530
535
  prismaInstance = globalForPrisma.standardPrisma;
531
536
  } else {
532
- prismaInstance = new client$1.PrismaClient({
537
+ prismaInstance = new client$2.PrismaClient({
533
538
  datasourceUrl: url,
534
539
  log: logLevels
535
540
  });
@@ -595,7 +600,7 @@ exports.FilterOperators = void 0;
595
600
 
596
601
  var _FieldTypePrimitiveMa, _FilterOperatorToSQL;
597
602
  var fieldsWithCommaSeparatedValues = ['SINGLE_SELECT', 'MULTI_SELECT', 'USER', 'COMPANY', 'CONTACT'];
598
- var FieldTypePrimitiveMap = (_FieldTypePrimitiveMa = {}, _FieldTypePrimitiveMa[client$1.PropertyType.BADGE_LIST] = 'string', _FieldTypePrimitiveMa[client$1.PropertyType.CHECKBOX] = 'boolean', _FieldTypePrimitiveMa[client$1.PropertyType.BOOLEAN] = 'boolean', _FieldTypePrimitiveMa[client$1.PropertyType.NUMBER] = 'number', _FieldTypePrimitiveMa[client$1.PropertyType.FLOAT] = 'number', _FieldTypePrimitiveMa[client$1.PropertyType.JSON_ARRAY] = 'string', _FieldTypePrimitiveMa[client$1.PropertyType.JSON_OBJECT] = 'string', _FieldTypePrimitiveMa[client$1.PropertyType.CURRENCY] = 'number', _FieldTypePrimitiveMa[client$1.PropertyType.DATE] = 'date', _FieldTypePrimitiveMa[client$1.PropertyType.LONG_TEXT] = 'string', _FieldTypePrimitiveMa[client$1.PropertyType.MULTI_SELECT] = 'string', _FieldTypePrimitiveMa[client$1.PropertyType.PHONE] = 'string', _FieldTypePrimitiveMa[client$1.PropertyType.SINGLE_LINE_TEXT] = 'string', _FieldTypePrimitiveMa[client$1.PropertyType.SINGLE_SELECT] = 'string', _FieldTypePrimitiveMa[client$1.PropertyType.URL] = 'string', _FieldTypePrimitiveMa[client$1.PropertyType.USER] = 'string', _FieldTypePrimitiveMa[client$1.PropertyType.CONTACT] = 'string', _FieldTypePrimitiveMa[client$1.PropertyType.COMPANY] = 'string', _FieldTypePrimitiveMa[client$1.PropertyType.COMPOSITE] = 'string', _FieldTypePrimitiveMa[client$1.PropertyType.PERSON] = 'string', _FieldTypePrimitiveMa[client$1.PropertyType.ENRICHMENT] = 'string', _FieldTypePrimitiveMa);
603
+ var FieldTypePrimitiveMap = (_FieldTypePrimitiveMa = {}, _FieldTypePrimitiveMa[client$2.PropertyType.BADGE_LIST] = 'string', _FieldTypePrimitiveMa[client$2.PropertyType.CHECKBOX] = 'boolean', _FieldTypePrimitiveMa[client$2.PropertyType.BOOLEAN] = 'boolean', _FieldTypePrimitiveMa[client$2.PropertyType.NUMBER] = 'number', _FieldTypePrimitiveMa[client$2.PropertyType.FLOAT] = 'number', _FieldTypePrimitiveMa[client$2.PropertyType.JSON_ARRAY] = 'string', _FieldTypePrimitiveMa[client$2.PropertyType.JSON_OBJECT] = 'string', _FieldTypePrimitiveMa[client$2.PropertyType.CURRENCY] = 'number', _FieldTypePrimitiveMa[client$2.PropertyType.DATE] = 'date', _FieldTypePrimitiveMa[client$2.PropertyType.LONG_TEXT] = 'string', _FieldTypePrimitiveMa[client$2.PropertyType.MULTI_SELECT] = 'string', _FieldTypePrimitiveMa[client$2.PropertyType.PHONE] = 'string', _FieldTypePrimitiveMa[client$2.PropertyType.SINGLE_LINE_TEXT] = 'string', _FieldTypePrimitiveMa[client$2.PropertyType.SINGLE_SELECT] = 'string', _FieldTypePrimitiveMa[client$2.PropertyType.URL] = 'string', _FieldTypePrimitiveMa[client$2.PropertyType.USER] = 'string', _FieldTypePrimitiveMa[client$2.PropertyType.CONTACT] = 'string', _FieldTypePrimitiveMa[client$2.PropertyType.COMPANY] = 'string', _FieldTypePrimitiveMa[client$2.PropertyType.COMPOSITE] = 'string', _FieldTypePrimitiveMa[client$2.PropertyType.PERSON] = 'string', _FieldTypePrimitiveMa[client$2.PropertyType.ENRICHMENT] = 'string', _FieldTypePrimitiveMa);
599
604
  var SORT_MODE_TO_ABBR = {
600
605
  ascending: 'asc',
601
606
  descending: 'desc'
@@ -714,7 +719,7 @@ var getFilterClauseSQL = function getFilterClauseSQL(_ref) {
714
719
  var _fields$find;
715
720
  var fieldType = (fields == null || (_fields$find = fields.find(function (f) {
716
721
  return field.startsWith(f.name);
717
- })) == null ? void 0 : _fields$find.type) || client$1.PropertyType.SINGLE_LINE_TEXT;
722
+ })) == null ? void 0 : _fields$find.type) || client$2.PropertyType.SINGLE_LINE_TEXT;
718
723
  var column = "\"mastra\".\"" + table + "\".\"" + field + "\"";
719
724
  var operators = Object.keys(filter);
720
725
  var logicOperator = filter.op || 'or';
@@ -727,11 +732,11 @@ var getFilterClauseSQL = function getFilterClauseSQL(_ref) {
727
732
  childField = _field$split[1];
728
733
  fieldType = (fields == null || (_fields$find2 = fields.find(function (f) {
729
734
  return f.name === childField;
730
- })) == null ? void 0 : _fields$find2.type) || client$1.PropertyType.SINGLE_LINE_TEXT;
735
+ })) == null ? void 0 : _fields$find2.type) || client$2.PropertyType.SINGLE_LINE_TEXT;
731
736
  var JSONField = "\"mastra\".\"" + table + "\".\"" + parentField + "\"->>'" + childField + "'";
732
737
  column = getJSONField(JSONField, fieldType);
733
738
  }
734
- var primitiveType = FieldTypePrimitiveMap[fieldType || client$1.PropertyType.SINGLE_LINE_TEXT];
739
+ var primitiveType = FieldTypePrimitiveMap[fieldType || client$2.PropertyType.SINGLE_LINE_TEXT];
735
740
  var clauses = operators.filter(function (op) {
736
741
  return op !== exports.FilterOperators.OP;
737
742
  }).map(function (op) {
@@ -830,7 +835,7 @@ var getSortClauseSQL = function getSortClauseSQL(_ref) {
830
835
  childField = _field$split[1];
831
836
  var fieldType = (fields == null || (_fields$find = fields.find(function (f) {
832
837
  return f.name === childField;
833
- })) == null ? void 0 : _fields$find.type) || client$1.PropertyType.SINGLE_LINE_TEXT;
838
+ })) == null ? void 0 : _fields$find.type) || client$2.PropertyType.SINGLE_LINE_TEXT;
834
839
  var JSONField = "\"mastra\".\"" + parentTableRef + "\".\"" + parentField + "\"->>'" + childField + "'";
835
840
  var column = getJSONField(JSONField, fieldType);
836
841
  return column + " " + order.toUpperCase();
@@ -1422,7 +1427,7 @@ var DataLayer = /*#__PURE__*/function () {
1422
1427
  });
1423
1428
  })
1424
1429
  }) : undefined;
1425
- updatePromise = toUpdate.length ? this.db.$executeRaw(client$1.Prisma.raw("\n WITH updated_records (\"externalId\", \"data\") AS (\n VALUES\n " + toUpdate.map(function (_ref14) {
1430
+ updatePromise = toUpdate.length ? this.db.$executeRaw(client$2.Prisma.raw("\n WITH updated_records (\"externalId\", \"data\") AS (\n VALUES\n " + toUpdate.map(function (_ref14) {
1426
1431
  var externalId = _ref14.externalId,
1427
1432
  data = _ref14.data;
1428
1433
  return "('" + externalId + "', '" + JSON.stringify(data).replace(/'/g, "''") + "'::jsonb)";
@@ -1573,7 +1578,7 @@ var DataLayer = /*#__PURE__*/function () {
1573
1578
  },
1574
1579
  data: {
1575
1580
  path: [propertyName],
1576
- not: client$1.Prisma.JsonNull
1581
+ not: client$2.Prisma.JsonNull
1577
1582
  }
1578
1583
  }
1579
1584
  }));
@@ -1863,7 +1868,7 @@ var makeCallback = function makeCallback(framework) {
1863
1868
  };
1864
1869
 
1865
1870
  var APP_ID = 'mastra';
1866
- var client = /*#__PURE__*/new inngest.Inngest({
1871
+ var client$1 = /*#__PURE__*/new inngest.Inngest({
1867
1872
  id: APP_ID
1868
1873
  });
1869
1874
 
@@ -1970,7 +1975,7 @@ function _getBlueprints() {
1970
1975
  var createWorkflowHandler = function createWorkflowHandler(_ref2) {
1971
1976
  var blueprintDirPath = _ref2.blueprintDirPath,
1972
1977
  runBlueprint = _ref2.runBlueprint;
1973
- return client.createFunction({
1978
+ return client$1.createFunction({
1974
1979
  id: 'workflow-executor',
1975
1980
  retries: 0
1976
1981
  }, {
@@ -2065,18 +2070,35 @@ var makeInngest = function makeInngest(framework) {
2065
2070
  // TODO: hook into framework to add framework functions to the inngest client
2066
2071
  var eventHandlers = framework.getGlobalEventHandlers();
2067
2072
  var globalEventHandlers = eventHandlers.map(function (eh) {
2068
- return client.createFunction({
2073
+ return client$1.createFunction({
2069
2074
  id: eh.id
2070
2075
  }, {
2071
2076
  event: eh.event
2072
- }, eh.executor);
2077
+ }, /*#__PURE__*/function () {
2078
+ var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(props) {
2079
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
2080
+ while (1) switch (_context.prev = _context.next) {
2081
+ case 0:
2082
+ return _context.abrupt("return", eh.executor(_extends({}, props, {
2083
+ mastra: framework
2084
+ })));
2085
+ case 1:
2086
+ case "end":
2087
+ return _context.stop();
2088
+ }
2089
+ }, _callee);
2090
+ }));
2091
+ return function (_x) {
2092
+ return _ref.apply(this, arguments);
2093
+ };
2094
+ }());
2073
2095
  });
2074
2096
  var systemWorkflowHandler = createWorkflowHandler({
2075
2097
  blueprintDirPath: (_framework$config$wor = framework.config.workflows) == null ? void 0 : _framework$config$wor.blueprintDirPath,
2076
2098
  runBlueprint: framework.runBlueprint
2077
2099
  });
2078
2100
  var handler = next.serve({
2079
- client: client,
2101
+ client: client$1,
2080
2102
  functions: [].concat(globalEventHandlers, [systemWorkflowHandler])
2081
2103
  });
2082
2104
  // @ts-ignore
@@ -2435,19 +2457,6 @@ var Integration = /*#__PURE__*/function () {
2435
2457
  return _ref4.apply(this, arguments);
2436
2458
  };
2437
2459
  }();
2438
- this.getEventHandlers = function (_ref5) {
2439
- var makeWebhookUrl = _ref5.makeWebhookUrl;
2440
- return Object.keys(_this.events).map(function (eventKey) {
2441
- var _this$events$eventKey;
2442
- var eventHandler = (_this$events$eventKey = _this.events[eventKey]) == null ? void 0 : _this$events$eventKey.handler;
2443
- if (!eventHandler) return null;
2444
- return eventHandler({
2445
- integrationInstance: _this,
2446
- eventKey: eventKey,
2447
- makeWebhookUrl: makeWebhookUrl
2448
- });
2449
- }).filter(Boolean);
2450
- };
2451
2460
  if (!(config != null && config.name)) {
2452
2461
  throw new IntegrationError('Integration name must be defined');
2453
2462
  }
@@ -2492,12 +2501,12 @@ var Integration = /*#__PURE__*/function () {
2492
2501
  return getApiClient;
2493
2502
  }();
2494
2503
  _proto.getApi = /*#__PURE__*/function () {
2495
- var _getApi = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(_ref6) {
2504
+ var _getApi = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(_ref5) {
2496
2505
  var connectionId;
2497
2506
  return _regeneratorRuntime().wrap(function _callee5$(_context5) {
2498
2507
  while (1) switch (_context5.prev = _context5.next) {
2499
2508
  case 0:
2500
- connectionId = _ref6.connectionId;
2509
+ connectionId = _ref5.connectionId;
2501
2510
  _context5.next = 3;
2502
2511
  return this.getApiClient({
2503
2512
  connectionId: connectionId
@@ -2521,8 +2530,8 @@ var Integration = /*#__PURE__*/function () {
2521
2530
  _proto.getAuthenticator = function getAuthenticator() {
2522
2531
  throw new IntegrationError('Authenticator not implemented');
2523
2532
  };
2524
- _proto.attachDataLayer = function attachDataLayer(_ref7) {
2525
- var dataLayer = _ref7.dataLayer;
2533
+ _proto.attachDataLayer = function attachDataLayer(_ref6) {
2534
+ var dataLayer = _ref6.dataLayer;
2526
2535
  this.dataLayer = dataLayer;
2527
2536
  };
2528
2537
  _proto.registerApis = function registerApis() {
@@ -2579,14 +2588,14 @@ var Integration = /*#__PURE__*/function () {
2579
2588
  return processWebhookRequest;
2580
2589
  }();
2581
2590
  _proto.triggerEvent = /*#__PURE__*/function () {
2582
- var _triggerEvent = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(_ref8) {
2591
+ var _triggerEvent = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(_ref7) {
2583
2592
  var key, data, user, event;
2584
2593
  return _regeneratorRuntime().wrap(function _callee8$(_context8) {
2585
2594
  while (1) switch (_context8.prev = _context8.next) {
2586
2595
  case 0:
2587
- key = _ref8.key, data = _ref8.data, user = _ref8.user;
2596
+ key = _ref7.key, data = _ref7.data, user = _ref7.user;
2588
2597
  _context8.next = 3;
2589
- return client.send({
2598
+ return client$1.send({
2590
2599
  name: key,
2591
2600
  data: data,
2592
2601
  user: user
@@ -2606,13 +2615,13 @@ var Integration = /*#__PURE__*/function () {
2606
2615
  return triggerEvent;
2607
2616
  }();
2608
2617
  _proto.test = /*#__PURE__*/function () {
2609
- var _test = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(_ref9) {
2618
+ var _test = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(_ref8) {
2610
2619
  var _this$dataLayer;
2611
2620
  var connectionId, connection, _this$config$scopes, authenticator, bearer, desiredScopes, _bearer$scope, actualScopes, isMissingScopes;
2612
2621
  return _regeneratorRuntime().wrap(function _callee9$(_context9) {
2613
2622
  while (1) switch (_context9.prev = _context9.next) {
2614
2623
  case 0:
2615
- connectionId = _ref9.connectionId;
2624
+ connectionId = _ref8.connectionId;
2616
2625
  _context9.next = 3;
2617
2626
  return (_this$dataLayer = this.dataLayer) == null ? void 0 : _this$dataLayer.getConnection({
2618
2627
  connectionId: connectionId,
@@ -2663,7 +2672,7 @@ var Integration = /*#__PURE__*/function () {
2663
2672
  return test;
2664
2673
  }();
2665
2674
  _proto.onConnectionCreated = /*#__PURE__*/function () {
2666
- var _onConnectionCreated = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(_ref10) {
2675
+ var _onConnectionCreated = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(_ref9) {
2667
2676
  return _regeneratorRuntime().wrap(function _callee10$(_context10) {
2668
2677
  while (1) switch (_context10.prev = _context10.next) {
2669
2678
  case 0:
@@ -2679,7 +2688,7 @@ var Integration = /*#__PURE__*/function () {
2679
2688
  return onConnectionCreated;
2680
2689
  }();
2681
2690
  _proto.onDisconnect = /*#__PURE__*/function () {
2682
- var _onDisconnect = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(_ref11) {
2691
+ var _onDisconnect = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(_ref10) {
2683
2692
  return _regeneratorRuntime().wrap(function _callee11$(_context11) {
2684
2693
  while (1) switch (_context11.prev = _context11.next) {
2685
2694
  case 0:
@@ -3123,19 +3132,19 @@ function setFieldOptions(_ref3) {
3123
3132
 
3124
3133
  function zodToPropertType(zodType) {
3125
3134
  if (zodType instanceof zod.z.ZodString) {
3126
- return client$1.PropertyType.SINGLE_LINE_TEXT;
3135
+ return client$2.PropertyType.SINGLE_LINE_TEXT;
3127
3136
  }
3128
3137
  if (zodType instanceof zod.z.ZodBoolean) {
3129
- return client$1.PropertyType.BOOLEAN;
3138
+ return client$2.PropertyType.BOOLEAN;
3130
3139
  }
3131
3140
  if (zodType instanceof zod.z.ZodRecord) {
3132
- return client$1.PropertyType.JSON_OBJECT;
3141
+ return client$2.PropertyType.JSON_OBJECT;
3133
3142
  }
3134
3143
  if (zodType instanceof zod.z.ZodNumber) {
3135
- return client$1.PropertyType.NUMBER;
3144
+ return client$2.PropertyType.NUMBER;
3136
3145
  }
3137
3146
  if (zodType instanceof zod.z.ZodArray) {
3138
- return client$1.PropertyType.JSON_ARRAY;
3147
+ return client$2.PropertyType.JSON_ARRAY;
3139
3148
  }
3140
3149
  if (zodType instanceof zod.z.ZodOptional) {
3141
3150
  return zodToPropertType(zodType._def.innerType);
@@ -3144,10 +3153,10 @@ function zodToPropertType(zodType) {
3144
3153
  return zodToPropertType(zodType._def.innerType);
3145
3154
  }
3146
3155
  if (zodType instanceof zod.z.ZodLiteral) {
3147
- return client$1.PropertyType.SINGLE_LINE_TEXT;
3156
+ return client$2.PropertyType.SINGLE_LINE_TEXT;
3148
3157
  }
3149
3158
  if (zodType instanceof zod.z.ZodObject) {
3150
- return client$1.PropertyType.JSON_OBJECT;
3159
+ return client$2.PropertyType.JSON_OBJECT;
3151
3160
  }
3152
3161
  // TODO UNIONS
3153
3162
  return undefined;
@@ -4069,9 +4078,9 @@ function _runActionsRecursively() {
4069
4078
  data: data
4070
4079
  });
4071
4080
  executorResult = {};
4072
- _ctx = mastraConnectionId ? {
4081
+ _ctx = mastraConnectionId ? _extends({}, ctx, {
4073
4082
  connectionId: mastraConnectionId
4074
- } : ctx;
4083
+ }) : ctx;
4075
4084
  _context2.prev = 46;
4076
4085
  _context2.next = 49;
4077
4086
  return actionExecutor({
@@ -4238,266 +4247,1980 @@ function _blueprintRunner() {
4238
4247
  return _blueprintRunner.apply(this, arguments);
4239
4248
  }
4240
4249
 
4241
- var Framework = /*#__PURE__*/function () {
4242
- function Framework(_ref) {
4243
- var _this = this;
4244
- var dataLayer = _ref.dataLayer,
4245
- config = _ref.config;
4246
- //global events grouped by Integration
4247
- this.globalEvents = new Map();
4248
- // global event handlers
4249
- this.globalEventHandlers = [];
4250
- // global apis grouped by Integration
4251
- this.globalApis = new Map();
4252
- this.integrations = new Map();
4253
- this.dataLayer = void 0;
4254
- this.config = void 0;
4255
- this.runBlueprint = /*#__PURE__*/function () {
4256
- var _ref3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref2) {
4257
- var _this$availableIntegr;
4258
- var blueprint, _ref2$dataCtx, dataCtx, ctx, systemApis, systemEvents, availableIntegrations, availableIntegrationApis, availableIntegrationEvents, frameworkApis, frameworkEvents;
4259
- return _regeneratorRuntime().wrap(function _callee$(_context) {
4260
- while (1) switch (_context.prev = _context.next) {
4261
- case 0:
4262
- blueprint = _ref2.blueprint, _ref2$dataCtx = _ref2.dataCtx, dataCtx = _ref2$dataCtx === void 0 ? {} : _ref2$dataCtx, ctx = _ref2.ctx;
4263
- systemApis = _this.getSystemApis();
4264
- systemEvents = _this.getSystemEvents();
4265
- availableIntegrations = (_this$availableIntegr = _this.availableIntegrations()) == null ? void 0 : _this$availableIntegr.map(function (_ref4) {
4266
- var integration = _ref4.integration;
4267
- return integration;
4268
- });
4269
- availableIntegrationApis = availableIntegrations.reduce(function (acc, _ref5) {
4270
- var name = _ref5.name;
4271
- var apis = _this.getApisByIntegration(name);
4272
- return _extends({}, acc, apis);
4273
- }, {});
4274
- availableIntegrationEvents = availableIntegrations.reduce(function (acc, _ref6) {
4275
- var name = _ref6.name;
4276
- var events = _this.getEventsByIntegration(name);
4277
- return _extends({}, acc, events);
4278
- }, {});
4279
- frameworkApis = _extends({}, systemApis, availableIntegrationApis);
4280
- frameworkEvents = _extends({}, systemEvents, availableIntegrationEvents);
4281
- _context.next = 10;
4282
- return blueprintRunner({
4283
- dataCtx: dataCtx,
4284
- blueprint: blueprint,
4285
- frameworkApis: frameworkApis,
4286
- frameworkEvents: frameworkEvents,
4287
- ctx: ctx
4288
- });
4289
- case 10:
4290
- case "end":
4291
- return _context.stop();
4292
- }
4293
- }, _callee);
4294
- }));
4295
- return function (_x) {
4296
- return _ref3.apply(this, arguments);
4297
- };
4298
- }();
4299
- this.dataLayer = dataLayer;
4300
- this.config = config;
4250
+ function getAgentDir(_ref) {
4251
+ var agentDir = _ref.agentDir;
4252
+ var ARK_APP_DIR = process.env.ARK_APP_DIR || process.cwd();
4253
+ return path.join(ARK_APP_DIR, agentDir);
4254
+ }
4255
+ function listAgentsJson(_ref2) {
4256
+ var agentDir = _ref2.agentDir;
4257
+ var agentDirPath = getAgentDir({
4258
+ agentDir: agentDir
4259
+ });
4260
+ var agents = fs.readdirSync(agentDirPath);
4261
+ return agents;
4262
+ }
4263
+ function getAgentFile(agentFilePath) {
4264
+ try {
4265
+ var fileP = agentFilePath;
4266
+ var fileB = fs.readFileSync(fileP, 'utf8');
4267
+ var json = JSON.parse(fileB);
4268
+ return json;
4269
+ } catch (e) {
4270
+ console.error('No agent blueprint found:', agentFilePath);
4271
+ return;
4301
4272
  }
4302
- Framework.init = function init(config) {
4303
- var _config$workflows$sys;
4304
- if (!config.db.uri) {
4305
- throw new Error('No database config/provider found');
4306
- }
4307
- var dataLayer = new DataLayer({
4308
- url: config.db.uri,
4309
- provider: config.db.provider
4310
- });
4311
- var framework = new Framework({
4312
- config: config,
4313
- dataLayer: dataLayer
4314
- });
4315
- // Register integrations
4316
- config.integrations.forEach(function (integration) {
4317
- framework.__registerIntgeration(integration);
4318
- });
4319
- // Register System apis
4320
- framework.__registerApis({
4321
- apis: (_config$workflows$sys = config.workflows.systemApis) == null ? void 0 : _config$workflows$sys.map(function (api) {
4322
- return _extends({}, api, {
4323
- integrationName: config.name
4324
- });
4325
- })
4326
- });
4327
- // Register System events
4328
- framework.__registerEvents({
4329
- events: config.workflows.systemEvents
4330
- });
4331
- return framework;
4332
- };
4333
- var _proto = Framework.prototype;
4334
- _proto.connectedIntegrations = /*#__PURE__*/function () {
4335
- var _connectedIntegrations = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(_ref7) {
4336
- var _this2 = this;
4337
- var context, ints, connectionChecks;
4338
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
4339
- while (1) switch (_context3.prev = _context3.next) {
4273
+ }
4274
+ function getAgentBlueprint(_ref3) {
4275
+ var agentId = _ref3.agentId,
4276
+ agentDir = _ref3.agentDir;
4277
+ var agentDirPath = getAgentDir({
4278
+ agentDir: agentDir
4279
+ });
4280
+ var agentBlueprintPath = path.join(agentDirPath, agentId + ".json");
4281
+ return getAgentFile(agentBlueprintPath);
4282
+ }
4283
+
4284
+ var VectorLayer = /*#__PURE__*/function () {
4285
+ function VectorLayer() {
4286
+ this.supportedProviders = ['PINECONE'];
4287
+ }
4288
+ var _proto = VectorLayer.prototype;
4289
+ _proto.getPineconeIndexes = /*#__PURE__*/function () {
4290
+ var _getPineconeIndexes = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
4291
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
4292
+ while (1) switch (_context.prev = _context.next) {
4340
4293
  case 0:
4341
- context = _ref7.context;
4342
- ints = this.availableIntegrations();
4343
- _context3.next = 4;
4344
- return Promise.all(ints.map(/*#__PURE__*/function () {
4345
- var _ref9 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_ref8) {
4346
- var integration, connection;
4347
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
4348
- while (1) switch (_context2.prev = _context2.next) {
4349
- case 0:
4350
- integration = _ref8.integration;
4351
- _context2.next = 3;
4352
- return _this2.dataLayer.getConnection({
4353
- connectionId: context.connectionId,
4354
- name: integration.name
4355
- });
4356
- case 3:
4357
- connection = _context2.sent;
4358
- return _context2.abrupt("return", {
4359
- integration: integration,
4360
- connected: !!connection
4361
- });
4362
- case 5:
4363
- case "end":
4364
- return _context2.stop();
4365
- }
4366
- }, _callee2);
4367
- }));
4368
- return function (_x3) {
4369
- return _ref9.apply(this, arguments);
4370
- };
4371
- }()));
4372
- case 4:
4373
- connectionChecks = _context3.sent;
4374
- return _context3.abrupt("return", connectionChecks.filter(function (_ref10) {
4375
- var connected = _ref10.connected;
4376
- return connected;
4377
- }).map(function (_ref11) {
4378
- var integration = _ref11.integration;
4379
- return integration;
4380
- }));
4381
- case 6:
4294
+ return _context.abrupt("return", this.Pinecone.listIndexes());
4295
+ case 1:
4382
4296
  case "end":
4383
- return _context3.stop();
4297
+ return _context.stop();
4384
4298
  }
4385
- }, _callee3, this);
4299
+ }, _callee, this);
4386
4300
  }));
4387
- function connectedIntegrations(_x2) {
4388
- return _connectedIntegrations.apply(this, arguments);
4301
+ function getPineconeIndexes() {
4302
+ return _getPineconeIndexes.apply(this, arguments);
4389
4303
  }
4390
- return connectedIntegrations;
4304
+ return getPineconeIndexes;
4391
4305
  }();
4392
- _proto.__registerIntgeration = function __registerIntgeration(definition) {
4393
- var _this$globalEventHand;
4394
- var name = definition.name;
4395
- definition.attachDataLayer({
4396
- dataLayer: this.dataLayer
4397
- });
4398
- var router = this.createRouter();
4399
- definition.corePresets = {
4400
- redirectURI: router.makeRedirectURI()
4401
- };
4402
- this.integrations.set(name, definition);
4403
- definition.registerEvents();
4404
- this.__registerEvents({
4405
- events: definition.getEvents(),
4406
- integrationName: name
4407
- });
4408
- definition.registerApis();
4409
- definition._convertApiClientToSystemApis();
4410
- this.__registerApis({
4411
- apis: Object.values(definition.getApis()),
4412
- integrationName: name
4413
- });
4414
- (_this$globalEventHand = this.globalEventHandlers).push.apply(_this$globalEventHand, definition.getEventHandlers({
4415
- makeWebhookUrl: router.makeWebhookUrl
4416
- }));
4417
- };
4418
- _proto.__registerEvents = function __registerEvents(_ref12) {
4419
- var events = _ref12.events,
4420
- _ref12$integrationNam = _ref12.integrationName,
4421
- integrationName = _ref12$integrationNam === void 0 ? this.config.name : _ref12$integrationNam;
4422
- var integrationEvents = this.globalEvents.get(integrationName) || {};
4423
- this.globalEvents.set(integrationName, _extends({}, integrationEvents, events));
4424
- };
4425
- _proto.__registerApis = function __registerApis(_ref13) {
4426
- var apis = _ref13.apis,
4427
- _ref13$integrationNam = _ref13.integrationName,
4428
- integrationName = _ref13$integrationNam === void 0 ? this.config.name : _ref13$integrationNam;
4429
- var integrationApis = this.globalApis.get(integrationName) || {};
4430
- this.globalApis.set(integrationName, _extends({}, integrationApis, apis.reduce(function (acc, api) {
4431
- var _extends2;
4432
- return _extends({}, acc, (_extends2 = {}, _extends2[api.type] = api, _extends2));
4433
- }, {})));
4434
- };
4435
- _proto.availableIntegrations = function availableIntegrations() {
4436
- return Array.from(this.integrations.entries()).map(function (_ref14) {
4437
- var name = _ref14[0],
4438
- integration = _ref14[1];
4439
- return {
4440
- name: name,
4441
- integration: integration
4442
- };
4443
- });
4444
- };
4445
- _proto.getIntegration = function getIntegration(name) {
4446
- return this.integrations.get(name);
4447
- };
4448
- _proto.getGlobalEvents = function getGlobalEvents() {
4449
- return this.globalEvents;
4450
- };
4451
- _proto.getSystemEvents = function getSystemEvents() {
4452
- var events = this.globalEvents.get(this.config.name);
4453
- return events || {};
4454
- };
4455
- _proto.getEventsByIntegration = function getEventsByIntegration(name) {
4456
- return this.globalEvents.get(name);
4457
- };
4458
- _proto.getGlobalEventHandlers = function getGlobalEventHandlers() {
4459
- return this.globalEventHandlers;
4460
- };
4461
- _proto.getApis = function getApis() {
4462
- return this.globalApis;
4463
- };
4464
- _proto.getSystemApis = function getSystemApis() {
4465
- return this.globalApis.get(this.config.name);
4466
- };
4467
- _proto.getApisByIntegration = function getApisByIntegration(name, includeHidden) {
4468
- var integrationApis = this.globalApis.get(name);
4469
- if (includeHidden) {
4470
- return integrationApis;
4471
- }
4472
- return _.omitBy(integrationApis, function (value) {
4473
- return value.isHidden;
4474
- });
4475
- };
4476
- _proto.authenticatableIntegrations = function authenticatableIntegrations() {
4477
- return this.availableIntegrations().filter(function (_ref15) {
4478
- var integration = _ref15.integration;
4479
- try {
4480
- integration.getAuthenticator();
4481
- return true;
4482
- } catch (e) {
4483
- return false;
4306
+ return _createClass(VectorLayer, [{
4307
+ key: "Pinecone",
4308
+ get: function get() {
4309
+ if (!process.env.PINECONE_API_KEY) {
4310
+ throw new Error('Pinecone API key not found');
4484
4311
  }
4485
- });
4486
- };
4487
- _proto.authenticator = function authenticator(name) {
4488
- var _int = this.getIntegration(name);
4489
- if (!_int) {
4490
- throw new Error("No integration exists for " + name);
4312
+ return new pinecone.Pinecone({
4313
+ apiKey: process.env.PINECONE_API_KEY
4314
+ });
4315
+ }
4316
+ }]);
4317
+ }();
4318
+
4319
+ function getVectorProvider(provider) {
4320
+ if (provider === 'PINECONE') {
4321
+ var _VectorLayer = new VectorLayer(),
4322
+ Pinecone = _VectorLayer.Pinecone;
4323
+ return Pinecone;
4324
+ }
4325
+ }
4326
+ var delay$1 = function delay(ms) {
4327
+ return new Promise(function (resolve) {
4328
+ return setTimeout(resolve, ms);
4329
+ });
4330
+ };
4331
+ function executeGenericVectorSync(_x) {
4332
+ return _executeGenericVectorSync.apply(this, arguments);
4333
+ }
4334
+ function _executeGenericVectorSync() {
4335
+ _executeGenericVectorSync = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(_ref) {
4336
+ var _event$user, _event$data, _event$data2;
4337
+ var event, mastra, connectionId, vector_provider, entities, systemName, vp, _iterator, _step, _yield$mastra$dataLay, _mastra$dataLayer, vectorE, integrationName, k_id, _mastra$dataLayer2, connection, _loop, _ret, _iterator2, _step2;
4338
+ return _regeneratorRuntime().wrap(function _callee3$(_context4) {
4339
+ while (1) switch (_context4.prev = _context4.next) {
4340
+ case 0:
4341
+ event = _ref.event, mastra = _ref.mastra;
4342
+ connectionId = event == null || (_event$user = event.user) == null ? void 0 : _event$user.connectionId;
4343
+ vector_provider = event == null || (_event$data = event.data) == null ? void 0 : _event$data.vector_provider;
4344
+ entities = event == null || (_event$data2 = event.data) == null ? void 0 : _event$data2.entities;
4345
+ systemName = mastra.config.name;
4346
+ if (vector_provider) {
4347
+ _context4.next = 8;
4348
+ break;
4349
+ }
4350
+ console.error("No vector_provider defined for agent");
4351
+ return _context4.abrupt("return");
4352
+ case 8:
4353
+ vp = getVectorProvider(vector_provider);
4354
+ if (vp) {
4355
+ _context4.next = 12;
4356
+ break;
4357
+ }
4358
+ console.error('UNSUPPORTED VECTOR PROVIDER', vector_provider);
4359
+ return _context4.abrupt("return");
4360
+ case 12:
4361
+ if (process.env.OPENAI_API_KEY) {
4362
+ _context4.next = 15;
4363
+ break;
4364
+ }
4365
+ console.error('NO OPENAI_API_KEY');
4366
+ return _context4.abrupt("return");
4367
+ case 15:
4368
+ _iterator = _createForOfIteratorHelperLoose(entities);
4369
+ case 16:
4370
+ if ((_step = _iterator()).done) {
4371
+ _context4.next = 50;
4372
+ break;
4373
+ }
4374
+ vectorE = _step.value;
4375
+ integrationName = vectorE.integration;
4376
+ _context4.next = 21;
4377
+ return (_mastra$dataLayer = mastra.dataLayer) == null ? void 0 : _mastra$dataLayer.getConnection({
4378
+ connectionId: connectionId,
4379
+ name: integrationName
4380
+ });
4381
+ case 21:
4382
+ _context4.t1 = _yield$mastra$dataLay = _context4.sent;
4383
+ if (!(_context4.t1 == null)) {
4384
+ _context4.next = 26;
4385
+ break;
4386
+ }
4387
+ _context4.t2 = void 0;
4388
+ _context4.next = 27;
4389
+ break;
4390
+ case 26:
4391
+ _context4.t2 = _yield$mastra$dataLay.id;
4392
+ case 27:
4393
+ _context4.t0 = _context4.t2;
4394
+ if (_context4.t0) {
4395
+ _context4.next = 30;
4396
+ break;
4397
+ }
4398
+ _context4.t0 = '';
4399
+ case 30:
4400
+ k_id = _context4.t0;
4401
+ if (!(!k_id && integrationName === systemName)) {
4402
+ _context4.next = 36;
4403
+ break;
4404
+ }
4405
+ _context4.next = 34;
4406
+ return (_mastra$dataLayer2 = mastra.dataLayer) == null ? void 0 : _mastra$dataLayer2.createConnection({
4407
+ connection: {
4408
+ connectionId: connectionId,
4409
+ name: integrationName
4410
+ },
4411
+ credential: {
4412
+ type: 'API_KEY',
4413
+ value: connectionId,
4414
+ scope: []
4415
+ }
4416
+ });
4417
+ case 34:
4418
+ connection = _context4.sent;
4419
+ k_id = connection.id;
4420
+ case 36:
4421
+ if (k_id) {
4422
+ _context4.next = 39;
4423
+ break;
4424
+ }
4425
+ console.error('Error bootstrapping shit');
4426
+ return _context4.abrupt("return");
4427
+ case 39:
4428
+ _loop = /*#__PURE__*/_regeneratorRuntime().mark(function _loop() {
4429
+ var _mastra$dataLayer3, _entityRecords, _records;
4430
+ var entity, entityRecords, records, _mastra$dataLayer4, _entityRecords2, _records2, _yield$mastra$trigger, _event, res, recordsMapped, entityTypeIndex, _recordsMapped$map, vectors;
4431
+ return _regeneratorRuntime().wrap(function _loop$(_context3) {
4432
+ while (1) switch (_context3.prev = _context3.next) {
4433
+ case 0:
4434
+ entity = _step2.value;
4435
+ _context3.next = 3;
4436
+ return (_mastra$dataLayer3 = mastra.dataLayer) == null ? void 0 : _mastra$dataLayer3.getEntityRecordsByConnectionAndType({
4437
+ k_id: k_id,
4438
+ type: entity.name
4439
+ });
4440
+ case 3:
4441
+ entityRecords = _context3.sent;
4442
+ records = (_entityRecords = entityRecords) == null ? void 0 : _entityRecords.records;
4443
+ if (!(!records || ((_records = records) == null ? void 0 : _records.length) === 0)) {
4444
+ _context3.next = 23;
4445
+ break;
4446
+ }
4447
+ // @TODO: SYNC THEM
4448
+ console.error('NO RECORDS');
4449
+ _context3.next = 9;
4450
+ return mastra.triggerEvent({
4451
+ key: entity.syncEvent,
4452
+ data: {},
4453
+ user: {
4454
+ connectionId: connectionId
4455
+ }
4456
+ });
4457
+ case 9:
4458
+ _yield$mastra$trigger = _context3.sent;
4459
+ _event = _yield$mastra$trigger.event;
4460
+ console.log(_event, '####');
4461
+ _context3.next = 14;
4462
+ return _event.subscribe();
4463
+ case 14:
4464
+ res = _context3.sent;
4465
+ console.log('Subscribe result', res);
4466
+ _context3.next = 18;
4467
+ return (_mastra$dataLayer4 = mastra.dataLayer) == null ? void 0 : _mastra$dataLayer4.getEntityRecordsByConnectionAndType({
4468
+ k_id: k_id,
4469
+ type: entity.name
4470
+ });
4471
+ case 18:
4472
+ entityRecords = _context3.sent;
4473
+ records = (_entityRecords2 = entityRecords) == null ? void 0 : _entityRecords2.records;
4474
+ if (!(!records || ((_records2 = records) == null ? void 0 : _records2.length) === 0)) {
4475
+ _context3.next = 23;
4476
+ break;
4477
+ }
4478
+ console.error('NO RECORDS AFTER SYNC');
4479
+ return _context3.abrupt("return", {
4480
+ v: void 0
4481
+ });
4482
+ case 23:
4483
+ recordsMapped = records.map(function (_ref7) {
4484
+ var data = _ref7.data,
4485
+ externalId = _ref7.externalId;
4486
+ return _extends({
4487
+ id: externalId
4488
+ }, _.pick(data, entity.fields));
4489
+ });
4490
+ console.log(recordsMapped, 'RECORDS');
4491
+ _context3.next = 27;
4492
+ return vp.createIndex({
4493
+ suppressConflicts: true,
4494
+ name: entity.name,
4495
+ dimension: 1536,
4496
+ metric: 'cosine',
4497
+ spec: {
4498
+ serverless: {
4499
+ cloud: 'aws',
4500
+ region: 'us-east-1'
4501
+ }
4502
+ }
4503
+ });
4504
+ case 27:
4505
+ _context3.next = 29;
4506
+ return delay$1(5000);
4507
+ case 29:
4508
+ entityTypeIndex = vp.index(entity.name);
4509
+ console.log(entityTypeIndex, 'INDEX');
4510
+ _context3.prev = 31;
4511
+ _context3.next = 34;
4512
+ return Promise.all((_recordsMapped$map = recordsMapped.map(/*#__PURE__*/function () {
4513
+ var _ref8 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(record) {
4514
+ var _yield$embed, embedding;
4515
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
4516
+ while (1) switch (_context2.prev = _context2.next) {
4517
+ case 0:
4518
+ _context2.next = 2;
4519
+ return ai.embed({
4520
+ model: openai.openai.embedding('text-embedding-3-small'),
4521
+ value: JSON.stringify(record)
4522
+ });
4523
+ case 2:
4524
+ _yield$embed = _context2.sent;
4525
+ embedding = _yield$embed.embedding;
4526
+ return _context2.abrupt("return", {
4527
+ id: record.id,
4528
+ values: embedding,
4529
+ metadata: record
4530
+ });
4531
+ case 5:
4532
+ case "end":
4533
+ return _context2.stop();
4534
+ }
4535
+ }, _callee2);
4536
+ }));
4537
+ return function (_x5) {
4538
+ return _ref8.apply(this, arguments);
4539
+ };
4540
+ }())) != null ? _recordsMapped$map : []);
4541
+ case 34:
4542
+ vectors = _context3.sent;
4543
+ console.log('UPSERTING', vectors);
4544
+ if (!(vectors.length > 0)) {
4545
+ _context3.next = 39;
4546
+ break;
4547
+ }
4548
+ _context3.next = 39;
4549
+ return entityTypeIndex.namespace(entity.name).upsert(vectors);
4550
+ case 39:
4551
+ _context3.next = 44;
4552
+ break;
4553
+ case 41:
4554
+ _context3.prev = 41;
4555
+ _context3.t0 = _context3["catch"](31);
4556
+ console.error(_context3.t0);
4557
+ case 44:
4558
+ return _context3.abrupt("return", {
4559
+ v: void 0
4560
+ });
4561
+ case 45:
4562
+ case "end":
4563
+ return _context3.stop();
4564
+ }
4565
+ }, _loop, null, [[31, 41]]);
4566
+ });
4567
+ _iterator2 = _createForOfIteratorHelperLoose(vectorE.data);
4568
+ case 41:
4569
+ if ((_step2 = _iterator2()).done) {
4570
+ _context4.next = 48;
4571
+ break;
4572
+ }
4573
+ return _context4.delegateYield(_loop(), "t3", 43);
4574
+ case 43:
4575
+ _ret = _context4.t3;
4576
+ if (!_ret) {
4577
+ _context4.next = 46;
4578
+ break;
4579
+ }
4580
+ return _context4.abrupt("return", _ret.v);
4581
+ case 46:
4582
+ _context4.next = 41;
4583
+ break;
4584
+ case 48:
4585
+ _context4.next = 16;
4586
+ break;
4587
+ case 50:
4588
+ case "end":
4589
+ return _context4.stop();
4590
+ }
4591
+ }, _callee3);
4592
+ }));
4593
+ return _executeGenericVectorSync.apply(this, arguments);
4594
+ }
4595
+ function executeVectorSync(_x2) {
4596
+ return _executeVectorSync.apply(this, arguments);
4597
+ }
4598
+ function _executeVectorSync() {
4599
+ _executeVectorSync = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(_ref2) {
4600
+ var _event$user2, _agent$knowledge_sour3;
4601
+ var event, mastra, agentDir, agent, connectionId, systemName, vp, _agent$knowledge_sour4, _iterator3, _step3, _yield$mastra$dataLay2, _mastra$dataLayer5, vectorE, integrationName, k_id, _mastra$dataLayer6, connection, _loop2, _ret2, _iterator4, _step4;
4602
+ return _regeneratorRuntime().wrap(function _callee5$(_context7) {
4603
+ while (1) switch (_context7.prev = _context7.next) {
4604
+ case 0:
4605
+ event = _ref2.event, mastra = _ref2.mastra;
4606
+ agentDir = mastra.config.agents.agentDirPath;
4607
+ agent = getAgentBlueprint({
4608
+ agentDir: agentDir,
4609
+ agentId: event.data.agentId
4610
+ });
4611
+ connectionId = event == null || (_event$user2 = event.user) == null ? void 0 : _event$user2.connectionId;
4612
+ systemName = mastra.config.name;
4613
+ if (agent.knowledge_sources.vector_provider) {
4614
+ _context7.next = 8;
4615
+ break;
4616
+ }
4617
+ console.error("No vector_provider defined for agent");
4618
+ return _context7.abrupt("return");
4619
+ case 8:
4620
+ vp = getVectorProvider(agent == null || (_agent$knowledge_sour3 = agent.knowledge_sources) == null ? void 0 : _agent$knowledge_sour3.vector_provider);
4621
+ if (vp) {
4622
+ _context7.next = 12;
4623
+ break;
4624
+ }
4625
+ console.error('UNSUPPORTED VECTOR PROVIDER', agent == null || (_agent$knowledge_sour4 = agent.knowledge_sources) == null ? void 0 : _agent$knowledge_sour4.vector_provider);
4626
+ return _context7.abrupt("return");
4627
+ case 12:
4628
+ if (process.env.OPENAI_API_KEY) {
4629
+ _context7.next = 15;
4630
+ break;
4631
+ }
4632
+ console.error('NO OPENAI_API_KEY');
4633
+ return _context7.abrupt("return");
4634
+ case 15:
4635
+ if (!(!agent || !(agent != null && agent.knowledge_sources))) {
4636
+ _context7.next = 18;
4637
+ break;
4638
+ }
4639
+ console.error('NO AGENT OR KNOWLEDGE SOURCES');
4640
+ return _context7.abrupt("return");
4641
+ case 18:
4642
+ _iterator3 = _createForOfIteratorHelperLoose(agent.knowledge_sources.entities);
4643
+ case 19:
4644
+ if ((_step3 = _iterator3()).done) {
4645
+ _context7.next = 53;
4646
+ break;
4647
+ }
4648
+ vectorE = _step3.value;
4649
+ integrationName = vectorE.integration;
4650
+ _context7.next = 24;
4651
+ return (_mastra$dataLayer5 = mastra.dataLayer) == null ? void 0 : _mastra$dataLayer5.getConnection({
4652
+ connectionId: connectionId,
4653
+ name: integrationName
4654
+ });
4655
+ case 24:
4656
+ _context7.t1 = _yield$mastra$dataLay2 = _context7.sent;
4657
+ if (!(_context7.t1 == null)) {
4658
+ _context7.next = 29;
4659
+ break;
4660
+ }
4661
+ _context7.t2 = void 0;
4662
+ _context7.next = 30;
4663
+ break;
4664
+ case 29:
4665
+ _context7.t2 = _yield$mastra$dataLay2.id;
4666
+ case 30:
4667
+ _context7.t0 = _context7.t2;
4668
+ if (_context7.t0) {
4669
+ _context7.next = 33;
4670
+ break;
4671
+ }
4672
+ _context7.t0 = '';
4673
+ case 33:
4674
+ k_id = _context7.t0;
4675
+ if (!(!k_id && integrationName === systemName)) {
4676
+ _context7.next = 39;
4677
+ break;
4678
+ }
4679
+ _context7.next = 37;
4680
+ return (_mastra$dataLayer6 = mastra.dataLayer) == null ? void 0 : _mastra$dataLayer6.createConnection({
4681
+ connection: {
4682
+ connectionId: connectionId,
4683
+ name: integrationName
4684
+ },
4685
+ credential: {
4686
+ type: 'API_KEY',
4687
+ value: connectionId,
4688
+ scope: []
4689
+ }
4690
+ });
4691
+ case 37:
4692
+ connection = _context7.sent;
4693
+ k_id = connection.id;
4694
+ case 39:
4695
+ if (k_id) {
4696
+ _context7.next = 42;
4697
+ break;
4698
+ }
4699
+ console.error('Error bootstrapping shit');
4700
+ return _context7.abrupt("return");
4701
+ case 42:
4702
+ _loop2 = /*#__PURE__*/_regeneratorRuntime().mark(function _loop2() {
4703
+ var _mastra$dataLayer7, _entityRecords3, _records3;
4704
+ var entity, entityRecords, records, _mastra$dataLayer8, _entityRecords4, _records4, _yield$mastra$trigger2, _event2, res, recordsMapped, entityTypeIndex, _recordsMapped$map2, vectors;
4705
+ return _regeneratorRuntime().wrap(function _loop2$(_context6) {
4706
+ while (1) switch (_context6.prev = _context6.next) {
4707
+ case 0:
4708
+ entity = _step4.value;
4709
+ _context6.next = 3;
4710
+ return (_mastra$dataLayer7 = mastra.dataLayer) == null ? void 0 : _mastra$dataLayer7.getEntityRecordsByConnectionAndType({
4711
+ k_id: k_id,
4712
+ type: entity.name
4713
+ });
4714
+ case 3:
4715
+ entityRecords = _context6.sent;
4716
+ records = (_entityRecords3 = entityRecords) == null ? void 0 : _entityRecords3.records;
4717
+ if (!(!records || ((_records3 = records) == null ? void 0 : _records3.length) === 0)) {
4718
+ _context6.next = 23;
4719
+ break;
4720
+ }
4721
+ // @TODO: SYNC THEM
4722
+ console.error('NO RECORDS');
4723
+ _context6.next = 9;
4724
+ return mastra.triggerEvent({
4725
+ key: entity.syncEvent,
4726
+ data: {},
4727
+ user: {
4728
+ connectionId: connectionId
4729
+ }
4730
+ });
4731
+ case 9:
4732
+ _yield$mastra$trigger2 = _context6.sent;
4733
+ _event2 = _yield$mastra$trigger2.event;
4734
+ console.log(_event2, '####');
4735
+ _context6.next = 14;
4736
+ return _event2.subscribe();
4737
+ case 14:
4738
+ res = _context6.sent;
4739
+ console.log('Subscribe result', res);
4740
+ _context6.next = 18;
4741
+ return (_mastra$dataLayer8 = mastra.dataLayer) == null ? void 0 : _mastra$dataLayer8.getEntityRecordsByConnectionAndType({
4742
+ k_id: k_id,
4743
+ type: entity.name
4744
+ });
4745
+ case 18:
4746
+ entityRecords = _context6.sent;
4747
+ records = (_entityRecords4 = entityRecords) == null ? void 0 : _entityRecords4.records;
4748
+ if (!(!records || ((_records4 = records) == null ? void 0 : _records4.length) === 0)) {
4749
+ _context6.next = 23;
4750
+ break;
4751
+ }
4752
+ console.error('NO RECORDS AFTER SYNC');
4753
+ return _context6.abrupt("return", {
4754
+ v: void 0
4755
+ });
4756
+ case 23:
4757
+ recordsMapped = records.map(function (_ref9) {
4758
+ var data = _ref9.data,
4759
+ externalId = _ref9.externalId;
4760
+ return _extends({
4761
+ id: externalId
4762
+ }, _.pick(data, entity.fields));
4763
+ });
4764
+ console.log(recordsMapped, 'RECORDS');
4765
+ _context6.next = 27;
4766
+ return vp.createIndex({
4767
+ suppressConflicts: true,
4768
+ name: entity.name,
4769
+ dimension: 1536,
4770
+ metric: 'cosine',
4771
+ spec: {
4772
+ serverless: {
4773
+ cloud: 'aws',
4774
+ region: 'us-east-1'
4775
+ }
4776
+ }
4777
+ });
4778
+ case 27:
4779
+ entityTypeIndex = vp.index(entity.name);
4780
+ console.log(entityTypeIndex, 'INDEX');
4781
+ _context6.prev = 29;
4782
+ _context6.next = 32;
4783
+ return Promise.all((_recordsMapped$map2 = recordsMapped.map(/*#__PURE__*/function () {
4784
+ var _ref10 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(record) {
4785
+ var _yield$embed2, embedding;
4786
+ return _regeneratorRuntime().wrap(function _callee4$(_context5) {
4787
+ while (1) switch (_context5.prev = _context5.next) {
4788
+ case 0:
4789
+ _context5.next = 2;
4790
+ return ai.embed({
4791
+ model: openai.openai.embedding('text-embedding-3-small'),
4792
+ value: JSON.stringify(record)
4793
+ });
4794
+ case 2:
4795
+ _yield$embed2 = _context5.sent;
4796
+ embedding = _yield$embed2.embedding;
4797
+ return _context5.abrupt("return", {
4798
+ id: record.id,
4799
+ values: embedding,
4800
+ metadata: record
4801
+ });
4802
+ case 5:
4803
+ case "end":
4804
+ return _context5.stop();
4805
+ }
4806
+ }, _callee4);
4807
+ }));
4808
+ return function (_x6) {
4809
+ return _ref10.apply(this, arguments);
4810
+ };
4811
+ }())) != null ? _recordsMapped$map2 : []);
4812
+ case 32:
4813
+ vectors = _context6.sent;
4814
+ console.log('UPSERTING', vectors);
4815
+ if (!(vectors.length > 0)) {
4816
+ _context6.next = 37;
4817
+ break;
4818
+ }
4819
+ _context6.next = 37;
4820
+ return entityTypeIndex.namespace(entity.name).upsert(vectors);
4821
+ case 37:
4822
+ _context6.next = 42;
4823
+ break;
4824
+ case 39:
4825
+ _context6.prev = 39;
4826
+ _context6.t0 = _context6["catch"](29);
4827
+ console.error(_context6.t0);
4828
+ case 42:
4829
+ return _context6.abrupt("return", {
4830
+ v: void 0
4831
+ });
4832
+ case 43:
4833
+ case "end":
4834
+ return _context6.stop();
4835
+ }
4836
+ }, _loop2, null, [[29, 39]]);
4837
+ });
4838
+ _iterator4 = _createForOfIteratorHelperLoose(vectorE.data);
4839
+ case 44:
4840
+ if ((_step4 = _iterator4()).done) {
4841
+ _context7.next = 51;
4842
+ break;
4843
+ }
4844
+ return _context7.delegateYield(_loop2(), "t3", 46);
4845
+ case 46:
4846
+ _ret2 = _context7.t3;
4847
+ if (!_ret2) {
4848
+ _context7.next = 49;
4849
+ break;
4850
+ }
4851
+ return _context7.abrupt("return", _ret2.v);
4852
+ case 49:
4853
+ _context7.next = 44;
4854
+ break;
4855
+ case 51:
4856
+ _context7.next = 19;
4857
+ break;
4858
+ case 53:
4859
+ case "end":
4860
+ return _context7.stop();
4861
+ }
4862
+ }, _callee5);
4863
+ }));
4864
+ return _executeVectorSync.apply(this, arguments);
4865
+ }
4866
+ function vectorQueryEngine(_x3) {
4867
+ return _vectorQueryEngine.apply(this, arguments);
4868
+ }
4869
+ function _vectorQueryEngine() {
4870
+ _vectorQueryEngine = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(_ref3) {
4871
+ var vector_provider, _ref3$topK, topK, indexName, content, entityType, vp, index, _yield$embed3, embedding, queryResponse;
4872
+ return _regeneratorRuntime().wrap(function _callee6$(_context8) {
4873
+ while (1) switch (_context8.prev = _context8.next) {
4874
+ case 0:
4875
+ vector_provider = _ref3.vector_provider, _ref3$topK = _ref3.topK, topK = _ref3$topK === void 0 ? 1 : _ref3$topK, indexName = _ref3.indexName, content = _ref3.content, entityType = _ref3.entityType;
4876
+ vp = getVectorProvider(vector_provider);
4877
+ if (vp) {
4878
+ _context8.next = 5;
4879
+ break;
4880
+ }
4881
+ console.error('UNSUPPORTED VECTOR PROVIDER', vector_provider);
4882
+ return _context8.abrupt("return");
4883
+ case 5:
4884
+ index = vp.index(indexName);
4885
+ _context8.next = 8;
4886
+ return ai.embed({
4887
+ model: openai.openai.embedding('text-embedding-3-small'),
4888
+ value: content
4889
+ });
4890
+ case 8:
4891
+ _yield$embed3 = _context8.sent;
4892
+ embedding = _yield$embed3.embedding;
4893
+ console.log(embedding, 'EMBEDDING');
4894
+ _context8.next = 13;
4895
+ return index.namespace(entityType).query({
4896
+ vector: embedding,
4897
+ topK: topK,
4898
+ includeMetadata: true
4899
+ });
4900
+ case 13:
4901
+ queryResponse = _context8.sent;
4902
+ return _context8.abrupt("return", queryResponse);
4903
+ case 15:
4904
+ case "end":
4905
+ return _context8.stop();
4906
+ }
4907
+ }, _callee6);
4908
+ }));
4909
+ return _vectorQueryEngine.apply(this, arguments);
4910
+ }
4911
+ function getVectorQueryApis(_ref4) {
4912
+ var mastra = _ref4.mastra;
4913
+ var agentDir = mastra.config.agents.agentDirPath;
4914
+ var agents = listAgentsJson({
4915
+ agentDir: agentDir
4916
+ });
4917
+ var agentData = agents.map(function (agentFile) {
4918
+ var _agent$knowledge_sour;
4919
+ var agentDirPath = getAgentDir({
4920
+ agentDir: agentDir
4921
+ });
4922
+ var agent = getAgentFile(path.join(agentDirPath, agentFile));
4923
+ if (!(agent != null && (_agent$knowledge_sour = agent.knowledge_sources) != null && _agent$knowledge_sour.vector_provider)) {
4924
+ console.error("No vector_provider defined for agent");
4925
+ return;
4926
+ }
4927
+ return agent;
4928
+ }).filter(Boolean);
4929
+ return agentData.flatMap(function (agent) {
4930
+ var entities = agent == null ? void 0 : agent.knowledge_sources.entities;
4931
+ return entities.flatMap(function (_ref5) {
4932
+ var data = _ref5.data,
4933
+ integration = _ref5.integration;
4934
+ return data.map(function (entity) {
4935
+ return {
4936
+ integrationName: integration,
4937
+ type: "get_" + entity.name + "_from_vector_" + entity.index,
4938
+ label: "Provides " + entity.name + " information from Vector " + entity.index + " Store",
4939
+ description: "Provides " + entity.name + " information from Vector " + entity.index + " Store",
4940
+ schema: zod.z.object({
4941
+ content: zod.z.string(),
4942
+ topResult: zod.z.number()
4943
+ }),
4944
+ executor: function () {
4945
+ var _executor = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref6) {
4946
+ var _agent$knowledge_sour2;
4947
+ var data, res;
4948
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
4949
+ while (1) switch (_context.prev = _context.next) {
4950
+ case 0:
4951
+ data = _ref6.data;
4952
+ _context.next = 3;
4953
+ return vectorQueryEngine({
4954
+ vector_provider: agent == null || (_agent$knowledge_sour2 = agent.knowledge_sources) == null ? void 0 : _agent$knowledge_sour2.vector_provider,
4955
+ indexName: entity.index,
4956
+ content: data.content,
4957
+ topK: data.topResult || 1,
4958
+ entityType: entity.name
4959
+ });
4960
+ case 3:
4961
+ res = _context.sent;
4962
+ console.log(JSON.stringify({
4963
+ res: res
4964
+ }, null, 2));
4965
+ // @TODO: make this a proper response
4966
+ return _context.abrupt("return", res);
4967
+ case 6:
4968
+ case "end":
4969
+ return _context.stop();
4970
+ }
4971
+ }, _callee);
4972
+ }));
4973
+ function executor(_x4) {
4974
+ return _executor.apply(this, arguments);
4975
+ }
4976
+ return executor;
4977
+ }()
4978
+ };
4979
+ });
4980
+ });
4981
+ }).filter(Boolean);
4982
+ }
4983
+ function agentVectorSyncEvent() {
4984
+ return {
4985
+ // @TODO: naming convention
4986
+ id: 'agent-vector-sync',
4987
+ event: 'AGENT_VECTOR_SYNC',
4988
+ executor: executeVectorSync
4989
+ };
4990
+ }
4991
+ function genericVectorySyncEvent() {
4992
+ return {
4993
+ // @TODO: naming convention
4994
+ id: 'vector-sync',
4995
+ event: 'VECTOR_SYNC',
4996
+ executor: executeGenericVectorSync
4997
+ };
4998
+ }
4999
+
5000
+ function getAgentSystemApis(_ref) {
5001
+ var mastra = _ref.mastra;
5002
+ var agentDir = mastra.config.agents.agentDirPath;
5003
+ var agents = listAgentsJson({
5004
+ agentDir: agentDir
5005
+ });
5006
+ // Remove the .json extension from the agent names
5007
+ var agentList = agents.map(function (agent) {
5008
+ return agent.slice(0, -5);
5009
+ });
5010
+ return [{
5011
+ integrationName: 'SYSTEM',
5012
+ type: 'message_agent',
5013
+ label: 'Send Message To Agent',
5014
+ description: 'Sends a message to an Agent',
5015
+ schema: zod.z.object({
5016
+ agentId: zod.z["enum"](agentList),
5017
+ message: zod.z.string()
5018
+ }),
5019
+ outputSchema: zod.z.object({
5020
+ message: zod.z.string()
5021
+ }),
5022
+ executor: function () {
5023
+ var _executor = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref2) {
5024
+ var data, executor, result, _run$content, thread, run;
5025
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
5026
+ while (1) switch (_context.prev = _context.next) {
5027
+ case 0:
5028
+ data = _ref2.data;
5029
+ _context.next = 3;
5030
+ return mastra.getAgent({
5031
+ agentId: data.agentId,
5032
+ connectionId: data.connectionId
5033
+ });
5034
+ case 3:
5035
+ executor = _context.sent;
5036
+ if (executor) {
5037
+ _context.next = 6;
5038
+ break;
5039
+ }
5040
+ throw new Error('Could not create agent executor');
5041
+ case 6:
5042
+ if (!(typeof executor === 'function')) {
5043
+ _context.next = 13;
5044
+ break;
5045
+ }
5046
+ _context.next = 9;
5047
+ return executor({
5048
+ prompt: data == null ? void 0 : data.message
5049
+ });
5050
+ case 9:
5051
+ result = _context.sent;
5052
+ return _context.abrupt("return", {
5053
+ message: result == null ? void 0 : result.text
5054
+ });
5055
+ case 13:
5056
+ _context.next = 15;
5057
+ return executor.initializeThread([{
5058
+ role: 'user',
5059
+ content: data == null ? void 0 : data.message
5060
+ }]);
5061
+ case 15:
5062
+ thread = _context.sent;
5063
+ _context.next = 18;
5064
+ return executor.watchRun({
5065
+ threadId: thread.id
5066
+ });
5067
+ case 18:
5068
+ run = _context.sent;
5069
+ return _context.abrupt("return", {
5070
+ message: run == null || (_run$content = run.content) == null || (_run$content = _run$content[0]) == null || (_run$content = _run$content.text) == null ? void 0 : _run$content.value
5071
+ });
5072
+ case 20:
5073
+ case "end":
5074
+ return _context.stop();
5075
+ }
5076
+ }, _callee);
5077
+ }));
5078
+ function executor(_x) {
5079
+ return _executor.apply(this, arguments);
5080
+ }
5081
+ return executor;
5082
+ }()
5083
+ }];
5084
+ }
5085
+
5086
+ var loggerPath = /*#__PURE__*/path.join(/*#__PURE__*/process.cwd(), 'mastra-agent-logs');
5087
+ function createFileLogger(_ref) {
5088
+ var destinationPath = _ref.destinationPath;
5089
+ var fullPath = path.join(loggerPath, destinationPath);
5090
+ return function (log) {
5091
+ if (!fs.existsSync(loggerPath)) {
5092
+ fs.mkdirSync(loggerPath, {
5093
+ recursive: true
5094
+ });
5095
+ return fs.writeFileSync(fullPath, JSON.stringify([_extends({}, log, {
5096
+ createdAt: new Date()
5097
+ })], null, 2));
5098
+ }
5099
+ var logs = JSON.parse(fs.readFileSync(fullPath, 'utf-8'));
5100
+ logs.push(_extends({}, log, {
5101
+ createdAt: new Date()
5102
+ }));
5103
+ return fs.writeFileSync(fullPath, JSON.stringify(logs, null, 2));
5104
+ };
5105
+ }
5106
+
5107
+ var client = /*#__PURE__*/new OpenAI({
5108
+ apiKey: process.env.OPENAI_API_KEY
5109
+ });
5110
+ function getAssistantAgent(_x3) {
5111
+ return _getAssistantAgent.apply(this, arguments);
5112
+ }
5113
+ function _getAssistantAgent() {
5114
+ _getAssistantAgent = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(_ref3) {
5115
+ var id, toolMap, logger, agent, handleRunStatus, handleRequiresAction, getRun;
5116
+ return _regeneratorRuntime().wrap(function _callee11$(_context11) {
5117
+ while (1) switch (_context11.prev = _context11.next) {
5118
+ case 0:
5119
+ id = _ref3.id, toolMap = _ref3.toolMap;
5120
+ logger = createFileLogger({
5121
+ destinationPath: id + ".json"
5122
+ });
5123
+ _context11.next = 4;
5124
+ return client.beta.assistants.retrieve(id);
5125
+ case 4:
5126
+ agent = _context11.sent;
5127
+ handleRunStatus = /*#__PURE__*/function () {
5128
+ var _ref5 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(_ref4) {
5129
+ var threadId, run, _messages$data, messages;
5130
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
5131
+ while (1) switch (_context3.prev = _context3.next) {
5132
+ case 0:
5133
+ threadId = _ref4.threadId, run = _ref4.run;
5134
+ if (!(run.status === 'completed')) {
5135
+ _context3.next = 8;
5136
+ break;
5137
+ }
5138
+ _context3.next = 4;
5139
+ return client.beta.threads.messages.list(threadId);
5140
+ case 4:
5141
+ messages = _context3.sent;
5142
+ return _context3.abrupt("return", (_messages$data = messages.data) == null ? void 0 : _messages$data[0]);
5143
+ case 8:
5144
+ if (!(run.status === 'requires_action')) {
5145
+ _context3.next = 14;
5146
+ break;
5147
+ }
5148
+ _context3.next = 11;
5149
+ return handleRequiresAction({
5150
+ run: run,
5151
+ threadId: threadId
5152
+ });
5153
+ case 11:
5154
+ return _context3.abrupt("return", _context3.sent);
5155
+ case 14:
5156
+ console.error('Run did not complete:', run);
5157
+ logger({
5158
+ statusCode: 400,
5159
+ message: JSON.stringify({
5160
+ message: "Run did not complete",
5161
+ event_type: 'run_error',
5162
+ metadata: {
5163
+ run: run
5164
+ }
5165
+ }, null, 2)
5166
+ });
5167
+ case 16:
5168
+ case "end":
5169
+ return _context3.stop();
5170
+ }
5171
+ }, _callee3);
5172
+ }));
5173
+ return function handleRunStatus(_x4) {
5174
+ return _ref5.apply(this, arguments);
5175
+ };
5176
+ }();
5177
+ handleRequiresAction = /*#__PURE__*/function () {
5178
+ var _ref7 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(_ref6) {
5179
+ var threadId, run, toolOutputs;
5180
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
5181
+ while (1) switch (_context5.prev = _context5.next) {
5182
+ case 0:
5183
+ threadId = _ref6.threadId, run = _ref6.run;
5184
+ if (!(run.required_action && run.required_action.submit_tool_outputs && run.required_action.submit_tool_outputs.tool_calls)) {
5185
+ _context5.next = 23;
5186
+ break;
5187
+ }
5188
+ _context5.t0 = _.compact;
5189
+ _context5.next = 5;
5190
+ return Promise.all(run.required_action.submit_tool_outputs.tool_calls.map(/*#__PURE__*/function () {
5191
+ var _ref8 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(tool, index, tools) {
5192
+ var callInfo, toolMetadata, toolFn, args, output;
5193
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
5194
+ while (1) switch (_context4.prev = _context4.next) {
5195
+ case 0:
5196
+ callInfo = index + 1 + " of " + tools.length;
5197
+ console.log('Tool:', tool["function"].name, tool.id, Object.keys(toolMap));
5198
+ toolMetadata = {
5199
+ id: tool.id,
5200
+ fn: tool["function"].name,
5201
+ availableTools: Object.keys(toolMap)
5202
+ };
5203
+ logger({
5204
+ statusCode: 100,
5205
+ message: JSON.stringify({
5206
+ message: "[local] Starting tool call " + callInfo + ": " + tool["function"].name,
5207
+ metadata: {
5208
+ tool: toolMetadata
5209
+ }
5210
+ }, null, 2)
5211
+ });
5212
+ toolFn = toolMap == null ? void 0 : toolMap[tool["function"].name];
5213
+ if (toolFn) {
5214
+ _context4.next = 8;
5215
+ break;
5216
+ }
5217
+ logger({
5218
+ statusCode: 404,
5219
+ message: JSON.stringify({
5220
+ message: "[local] No tool fn found: " + tool["function"].name,
5221
+ metadata: {
5222
+ tool: toolMetadata
5223
+ }
5224
+ }, null, 2)
5225
+ });
5226
+ return _context4.abrupt("return");
5227
+ case 8:
5228
+ console.log('Executing tool:', tool["function"].name, tool.id, tool["function"].arguments);
5229
+ args = {};
5230
+ try {
5231
+ if (tool["function"].arguments) {
5232
+ args = JSON.parse(tool["function"].arguments);
5233
+ logger({
5234
+ statusCode: 100,
5235
+ message: JSON.stringify({
5236
+ message: "[local] Passing args to tool call: " + tool["function"].name,
5237
+ metadata: {
5238
+ args: args,
5239
+ tool: toolMetadata
5240
+ }
5241
+ }, null, 2)
5242
+ });
5243
+ }
5244
+ } catch (e) {
5245
+ console.error(e);
5246
+ }
5247
+ _context4.next = 13;
5248
+ return toolFn(args);
5249
+ case 13:
5250
+ output = _context4.sent;
5251
+ logger({
5252
+ statusCode: 200,
5253
+ message: JSON.stringify({
5254
+ message: "[local] Completed tool call " + callInfo + ": " + tool["function"].name,
5255
+ metadata: {
5256
+ output: output,
5257
+ tool: toolMetadata
5258
+ }
5259
+ }, null, 2)
5260
+ });
5261
+ return _context4.abrupt("return", {
5262
+ tool_call_id: tool.id,
5263
+ output: JSON.stringify(output)
5264
+ });
5265
+ case 16:
5266
+ case "end":
5267
+ return _context4.stop();
5268
+ }
5269
+ }, _callee4);
5270
+ }));
5271
+ return function (_x6, _x7, _x8) {
5272
+ return _ref8.apply(this, arguments);
5273
+ };
5274
+ }()));
5275
+ case 5:
5276
+ _context5.t1 = _context5.sent;
5277
+ toolOutputs = (0, _context5.t0)(_context5.t1);
5278
+ if (toolOutputs) {
5279
+ _context5.next = 11;
5280
+ break;
5281
+ }
5282
+ console.error('No tool outputs to submit.');
5283
+ logger({
5284
+ statusCode: 404,
5285
+ message: JSON.stringify({
5286
+ message: "No tool outputs submitted",
5287
+ metadata: {}
5288
+ }, null, 2)
5289
+ });
5290
+ return _context5.abrupt("return", handleRunStatus({
5291
+ threadId: threadId,
5292
+ run: run
5293
+ }));
5294
+ case 11:
5295
+ if (!(toolOutputs && (toolOutputs == null ? void 0 : toolOutputs.length) > 0)) {
5296
+ _context5.next = 20;
5297
+ break;
5298
+ }
5299
+ console.log(toolOutputs, '###### YOOOOOO');
5300
+ _context5.next = 15;
5301
+ return client.beta.threads.runs.submitToolOutputsAndPoll(threadId, run.id, {
5302
+ tool_outputs: toolOutputs
5303
+ });
5304
+ case 15:
5305
+ run = _context5.sent;
5306
+ logger({
5307
+ statusCode: 200,
5308
+ message: JSON.stringify({
5309
+ message: "Tool outputs submitted",
5310
+ metadata: {
5311
+ run: run
5312
+ }
5313
+ }, null, 2)
5314
+ });
5315
+ console.log('Tool outputs submitted successfully.');
5316
+ _context5.next = 22;
5317
+ break;
5318
+ case 20:
5319
+ logger({
5320
+ statusCode: 404,
5321
+ message: JSON.stringify({
5322
+ message: "No tool outputs to submit",
5323
+ metadata: {}
5324
+ }, null, 2)
5325
+ });
5326
+ console.log('No tool outputs to submit.');
5327
+ case 22:
5328
+ return _context5.abrupt("return", handleRunStatus({
5329
+ threadId: threadId,
5330
+ run: run
5331
+ }));
5332
+ case 23:
5333
+ case "end":
5334
+ return _context5.stop();
5335
+ }
5336
+ }, _callee5);
5337
+ }));
5338
+ return function handleRequiresAction(_x5) {
5339
+ return _ref7.apply(this, arguments);
5340
+ };
5341
+ }();
5342
+ getRun = /*#__PURE__*/function () {
5343
+ var _ref10 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(_ref9) {
5344
+ var threadId, runId;
5345
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
5346
+ while (1) switch (_context6.prev = _context6.next) {
5347
+ case 0:
5348
+ threadId = _ref9.threadId, runId = _ref9.runId;
5349
+ _context6.next = 3;
5350
+ return client.beta.threads.runs.retrieve(threadId, runId);
5351
+ case 3:
5352
+ return _context6.abrupt("return", _context6.sent);
5353
+ case 4:
5354
+ case "end":
5355
+ return _context6.stop();
5356
+ }
5357
+ }, _callee6);
5358
+ }));
5359
+ return function getRun(_x9) {
5360
+ return _ref10.apply(this, arguments);
5361
+ };
5362
+ }();
5363
+ return _context11.abrupt("return", {
5364
+ agent: agent,
5365
+ initializeThread: function () {
5366
+ var _initializeThread = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(messages) {
5367
+ return _regeneratorRuntime().wrap(function _callee7$(_context7) {
5368
+ while (1) switch (_context7.prev = _context7.next) {
5369
+ case 0:
5370
+ if (messages === void 0) {
5371
+ messages = [];
5372
+ }
5373
+ _context7.next = 3;
5374
+ return client.beta.threads.create({
5375
+ messages: messages
5376
+ });
5377
+ case 3:
5378
+ return _context7.abrupt("return", _context7.sent);
5379
+ case 4:
5380
+ case "end":
5381
+ return _context7.stop();
5382
+ }
5383
+ }, _callee7);
5384
+ }));
5385
+ function initializeThread(_x10) {
5386
+ return _initializeThread.apply(this, arguments);
5387
+ }
5388
+ return initializeThread;
5389
+ }(),
5390
+ listMessages: function () {
5391
+ var _listMessages = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(_ref11) {
5392
+ var threadId;
5393
+ return _regeneratorRuntime().wrap(function _callee8$(_context8) {
5394
+ while (1) switch (_context8.prev = _context8.next) {
5395
+ case 0:
5396
+ threadId = _ref11.threadId;
5397
+ _context8.next = 3;
5398
+ return client.beta.threads.messages.list(threadId);
5399
+ case 3:
5400
+ return _context8.abrupt("return", _context8.sent);
5401
+ case 4:
5402
+ case "end":
5403
+ return _context8.stop();
5404
+ }
5405
+ }, _callee8);
5406
+ }));
5407
+ function listMessages(_x11) {
5408
+ return _listMessages.apply(this, arguments);
5409
+ }
5410
+ return listMessages;
5411
+ }(),
5412
+ getRun: getRun,
5413
+ handleRunStatus: handleRunStatus,
5414
+ handleRequiresAction: handleRequiresAction,
5415
+ createUserMessage: function () {
5416
+ var _createUserMessage = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(_ref12) {
5417
+ var threadId, content;
5418
+ return _regeneratorRuntime().wrap(function _callee9$(_context9) {
5419
+ while (1) switch (_context9.prev = _context9.next) {
5420
+ case 0:
5421
+ threadId = _ref12.threadId, content = _ref12.content;
5422
+ _context9.next = 3;
5423
+ return client.beta.threads.messages.create(threadId, {
5424
+ role: 'user',
5425
+ content: content
5426
+ });
5427
+ case 3:
5428
+ return _context9.abrupt("return", _context9.sent);
5429
+ case 4:
5430
+ case "end":
5431
+ return _context9.stop();
5432
+ }
5433
+ }, _callee9);
5434
+ }));
5435
+ function createUserMessage(_x12) {
5436
+ return _createUserMessage.apply(this, arguments);
5437
+ }
5438
+ return createUserMessage;
5439
+ }(),
5440
+ watchRun: function () {
5441
+ var _watchRun = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(_ref13) {
5442
+ var runId, threadId, run;
5443
+ return _regeneratorRuntime().wrap(function _callee10$(_context10) {
5444
+ while (1) switch (_context10.prev = _context10.next) {
5445
+ case 0:
5446
+ runId = _ref13.runId, threadId = _ref13.threadId;
5447
+ if (!runId) {
5448
+ _context10.next = 7;
5449
+ break;
5450
+ }
5451
+ _context10.next = 4;
5452
+ return getRun({
5453
+ threadId: threadId,
5454
+ runId: runId
5455
+ });
5456
+ case 4:
5457
+ run = _context10.sent;
5458
+ _context10.next = 11;
5459
+ break;
5460
+ case 7:
5461
+ _context10.next = 9;
5462
+ return client.beta.threads.runs.createAndPoll(threadId, {
5463
+ assistant_id: id,
5464
+ tool_choice: 'required'
5465
+ });
5466
+ case 9:
5467
+ run = _context10.sent;
5468
+ logger({
5469
+ statusCode: 202,
5470
+ message: JSON.stringify({
5471
+ message: "Creating and polling run, tool choice required",
5472
+ metadata: {
5473
+ run: run,
5474
+ tool_choice: 'required',
5475
+ threadId: threadId,
5476
+ assistant_id: id
5477
+ }
5478
+ }, null, 2)
5479
+ });
5480
+ case 11:
5481
+ return _context10.abrupt("return", handleRunStatus({
5482
+ threadId: threadId,
5483
+ run: run
5484
+ }));
5485
+ case 12:
5486
+ case "end":
5487
+ return _context10.stop();
5488
+ }
5489
+ }, _callee10);
5490
+ }));
5491
+ function watchRun(_x13) {
5492
+ return _watchRun.apply(this, arguments);
5493
+ }
5494
+ return watchRun;
5495
+ }()
5496
+ });
5497
+ case 9:
5498
+ case "end":
5499
+ return _context11.stop();
5500
+ }
5501
+ }, _callee11);
5502
+ }));
5503
+ return _getAssistantAgent.apply(this, arguments);
5504
+ }
5505
+
5506
+ var delay = function delay(ms) {
5507
+ return new Promise(function (resolve) {
5508
+ return setTimeout(resolve, ms);
5509
+ });
5510
+ };
5511
+ function getAgentParams(_ref) {
5512
+ var tools = _ref.tools,
5513
+ resultTool = _ref.resultTool,
5514
+ model = _ref.model;
5515
+ var toolsConverted = Object.entries(tools).reduce(function (memo, _ref2) {
5516
+ var key = _ref2[0],
5517
+ val = _ref2[1];
5518
+ memo[key] = ai.tool(val);
5519
+ return memo;
5520
+ }, {});
5521
+ var answerTool = {};
5522
+ if (resultTool) {
5523
+ answerTool = {
5524
+ answer: ai.tool(resultTool)
5525
+ };
5526
+ }
5527
+ var modelDef;
5528
+ if (model.type === 'openai') {
5529
+ var mName = model.name;
5530
+ if (!mName) {
5531
+ mName = "gpt-4o-2024-08-06";
5532
+ }
5533
+ var openai$1 = openai.createOpenAI({
5534
+ apiKey: process.env.OPENAI_API_KEY
5535
+ });
5536
+ modelDef = openai$1(mName, {
5537
+ structuredOutputs: true
5538
+ });
5539
+ } else if (model.type === 'anthropic') {
5540
+ var _mName = model.name;
5541
+ if (!_mName) {
5542
+ _mName = "claude-3-5-sonnet-20240620";
5543
+ }
5544
+ var anthropic$1 = anthropic.createAnthropic({
5545
+ apiKey: process.env.ANTHROPIC_API_KEY
5546
+ });
5547
+ modelDef = anthropic$1(_mName);
5548
+ } else if (model.type === 'groq') {
5549
+ var _process$env$GROQ_API;
5550
+ modelDef = createOpenAICompatibleModel('https://api.groq.com/openai/v1', (_process$env$GROQ_API = process.env.GROQ_API_KEY) != null ? _process$env$GROQ_API : '', 'llama-3.2-90b-text-preview', model.name);
5551
+ } else if (model.type === 'perplexity') {
5552
+ var _process$env$PERPLEXI;
5553
+ modelDef = createOpenAICompatibleModel('https://api.perplexity.ai/', (_process$env$PERPLEXI = process.env.PERPLEXITY_API_KEY) != null ? _process$env$PERPLEXI : '', 'llama-3.1-sonar-large-128k-chat', model.name);
5554
+ } else if (model.type === 'fireworks') {
5555
+ var _process$env$FIREWORK;
5556
+ modelDef = createOpenAICompatibleModel('https://api.fireworks.ai/inference/v1', (_process$env$FIREWORK = process.env.FIREWORKS_API_KEY) != null ? _process$env$FIREWORK : '', 'llama-v3p1-70b-instruct', model.name);
5557
+ }
5558
+ return {
5559
+ toolsConverted: toolsConverted,
5560
+ modelDef: modelDef,
5561
+ answerTool: answerTool,
5562
+ toolChoice: (model == null ? void 0 : model.toolChoice) || 'required'
5563
+ };
5564
+ }
5565
+ function createStreamAgent(_ref3) {
5566
+ var agent_instructions = _ref3.agent_instructions,
5567
+ _ref3$maxSteps = _ref3.maxSteps,
5568
+ maxSteps = _ref3$maxSteps === void 0 ? 5 : _ref3$maxSteps,
5569
+ tools = _ref3.tools,
5570
+ resultTool = _ref3.resultTool,
5571
+ _ref3$context = _ref3.context,
5572
+ context = _ref3$context === void 0 ? [] : _ref3$context,
5573
+ model = _ref3.model;
5574
+ var params = getAgentParams({
5575
+ tools: tools,
5576
+ resultTool: resultTool,
5577
+ model: model
5578
+ });
5579
+ return /*#__PURE__*/function () {
5580
+ var _ref5 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_ref4) {
5581
+ var prompt, argsForExecute;
5582
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
5583
+ while (1) switch (_context2.prev = _context2.next) {
5584
+ case 0:
5585
+ prompt = _ref4.prompt;
5586
+ argsForExecute = {
5587
+ model: params.modelDef,
5588
+ tools: _extends({}, params.toolsConverted, params.answerTool),
5589
+ toolChoice: (params == null ? void 0 : params.toolChoice) || 'required',
5590
+ maxSteps: maxSteps,
5591
+ // system: systemPrompt,
5592
+ onStepFinish: function () {
5593
+ var _onStepFinish = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(props) {
5594
+ var _props$response, _props$response2;
5595
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
5596
+ while (1) switch (_context.prev = _context.next) {
5597
+ case 0:
5598
+ console.log(JSON.stringify(props, null, 2));
5599
+ if (!(props != null && (_props$response = props.response) != null && (_props$response = _props$response.headers) != null && _props$response['x-ratelimit-remaining-tokens'] && parseInt(props == null || (_props$response2 = props.response) == null || (_props$response2 = _props$response2.headers) == null ? void 0 : _props$response2['x-ratelimit-remaining-tokens'], 10) < 2000)) {
5600
+ _context.next = 5;
5601
+ break;
5602
+ }
5603
+ console.log('Rate limit reached, waiting 10 seconds');
5604
+ _context.next = 5;
5605
+ return delay(10 * 1000);
5606
+ case 5:
5607
+ case "end":
5608
+ return _context.stop();
5609
+ }
5610
+ }, _callee);
5611
+ }));
5612
+ function onStepFinish(_x2) {
5613
+ return _onStepFinish.apply(this, arguments);
5614
+ }
5615
+ return onStepFinish;
5616
+ }()
5617
+ };
5618
+ _context2.next = 4;
5619
+ return ai.streamText(_extends({
5620
+ messages: [].concat(context, [{
5621
+ role: 'user',
5622
+ content: prompt
5623
+ }, {
5624
+ role: 'system',
5625
+ content: agent_instructions
5626
+ }])
5627
+ }, argsForExecute));
5628
+ case 4:
5629
+ return _context2.abrupt("return", _context2.sent);
5630
+ case 5:
5631
+ case "end":
5632
+ return _context2.stop();
5633
+ }
5634
+ }, _callee2);
5635
+ }));
5636
+ return function (_x) {
5637
+ return _ref5.apply(this, arguments);
5638
+ };
5639
+ }();
5640
+ }
5641
+ function createAgent(_ref6) {
5642
+ var agent_instructions = _ref6.agent_instructions,
5643
+ _ref6$maxSteps = _ref6.maxSteps,
5644
+ maxSteps = _ref6$maxSteps === void 0 ? 5 : _ref6$maxSteps,
5645
+ tools = _ref6.tools,
5646
+ resultTool = _ref6.resultTool,
5647
+ _ref6$context = _ref6.context,
5648
+ context = _ref6$context === void 0 ? [] : _ref6$context,
5649
+ model = _ref6.model;
5650
+ var params = getAgentParams({
5651
+ tools: tools,
5652
+ resultTool: resultTool,
5653
+ model: model
5654
+ });
5655
+ return /*#__PURE__*/function () {
5656
+ var _ref8 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(_ref7) {
5657
+ var prompt, argsForExecute;
5658
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
5659
+ while (1) switch (_context4.prev = _context4.next) {
5660
+ case 0:
5661
+ prompt = _ref7.prompt;
5662
+ argsForExecute = {
5663
+ model: params.modelDef,
5664
+ tools: _extends({}, params.toolsConverted, params.answerTool),
5665
+ toolChoice: (params == null ? void 0 : params.toolChoice) || 'required',
5666
+ maxSteps: maxSteps,
5667
+ // system: systemPrompt,
5668
+ onStepFinish: function () {
5669
+ var _onStepFinish2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(props) {
5670
+ var _props$response3, _props$response4;
5671
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
5672
+ while (1) switch (_context3.prev = _context3.next) {
5673
+ case 0:
5674
+ console.log(JSON.stringify(props, null, 2));
5675
+ if (!(props != null && (_props$response3 = props.response) != null && (_props$response3 = _props$response3.headers) != null && _props$response3['x-ratelimit-remaining-tokens'] && parseInt(props == null || (_props$response4 = props.response) == null || (_props$response4 = _props$response4.headers) == null ? void 0 : _props$response4['x-ratelimit-remaining-tokens'], 10) < 2000)) {
5676
+ _context3.next = 5;
5677
+ break;
5678
+ }
5679
+ console.log('Rate limit reached, waiting 10 seconds');
5680
+ _context3.next = 5;
5681
+ return delay(10 * 1000);
5682
+ case 5:
5683
+ case "end":
5684
+ return _context3.stop();
5685
+ }
5686
+ }, _callee3);
5687
+ }));
5688
+ function onStepFinish(_x4) {
5689
+ return _onStepFinish2.apply(this, arguments);
5690
+ }
5691
+ return onStepFinish;
5692
+ }()
5693
+ };
5694
+ _context4.next = 4;
5695
+ return ai.generateText(_extends({
5696
+ messages: [].concat(context, [{
5697
+ role: 'user',
5698
+ content: prompt
5699
+ }, {
5700
+ role: 'system',
5701
+ content: agent_instructions
5702
+ }])
5703
+ }, argsForExecute));
5704
+ case 4:
5705
+ return _context4.abrupt("return", _context4.sent);
5706
+ case 5:
5707
+ case "end":
5708
+ return _context4.stop();
5709
+ }
5710
+ }, _callee4);
5711
+ }));
5712
+ return function (_x3) {
5713
+ return _ref8.apply(this, arguments);
5714
+ };
5715
+ }();
5716
+ }
5717
+ function createOpenAICompatibleModel(baseURL, apiKey, defaultModelName, modelName) {
5718
+ var client = openai.createOpenAI({
5719
+ baseURL: baseURL,
5720
+ apiKey: apiKey
5721
+ });
5722
+ return client(modelName || defaultModelName);
5723
+ }
5724
+
5725
+ function getAgent(_x) {
5726
+ return _getAgent.apply(this, arguments);
5727
+ }
5728
+ function _getAgent() {
5729
+ _getAgent = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(_ref) {
5730
+ var connectionId, agent, apis, tools, toolMap, assistant, _agent$model2, keyToModel, _tools, _toolMap, resultTool, schema, _agent$model;
5731
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
5732
+ while (1) switch (_context3.prev = _context3.next) {
5733
+ case 0:
5734
+ connectionId = _ref.connectionId, agent = _ref.agent, apis = _ref.apis;
5735
+ if (!(agent.model.provider === 'OPEN_AI_ASSISTANT')) {
5736
+ _context3.next = 10;
5737
+ break;
5738
+ }
5739
+ tools = Object.keys(agent.tools);
5740
+ toolMap = Object.entries(apis).reduce(function (memo, _ref2) {
5741
+ var k = _ref2[0],
5742
+ def = _ref2[1];
5743
+ if (tools.includes(k)) {
5744
+ memo[k] = /*#__PURE__*/function () {
5745
+ var _ref3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(props) {
5746
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
5747
+ while (1) switch (_context.prev = _context.next) {
5748
+ case 0:
5749
+ return _context.abrupt("return", def.executor({
5750
+ data: props,
5751
+ ctx: {
5752
+ connectionId: connectionId
5753
+ }
5754
+ }));
5755
+ case 1:
5756
+ case "end":
5757
+ return _context.stop();
5758
+ }
5759
+ }, _callee);
5760
+ }));
5761
+ return function (_x2) {
5762
+ return _ref3.apply(this, arguments);
5763
+ };
5764
+ }();
5765
+ }
5766
+ return memo;
5767
+ }, {});
5768
+ _context3.next = 6;
5769
+ return getAssistantAgent({
5770
+ id: agent.id,
5771
+ toolMap: toolMap
5772
+ });
5773
+ case 6:
5774
+ assistant = _context3.sent;
5775
+ return _context3.abrupt("return", assistant);
5776
+ case 10:
5777
+ if (!['OPEN_AI_VERCEL', 'ANTHROPIC_VERCEL', 'GROQ_VERCEL', 'PERPLEXITY_VERCEL', 'FIREWORKS_VERCEL'].includes(agent.model.provider)) {
5778
+ _context3.next = 19;
5779
+ break;
5780
+ }
5781
+ keyToModel = {
5782
+ OPEN_AI_VERCEL: 'openai',
5783
+ ANTHROPIC_VERCEL: 'anthropic',
5784
+ GROQ_VERCEL: 'groq',
5785
+ PERPLEXITY_VERCEL: 'perplexity',
5786
+ FIREWORKS_VERCEL: 'fireworks'
5787
+ };
5788
+ _tools = Object.keys(agent.tools);
5789
+ _toolMap = Object.entries(apis).reduce(function (memo, _ref4) {
5790
+ var k = _ref4[0],
5791
+ def = _ref4[1];
5792
+ if (_tools.includes(k)) {
5793
+ memo[k] = {
5794
+ description: def.label,
5795
+ parameters: def.schema,
5796
+ execute: function () {
5797
+ var _execute = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(props) {
5798
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
5799
+ while (1) switch (_context2.prev = _context2.next) {
5800
+ case 0:
5801
+ return _context2.abrupt("return", def.executor({
5802
+ data: props,
5803
+ ctx: {
5804
+ connectionId: connectionId
5805
+ }
5806
+ }));
5807
+ case 1:
5808
+ case "end":
5809
+ return _context2.stop();
5810
+ }
5811
+ }, _callee2);
5812
+ }));
5813
+ function execute(_x3) {
5814
+ return _execute.apply(this, arguments);
5815
+ }
5816
+ return execute;
5817
+ }()
5818
+ };
5819
+ }
5820
+ return memo;
5821
+ }, {});
5822
+ resultTool = undefined;
5823
+ if (agent.outputs.structured) {
5824
+ schema = Object.entries(agent.outputs.structured.schema).reduce(function (memo, _ref5) {
5825
+ var k = _ref5[0],
5826
+ v = _ref5[1];
5827
+ if (v.type === 'string') {
5828
+ memo[k] = zod.z.string();
5829
+ }
5830
+ if (v.type === 'array') {
5831
+ var _v$items;
5832
+ var itemType = v == null || (_v$items = v.items) == null ? void 0 : _v$items.type;
5833
+ if (itemType === 'string') {
5834
+ memo[k] = zod.z.array(zod.z.string());
5835
+ }
5836
+ }
5837
+ return memo;
5838
+ }, {});
5839
+ resultTool = {
5840
+ description: agent.outputs.structured.description,
5841
+ parameters: zod.z.object(schema)
5842
+ };
5843
+ }
5844
+ if (!(agent.model.generation_type === 'stream')) {
5845
+ _context3.next = 18;
5846
+ break;
5847
+ }
5848
+ return _context3.abrupt("return", createStreamAgent({
5849
+ agent_instructions: agent.agent_instructions,
5850
+ model: {
5851
+ type: keyToModel[agent.model.provider],
5852
+ name: agent.model.name,
5853
+ toolChoice: ((_agent$model = agent.model) == null ? void 0 : _agent$model.toolChoice) || 'required'
5854
+ },
5855
+ tools: _toolMap,
5856
+ resultTool: resultTool
5857
+ }));
5858
+ case 18:
5859
+ return _context3.abrupt("return", createAgent({
5860
+ agent_instructions: agent.agent_instructions,
5861
+ model: {
5862
+ type: keyToModel[agent.model.provider],
5863
+ name: agent.model.name,
5864
+ toolChoice: ((_agent$model2 = agent.model) == null ? void 0 : _agent$model2.toolChoice) || 'required'
5865
+ },
5866
+ tools: _toolMap,
5867
+ resultTool: resultTool
5868
+ }));
5869
+ case 19:
5870
+ case "end":
5871
+ return _context3.stop();
5872
+ }
5873
+ }, _callee3);
5874
+ }));
5875
+ return _getAgent.apply(this, arguments);
5876
+ }
5877
+
5878
+ var Mastra = /*#__PURE__*/function () {
5879
+ function Mastra(_ref) {
5880
+ var _this = this;
5881
+ var dataLayer = _ref.dataLayer,
5882
+ vectorLayer = _ref.vectorLayer,
5883
+ config = _ref.config;
5884
+ //global events grouped by Integration
5885
+ this.globalEvents = new Map();
5886
+ // global apis grouped by Integration
5887
+ this.globalApis = new Map();
5888
+ this.integrations = new Map();
5889
+ this.dataLayer = void 0;
5890
+ this.vectorLayer = void 0;
5891
+ this.agentsConfig = {
5892
+ agentDirPath: '',
5893
+ vectorProvider: []
5894
+ };
5895
+ this.config = void 0;
5896
+ this.runBlueprint = /*#__PURE__*/function () {
5897
+ var _ref3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref2) {
5898
+ var _this$availableIntegr;
5899
+ var blueprint, _ref2$dataCtx, dataCtx, ctx, systemApis, systemEvents, availableIntegrations, availableIntegrationApis, availableIntegrationEvents, frameworkApis, frameworkEvents;
5900
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
5901
+ while (1) switch (_context.prev = _context.next) {
5902
+ case 0:
5903
+ blueprint = _ref2.blueprint, _ref2$dataCtx = _ref2.dataCtx, dataCtx = _ref2$dataCtx === void 0 ? {} : _ref2$dataCtx, ctx = _ref2.ctx;
5904
+ systemApis = _this.getSystemApis();
5905
+ systemEvents = _this.getSystemEvents();
5906
+ availableIntegrations = (_this$availableIntegr = _this.availableIntegrations()) == null ? void 0 : _this$availableIntegr.map(function (_ref4) {
5907
+ var integration = _ref4.integration;
5908
+ return integration;
5909
+ });
5910
+ availableIntegrationApis = availableIntegrations.reduce(function (acc, _ref5) {
5911
+ var name = _ref5.name;
5912
+ var apis = _this.getApisByIntegration(name);
5913
+ return _extends({}, acc, apis);
5914
+ }, {});
5915
+ availableIntegrationEvents = availableIntegrations.reduce(function (acc, _ref6) {
5916
+ var name = _ref6.name;
5917
+ var events = _this.getEventsByIntegration(name);
5918
+ return _extends({}, acc, events);
5919
+ }, {});
5920
+ frameworkApis = _extends({}, systemApis, availableIntegrationApis);
5921
+ frameworkEvents = _extends({}, systemEvents, availableIntegrationEvents);
5922
+ _context.next = 10;
5923
+ return blueprintRunner({
5924
+ dataCtx: dataCtx,
5925
+ blueprint: blueprint,
5926
+ frameworkApis: frameworkApis,
5927
+ frameworkEvents: frameworkEvents,
5928
+ ctx: ctx
5929
+ });
5930
+ case 10:
5931
+ case "end":
5932
+ return _context.stop();
5933
+ }
5934
+ }, _callee);
5935
+ }));
5936
+ return function (_x) {
5937
+ return _ref3.apply(this, arguments);
5938
+ };
5939
+ }();
5940
+ this.dataLayer = dataLayer;
5941
+ this.vectorLayer = vectorLayer;
5942
+ this.config = config;
5943
+ }
5944
+ Mastra.init = function init(config) {
5945
+ var _config$workflows$sys;
5946
+ if (!config.db.uri) {
5947
+ throw new Error('No database config/provider found');
5948
+ }
5949
+ var dataLayer = new DataLayer({
5950
+ url: config.db.uri,
5951
+ provider: config.db.provider
5952
+ });
5953
+ var vectorLayer = new VectorLayer();
5954
+ var framework = new Mastra({
5955
+ config: config,
5956
+ dataLayer: dataLayer,
5957
+ vectorLayer: vectorLayer
5958
+ });
5959
+ // Register integrations
5960
+ config.integrations.forEach(function (integration) {
5961
+ framework.__registerIntgeration(integration);
5962
+ });
5963
+ // Register system apis
5964
+ framework.__registerApis({
5965
+ apis: [].concat(getAgentSystemApis({
5966
+ mastra: framework
5967
+ }), (_config$workflows$sys = config.workflows.systemApis) == null ? void 0 : _config$workflows$sys.map(function (api) {
5968
+ return _extends({}, api, {
5969
+ integrationName: config.name
5970
+ });
5971
+ }), getVectorQueryApis({
5972
+ mastra: framework
5973
+ }))
5974
+ });
5975
+ // Register System events
5976
+ framework.__registerEvents({
5977
+ events: config.workflows.systemEvents
5978
+ });
5979
+ // Register vector sync event
5980
+ framework.__registerEvents({
5981
+ events: {
5982
+ AGENT_VECTOR_SYNC: {
5983
+ label: 'Sync vector data for an agent',
5984
+ description: 'Sync vector data for an agent',
5985
+ schema: zod.z.object({
5986
+ agentId: zod.z.string()
5987
+ }),
5988
+ handler: agentVectorSyncEvent
5989
+ },
5990
+ VECTOR_SYNC: {
5991
+ label: 'Sync vector data',
5992
+ description: 'Sync vector data',
5993
+ schema: zod.z.object({
5994
+ vector_provider: zod.z.string(),
5995
+ entities: zod.z.array(zod.z.object({
5996
+ integration: zod.z.string(),
5997
+ data: zod.z.array(zod.z.object({
5998
+ name: zod.z.string(),
5999
+ fields: zod.z.array(zod.z.string()),
6000
+ syncEvent: zod.z.string(),
6001
+ index: zod.z.string()
6002
+ }))
6003
+ }))
6004
+ }),
6005
+ handler: genericVectorySyncEvent
6006
+ }
6007
+ },
6008
+ integrationName: config.name
6009
+ });
6010
+ // Register agent config
6011
+ framework.agentsConfig = config.agents;
6012
+ return framework;
6013
+ };
6014
+ var _proto = Mastra.prototype;
6015
+ _proto.connectedIntegrations = /*#__PURE__*/function () {
6016
+ var _connectedIntegrations = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(_ref7) {
6017
+ var _this2 = this;
6018
+ var context, ints, connectionChecks;
6019
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
6020
+ while (1) switch (_context3.prev = _context3.next) {
6021
+ case 0:
6022
+ context = _ref7.context;
6023
+ ints = this.availableIntegrations();
6024
+ _context3.next = 4;
6025
+ return Promise.all(ints.map(/*#__PURE__*/function () {
6026
+ var _ref9 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_ref8) {
6027
+ var integration, connection;
6028
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
6029
+ while (1) switch (_context2.prev = _context2.next) {
6030
+ case 0:
6031
+ integration = _ref8.integration;
6032
+ _context2.next = 3;
6033
+ return _this2.dataLayer.getConnection({
6034
+ connectionId: context.connectionId,
6035
+ name: integration.name
6036
+ });
6037
+ case 3:
6038
+ connection = _context2.sent;
6039
+ return _context2.abrupt("return", {
6040
+ integration: integration,
6041
+ connected: !!connection
6042
+ });
6043
+ case 5:
6044
+ case "end":
6045
+ return _context2.stop();
6046
+ }
6047
+ }, _callee2);
6048
+ }));
6049
+ return function (_x3) {
6050
+ return _ref9.apply(this, arguments);
6051
+ };
6052
+ }()));
6053
+ case 4:
6054
+ connectionChecks = _context3.sent;
6055
+ return _context3.abrupt("return", connectionChecks.filter(function (_ref10) {
6056
+ var connected = _ref10.connected;
6057
+ return connected;
6058
+ }).map(function (_ref11) {
6059
+ var integration = _ref11.integration;
6060
+ return integration;
6061
+ }));
6062
+ case 6:
6063
+ case "end":
6064
+ return _context3.stop();
6065
+ }
6066
+ }, _callee3, this);
6067
+ }));
6068
+ function connectedIntegrations(_x2) {
6069
+ return _connectedIntegrations.apply(this, arguments);
6070
+ }
6071
+ return connectedIntegrations;
6072
+ }();
6073
+ _proto.__registerIntgeration = function __registerIntgeration(definition) {
6074
+ var name = definition.name;
6075
+ definition.attachDataLayer({
6076
+ dataLayer: this.dataLayer
6077
+ });
6078
+ var router = this.createRouter();
6079
+ definition.corePresets = {
6080
+ redirectURI: router.makeRedirectURI()
6081
+ };
6082
+ this.integrations.set(name, definition);
6083
+ definition.registerEvents();
6084
+ this.__registerEvents({
6085
+ events: definition.getEvents(),
6086
+ integrationName: name
6087
+ });
6088
+ definition.registerApis();
6089
+ definition._convertApiClientToSystemApis();
6090
+ this.__registerApis({
6091
+ apis: Object.values(definition.getApis()),
6092
+ integrationName: name
6093
+ });
6094
+ };
6095
+ _proto.registerApi = function registerApi(name, api) {
6096
+ var _extends2;
6097
+ var integrationApis = this.globalApis.get(this.config.name) || {};
6098
+ this.globalApis.set(this.config.name, _extends({}, integrationApis, (_extends2 = {}, _extends2[name] = _extends({}, api, {
6099
+ integrationName: this.config.name
6100
+ }), _extends2)));
6101
+ };
6102
+ _proto.registerEvent = function registerEvent(name, event) {
6103
+ var _extends3;
6104
+ var integrationEvents = this.globalEvents.get('SYSTEM') || {};
6105
+ this.globalEvents.set('SYSTEM', _extends({}, integrationEvents, (_extends3 = {}, _extends3[name] = event, _extends3)));
6106
+ };
6107
+ _proto.__registerEvents = function __registerEvents(_ref12) {
6108
+ var events = _ref12.events,
6109
+ _ref12$integrationNam = _ref12.integrationName,
6110
+ integrationName = _ref12$integrationNam === void 0 ? this.config.name : _ref12$integrationNam;
6111
+ var integrationEvents = this.globalEvents.get(integrationName) || {};
6112
+ this.globalEvents.set(integrationName, _extends({}, integrationEvents, events));
6113
+ };
6114
+ _proto.__registerApis = function __registerApis(_ref13) {
6115
+ var apis = _ref13.apis,
6116
+ _ref13$integrationNam = _ref13.integrationName,
6117
+ integrationName = _ref13$integrationNam === void 0 ? this.config.name : _ref13$integrationNam;
6118
+ var integrationApis = this.globalApis.get(integrationName) || {};
6119
+ this.globalApis.set(integrationName, _extends({}, integrationApis, apis.reduce(function (acc, api) {
6120
+ var _extends4;
6121
+ return _extends({}, acc, (_extends4 = {}, _extends4[api.type] = api, _extends4));
6122
+ }, {})));
6123
+ };
6124
+ _proto.availableIntegrations = function availableIntegrations() {
6125
+ return Array.from(this.integrations.entries()).map(function (_ref14) {
6126
+ var name = _ref14[0],
6127
+ integration = _ref14[1];
6128
+ return {
6129
+ name: name,
6130
+ integration: integration
6131
+ };
6132
+ });
6133
+ };
6134
+ _proto.getIntegration = function getIntegration(name) {
6135
+ return this.integrations.get(name);
6136
+ };
6137
+ _proto.getGlobalEvents = function getGlobalEvents() {
6138
+ return this.globalEvents;
6139
+ };
6140
+ _proto.getSystemEvents = function getSystemEvents() {
6141
+ var events = this.globalEvents.get(this.config.name);
6142
+ return events || {};
6143
+ };
6144
+ _proto.getEventsByIntegration = function getEventsByIntegration(name) {
6145
+ return this.globalEvents.get(name);
6146
+ };
6147
+ _proto.getGlobalEventHandlers = function getGlobalEventHandlers() {
6148
+ var _this3 = this;
6149
+ return Array.from(this.globalEvents.entries()).flatMap(function (_ref15) {
6150
+ var integrationName = _ref15[0],
6151
+ events = _ref15[1];
6152
+ var groupedHandlers = Object.keys(events).map(function (eventKey) {
6153
+ var _events$eventKey;
6154
+ var eventHandler = (_events$eventKey = events[eventKey]) == null ? void 0 : _events$eventKey.handler;
6155
+ if (!eventHandler) return null;
6156
+ var isSystemEvent = integrationName === _this3.config.name;
6157
+ var _this3$createRouter = _this3.createRouter(),
6158
+ makeWebhookUrl = _this3$createRouter.makeWebhookUrl;
6159
+ if (isSystemEvent) {
6160
+ return eventHandler({
6161
+ getIntegration: function getIntegration(name) {
6162
+ return _this3.getIntegration(name);
6163
+ },
6164
+ eventKey: eventKey,
6165
+ getVectorProvider: function getVectorProvider(name) {
6166
+ return _this3.agentsConfig.vectorProvider.find(function (provider) {
6167
+ return provider.name === name;
6168
+ });
6169
+ },
6170
+ makeWebhookUrl: makeWebhookUrl
6171
+ });
6172
+ } else {
6173
+ var integration = _this3.getIntegration(integrationName);
6174
+ return eventHandler({
6175
+ integrationInstance: integration,
6176
+ eventKey: eventKey,
6177
+ makeWebhookUrl: makeWebhookUrl
6178
+ });
6179
+ }
6180
+ }).filter(Boolean);
6181
+ return groupedHandlers;
6182
+ });
6183
+ };
6184
+ _proto.getApis = function getApis() {
6185
+ return this.globalApis;
6186
+ };
6187
+ _proto.getSystemApis = function getSystemApis() {
6188
+ return this.globalApis.get(this.config.name);
6189
+ };
6190
+ _proto.getApisByIntegration = function getApisByIntegration(name, includeHidden) {
6191
+ var integrationApis = this.globalApis.get(name);
6192
+ if (includeHidden) {
6193
+ return integrationApis;
6194
+ }
6195
+ return _.omitBy(integrationApis, function (value) {
6196
+ return value.isHidden;
6197
+ });
6198
+ };
6199
+ _proto.authenticatableIntegrations = function authenticatableIntegrations() {
6200
+ return this.availableIntegrations().filter(function (_ref16) {
6201
+ var integration = _ref16.integration;
6202
+ try {
6203
+ integration.getAuthenticator();
6204
+ return true;
6205
+ } catch (e) {
6206
+ return false;
6207
+ }
6208
+ });
6209
+ };
6210
+ _proto.authenticator = function authenticator(name) {
6211
+ var _int = this.getIntegration(name);
6212
+ if (!_int) {
6213
+ throw new Error("No integration exists for " + name);
4491
6214
  }
4492
6215
  return _int.getAuthenticator();
4493
6216
  };
4494
6217
  _proto.connectIntegrationByCredential = /*#__PURE__*/function () {
4495
- var _connectIntegrationByCredential = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(_ref16) {
6218
+ var _connectIntegrationByCredential = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(_ref17) {
4496
6219
  var name, connectionId, credential, authenticator, integration;
4497
6220
  return _regeneratorRuntime().wrap(function _callee4$(_context4) {
4498
6221
  while (1) switch (_context4.prev = _context4.next) {
4499
6222
  case 0:
4500
- name = _ref16.name, connectionId = _ref16.connectionId, credential = _ref16.credential;
6223
+ name = _ref17.name, connectionId = _ref17.connectionId, credential = _ref17.credential;
4501
6224
  authenticator = this.authenticator(name);
4502
6225
  if (authenticator) {
4503
6226
  _context4.next = 4;
@@ -4533,13 +6256,13 @@ var Framework = /*#__PURE__*/function () {
4533
6256
  return connectIntegrationByCredential;
4534
6257
  }();
4535
6258
  _proto.disconnectIntegration = /*#__PURE__*/function () {
4536
- var _disconnectIntegration = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(_ref17) {
6259
+ var _disconnectIntegration = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(_ref18) {
4537
6260
  var _yield$this$dataLayer;
4538
6261
  var name, connectionId, integration, k_id, authenticator;
4539
6262
  return _regeneratorRuntime().wrap(function _callee5$(_context5) {
4540
6263
  while (1) switch (_context5.prev = _context5.next) {
4541
6264
  case 0:
4542
- name = _ref17.name, connectionId = _ref17.connectionId;
6265
+ name = _ref18.name, connectionId = _ref18.connectionId;
4543
6266
  integration = this.getIntegration(name);
4544
6267
  _context5.next = 4;
4545
6268
  return this.dataLayer.getConnection({
@@ -4600,14 +6323,14 @@ var Framework = /*#__PURE__*/function () {
4600
6323
  return disconnectIntegration;
4601
6324
  }();
4602
6325
  _proto.callApi = /*#__PURE__*/function () {
4603
- var _callApi = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(_ref18) {
6326
+ var _callApi = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(_ref19) {
4604
6327
  var _int2$getApis;
4605
- var _ref18$integrationNam, integrationName, api, payload, _this$globalApis$get, _apiExecutor, _int2, apiExecutor;
6328
+ var _ref19$integrationNam, integrationName, api, payload, _this$globalApis$get, _apiExecutor, _int2, apiExecutor;
4606
6329
  return _regeneratorRuntime().wrap(function _callee6$(_context6) {
4607
6330
  while (1) switch (_context6.prev = _context6.next) {
4608
6331
  case 0:
4609
- _ref18$integrationNam = _ref18.integrationName, integrationName = _ref18$integrationNam === void 0 ? this.config.name : _ref18$integrationNam, api = _ref18.api, payload = _ref18.payload;
4610
- if (!(integrationName === this.config.name)) {
6332
+ _ref19$integrationNam = _ref19.integrationName, integrationName = _ref19$integrationNam === void 0 ? this.config.name : _ref19$integrationNam, api = _ref19.api, payload = _ref19.payload;
6333
+ if (!(integrationName === this.config.name || integrationName === 'SYSTEM')) {
4611
6334
  _context6.next = 6;
4612
6335
  break;
4613
6336
  }
@@ -4647,19 +6370,19 @@ var Framework = /*#__PURE__*/function () {
4647
6370
  return callApi;
4648
6371
  }();
4649
6372
  _proto.subscribeEvent = /*#__PURE__*/function () {
4650
- var _subscribeEvent = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(_ref19) {
4651
- var _this$config$runner$u, _this$config$runner, _ref20, _this$config$runner$s, _this$config$runner2;
4652
- var id, _ref19$interval, interval, _ref19$timeout, timeout, inngestApiUrl, inngestApiToken, startTime, _poll;
6373
+ var _subscribeEvent = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(_ref20) {
6374
+ var _this$config$runner$u, _this$config$runner, _ref21, _this$config$runner$s, _this$config$runner2;
6375
+ var id, _ref20$interval, interval, _ref20$timeout, timeout, inngestApiUrl, inngestApiToken, startTime, _poll;
4653
6376
  return _regeneratorRuntime().wrap(function _callee8$(_context8) {
4654
6377
  while (1) switch (_context8.prev = _context8.next) {
4655
6378
  case 0:
4656
- id = _ref19.id, _ref19$interval = _ref19.interval, interval = _ref19$interval === void 0 ? 5000 : _ref19$interval, _ref19$timeout = _ref19.timeout, timeout = _ref19$timeout === void 0 ? 60000 : _ref19$timeout;
6379
+ id = _ref20.id, _ref20$interval = _ref20.interval, interval = _ref20$interval === void 0 ? 5000 : _ref20$interval, _ref20$timeout = _ref20.timeout, timeout = _ref20$timeout === void 0 ? 60000 : _ref20$timeout;
4657
6380
  inngestApiUrl = (_this$config$runner$u = (_this$config$runner = this.config.runner) == null ? void 0 : _this$config$runner.uri) != null ? _this$config$runner$u : process.env.INNGEST_URL;
4658
- inngestApiToken = (_ref20 = (_this$config$runner$s = (_this$config$runner2 = this.config.runner) == null ? void 0 : _this$config$runner2.signingKey) != null ? _this$config$runner$s : process.env.INNGEST_SIGNING_KEY) != null ? _ref20 : '123';
6381
+ inngestApiToken = (_ref21 = (_this$config$runner$s = (_this$config$runner2 = this.config.runner) == null ? void 0 : _this$config$runner2.signingKey) != null ? _this$config$runner$s : process.env.INNGEST_SIGNING_KEY) != null ? _ref21 : '123';
4659
6382
  startTime = Date.now();
4660
6383
  _poll = /*#__PURE__*/function () {
4661
- var _ref21 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {
4662
- var response, _yield$response$json, data, error, lastRun, elapsedTime;
6384
+ var _ref22 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {
6385
+ var response, obj, data, error, lastRun, elapsedTime;
4663
6386
  return _regeneratorRuntime().wrap(function _callee7$(_context7) {
4664
6387
  while (1) switch (_context7.prev = _context7.next) {
4665
6388
  case 0:
@@ -4674,65 +6397,93 @@ var Framework = /*#__PURE__*/function () {
4674
6397
  });
4675
6398
  case 3:
4676
6399
  response = _context7.sent;
6400
+ console.log("Polling for event " + id + "...", response.ok);
4677
6401
  if (!response.ok) {
4678
- _context7.next = 16;
6402
+ _context7.next = 28;
4679
6403
  break;
4680
6404
  }
4681
- _context7.next = 7;
6405
+ _context7.next = 8;
4682
6406
  return response.json();
4683
- case 7:
4684
- _yield$response$json = _context7.sent;
4685
- data = _yield$response$json.data;
4686
- error = _yield$response$json.error;
6407
+ case 8:
6408
+ obj = _context7.sent;
6409
+ console.log({
6410
+ obj: obj
6411
+ });
6412
+ data = obj.data, error = obj.error;
6413
+ console.log("Got data for event " + id + "...", data, error);
4687
6414
  if (!error) {
4688
- _context7.next = 12;
6415
+ _context7.next = 15;
4689
6416
  break;
4690
6417
  }
6418
+ console.error(error);
4691
6419
  return _context7.abrupt("return", null);
4692
- case 12:
6420
+ case 15:
6421
+ if (!((data == null ? void 0 : data.length) === 0)) {
6422
+ _context7.next = 19;
6423
+ break;
6424
+ }
6425
+ _context7.next = 18;
6426
+ return new Promise(function (resolve) {
6427
+ return setTimeout(resolve, interval);
6428
+ });
6429
+ case 18:
6430
+ return _context7.abrupt("return", _poll());
6431
+ case 19:
4693
6432
  lastRun = data == null ? void 0 : data[0];
6433
+ console.log(lastRun);
4694
6434
  if (lastRun) {
4695
- _context7.next = 15;
6435
+ _context7.next = 23;
4696
6436
  break;
4697
6437
  }
4698
6438
  return _context7.abrupt("return", null);
4699
- case 15:
6439
+ case 23:
6440
+ if (!(lastRun.status === 'Running')) {
6441
+ _context7.next = 27;
6442
+ break;
6443
+ }
6444
+ _context7.next = 26;
6445
+ return new Promise(function (resolve) {
6446
+ return setTimeout(resolve, interval);
6447
+ });
6448
+ case 26:
6449
+ return _context7.abrupt("return", _poll());
6450
+ case 27:
4700
6451
  return _context7.abrupt("return", {
4701
6452
  status: lastRun.status,
4702
6453
  startedAt: lastRun.run_started_at,
4703
6454
  endedAt: lastRun.ended_at
4704
6455
  });
4705
- case 16:
4706
- _context7.next = 21;
6456
+ case 28:
6457
+ _context7.next = 33;
4707
6458
  break;
4708
- case 18:
4709
- _context7.prev = 18;
6459
+ case 30:
6460
+ _context7.prev = 30;
4710
6461
  _context7.t0 = _context7["catch"](0);
4711
6462
  console.error("Request failed: " + _context7.t0);
4712
- case 21:
6463
+ case 33:
4713
6464
  // Check if timeout has been reached
4714
6465
  elapsedTime = Date.now() - startTime;
4715
6466
  if (!(elapsedTime >= timeout)) {
4716
- _context7.next = 25;
6467
+ _context7.next = 37;
4717
6468
  break;
4718
6469
  }
4719
6470
  console.log('Polling timeout reached.');
4720
6471
  return _context7.abrupt("return", null);
4721
- case 25:
4722
- _context7.next = 27;
6472
+ case 37:
6473
+ _context7.next = 39;
4723
6474
  return new Promise(function (resolve) {
4724
6475
  return setTimeout(resolve, interval);
4725
6476
  });
4726
- case 27:
6477
+ case 39:
4727
6478
  return _context7.abrupt("return", _poll());
4728
- case 28:
6479
+ case 40:
4729
6480
  case "end":
4730
6481
  return _context7.stop();
4731
6482
  }
4732
- }, _callee7, null, [[0, 18]]);
6483
+ }, _callee7, null, [[0, 30]]);
4733
6484
  }));
4734
6485
  return function poll() {
4735
- return _ref21.apply(this, arguments);
6486
+ return _ref22.apply(this, arguments);
4736
6487
  };
4737
6488
  }();
4738
6489
  return _context8.abrupt("return", _poll());
@@ -4748,13 +6499,13 @@ var Framework = /*#__PURE__*/function () {
4748
6499
  return subscribeEvent;
4749
6500
  }();
4750
6501
  _proto.triggerEvent = /*#__PURE__*/function () {
4751
- var _triggerEvent = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(_ref22) {
4752
- var _this3 = this;
4753
- var key, data, user, _ref22$integrationNam, integrationName, returnObj, integrationEvents, integrationEvent, event, workflowEvent;
6502
+ var _triggerEvent = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(_ref23) {
6503
+ var _this4 = this;
6504
+ var key, data, user, _ref23$integrationNam, integrationName, returnObj, integrationEvents, integrationEvent, event, workflowEvent;
4754
6505
  return _regeneratorRuntime().wrap(function _callee11$(_context11) {
4755
6506
  while (1) switch (_context11.prev = _context11.next) {
4756
6507
  case 0:
4757
- key = _ref22.key, data = _ref22.data, user = _ref22.user, _ref22$integrationNam = _ref22.integrationName, integrationName = _ref22$integrationNam === void 0 ? this.config.name : _ref22$integrationNam;
6508
+ key = _ref23.key, data = _ref23.data, user = _ref23.user, _ref23$integrationNam = _ref23.integrationName, integrationName = _ref23$integrationNam === void 0 ? this.config.name : _ref23$integrationNam;
4758
6509
  _context11.prev = 1;
4759
6510
  returnObj = {
4760
6511
  event: {}
@@ -4774,7 +6525,7 @@ var Framework = /*#__PURE__*/function () {
4774
6525
  throw new Error("No event exists for " + key + " in " + integrationName);
4775
6526
  case 9:
4776
6527
  _context11.next = 11;
4777
- return client.send({
6528
+ return client$1.send({
4778
6529
  name: key,
4779
6530
  data: data,
4780
6531
  user: user
@@ -4785,12 +6536,12 @@ var Framework = /*#__PURE__*/function () {
4785
6536
  subscribe: function () {
4786
6537
  var _subscribe = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(_temp) {
4787
6538
  var _event$ids;
4788
- var _ref23, interval, timeout;
6539
+ var _ref24, interval, timeout;
4789
6540
  return _regeneratorRuntime().wrap(function _callee9$(_context9) {
4790
6541
  while (1) switch (_context9.prev = _context9.next) {
4791
6542
  case 0:
4792
- _ref23 = _temp === void 0 ? {} : _temp, interval = _ref23.interval, timeout = _ref23.timeout;
4793
- return _context9.abrupt("return", _this3.subscribeEvent({
6543
+ _ref24 = _temp === void 0 ? {} : _temp, interval = _ref24.interval, timeout = _ref24.timeout;
6544
+ return _context9.abrupt("return", _this4.subscribeEvent({
4794
6545
  id: (_event$ids = event.ids) == null ? void 0 : _event$ids[0],
4795
6546
  interval: interval,
4796
6547
  timeout: timeout
@@ -4808,7 +6559,7 @@ var Framework = /*#__PURE__*/function () {
4808
6559
  }()
4809
6560
  });
4810
6561
  _context11.next = 15;
4811
- return client.send({
6562
+ return client$1.send({
4812
6563
  name: 'workflow/run-automations',
4813
6564
  data: {
4814
6565
  trigger: key,
@@ -4822,12 +6573,12 @@ var Framework = /*#__PURE__*/function () {
4822
6573
  subscribe: function () {
4823
6574
  var _subscribe2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(_temp2) {
4824
6575
  var _workflowEvent$ids;
4825
- var _ref24, interval, timeout;
6576
+ var _ref25, interval, timeout;
4826
6577
  return _regeneratorRuntime().wrap(function _callee10$(_context10) {
4827
6578
  while (1) switch (_context10.prev = _context10.next) {
4828
6579
  case 0:
4829
- _ref24 = _temp2 === void 0 ? {} : _temp2, interval = _ref24.interval, timeout = _ref24.timeout;
4830
- return _context10.abrupt("return", _this3.subscribeEvent({
6580
+ _ref25 = _temp2 === void 0 ? {} : _temp2, interval = _ref25.interval, timeout = _ref25.timeout;
6581
+ return _context10.abrupt("return", _this4.subscribeEvent({
4831
6582
  id: (_workflowEvent$ids = workflowEvent.ids) == null ? void 0 : _workflowEvent$ids[0],
4832
6583
  interval: interval,
4833
6584
  timeout: timeout
@@ -4864,14 +6615,14 @@ var Framework = /*#__PURE__*/function () {
4864
6615
  _proto.triggerSystemEvent =
4865
6616
  /*#__PURE__*/
4866
6617
  function () {
4867
- var _triggerSystemEvent = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee12(_ref25) {
6618
+ var _triggerSystemEvent = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee12(_ref26) {
4868
6619
  var key, data, user, event, systemEvent;
4869
6620
  return _regeneratorRuntime().wrap(function _callee12$(_context12) {
4870
6621
  while (1) switch (_context12.prev = _context12.next) {
4871
6622
  case 0:
4872
- key = _ref25.key, data = _ref25.data, user = _ref25.user;
6623
+ key = _ref26.key, data = _ref26.data, user = _ref26.user;
4873
6624
  _context12.next = 3;
4874
- return client.send({
6625
+ return client$1.send({
4875
6626
  name: key,
4876
6627
  data: data,
4877
6628
  user: user
@@ -4884,7 +6635,7 @@ var Framework = /*#__PURE__*/function () {
4884
6635
  break;
4885
6636
  }
4886
6637
  _context12.next = 8;
4887
- return client.send({
6638
+ return client$1.send({
4888
6639
  name: 'workflow/run-automations',
4889
6640
  data: {
4890
6641
  trigger: key,
@@ -4907,10 +6658,10 @@ var Framework = /*#__PURE__*/function () {
4907
6658
  }();
4908
6659
  _proto.createRouter = function createRouter() {
4909
6660
  var self = this;
4910
- var makeWebhookUrl = function makeWebhookUrl(_ref26) {
6661
+ var makeWebhookUrl = function makeWebhookUrl(_ref27) {
4911
6662
  var _self$config;
4912
- var event = _ref26.event,
4913
- name = _ref26.name;
6663
+ var event = _ref27.event,
6664
+ name = _ref27.name;
4914
6665
  return encodeURI("" + (self == null || (_self$config = self.config) == null ? void 0 : _self$config.systemHostURL) + self.routes.webhook + "?name=" + name + "&event=" + event);
4915
6666
  };
4916
6667
  var makeRedirectURI = function makeRedirectURI() {
@@ -4940,21 +6691,56 @@ var Framework = /*#__PURE__*/function () {
4940
6691
  registerRoutes: registerRoutes
4941
6692
  };
4942
6693
  };
4943
- return _createClass(Framework, [{
6694
+ _proto.getAgent = /*#__PURE__*/function () {
6695
+ var _getAgent2 = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee13(_ref28) {
6696
+ var connectionId, agentId, agentBlueprint, arrMap, finalApis;
6697
+ return _regeneratorRuntime().wrap(function _callee13$(_context13) {
6698
+ while (1) switch (_context13.prev = _context13.next) {
6699
+ case 0:
6700
+ connectionId = _ref28.connectionId, agentId = _ref28.agentId;
6701
+ _context13.next = 3;
6702
+ return getAgentBlueprint({
6703
+ agentDir: this.config.agents.agentDirPath,
6704
+ agentId: agentId
6705
+ });
6706
+ case 3:
6707
+ agentBlueprint = _context13.sent;
6708
+ arrMap = Array.from(this.getApis());
6709
+ finalApis = arrMap.reduce(function (acc, _ref29) {
6710
+ var v = _ref29[1];
6711
+ return _extends({}, acc, v);
6712
+ }, {});
6713
+ return _context13.abrupt("return", getAgent({
6714
+ connectionId: connectionId,
6715
+ agent: agentBlueprint,
6716
+ apis: finalApis
6717
+ }));
6718
+ case 7:
6719
+ case "end":
6720
+ return _context13.stop();
6721
+ }
6722
+ }, _callee13, this);
6723
+ }));
6724
+ function getAgent$1(_x12) {
6725
+ return _getAgent2.apply(this, arguments);
6726
+ }
6727
+ return getAgent$1;
6728
+ }();
6729
+ return _createClass(Mastra, [{
4944
6730
  key: "routes",
4945
6731
  get: function get() {
4946
- var _this4 = this;
6732
+ var _this5 = this;
4947
6733
  var registry = {
4948
6734
  connect: '/connect',
4949
6735
  callback: '/connect/callback',
4950
6736
  inngest: '/inngest',
4951
6737
  webhook: '/webhook'
4952
6738
  };
4953
- return Object.entries(registry).reduce(function (acc, _ref27) {
4954
- var _extends3;
4955
- var key = _ref27[0],
4956
- value = _ref27[1];
4957
- return _extends({}, acc, (_extends3 = {}, _extends3[key] = "" + _this4.config.routeRegistrationPath + value, _extends3));
6739
+ return Object.entries(registry).reduce(function (acc, _ref30) {
6740
+ var _extends5;
6741
+ var key = _ref30[0],
6742
+ value = _ref30[1];
6743
+ return _extends({}, acc, (_extends5 = {}, _extends5[key] = "" + _this5.config.routeRegistrationPath + value, _extends5));
4958
6744
  }, {});
4959
6745
  }
4960
6746
  }]);
@@ -4962,16 +6748,16 @@ var Framework = /*#__PURE__*/function () {
4962
6748
 
4963
6749
  Object.defineProperty(exports, 'PropertyType', {
4964
6750
  enumerable: true,
4965
- get: function () { return client$1.PropertyType; }
6751
+ get: function () { return client$2.PropertyType; }
4966
6752
  });
4967
6753
  exports.DataLayer = DataLayer;
4968
6754
  exports.FieldTypePrimitiveMap = FieldTypePrimitiveMap;
4969
6755
  exports.FilterOperatorToSQL = FilterOperatorToSQL;
4970
- exports.Framework = Framework;
4971
6756
  exports.Integration = Integration;
4972
6757
  exports.IntegrationAuth = IntegrationAuth;
4973
6758
  exports.IntegrationError = IntegrationError;
4974
6759
  exports.IntegrationFieldTypeEnum = IntegrationFieldTypeEnum;
6760
+ exports.Mastra = Mastra;
4975
6761
  exports.RunStatus = RunStatus;
4976
6762
  exports.SORT_MODE_TO_ABBR = SORT_MODE_TO_ABBR;
4977
6763
  exports.WorkflowStatusEnum = WorkflowStatusEnum;