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