@mastra/core 0.1.3 → 0.1.5

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 +2143 -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 +2128 -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
package/dist/core.esm.js CHANGED
@@ -11,11 +11,17 @@ import qs from 'qs';
11
11
  import { serve } from 'inngest/next';
12
12
  import path from 'path';
13
13
  import * as fs from 'fs';
14
+ import { readdirSync, readFileSync, existsSync, mkdirSync, writeFileSync } from 'fs';
14
15
  import first from 'lodash-es/first';
15
16
  import last from 'lodash-es/last';
16
17
  import { Inngest } from 'inngest';
17
18
  import { OAuth2Client } from '@badgateway/oauth2-client';
18
- import _, { isEmpty, omit, omitBy } from 'lodash-es';
19
+ import _, { isEmpty, omit, pick, compact, omitBy } from 'lodash-es';
20
+ import { openai, createOpenAI } from '@ai-sdk/openai';
21
+ import { embed, tool, generateText, streamText } from 'ai';
22
+ import { Pinecone } from '@pinecone-database/pinecone';
23
+ import OpenAI from 'openai';
24
+ import { createAnthropic } from '@ai-sdk/anthropic';
19
25
 
20
26
  var WorkflowStatusEnum = {
21
27
  DRAFT: 'DRAFT',
@@ -1841,7 +1847,7 @@ var makeCallback = function makeCallback(framework) {
1841
1847
  };
1842
1848
 
1843
1849
  var APP_ID = 'mastra';
1844
- var client = /*#__PURE__*/new Inngest({
1850
+ var client$1 = /*#__PURE__*/new Inngest({
1845
1851
  id: APP_ID
1846
1852
  });
1847
1853
 
@@ -1948,7 +1954,7 @@ function _getBlueprints() {
1948
1954
  var createWorkflowHandler = function createWorkflowHandler(_ref2) {
1949
1955
  var blueprintDirPath = _ref2.blueprintDirPath,
1950
1956
  runBlueprint = _ref2.runBlueprint;
1951
- return client.createFunction({
1957
+ return client$1.createFunction({
1952
1958
  id: 'workflow-executor',
1953
1959
  retries: 0
1954
1960
  }, {
@@ -2043,18 +2049,35 @@ var makeInngest = function makeInngest(framework) {
2043
2049
  // TODO: hook into framework to add framework functions to the inngest client
2044
2050
  var eventHandlers = framework.getGlobalEventHandlers();
2045
2051
  var globalEventHandlers = eventHandlers.map(function (eh) {
2046
- return client.createFunction({
2052
+ return client$1.createFunction({
2047
2053
  id: eh.id
2048
2054
  }, {
2049
2055
  event: eh.event
2050
- }, eh.executor);
2056
+ }, /*#__PURE__*/function () {
2057
+ var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(props) {
2058
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
2059
+ while (1) switch (_context.prev = _context.next) {
2060
+ case 0:
2061
+ return _context.abrupt("return", eh.executor(_extends({}, props, {
2062
+ mastra: framework
2063
+ })));
2064
+ case 1:
2065
+ case "end":
2066
+ return _context.stop();
2067
+ }
2068
+ }, _callee);
2069
+ }));
2070
+ return function (_x) {
2071
+ return _ref.apply(this, arguments);
2072
+ };
2073
+ }());
2051
2074
  });
2052
2075
  var systemWorkflowHandler = createWorkflowHandler({
2053
2076
  blueprintDirPath: (_framework$config$wor = framework.config.workflows) == null ? void 0 : _framework$config$wor.blueprintDirPath,
2054
2077
  runBlueprint: framework.runBlueprint
2055
2078
  });
2056
2079
  var handler = serve({
2057
- client: client,
2080
+ client: client$1,
2058
2081
  functions: [].concat(globalEventHandlers, [systemWorkflowHandler])
2059
2082
  });
2060
2083
  // @ts-ignore
@@ -2413,19 +2436,6 @@ var Integration = /*#__PURE__*/function () {
2413
2436
  return _ref4.apply(this, arguments);
2414
2437
  };
2415
2438
  }();
2416
- this.getEventHandlers = function (_ref5) {
2417
- var makeWebhookUrl = _ref5.makeWebhookUrl;
2418
- return Object.keys(_this.events).map(function (eventKey) {
2419
- var _this$events$eventKey;
2420
- var eventHandler = (_this$events$eventKey = _this.events[eventKey]) == null ? void 0 : _this$events$eventKey.handler;
2421
- if (!eventHandler) return null;
2422
- return eventHandler({
2423
- integrationInstance: _this,
2424
- eventKey: eventKey,
2425
- makeWebhookUrl: makeWebhookUrl
2426
- });
2427
- }).filter(Boolean);
2428
- };
2429
2439
  if (!(config != null && config.name)) {
2430
2440
  throw new IntegrationError('Integration name must be defined');
2431
2441
  }
@@ -2470,12 +2480,12 @@ var Integration = /*#__PURE__*/function () {
2470
2480
  return getApiClient;
2471
2481
  }();
2472
2482
  _proto.getApi = /*#__PURE__*/function () {
2473
- var _getApi = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(_ref6) {
2483
+ var _getApi = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(_ref5) {
2474
2484
  var connectionId;
2475
2485
  return _regeneratorRuntime().wrap(function _callee5$(_context5) {
2476
2486
  while (1) switch (_context5.prev = _context5.next) {
2477
2487
  case 0:
2478
- connectionId = _ref6.connectionId;
2488
+ connectionId = _ref5.connectionId;
2479
2489
  _context5.next = 3;
2480
2490
  return this.getApiClient({
2481
2491
  connectionId: connectionId
@@ -2499,8 +2509,8 @@ var Integration = /*#__PURE__*/function () {
2499
2509
  _proto.getAuthenticator = function getAuthenticator() {
2500
2510
  throw new IntegrationError('Authenticator not implemented');
2501
2511
  };
2502
- _proto.attachDataLayer = function attachDataLayer(_ref7) {
2503
- var dataLayer = _ref7.dataLayer;
2512
+ _proto.attachDataLayer = function attachDataLayer(_ref6) {
2513
+ var dataLayer = _ref6.dataLayer;
2504
2514
  this.dataLayer = dataLayer;
2505
2515
  };
2506
2516
  _proto.registerApis = function registerApis() {
@@ -2557,14 +2567,14 @@ var Integration = /*#__PURE__*/function () {
2557
2567
  return processWebhookRequest;
2558
2568
  }();
2559
2569
  _proto.triggerEvent = /*#__PURE__*/function () {
2560
- var _triggerEvent = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(_ref8) {
2570
+ var _triggerEvent = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(_ref7) {
2561
2571
  var key, data, user, event;
2562
2572
  return _regeneratorRuntime().wrap(function _callee8$(_context8) {
2563
2573
  while (1) switch (_context8.prev = _context8.next) {
2564
2574
  case 0:
2565
- key = _ref8.key, data = _ref8.data, user = _ref8.user;
2575
+ key = _ref7.key, data = _ref7.data, user = _ref7.user;
2566
2576
  _context8.next = 3;
2567
- return client.send({
2577
+ return client$1.send({
2568
2578
  name: key,
2569
2579
  data: data,
2570
2580
  user: user
@@ -2584,13 +2594,13 @@ var Integration = /*#__PURE__*/function () {
2584
2594
  return triggerEvent;
2585
2595
  }();
2586
2596
  _proto.test = /*#__PURE__*/function () {
2587
- var _test = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(_ref9) {
2597
+ var _test = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(_ref8) {
2588
2598
  var _this$dataLayer;
2589
2599
  var connectionId, connection, _this$config$scopes, authenticator, bearer, desiredScopes, _bearer$scope, actualScopes, isMissingScopes;
2590
2600
  return _regeneratorRuntime().wrap(function _callee9$(_context9) {
2591
2601
  while (1) switch (_context9.prev = _context9.next) {
2592
2602
  case 0:
2593
- connectionId = _ref9.connectionId;
2603
+ connectionId = _ref8.connectionId;
2594
2604
  _context9.next = 3;
2595
2605
  return (_this$dataLayer = this.dataLayer) == null ? void 0 : _this$dataLayer.getConnection({
2596
2606
  connectionId: connectionId,
@@ -2641,7 +2651,7 @@ var Integration = /*#__PURE__*/function () {
2641
2651
  return test;
2642
2652
  }();
2643
2653
  _proto.onConnectionCreated = /*#__PURE__*/function () {
2644
- var _onConnectionCreated = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(_ref10) {
2654
+ var _onConnectionCreated = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(_ref9) {
2645
2655
  return _regeneratorRuntime().wrap(function _callee10$(_context10) {
2646
2656
  while (1) switch (_context10.prev = _context10.next) {
2647
2657
  case 0:
@@ -2657,7 +2667,7 @@ var Integration = /*#__PURE__*/function () {
2657
2667
  return onConnectionCreated;
2658
2668
  }();
2659
2669
  _proto.onDisconnect = /*#__PURE__*/function () {
2660
- var _onDisconnect = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(_ref11) {
2670
+ var _onDisconnect = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(_ref10) {
2661
2671
  return _regeneratorRuntime().wrap(function _callee11$(_context11) {
2662
2672
  while (1) switch (_context11.prev = _context11.next) {
2663
2673
  case 0:
@@ -4047,9 +4057,9 @@ function _runActionsRecursively() {
4047
4057
  data: data
4048
4058
  });
4049
4059
  executorResult = {};
4050
- _ctx = mastraConnectionId ? {
4060
+ _ctx = mastraConnectionId ? _extends({}, ctx, {
4051
4061
  connectionId: mastraConnectionId
4052
- } : ctx;
4062
+ }) : ctx;
4053
4063
  _context2.prev = 46;
4054
4064
  _context2.next = 49;
4055
4065
  return actionExecutor({
@@ -4216,266 +4226,1983 @@ function _blueprintRunner() {
4216
4226
  return _blueprintRunner.apply(this, arguments);
4217
4227
  }
4218
4228
 
4219
- var Framework = /*#__PURE__*/function () {
4220
- function Framework(_ref) {
4221
- var _this = this;
4222
- var dataLayer = _ref.dataLayer,
4223
- config = _ref.config;
4224
- //global events grouped by Integration
4225
- this.globalEvents = new Map();
4226
- // global event handlers
4227
- this.globalEventHandlers = [];
4228
- // global apis grouped by Integration
4229
- this.globalApis = new Map();
4230
- this.integrations = new Map();
4231
- this.dataLayer = void 0;
4232
- this.config = void 0;
4233
- this.runBlueprint = /*#__PURE__*/function () {
4234
- var _ref3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref2) {
4235
- var _this$availableIntegr;
4236
- var blueprint, _ref2$dataCtx, dataCtx, ctx, systemApis, systemEvents, availableIntegrations, availableIntegrationApis, availableIntegrationEvents, frameworkApis, frameworkEvents;
4237
- return _regeneratorRuntime().wrap(function _callee$(_context) {
4238
- while (1) switch (_context.prev = _context.next) {
4239
- case 0:
4240
- blueprint = _ref2.blueprint, _ref2$dataCtx = _ref2.dataCtx, dataCtx = _ref2$dataCtx === void 0 ? {} : _ref2$dataCtx, ctx = _ref2.ctx;
4241
- systemApis = _this.getSystemApis();
4242
- systemEvents = _this.getSystemEvents();
4243
- availableIntegrations = (_this$availableIntegr = _this.availableIntegrations()) == null ? void 0 : _this$availableIntegr.map(function (_ref4) {
4244
- var integration = _ref4.integration;
4245
- return integration;
4246
- });
4247
- availableIntegrationApis = availableIntegrations.reduce(function (acc, _ref5) {
4248
- var name = _ref5.name;
4249
- var apis = _this.getApisByIntegration(name);
4250
- return _extends({}, acc, apis);
4251
- }, {});
4252
- availableIntegrationEvents = availableIntegrations.reduce(function (acc, _ref6) {
4253
- var name = _ref6.name;
4254
- var events = _this.getEventsByIntegration(name);
4255
- return _extends({}, acc, events);
4256
- }, {});
4257
- frameworkApis = _extends({}, systemApis, availableIntegrationApis);
4258
- frameworkEvents = _extends({}, systemEvents, availableIntegrationEvents);
4259
- _context.next = 10;
4260
- return blueprintRunner({
4261
- dataCtx: dataCtx,
4262
- blueprint: blueprint,
4263
- frameworkApis: frameworkApis,
4264
- frameworkEvents: frameworkEvents,
4265
- ctx: ctx
4266
- });
4267
- case 10:
4268
- case "end":
4269
- return _context.stop();
4270
- }
4271
- }, _callee);
4272
- }));
4273
- return function (_x) {
4274
- return _ref3.apply(this, arguments);
4275
- };
4276
- }();
4277
- this.dataLayer = dataLayer;
4278
- this.config = config;
4229
+ function getAgentDir(_ref) {
4230
+ var agentDir = _ref.agentDir;
4231
+ var ARK_APP_DIR = process.env.ARK_APP_DIR || process.cwd();
4232
+ return path.join(ARK_APP_DIR, agentDir);
4233
+ }
4234
+ function listAgentsJson(_ref2) {
4235
+ var agentDir = _ref2.agentDir;
4236
+ var agentDirPath = getAgentDir({
4237
+ agentDir: agentDir
4238
+ });
4239
+ var agents = readdirSync(agentDirPath);
4240
+ return agents;
4241
+ }
4242
+ function getAgentFile(agentFilePath) {
4243
+ try {
4244
+ var fileP = agentFilePath;
4245
+ var fileB = readFileSync(fileP, 'utf8');
4246
+ var json = JSON.parse(fileB);
4247
+ return json;
4248
+ } catch (e) {
4249
+ console.error('No agent blueprint found:', agentFilePath);
4250
+ return;
4279
4251
  }
4280
- Framework.init = function init(config) {
4281
- var _config$workflows$sys;
4282
- if (!config.db.uri) {
4283
- throw new Error('No database config/provider found');
4284
- }
4285
- var dataLayer = new DataLayer({
4286
- url: config.db.uri,
4287
- provider: config.db.provider
4288
- });
4289
- var framework = new Framework({
4290
- config: config,
4291
- dataLayer: dataLayer
4292
- });
4293
- // Register integrations
4294
- config.integrations.forEach(function (integration) {
4295
- framework.__registerIntgeration(integration);
4296
- });
4297
- // Register System apis
4298
- framework.__registerApis({
4299
- apis: (_config$workflows$sys = config.workflows.systemApis) == null ? void 0 : _config$workflows$sys.map(function (api) {
4300
- return _extends({}, api, {
4301
- integrationName: config.name
4302
- });
4303
- })
4304
- });
4305
- // Register System events
4306
- framework.__registerEvents({
4307
- events: config.workflows.systemEvents
4308
- });
4309
- return framework;
4310
- };
4311
- var _proto = Framework.prototype;
4312
- _proto.connectedIntegrations = /*#__PURE__*/function () {
4313
- var _connectedIntegrations = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(_ref7) {
4314
- var _this2 = this;
4315
- var context, ints, connectionChecks;
4316
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
4317
- while (1) switch (_context3.prev = _context3.next) {
4252
+ }
4253
+ function getAgentBlueprint(_ref3) {
4254
+ var agentId = _ref3.agentId,
4255
+ agentDir = _ref3.agentDir;
4256
+ var agentDirPath = getAgentDir({
4257
+ agentDir: agentDir
4258
+ });
4259
+ var agentBlueprintPath = path.join(agentDirPath, agentId + ".json");
4260
+ return getAgentFile(agentBlueprintPath);
4261
+ }
4262
+
4263
+ var VectorLayer = /*#__PURE__*/function () {
4264
+ function VectorLayer() {
4265
+ this.supportedProviders = ['PINECONE'];
4266
+ }
4267
+ var _proto = VectorLayer.prototype;
4268
+ _proto.getPineconeIndexes = /*#__PURE__*/function () {
4269
+ var _getPineconeIndexes = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
4270
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
4271
+ while (1) switch (_context.prev = _context.next) {
4318
4272
  case 0:
4319
- context = _ref7.context;
4320
- ints = this.availableIntegrations();
4321
- _context3.next = 4;
4322
- return Promise.all(ints.map(/*#__PURE__*/function () {
4323
- var _ref9 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_ref8) {
4324
- var integration, connection;
4325
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
4326
- while (1) switch (_context2.prev = _context2.next) {
4327
- case 0:
4328
- integration = _ref8.integration;
4329
- _context2.next = 3;
4330
- return _this2.dataLayer.getConnection({
4331
- connectionId: context.connectionId,
4332
- name: integration.name
4333
- });
4334
- case 3:
4335
- connection = _context2.sent;
4336
- return _context2.abrupt("return", {
4337
- integration: integration,
4338
- connected: !!connection
4339
- });
4340
- case 5:
4341
- case "end":
4342
- return _context2.stop();
4343
- }
4344
- }, _callee2);
4345
- }));
4346
- return function (_x3) {
4347
- return _ref9.apply(this, arguments);
4348
- };
4349
- }()));
4350
- case 4:
4351
- connectionChecks = _context3.sent;
4352
- return _context3.abrupt("return", connectionChecks.filter(function (_ref10) {
4353
- var connected = _ref10.connected;
4354
- return connected;
4355
- }).map(function (_ref11) {
4356
- var integration = _ref11.integration;
4357
- return integration;
4358
- }));
4359
- case 6:
4273
+ return _context.abrupt("return", this.Pinecone.listIndexes());
4274
+ case 1:
4360
4275
  case "end":
4361
- return _context3.stop();
4276
+ return _context.stop();
4362
4277
  }
4363
- }, _callee3, this);
4278
+ }, _callee, this);
4364
4279
  }));
4365
- function connectedIntegrations(_x2) {
4366
- return _connectedIntegrations.apply(this, arguments);
4280
+ function getPineconeIndexes() {
4281
+ return _getPineconeIndexes.apply(this, arguments);
4367
4282
  }
4368
- return connectedIntegrations;
4283
+ return getPineconeIndexes;
4369
4284
  }();
4370
- _proto.__registerIntgeration = function __registerIntgeration(definition) {
4371
- var _this$globalEventHand;
4372
- var name = definition.name;
4373
- definition.attachDataLayer({
4374
- dataLayer: this.dataLayer
4375
- });
4376
- var router = this.createRouter();
4377
- definition.corePresets = {
4378
- redirectURI: router.makeRedirectURI()
4379
- };
4380
- this.integrations.set(name, definition);
4381
- definition.registerEvents();
4382
- this.__registerEvents({
4383
- events: definition.getEvents(),
4384
- integrationName: name
4385
- });
4386
- definition.registerApis();
4387
- definition._convertApiClientToSystemApis();
4388
- this.__registerApis({
4389
- apis: Object.values(definition.getApis()),
4390
- integrationName: name
4391
- });
4392
- (_this$globalEventHand = this.globalEventHandlers).push.apply(_this$globalEventHand, definition.getEventHandlers({
4393
- makeWebhookUrl: router.makeWebhookUrl
4394
- }));
4395
- };
4396
- _proto.__registerEvents = function __registerEvents(_ref12) {
4397
- var events = _ref12.events,
4398
- _ref12$integrationNam = _ref12.integrationName,
4399
- integrationName = _ref12$integrationNam === void 0 ? this.config.name : _ref12$integrationNam;
4400
- var integrationEvents = this.globalEvents.get(integrationName) || {};
4401
- this.globalEvents.set(integrationName, _extends({}, integrationEvents, events));
4402
- };
4403
- _proto.__registerApis = function __registerApis(_ref13) {
4404
- var apis = _ref13.apis,
4405
- _ref13$integrationNam = _ref13.integrationName,
4406
- integrationName = _ref13$integrationNam === void 0 ? this.config.name : _ref13$integrationNam;
4407
- var integrationApis = this.globalApis.get(integrationName) || {};
4408
- this.globalApis.set(integrationName, _extends({}, integrationApis, apis.reduce(function (acc, api) {
4409
- var _extends2;
4410
- return _extends({}, acc, (_extends2 = {}, _extends2[api.type] = api, _extends2));
4411
- }, {})));
4412
- };
4413
- _proto.availableIntegrations = function availableIntegrations() {
4414
- return Array.from(this.integrations.entries()).map(function (_ref14) {
4415
- var name = _ref14[0],
4416
- integration = _ref14[1];
4417
- return {
4418
- name: name,
4419
- integration: integration
4420
- };
4421
- });
4422
- };
4423
- _proto.getIntegration = function getIntegration(name) {
4424
- return this.integrations.get(name);
4425
- };
4426
- _proto.getGlobalEvents = function getGlobalEvents() {
4427
- return this.globalEvents;
4428
- };
4429
- _proto.getSystemEvents = function getSystemEvents() {
4430
- var events = this.globalEvents.get(this.config.name);
4431
- return events || {};
4432
- };
4433
- _proto.getEventsByIntegration = function getEventsByIntegration(name) {
4434
- return this.globalEvents.get(name);
4435
- };
4436
- _proto.getGlobalEventHandlers = function getGlobalEventHandlers() {
4437
- return this.globalEventHandlers;
4438
- };
4439
- _proto.getApis = function getApis() {
4440
- return this.globalApis;
4441
- };
4442
- _proto.getSystemApis = function getSystemApis() {
4443
- return this.globalApis.get(this.config.name);
4444
- };
4445
- _proto.getApisByIntegration = function getApisByIntegration(name, includeHidden) {
4446
- var integrationApis = this.globalApis.get(name);
4447
- if (includeHidden) {
4448
- return integrationApis;
4449
- }
4450
- return omitBy(integrationApis, function (value) {
4451
- return value.isHidden;
4452
- });
4453
- };
4454
- _proto.authenticatableIntegrations = function authenticatableIntegrations() {
4455
- return this.availableIntegrations().filter(function (_ref15) {
4456
- var integration = _ref15.integration;
4457
- try {
4458
- integration.getAuthenticator();
4459
- return true;
4460
- } catch (e) {
4461
- return false;
4285
+ return _createClass(VectorLayer, [{
4286
+ key: "Pinecone",
4287
+ get: function get() {
4288
+ if (!process.env.PINECONE_API_KEY) {
4289
+ throw new Error('Pinecone API key not found');
4462
4290
  }
4463
- });
4464
- };
4465
- _proto.authenticator = function authenticator(name) {
4466
- var _int = this.getIntegration(name);
4467
- if (!_int) {
4468
- throw new Error("No integration exists for " + name);
4291
+ return new Pinecone({
4292
+ apiKey: process.env.PINECONE_API_KEY
4293
+ });
4294
+ }
4295
+ }]);
4296
+ }();
4297
+
4298
+ function getVectorProvider(provider) {
4299
+ if (provider === 'PINECONE') {
4300
+ var _VectorLayer = new VectorLayer(),
4301
+ Pinecone = _VectorLayer.Pinecone;
4302
+ return Pinecone;
4303
+ }
4304
+ }
4305
+ var delay$1 = function delay(ms) {
4306
+ return new Promise(function (resolve) {
4307
+ return setTimeout(resolve, ms);
4308
+ });
4309
+ };
4310
+ function executeGenericVectorSync(_x) {
4311
+ return _executeGenericVectorSync.apply(this, arguments);
4312
+ }
4313
+ function _executeGenericVectorSync() {
4314
+ _executeGenericVectorSync = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(_ref) {
4315
+ var _event$user, _event$data, _event$data2;
4316
+ 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;
4317
+ return _regeneratorRuntime().wrap(function _callee3$(_context4) {
4318
+ while (1) switch (_context4.prev = _context4.next) {
4319
+ case 0:
4320
+ event = _ref.event, mastra = _ref.mastra;
4321
+ connectionId = event == null || (_event$user = event.user) == null ? void 0 : _event$user.connectionId;
4322
+ vector_provider = event == null || (_event$data = event.data) == null ? void 0 : _event$data.vector_provider;
4323
+ entities = event == null || (_event$data2 = event.data) == null ? void 0 : _event$data2.entities;
4324
+ systemName = mastra.config.name;
4325
+ if (vector_provider) {
4326
+ _context4.next = 8;
4327
+ break;
4328
+ }
4329
+ console.error("No vector_provider defined for agent");
4330
+ return _context4.abrupt("return");
4331
+ case 8:
4332
+ vp = getVectorProvider(vector_provider);
4333
+ if (vp) {
4334
+ _context4.next = 12;
4335
+ break;
4336
+ }
4337
+ console.error('UNSUPPORTED VECTOR PROVIDER', vector_provider);
4338
+ return _context4.abrupt("return");
4339
+ case 12:
4340
+ if (process.env.OPENAI_API_KEY) {
4341
+ _context4.next = 15;
4342
+ break;
4343
+ }
4344
+ console.error('NO OPENAI_API_KEY');
4345
+ return _context4.abrupt("return");
4346
+ case 15:
4347
+ _iterator = _createForOfIteratorHelperLoose(entities);
4348
+ case 16:
4349
+ if ((_step = _iterator()).done) {
4350
+ _context4.next = 50;
4351
+ break;
4352
+ }
4353
+ vectorE = _step.value;
4354
+ integrationName = vectorE.integration;
4355
+ _context4.next = 21;
4356
+ return (_mastra$dataLayer = mastra.dataLayer) == null ? void 0 : _mastra$dataLayer.getConnection({
4357
+ connectionId: connectionId,
4358
+ name: integrationName
4359
+ });
4360
+ case 21:
4361
+ _context4.t1 = _yield$mastra$dataLay = _context4.sent;
4362
+ if (!(_context4.t1 == null)) {
4363
+ _context4.next = 26;
4364
+ break;
4365
+ }
4366
+ _context4.t2 = void 0;
4367
+ _context4.next = 27;
4368
+ break;
4369
+ case 26:
4370
+ _context4.t2 = _yield$mastra$dataLay.id;
4371
+ case 27:
4372
+ _context4.t0 = _context4.t2;
4373
+ if (_context4.t0) {
4374
+ _context4.next = 30;
4375
+ break;
4376
+ }
4377
+ _context4.t0 = '';
4378
+ case 30:
4379
+ k_id = _context4.t0;
4380
+ if (!(!k_id && integrationName === systemName)) {
4381
+ _context4.next = 36;
4382
+ break;
4383
+ }
4384
+ _context4.next = 34;
4385
+ return (_mastra$dataLayer2 = mastra.dataLayer) == null ? void 0 : _mastra$dataLayer2.createConnection({
4386
+ connection: {
4387
+ connectionId: connectionId,
4388
+ name: integrationName
4389
+ },
4390
+ credential: {
4391
+ type: 'API_KEY',
4392
+ value: connectionId,
4393
+ scope: []
4394
+ }
4395
+ });
4396
+ case 34:
4397
+ connection = _context4.sent;
4398
+ k_id = connection.id;
4399
+ case 36:
4400
+ if (k_id) {
4401
+ _context4.next = 39;
4402
+ break;
4403
+ }
4404
+ console.error('Error bootstrapping shit');
4405
+ return _context4.abrupt("return");
4406
+ case 39:
4407
+ _loop = /*#__PURE__*/_regeneratorRuntime().mark(function _loop() {
4408
+ var _mastra$dataLayer3, _entityRecords, _records;
4409
+ var entity, entityRecords, records, _mastra$dataLayer4, _entityRecords2, _records2, _yield$mastra$trigger, _event, res, recordsMapped, entityTypeIndex, _recordsMapped$map, vectors;
4410
+ return _regeneratorRuntime().wrap(function _loop$(_context3) {
4411
+ while (1) switch (_context3.prev = _context3.next) {
4412
+ case 0:
4413
+ entity = _step2.value;
4414
+ _context3.next = 3;
4415
+ return (_mastra$dataLayer3 = mastra.dataLayer) == null ? void 0 : _mastra$dataLayer3.getEntityRecordsByConnectionAndType({
4416
+ k_id: k_id,
4417
+ type: entity.name
4418
+ });
4419
+ case 3:
4420
+ entityRecords = _context3.sent;
4421
+ records = (_entityRecords = entityRecords) == null ? void 0 : _entityRecords.records;
4422
+ if (!(!records || ((_records = records) == null ? void 0 : _records.length) === 0)) {
4423
+ _context3.next = 23;
4424
+ break;
4425
+ }
4426
+ // @TODO: SYNC THEM
4427
+ console.error('NO RECORDS');
4428
+ _context3.next = 9;
4429
+ return mastra.triggerEvent({
4430
+ key: entity.syncEvent,
4431
+ data: {},
4432
+ user: {
4433
+ connectionId: connectionId
4434
+ }
4435
+ });
4436
+ case 9:
4437
+ _yield$mastra$trigger = _context3.sent;
4438
+ _event = _yield$mastra$trigger.event;
4439
+ console.log(_event, '####');
4440
+ _context3.next = 14;
4441
+ return _event.subscribe();
4442
+ case 14:
4443
+ res = _context3.sent;
4444
+ console.log('Subscribe result', res);
4445
+ _context3.next = 18;
4446
+ return (_mastra$dataLayer4 = mastra.dataLayer) == null ? void 0 : _mastra$dataLayer4.getEntityRecordsByConnectionAndType({
4447
+ k_id: k_id,
4448
+ type: entity.name
4449
+ });
4450
+ case 18:
4451
+ entityRecords = _context3.sent;
4452
+ records = (_entityRecords2 = entityRecords) == null ? void 0 : _entityRecords2.records;
4453
+ if (!(!records || ((_records2 = records) == null ? void 0 : _records2.length) === 0)) {
4454
+ _context3.next = 23;
4455
+ break;
4456
+ }
4457
+ console.error('NO RECORDS AFTER SYNC');
4458
+ return _context3.abrupt("return", {
4459
+ v: void 0
4460
+ });
4461
+ case 23:
4462
+ recordsMapped = records.map(function (_ref7) {
4463
+ var data = _ref7.data,
4464
+ externalId = _ref7.externalId;
4465
+ return _extends({
4466
+ id: externalId
4467
+ }, pick(data, entity.fields));
4468
+ });
4469
+ console.log(recordsMapped, 'RECORDS');
4470
+ _context3.next = 27;
4471
+ return vp.createIndex({
4472
+ suppressConflicts: true,
4473
+ name: entity.name,
4474
+ dimension: 1536,
4475
+ metric: 'cosine',
4476
+ spec: {
4477
+ serverless: {
4478
+ cloud: 'aws',
4479
+ region: 'us-east-1'
4480
+ }
4481
+ }
4482
+ });
4483
+ case 27:
4484
+ _context3.next = 29;
4485
+ return delay$1(5000);
4486
+ case 29:
4487
+ entityTypeIndex = vp.index(entity.name);
4488
+ console.log(entityTypeIndex, 'INDEX');
4489
+ _context3.prev = 31;
4490
+ _context3.next = 34;
4491
+ return Promise.all((_recordsMapped$map = recordsMapped.map(/*#__PURE__*/function () {
4492
+ var _ref8 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(record) {
4493
+ var _yield$embed, embedding;
4494
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
4495
+ while (1) switch (_context2.prev = _context2.next) {
4496
+ case 0:
4497
+ _context2.next = 2;
4498
+ return embed({
4499
+ model: openai.embedding('text-embedding-3-small'),
4500
+ value: JSON.stringify(record)
4501
+ });
4502
+ case 2:
4503
+ _yield$embed = _context2.sent;
4504
+ embedding = _yield$embed.embedding;
4505
+ return _context2.abrupt("return", {
4506
+ id: record.id,
4507
+ values: embedding,
4508
+ metadata: record
4509
+ });
4510
+ case 5:
4511
+ case "end":
4512
+ return _context2.stop();
4513
+ }
4514
+ }, _callee2);
4515
+ }));
4516
+ return function (_x5) {
4517
+ return _ref8.apply(this, arguments);
4518
+ };
4519
+ }())) != null ? _recordsMapped$map : []);
4520
+ case 34:
4521
+ vectors = _context3.sent;
4522
+ console.log('UPSERTING', vectors);
4523
+ if (!(vectors.length > 0)) {
4524
+ _context3.next = 39;
4525
+ break;
4526
+ }
4527
+ _context3.next = 39;
4528
+ return entityTypeIndex.namespace(entity.name).upsert(vectors);
4529
+ case 39:
4530
+ _context3.next = 44;
4531
+ break;
4532
+ case 41:
4533
+ _context3.prev = 41;
4534
+ _context3.t0 = _context3["catch"](31);
4535
+ console.error(_context3.t0);
4536
+ case 44:
4537
+ return _context3.abrupt("return", {
4538
+ v: void 0
4539
+ });
4540
+ case 45:
4541
+ case "end":
4542
+ return _context3.stop();
4543
+ }
4544
+ }, _loop, null, [[31, 41]]);
4545
+ });
4546
+ _iterator2 = _createForOfIteratorHelperLoose(vectorE.data);
4547
+ case 41:
4548
+ if ((_step2 = _iterator2()).done) {
4549
+ _context4.next = 48;
4550
+ break;
4551
+ }
4552
+ return _context4.delegateYield(_loop(), "t3", 43);
4553
+ case 43:
4554
+ _ret = _context4.t3;
4555
+ if (!_ret) {
4556
+ _context4.next = 46;
4557
+ break;
4558
+ }
4559
+ return _context4.abrupt("return", _ret.v);
4560
+ case 46:
4561
+ _context4.next = 41;
4562
+ break;
4563
+ case 48:
4564
+ _context4.next = 16;
4565
+ break;
4566
+ case 50:
4567
+ case "end":
4568
+ return _context4.stop();
4569
+ }
4570
+ }, _callee3);
4571
+ }));
4572
+ return _executeGenericVectorSync.apply(this, arguments);
4573
+ }
4574
+ function executeVectorSync(_x2) {
4575
+ return _executeVectorSync.apply(this, arguments);
4576
+ }
4577
+ function _executeVectorSync() {
4578
+ _executeVectorSync = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(_ref2) {
4579
+ var _event$user2, _agent$knowledge_sour3;
4580
+ 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;
4581
+ return _regeneratorRuntime().wrap(function _callee5$(_context7) {
4582
+ while (1) switch (_context7.prev = _context7.next) {
4583
+ case 0:
4584
+ event = _ref2.event, mastra = _ref2.mastra;
4585
+ agentDir = mastra.config.agents.agentDirPath;
4586
+ agent = getAgentBlueprint({
4587
+ agentDir: agentDir,
4588
+ agentId: event.data.agentId
4589
+ });
4590
+ connectionId = event == null || (_event$user2 = event.user) == null ? void 0 : _event$user2.connectionId;
4591
+ systemName = mastra.config.name;
4592
+ if (agent.knowledge_sources.vector_provider) {
4593
+ _context7.next = 8;
4594
+ break;
4595
+ }
4596
+ console.error("No vector_provider defined for agent");
4597
+ return _context7.abrupt("return");
4598
+ case 8:
4599
+ vp = getVectorProvider(agent == null || (_agent$knowledge_sour3 = agent.knowledge_sources) == null ? void 0 : _agent$knowledge_sour3.vector_provider);
4600
+ if (vp) {
4601
+ _context7.next = 12;
4602
+ break;
4603
+ }
4604
+ console.error('UNSUPPORTED VECTOR PROVIDER', agent == null || (_agent$knowledge_sour4 = agent.knowledge_sources) == null ? void 0 : _agent$knowledge_sour4.vector_provider);
4605
+ return _context7.abrupt("return");
4606
+ case 12:
4607
+ if (process.env.OPENAI_API_KEY) {
4608
+ _context7.next = 15;
4609
+ break;
4610
+ }
4611
+ console.error('NO OPENAI_API_KEY');
4612
+ return _context7.abrupt("return");
4613
+ case 15:
4614
+ if (!(!agent || !(agent != null && agent.knowledge_sources))) {
4615
+ _context7.next = 18;
4616
+ break;
4617
+ }
4618
+ console.error('NO AGENT OR KNOWLEDGE SOURCES');
4619
+ return _context7.abrupt("return");
4620
+ case 18:
4621
+ _iterator3 = _createForOfIteratorHelperLoose(agent.knowledge_sources.entities);
4622
+ case 19:
4623
+ if ((_step3 = _iterator3()).done) {
4624
+ _context7.next = 53;
4625
+ break;
4626
+ }
4627
+ vectorE = _step3.value;
4628
+ integrationName = vectorE.integration;
4629
+ _context7.next = 24;
4630
+ return (_mastra$dataLayer5 = mastra.dataLayer) == null ? void 0 : _mastra$dataLayer5.getConnection({
4631
+ connectionId: connectionId,
4632
+ name: integrationName
4633
+ });
4634
+ case 24:
4635
+ _context7.t1 = _yield$mastra$dataLay2 = _context7.sent;
4636
+ if (!(_context7.t1 == null)) {
4637
+ _context7.next = 29;
4638
+ break;
4639
+ }
4640
+ _context7.t2 = void 0;
4641
+ _context7.next = 30;
4642
+ break;
4643
+ case 29:
4644
+ _context7.t2 = _yield$mastra$dataLay2.id;
4645
+ case 30:
4646
+ _context7.t0 = _context7.t2;
4647
+ if (_context7.t0) {
4648
+ _context7.next = 33;
4649
+ break;
4650
+ }
4651
+ _context7.t0 = '';
4652
+ case 33:
4653
+ k_id = _context7.t0;
4654
+ if (!(!k_id && integrationName === systemName)) {
4655
+ _context7.next = 39;
4656
+ break;
4657
+ }
4658
+ _context7.next = 37;
4659
+ return (_mastra$dataLayer6 = mastra.dataLayer) == null ? void 0 : _mastra$dataLayer6.createConnection({
4660
+ connection: {
4661
+ connectionId: connectionId,
4662
+ name: integrationName
4663
+ },
4664
+ credential: {
4665
+ type: 'API_KEY',
4666
+ value: connectionId,
4667
+ scope: []
4668
+ }
4669
+ });
4670
+ case 37:
4671
+ connection = _context7.sent;
4672
+ k_id = connection.id;
4673
+ case 39:
4674
+ if (k_id) {
4675
+ _context7.next = 42;
4676
+ break;
4677
+ }
4678
+ console.error('Error bootstrapping shit');
4679
+ return _context7.abrupt("return");
4680
+ case 42:
4681
+ _loop2 = /*#__PURE__*/_regeneratorRuntime().mark(function _loop2() {
4682
+ var _mastra$dataLayer7, _entityRecords3, _records3;
4683
+ var entity, entityRecords, records, _mastra$dataLayer8, _entityRecords4, _records4, _yield$mastra$trigger2, _event2, res, recordsMapped, entityTypeIndex, _recordsMapped$map2, vectors;
4684
+ return _regeneratorRuntime().wrap(function _loop2$(_context6) {
4685
+ while (1) switch (_context6.prev = _context6.next) {
4686
+ case 0:
4687
+ entity = _step4.value;
4688
+ _context6.next = 3;
4689
+ return (_mastra$dataLayer7 = mastra.dataLayer) == null ? void 0 : _mastra$dataLayer7.getEntityRecordsByConnectionAndType({
4690
+ k_id: k_id,
4691
+ type: entity.name
4692
+ });
4693
+ case 3:
4694
+ entityRecords = _context6.sent;
4695
+ records = (_entityRecords3 = entityRecords) == null ? void 0 : _entityRecords3.records;
4696
+ if (!(!records || ((_records3 = records) == null ? void 0 : _records3.length) === 0)) {
4697
+ _context6.next = 23;
4698
+ break;
4699
+ }
4700
+ // @TODO: SYNC THEM
4701
+ console.error('NO RECORDS');
4702
+ _context6.next = 9;
4703
+ return mastra.triggerEvent({
4704
+ key: entity.syncEvent,
4705
+ data: {},
4706
+ user: {
4707
+ connectionId: connectionId
4708
+ }
4709
+ });
4710
+ case 9:
4711
+ _yield$mastra$trigger2 = _context6.sent;
4712
+ _event2 = _yield$mastra$trigger2.event;
4713
+ console.log(_event2, '####');
4714
+ _context6.next = 14;
4715
+ return _event2.subscribe();
4716
+ case 14:
4717
+ res = _context6.sent;
4718
+ console.log('Subscribe result', res);
4719
+ _context6.next = 18;
4720
+ return (_mastra$dataLayer8 = mastra.dataLayer) == null ? void 0 : _mastra$dataLayer8.getEntityRecordsByConnectionAndType({
4721
+ k_id: k_id,
4722
+ type: entity.name
4723
+ });
4724
+ case 18:
4725
+ entityRecords = _context6.sent;
4726
+ records = (_entityRecords4 = entityRecords) == null ? void 0 : _entityRecords4.records;
4727
+ if (!(!records || ((_records4 = records) == null ? void 0 : _records4.length) === 0)) {
4728
+ _context6.next = 23;
4729
+ break;
4730
+ }
4731
+ console.error('NO RECORDS AFTER SYNC');
4732
+ return _context6.abrupt("return", {
4733
+ v: void 0
4734
+ });
4735
+ case 23:
4736
+ recordsMapped = records.map(function (_ref9) {
4737
+ var data = _ref9.data,
4738
+ externalId = _ref9.externalId;
4739
+ return _extends({
4740
+ id: externalId
4741
+ }, pick(data, entity.fields));
4742
+ });
4743
+ console.log(recordsMapped, 'RECORDS');
4744
+ _context6.next = 27;
4745
+ return vp.createIndex({
4746
+ suppressConflicts: true,
4747
+ name: entity.name,
4748
+ dimension: 1536,
4749
+ metric: 'cosine',
4750
+ spec: {
4751
+ serverless: {
4752
+ cloud: 'aws',
4753
+ region: 'us-east-1'
4754
+ }
4755
+ }
4756
+ });
4757
+ case 27:
4758
+ entityTypeIndex = vp.index(entity.name);
4759
+ console.log(entityTypeIndex, 'INDEX');
4760
+ _context6.prev = 29;
4761
+ _context6.next = 32;
4762
+ return Promise.all((_recordsMapped$map2 = recordsMapped.map(/*#__PURE__*/function () {
4763
+ var _ref10 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(record) {
4764
+ var _yield$embed2, embedding;
4765
+ return _regeneratorRuntime().wrap(function _callee4$(_context5) {
4766
+ while (1) switch (_context5.prev = _context5.next) {
4767
+ case 0:
4768
+ _context5.next = 2;
4769
+ return embed({
4770
+ model: openai.embedding('text-embedding-3-small'),
4771
+ value: JSON.stringify(record)
4772
+ });
4773
+ case 2:
4774
+ _yield$embed2 = _context5.sent;
4775
+ embedding = _yield$embed2.embedding;
4776
+ return _context5.abrupt("return", {
4777
+ id: record.id,
4778
+ values: embedding,
4779
+ metadata: record
4780
+ });
4781
+ case 5:
4782
+ case "end":
4783
+ return _context5.stop();
4784
+ }
4785
+ }, _callee4);
4786
+ }));
4787
+ return function (_x6) {
4788
+ return _ref10.apply(this, arguments);
4789
+ };
4790
+ }())) != null ? _recordsMapped$map2 : []);
4791
+ case 32:
4792
+ vectors = _context6.sent;
4793
+ console.log('UPSERTING', vectors);
4794
+ if (!(vectors.length > 0)) {
4795
+ _context6.next = 37;
4796
+ break;
4797
+ }
4798
+ _context6.next = 37;
4799
+ return entityTypeIndex.namespace(entity.name).upsert(vectors);
4800
+ case 37:
4801
+ _context6.next = 42;
4802
+ break;
4803
+ case 39:
4804
+ _context6.prev = 39;
4805
+ _context6.t0 = _context6["catch"](29);
4806
+ console.error(_context6.t0);
4807
+ case 42:
4808
+ return _context6.abrupt("return", {
4809
+ v: void 0
4810
+ });
4811
+ case 43:
4812
+ case "end":
4813
+ return _context6.stop();
4814
+ }
4815
+ }, _loop2, null, [[29, 39]]);
4816
+ });
4817
+ _iterator4 = _createForOfIteratorHelperLoose(vectorE.data);
4818
+ case 44:
4819
+ if ((_step4 = _iterator4()).done) {
4820
+ _context7.next = 51;
4821
+ break;
4822
+ }
4823
+ return _context7.delegateYield(_loop2(), "t3", 46);
4824
+ case 46:
4825
+ _ret2 = _context7.t3;
4826
+ if (!_ret2) {
4827
+ _context7.next = 49;
4828
+ break;
4829
+ }
4830
+ return _context7.abrupt("return", _ret2.v);
4831
+ case 49:
4832
+ _context7.next = 44;
4833
+ break;
4834
+ case 51:
4835
+ _context7.next = 19;
4836
+ break;
4837
+ case 53:
4838
+ case "end":
4839
+ return _context7.stop();
4840
+ }
4841
+ }, _callee5);
4842
+ }));
4843
+ return _executeVectorSync.apply(this, arguments);
4844
+ }
4845
+ function vectorQueryEngine(_x3) {
4846
+ return _vectorQueryEngine.apply(this, arguments);
4847
+ }
4848
+ function _vectorQueryEngine() {
4849
+ _vectorQueryEngine = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(_ref3) {
4850
+ var vector_provider, _ref3$topK, topK, indexName, content, entityType, vp, index, _yield$embed3, embedding, queryResponse;
4851
+ return _regeneratorRuntime().wrap(function _callee6$(_context8) {
4852
+ while (1) switch (_context8.prev = _context8.next) {
4853
+ case 0:
4854
+ 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;
4855
+ vp = getVectorProvider(vector_provider);
4856
+ if (vp) {
4857
+ _context8.next = 5;
4858
+ break;
4859
+ }
4860
+ console.error('UNSUPPORTED VECTOR PROVIDER', vector_provider);
4861
+ return _context8.abrupt("return");
4862
+ case 5:
4863
+ index = vp.index(indexName);
4864
+ _context8.next = 8;
4865
+ return embed({
4866
+ model: openai.embedding('text-embedding-3-small'),
4867
+ value: content
4868
+ });
4869
+ case 8:
4870
+ _yield$embed3 = _context8.sent;
4871
+ embedding = _yield$embed3.embedding;
4872
+ console.log(embedding, 'EMBEDDING');
4873
+ _context8.next = 13;
4874
+ return index.namespace(entityType).query({
4875
+ vector: embedding,
4876
+ topK: topK,
4877
+ includeMetadata: true
4878
+ });
4879
+ case 13:
4880
+ queryResponse = _context8.sent;
4881
+ return _context8.abrupt("return", queryResponse);
4882
+ case 15:
4883
+ case "end":
4884
+ return _context8.stop();
4885
+ }
4886
+ }, _callee6);
4887
+ }));
4888
+ return _vectorQueryEngine.apply(this, arguments);
4889
+ }
4890
+ function getVectorQueryApis(_ref4) {
4891
+ var mastra = _ref4.mastra;
4892
+ var agentDir = mastra.config.agents.agentDirPath;
4893
+ var agents = listAgentsJson({
4894
+ agentDir: agentDir
4895
+ });
4896
+ var agentData = agents.map(function (agentFile) {
4897
+ var _agent$knowledge_sour;
4898
+ var agentDirPath = getAgentDir({
4899
+ agentDir: agentDir
4900
+ });
4901
+ var agent = getAgentFile(path.join(agentDirPath, agentFile));
4902
+ if (!(agent != null && (_agent$knowledge_sour = agent.knowledge_sources) != null && _agent$knowledge_sour.vector_provider)) {
4903
+ console.error("No vector_provider defined for agent");
4904
+ return;
4905
+ }
4906
+ return agent;
4907
+ }).filter(Boolean);
4908
+ return agentData.flatMap(function (agent) {
4909
+ var entities = agent == null ? void 0 : agent.knowledge_sources.entities;
4910
+ return entities.flatMap(function (_ref5) {
4911
+ var data = _ref5.data,
4912
+ integration = _ref5.integration;
4913
+ return data.map(function (entity) {
4914
+ return {
4915
+ integrationName: integration,
4916
+ type: "get_" + entity.name + "_from_vector_" + entity.index,
4917
+ label: "Provides " + entity.name + " information from Vector " + entity.index + " Store",
4918
+ description: "Provides " + entity.name + " information from Vector " + entity.index + " Store",
4919
+ schema: z.object({
4920
+ content: z.string(),
4921
+ topResult: z.number()
4922
+ }),
4923
+ executor: function () {
4924
+ var _executor = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref6) {
4925
+ var _agent$knowledge_sour2;
4926
+ var data, res;
4927
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
4928
+ while (1) switch (_context.prev = _context.next) {
4929
+ case 0:
4930
+ data = _ref6.data;
4931
+ _context.next = 3;
4932
+ return vectorQueryEngine({
4933
+ vector_provider: agent == null || (_agent$knowledge_sour2 = agent.knowledge_sources) == null ? void 0 : _agent$knowledge_sour2.vector_provider,
4934
+ indexName: entity.index,
4935
+ content: data.content,
4936
+ topK: data.topResult || 1,
4937
+ entityType: entity.name
4938
+ });
4939
+ case 3:
4940
+ res = _context.sent;
4941
+ console.log(JSON.stringify({
4942
+ res: res
4943
+ }, null, 2));
4944
+ // @TODO: make this a proper response
4945
+ return _context.abrupt("return", res);
4946
+ case 6:
4947
+ case "end":
4948
+ return _context.stop();
4949
+ }
4950
+ }, _callee);
4951
+ }));
4952
+ function executor(_x4) {
4953
+ return _executor.apply(this, arguments);
4954
+ }
4955
+ return executor;
4956
+ }()
4957
+ };
4958
+ });
4959
+ });
4960
+ }).filter(Boolean);
4961
+ }
4962
+ function agentVectorSyncEvent() {
4963
+ return {
4964
+ // @TODO: naming convention
4965
+ id: 'agent-vector-sync',
4966
+ event: 'AGENT_VECTOR_SYNC',
4967
+ executor: executeVectorSync
4968
+ };
4969
+ }
4970
+ function genericVectorySyncEvent() {
4971
+ return {
4972
+ // @TODO: naming convention
4973
+ id: 'vector-sync',
4974
+ event: 'VECTOR_SYNC',
4975
+ executor: executeGenericVectorSync
4976
+ };
4977
+ }
4978
+
4979
+ function getAgentSystemApis(_ref) {
4980
+ var mastra = _ref.mastra;
4981
+ var agentDir = mastra.config.agents.agentDirPath;
4982
+ var agents = listAgentsJson({
4983
+ agentDir: agentDir
4984
+ });
4985
+ // Remove the .json extension from the agent names
4986
+ var agentList = agents.map(function (agent) {
4987
+ return agent.slice(0, -5);
4988
+ });
4989
+ return [{
4990
+ integrationName: 'SYSTEM',
4991
+ type: 'message_agent',
4992
+ label: 'Send Message To Agent',
4993
+ description: 'Sends a message to an Agent',
4994
+ schema: z.object({
4995
+ agentId: z["enum"](agentList),
4996
+ message: z.string()
4997
+ }),
4998
+ outputSchema: z.object({
4999
+ message: z.string()
5000
+ }),
5001
+ executor: function () {
5002
+ var _executor = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref2) {
5003
+ var data, executor, result, _run$content, thread, run;
5004
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
5005
+ while (1) switch (_context.prev = _context.next) {
5006
+ case 0:
5007
+ data = _ref2.data;
5008
+ _context.next = 3;
5009
+ return mastra.getAgent({
5010
+ agentId: data.agentId,
5011
+ connectionId: data.connectionId
5012
+ });
5013
+ case 3:
5014
+ executor = _context.sent;
5015
+ if (executor) {
5016
+ _context.next = 6;
5017
+ break;
5018
+ }
5019
+ throw new Error('Could not create agent executor');
5020
+ case 6:
5021
+ if (!(typeof executor === 'function')) {
5022
+ _context.next = 13;
5023
+ break;
5024
+ }
5025
+ _context.next = 9;
5026
+ return executor({
5027
+ prompt: data == null ? void 0 : data.message
5028
+ });
5029
+ case 9:
5030
+ result = _context.sent;
5031
+ return _context.abrupt("return", {
5032
+ message: result == null ? void 0 : result.text
5033
+ });
5034
+ case 13:
5035
+ _context.next = 15;
5036
+ return executor.initializeThread([{
5037
+ role: 'user',
5038
+ content: data == null ? void 0 : data.message
5039
+ }]);
5040
+ case 15:
5041
+ thread = _context.sent;
5042
+ _context.next = 18;
5043
+ return executor.watchRun({
5044
+ threadId: thread.id
5045
+ });
5046
+ case 18:
5047
+ run = _context.sent;
5048
+ return _context.abrupt("return", {
5049
+ 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
5050
+ });
5051
+ case 20:
5052
+ case "end":
5053
+ return _context.stop();
5054
+ }
5055
+ }, _callee);
5056
+ }));
5057
+ function executor(_x) {
5058
+ return _executor.apply(this, arguments);
5059
+ }
5060
+ return executor;
5061
+ }()
5062
+ }];
5063
+ }
5064
+
5065
+ var loggerPath = /*#__PURE__*/path.join(/*#__PURE__*/process.cwd(), 'mastra-agent-logs');
5066
+ function createFileLogger(_ref) {
5067
+ var destinationPath = _ref.destinationPath;
5068
+ var fullPath = path.join(loggerPath, destinationPath);
5069
+ return function (log) {
5070
+ if (!existsSync(loggerPath)) {
5071
+ mkdirSync(loggerPath, {
5072
+ recursive: true
5073
+ });
5074
+ return writeFileSync(fullPath, JSON.stringify([_extends({}, log, {
5075
+ createdAt: new Date()
5076
+ })], null, 2));
5077
+ }
5078
+ var logs = JSON.parse(readFileSync(fullPath, 'utf-8'));
5079
+ logs.push(_extends({}, log, {
5080
+ createdAt: new Date()
5081
+ }));
5082
+ return writeFileSync(fullPath, JSON.stringify(logs, null, 2));
5083
+ };
5084
+ }
5085
+
5086
+ var client;
5087
+ if (process.env.OPENAI_API_KEY) {
5088
+ client = /*#__PURE__*/new OpenAI({
5089
+ apiKey: process.env.OPENAI_API_KEY
5090
+ });
5091
+ }
5092
+ function getAssistantAgent(_x3) {
5093
+ return _getAssistantAgent.apply(this, arguments);
5094
+ }
5095
+ function _getAssistantAgent() {
5096
+ _getAssistantAgent = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(_ref3) {
5097
+ var id, toolMap, logger, agent, handleRunStatus, handleRequiresAction, getRun;
5098
+ return _regeneratorRuntime().wrap(function _callee11$(_context11) {
5099
+ while (1) switch (_context11.prev = _context11.next) {
5100
+ case 0:
5101
+ id = _ref3.id, toolMap = _ref3.toolMap;
5102
+ logger = createFileLogger({
5103
+ destinationPath: id + ".json"
5104
+ });
5105
+ _context11.next = 4;
5106
+ return client.beta.assistants.retrieve(id);
5107
+ case 4:
5108
+ agent = _context11.sent;
5109
+ handleRunStatus = /*#__PURE__*/function () {
5110
+ var _ref5 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(_ref4) {
5111
+ var threadId, run, _messages$data, messages;
5112
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
5113
+ while (1) switch (_context3.prev = _context3.next) {
5114
+ case 0:
5115
+ threadId = _ref4.threadId, run = _ref4.run;
5116
+ if (!(run.status === 'completed')) {
5117
+ _context3.next = 8;
5118
+ break;
5119
+ }
5120
+ _context3.next = 4;
5121
+ return client.beta.threads.messages.list(threadId);
5122
+ case 4:
5123
+ messages = _context3.sent;
5124
+ return _context3.abrupt("return", (_messages$data = messages.data) == null ? void 0 : _messages$data[0]);
5125
+ case 8:
5126
+ if (!(run.status === 'requires_action')) {
5127
+ _context3.next = 14;
5128
+ break;
5129
+ }
5130
+ _context3.next = 11;
5131
+ return handleRequiresAction({
5132
+ run: run,
5133
+ threadId: threadId
5134
+ });
5135
+ case 11:
5136
+ return _context3.abrupt("return", _context3.sent);
5137
+ case 14:
5138
+ console.error('Run did not complete:', run);
5139
+ logger({
5140
+ statusCode: 400,
5141
+ message: JSON.stringify({
5142
+ message: "Run did not complete",
5143
+ event_type: 'run_error',
5144
+ metadata: {
5145
+ run: run
5146
+ }
5147
+ }, null, 2)
5148
+ });
5149
+ case 16:
5150
+ case "end":
5151
+ return _context3.stop();
5152
+ }
5153
+ }, _callee3);
5154
+ }));
5155
+ return function handleRunStatus(_x4) {
5156
+ return _ref5.apply(this, arguments);
5157
+ };
5158
+ }();
5159
+ handleRequiresAction = /*#__PURE__*/function () {
5160
+ var _ref7 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(_ref6) {
5161
+ var threadId, run, toolOutputs;
5162
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
5163
+ while (1) switch (_context5.prev = _context5.next) {
5164
+ case 0:
5165
+ threadId = _ref6.threadId, run = _ref6.run;
5166
+ if (!(run.required_action && run.required_action.submit_tool_outputs && run.required_action.submit_tool_outputs.tool_calls)) {
5167
+ _context5.next = 23;
5168
+ break;
5169
+ }
5170
+ _context5.t0 = compact;
5171
+ _context5.next = 5;
5172
+ return Promise.all(run.required_action.submit_tool_outputs.tool_calls.map(/*#__PURE__*/function () {
5173
+ var _ref8 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(tool, index, tools) {
5174
+ var callInfo, toolMetadata, toolFn, args, output;
5175
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
5176
+ while (1) switch (_context4.prev = _context4.next) {
5177
+ case 0:
5178
+ callInfo = index + 1 + " of " + tools.length;
5179
+ console.log('Tool:', tool["function"].name, tool.id, Object.keys(toolMap));
5180
+ toolMetadata = {
5181
+ id: tool.id,
5182
+ fn: tool["function"].name,
5183
+ availableTools: Object.keys(toolMap)
5184
+ };
5185
+ logger({
5186
+ statusCode: 100,
5187
+ message: JSON.stringify({
5188
+ message: "[local] Starting tool call " + callInfo + ": " + tool["function"].name,
5189
+ metadata: {
5190
+ tool: toolMetadata
5191
+ }
5192
+ }, null, 2)
5193
+ });
5194
+ toolFn = toolMap == null ? void 0 : toolMap[tool["function"].name];
5195
+ if (toolFn) {
5196
+ _context4.next = 8;
5197
+ break;
5198
+ }
5199
+ logger({
5200
+ statusCode: 404,
5201
+ message: JSON.stringify({
5202
+ message: "[local] No tool fn found: " + tool["function"].name,
5203
+ metadata: {
5204
+ tool: toolMetadata
5205
+ }
5206
+ }, null, 2)
5207
+ });
5208
+ return _context4.abrupt("return");
5209
+ case 8:
5210
+ console.log('Executing tool:', tool["function"].name, tool.id, tool["function"].arguments);
5211
+ args = {};
5212
+ try {
5213
+ if (tool["function"].arguments) {
5214
+ args = JSON.parse(tool["function"].arguments);
5215
+ logger({
5216
+ statusCode: 100,
5217
+ message: JSON.stringify({
5218
+ message: "[local] Passing args to tool call: " + tool["function"].name,
5219
+ metadata: {
5220
+ args: args,
5221
+ tool: toolMetadata
5222
+ }
5223
+ }, null, 2)
5224
+ });
5225
+ }
5226
+ } catch (e) {
5227
+ console.error(e);
5228
+ }
5229
+ _context4.next = 13;
5230
+ return toolFn(args);
5231
+ case 13:
5232
+ output = _context4.sent;
5233
+ logger({
5234
+ statusCode: 200,
5235
+ message: JSON.stringify({
5236
+ message: "[local] Completed tool call " + callInfo + ": " + tool["function"].name,
5237
+ metadata: {
5238
+ output: output,
5239
+ tool: toolMetadata
5240
+ }
5241
+ }, null, 2)
5242
+ });
5243
+ return _context4.abrupt("return", {
5244
+ tool_call_id: tool.id,
5245
+ output: JSON.stringify(output)
5246
+ });
5247
+ case 16:
5248
+ case "end":
5249
+ return _context4.stop();
5250
+ }
5251
+ }, _callee4);
5252
+ }));
5253
+ return function (_x6, _x7, _x8) {
5254
+ return _ref8.apply(this, arguments);
5255
+ };
5256
+ }()));
5257
+ case 5:
5258
+ _context5.t1 = _context5.sent;
5259
+ toolOutputs = (0, _context5.t0)(_context5.t1);
5260
+ if (toolOutputs) {
5261
+ _context5.next = 11;
5262
+ break;
5263
+ }
5264
+ console.error('No tool outputs to submit.');
5265
+ logger({
5266
+ statusCode: 404,
5267
+ message: JSON.stringify({
5268
+ message: "No tool outputs submitted",
5269
+ metadata: {}
5270
+ }, null, 2)
5271
+ });
5272
+ return _context5.abrupt("return", handleRunStatus({
5273
+ threadId: threadId,
5274
+ run: run
5275
+ }));
5276
+ case 11:
5277
+ if (!(toolOutputs && (toolOutputs == null ? void 0 : toolOutputs.length) > 0)) {
5278
+ _context5.next = 20;
5279
+ break;
5280
+ }
5281
+ console.log(toolOutputs, '###### YOOOOOO');
5282
+ _context5.next = 15;
5283
+ return client.beta.threads.runs.submitToolOutputsAndPoll(threadId, run.id, {
5284
+ tool_outputs: toolOutputs
5285
+ });
5286
+ case 15:
5287
+ run = _context5.sent;
5288
+ logger({
5289
+ statusCode: 200,
5290
+ message: JSON.stringify({
5291
+ message: "Tool outputs submitted",
5292
+ metadata: {
5293
+ run: run
5294
+ }
5295
+ }, null, 2)
5296
+ });
5297
+ console.log('Tool outputs submitted successfully.');
5298
+ _context5.next = 22;
5299
+ break;
5300
+ case 20:
5301
+ logger({
5302
+ statusCode: 404,
5303
+ message: JSON.stringify({
5304
+ message: "No tool outputs to submit",
5305
+ metadata: {}
5306
+ }, null, 2)
5307
+ });
5308
+ console.log('No tool outputs to submit.');
5309
+ case 22:
5310
+ return _context5.abrupt("return", handleRunStatus({
5311
+ threadId: threadId,
5312
+ run: run
5313
+ }));
5314
+ case 23:
5315
+ case "end":
5316
+ return _context5.stop();
5317
+ }
5318
+ }, _callee5);
5319
+ }));
5320
+ return function handleRequiresAction(_x5) {
5321
+ return _ref7.apply(this, arguments);
5322
+ };
5323
+ }();
5324
+ getRun = /*#__PURE__*/function () {
5325
+ var _ref10 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(_ref9) {
5326
+ var threadId, runId;
5327
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
5328
+ while (1) switch (_context6.prev = _context6.next) {
5329
+ case 0:
5330
+ threadId = _ref9.threadId, runId = _ref9.runId;
5331
+ _context6.next = 3;
5332
+ return client.beta.threads.runs.retrieve(threadId, runId);
5333
+ case 3:
5334
+ return _context6.abrupt("return", _context6.sent);
5335
+ case 4:
5336
+ case "end":
5337
+ return _context6.stop();
5338
+ }
5339
+ }, _callee6);
5340
+ }));
5341
+ return function getRun(_x9) {
5342
+ return _ref10.apply(this, arguments);
5343
+ };
5344
+ }();
5345
+ return _context11.abrupt("return", {
5346
+ agent: agent,
5347
+ initializeThread: function () {
5348
+ var _initializeThread = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(messages) {
5349
+ return _regeneratorRuntime().wrap(function _callee7$(_context7) {
5350
+ while (1) switch (_context7.prev = _context7.next) {
5351
+ case 0:
5352
+ if (messages === void 0) {
5353
+ messages = [];
5354
+ }
5355
+ _context7.next = 3;
5356
+ return client.beta.threads.create({
5357
+ messages: messages
5358
+ });
5359
+ case 3:
5360
+ return _context7.abrupt("return", _context7.sent);
5361
+ case 4:
5362
+ case "end":
5363
+ return _context7.stop();
5364
+ }
5365
+ }, _callee7);
5366
+ }));
5367
+ function initializeThread(_x10) {
5368
+ return _initializeThread.apply(this, arguments);
5369
+ }
5370
+ return initializeThread;
5371
+ }(),
5372
+ listMessages: function () {
5373
+ var _listMessages = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(_ref11) {
5374
+ var threadId;
5375
+ return _regeneratorRuntime().wrap(function _callee8$(_context8) {
5376
+ while (1) switch (_context8.prev = _context8.next) {
5377
+ case 0:
5378
+ threadId = _ref11.threadId;
5379
+ _context8.next = 3;
5380
+ return client.beta.threads.messages.list(threadId);
5381
+ case 3:
5382
+ return _context8.abrupt("return", _context8.sent);
5383
+ case 4:
5384
+ case "end":
5385
+ return _context8.stop();
5386
+ }
5387
+ }, _callee8);
5388
+ }));
5389
+ function listMessages(_x11) {
5390
+ return _listMessages.apply(this, arguments);
5391
+ }
5392
+ return listMessages;
5393
+ }(),
5394
+ getRun: getRun,
5395
+ handleRunStatus: handleRunStatus,
5396
+ handleRequiresAction: handleRequiresAction,
5397
+ createUserMessage: function () {
5398
+ var _createUserMessage = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(_ref12) {
5399
+ var threadId, content;
5400
+ return _regeneratorRuntime().wrap(function _callee9$(_context9) {
5401
+ while (1) switch (_context9.prev = _context9.next) {
5402
+ case 0:
5403
+ threadId = _ref12.threadId, content = _ref12.content;
5404
+ _context9.next = 3;
5405
+ return client.beta.threads.messages.create(threadId, {
5406
+ role: 'user',
5407
+ content: content
5408
+ });
5409
+ case 3:
5410
+ return _context9.abrupt("return", _context9.sent);
5411
+ case 4:
5412
+ case "end":
5413
+ return _context9.stop();
5414
+ }
5415
+ }, _callee9);
5416
+ }));
5417
+ function createUserMessage(_x12) {
5418
+ return _createUserMessage.apply(this, arguments);
5419
+ }
5420
+ return createUserMessage;
5421
+ }(),
5422
+ watchRun: function () {
5423
+ var _watchRun = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(_ref13) {
5424
+ var runId, threadId, run;
5425
+ return _regeneratorRuntime().wrap(function _callee10$(_context10) {
5426
+ while (1) switch (_context10.prev = _context10.next) {
5427
+ case 0:
5428
+ runId = _ref13.runId, threadId = _ref13.threadId;
5429
+ if (!runId) {
5430
+ _context10.next = 7;
5431
+ break;
5432
+ }
5433
+ _context10.next = 4;
5434
+ return getRun({
5435
+ threadId: threadId,
5436
+ runId: runId
5437
+ });
5438
+ case 4:
5439
+ run = _context10.sent;
5440
+ _context10.next = 11;
5441
+ break;
5442
+ case 7:
5443
+ _context10.next = 9;
5444
+ return client.beta.threads.runs.createAndPoll(threadId, {
5445
+ assistant_id: id,
5446
+ tool_choice: 'required'
5447
+ });
5448
+ case 9:
5449
+ run = _context10.sent;
5450
+ logger({
5451
+ statusCode: 202,
5452
+ message: JSON.stringify({
5453
+ message: "Creating and polling run, tool choice required",
5454
+ metadata: {
5455
+ run: run,
5456
+ tool_choice: 'required',
5457
+ threadId: threadId,
5458
+ assistant_id: id
5459
+ }
5460
+ }, null, 2)
5461
+ });
5462
+ case 11:
5463
+ return _context10.abrupt("return", handleRunStatus({
5464
+ threadId: threadId,
5465
+ run: run
5466
+ }));
5467
+ case 12:
5468
+ case "end":
5469
+ return _context10.stop();
5470
+ }
5471
+ }, _callee10);
5472
+ }));
5473
+ function watchRun(_x13) {
5474
+ return _watchRun.apply(this, arguments);
5475
+ }
5476
+ return watchRun;
5477
+ }()
5478
+ });
5479
+ case 9:
5480
+ case "end":
5481
+ return _context11.stop();
5482
+ }
5483
+ }, _callee11);
5484
+ }));
5485
+ return _getAssistantAgent.apply(this, arguments);
5486
+ }
5487
+
5488
+ var delay = function delay(ms) {
5489
+ return new Promise(function (resolve) {
5490
+ return setTimeout(resolve, ms);
5491
+ });
5492
+ };
5493
+ function getAgentParams(_ref) {
5494
+ var tools = _ref.tools,
5495
+ resultTool = _ref.resultTool,
5496
+ model = _ref.model;
5497
+ var toolsConverted = Object.entries(tools).reduce(function (memo, _ref2) {
5498
+ var key = _ref2[0],
5499
+ val = _ref2[1];
5500
+ memo[key] = tool(val);
5501
+ return memo;
5502
+ }, {});
5503
+ var answerTool = {};
5504
+ if (resultTool) {
5505
+ answerTool = {
5506
+ answer: tool(resultTool)
5507
+ };
5508
+ }
5509
+ var modelDef;
5510
+ if (model.type === 'openai') {
5511
+ var mName = model.name;
5512
+ if (!mName) {
5513
+ mName = "gpt-4o-2024-08-06";
5514
+ }
5515
+ var openai = createOpenAI({
5516
+ apiKey: process.env.OPENAI_API_KEY
5517
+ });
5518
+ modelDef = openai(mName, {
5519
+ structuredOutputs: true
5520
+ });
5521
+ } else if (model.type === 'anthropic') {
5522
+ var _mName = model.name;
5523
+ if (!_mName) {
5524
+ _mName = "claude-3-5-sonnet-20240620";
5525
+ }
5526
+ var anthropic = createAnthropic({
5527
+ apiKey: process.env.ANTHROPIC_API_KEY
5528
+ });
5529
+ modelDef = anthropic(_mName);
5530
+ } else if (model.type === 'groq') {
5531
+ var _process$env$GROQ_API;
5532
+ 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);
5533
+ } else if (model.type === 'perplexity') {
5534
+ var _process$env$PERPLEXI;
5535
+ 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);
5536
+ } else if (model.type === 'fireworks') {
5537
+ var _process$env$FIREWORK;
5538
+ 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);
5539
+ }
5540
+ return {
5541
+ toolsConverted: toolsConverted,
5542
+ modelDef: modelDef,
5543
+ answerTool: answerTool,
5544
+ toolChoice: (model == null ? void 0 : model.toolChoice) || 'required'
5545
+ };
5546
+ }
5547
+ function createStreamAgent(_ref3) {
5548
+ var agent_instructions = _ref3.agent_instructions,
5549
+ _ref3$maxSteps = _ref3.maxSteps,
5550
+ maxSteps = _ref3$maxSteps === void 0 ? 5 : _ref3$maxSteps,
5551
+ tools = _ref3.tools,
5552
+ resultTool = _ref3.resultTool,
5553
+ _ref3$context = _ref3.context,
5554
+ context = _ref3$context === void 0 ? [] : _ref3$context,
5555
+ model = _ref3.model;
5556
+ var params = getAgentParams({
5557
+ tools: tools,
5558
+ resultTool: resultTool,
5559
+ model: model
5560
+ });
5561
+ return /*#__PURE__*/function () {
5562
+ var _ref5 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_ref4) {
5563
+ var prompt, argsForExecute;
5564
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
5565
+ while (1) switch (_context2.prev = _context2.next) {
5566
+ case 0:
5567
+ prompt = _ref4.prompt;
5568
+ argsForExecute = {
5569
+ model: params.modelDef,
5570
+ tools: _extends({}, params.toolsConverted, params.answerTool),
5571
+ toolChoice: (params == null ? void 0 : params.toolChoice) || 'required',
5572
+ maxSteps: maxSteps,
5573
+ // system: systemPrompt,
5574
+ onStepFinish: function () {
5575
+ var _onStepFinish = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(props) {
5576
+ var _props$response, _props$response2;
5577
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
5578
+ while (1) switch (_context.prev = _context.next) {
5579
+ case 0:
5580
+ console.log(JSON.stringify(props, null, 2));
5581
+ 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)) {
5582
+ _context.next = 5;
5583
+ break;
5584
+ }
5585
+ console.log('Rate limit reached, waiting 10 seconds');
5586
+ _context.next = 5;
5587
+ return delay(10 * 1000);
5588
+ case 5:
5589
+ case "end":
5590
+ return _context.stop();
5591
+ }
5592
+ }, _callee);
5593
+ }));
5594
+ function onStepFinish(_x2) {
5595
+ return _onStepFinish.apply(this, arguments);
5596
+ }
5597
+ return onStepFinish;
5598
+ }()
5599
+ };
5600
+ _context2.next = 4;
5601
+ return streamText(_extends({
5602
+ messages: [].concat(context, [{
5603
+ role: 'user',
5604
+ content: prompt
5605
+ }, {
5606
+ role: 'system',
5607
+ content: agent_instructions
5608
+ }])
5609
+ }, argsForExecute));
5610
+ case 4:
5611
+ return _context2.abrupt("return", _context2.sent);
5612
+ case 5:
5613
+ case "end":
5614
+ return _context2.stop();
5615
+ }
5616
+ }, _callee2);
5617
+ }));
5618
+ return function (_x) {
5619
+ return _ref5.apply(this, arguments);
5620
+ };
5621
+ }();
5622
+ }
5623
+ function createAgent(_ref6) {
5624
+ var agent_instructions = _ref6.agent_instructions,
5625
+ _ref6$maxSteps = _ref6.maxSteps,
5626
+ maxSteps = _ref6$maxSteps === void 0 ? 5 : _ref6$maxSteps,
5627
+ tools = _ref6.tools,
5628
+ resultTool = _ref6.resultTool,
5629
+ _ref6$context = _ref6.context,
5630
+ context = _ref6$context === void 0 ? [] : _ref6$context,
5631
+ model = _ref6.model;
5632
+ var params = getAgentParams({
5633
+ tools: tools,
5634
+ resultTool: resultTool,
5635
+ model: model
5636
+ });
5637
+ return /*#__PURE__*/function () {
5638
+ var _ref8 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(_ref7) {
5639
+ var prompt, argsForExecute;
5640
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
5641
+ while (1) switch (_context4.prev = _context4.next) {
5642
+ case 0:
5643
+ prompt = _ref7.prompt;
5644
+ argsForExecute = {
5645
+ model: params.modelDef,
5646
+ tools: _extends({}, params.toolsConverted, params.answerTool),
5647
+ toolChoice: (params == null ? void 0 : params.toolChoice) || 'required',
5648
+ maxSteps: maxSteps,
5649
+ // system: systemPrompt,
5650
+ onStepFinish: function () {
5651
+ var _onStepFinish2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(props) {
5652
+ var _props$response3, _props$response4;
5653
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
5654
+ while (1) switch (_context3.prev = _context3.next) {
5655
+ case 0:
5656
+ console.log(JSON.stringify(props, null, 2));
5657
+ 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)) {
5658
+ _context3.next = 5;
5659
+ break;
5660
+ }
5661
+ console.log('Rate limit reached, waiting 10 seconds');
5662
+ _context3.next = 5;
5663
+ return delay(10 * 1000);
5664
+ case 5:
5665
+ case "end":
5666
+ return _context3.stop();
5667
+ }
5668
+ }, _callee3);
5669
+ }));
5670
+ function onStepFinish(_x4) {
5671
+ return _onStepFinish2.apply(this, arguments);
5672
+ }
5673
+ return onStepFinish;
5674
+ }()
5675
+ };
5676
+ _context4.next = 4;
5677
+ return generateText(_extends({
5678
+ messages: [].concat(context, [{
5679
+ role: 'user',
5680
+ content: prompt
5681
+ }, {
5682
+ role: 'system',
5683
+ content: agent_instructions
5684
+ }])
5685
+ }, argsForExecute));
5686
+ case 4:
5687
+ return _context4.abrupt("return", _context4.sent);
5688
+ case 5:
5689
+ case "end":
5690
+ return _context4.stop();
5691
+ }
5692
+ }, _callee4);
5693
+ }));
5694
+ return function (_x3) {
5695
+ return _ref8.apply(this, arguments);
5696
+ };
5697
+ }();
5698
+ }
5699
+ function createOpenAICompatibleModel(baseURL, apiKey, defaultModelName, modelName) {
5700
+ var client = createOpenAI({
5701
+ baseURL: baseURL,
5702
+ apiKey: apiKey
5703
+ });
5704
+ return client(modelName || defaultModelName);
5705
+ }
5706
+
5707
+ function getAgent(_x) {
5708
+ return _getAgent.apply(this, arguments);
5709
+ }
5710
+ function _getAgent() {
5711
+ _getAgent = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(_ref) {
5712
+ var connectionId, agent, apis, tools, toolMap, assistant, _agent$model2, keyToModel, _tools, _toolMap, resultTool, schema, _agent$model;
5713
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
5714
+ while (1) switch (_context3.prev = _context3.next) {
5715
+ case 0:
5716
+ connectionId = _ref.connectionId, agent = _ref.agent, apis = _ref.apis;
5717
+ if (!(agent.model.provider === 'OPEN_AI_ASSISTANT')) {
5718
+ _context3.next = 10;
5719
+ break;
5720
+ }
5721
+ tools = Object.keys(agent.tools);
5722
+ toolMap = Object.entries(apis).reduce(function (memo, _ref2) {
5723
+ var k = _ref2[0],
5724
+ def = _ref2[1];
5725
+ if (tools.includes(k)) {
5726
+ memo[k] = /*#__PURE__*/function () {
5727
+ var _ref3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(props) {
5728
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
5729
+ while (1) switch (_context.prev = _context.next) {
5730
+ case 0:
5731
+ return _context.abrupt("return", def.executor({
5732
+ data: props,
5733
+ ctx: {
5734
+ connectionId: connectionId
5735
+ }
5736
+ }));
5737
+ case 1:
5738
+ case "end":
5739
+ return _context.stop();
5740
+ }
5741
+ }, _callee);
5742
+ }));
5743
+ return function (_x2) {
5744
+ return _ref3.apply(this, arguments);
5745
+ };
5746
+ }();
5747
+ }
5748
+ return memo;
5749
+ }, {});
5750
+ _context3.next = 6;
5751
+ return getAssistantAgent({
5752
+ id: agent.id,
5753
+ toolMap: toolMap
5754
+ });
5755
+ case 6:
5756
+ assistant = _context3.sent;
5757
+ return _context3.abrupt("return", assistant);
5758
+ case 10:
5759
+ if (!['OPEN_AI_VERCEL', 'ANTHROPIC_VERCEL', 'GROQ_VERCEL', 'PERPLEXITY_VERCEL', 'FIREWORKS_VERCEL'].includes(agent.model.provider)) {
5760
+ _context3.next = 19;
5761
+ break;
5762
+ }
5763
+ keyToModel = {
5764
+ OPEN_AI_VERCEL: 'openai',
5765
+ ANTHROPIC_VERCEL: 'anthropic',
5766
+ GROQ_VERCEL: 'groq',
5767
+ PERPLEXITY_VERCEL: 'perplexity',
5768
+ FIREWORKS_VERCEL: 'fireworks'
5769
+ };
5770
+ _tools = Object.keys(agent.tools);
5771
+ _toolMap = Object.entries(apis).reduce(function (memo, _ref4) {
5772
+ var k = _ref4[0],
5773
+ def = _ref4[1];
5774
+ if (_tools.includes(k)) {
5775
+ memo[k] = {
5776
+ description: def.label,
5777
+ parameters: def.schema,
5778
+ execute: function () {
5779
+ var _execute = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(props) {
5780
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
5781
+ while (1) switch (_context2.prev = _context2.next) {
5782
+ case 0:
5783
+ return _context2.abrupt("return", def.executor({
5784
+ data: props,
5785
+ ctx: {
5786
+ connectionId: connectionId
5787
+ }
5788
+ }));
5789
+ case 1:
5790
+ case "end":
5791
+ return _context2.stop();
5792
+ }
5793
+ }, _callee2);
5794
+ }));
5795
+ function execute(_x3) {
5796
+ return _execute.apply(this, arguments);
5797
+ }
5798
+ return execute;
5799
+ }()
5800
+ };
5801
+ }
5802
+ return memo;
5803
+ }, {});
5804
+ resultTool = undefined;
5805
+ if (agent.outputs.structured) {
5806
+ schema = Object.entries(agent.outputs.structured.schema).reduce(function (memo, _ref5) {
5807
+ var k = _ref5[0],
5808
+ v = _ref5[1];
5809
+ if (v.type === 'string') {
5810
+ memo[k] = z.string();
5811
+ }
5812
+ if (v.type === 'array') {
5813
+ var _v$items;
5814
+ var itemType = v == null || (_v$items = v.items) == null ? void 0 : _v$items.type;
5815
+ if (itemType === 'string') {
5816
+ memo[k] = z.array(z.string());
5817
+ }
5818
+ }
5819
+ return memo;
5820
+ }, {});
5821
+ resultTool = {
5822
+ description: agent.outputs.structured.description,
5823
+ parameters: z.object(schema)
5824
+ };
5825
+ }
5826
+ if (!(agent.model.generation_type === 'stream')) {
5827
+ _context3.next = 18;
5828
+ break;
5829
+ }
5830
+ return _context3.abrupt("return", createStreamAgent({
5831
+ agent_instructions: agent.agent_instructions,
5832
+ model: {
5833
+ type: keyToModel[agent.model.provider],
5834
+ name: agent.model.name,
5835
+ toolChoice: ((_agent$model = agent.model) == null ? void 0 : _agent$model.toolChoice) || 'required'
5836
+ },
5837
+ tools: _toolMap,
5838
+ resultTool: resultTool
5839
+ }));
5840
+ case 18:
5841
+ return _context3.abrupt("return", createAgent({
5842
+ agent_instructions: agent.agent_instructions,
5843
+ model: {
5844
+ type: keyToModel[agent.model.provider],
5845
+ name: agent.model.name,
5846
+ toolChoice: ((_agent$model2 = agent.model) == null ? void 0 : _agent$model2.toolChoice) || 'required'
5847
+ },
5848
+ tools: _toolMap,
5849
+ resultTool: resultTool
5850
+ }));
5851
+ case 19:
5852
+ case "end":
5853
+ return _context3.stop();
5854
+ }
5855
+ }, _callee3);
5856
+ }));
5857
+ return _getAgent.apply(this, arguments);
5858
+ }
5859
+
5860
+ var Mastra = /*#__PURE__*/function () {
5861
+ function Mastra(_ref) {
5862
+ var _this = this;
5863
+ var dataLayer = _ref.dataLayer,
5864
+ vectorLayer = _ref.vectorLayer,
5865
+ config = _ref.config;
5866
+ //global events grouped by Integration
5867
+ this.globalEvents = new Map();
5868
+ // global apis grouped by Integration
5869
+ this.globalApis = new Map();
5870
+ this.integrations = new Map();
5871
+ this.dataLayer = void 0;
5872
+ this.vectorLayer = void 0;
5873
+ this.agentsConfig = {
5874
+ agentDirPath: '',
5875
+ vectorProvider: []
5876
+ };
5877
+ this.config = void 0;
5878
+ this.runBlueprint = /*#__PURE__*/function () {
5879
+ var _ref3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref2) {
5880
+ var _this$availableIntegr;
5881
+ var blueprint, _ref2$dataCtx, dataCtx, ctx, systemApis, systemEvents, availableIntegrations, availableIntegrationApis, availableIntegrationEvents, frameworkApis, frameworkEvents;
5882
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
5883
+ while (1) switch (_context.prev = _context.next) {
5884
+ case 0:
5885
+ blueprint = _ref2.blueprint, _ref2$dataCtx = _ref2.dataCtx, dataCtx = _ref2$dataCtx === void 0 ? {} : _ref2$dataCtx, ctx = _ref2.ctx;
5886
+ systemApis = _this.getSystemApis();
5887
+ systemEvents = _this.getSystemEvents();
5888
+ availableIntegrations = (_this$availableIntegr = _this.availableIntegrations()) == null ? void 0 : _this$availableIntegr.map(function (_ref4) {
5889
+ var integration = _ref4.integration;
5890
+ return integration;
5891
+ });
5892
+ availableIntegrationApis = availableIntegrations.reduce(function (acc, _ref5) {
5893
+ var name = _ref5.name;
5894
+ var apis = _this.getApisByIntegration(name);
5895
+ return _extends({}, acc, apis);
5896
+ }, {});
5897
+ availableIntegrationEvents = availableIntegrations.reduce(function (acc, _ref6) {
5898
+ var name = _ref6.name;
5899
+ var events = _this.getEventsByIntegration(name);
5900
+ return _extends({}, acc, events);
5901
+ }, {});
5902
+ frameworkApis = _extends({}, systemApis, availableIntegrationApis);
5903
+ frameworkEvents = _extends({}, systemEvents, availableIntegrationEvents);
5904
+ _context.next = 10;
5905
+ return blueprintRunner({
5906
+ dataCtx: dataCtx,
5907
+ blueprint: blueprint,
5908
+ frameworkApis: frameworkApis,
5909
+ frameworkEvents: frameworkEvents,
5910
+ ctx: ctx
5911
+ });
5912
+ case 10:
5913
+ case "end":
5914
+ return _context.stop();
5915
+ }
5916
+ }, _callee);
5917
+ }));
5918
+ return function (_x) {
5919
+ return _ref3.apply(this, arguments);
5920
+ };
5921
+ }();
5922
+ this.dataLayer = dataLayer;
5923
+ this.vectorLayer = vectorLayer;
5924
+ this.config = config;
5925
+ }
5926
+ Mastra.init = function init(config) {
5927
+ var _config$workflows$sys;
5928
+ if (!config.db.uri) {
5929
+ throw new Error('No database config/provider found');
5930
+ }
5931
+ var dataLayer = new DataLayer({
5932
+ url: config.db.uri,
5933
+ provider: config.db.provider
5934
+ });
5935
+ var vectorLayer = new VectorLayer();
5936
+ var framework = new Mastra({
5937
+ config: config,
5938
+ dataLayer: dataLayer,
5939
+ vectorLayer: vectorLayer
5940
+ });
5941
+ // Register integrations
5942
+ config.integrations.forEach(function (integration) {
5943
+ framework.__registerIntgeration(integration);
5944
+ });
5945
+ // Register system apis
5946
+ framework.__registerApis({
5947
+ apis: [].concat(getAgentSystemApis({
5948
+ mastra: framework
5949
+ }), (_config$workflows$sys = config.workflows.systemApis) == null ? void 0 : _config$workflows$sys.map(function (api) {
5950
+ return _extends({}, api, {
5951
+ integrationName: config.name
5952
+ });
5953
+ }), getVectorQueryApis({
5954
+ mastra: framework
5955
+ }))
5956
+ });
5957
+ // Register System events
5958
+ framework.__registerEvents({
5959
+ events: config.workflows.systemEvents
5960
+ });
5961
+ // Register vector sync event
5962
+ framework.__registerEvents({
5963
+ events: {
5964
+ AGENT_VECTOR_SYNC: {
5965
+ label: 'Sync vector data for an agent',
5966
+ description: 'Sync vector data for an agent',
5967
+ schema: z.object({
5968
+ agentId: z.string()
5969
+ }),
5970
+ handler: agentVectorSyncEvent
5971
+ },
5972
+ VECTOR_SYNC: {
5973
+ label: 'Sync vector data',
5974
+ description: 'Sync vector data',
5975
+ schema: z.object({
5976
+ vector_provider: z.string(),
5977
+ entities: z.array(z.object({
5978
+ integration: z.string(),
5979
+ data: z.array(z.object({
5980
+ name: z.string(),
5981
+ fields: z.array(z.string()),
5982
+ syncEvent: z.string(),
5983
+ index: z.string()
5984
+ }))
5985
+ }))
5986
+ }),
5987
+ handler: genericVectorySyncEvent
5988
+ }
5989
+ },
5990
+ integrationName: config.name
5991
+ });
5992
+ // Register agent config
5993
+ framework.agentsConfig = config.agents;
5994
+ return framework;
5995
+ };
5996
+ var _proto = Mastra.prototype;
5997
+ _proto.connectedIntegrations = /*#__PURE__*/function () {
5998
+ var _connectedIntegrations = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(_ref7) {
5999
+ var _this2 = this;
6000
+ var context, ints, connectionChecks;
6001
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
6002
+ while (1) switch (_context3.prev = _context3.next) {
6003
+ case 0:
6004
+ context = _ref7.context;
6005
+ ints = this.availableIntegrations();
6006
+ _context3.next = 4;
6007
+ return Promise.all(ints.map(/*#__PURE__*/function () {
6008
+ var _ref9 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_ref8) {
6009
+ var integration, connection;
6010
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
6011
+ while (1) switch (_context2.prev = _context2.next) {
6012
+ case 0:
6013
+ integration = _ref8.integration;
6014
+ _context2.next = 3;
6015
+ return _this2.dataLayer.getConnection({
6016
+ connectionId: context.connectionId,
6017
+ name: integration.name
6018
+ });
6019
+ case 3:
6020
+ connection = _context2.sent;
6021
+ return _context2.abrupt("return", {
6022
+ integration: integration,
6023
+ connected: !!connection
6024
+ });
6025
+ case 5:
6026
+ case "end":
6027
+ return _context2.stop();
6028
+ }
6029
+ }, _callee2);
6030
+ }));
6031
+ return function (_x3) {
6032
+ return _ref9.apply(this, arguments);
6033
+ };
6034
+ }()));
6035
+ case 4:
6036
+ connectionChecks = _context3.sent;
6037
+ return _context3.abrupt("return", connectionChecks.filter(function (_ref10) {
6038
+ var connected = _ref10.connected;
6039
+ return connected;
6040
+ }).map(function (_ref11) {
6041
+ var integration = _ref11.integration;
6042
+ return integration;
6043
+ }));
6044
+ case 6:
6045
+ case "end":
6046
+ return _context3.stop();
6047
+ }
6048
+ }, _callee3, this);
6049
+ }));
6050
+ function connectedIntegrations(_x2) {
6051
+ return _connectedIntegrations.apply(this, arguments);
6052
+ }
6053
+ return connectedIntegrations;
6054
+ }();
6055
+ _proto.__registerIntgeration = function __registerIntgeration(definition) {
6056
+ var name = definition.name;
6057
+ definition.attachDataLayer({
6058
+ dataLayer: this.dataLayer
6059
+ });
6060
+ var router = this.createRouter();
6061
+ definition.corePresets = {
6062
+ redirectURI: router.makeRedirectURI()
6063
+ };
6064
+ this.integrations.set(name, definition);
6065
+ definition.registerEvents();
6066
+ this.__registerEvents({
6067
+ events: definition.getEvents(),
6068
+ integrationName: name
6069
+ });
6070
+ definition.registerApis();
6071
+ definition._convertApiClientToSystemApis();
6072
+ this.__registerApis({
6073
+ apis: Object.values(definition.getApis()),
6074
+ integrationName: name
6075
+ });
6076
+ };
6077
+ _proto.registerApi = function registerApi(name, api) {
6078
+ var _extends2;
6079
+ var integrationApis = this.globalApis.get(this.config.name) || {};
6080
+ this.globalApis.set(this.config.name, _extends({}, integrationApis, (_extends2 = {}, _extends2[name] = _extends({}, api, {
6081
+ integrationName: this.config.name
6082
+ }), _extends2)));
6083
+ };
6084
+ _proto.registerEvent = function registerEvent(name, event) {
6085
+ var _extends3;
6086
+ var integrationEvents = this.globalEvents.get('SYSTEM') || {};
6087
+ this.globalEvents.set('SYSTEM', _extends({}, integrationEvents, (_extends3 = {}, _extends3[name] = event, _extends3)));
6088
+ };
6089
+ _proto.__registerEvents = function __registerEvents(_ref12) {
6090
+ var events = _ref12.events,
6091
+ _ref12$integrationNam = _ref12.integrationName,
6092
+ integrationName = _ref12$integrationNam === void 0 ? this.config.name : _ref12$integrationNam;
6093
+ var integrationEvents = this.globalEvents.get(integrationName) || {};
6094
+ this.globalEvents.set(integrationName, _extends({}, integrationEvents, events));
6095
+ };
6096
+ _proto.__registerApis = function __registerApis(_ref13) {
6097
+ var apis = _ref13.apis,
6098
+ _ref13$integrationNam = _ref13.integrationName,
6099
+ integrationName = _ref13$integrationNam === void 0 ? this.config.name : _ref13$integrationNam;
6100
+ var integrationApis = this.globalApis.get(integrationName) || {};
6101
+ this.globalApis.set(integrationName, _extends({}, integrationApis, apis.reduce(function (acc, api) {
6102
+ var _extends4;
6103
+ return _extends({}, acc, (_extends4 = {}, _extends4[api.type] = api, _extends4));
6104
+ }, {})));
6105
+ };
6106
+ _proto.availableIntegrations = function availableIntegrations() {
6107
+ return Array.from(this.integrations.entries()).map(function (_ref14) {
6108
+ var name = _ref14[0],
6109
+ integration = _ref14[1];
6110
+ return {
6111
+ name: name,
6112
+ integration: integration
6113
+ };
6114
+ });
6115
+ };
6116
+ _proto.getIntegration = function getIntegration(name) {
6117
+ return this.integrations.get(name);
6118
+ };
6119
+ _proto.getGlobalEvents = function getGlobalEvents() {
6120
+ return this.globalEvents;
6121
+ };
6122
+ _proto.getSystemEvents = function getSystemEvents() {
6123
+ var events = this.globalEvents.get(this.config.name);
6124
+ return events || {};
6125
+ };
6126
+ _proto.getEventsByIntegration = function getEventsByIntegration(name) {
6127
+ return this.globalEvents.get(name);
6128
+ };
6129
+ _proto.getGlobalEventHandlers = function getGlobalEventHandlers() {
6130
+ var _this3 = this;
6131
+ return Array.from(this.globalEvents.entries()).flatMap(function (_ref15) {
6132
+ var integrationName = _ref15[0],
6133
+ events = _ref15[1];
6134
+ var groupedHandlers = Object.keys(events).map(function (eventKey) {
6135
+ var _events$eventKey;
6136
+ var eventHandler = (_events$eventKey = events[eventKey]) == null ? void 0 : _events$eventKey.handler;
6137
+ if (!eventHandler) return null;
6138
+ var isSystemEvent = integrationName === _this3.config.name;
6139
+ var _this3$createRouter = _this3.createRouter(),
6140
+ makeWebhookUrl = _this3$createRouter.makeWebhookUrl;
6141
+ if (isSystemEvent) {
6142
+ return eventHandler({
6143
+ getIntegration: function getIntegration(name) {
6144
+ return _this3.getIntegration(name);
6145
+ },
6146
+ eventKey: eventKey,
6147
+ getVectorProvider: function getVectorProvider(name) {
6148
+ return _this3.agentsConfig.vectorProvider.find(function (provider) {
6149
+ return provider.name === name;
6150
+ });
6151
+ },
6152
+ makeWebhookUrl: makeWebhookUrl
6153
+ });
6154
+ } else {
6155
+ var integration = _this3.getIntegration(integrationName);
6156
+ return eventHandler({
6157
+ integrationInstance: integration,
6158
+ eventKey: eventKey,
6159
+ makeWebhookUrl: makeWebhookUrl
6160
+ });
6161
+ }
6162
+ }).filter(Boolean);
6163
+ return groupedHandlers;
6164
+ });
6165
+ };
6166
+ _proto.getApis = function getApis() {
6167
+ return this.globalApis;
6168
+ };
6169
+ _proto.getSystemApis = function getSystemApis() {
6170
+ return this.globalApis.get(this.config.name);
6171
+ };
6172
+ _proto.getApisByIntegration = function getApisByIntegration(name, includeHidden) {
6173
+ var integrationApis = this.globalApis.get(name);
6174
+ if (includeHidden) {
6175
+ return integrationApis;
6176
+ }
6177
+ return omitBy(integrationApis, function (value) {
6178
+ return value.isHidden;
6179
+ });
6180
+ };
6181
+ _proto.authenticatableIntegrations = function authenticatableIntegrations() {
6182
+ return this.availableIntegrations().filter(function (_ref16) {
6183
+ var integration = _ref16.integration;
6184
+ try {
6185
+ integration.getAuthenticator();
6186
+ return true;
6187
+ } catch (e) {
6188
+ return false;
6189
+ }
6190
+ });
6191
+ };
6192
+ _proto.authenticator = function authenticator(name) {
6193
+ var _int = this.getIntegration(name);
6194
+ if (!_int) {
6195
+ throw new Error("No integration exists for " + name);
4469
6196
  }
4470
6197
  return _int.getAuthenticator();
4471
6198
  };
4472
6199
  _proto.connectIntegrationByCredential = /*#__PURE__*/function () {
4473
- var _connectIntegrationByCredential = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(_ref16) {
6200
+ var _connectIntegrationByCredential = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(_ref17) {
4474
6201
  var name, connectionId, credential, authenticator, integration;
4475
6202
  return _regeneratorRuntime().wrap(function _callee4$(_context4) {
4476
6203
  while (1) switch (_context4.prev = _context4.next) {
4477
6204
  case 0:
4478
- name = _ref16.name, connectionId = _ref16.connectionId, credential = _ref16.credential;
6205
+ name = _ref17.name, connectionId = _ref17.connectionId, credential = _ref17.credential;
4479
6206
  authenticator = this.authenticator(name);
4480
6207
  if (authenticator) {
4481
6208
  _context4.next = 4;
@@ -4511,13 +6238,13 @@ var Framework = /*#__PURE__*/function () {
4511
6238
  return connectIntegrationByCredential;
4512
6239
  }();
4513
6240
  _proto.disconnectIntegration = /*#__PURE__*/function () {
4514
- var _disconnectIntegration = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(_ref17) {
6241
+ var _disconnectIntegration = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(_ref18) {
4515
6242
  var _yield$this$dataLayer;
4516
6243
  var name, connectionId, integration, k_id, authenticator;
4517
6244
  return _regeneratorRuntime().wrap(function _callee5$(_context5) {
4518
6245
  while (1) switch (_context5.prev = _context5.next) {
4519
6246
  case 0:
4520
- name = _ref17.name, connectionId = _ref17.connectionId;
6247
+ name = _ref18.name, connectionId = _ref18.connectionId;
4521
6248
  integration = this.getIntegration(name);
4522
6249
  _context5.next = 4;
4523
6250
  return this.dataLayer.getConnection({
@@ -4578,14 +6305,14 @@ var Framework = /*#__PURE__*/function () {
4578
6305
  return disconnectIntegration;
4579
6306
  }();
4580
6307
  _proto.callApi = /*#__PURE__*/function () {
4581
- var _callApi = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(_ref18) {
6308
+ var _callApi = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(_ref19) {
4582
6309
  var _int2$getApis;
4583
- var _ref18$integrationNam, integrationName, api, payload, _this$globalApis$get, _apiExecutor, _int2, apiExecutor;
6310
+ var _ref19$integrationNam, integrationName, api, payload, _this$globalApis$get, _apiExecutor, _int2, apiExecutor;
4584
6311
  return _regeneratorRuntime().wrap(function _callee6$(_context6) {
4585
6312
  while (1) switch (_context6.prev = _context6.next) {
4586
6313
  case 0:
4587
- _ref18$integrationNam = _ref18.integrationName, integrationName = _ref18$integrationNam === void 0 ? this.config.name : _ref18$integrationNam, api = _ref18.api, payload = _ref18.payload;
4588
- if (!(integrationName === this.config.name)) {
6314
+ _ref19$integrationNam = _ref19.integrationName, integrationName = _ref19$integrationNam === void 0 ? this.config.name : _ref19$integrationNam, api = _ref19.api, payload = _ref19.payload;
6315
+ if (!(integrationName === this.config.name || integrationName === 'SYSTEM')) {
4589
6316
  _context6.next = 6;
4590
6317
  break;
4591
6318
  }
@@ -4625,19 +6352,19 @@ var Framework = /*#__PURE__*/function () {
4625
6352
  return callApi;
4626
6353
  }();
4627
6354
  _proto.subscribeEvent = /*#__PURE__*/function () {
4628
- var _subscribeEvent = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(_ref19) {
4629
- var _this$config$runner$u, _this$config$runner, _ref20, _this$config$runner$s, _this$config$runner2;
4630
- var id, _ref19$interval, interval, _ref19$timeout, timeout, inngestApiUrl, inngestApiToken, startTime, _poll;
6355
+ var _subscribeEvent = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(_ref20) {
6356
+ var _this$config$runner$u, _this$config$runner, _ref21, _this$config$runner$s, _this$config$runner2;
6357
+ var id, _ref20$interval, interval, _ref20$timeout, timeout, inngestApiUrl, inngestApiToken, startTime, _poll;
4631
6358
  return _regeneratorRuntime().wrap(function _callee8$(_context8) {
4632
6359
  while (1) switch (_context8.prev = _context8.next) {
4633
6360
  case 0:
4634
- 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;
6361
+ 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;
4635
6362
  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;
4636
- 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';
6363
+ 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';
4637
6364
  startTime = Date.now();
4638
6365
  _poll = /*#__PURE__*/function () {
4639
- var _ref21 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {
4640
- var response, _yield$response$json, data, error, lastRun, elapsedTime;
6366
+ var _ref22 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {
6367
+ var response, obj, data, error, lastRun, elapsedTime;
4641
6368
  return _regeneratorRuntime().wrap(function _callee7$(_context7) {
4642
6369
  while (1) switch (_context7.prev = _context7.next) {
4643
6370
  case 0:
@@ -4652,65 +6379,93 @@ var Framework = /*#__PURE__*/function () {
4652
6379
  });
4653
6380
  case 3:
4654
6381
  response = _context7.sent;
6382
+ console.log("Polling for event " + id + "...", response.ok);
4655
6383
  if (!response.ok) {
4656
- _context7.next = 16;
6384
+ _context7.next = 28;
4657
6385
  break;
4658
6386
  }
4659
- _context7.next = 7;
6387
+ _context7.next = 8;
4660
6388
  return response.json();
4661
- case 7:
4662
- _yield$response$json = _context7.sent;
4663
- data = _yield$response$json.data;
4664
- error = _yield$response$json.error;
6389
+ case 8:
6390
+ obj = _context7.sent;
6391
+ console.log({
6392
+ obj: obj
6393
+ });
6394
+ data = obj.data, error = obj.error;
6395
+ console.log("Got data for event " + id + "...", data, error);
4665
6396
  if (!error) {
4666
- _context7.next = 12;
6397
+ _context7.next = 15;
4667
6398
  break;
4668
6399
  }
6400
+ console.error(error);
4669
6401
  return _context7.abrupt("return", null);
4670
- case 12:
6402
+ case 15:
6403
+ if (!((data == null ? void 0 : data.length) === 0)) {
6404
+ _context7.next = 19;
6405
+ break;
6406
+ }
6407
+ _context7.next = 18;
6408
+ return new Promise(function (resolve) {
6409
+ return setTimeout(resolve, interval);
6410
+ });
6411
+ case 18:
6412
+ return _context7.abrupt("return", _poll());
6413
+ case 19:
4671
6414
  lastRun = data == null ? void 0 : data[0];
6415
+ console.log(lastRun);
4672
6416
  if (lastRun) {
4673
- _context7.next = 15;
6417
+ _context7.next = 23;
4674
6418
  break;
4675
6419
  }
4676
6420
  return _context7.abrupt("return", null);
4677
- case 15:
6421
+ case 23:
6422
+ if (!(lastRun.status === 'Running')) {
6423
+ _context7.next = 27;
6424
+ break;
6425
+ }
6426
+ _context7.next = 26;
6427
+ return new Promise(function (resolve) {
6428
+ return setTimeout(resolve, interval);
6429
+ });
6430
+ case 26:
6431
+ return _context7.abrupt("return", _poll());
6432
+ case 27:
4678
6433
  return _context7.abrupt("return", {
4679
6434
  status: lastRun.status,
4680
6435
  startedAt: lastRun.run_started_at,
4681
6436
  endedAt: lastRun.ended_at
4682
6437
  });
4683
- case 16:
4684
- _context7.next = 21;
6438
+ case 28:
6439
+ _context7.next = 33;
4685
6440
  break;
4686
- case 18:
4687
- _context7.prev = 18;
6441
+ case 30:
6442
+ _context7.prev = 30;
4688
6443
  _context7.t0 = _context7["catch"](0);
4689
6444
  console.error("Request failed: " + _context7.t0);
4690
- case 21:
6445
+ case 33:
4691
6446
  // Check if timeout has been reached
4692
6447
  elapsedTime = Date.now() - startTime;
4693
6448
  if (!(elapsedTime >= timeout)) {
4694
- _context7.next = 25;
6449
+ _context7.next = 37;
4695
6450
  break;
4696
6451
  }
4697
6452
  console.log('Polling timeout reached.');
4698
6453
  return _context7.abrupt("return", null);
4699
- case 25:
4700
- _context7.next = 27;
6454
+ case 37:
6455
+ _context7.next = 39;
4701
6456
  return new Promise(function (resolve) {
4702
6457
  return setTimeout(resolve, interval);
4703
6458
  });
4704
- case 27:
6459
+ case 39:
4705
6460
  return _context7.abrupt("return", _poll());
4706
- case 28:
6461
+ case 40:
4707
6462
  case "end":
4708
6463
  return _context7.stop();
4709
6464
  }
4710
- }, _callee7, null, [[0, 18]]);
6465
+ }, _callee7, null, [[0, 30]]);
4711
6466
  }));
4712
6467
  return function poll() {
4713
- return _ref21.apply(this, arguments);
6468
+ return _ref22.apply(this, arguments);
4714
6469
  };
4715
6470
  }();
4716
6471
  return _context8.abrupt("return", _poll());
@@ -4726,13 +6481,13 @@ var Framework = /*#__PURE__*/function () {
4726
6481
  return subscribeEvent;
4727
6482
  }();
4728
6483
  _proto.triggerEvent = /*#__PURE__*/function () {
4729
- var _triggerEvent = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(_ref22) {
4730
- var _this3 = this;
4731
- var key, data, user, _ref22$integrationNam, integrationName, returnObj, integrationEvents, integrationEvent, event, workflowEvent;
6484
+ var _triggerEvent = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(_ref23) {
6485
+ var _this4 = this;
6486
+ var key, data, user, _ref23$integrationNam, integrationName, returnObj, integrationEvents, integrationEvent, event, workflowEvent;
4732
6487
  return _regeneratorRuntime().wrap(function _callee11$(_context11) {
4733
6488
  while (1) switch (_context11.prev = _context11.next) {
4734
6489
  case 0:
4735
- key = _ref22.key, data = _ref22.data, user = _ref22.user, _ref22$integrationNam = _ref22.integrationName, integrationName = _ref22$integrationNam === void 0 ? this.config.name : _ref22$integrationNam;
6490
+ key = _ref23.key, data = _ref23.data, user = _ref23.user, _ref23$integrationNam = _ref23.integrationName, integrationName = _ref23$integrationNam === void 0 ? this.config.name : _ref23$integrationNam;
4736
6491
  _context11.prev = 1;
4737
6492
  returnObj = {
4738
6493
  event: {}
@@ -4752,7 +6507,7 @@ var Framework = /*#__PURE__*/function () {
4752
6507
  throw new Error("No event exists for " + key + " in " + integrationName);
4753
6508
  case 9:
4754
6509
  _context11.next = 11;
4755
- return client.send({
6510
+ return client$1.send({
4756
6511
  name: key,
4757
6512
  data: data,
4758
6513
  user: user
@@ -4763,12 +6518,12 @@ var Framework = /*#__PURE__*/function () {
4763
6518
  subscribe: function () {
4764
6519
  var _subscribe = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(_temp) {
4765
6520
  var _event$ids;
4766
- var _ref23, interval, timeout;
6521
+ var _ref24, interval, timeout;
4767
6522
  return _regeneratorRuntime().wrap(function _callee9$(_context9) {
4768
6523
  while (1) switch (_context9.prev = _context9.next) {
4769
6524
  case 0:
4770
- _ref23 = _temp === void 0 ? {} : _temp, interval = _ref23.interval, timeout = _ref23.timeout;
4771
- return _context9.abrupt("return", _this3.subscribeEvent({
6525
+ _ref24 = _temp === void 0 ? {} : _temp, interval = _ref24.interval, timeout = _ref24.timeout;
6526
+ return _context9.abrupt("return", _this4.subscribeEvent({
4772
6527
  id: (_event$ids = event.ids) == null ? void 0 : _event$ids[0],
4773
6528
  interval: interval,
4774
6529
  timeout: timeout
@@ -4786,7 +6541,7 @@ var Framework = /*#__PURE__*/function () {
4786
6541
  }()
4787
6542
  });
4788
6543
  _context11.next = 15;
4789
- return client.send({
6544
+ return client$1.send({
4790
6545
  name: 'workflow/run-automations',
4791
6546
  data: {
4792
6547
  trigger: key,
@@ -4800,12 +6555,12 @@ var Framework = /*#__PURE__*/function () {
4800
6555
  subscribe: function () {
4801
6556
  var _subscribe2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(_temp2) {
4802
6557
  var _workflowEvent$ids;
4803
- var _ref24, interval, timeout;
6558
+ var _ref25, interval, timeout;
4804
6559
  return _regeneratorRuntime().wrap(function _callee10$(_context10) {
4805
6560
  while (1) switch (_context10.prev = _context10.next) {
4806
6561
  case 0:
4807
- _ref24 = _temp2 === void 0 ? {} : _temp2, interval = _ref24.interval, timeout = _ref24.timeout;
4808
- return _context10.abrupt("return", _this3.subscribeEvent({
6562
+ _ref25 = _temp2 === void 0 ? {} : _temp2, interval = _ref25.interval, timeout = _ref25.timeout;
6563
+ return _context10.abrupt("return", _this4.subscribeEvent({
4809
6564
  id: (_workflowEvent$ids = workflowEvent.ids) == null ? void 0 : _workflowEvent$ids[0],
4810
6565
  interval: interval,
4811
6566
  timeout: timeout
@@ -4842,14 +6597,14 @@ var Framework = /*#__PURE__*/function () {
4842
6597
  _proto.triggerSystemEvent =
4843
6598
  /*#__PURE__*/
4844
6599
  function () {
4845
- var _triggerSystemEvent = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee12(_ref25) {
6600
+ var _triggerSystemEvent = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee12(_ref26) {
4846
6601
  var key, data, user, event, systemEvent;
4847
6602
  return _regeneratorRuntime().wrap(function _callee12$(_context12) {
4848
6603
  while (1) switch (_context12.prev = _context12.next) {
4849
6604
  case 0:
4850
- key = _ref25.key, data = _ref25.data, user = _ref25.user;
6605
+ key = _ref26.key, data = _ref26.data, user = _ref26.user;
4851
6606
  _context12.next = 3;
4852
- return client.send({
6607
+ return client$1.send({
4853
6608
  name: key,
4854
6609
  data: data,
4855
6610
  user: user
@@ -4862,7 +6617,7 @@ var Framework = /*#__PURE__*/function () {
4862
6617
  break;
4863
6618
  }
4864
6619
  _context12.next = 8;
4865
- return client.send({
6620
+ return client$1.send({
4866
6621
  name: 'workflow/run-automations',
4867
6622
  data: {
4868
6623
  trigger: key,
@@ -4885,10 +6640,10 @@ var Framework = /*#__PURE__*/function () {
4885
6640
  }();
4886
6641
  _proto.createRouter = function createRouter() {
4887
6642
  var self = this;
4888
- var makeWebhookUrl = function makeWebhookUrl(_ref26) {
6643
+ var makeWebhookUrl = function makeWebhookUrl(_ref27) {
4889
6644
  var _self$config;
4890
- var event = _ref26.event,
4891
- name = _ref26.name;
6645
+ var event = _ref27.event,
6646
+ name = _ref27.name;
4892
6647
  return encodeURI("" + (self == null || (_self$config = self.config) == null ? void 0 : _self$config.systemHostURL) + self.routes.webhook + "?name=" + name + "&event=" + event);
4893
6648
  };
4894
6649
  var makeRedirectURI = function makeRedirectURI() {
@@ -4918,25 +6673,60 @@ var Framework = /*#__PURE__*/function () {
4918
6673
  registerRoutes: registerRoutes
4919
6674
  };
4920
6675
  };
4921
- return _createClass(Framework, [{
6676
+ _proto.getAgent = /*#__PURE__*/function () {
6677
+ var _getAgent2 = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee13(_ref28) {
6678
+ var connectionId, agentId, agentBlueprint, arrMap, finalApis;
6679
+ return _regeneratorRuntime().wrap(function _callee13$(_context13) {
6680
+ while (1) switch (_context13.prev = _context13.next) {
6681
+ case 0:
6682
+ connectionId = _ref28.connectionId, agentId = _ref28.agentId;
6683
+ _context13.next = 3;
6684
+ return getAgentBlueprint({
6685
+ agentDir: this.config.agents.agentDirPath,
6686
+ agentId: agentId
6687
+ });
6688
+ case 3:
6689
+ agentBlueprint = _context13.sent;
6690
+ arrMap = Array.from(this.getApis());
6691
+ finalApis = arrMap.reduce(function (acc, _ref29) {
6692
+ var v = _ref29[1];
6693
+ return _extends({}, acc, v);
6694
+ }, {});
6695
+ return _context13.abrupt("return", getAgent({
6696
+ connectionId: connectionId,
6697
+ agent: agentBlueprint,
6698
+ apis: finalApis
6699
+ }));
6700
+ case 7:
6701
+ case "end":
6702
+ return _context13.stop();
6703
+ }
6704
+ }, _callee13, this);
6705
+ }));
6706
+ function getAgent$1(_x12) {
6707
+ return _getAgent2.apply(this, arguments);
6708
+ }
6709
+ return getAgent$1;
6710
+ }();
6711
+ return _createClass(Mastra, [{
4922
6712
  key: "routes",
4923
6713
  get: function get() {
4924
- var _this4 = this;
6714
+ var _this5 = this;
4925
6715
  var registry = {
4926
6716
  connect: '/connect',
4927
6717
  callback: '/connect/callback',
4928
6718
  inngest: '/inngest',
4929
6719
  webhook: '/webhook'
4930
6720
  };
4931
- return Object.entries(registry).reduce(function (acc, _ref27) {
4932
- var _extends3;
4933
- var key = _ref27[0],
4934
- value = _ref27[1];
4935
- return _extends({}, acc, (_extends3 = {}, _extends3[key] = "" + _this4.config.routeRegistrationPath + value, _extends3));
6721
+ return Object.entries(registry).reduce(function (acc, _ref30) {
6722
+ var _extends5;
6723
+ var key = _ref30[0],
6724
+ value = _ref30[1];
6725
+ return _extends({}, acc, (_extends5 = {}, _extends5[key] = "" + _this5.config.routeRegistrationPath + value, _extends5));
4936
6726
  }, {});
4937
6727
  }
4938
6728
  }]);
4939
6729
  }();
4940
6730
 
4941
- export { DataLayer, FieldTypePrimitiveMap, FilterOperatorToSQL, FilterOperators, Framework, Integration, IntegrationAuth, IntegrationCredentialType, IntegrationError, IntegrationErrors, IntegrationFieldTypeEnum, RunStatus, SORT_MODE_TO_ABBR, WorkflowStatusEnum, allowedKey, apiKeyConnectionOptions, buildQueryString, callbackParams, connectParams, constructObjFromStringPath, extractSchemaOptions, fieldsWithCommaSeparatedValues, filterQuerySchema, flattenObject, generateSyncs, getEntityKey, getJSONField, getPath, getResponseDataKey, isLiteralObject, isObjectEmpty, mergeWithDefinedOnly, nextHeaders, oauthState, parseQueryParams, recordHasData, registerRoutes, sortQuerySchema, splitAndStripQuotes, transformFilterValueArray, transformFilterValueBoolean, webhookQueryParams };
6731
+ export { DataLayer, FieldTypePrimitiveMap, FilterOperatorToSQL, FilterOperators, Integration, IntegrationAuth, IntegrationCredentialType, IntegrationError, IntegrationErrors, IntegrationFieldTypeEnum, Mastra, RunStatus, SORT_MODE_TO_ABBR, WorkflowStatusEnum, allowedKey, apiKeyConnectionOptions, buildQueryString, callbackParams, connectParams, constructObjFromStringPath, extractSchemaOptions, fieldsWithCommaSeparatedValues, filterQuerySchema, flattenObject, generateSyncs, getEntityKey, getJSONField, getPath, getResponseDataKey, isLiteralObject, isObjectEmpty, mergeWithDefinedOnly, nextHeaders, oauthState, parseQueryParams, recordHasData, registerRoutes, sortQuerySchema, splitAndStripQuotes, transformFilterValueArray, transformFilterValueBoolean, webhookQueryParams };
4942
6732
  //# sourceMappingURL=core.esm.js.map