@xpert-ai/plugin-sdk 3.6.7 → 3.7.1

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 (43) hide show
  1. package/SCHEMA_SPECIFICATION.md +2 -1
  2. package/index.cjs.js +1278 -241
  3. package/index.esm.js +1270 -243
  4. package/package.json +2 -1
  5. package/src/index.d.ts +2 -0
  6. package/src/lib/agent/index.d.ts +1 -0
  7. package/src/lib/agent/middleware/index.d.ts +5 -0
  8. package/src/lib/agent/middleware/runtime.d.ts +57 -0
  9. package/src/lib/agent/middleware/strategy.decorator.d.ts +2 -0
  10. package/src/lib/agent/middleware/strategy.interface.d.ts +16 -0
  11. package/src/lib/agent/middleware/strategy.registry.d.ts +6 -0
  12. package/src/lib/agent/middleware/types.d.ts +251 -0
  13. package/src/lib/agent/skill/index.d.ts +3 -0
  14. package/src/lib/agent/skill/skill-source-provider.decorator.d.ts +2 -0
  15. package/src/lib/agent/skill/skill-source-provider.interface.d.ts +23 -0
  16. package/src/lib/agent/skill/skill-source-provider.registry.d.ts +6 -0
  17. package/src/lib/ai-model/commands/create-model-client.command.d.ts +21 -0
  18. package/src/lib/ai-model/commands/index.d.ts +1 -0
  19. package/src/lib/ai-model/index.d.ts +1 -0
  20. package/src/lib/ai-model/types/index.d.ts +1 -0
  21. package/src/lib/ai-model/types/model.d.ts +2 -1
  22. package/src/lib/ai-model/types/profile.d.ts +172 -0
  23. package/src/lib/core/index.d.ts +2 -0
  24. package/src/lib/core/strategy-bus.d.ts +17 -0
  25. package/src/lib/core/types.d.ts +16 -0
  26. package/src/lib/data/datasource/strategy.decorator.d.ts +1 -1
  27. package/src/lib/data/datasource/types.d.ts +29 -1
  28. package/src/lib/integration/strategy.decorator.d.ts +1 -1
  29. package/src/lib/rag/image/strategy.decorator.d.ts +1 -1
  30. package/src/lib/rag/knowledge/knowledge-strategy.decorator.d.ts +1 -1
  31. package/src/lib/rag/retriever/strategy.decorator.d.ts +1 -1
  32. package/src/lib/rag/source/strategy.decorator.d.ts +1 -1
  33. package/src/lib/rag/textsplitter/strategy.decorator.d.ts +1 -1
  34. package/src/lib/rag/transformer/strategy.decorator.d.ts +1 -1
  35. package/src/lib/strategy.d.ts +29 -3
  36. package/src/lib/toolset/strategy.decorator.d.ts +1 -1
  37. package/src/lib/types.d.ts +4 -0
  38. package/src/lib/vectorstore/strategy.decorator.d.ts +1 -1
  39. package/src/lib/workflow/commands/index.d.ts +1 -0
  40. package/src/lib/workflow/commands/wrap-workflow-node-execution.command.d.ts +26 -0
  41. package/src/lib/workflow/index.d.ts +1 -0
  42. package/src/lib/workflow/node/strategy.decorator.d.ts +1 -1
  43. package/src/lib/workflow/trigger/strategy.decorator.d.ts +1 -1
package/index.cjs.js CHANGED
@@ -4,10 +4,15 @@ var common = require('@nestjs/common');
4
4
  var constants = require('@nestjs/common/constants');
5
5
  var lodashEs = require('lodash-es');
6
6
  var core = require('@nestjs/core');
7
+ var contracts = require('@metad/contracts');
8
+ var node_async_hooks = require('node:async_hooks');
9
+ var passportJwt = require('passport-jwt');
10
+ var jsonwebtoken = require('jsonwebtoken');
11
+ var node_crypto = require('node:crypto');
12
+ var cqrs = require('@nestjs/cqrs');
7
13
  var fs = require('fs');
8
14
  var http = require('http');
9
15
  var https = require('https');
10
- var contracts = require('@metad/contracts');
11
16
  var tools = require('@langchain/core/tools');
12
17
  var zod = require('zod');
13
18
  var fsPromises = require('fs/promises');
@@ -15,10 +20,6 @@ var path = require('path');
15
20
  var i18next = require('i18next');
16
21
  var FsBackend = require('i18next-fs-backend');
17
22
  var yaml = require('yaml');
18
- var node_async_hooks = require('node:async_hooks');
19
- var passportJwt = require('passport-jwt');
20
- var jsonwebtoken = require('jsonwebtoken');
21
- var node_crypto = require('node:crypto');
22
23
  var _axios = require('axios');
23
24
  var openai = require('@langchain/openai');
24
25
  var documents = require('@langchain/core/documents');
@@ -83,6 +84,11 @@ var _axios__namespace = /*#__PURE__*/_interopNamespaceDefault(_axios);
83
84
  };
84
85
  }
85
86
 
87
+ const ORGANIZATION_METADATA_KEY = 'xpert:organizationId';
88
+ const PLUGIN_METADATA_KEY = 'xpert:pluginName';
89
+ const GLOBAL_ORGANIZATION_SCOPE = 'global';
90
+ const STRATEGY_META_KEY = 'XPERT_STRATEGY_META_KEY';
91
+
86
92
  function _extends() {
87
93
  _extends = Object.assign || function assign(target) {
88
94
  for(var i = 1; i < arguments.length; i++){
@@ -114,8 +120,46 @@ function createPluginLogger(scope, baseMeta = {}) {
114
120
  }
115
121
 
116
122
  const INTEGRATION_STRATEGY = 'INTEGRATION_STRATEGY';
117
- const IntegrationStrategyKey = (provider)=>common.SetMetadata(INTEGRATION_STRATEGY, provider);
118
-
123
+ const IntegrationStrategyKey = (provider)=>common.applyDecorators(common.SetMetadata(INTEGRATION_STRATEGY, provider), common.SetMetadata(STRATEGY_META_KEY, INTEGRATION_STRATEGY));
124
+
125
+ /******************************************************************************
126
+ Copyright (c) Microsoft Corporation.
127
+
128
+ Permission to use, copy, modify, and/or distribute this software for any
129
+ purpose with or without fee is hereby granted.
130
+
131
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
132
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
133
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
134
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
135
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
136
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
137
+ PERFORMANCE OF THIS SOFTWARE.
138
+ ***************************************************************************** */ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */ function _instanceof$2(left, right) {
139
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
140
+ return !!right[Symbol.hasInstance](left);
141
+ } else {
142
+ return left instanceof right;
143
+ }
144
+ }
145
+ var extendStatics = function extendStatics1(d, b) {
146
+ extendStatics = Object.setPrototypeOf || _instanceof$2({
147
+ __proto__: []
148
+ }, Array) && function(d, b) {
149
+ d.__proto__ = b;
150
+ } || function(d, b) {
151
+ for(var p in b)if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
152
+ };
153
+ return extendStatics(d, b);
154
+ };
155
+ function __extends(d, b) {
156
+ if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
157
+ extendStatics(d, b);
158
+ function __() {
159
+ this.constructor = d;
160
+ }
161
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
162
+ }
119
163
  function __decorate(decorators, target, key, desc) {
120
164
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
121
165
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -125,40 +169,1104 @@ function __decorate(decorators, target, key, desc) {
125
169
  function __metadata(metadataKey, metadataValue) {
126
170
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
127
171
  }
172
+ function __values(o) {
173
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
174
+ if (m) return m.call(o);
175
+ if (o && typeof o.length === "number") return {
176
+ next: function next() {
177
+ if (o && i >= o.length) o = void 0;
178
+ return {
179
+ value: o && o[i++],
180
+ done: !o
181
+ };
182
+ }
183
+ };
184
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
185
+ }
186
+ function __read(o, n) {
187
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
188
+ if (!m) return o;
189
+ var i = m.call(o), r, ar = [], e;
190
+ try {
191
+ while((n === void 0 || n-- > 0) && !(r = i.next()).done)ar.push(r.value);
192
+ } catch (error) {
193
+ e = {
194
+ error: error
195
+ };
196
+ } finally{
197
+ try {
198
+ if (r && !r.done && (m = i["return"])) m.call(i);
199
+ } finally{
200
+ if (e) throw e.error;
201
+ }
202
+ }
203
+ return ar;
204
+ }
205
+ function __spreadArray(to, from, pack) {
206
+ if (pack || arguments.length === 2) for(var i = 0, l = from.length, ar; i < l; i++){
207
+ if (ar || !(i in from)) {
208
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
209
+ ar[i] = from[i];
210
+ }
211
+ }
212
+ return to.concat(ar || Array.prototype.slice.call(from));
213
+ }
128
214
  typeof SuppressedError === "function" ? SuppressedError : function _SuppressedError(error, suppressed, message) {
129
215
  var e = new Error(message);
130
216
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
131
217
  };
132
218
 
219
+ function isFunction(value) {
220
+ return typeof value === "function";
221
+ }
222
+
223
+ function createErrorClass(createImpl) {
224
+ var _super = function _super(instance) {
225
+ Error.call(instance);
226
+ instance.stack = new Error().stack;
227
+ };
228
+ var ctorFunc = createImpl(_super);
229
+ ctorFunc.prototype = Object.create(Error.prototype);
230
+ ctorFunc.prototype.constructor = ctorFunc;
231
+ return ctorFunc;
232
+ }
233
+
234
+ var UnsubscriptionError = createErrorClass(function(_super) {
235
+ return function UnsubscriptionErrorImpl(errors) {
236
+ _super(this);
237
+ this.message = errors ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function(err, i) {
238
+ return i + 1 + ") " + err.toString();
239
+ }).join("\n ") : "";
240
+ this.name = "UnsubscriptionError";
241
+ this.errors = errors;
242
+ };
243
+ });
244
+
245
+ function arrRemove(arr, item) {
246
+ if (arr) {
247
+ var index = arr.indexOf(item);
248
+ 0 <= index && arr.splice(index, 1);
249
+ }
250
+ }
251
+
252
+ function _instanceof$1(left, right) {
253
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
254
+ return !!right[Symbol.hasInstance](left);
255
+ } else {
256
+ return left instanceof right;
257
+ }
258
+ }
259
+ var Subscription = function() {
260
+ function Subscription(initialTeardown) {
261
+ this.initialTeardown = initialTeardown;
262
+ this.closed = false;
263
+ this._parentage = null;
264
+ this._finalizers = null;
265
+ }
266
+ Subscription.prototype.unsubscribe = function() {
267
+ var e_1, _a, e_2, _b;
268
+ var errors;
269
+ if (!this.closed) {
270
+ this.closed = true;
271
+ var _parentage = this._parentage;
272
+ if (_parentage) {
273
+ this._parentage = null;
274
+ if (Array.isArray(_parentage)) {
275
+ try {
276
+ for(var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()){
277
+ var parent_1 = _parentage_1_1.value;
278
+ parent_1.remove(this);
279
+ }
280
+ } catch (e_1_1) {
281
+ e_1 = {
282
+ error: e_1_1
283
+ };
284
+ } finally{
285
+ try {
286
+ if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
287
+ } finally{
288
+ if (e_1) throw e_1.error;
289
+ }
290
+ }
291
+ } else {
292
+ _parentage.remove(this);
293
+ }
294
+ }
295
+ var initialFinalizer = this.initialTeardown;
296
+ if (isFunction(initialFinalizer)) {
297
+ try {
298
+ initialFinalizer();
299
+ } catch (e) {
300
+ errors = _instanceof$1(e, UnsubscriptionError) ? e.errors : [
301
+ e
302
+ ];
303
+ }
304
+ }
305
+ var _finalizers = this._finalizers;
306
+ if (_finalizers) {
307
+ this._finalizers = null;
308
+ try {
309
+ for(var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()){
310
+ var finalizer = _finalizers_1_1.value;
311
+ try {
312
+ execFinalizer(finalizer);
313
+ } catch (err) {
314
+ errors = errors !== null && errors !== void 0 ? errors : [];
315
+ if (_instanceof$1(err, UnsubscriptionError)) {
316
+ errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));
317
+ } else {
318
+ errors.push(err);
319
+ }
320
+ }
321
+ }
322
+ } catch (e_2_1) {
323
+ e_2 = {
324
+ error: e_2_1
325
+ };
326
+ } finally{
327
+ try {
328
+ if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
329
+ } finally{
330
+ if (e_2) throw e_2.error;
331
+ }
332
+ }
333
+ }
334
+ if (errors) {
335
+ throw new UnsubscriptionError(errors);
336
+ }
337
+ }
338
+ };
339
+ Subscription.prototype.add = function(teardown) {
340
+ var _a;
341
+ if (teardown && teardown !== this) {
342
+ if (this.closed) {
343
+ execFinalizer(teardown);
344
+ } else {
345
+ if (_instanceof$1(teardown, Subscription)) {
346
+ if (teardown.closed || teardown._hasParent(this)) {
347
+ return;
348
+ }
349
+ teardown._addParent(this);
350
+ }
351
+ (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
352
+ }
353
+ }
354
+ };
355
+ Subscription.prototype._hasParent = function(parent) {
356
+ var _parentage = this._parentage;
357
+ return _parentage === parent || Array.isArray(_parentage) && _parentage.includes(parent);
358
+ };
359
+ Subscription.prototype._addParent = function(parent) {
360
+ var _parentage = this._parentage;
361
+ this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [
362
+ _parentage,
363
+ parent
364
+ ] : parent;
365
+ };
366
+ Subscription.prototype._removeParent = function(parent) {
367
+ var _parentage = this._parentage;
368
+ if (_parentage === parent) {
369
+ this._parentage = null;
370
+ } else if (Array.isArray(_parentage)) {
371
+ arrRemove(_parentage, parent);
372
+ }
373
+ };
374
+ Subscription.prototype.remove = function(teardown) {
375
+ var _finalizers = this._finalizers;
376
+ _finalizers && arrRemove(_finalizers, teardown);
377
+ if (_instanceof$1(teardown, Subscription)) {
378
+ teardown._removeParent(this);
379
+ }
380
+ };
381
+ Subscription.EMPTY = function() {
382
+ var empty = new Subscription();
383
+ empty.closed = true;
384
+ return empty;
385
+ }();
386
+ return Subscription;
387
+ }();
388
+ var EMPTY_SUBSCRIPTION = Subscription.EMPTY;
389
+ function isSubscription(value) {
390
+ return _instanceof$1(value, Subscription) || value && "closed" in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe);
391
+ }
392
+ function execFinalizer(finalizer) {
393
+ if (isFunction(finalizer)) {
394
+ finalizer();
395
+ } else {
396
+ finalizer.unsubscribe();
397
+ }
398
+ }
399
+
400
+ var config = {
401
+ Promise: undefined};
402
+
403
+ var timeoutProvider = {
404
+ setTimeout: function setTimeout1(handler, timeout) {
405
+ var args = [];
406
+ for(var _i = 2; _i < arguments.length; _i++){
407
+ args[_i - 2] = arguments[_i];
408
+ }
409
+ return setTimeout.apply(void 0, __spreadArray([
410
+ handler,
411
+ timeout
412
+ ], __read(args)));
413
+ },
414
+ clearTimeout: function clearTimeout1(handle) {
415
+ return (clearTimeout)(handle);
416
+ },
417
+ delegate: undefined
418
+ };
419
+
420
+ function reportUnhandledError(err) {
421
+ timeoutProvider.setTimeout(function() {
422
+ {
423
+ throw err;
424
+ }
425
+ });
426
+ }
427
+
428
+ function noop() {}
429
+
430
+ function errorContext(cb) {
431
+ {
432
+ cb();
433
+ }
434
+ }
435
+
436
+ var Subscriber = function(_super) {
437
+ __extends(Subscriber, _super);
438
+ function Subscriber(destination) {
439
+ var _this = _super.call(this) || this;
440
+ _this.isStopped = false;
441
+ if (destination) {
442
+ _this.destination = destination;
443
+ if (isSubscription(destination)) {
444
+ destination.add(_this);
445
+ }
446
+ } else {
447
+ _this.destination = EMPTY_OBSERVER;
448
+ }
449
+ return _this;
450
+ }
451
+ Subscriber.create = function(next, error, complete) {
452
+ return new SafeSubscriber(next, error, complete);
453
+ };
454
+ Subscriber.prototype.next = function(value) {
455
+ if (this.isStopped) ; else {
456
+ this._next(value);
457
+ }
458
+ };
459
+ Subscriber.prototype.error = function(err) {
460
+ if (this.isStopped) ; else {
461
+ this.isStopped = true;
462
+ this._error(err);
463
+ }
464
+ };
465
+ Subscriber.prototype.complete = function() {
466
+ if (this.isStopped) ; else {
467
+ this.isStopped = true;
468
+ this._complete();
469
+ }
470
+ };
471
+ Subscriber.prototype.unsubscribe = function() {
472
+ if (!this.closed) {
473
+ this.isStopped = true;
474
+ _super.prototype.unsubscribe.call(this);
475
+ this.destination = null;
476
+ }
477
+ };
478
+ Subscriber.prototype._next = function(value) {
479
+ this.destination.next(value);
480
+ };
481
+ Subscriber.prototype._error = function(err) {
482
+ try {
483
+ this.destination.error(err);
484
+ } finally{
485
+ this.unsubscribe();
486
+ }
487
+ };
488
+ Subscriber.prototype._complete = function() {
489
+ try {
490
+ this.destination.complete();
491
+ } finally{
492
+ this.unsubscribe();
493
+ }
494
+ };
495
+ return Subscriber;
496
+ }(Subscription);
497
+ var ConsumerObserver = function() {
498
+ function ConsumerObserver(partialObserver) {
499
+ this.partialObserver = partialObserver;
500
+ }
501
+ ConsumerObserver.prototype.next = function(value) {
502
+ var partialObserver = this.partialObserver;
503
+ if (partialObserver.next) {
504
+ try {
505
+ partialObserver.next(value);
506
+ } catch (error) {
507
+ handleUnhandledError(error);
508
+ }
509
+ }
510
+ };
511
+ ConsumerObserver.prototype.error = function(err) {
512
+ var partialObserver = this.partialObserver;
513
+ if (partialObserver.error) {
514
+ try {
515
+ partialObserver.error(err);
516
+ } catch (error) {
517
+ handleUnhandledError(error);
518
+ }
519
+ } else {
520
+ handleUnhandledError(err);
521
+ }
522
+ };
523
+ ConsumerObserver.prototype.complete = function() {
524
+ var partialObserver = this.partialObserver;
525
+ if (partialObserver.complete) {
526
+ try {
527
+ partialObserver.complete();
528
+ } catch (error) {
529
+ handleUnhandledError(error);
530
+ }
531
+ }
532
+ };
533
+ return ConsumerObserver;
534
+ }();
535
+ var SafeSubscriber = function(_super) {
536
+ __extends(SafeSubscriber, _super);
537
+ function SafeSubscriber(observerOrNext, error, complete) {
538
+ var _this = _super.call(this) || this;
539
+ var partialObserver;
540
+ if (isFunction(observerOrNext) || !observerOrNext) {
541
+ partialObserver = {
542
+ next: observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : undefined,
543
+ error: error !== null && error !== void 0 ? error : undefined,
544
+ complete: complete !== null && complete !== void 0 ? complete : undefined
545
+ };
546
+ } else {
547
+ {
548
+ partialObserver = observerOrNext;
549
+ }
550
+ }
551
+ _this.destination = new ConsumerObserver(partialObserver);
552
+ return _this;
553
+ }
554
+ return SafeSubscriber;
555
+ }(Subscriber);
556
+ function handleUnhandledError(error) {
557
+ {
558
+ reportUnhandledError(error);
559
+ }
560
+ }
561
+ function defaultErrorHandler(err) {
562
+ throw err;
563
+ }
564
+ var EMPTY_OBSERVER = {
565
+ closed: true,
566
+ next: noop,
567
+ error: defaultErrorHandler,
568
+ complete: noop
569
+ };
570
+
571
+ var observable = function() {
572
+ return typeof Symbol === "function" && Symbol.observable || "@@observable";
573
+ }();
574
+
575
+ function identity(x) {
576
+ return x;
577
+ }
578
+
579
+ function pipeFromArray(fns) {
580
+ if (fns.length === 0) {
581
+ return identity;
582
+ }
583
+ if (fns.length === 1) {
584
+ return fns[0];
585
+ }
586
+ return function piped(input) {
587
+ return fns.reduce(function(prev, fn) {
588
+ return fn(prev);
589
+ }, input);
590
+ };
591
+ }
592
+
593
+ function _instanceof(left, right) {
594
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
595
+ return !!right[Symbol.hasInstance](left);
596
+ } else {
597
+ return left instanceof right;
598
+ }
599
+ }
600
+ var Observable = function() {
601
+ function Observable(subscribe) {
602
+ if (subscribe) {
603
+ this._subscribe = subscribe;
604
+ }
605
+ }
606
+ Observable.prototype.lift = function(operator) {
607
+ var observable = new Observable();
608
+ observable.source = this;
609
+ observable.operator = operator;
610
+ return observable;
611
+ };
612
+ Observable.prototype.subscribe = function(observerOrNext, error, complete) {
613
+ var _this = this;
614
+ var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
615
+ errorContext(function() {
616
+ var _a = _this, operator = _a.operator, source = _a.source;
617
+ subscriber.add(operator ? operator.call(subscriber, source) : source ? _this._subscribe(subscriber) : _this._trySubscribe(subscriber));
618
+ });
619
+ return subscriber;
620
+ };
621
+ Observable.prototype._trySubscribe = function(sink) {
622
+ try {
623
+ return this._subscribe(sink);
624
+ } catch (err) {
625
+ sink.error(err);
626
+ }
627
+ };
628
+ Observable.prototype.forEach = function(next, promiseCtor) {
629
+ var _this = this;
630
+ promiseCtor = getPromiseCtor(promiseCtor);
631
+ return new promiseCtor(function(resolve, reject) {
632
+ var subscriber = new SafeSubscriber({
633
+ next: function next1(value) {
634
+ try {
635
+ next(value);
636
+ } catch (err) {
637
+ reject(err);
638
+ subscriber.unsubscribe();
639
+ }
640
+ },
641
+ error: reject,
642
+ complete: resolve
643
+ });
644
+ _this.subscribe(subscriber);
645
+ });
646
+ };
647
+ Observable.prototype._subscribe = function(subscriber) {
648
+ var _a;
649
+ return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
650
+ };
651
+ Observable.prototype[observable] = function() {
652
+ return this;
653
+ };
654
+ Observable.prototype.pipe = function() {
655
+ var operations = [];
656
+ for(var _i = 0; _i < arguments.length; _i++){
657
+ operations[_i] = arguments[_i];
658
+ }
659
+ return pipeFromArray(operations)(this);
660
+ };
661
+ Observable.prototype.toPromise = function(promiseCtor) {
662
+ var _this = this;
663
+ promiseCtor = getPromiseCtor(promiseCtor);
664
+ return new promiseCtor(function(resolve, reject) {
665
+ var value;
666
+ _this.subscribe(function(x) {
667
+ return value = x;
668
+ }, function(err) {
669
+ return reject(err);
670
+ }, function() {
671
+ return resolve(value);
672
+ });
673
+ });
674
+ };
675
+ Observable.create = function(subscribe) {
676
+ return new Observable(subscribe);
677
+ };
678
+ return Observable;
679
+ }();
680
+ function getPromiseCtor(promiseCtor) {
681
+ var _a;
682
+ return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise;
683
+ }
684
+ function isObserver(value) {
685
+ return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
686
+ }
687
+ function isSubscriber(value) {
688
+ return value && _instanceof(value, Subscriber) || isObserver(value) && isSubscription(value);
689
+ }
690
+
691
+ function hasLift(source) {
692
+ return isFunction(source === null || source === void 0 ? void 0 : source.lift);
693
+ }
694
+ function operate(init) {
695
+ return function(source) {
696
+ if (hasLift(source)) {
697
+ return source.lift(function(liftedSource) {
698
+ try {
699
+ return init(liftedSource, this);
700
+ } catch (err) {
701
+ this.error(err);
702
+ }
703
+ });
704
+ }
705
+ throw new TypeError("Unable to lift unknown Observable type");
706
+ };
707
+ }
708
+
709
+ function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
710
+ return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
711
+ }
712
+ var OperatorSubscriber = function(_super) {
713
+ __extends(OperatorSubscriber, _super);
714
+ function OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
715
+ var _this = _super.call(this, destination) || this;
716
+ _this.onFinalize = onFinalize;
717
+ _this.shouldUnsubscribe = shouldUnsubscribe;
718
+ _this._next = onNext ? function(value) {
719
+ try {
720
+ onNext(value);
721
+ } catch (err) {
722
+ destination.error(err);
723
+ }
724
+ } : _super.prototype._next;
725
+ _this._error = onError ? function(err) {
726
+ try {
727
+ onError(err);
728
+ } catch (err) {
729
+ destination.error(err);
730
+ } finally{
731
+ this.unsubscribe();
732
+ }
733
+ } : _super.prototype._error;
734
+ _this._complete = onComplete ? function() {
735
+ try {
736
+ onComplete();
737
+ } catch (err) {
738
+ destination.error(err);
739
+ } finally{
740
+ this.unsubscribe();
741
+ }
742
+ } : _super.prototype._complete;
743
+ return _this;
744
+ }
745
+ OperatorSubscriber.prototype.unsubscribe = function() {
746
+ var _a;
747
+ if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
748
+ var closed_1 = this.closed;
749
+ _super.prototype.unsubscribe.call(this);
750
+ !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));
751
+ }
752
+ };
753
+ return OperatorSubscriber;
754
+ }(Subscriber);
755
+
756
+ var ObjectUnsubscribedError = createErrorClass(function(_super) {
757
+ return function ObjectUnsubscribedErrorImpl() {
758
+ _super(this);
759
+ this.name = "ObjectUnsubscribedError";
760
+ this.message = "object unsubscribed";
761
+ };
762
+ });
763
+
764
+ var Subject = function(_super) {
765
+ __extends(Subject, _super);
766
+ function Subject() {
767
+ var _this = _super.call(this) || this;
768
+ _this.closed = false;
769
+ _this.currentObservers = null;
770
+ _this.observers = [];
771
+ _this.isStopped = false;
772
+ _this.hasError = false;
773
+ _this.thrownError = null;
774
+ return _this;
775
+ }
776
+ Subject.prototype.lift = function(operator) {
777
+ var subject = new AnonymousSubject(this, this);
778
+ subject.operator = operator;
779
+ return subject;
780
+ };
781
+ Subject.prototype._throwIfClosed = function() {
782
+ if (this.closed) {
783
+ throw new ObjectUnsubscribedError();
784
+ }
785
+ };
786
+ Subject.prototype.next = function(value) {
787
+ var _this = this;
788
+ errorContext(function() {
789
+ var e_1, _a;
790
+ _this._throwIfClosed();
791
+ if (!_this.isStopped) {
792
+ if (!_this.currentObservers) {
793
+ _this.currentObservers = Array.from(_this.observers);
794
+ }
795
+ try {
796
+ for(var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()){
797
+ var observer = _c.value;
798
+ observer.next(value);
799
+ }
800
+ } catch (e_1_1) {
801
+ e_1 = {
802
+ error: e_1_1
803
+ };
804
+ } finally{
805
+ try {
806
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
807
+ } finally{
808
+ if (e_1) throw e_1.error;
809
+ }
810
+ }
811
+ }
812
+ });
813
+ };
814
+ Subject.prototype.error = function(err) {
815
+ var _this = this;
816
+ errorContext(function() {
817
+ _this._throwIfClosed();
818
+ if (!_this.isStopped) {
819
+ _this.hasError = _this.isStopped = true;
820
+ _this.thrownError = err;
821
+ var observers = _this.observers;
822
+ while(observers.length){
823
+ observers.shift().error(err);
824
+ }
825
+ }
826
+ });
827
+ };
828
+ Subject.prototype.complete = function() {
829
+ var _this = this;
830
+ errorContext(function() {
831
+ _this._throwIfClosed();
832
+ if (!_this.isStopped) {
833
+ _this.isStopped = true;
834
+ var observers = _this.observers;
835
+ while(observers.length){
836
+ observers.shift().complete();
837
+ }
838
+ }
839
+ });
840
+ };
841
+ Subject.prototype.unsubscribe = function() {
842
+ this.isStopped = this.closed = true;
843
+ this.observers = this.currentObservers = null;
844
+ };
845
+ Object.defineProperty(Subject.prototype, "observed", {
846
+ get: function get() {
847
+ var _a;
848
+ return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0;
849
+ },
850
+ enumerable: false,
851
+ configurable: true
852
+ });
853
+ Subject.prototype._trySubscribe = function(subscriber) {
854
+ this._throwIfClosed();
855
+ return _super.prototype._trySubscribe.call(this, subscriber);
856
+ };
857
+ Subject.prototype._subscribe = function(subscriber) {
858
+ this._throwIfClosed();
859
+ this._checkFinalizedStatuses(subscriber);
860
+ return this._innerSubscribe(subscriber);
861
+ };
862
+ Subject.prototype._innerSubscribe = function(subscriber) {
863
+ var _this = this;
864
+ var _a = this, hasError = _a.hasError, isStopped = _a.isStopped, observers = _a.observers;
865
+ if (hasError || isStopped) {
866
+ return EMPTY_SUBSCRIPTION;
867
+ }
868
+ this.currentObservers = null;
869
+ observers.push(subscriber);
870
+ return new Subscription(function() {
871
+ _this.currentObservers = null;
872
+ arrRemove(observers, subscriber);
873
+ });
874
+ };
875
+ Subject.prototype._checkFinalizedStatuses = function(subscriber) {
876
+ var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, isStopped = _a.isStopped;
877
+ if (hasError) {
878
+ subscriber.error(thrownError);
879
+ } else if (isStopped) {
880
+ subscriber.complete();
881
+ }
882
+ };
883
+ Subject.prototype.asObservable = function() {
884
+ var observable = new Observable();
885
+ observable.source = this;
886
+ return observable;
887
+ };
888
+ Subject.create = function(destination, source) {
889
+ return new AnonymousSubject(destination, source);
890
+ };
891
+ return Subject;
892
+ }(Observable);
893
+ var AnonymousSubject = function(_super) {
894
+ __extends(AnonymousSubject, _super);
895
+ function AnonymousSubject(destination, source) {
896
+ var _this = _super.call(this) || this;
897
+ _this.destination = destination;
898
+ _this.source = source;
899
+ return _this;
900
+ }
901
+ AnonymousSubject.prototype.next = function(value) {
902
+ var _a, _b;
903
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value);
904
+ };
905
+ AnonymousSubject.prototype.error = function(err) {
906
+ var _a, _b;
907
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err);
908
+ };
909
+ AnonymousSubject.prototype.complete = function() {
910
+ var _a, _b;
911
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a);
912
+ };
913
+ AnonymousSubject.prototype._subscribe = function(subscriber) {
914
+ var _a, _b;
915
+ return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : EMPTY_SUBSCRIPTION;
916
+ };
917
+ return AnonymousSubject;
918
+ }(Subject);
919
+
920
+ function filter(predicate, thisArg) {
921
+ return operate(function(source, subscriber) {
922
+ var index = 0;
923
+ source.subscribe(createOperatorSubscriber(subscriber, function(value) {
924
+ return predicate.call(thisArg, value, index++) && subscriber.next(value);
925
+ }));
926
+ });
927
+ }
928
+
929
+ // request-context.ts
930
+ class RequestContext {
931
+ static currentRequestContext() {
932
+ const session = getRequestContext();
933
+ return session;
934
+ }
935
+ static currentRequest() {
936
+ const requestContext = RequestContext.currentRequestContext();
937
+ if (requestContext) {
938
+ return requestContext.request;
939
+ }
940
+ return null;
941
+ }
942
+ static currentTenantId() {
943
+ const user = RequestContext.currentUser();
944
+ if (user) {
945
+ return user.tenantId;
946
+ }
947
+ return null;
948
+ }
949
+ static currentUserId() {
950
+ const user = RequestContext.currentUser();
951
+ if (user) {
952
+ return user.id;
953
+ }
954
+ return null;
955
+ }
956
+ static currentRoleId() {
957
+ const user = RequestContext.currentUser();
958
+ if (user) {
959
+ return user.roleId;
960
+ }
961
+ return null;
962
+ }
963
+ static currentUser(throwError) {
964
+ const requestContext = RequestContext.currentRequestContext();
965
+ if (requestContext) {
966
+ // tslint:disable-next-line
967
+ const user = requestContext.request['user'];
968
+ if (user) {
969
+ return user;
970
+ }
971
+ }
972
+ if (throwError) {
973
+ throw new common.HttpException('Unauthorized', common.HttpStatus.UNAUTHORIZED);
974
+ }
975
+ return null;
976
+ }
977
+ static hasPermission(permission, throwError) {
978
+ return this.hasPermissions([
979
+ permission
980
+ ], throwError);
981
+ }
982
+ /**
983
+ * Retrieves the language code from the headers of the current request.
984
+ * @returns The language code (LanguagesEnum) extracted from the headers, or the default language (ENGLISH) if not found.
985
+ */ static getLanguageCode() {
986
+ // Retrieve the current request
987
+ const req = RequestContext.currentRequest();
988
+ // Variable to store the extracted language code
989
+ let lang;
990
+ // Check if a request exists
991
+ if (req) {
992
+ // Check if the 'language' header exists in the request
993
+ if (req.headers && req.headers['language']) {
994
+ // If found, set the lang variable
995
+ lang = req.headers['language'];
996
+ }
997
+ }
998
+ // Return the extracted language code or the default language (ENGLISH) if not found
999
+ return lang || contracts.LanguagesEnum.English;
1000
+ }
1001
+ static getOrganizationId() {
1002
+ const req = this.currentRequest();
1003
+ let organizationId;
1004
+ const keys = [
1005
+ 'organization-id'
1006
+ ];
1007
+ if (req) {
1008
+ for (const key of keys){
1009
+ if (req.headers && req.headers[key]) {
1010
+ organizationId = req.headers[key];
1011
+ break;
1012
+ }
1013
+ }
1014
+ }
1015
+ return organizationId;
1016
+ }
1017
+ static hasPermissions(findPermissions, throwError) {
1018
+ const requestContext = RequestContext.currentRequestContext();
1019
+ if (requestContext) {
1020
+ // tslint:disable-next-line
1021
+ const token = passportJwt.ExtractJwt.fromAuthHeaderAsBearerToken()(requestContext.request);
1022
+ if (token) {
1023
+ const { permissions } = jsonwebtoken.verify(token, process.env['JWT_SECRET']);
1024
+ if (permissions) {
1025
+ const found = permissions.filter((value)=>findPermissions.indexOf(value) >= 0);
1026
+ if (found.length === findPermissions.length) {
1027
+ return true;
1028
+ }
1029
+ } else {
1030
+ return false;
1031
+ }
1032
+ }
1033
+ }
1034
+ if (throwError) {
1035
+ throw new common.HttpException('Unauthorized', common.HttpStatus.UNAUTHORIZED);
1036
+ }
1037
+ return false;
1038
+ }
1039
+ static hasAnyPermission(findPermissions, throwError) {
1040
+ const requestContext = RequestContext.currentRequestContext();
1041
+ if (requestContext) {
1042
+ // tslint:disable-next-line
1043
+ const token = passportJwt.ExtractJwt.fromAuthHeaderAsBearerToken()(requestContext.request);
1044
+ if (token) {
1045
+ const { permissions } = jsonwebtoken.verify(token, process.env['JWT_SECRET']);
1046
+ const found = permissions.filter((value)=>findPermissions.indexOf(value) >= 0);
1047
+ if (found.length > 0) {
1048
+ return true;
1049
+ }
1050
+ }
1051
+ }
1052
+ if (throwError) {
1053
+ throw new common.HttpException('Unauthorized', common.HttpStatus.UNAUTHORIZED);
1054
+ }
1055
+ return false;
1056
+ }
1057
+ static currentToken(throwError) {
1058
+ const requestContext = RequestContext.currentRequestContext();
1059
+ if (requestContext) {
1060
+ // tslint:disable-next-line
1061
+ return passportJwt.ExtractJwt.fromAuthHeaderAsBearerToken()(requestContext.request);
1062
+ }
1063
+ if (throwError) {
1064
+ throw new common.HttpException('Unauthorized', common.HttpStatus.UNAUTHORIZED);
1065
+ }
1066
+ return null;
1067
+ }
1068
+ /**
1069
+ * Checks if the current user has a specific role.
1070
+ * @param {RolesEnum} role - The role to check.
1071
+ * @param {boolean} throwError - Flag indicating whether to throw an error if the role is not granted.
1072
+ * @returns {boolean} - True if the user has the role, otherwise false.
1073
+ */ static hasRole(role, throwError) {
1074
+ return this.hasRoles([
1075
+ role
1076
+ ], throwError);
1077
+ }
1078
+ /**
1079
+ * Checks if the current request context has any of the specified roles.
1080
+ *
1081
+ * @param roles - An array of roles to check.
1082
+ * @param throwError - Whether to throw an error if no roles are found.
1083
+ * @returns True if any of the required roles are found, otherwise false.
1084
+ */ static hasRoles(roles, throwError) {
1085
+ const context = RequestContext.currentRequestContext();
1086
+ if (context) {
1087
+ try {
1088
+ // tslint:disable-next-line
1089
+ const token = this.currentToken();
1090
+ if (token) {
1091
+ const { role } = jsonwebtoken.verify(token, process.env['JWT_SECRET']);
1092
+ return roles.includes(role != null ? role : null);
1093
+ } else if (this.currentUser().role) {
1094
+ return roles.includes(this.currentUser().role.name);
1095
+ }
1096
+ } catch (error) {
1097
+ if (error instanceof jsonwebtoken.JsonWebTokenError) {
1098
+ return false;
1099
+ } else {
1100
+ throw error;
1101
+ }
1102
+ }
1103
+ }
1104
+ if (throwError) {
1105
+ throw new common.HttpException('Unauthorized', common.HttpStatus.UNAUTHORIZED);
1106
+ }
1107
+ return false;
1108
+ }
1109
+ constructor(request, response, reqId, userId, extras = {}){
1110
+ this.request = request;
1111
+ this.response = response;
1112
+ this.reqId = reqId;
1113
+ this.userId = userId;
1114
+ this.extras = extras;
1115
+ }
1116
+ }
1117
+ const als = new node_async_hooks.AsyncLocalStorage();
1118
+ function getRequestContext() {
1119
+ return als.getStore();
1120
+ }
1121
+
1122
+ // request-context.middleware.ts
1123
+ exports.RequestContextMiddleware = class RequestContextMiddleware {
1124
+ use(req, _res, next) {
1125
+ var _req_user;
1126
+ const reqId = req.headers['x-request-id'] || node_crypto.randomUUID();
1127
+ // The userId can be placed in the authentication result here.
1128
+ const userId = (_req_user = req['user']) == null ? void 0 : _req_user['id'];
1129
+ const ctx = new RequestContext(req, _res, reqId, userId);
1130
+ als.run(ctx, next);
1131
+ }
1132
+ };
1133
+ exports.RequestContextMiddleware = __decorate([
1134
+ common.Injectable()
1135
+ ], exports.RequestContextMiddleware);
1136
+ function runWithRequestContext(req, res, next) {
1137
+ var _req_user;
1138
+ const reqId = req.headers['x-request-id'] || node_crypto.randomUUID();
1139
+ const userId = (_req_user = req['user']) == null ? void 0 : _req_user['id'];
1140
+ const ctx = new RequestContext(req, res, reqId, userId);
1141
+ // Enable ALS scope
1142
+ als.run(ctx, next);
1143
+ }
1144
+
1145
+ exports.StrategyBus = class StrategyBus {
1146
+ upsert(strategyType, entry) {
1147
+ this.subject.next({
1148
+ type: 'UPSERT',
1149
+ strategyType,
1150
+ entry
1151
+ });
1152
+ }
1153
+ remove(orgId, pluginName) {
1154
+ this.subject.next({
1155
+ type: 'REMOVE',
1156
+ orgId,
1157
+ pluginName
1158
+ });
1159
+ }
1160
+ constructor(){
1161
+ this.subject = new Subject();
1162
+ this.events$ = this.subject.asObservable();
1163
+ }
1164
+ };
1165
+ exports.StrategyBus = __decorate([
1166
+ common.Injectable()
1167
+ ], exports.StrategyBus);
1168
+
133
1169
  class BaseStrategyRegistry {
134
1170
  onModuleInit() {
1171
+ this.bus.events$.pipe(filter((event)=>!event.strategyType || event.strategyType === this.strategyKey)).subscribe((evt)=>{
1172
+ this.logger.debug(`Received strategy bus event: ${JSON.stringify(evt)}`);
1173
+ if (evt.type === 'UPSERT') {
1174
+ this.upsert(evt.entry.instance);
1175
+ } else if (evt.type === 'REMOVE') {
1176
+ this.remove(evt.orgId, evt.pluginName);
1177
+ }
1178
+ });
135
1179
  const providers = this.discoveryService.getProviders();
136
1180
  for (const wrapper of providers){
137
1181
  const { instance } = wrapper;
138
1182
  if (!instance) continue;
139
- const type = this.reflector.get(this.strategyKey, instance.constructor);
140
- if (type) {
141
- this.strategies.set(type, instance);
1183
+ this.upsert(instance);
1184
+ }
1185
+ }
1186
+ upsert(instance) {
1187
+ const type = this.reflector.get(this.strategyKey, instance.constructor);
1188
+ if (type) {
1189
+ var _instance_metatype;
1190
+ const target = (_instance_metatype = instance.metatype) != null ? _instance_metatype : instance.constructor;
1191
+ var _this_reflector_get;
1192
+ const organizationId = (_this_reflector_get = this.reflector.get(ORGANIZATION_METADATA_KEY, target)) != null ? _this_reflector_get : GLOBAL_ORGANIZATION_SCOPE;
1193
+ var _this_strategies_get;
1194
+ const orgMap = (_this_strategies_get = this.strategies.get(organizationId)) != null ? _this_strategies_get : new Map();
1195
+ orgMap.set(type, instance);
1196
+ this.strategies.set(organizationId, orgMap);
1197
+ const pluginName = this.reflector.get(PLUGIN_METADATA_KEY, target);
1198
+ this.logger.debug(`Registered strategy of type ${type} for organization ${organizationId} from plugin ${pluginName}`);
1199
+ if (pluginName) {
1200
+ var _this_pluginStrategies_get;
1201
+ const pluginStrategies = (_this_pluginStrategies_get = this.pluginStrategies.get(pluginName)) != null ? _this_pluginStrategies_get : new Set();
1202
+ pluginStrategies.add(type);
1203
+ this.pluginStrategies.set(pluginName, pluginStrategies);
142
1204
  }
143
1205
  }
144
1206
  }
145
- get(type) {
146
- const strategy = this.strategies.get(type);
1207
+ /**
1208
+ * Remove all strategies registered by the given plugin for the given organization.
1209
+ */ remove(organizationId, pluginName) {
1210
+ const strategies = this.pluginStrategies.get(pluginName);
1211
+ const orgMap = this.strategies.get(organizationId);
1212
+ for (const type of strategies != null ? strategies : []){
1213
+ orgMap == null ? void 0 : orgMap.delete(type);
1214
+ }
1215
+ }
1216
+ /**
1217
+ * Resolve organization id, falling back to request context org or global scope.
1218
+ */ resolveOrganization(organizationId) {
1219
+ var _ref;
1220
+ return (_ref = organizationId != null ? organizationId : RequestContext.getOrganizationId()) != null ? _ref : GLOBAL_ORGANIZATION_SCOPE;
1221
+ }
1222
+ /**
1223
+ * Get strategy by type from the given organization including global strategies as fallback.
1224
+ *
1225
+ * @param type
1226
+ * @param organizationId
1227
+ * @returns
1228
+ */ get(type, organizationId) {
1229
+ var _this_strategies_get, _this_strategies_get1;
1230
+ organizationId != null ? organizationId : organizationId = RequestContext.getOrganizationId();
1231
+ const orgKey = this.resolveOrganization(organizationId);
1232
+ var _this_strategies_get_get;
1233
+ const strategy = (_this_strategies_get_get = (_this_strategies_get = this.strategies.get(orgKey)) == null ? void 0 : _this_strategies_get.get(type)) != null ? _this_strategies_get_get : orgKey === GLOBAL_ORGANIZATION_SCOPE ? undefined : (_this_strategies_get1 = this.strategies.get(GLOBAL_ORGANIZATION_SCOPE)) == null ? void 0 : _this_strategies_get1.get(type);
147
1234
  if (!strategy) {
148
1235
  throw new Error(`No strategy found for type ${type}`);
149
1236
  }
150
1237
  return strategy;
151
1238
  }
152
- list() {
153
- return Array.from(this.strategies.values());
1239
+ /**
1240
+ * List all strategies for the given organization including global strategies, or only global strategies if global org is specified.
1241
+ *
1242
+ * @param organizationId
1243
+ * @returns
1244
+ */ list(organizationId) {
1245
+ var _this_strategies_get, _this_strategies_get1;
1246
+ organizationId != null ? organizationId : organizationId = RequestContext.getOrganizationId();
1247
+ const orgKey = this.resolveOrganization(organizationId);
1248
+ var _this_strategies_get_values;
1249
+ const scoped = (_this_strategies_get_values = (_this_strategies_get = this.strategies.get(orgKey)) == null ? void 0 : _this_strategies_get.values()) != null ? _this_strategies_get_values : [];
1250
+ var _this_strategies_get_values1;
1251
+ const global = orgKey === GLOBAL_ORGANIZATION_SCOPE ? [] : (_this_strategies_get_values1 = (_this_strategies_get1 = this.strategies.get(GLOBAL_ORGANIZATION_SCOPE)) == null ? void 0 : _this_strategies_get1.values()) != null ? _this_strategies_get_values1 : [];
1252
+ return Array.from(new Set([
1253
+ ...scoped,
1254
+ ...global
1255
+ ]));
154
1256
  }
155
1257
  constructor(strategyKey, discoveryService, reflector){
156
1258
  this.strategyKey = strategyKey;
157
1259
  this.discoveryService = discoveryService;
158
1260
  this.reflector = reflector;
1261
+ this.logger = new common.Logger(BaseStrategyRegistry.name);
159
1262
  this.strategies = new Map();
1263
+ this.pluginStrategies = new Map();
160
1264
  }
161
1265
  }
1266
+ __decorate([
1267
+ common.Inject(exports.StrategyBus),
1268
+ __metadata("design:type", typeof exports.StrategyBus === "undefined" ? Object : exports.StrategyBus)
1269
+ ], BaseStrategyRegistry.prototype, "bus", void 0);
162
1270
 
163
1271
  exports.IntegrationStrategyRegistry = class IntegrationStrategyRegistry extends BaseStrategyRegistry {
164
1272
  constructor(discoveryService, reflector){
@@ -175,7 +1283,7 @@ exports.IntegrationStrategyRegistry = __decorate([
175
1283
  ], exports.IntegrationStrategyRegistry);
176
1284
 
177
1285
  const WORKFLOW_TRIGGER_STRATEGY = 'WORKFLOW_TRIGGER_STRATEGY';
178
- const WorkflowTriggerStrategy = (provider)=>common.SetMetadata(WORKFLOW_TRIGGER_STRATEGY, provider);
1286
+ const WorkflowTriggerStrategy = (provider)=>common.applyDecorators(common.SetMetadata(WORKFLOW_TRIGGER_STRATEGY, provider), common.SetMetadata(STRATEGY_META_KEY, WORKFLOW_TRIGGER_STRATEGY));
179
1287
 
180
1288
  exports.WorkflowTriggerRegistry = class WorkflowTriggerRegistry extends BaseStrategyRegistry {
181
1289
  constructor(discoveryService, reflector){
@@ -194,7 +1302,7 @@ exports.WorkflowTriggerRegistry = __decorate([
194
1302
  const WORKFLOW_NODE_STRATEGY = 'WORKFLOW_NODE_STRATEGY';
195
1303
  /**
196
1304
  * Decorator to mark a provider as a Workflow Node Strategy
197
- */ const WorkflowNodeStrategy = (provider)=>common.SetMetadata(WORKFLOW_NODE_STRATEGY, provider);
1305
+ */ const WorkflowNodeStrategy = (provider)=>common.applyDecorators(common.SetMetadata(WORKFLOW_NODE_STRATEGY, provider), common.SetMetadata(STRATEGY_META_KEY, WORKFLOW_NODE_STRATEGY));
198
1306
 
199
1307
  exports.WorkflowNodeRegistry = class WorkflowNodeRegistry extends BaseStrategyRegistry {
200
1308
  constructor(discoveryService, reflector){
@@ -210,8 +1318,19 @@ exports.WorkflowNodeRegistry = __decorate([
210
1318
  ])
211
1319
  ], exports.WorkflowNodeRegistry);
212
1320
 
1321
+ /**
1322
+ * Wrap Workflow Node Execution Command
1323
+ */ class WrapWorkflowNodeExecutionCommand extends cqrs.Command {
1324
+ constructor(fuc, params){
1325
+ super();
1326
+ this.fuc = fuc;
1327
+ this.params = params;
1328
+ }
1329
+ }
1330
+ WrapWorkflowNodeExecutionCommand.type = '[Workflow] Wrap Workflow Node Execution';
1331
+
213
1332
  const VECTOR_STORE_STRATEGY = 'VECTOR_STORE_STRATEGY';
214
- const VectorStoreStrategy = (provider)=>common.SetMetadata(VECTOR_STORE_STRATEGY, provider);
1333
+ const VectorStoreStrategy = (provider)=>common.applyDecorators(common.SetMetadata(VECTOR_STORE_STRATEGY, provider), common.SetMetadata(STRATEGY_META_KEY, VECTOR_STORE_STRATEGY));
215
1334
 
216
1335
  exports.VectorStoreRegistry = class VectorStoreRegistry extends BaseStrategyRegistry {
217
1336
  constructor(discoveryService, reflector){
@@ -228,7 +1347,7 @@ exports.VectorStoreRegistry = __decorate([
228
1347
  ], exports.VectorStoreRegistry);
229
1348
 
230
1349
  const TEXT_SPLITTER_STRATEGY = 'TEXT_SPLITTER_STRATEGY';
231
- const TextSplitterStrategy = (provider)=>common.SetMetadata(TEXT_SPLITTER_STRATEGY, provider);
1350
+ const TextSplitterStrategy = (provider)=>common.applyDecorators(common.SetMetadata(TEXT_SPLITTER_STRATEGY, provider), common.SetMetadata(STRATEGY_META_KEY, TEXT_SPLITTER_STRATEGY));
232
1351
 
233
1352
  exports.TextSplitterRegistry = class TextSplitterRegistry extends BaseStrategyRegistry {
234
1353
  constructor(discoveryService, reflector){
@@ -247,7 +1366,7 @@ exports.TextSplitterRegistry = __decorate([
247
1366
  const DOCUMENT_SOURCE_STRATEGY = 'DOCUMENT_SOURCE_STRATEGY';
248
1367
  /**
249
1368
  * Decorator to mark a provider as a Document Source Strategy
250
- */ const DocumentSourceStrategy = (provider)=>common.SetMetadata(DOCUMENT_SOURCE_STRATEGY, provider);
1369
+ */ const DocumentSourceStrategy = (provider)=>common.applyDecorators(common.SetMetadata(DOCUMENT_SOURCE_STRATEGY, provider), common.SetMetadata(STRATEGY_META_KEY, DOCUMENT_SOURCE_STRATEGY));
251
1370
 
252
1371
  exports.DocumentSourceRegistry = class DocumentSourceRegistry extends BaseStrategyRegistry {
253
1372
  constructor(discoveryService, reflector){
@@ -266,7 +1385,7 @@ exports.DocumentSourceRegistry = __decorate([
266
1385
  const DOCUMENT_TRANSFORMER_STRATEGY = 'DOCUMENT_TRANSFORMER_STRATEGY';
267
1386
  /**
268
1387
  * Decorator to mark a provider as a Document Transformer Strategy
269
- */ const DocumentTransformerStrategy = (provider)=>common.SetMetadata(DOCUMENT_TRANSFORMER_STRATEGY, provider);
1388
+ */ const DocumentTransformerStrategy = (provider)=>common.applyDecorators(common.SetMetadata(DOCUMENT_TRANSFORMER_STRATEGY, provider), common.SetMetadata(STRATEGY_META_KEY, DOCUMENT_TRANSFORMER_STRATEGY));
270
1389
 
271
1390
  exports.DocumentTransformerRegistry = class DocumentTransformerRegistry extends BaseStrategyRegistry {
272
1391
  constructor(discoveryService, reflector){
@@ -285,7 +1404,7 @@ exports.DocumentTransformerRegistry = __decorate([
285
1404
  const RETRIEVER_STRATEGY = 'RETRIEVER_STRATEGY';
286
1405
  /**
287
1406
  * Decorator to mark a provider as a Retriever Strategy
288
- */ const RetrieverStrategy = (provider)=>common.SetMetadata(RETRIEVER_STRATEGY, provider);
1407
+ */ const RetrieverStrategy = (provider)=>common.applyDecorators(common.SetMetadata(RETRIEVER_STRATEGY, provider), common.SetMetadata(STRATEGY_META_KEY, RETRIEVER_STRATEGY));
289
1408
 
290
1409
  exports.RetrieverRegistry = class RetrieverRegistry extends BaseStrategyRegistry {
291
1410
  constructor(discoveryService, reflector){
@@ -360,7 +1479,7 @@ async function downloadRemoteFile(url, dest) {
360
1479
  const IMAGE_UNDERSTANDING_STRATEGY = 'IMAGE_UNDERSTANDING_STRATEGY';
361
1480
  /**
362
1481
  * Decorator to mark a provider as an Image Understanding Strategy
363
- */ const ImageUnderstandingStrategy = (provider)=>common.SetMetadata(IMAGE_UNDERSTANDING_STRATEGY, provider);
1482
+ */ const ImageUnderstandingStrategy = (provider)=>common.applyDecorators(common.SetMetadata(IMAGE_UNDERSTANDING_STRATEGY, provider), common.SetMetadata(STRATEGY_META_KEY, IMAGE_UNDERSTANDING_STRATEGY));
364
1483
 
365
1484
  exports.ImageUnderstandingRegistry = class ImageUnderstandingRegistry extends BaseStrategyRegistry {
366
1485
  constructor(discoveryService, reflector){
@@ -377,7 +1496,7 @@ exports.ImageUnderstandingRegistry = __decorate([
377
1496
  ], exports.ImageUnderstandingRegistry);
378
1497
 
379
1498
  const KNOWLEDGE_STRATEGY = 'KNOWLEDGE_STRATEGY';
380
- const KnowledgeStrategyKey = (provider)=>common.SetMetadata(KNOWLEDGE_STRATEGY, provider);
1499
+ const KnowledgeStrategyKey = (provider)=>common.applyDecorators(common.SetMetadata(KNOWLEDGE_STRATEGY, provider), common.SetMetadata(STRATEGY_META_KEY, KNOWLEDGE_STRATEGY));
381
1500
 
382
1501
  exports.KnowledgeStrategyRegistry = class KnowledgeStrategyRegistry extends BaseStrategyRegistry {
383
1502
  constructor(discoveryService, reflector){
@@ -396,7 +1515,7 @@ exports.KnowledgeStrategyRegistry = __decorate([
396
1515
  const TOOLSET_STRATEGY = 'TOOLSET_STRATEGY';
397
1516
  /**
398
1517
  * Decorator to mark a provider as a Toolset Strategy
399
- */ const ToolsetStrategy = (provider)=>common.SetMetadata(TOOLSET_STRATEGY, provider);
1518
+ */ const ToolsetStrategy = (provider)=>common.applyDecorators(common.SetMetadata(TOOLSET_STRATEGY, provider), common.SetMetadata(STRATEGY_META_KEY, TOOLSET_STRATEGY));
400
1519
 
401
1520
  exports.ToolsetRegistry = class ToolsetRegistry extends BaseStrategyRegistry {
402
1521
  constructor(discoveryService, reflector){
@@ -700,224 +1819,8 @@ function getErrorMessage(err) {
700
1819
  return error;
701
1820
  }
702
1821
 
703
- // request-context.ts
704
- class RequestContext {
705
- static currentRequestContext() {
706
- const session = getRequestContext();
707
- return session;
708
- }
709
- static currentRequest() {
710
- const requestContext = RequestContext.currentRequestContext();
711
- if (requestContext) {
712
- return requestContext.request;
713
- }
714
- return null;
715
- }
716
- static currentTenantId() {
717
- const user = RequestContext.currentUser();
718
- if (user) {
719
- return user.tenantId;
720
- }
721
- return null;
722
- }
723
- static currentUserId() {
724
- const user = RequestContext.currentUser();
725
- if (user) {
726
- return user.id;
727
- }
728
- return null;
729
- }
730
- static currentRoleId() {
731
- const user = RequestContext.currentUser();
732
- if (user) {
733
- return user.roleId;
734
- }
735
- return null;
736
- }
737
- static currentUser(throwError) {
738
- const requestContext = RequestContext.currentRequestContext();
739
- if (requestContext) {
740
- // tslint:disable-next-line
741
- const user = requestContext.request['user'];
742
- if (user) {
743
- return user;
744
- }
745
- }
746
- if (throwError) {
747
- throw new common.HttpException('Unauthorized', common.HttpStatus.UNAUTHORIZED);
748
- }
749
- return null;
750
- }
751
- static hasPermission(permission, throwError) {
752
- return this.hasPermissions([
753
- permission
754
- ], throwError);
755
- }
756
- /**
757
- * Retrieves the language code from the headers of the current request.
758
- * @returns The language code (LanguagesEnum) extracted from the headers, or the default language (ENGLISH) if not found.
759
- */ static getLanguageCode() {
760
- // Retrieve the current request
761
- const req = RequestContext.currentRequest();
762
- // Variable to store the extracted language code
763
- let lang;
764
- // Check if a request exists
765
- if (req) {
766
- // Check if the 'language' header exists in the request
767
- if (req.headers && req.headers['language']) {
768
- // If found, set the lang variable
769
- lang = req.headers['language'];
770
- }
771
- }
772
- // Return the extracted language code or the default language (ENGLISH) if not found
773
- return lang || contracts.LanguagesEnum.English;
774
- }
775
- static getOrganizationId() {
776
- const req = this.currentRequest();
777
- let organizationId;
778
- const keys = [
779
- 'organization-id'
780
- ];
781
- if (req) {
782
- for (const key of keys){
783
- if (req.headers && req.headers[key]) {
784
- organizationId = req.headers[key];
785
- break;
786
- }
787
- }
788
- }
789
- return organizationId;
790
- }
791
- static hasPermissions(findPermissions, throwError) {
792
- const requestContext = RequestContext.currentRequestContext();
793
- if (requestContext) {
794
- // tslint:disable-next-line
795
- const token = passportJwt.ExtractJwt.fromAuthHeaderAsBearerToken()(requestContext.request);
796
- if (token) {
797
- const { permissions } = jsonwebtoken.verify(token, process.env['JWT_SECRET']);
798
- if (permissions) {
799
- const found = permissions.filter((value)=>findPermissions.indexOf(value) >= 0);
800
- if (found.length === findPermissions.length) {
801
- return true;
802
- }
803
- } else {
804
- return false;
805
- }
806
- }
807
- }
808
- if (throwError) {
809
- throw new common.HttpException('Unauthorized', common.HttpStatus.UNAUTHORIZED);
810
- }
811
- return false;
812
- }
813
- static hasAnyPermission(findPermissions, throwError) {
814
- const requestContext = RequestContext.currentRequestContext();
815
- if (requestContext) {
816
- // tslint:disable-next-line
817
- const token = passportJwt.ExtractJwt.fromAuthHeaderAsBearerToken()(requestContext.request);
818
- if (token) {
819
- const { permissions } = jsonwebtoken.verify(token, process.env['JWT_SECRET']);
820
- const found = permissions.filter((value)=>findPermissions.indexOf(value) >= 0);
821
- if (found.length > 0) {
822
- return true;
823
- }
824
- }
825
- }
826
- if (throwError) {
827
- throw new common.HttpException('Unauthorized', common.HttpStatus.UNAUTHORIZED);
828
- }
829
- return false;
830
- }
831
- static currentToken(throwError) {
832
- const requestContext = RequestContext.currentRequestContext();
833
- if (requestContext) {
834
- // tslint:disable-next-line
835
- return passportJwt.ExtractJwt.fromAuthHeaderAsBearerToken()(requestContext.request);
836
- }
837
- if (throwError) {
838
- throw new common.HttpException('Unauthorized', common.HttpStatus.UNAUTHORIZED);
839
- }
840
- return null;
841
- }
842
- /**
843
- * Checks if the current user has a specific role.
844
- * @param {RolesEnum} role - The role to check.
845
- * @param {boolean} throwError - Flag indicating whether to throw an error if the role is not granted.
846
- * @returns {boolean} - True if the user has the role, otherwise false.
847
- */ static hasRole(role, throwError) {
848
- return this.hasRoles([
849
- role
850
- ], throwError);
851
- }
852
- /**
853
- * Checks if the current request context has any of the specified roles.
854
- *
855
- * @param roles - An array of roles to check.
856
- * @param throwError - Whether to throw an error if no roles are found.
857
- * @returns True if any of the required roles are found, otherwise false.
858
- */ static hasRoles(roles, throwError) {
859
- const context = RequestContext.currentRequestContext();
860
- if (context) {
861
- try {
862
- // tslint:disable-next-line
863
- const token = this.currentToken();
864
- if (token) {
865
- const { role } = jsonwebtoken.verify(token, process.env['JWT_SECRET']);
866
- return roles.includes(role != null ? role : null);
867
- } else if (this.currentUser().role) {
868
- return roles.includes(this.currentUser().role.name);
869
- }
870
- } catch (error) {
871
- if (error instanceof jsonwebtoken.JsonWebTokenError) {
872
- return false;
873
- } else {
874
- throw error;
875
- }
876
- }
877
- }
878
- if (throwError) {
879
- throw new common.HttpException('Unauthorized', common.HttpStatus.UNAUTHORIZED);
880
- }
881
- return false;
882
- }
883
- constructor(request, response, reqId, userId, extras = {}){
884
- this.request = request;
885
- this.response = response;
886
- this.reqId = reqId;
887
- this.userId = userId;
888
- this.extras = extras;
889
- }
890
- }
891
- const als = new node_async_hooks.AsyncLocalStorage();
892
- function getRequestContext() {
893
- return als.getStore();
894
- }
895
-
896
- // request-context.middleware.ts
897
- exports.RequestContextMiddleware = class RequestContextMiddleware {
898
- use(req, _res, next) {
899
- var _req_user;
900
- const reqId = req.headers['x-request-id'] || node_crypto.randomUUID();
901
- // The userId can be placed in the authentication result here.
902
- const userId = (_req_user = req['user']) == null ? void 0 : _req_user['id'];
903
- const ctx = new RequestContext(req, _res, reqId, userId);
904
- als.run(ctx, next);
905
- }
906
- };
907
- exports.RequestContextMiddleware = __decorate([
908
- common.Injectable()
909
- ], exports.RequestContextMiddleware);
910
- function runWithRequestContext(req, res, next) {
911
- var _req_user;
912
- const reqId = req.headers['x-request-id'] || node_crypto.randomUUID();
913
- const userId = (_req_user = req['user']) == null ? void 0 : _req_user['id'];
914
- const ctx = new RequestContext(req, res, reqId, userId);
915
- // Enable ALS scope
916
- als.run(ctx, next);
917
- }
918
-
919
1822
  const DATASOURCE_STRATEGY = 'DATASOURCE_STRATEGY';
920
- const DataSourceStrategy = (provider)=>common.SetMetadata(DATASOURCE_STRATEGY, provider);
1823
+ const DataSourceStrategy = (provider)=>common.applyDecorators(common.SetMetadata(DATASOURCE_STRATEGY, provider), common.SetMetadata(STRATEGY_META_KEY, DATASOURCE_STRATEGY));
921
1824
 
922
1825
  exports.DataSourceStrategyRegistry = class DataSourceStrategyRegistry extends BaseStrategyRegistry {
923
1826
  constructor(discoveryService, reflector){
@@ -1080,6 +1983,93 @@ class BaseSQLQueryRunner extends BaseQueryRunner {
1080
1983
  async ping() {
1081
1984
  await this.runQuery(`SELECT 1`);
1082
1985
  }
1986
+ /**
1987
+ * Default implementation for table operations
1988
+ */ async tableOp(action, params, options) {
1989
+ switch(action){
1990
+ case "createTable":
1991
+ {
1992
+ // Default implementation for creating table (generic SQL syntax)
1993
+ const { schema, table, columns, createMode = "error" } = params;
1994
+ const tableName = schema ? `${schema}.${table}` : table;
1995
+ // Check if table exists (try to query table info)
1996
+ let exists = false;
1997
+ try {
1998
+ const result = await this.runQuery(`SELECT * FROM ${tableName} WHERE 1=0`, options);
1999
+ exists = true;
2000
+ } catch (error) {
2001
+ // Table does not exist
2002
+ exists = false;
2003
+ }
2004
+ // --- MODE: ERROR → throw error if table exists ---
2005
+ if (exists && createMode === "error") {
2006
+ throw new Error(`Table "${tableName}" already exists`);
2007
+ }
2008
+ // --- MODE: IGNORE → do nothing if exists ---
2009
+ if (exists && createMode === "ignore") {
2010
+ return;
2011
+ }
2012
+ // --- MODE: UPGRADE → auto upgrade (simple implementation: only add new columns) ---
2013
+ // Note: This default implementation does not support modifying column types,
2014
+ // recommend each database to implement its own version
2015
+ if (exists && createMode === "upgrade") {
2016
+ console.warn(`[BaseSQLQueryRunner] UPGRADE mode uses basic implementation. Consider implementing tableOp for better support.`);
2017
+ // Try to add new columns (will fail if column already exists, but doesn't affect)
2018
+ for (const col of columns){
2019
+ try {
2020
+ const colType = this.mapColumnType(col.type, col.isKey, col.length);
2021
+ await this.runQuery(`ALTER TABLE ${tableName} ADD COLUMN ${col.fieldName} ${colType}`, options);
2022
+ } catch (error) {
2023
+ // Field might already exist, ignore error
2024
+ console.debug(`Failed to add column ${col.fieldName}:`, error instanceof Error ? error.message : String(error));
2025
+ }
2026
+ }
2027
+ return;
2028
+ }
2029
+ // --- MODE: CREATE NEW TABLE ---
2030
+ const columnsDDL = columns.map((col)=>{
2031
+ const colType = this.mapColumnType(col.type, col.isKey, col.length);
2032
+ const pk = col.isKey ? ' PRIMARY KEY' : '';
2033
+ const notNull = col.required ? ' NOT NULL' : '';
2034
+ return `${col.fieldName} ${colType}${pk}${notNull}`;
2035
+ }).join(', ');
2036
+ const createTableStatement = `CREATE TABLE ${tableName} (${columnsDDL})`;
2037
+ await this.runQuery(createTableStatement, options);
2038
+ return;
2039
+ }
2040
+ case "dropTable":
2041
+ {
2042
+ // Default implementation for dropping table
2043
+ const { schema, table } = params;
2044
+ const tableName = schema ? `${schema}.${table}` : table;
2045
+ await this.runQuery(`DROP TABLE IF EXISTS ${tableName}`, options);
2046
+ return;
2047
+ }
2048
+ default:
2049
+ // Throw error for other unimplemented operations
2050
+ throw new Error(`Unsupported table action: ${action}`);
2051
+ }
2052
+ }
2053
+ /**
2054
+ * Generic type mapping (subclasses can override)
2055
+ */ mapColumnType(type, isKey, length) {
2056
+ switch(type == null ? void 0 : type.toLowerCase()){
2057
+ case 'string':
2058
+ return length ? `VARCHAR(${length})` : isKey ? 'VARCHAR(255)' : 'VARCHAR(1000)';
2059
+ case 'number':
2060
+ return 'INT';
2061
+ case 'boolean':
2062
+ return 'BOOLEAN';
2063
+ case 'date':
2064
+ return 'DATE';
2065
+ case 'datetime':
2066
+ return 'TIMESTAMP';
2067
+ case 'object':
2068
+ return 'TEXT';
2069
+ default:
2070
+ return 'VARCHAR(1000)';
2071
+ }
2072
+ }
1083
2073
  constructor(...args){
1084
2074
  super(...args);
1085
2075
  this.syntax = "sql";
@@ -1143,6 +2133,7 @@ function AIModelProviderStrategy(provider) {
1143
2133
  }
1144
2134
  const dir = file ? path.dirname(file) : process.cwd();
1145
2135
  return function(target) {
2136
+ common.SetMetadata(STRATEGY_META_KEY, AI_MODEL_PROVIDER)(target);
1146
2137
  // Ensure NestJS is discoverable
1147
2138
  common.SetMetadata(AI_MODEL_PROVIDER, provider)(target);
1148
2139
  // Write custom path (does not affect Discovery)
@@ -2049,6 +3040,42 @@ class Speech2TextChatModel extends chat_models.BaseChatModel {
2049
3040
  return 0;
2050
3041
  }
2051
3042
 
3043
+ /**
3044
+ * Get a Chat Model of copilot model and check it's token limitation, record the token usage
3045
+ */ class CreateModelClientCommand extends cqrs.Command {
3046
+ constructor(copilotModel, options){
3047
+ super();
3048
+ this.copilotModel = copilotModel;
3049
+ this.options = options;
3050
+ }
3051
+ }
3052
+ CreateModelClientCommand.type = '[AI Model] Create Model Client';
3053
+
3054
+ const AGENT_MIDDLEWARE_STRATEGY = 'AGENT_MIDDLEWARE_STRATEGY';
3055
+ const AgentMiddlewareStrategy = (provider)=>common.applyDecorators(common.SetMetadata(AGENT_MIDDLEWARE_STRATEGY, provider), common.SetMetadata(STRATEGY_META_KEY, AGENT_MIDDLEWARE_STRATEGY));
3056
+
3057
+ exports.AgentMiddlewareRegistry = class AgentMiddlewareRegistry extends BaseStrategyRegistry {
3058
+ constructor(discoveryService, reflector){
3059
+ super(AGENT_MIDDLEWARE_STRATEGY, discoveryService, reflector);
3060
+ }
3061
+ };
3062
+ exports.AgentMiddlewareRegistry = __decorate([
3063
+ common.Injectable(),
3064
+ __metadata("design:type", Function),
3065
+ __metadata("design:paramtypes", [
3066
+ typeof core.DiscoveryService === "undefined" ? Object : core.DiscoveryService,
3067
+ typeof core.Reflector === "undefined" ? Object : core.Reflector
3068
+ ])
3069
+ ], exports.AgentMiddlewareRegistry);
3070
+
3071
+ /**
3072
+ * jump targets (user facing)
3073
+ */ const JUMP_TO_TARGETS = [
3074
+ "model",
3075
+ "tools",
3076
+ "end"
3077
+ ];
3078
+
2052
3079
  Object.defineProperty(exports, "IColumnDef", {
2053
3080
  enumerable: true,
2054
3081
  get: function () { return contracts.IColumnDef; }
@@ -2065,19 +3092,23 @@ Object.defineProperty(exports, "TDocumentAsset", {
2065
3092
  enumerable: true,
2066
3093
  get: function () { return contracts.TDocumentAsset; }
2067
3094
  });
3095
+ exports.AGENT_MIDDLEWARE_STRATEGY = AGENT_MIDDLEWARE_STRATEGY;
2068
3096
  exports.AIModelProviderNotFoundException = AIModelProviderNotFoundException;
2069
3097
  exports.AIModelProviderStrategy = AIModelProviderStrategy;
2070
3098
  exports.AI_MODEL_PROVIDER = AI_MODEL_PROVIDER;
2071
3099
  exports.AdapterDataSourceStrategy = AdapterDataSourceStrategy;
3100
+ exports.AgentMiddlewareStrategy = AgentMiddlewareStrategy;
2072
3101
  exports.AiModelNotFoundException = AiModelNotFoundException;
2073
3102
  exports.BaseHTTPQueryRunner = BaseHTTPQueryRunner;
2074
3103
  exports.BaseQueryRunner = BaseQueryRunner;
2075
3104
  exports.BaseSQLQueryRunner = BaseSQLQueryRunner;
3105
+ exports.BaseStrategyRegistry = BaseStrategyRegistry;
2076
3106
  exports.BaseTool = BaseTool;
2077
3107
  exports.BaseToolset = BaseToolset;
2078
3108
  exports.BuiltinToolset = BuiltinToolset;
2079
3109
  exports.ChatOAICompatReasoningModel = ChatOAICompatReasoningModel;
2080
3110
  exports.CommonParameterRules = CommonParameterRules;
3111
+ exports.CreateModelClientCommand = CreateModelClientCommand;
2081
3112
  exports.CredentialsValidateFailedError = CredentialsValidateFailedError;
2082
3113
  exports.DATASOURCE_STRATEGY = DATASOURCE_STRATEGY;
2083
3114
  exports.DOCUMENT_SOURCE_STRATEGY = DOCUMENT_SOURCE_STRATEGY;
@@ -2085,16 +3116,20 @@ exports.DOCUMENT_TRANSFORMER_STRATEGY = DOCUMENT_TRANSFORMER_STRATEGY;
2085
3116
  exports.DataSourceStrategy = DataSourceStrategy;
2086
3117
  exports.DocumentSourceStrategy = DocumentSourceStrategy;
2087
3118
  exports.DocumentTransformerStrategy = DocumentTransformerStrategy;
3119
+ exports.GLOBAL_ORGANIZATION_SCOPE = GLOBAL_ORGANIZATION_SCOPE;
2088
3120
  exports.IMAGE_UNDERSTANDING_STRATEGY = IMAGE_UNDERSTANDING_STRATEGY;
2089
3121
  exports.INTEGRATION_STRATEGY = INTEGRATION_STRATEGY;
2090
3122
  exports.ImageUnderstandingStrategy = ImageUnderstandingStrategy;
2091
3123
  exports.IntegrationStrategyKey = IntegrationStrategyKey;
3124
+ exports.JUMP_TO_TARGETS = JUMP_TO_TARGETS;
2092
3125
  exports.KNOWLEDGE_STRATEGY = KNOWLEDGE_STRATEGY;
2093
3126
  exports.KnowledgeStrategyKey = KnowledgeStrategyKey;
2094
3127
  exports.LLMUsage = LLMUsage;
2095
3128
  exports.LargeLanguageModel = LargeLanguageModel;
3129
+ exports.ORGANIZATION_METADATA_KEY = ORGANIZATION_METADATA_KEY;
2096
3130
  exports.OpenAICompatibleReranker = OpenAICompatibleReranker;
2097
3131
  exports.PLUGIN_METADATA = PLUGIN_METADATA;
3132
+ exports.PLUGIN_METADATA_KEY = PLUGIN_METADATA_KEY;
2098
3133
  exports.PROVIDE_AI_MODEL_LLM = PROVIDE_AI_MODEL_LLM;
2099
3134
  exports.PROVIDE_AI_MODEL_MODERATION = PROVIDE_AI_MODEL_MODERATION;
2100
3135
  exports.PROVIDE_AI_MODEL_RERANK = PROVIDE_AI_MODEL_RERANK;
@@ -2105,6 +3140,7 @@ exports.RETRIEVER_STRATEGY = RETRIEVER_STRATEGY;
2105
3140
  exports.RequestContext = RequestContext;
2106
3141
  exports.RerankModel = RerankModel;
2107
3142
  exports.RetrieverStrategy = RetrieverStrategy;
3143
+ exports.STRATEGY_META_KEY = STRATEGY_META_KEY;
2108
3144
  exports.Speech2TextChatModel = Speech2TextChatModel;
2109
3145
  exports.SpeechToTextModel = SpeechToTextModel;
2110
3146
  exports.TEXT_SPLITTER_STRATEGY = TEXT_SPLITTER_STRATEGY;
@@ -2119,6 +3155,7 @@ exports.WORKFLOW_NODE_STRATEGY = WORKFLOW_NODE_STRATEGY;
2119
3155
  exports.WORKFLOW_TRIGGER_STRATEGY = WORKFLOW_TRIGGER_STRATEGY;
2120
3156
  exports.WorkflowNodeStrategy = WorkflowNodeStrategy;
2121
3157
  exports.WorkflowTriggerStrategy = WorkflowTriggerStrategy;
3158
+ exports.WrapWorkflowNodeExecutionCommand = WrapWorkflowNodeExecutionCommand;
2122
3159
  exports.XpFileSystem = XpFileSystem;
2123
3160
  exports.XpertServerPlugin = XpertServerPlugin;
2124
3161
  exports.als = als;