@xpert-ai/plugin-sdk 3.18.1 → 3.18.2

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.
package/index.esm.js CHANGED
@@ -4,7 +4,7 @@ import { pick } from 'lodash-es';
4
4
  import { _ as _extends } from './_extends.esm.js';
5
5
  import { DiscoveryService, Reflector } from '@nestjs/core';
6
6
  import { Subject, filter } from 'rxjs';
7
- import { LanguagesEnum, ParameterType, AiModelTypeEnum, PriceType, FetchFrom, ModelFeature, ModelPropertyKey } from '@xpert-ai/contracts';
7
+ import { LanguagesEnum, ParameterType, AiModelTypeEnum, PriceType, FetchFrom, ModelFeature, ModelPropertyKey, MCP_TOOL_RISKS, MCP_TOOL_SIDE_EFFECTS, MCP_TOOL_IDEMPOTENCY, MCP_REQUIRED_CONTEXTS, MCP_CAPABILITY_VISIBILITIES } from '@xpert-ai/contracts';
8
8
  export { ASSISTANT_CHAT_SEND_MESSAGE_COMMAND, ASSISTANT_CONTEXT_SET_COMMAND } from '@xpert-ai/contracts';
9
9
  import { AsyncLocalStorage } from 'node:async_hooks';
10
10
  import { ExtractJwt } from 'passport-jwt';
@@ -15,8 +15,8 @@ import * as fs from 'fs';
15
15
  import fs__default from 'fs';
16
16
  import http from 'http';
17
17
  import https from 'https';
18
- import { c as createRuntimeCapability } from './model-provider.esm.js';
19
- export { A as ActorTokenRuntimeCapability, a as ArtifactsRuntimeCapability, B as BaseTool, b as BaseToolset, d as BuiltinToolset, D as DefaultAgentMiddlewareRuntimeCapabilityRegistry, D as DefaultRuntimeCapabilityRegistry, K as KnowledgeDocumentVisualAssetsRuntimeCapability, e as KnowledgebaseDocumentsRuntimeCapability, f as KnowledgebaseProvisioningRuntimeCapability, g as KnowledgebaseRuntimeCapability, M as ModelProviderBuiltinToolset, P as ProjectProvisioningRuntimeCapability, S as SANDBOX_JOB_ERROR_CODES, h as SANDBOX_JOB_PROGRESS_PREFIX, i as SandboxJobRuntimeError, j as SandboxJobsRuntimeCapability, W as WORKSPACE_FILES_SOURCE, k as WorkspaceFilesRuntimeCapability, X as XPERT_RUNTIME_CAPABILITIES_TOKEN, l as isSandboxJobRuntimeError } from './model-provider.esm.js';
18
+ import { c as createRuntimeCapability, B as BuiltinToolset } from './model-provider.esm.js';
19
+ export { A as ActorTokenRuntimeCapability, a as ArtifactsRuntimeCapability, b as BaseTool, d as BaseToolset, D as DefaultAgentMiddlewareRuntimeCapabilityRegistry, D as DefaultRuntimeCapabilityRegistry, K as KnowledgeDocumentVisualAssetsRuntimeCapability, e as KnowledgebaseDocumentsRuntimeCapability, f as KnowledgebaseProvisioningRuntimeCapability, g as KnowledgebaseRuntimeCapability, M as ModelProviderBuiltinToolset, P as ProjectProvisioningRuntimeCapability, S as SANDBOX_JOB_ERROR_CODES, h as SANDBOX_JOB_PROGRESS_PREFIX, i as SandboxJobRuntimeError, j as SandboxJobsRuntimeCapability, W as WORKSPACE_FILES_SOURCE, k as WorkspaceFilesRuntimeCapability, X as XPERT_RUNTIME_CAPABILITIES_TOKEN, l as isSandboxJobRuntimeError } from './model-provider.esm.js';
20
20
  import fsPromises from 'fs/promises';
21
21
  import * as path from 'path';
22
22
  import path__default, { join } from 'path';
@@ -40,7 +40,7 @@ import { getModelContextSize as getModelContextSize$1 } from '@langchain/core/la
40
40
  import { assertConnectorDefinition } from './connector.esm.js';
41
41
  export { CONNECTOR_AUTHORIZATION_MODES, CONNECTOR_SCOPE_TYPES, getConnectorAuthMethods, getConnectorAuthorizationModes } from './connector.esm.js';
42
42
  export { base64ToBytes, bytesToBase64, createCollaborationClient, createCollaborationPresenceStore, createSocketIoTransportAdapter, createYjsDocumentAdapter } from './collaboration-client.esm.js';
43
- import '@langchain/core/tools';
43
+ import { tool } from '@langchain/core/tools';
44
44
  import 'zod/v3';
45
45
 
46
46
  /**
@@ -503,12 +503,14 @@ let StrategyBus = class StrategyBus {
503
503
  entry
504
504
  });
505
505
  }
506
- remove(orgId, pluginName) {
507
- this.subject.next({
506
+ remove(orgId, pluginName, cause) {
507
+ this.subject.next(_extends({
508
508
  type: 'REMOVE',
509
509
  orgId,
510
510
  pluginName
511
- });
511
+ }, cause ? {
512
+ cause
513
+ } : {}));
512
514
  }
513
515
  constructor(){
514
516
  this.subject = new Subject();
@@ -543,22 +545,39 @@ class BaseStrategyRegistry {
543
545
  const type = this.reflector.get(this.strategyKey, target);
544
546
  if (type) {
545
547
  const source = this.getSource(instance);
546
- const pluginName = source.kind === 'plugin' ? source.pluginName : undefined;
547
- const organizationId = source.scopeKey;
548
- var _this_strategies_get;
549
- const orgMap = (_this_strategies_get = this.strategies.get(organizationId)) != null ? _this_strategies_get : new Map();
550
- orgMap.set(type, instance);
551
- this.strategies.set(organizationId, orgMap);
552
- this.logger.debug(`Registered strategy of type ${type} for scope ${organizationId} from plugin ${pluginName}`);
553
- if (pluginName) {
554
- var _this_pluginStrategies_get;
555
- const pluginStrategies = (_this_pluginStrategies_get = this.pluginStrategies.get(pluginName)) != null ? _this_pluginStrategies_get : new Set();
556
- pluginStrategies.add(type);
557
- this.pluginStrategies.set(pluginName, pluginStrategies);
558
- }
548
+ this.store(type, instance, source, false);
559
549
  }
560
550
  }
551
+ /** Registers a host-generated adapter without mutating shared class metadata. */ register(type, instance, source) {
552
+ if ((typeof instance !== 'object' || instance === null) && typeof instance !== 'function') {
553
+ throw new Error(`Cannot register non-object strategy '${type}'.`);
554
+ }
555
+ this.assertCanRegister(type, instance, source);
556
+ this.explicitSources.set(instance, source);
557
+ return this.store(type, instance, source, false);
558
+ }
559
+ /** Preflights adapter batches so a provider is expanded atomically across registries. */ assertCanRegister(type, instance, source) {
560
+ var _this_strategies_get;
561
+ const existing = (_this_strategies_get = this.strategies.get(source.scopeKey)) == null ? void 0 : _this_strategies_get.get(type);
562
+ if (!existing || existing === instance) return;
563
+ const existingSource = this.getSource(existing);
564
+ const samePlugin = existingSource.kind === 'plugin' && source.kind === 'plugin' && existingSource.pluginName === source.pluginName;
565
+ if (!samePlugin) {
566
+ throw new Error(`Strategy '${type}' is already registered for scope '${source.scopeKey}'.`);
567
+ }
568
+ }
569
+ /** Removes one exact programmatic registration without affecting fallback scopes. */ unregister(type, source, expected) {
570
+ const orgMap = this.strategies.get(source.scopeKey);
571
+ const current = orgMap == null ? void 0 : orgMap.get(type);
572
+ if (expected !== undefined && current !== expected) return false;
573
+ var _orgMap_delete;
574
+ return (_orgMap_delete = orgMap == null ? void 0 : orgMap.delete(type)) != null ? _orgMap_delete : false;
575
+ }
561
576
  /** Returns the explicit registry provenance attached by the plugin loader. */ getSource(instance) {
577
+ if (typeof instance === 'object' && instance !== null || typeof instance === 'function') {
578
+ const explicit = this.explicitSources.get(instance);
579
+ if (explicit) return explicit;
580
+ }
562
581
  const target = resolveStrategyMetadataTarget(instance);
563
582
  if (!target) {
564
583
  return {
@@ -662,11 +681,68 @@ class BaseStrategyRegistry {
662
681
  }
663
682
  return Array.from(effective.values());
664
683
  }
684
+ listRegistrations(organizationId) {
685
+ organizationId != null ? organizationId : organizationId = RequestContext.getOrganizationId();
686
+ const effective = new Map();
687
+ for (const scopeKey of this.resolveStrategyScopeKeys(organizationId)){
688
+ var _this_strategies_get;
689
+ var _this_strategies_get_entries;
690
+ for (const [type, strategy] of (_this_strategies_get_entries = (_this_strategies_get = this.strategies.get(scopeKey)) == null ? void 0 : _this_strategies_get.entries()) != null ? _this_strategies_get_entries : []){
691
+ if (!effective.has(type)) effective.set(type, strategy);
692
+ }
693
+ }
694
+ return Array.from(effective, ([type, strategy])=>({
695
+ type,
696
+ strategy,
697
+ source: this.getSource(strategy)
698
+ }));
699
+ }
700
+ /** Returns every direct registration without applying request-scope fallback rules. */ listAllRegistrations() {
701
+ const registrations = [];
702
+ for (const [scopeKey, strategies] of this.strategies){
703
+ for (const [type, strategy] of strategies){
704
+ const source = this.getSource(strategy);
705
+ registrations.push({
706
+ type,
707
+ strategy,
708
+ source: source.scopeKey === scopeKey ? source : _extends({}, source, {
709
+ scopeKey
710
+ })
711
+ });
712
+ }
713
+ }
714
+ return registrations;
715
+ }
716
+ store(type, instance, source, rejectCrossPluginConflict) {
717
+ const pluginName = source.kind === 'plugin' ? source.pluginName : undefined;
718
+ const organizationId = source.scopeKey;
719
+ var _this_strategies_get;
720
+ const orgMap = (_this_strategies_get = this.strategies.get(organizationId)) != null ? _this_strategies_get : new Map();
721
+ const existing = orgMap.get(type);
722
+ if (rejectCrossPluginConflict && existing && existing !== instance) {
723
+ const existingSource = this.getSource(existing);
724
+ const samePlugin = existingSource.kind === 'plugin' && source.kind === 'plugin' && existingSource.pluginName === source.pluginName;
725
+ if (!samePlugin) {
726
+ throw new Error(`Strategy '${type}' is already registered for scope '${organizationId}'.`);
727
+ }
728
+ }
729
+ orgMap.set(type, instance);
730
+ this.strategies.set(organizationId, orgMap);
731
+ this.logger.debug(`Registered strategy of type ${type} for scope ${organizationId} from plugin ${pluginName}`);
732
+ if (pluginName) {
733
+ var _this_pluginStrategies_get;
734
+ const pluginStrategies = (_this_pluginStrategies_get = this.pluginStrategies.get(pluginName)) != null ? _this_pluginStrategies_get : new Set();
735
+ pluginStrategies.add(type);
736
+ this.pluginStrategies.set(pluginName, pluginStrategies);
737
+ }
738
+ return existing;
739
+ }
665
740
  constructor(strategyKey, discoveryService, reflector){
666
741
  this.logger = new Logger(BaseStrategyRegistry.name);
667
742
  // Map<scopeKey, Map<type, strategy>>
668
743
  this.strategies = new Map();
669
744
  this.pluginStrategies = new Map();
745
+ this.explicitSources = new WeakMap();
670
746
  this.strategyKey = strategyKey;
671
747
  this.discoveryService = discoveryService;
672
748
  this.reflector = reflector;
@@ -1682,13 +1758,13 @@ var DefaultParameterName;
1682
1758
  const PARAMETER_RULE_TEMPLATE = {
1683
1759
  [DefaultParameterName.TEMPERATURE]: {
1684
1760
  label: {
1685
- en_US: "Temperature",
1686
- zh_Hans: "温度"
1761
+ en_US: 'Temperature',
1762
+ zh_Hans: '温度'
1687
1763
  },
1688
1764
  type: ParameterType.FLOAT,
1689
1765
  help: {
1690
- en_US: "Controls randomness. Lower temperature results in less random completions." + " As the temperature approaches zero, the model will become deterministic and repetitive." + " Higher temperature results in more random completions.",
1691
- zh_Hans: "温度控制随机性。较低的温度会导致较少的随机完成。随着温度接近零,模型将变得确定性和重复性。" + "较高的温度会导致更多的随机完成。"
1766
+ en_US: 'Controls randomness. Lower temperature results in less random completions.' + ' As the temperature approaches zero, the model will become deterministic and repetitive.' + ' Higher temperature results in more random completions.',
1767
+ zh_Hans: '温度控制随机性。较低的温度会导致较少的随机完成。随着温度接近零,模型将变得确定性和重复性。' + '较高的温度会导致更多的随机完成。'
1692
1768
  },
1693
1769
  required: false,
1694
1770
  default: 0.0,
@@ -1698,13 +1774,13 @@ const PARAMETER_RULE_TEMPLATE = {
1698
1774
  },
1699
1775
  [DefaultParameterName.TOP_P]: {
1700
1776
  label: {
1701
- en_US: "Top P",
1702
- zh_Hans: "Top P"
1777
+ en_US: 'Top P',
1778
+ zh_Hans: 'Top P'
1703
1779
  },
1704
1780
  type: ParameterType.FLOAT,
1705
1781
  help: {
1706
- en_US: "Controls diversity via nucleus sampling: 0.5 means half of all likelihood-weighted options" + " are considered.",
1707
- zh_Hans: "通过核心采样控制多样性:0.5表示考虑了一半的所有可能性加权选项。"
1782
+ en_US: 'Controls diversity via nucleus sampling: 0.5 means half of all likelihood-weighted options' + ' are considered.',
1783
+ zh_Hans: '通过核心采样控制多样性:0.5表示考虑了一半的所有可能性加权选项。'
1708
1784
  },
1709
1785
  required: false,
1710
1786
  default: 1.0,
@@ -1714,13 +1790,13 @@ const PARAMETER_RULE_TEMPLATE = {
1714
1790
  },
1715
1791
  [DefaultParameterName.TOP_K]: {
1716
1792
  label: {
1717
- en_US: "Top K",
1718
- zh_Hans: "Top K"
1793
+ en_US: 'Top K',
1794
+ zh_Hans: 'Top K'
1719
1795
  },
1720
1796
  type: ParameterType.INT,
1721
1797
  help: {
1722
- en_US: "Limits the number of tokens to consider for each step by keeping only the k most likely tokens.",
1723
- zh_Hans: "通过只保留每一步中最可能的 k 个标记来限制要考虑的标记数量。"
1798
+ en_US: 'Limits the number of tokens to consider for each step by keeping only the k most likely tokens.',
1799
+ zh_Hans: '通过只保留每一步中最可能的 k 个标记来限制要考虑的标记数量。'
1724
1800
  },
1725
1801
  required: false,
1726
1802
  default: 50,
@@ -1730,13 +1806,13 @@ const PARAMETER_RULE_TEMPLATE = {
1730
1806
  },
1731
1807
  [DefaultParameterName.PRESENCE_PENALTY]: {
1732
1808
  label: {
1733
- en_US: "Presence Penalty",
1734
- zh_Hans: "存在惩罚"
1809
+ en_US: 'Presence Penalty',
1810
+ zh_Hans: '存在惩罚'
1735
1811
  },
1736
1812
  type: ParameterType.FLOAT,
1737
1813
  help: {
1738
- en_US: "Applies a penalty to the log-probability of tokens already in the text.",
1739
- zh_Hans: "对文本中已有的标记的对数概率施加惩罚。"
1814
+ en_US: 'Applies a penalty to the log-probability of tokens already in the text.',
1815
+ zh_Hans: '对文本中已有的标记的对数概率施加惩罚。'
1740
1816
  },
1741
1817
  required: false,
1742
1818
  default: 0.0,
@@ -1746,13 +1822,13 @@ const PARAMETER_RULE_TEMPLATE = {
1746
1822
  },
1747
1823
  [DefaultParameterName.FREQUENCY_PENALTY]: {
1748
1824
  label: {
1749
- en_US: "Frequency Penalty",
1750
- zh_Hans: "频率惩罚"
1825
+ en_US: 'Frequency Penalty',
1826
+ zh_Hans: '频率惩罚'
1751
1827
  },
1752
1828
  type: ParameterType.FLOAT,
1753
1829
  help: {
1754
- en_US: "Applies a penalty to the log-probability of tokens that appear in the text.",
1755
- zh_Hans: "对文本中出现的标记的对数概率施加惩罚。"
1830
+ en_US: 'Applies a penalty to the log-probability of tokens that appear in the text.',
1831
+ zh_Hans: '对文本中出现的标记的对数概率施加惩罚。'
1756
1832
  },
1757
1833
  required: false,
1758
1834
  default: 0.0,
@@ -1762,13 +1838,13 @@ const PARAMETER_RULE_TEMPLATE = {
1762
1838
  },
1763
1839
  [DefaultParameterName.MAX_TOKENS]: {
1764
1840
  label: {
1765
- en_US: "Max Tokens",
1766
- zh_Hans: "最大标记"
1841
+ en_US: 'Max Tokens',
1842
+ zh_Hans: '最大标记'
1767
1843
  },
1768
1844
  type: ParameterType.INT,
1769
1845
  help: {
1770
- en_US: "Specifies the upper limit on the length of generated results." + " If the generated results are truncated, you can increase this parameter.",
1771
- zh_Hans: "指定生成结果长度的上限。如果生成结果截断,可以调大该参数。"
1846
+ en_US: 'Specifies the upper limit on the length of generated results.' + ' If the generated results are truncated, you can increase this parameter.',
1847
+ zh_Hans: '指定生成结果长度的上限。如果生成结果截断,可以调大该参数。'
1772
1848
  },
1773
1849
  required: false,
1774
1850
  default: 2048,
@@ -1778,28 +1854,28 @@ const PARAMETER_RULE_TEMPLATE = {
1778
1854
  },
1779
1855
  [DefaultParameterName.RESPONSE_FORMAT]: {
1780
1856
  label: {
1781
- en_US: "Response Format",
1782
- zh_Hans: "回复格式"
1857
+ en_US: 'Response Format',
1858
+ zh_Hans: '回复格式'
1783
1859
  },
1784
1860
  type: ParameterType.STRING,
1785
1861
  help: {
1786
- en_US: "Set a response format, ensure the output from llm is a valid code block as possible," + " such as JSON, XML, etc.",
1787
- zh_Hans: "设置一个返回格式,确保llm的输出尽可能是有效的代码块,如JSON、XML等"
1862
+ en_US: 'Set a response format, ensure the output from llm is a valid code block as possible,' + ' such as JSON, XML, etc.',
1863
+ zh_Hans: '设置一个返回格式,确保llm的输出尽可能是有效的代码块,如JSON、XML等'
1788
1864
  },
1789
1865
  required: false,
1790
1866
  options: [
1791
- "JSON",
1792
- "XML"
1867
+ 'JSON',
1868
+ 'XML'
1793
1869
  ]
1794
1870
  },
1795
1871
  [DefaultParameterName.JSON_SCHEMA]: {
1796
1872
  label: {
1797
- en_US: "JSON Schema"
1873
+ en_US: 'JSON Schema'
1798
1874
  },
1799
1875
  type: ParameterType.TEXT,
1800
1876
  help: {
1801
- en_US: "Set a response json schema will ensure LLM to adhere it.",
1802
- zh_Hans: "设置返回的json schema,llm将按照它返回"
1877
+ en_US: 'Set a response json schema will ensure LLM to adhere it.',
1878
+ zh_Hans: '设置返回的json schema,llm将按照它返回'
1803
1879
  },
1804
1880
  required: false
1805
1881
  }
@@ -5831,4 +5907,549 @@ function freezeItems(items) {
5831
5907
  ]) : undefined;
5832
5908
  }
5833
5909
 
5834
- export { ACCOUNT_BINDING_PERMISSION_SERVICE_TOKEN, AGENT_CHAT_DISPATCH_ERROR_STEER_TARGET_NOT_RUNNING, AGENT_CHAT_DISPATCH_MESSAGE_TYPE, AGENT_MIDDLEWARE_STRATEGY, AIModel, AIModelProviderNotFoundException, AIModelProviderRegistry, AIModelProviderStrategy, AI_MODEL_PROVIDER, AdapterDataSourceStrategy, AgentMiddlewareRegistry, AgentMiddlewareStrategy, AiModelNotFoundException, AssistantTaskRuntimeCapability, BOUND_IDENTITY_LOGIN_PERMISSION_SERVICE_TOKEN, BUILTIN_GLOBAL_SCOPE, BaseHTTPQueryRunner, BaseQueryRunner, BaseSQLQueryRunner, BaseSandbox, BaseStrategyRegistry, CHAT_CHANNEL, CHAT_CHANNEL_TEXT_LIMITS, COLLABORATION_DOCUMENT_PROVIDER, CONNECTION_COMMAND_ROUTER_TOKEN, CONNECTOR_STRATEGY, CancelConversationCommand, ChatChannel, ChatChannelRegistry, ChatOAICompatReasoningModel, CollaborationDocumentProvider, CollaborationDocumentProviderRegistry, CollaborationRuntimeCapability, CommonParameterRules, ConnectorRuntimeCapability, ConnectorStrategyKey, ConnectorStrategyRegistry, CreateModelClientCommand, CredentialsValidateFailedError, DATASOURCE_STRATEGY, DBCreateTableMode, DBProtocolEnum, DBSyntaxEnum, DBTableAction, DBTableDataAction, DEFAULT_EXECUTION_CONFIG, DEFAULT_SANDBOX_EXECUTION_MAX_OUTPUT_BYTES, DEFAULT_SANDBOX_FILE_OPERATION_EXECUTION_OPTIONS, DEFAULT_SANDBOX_FILE_OPERATION_TIMEOUT_MS, DEFAULT_SANDBOX_FILE_OPERATION_TIMEOUT_SEC, DEFAULT_SANDBOX_FILE_SEARCH_EXECUTION_OPTIONS, DEFAULT_SANDBOX_FILE_SEARCH_TIMEOUT_MS, DEFAULT_SANDBOX_FILE_SEARCH_TIMEOUT_SEC, DEFAULT_SANDBOX_SHELL_EXECUTION_OPTIONS, DEFAULT_SANDBOX_SHELL_TIMEOUT_MS, DEFAULT_SANDBOX_SHELL_TIMEOUT_SEC, DOCUMENT_SOURCE_STRATEGY, DOCUMENT_TRANSFORMER_STRATEGY, DataSourceStrategy, DataSourceStrategyRegistry, DocumentSourceRegistry, DocumentSourceStrategy, DocumentTransformerRegistry, DocumentTransformerStrategy, EVOLUTION_RUNTIME_SERVICE_TOKEN, EVOLUTION_TARGET_PROVIDER, EvolutionRuntimeCapability, EvolutionTargetProviderRegistry, EvolutionTargetProviderStrategy, FILE_STORAGE_PROVIDER, FILE_UPLOAD_TARGET_STRATEGY, FileRuntimeCapability, FileStorageProvider, FileStorageProviderRegistry, FileUploadTargetRegistry, FileUploadTargetStrategy, GLOBAL_ORGANIZATION_SCOPE, HANDOFF_PERMISSION_SERVICE_TOKEN, HANDOFF_PROCESSOR_STRATEGY, HANDOFF_QUEUE_SERVICE_TOKEN, HandoffProcessorRegistry, HandoffProcessorStrategy, IMAGE_UNDERSTANDING_STRATEGY, INTEGRATION_PERMISSION_SERVICE_TOKEN, INTEGRATION_STRATEGY, ImageGenerationModel, ImageUnderstandingRegistry, ImageUnderstandingStrategy, IntegrationStrategyKey, IntegrationStrategyRegistry, JUMP_TO_TARGETS, JsonSchemaValidator, KNOWLEDGE_STRATEGY, KnowledgeStrategyKey, KnowledgeStrategyRegistry, LLMUsage, LargeLanguageModel, MANAGED_CONNECTION_REGISTRY_TOKEN, MANAGED_QUEUE_HANDLER_REGISTRY_TOKEN, MANAGED_QUEUE_SERVICE_TOKEN, MCP_CAPABILITY_CHANGE_EVENT_TYPES, MODEL_OUTPUT_VALIDATION_ERROR_CODE, ModelOutputValidationError, ModelProvider, ORGANIZATION_METADATA_KEY, OpenAICompatibleReranker, PERMISSION_OPERATION_METADATA_KEY, PLUGIN_CONFIG_RESOLVER_TOKEN, PLUGIN_JOB_PROCESSOR_METADATA, PLUGIN_METADATA, PLUGIN_METADATA_KEY, PLUGIN_VERSION_METADATA_KEY, PLUGIN_WEBHOOK_AUTH_METADATA_KEY, PLUGIN_WEBHOOK_AUTH_SERVICE_TOKEN, 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, PluginJobProcessor, PluginWebhookAuth, PluginWebhookAuthGuard, RETRIEVER_STRATEGY, RequestContext, RequestContextMiddleware, RequirePermissionOperation, RerankModel, RetrieverRegistry, RetrieverStrategy, SANDBOX_PROVIDER, SANDBOX_RUNTIME_PROVIDER, SANDBOX_SHELL_TIMEOUT_LIMITS_SEC, SANDBOX_WORKSPACE_MAPPER, SKILL_SOURCE_PROVIDER, SPEECH_TO_TEXT_PERMISSION_SERVICE_TOKEN, SPEECH_TO_TEXT_SERVICE_TOKEN, SSOProviderRegistry, SSOProviderStrategyKey, SSO_BINDING_PERMISSION_SERVICE_TOKEN, SSO_PROVIDER, STRATEGY_META_KEY, SYSTEM_GLOBAL_SCOPE, SandboxProviderRegistry, SandboxProviderStrategy, SandboxRuntimeProviderRegistry, SandboxRuntimeProviderStrategy, SandboxWorkspaceMapperRegistry, SandboxWorkspaceMapperStrategy, SkillSourceProviderRegistry, SkillSourceProviderStrategy, Speech2TextChatModel, SpeechToTextModel, StrategyBus, TENANT_GLOBAL_SCOPE_PREFIX, TENANT_GLOBAL_SCOPE_SUFFIX, TEXT_SPLITTER_STRATEGY, TOOLSET_STRATEGY, TextEmbeddingModelManager, TextSplitterRegistry, TextSplitterStrategy, TextToSpeechModel, ToolsetRegistry, ToolsetStrategy, USER_PERMISSION_SERVICE_TOKEN, VECTOR_STORE_STRATEGY, VIDEO_GENERATION_PERMISSION_SERVICE_TOKEN, VIDEO_GENERATION_SERVICE_TOKEN, VIDEO_GENERATOR_FAMILIES, VIEW_EXTENSION_CACHE_SERVICE_TOKEN, VIEW_EXTENSION_PROVIDER, VectorStoreRegistry, VectorStoreStrategy, VideoGenerationModel, ViewExtensionProvider, ViewExtensionProviderRegistry, WORKFLOW_NODE_STRATEGY, WORKFLOW_TRIGGER_STRATEGY, WorkflowNodeRegistry, WorkflowNodeStrategy, WorkflowTriggerRegistry, WorkflowTriggerStrategy, WrapWorkflowNodeExecutionCommand, XPERT_AGENT_MIDDLEWARE_RUNTIME_TOKEN, XpFileSystem, XpertServerPlugin, als, appendSandboxMessage, assertConnectorDefinition, buildSandboxTimeoutMessage, calcTokenUsage, calculateLLMUsagePrice, calculateModelPrice, calculateModelUsageCharge, chunkText, countTokensSafe, createI18nInstance, createPluginLogger, createRuntimeCapability, defineAgentMessageType, defineChannelMessageType, defineMcpApp, defineMcpCapabilities, defineMcpPrompt, defineMcpResource, defineMcpResourceTemplate, defineXpertTool, derivePluginArtifactNamespace, downloadRemoteFile, formatSandboxTimeout, getDefaultTenantId, getErrorMessage, getModelContextSize, getPermissionOperationMetadata, getPositionList, getPositionMap, getRequestContext, getRequiredPermissionOperation, getTenantGlobalScopeKey, isDevelopmentSandboxRuntimeEnvironment, isModelOutputValidationError, isModelUsagePricingConfig, isRemoteFile, isSandboxBackend, isSandboxManagedServiceAdapter, isSandboxServiceProxyAdapter, isSandboxTerminalAdapter, isStrategyInstance, isStructuredMessageType, isTenantGlobalScopeKey, loadYamlFile, mergeCredentials, mergeParentChildChunks, normalizeContextSize, pluginArtifactTableName, processAsyncAIGCManagedJob, renderRemoteModuleIframeHtml, renderRemoteReactIframeHtml, renderRemoteVueIframeHtml, resolveModelUsagePricingSnapshot, resolveSandboxBackend, resolveSandboxExecutionOptions, resolveSandboxManagedServiceAdapter, resolveSandboxServiceProxyAdapter, resolveSandboxTerminalAdapter, resolveStrategyMetadataTarget, resolveTenantGlobalScopeKey, resolveTokenUsage, runWithRequestContext, secondsToMilliseconds, setDefaultTenantId, sumTokenUsage };
5910
+ const XPERT_TOOL_PROVIDER = 'XPERT_TOOL_PROVIDER';
5911
+ const XPERT_TOOL_PROVIDER_METADATA = 'XPERT_TOOL_PROVIDER_METADATA';
5912
+ const XPERT_TOOL_METHOD_METADATA = 'XPERT_TOOL_METHOD_METADATA';
5913
+ /** Marks one injectable business service as a reusable Tool provider and one native MCP service. */ const XpertToolProvider = (options)=>applyDecorators(Injectable(), SetMetadata(XPERT_TOOL_PROVIDER, options.provider), SetMetadata(XPERT_TOOL_PROVIDER_METADATA, Object.freeze(_extends({}, options))), SetMetadata(STRATEGY_META_KEY, XPERT_TOOL_PROVIDER));
5914
+ /** Exposes one business method through an Agent Middleware, native MCP, or both. */ const XpertTool = (options)=>SetMetadata(XPERT_TOOL_METHOD_METADATA, Object.freeze(_extends({}, options)));
5915
+
5916
+ const PROVIDER_PATTERN = /^[a-z][a-z0-9_]*$/;
5917
+ const MIDDLEWARE_PROVIDER_PATTERN = /^[A-Za-z][A-Za-z0-9_]*$/;
5918
+ const COMPONENT_KEY_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
5919
+ const SLUG_PATTERN = COMPONENT_KEY_PATTERN;
5920
+ const TOOL_NAME_PATTERN = /^[A-Za-z0-9_-]+$/;
5921
+ function describeXpertToolProvider(instance) {
5922
+ const target = instance.constructor;
5923
+ const options = Reflect.getMetadata(XPERT_TOOL_PROVIDER_METADATA, target);
5924
+ if (!options) {
5925
+ throw new Error(`Provider '${target.name}' is missing @XpertToolProvider metadata.`);
5926
+ }
5927
+ validateProviderOptions(options);
5928
+ const methods = collectDecoratedMethods(instance);
5929
+ const names = new Set();
5930
+ var _options_middlewares;
5931
+ const middlewareProviders = new Set(((_options_middlewares = options.middlewares) != null ? _options_middlewares : []).map(({ provider })=>provider));
5932
+ var _options_apps;
5933
+ const appKeys = new Set(((_options_apps = options.apps) != null ? _options_apps : []).map(({ key })=>key));
5934
+ const tools = methods.map(({ methodName, options: toolOptions })=>{
5935
+ var _toolOptions_mcp_app;
5936
+ validateToolOptions(toolOptions, methodName);
5937
+ if (names.has(toolOptions.name)) {
5938
+ throw new Error(`Tool '${toolOptions.name}' is declared more than once by provider '${options.provider}'.`);
5939
+ }
5940
+ names.add(toolOptions.name);
5941
+ const middlewareProvider = resolveMiddlewareProvider(toolOptions, options);
5942
+ if (!middlewareProvider && !toolOptions.mcp) {
5943
+ throw new Error(`Tool '${toolOptions.name}' is not exposed through Middleware or MCP.`);
5944
+ }
5945
+ if (middlewareProvider && !middlewareProviders.has(middlewareProvider)) {
5946
+ throw new Error(`Tool '${toolOptions.name}' references undeclared Middleware provider '${middlewareProvider}'.`);
5947
+ }
5948
+ const appKey = toolOptions.mcp && ((_toolOptions_mcp_app = toolOptions.mcp.app) == null ? void 0 : _toolOptions_mcp_app.resourceKey);
5949
+ if (appKey && !appKeys.has(appKey)) {
5950
+ throw new Error(`MCP Tool '${toolOptions.name}' references undeclared App '${appKey}'.`);
5951
+ }
5952
+ return Object.freeze({
5953
+ methodName,
5954
+ middlewareProvider,
5955
+ options: toolOptions
5956
+ });
5957
+ });
5958
+ if (!tools.length) {
5959
+ throw new Error(`Provider '${options.provider}' does not declare any @XpertTool methods.`);
5960
+ }
5961
+ return Object.freeze({
5962
+ options: Object.freeze(_extends({}, options)),
5963
+ tools: Object.freeze(tools)
5964
+ });
5965
+ }
5966
+ function collectDecoratedMethods(instance) {
5967
+ const result = [];
5968
+ const seen = new Set();
5969
+ let prototype = Object.getPrototypeOf(instance);
5970
+ while(prototype && prototype !== Object.prototype){
5971
+ for (const methodName of Object.getOwnPropertyNames(prototype)){
5972
+ if (methodName === 'constructor' || seen.has(methodName)) continue;
5973
+ seen.add(methodName);
5974
+ const method = Reflect.get(prototype, methodName);
5975
+ if (typeof method !== 'function') continue;
5976
+ const options = Reflect.getMetadata(XPERT_TOOL_METHOD_METADATA, method);
5977
+ if (options) result.push({
5978
+ methodName,
5979
+ options
5980
+ });
5981
+ }
5982
+ prototype = Object.getPrototypeOf(prototype);
5983
+ }
5984
+ return result;
5985
+ }
5986
+ function validateProviderOptions(options) {
5987
+ var _options_name;
5988
+ if (!PROVIDER_PATTERN.test(options.provider)) {
5989
+ throw new Error(`Xpert Tool provider '${options.provider}' must use lowercase snake_case.`);
5990
+ }
5991
+ if (!COMPONENT_KEY_PATTERN.test(options.componentKey)) {
5992
+ throw new Error(`Xpert Tool component key '${options.componentKey}' must use lowercase kebab-case.`);
5993
+ }
5994
+ if (!((_options_name = options.name) == null ? void 0 : _options_name.trim())) throw new Error(`Xpert Tool provider '${options.provider}' requires a name.`);
5995
+ if (options.slug && !SLUG_PATTERN.test(options.slug)) {
5996
+ throw new Error(`Xpert Tool provider slug '${options.slug}' must use lowercase kebab-case.`);
5997
+ }
5998
+ const middlewareProviders = new Set();
5999
+ var _options_middlewares;
6000
+ for (const definition of (_options_middlewares = options.middlewares) != null ? _options_middlewares : []){
6001
+ if (!MIDDLEWARE_PROVIDER_PATTERN.test(definition.provider)) {
6002
+ throw new Error(`Middleware provider '${definition.provider}' must be a stable identifier.`);
6003
+ }
6004
+ if (middlewareProviders.has(definition.provider)) {
6005
+ throw new Error(`Middleware provider '${definition.provider}' is declared more than once.`);
6006
+ }
6007
+ if (definition.meta.name !== definition.provider) {
6008
+ throw new Error(`Middleware metadata name must match provider '${definition.provider}'.`);
6009
+ }
6010
+ middlewareProviders.add(definition.provider);
6011
+ }
6012
+ if (options.defaultMiddleware && !middlewareProviders.has(options.defaultMiddleware)) {
6013
+ throw new Error(`Default Middleware provider '${options.defaultMiddleware}' is not declared.`);
6014
+ }
6015
+ const appKeys = new Set();
6016
+ var _options_apps;
6017
+ for (const app of (_options_apps = options.apps) != null ? _options_apps : []){
6018
+ if (!TOOL_NAME_PATTERN.test(app.key) || app.key.length > 191) {
6019
+ throw new Error(`MCP App key '${app.key}' is invalid.`);
6020
+ }
6021
+ if (appKeys.has(app.key)) {
6022
+ throw new Error(`MCP App '${app.key}' is declared more than once.`);
6023
+ }
6024
+ if (!isRelativeHtmlEntry(app.entry)) {
6025
+ throw new Error(`MCP App '${app.key}' entry must be a relative HTML path inside the plugin bundle.`);
6026
+ }
6027
+ appKeys.add(app.key);
6028
+ }
6029
+ }
6030
+ function validateToolOptions(options, methodName) {
6031
+ var _options_description;
6032
+ if (!TOOL_NAME_PATTERN.test(options.name) || options.name.length > 191) {
6033
+ throw new Error(`Method '${methodName}' declares invalid Tool name '${options.name}'.`);
6034
+ }
6035
+ if (!((_options_description = options.description) == null ? void 0 : _options_description.trim())) throw new Error(`Tool '${options.name}' requires a description.`);
6036
+ assertStrictObjectSchema(options.inputSchema, options.name, 'input');
6037
+ if (options.mcp && !options.outputSchema) {
6038
+ throw new Error(`MCP Tool '${options.name}' requires an outputSchema.`);
6039
+ }
6040
+ if (options.mcp && options.outputSchema) {
6041
+ assertStrictObjectSchema(options.outputSchema, options.name, 'output');
6042
+ }
6043
+ if (options.mcp && !options.mcp.requiredContext.length) {
6044
+ throw new Error(`MCP Tool '${options.name}' requires at least one execution context.`);
6045
+ }
6046
+ if (options.mcp) {
6047
+ const behavior = options.mcp.behavior;
6048
+ if (!includesValue(MCP_TOOL_RISKS, behavior == null ? void 0 : behavior.risk) || !includesValue(MCP_TOOL_SIDE_EFFECTS, behavior == null ? void 0 : behavior.sideEffect) || !includesValue(MCP_TOOL_IDEMPOTENCY, behavior == null ? void 0 : behavior.idempotency)) {
6049
+ throw new Error(`MCP Tool '${options.name}' requires valid behavior annotations.`);
6050
+ }
6051
+ const contexts = new Set(options.mcp.requiredContext);
6052
+ if (contexts.size !== options.mcp.requiredContext.length || [
6053
+ ...contexts
6054
+ ].some((context)=>!includesValue(MCP_REQUIRED_CONTEXTS, context))) {
6055
+ throw new Error(`MCP Tool '${options.name}' declares invalid or duplicate execution context requirements.`);
6056
+ }
6057
+ if (options.mcp.visibility && (!options.mcp.visibility.length || new Set(options.mcp.visibility).size !== options.mcp.visibility.length || options.mcp.visibility.some((visibility)=>!includesValue(MCP_CAPABILITY_VISIBILITIES, visibility)))) {
6058
+ throw new Error(`MCP Tool '${options.name}' declares invalid visibility.`);
6059
+ }
6060
+ if (options.mcp.app && options.mcp.visibility && !options.mcp.visibility.includes('app')) {
6061
+ throw new Error(`MCP Tool '${options.name}' with an App binding must include app visibility.`);
6062
+ }
6063
+ }
6064
+ }
6065
+ function isRelativeHtmlEntry(entry) {
6066
+ if (!entry || !entry.endsWith('.html') || entry.startsWith('/') || entry.includes('\\')) return false;
6067
+ return entry.split('/').every((segment)=>segment !== '.' && segment !== '..' && segment.length > 0);
6068
+ }
6069
+ function assertStrictObjectSchema(schema, toolName, role) {
6070
+ if (!schema || typeof Reflect.get(schema, 'parseAsync') !== 'function') {
6071
+ throw new Error(`Tool '${toolName}' requires a Zod ${role} schema.`);
6072
+ }
6073
+ const definition = Reflect.get(schema, '_def');
6074
+ if (!definition || Reflect.get(definition, 'unknownKeys') !== 'strict') {
6075
+ throw new Error(`Tool '${toolName}' ${role} schema must be a strict Zod object.`);
6076
+ }
6077
+ }
6078
+ function resolveMiddlewareProvider(tool, provider) {
6079
+ if (tool.middleware === false) return undefined;
6080
+ if (typeof tool.middleware === 'string') return tool.middleware;
6081
+ if (tool.middleware === true || tool.middleware === undefined) return provider.defaultMiddleware;
6082
+ return undefined;
6083
+ }
6084
+ function getXpertToolMethod(instance, descriptor) {
6085
+ const method = Reflect.get(instance, descriptor.methodName);
6086
+ if (typeof method !== 'function') {
6087
+ throw new Error(`Decorated Tool method '${descriptor.methodName}' is not callable.`);
6088
+ }
6089
+ return method.bind(instance);
6090
+ }
6091
+ function includesValue(values, value) {
6092
+ return values.some((candidate)=>candidate === value);
6093
+ }
6094
+
6095
+ let XpertToolProviderRegistry = class XpertToolProviderRegistry extends BaseStrategyRegistry {
6096
+ upsert(candidate) {
6097
+ const target = resolveStrategyMetadataTarget(candidate);
6098
+ if (!target || !Reflect.getMetadata(XPERT_TOOL_PROVIDER_METADATA, target)) return;
6099
+ const instance = candidate;
6100
+ const descriptor = describeXpertToolProvider(instance);
6101
+ const source = this.getSource(instance);
6102
+ this.assertUniqueClaims(instance, descriptor, source.scopeKey);
6103
+ const previous = this.register(descriptor.options.provider, instance, source);
6104
+ this.replacements.set(instance, previous != null ? previous : null);
6105
+ }
6106
+ rollback(instance) {
6107
+ const descriptor = describeXpertToolProvider(instance);
6108
+ const source = this.getSource(instance);
6109
+ const previous = this.replacements.get(instance);
6110
+ if (previous) {
6111
+ this.register(descriptor.options.provider, previous, this.getSource(previous));
6112
+ } else {
6113
+ this.unregister(descriptor.options.provider, source, instance);
6114
+ }
6115
+ this.replacements.delete(instance);
6116
+ }
6117
+ assertUniqueClaims(instance, descriptor, scopeKey) {
6118
+ var _this_strategies_get;
6119
+ const toolNames = new Set(descriptor.tools.map(({ options })=>options.name));
6120
+ var _this_strategies_get_entries;
6121
+ for (const [providerKey, existing] of (_this_strategies_get_entries = (_this_strategies_get = this.strategies.get(scopeKey)) == null ? void 0 : _this_strategies_get.entries()) != null ? _this_strategies_get_entries : []){
6122
+ if (existing === instance || providerKey === descriptor.options.provider) continue;
6123
+ const existingDescriptor = describeXpertToolProvider(existing);
6124
+ if (existingDescriptor.options.componentKey === descriptor.options.componentKey) {
6125
+ throw new Error(`Component key '${descriptor.options.componentKey}' is already registered for scope '${scopeKey}'.`);
6126
+ }
6127
+ const duplicateTool = existingDescriptor.tools.find(({ options })=>toolNames.has(options.name));
6128
+ if (duplicateTool) {
6129
+ throw new Error(`Tool '${duplicateTool.options.name}' is already registered for scope '${scopeKey}'.`);
6130
+ }
6131
+ }
6132
+ }
6133
+ constructor(discoveryService, reflector){
6134
+ super(XPERT_TOOL_PROVIDER, discoveryService, reflector);
6135
+ this.replacements = new WeakMap();
6136
+ }
6137
+ };
6138
+ XpertToolProviderRegistry = __decorate([
6139
+ Injectable(),
6140
+ __metadata("design:paramtypes", [
6141
+ DiscoveryService,
6142
+ Reflector
6143
+ ])
6144
+ ], XpertToolProviderRegistry);
6145
+
6146
+ class DecoratedToolsetStrategy {
6147
+ validateConfig() {
6148
+ return Promise.resolve();
6149
+ }
6150
+ async create(toolset, params) {
6151
+ return new DecoratedBuiltinToolset(this.instance, this.descriptor, toolset, params, this.pluginName, this.pluginVersion);
6152
+ }
6153
+ createTools() {
6154
+ return [];
6155
+ }
6156
+ constructor(instance, pluginName, pluginVersion){
6157
+ this.instance = instance;
6158
+ this.pluginName = pluginName;
6159
+ this.pluginVersion = pluginVersion;
6160
+ this.descriptor = describeXpertToolProvider(instance);
6161
+ const options = this.descriptor.options;
6162
+ var _options_author, _options_tags, _options_label, _options_configSchema;
6163
+ this.meta = _extends({
6164
+ author: (_options_author = options.author) != null ? _options_author : 'Plugin',
6165
+ tags: [
6166
+ ...(_options_tags = options.tags) != null ? _options_tags : [
6167
+ 'mcp'
6168
+ ]
6169
+ ],
6170
+ name: options.provider,
6171
+ label: (_options_label = options.label) != null ? _options_label : asI18n(options.name)
6172
+ }, options.description ? {
6173
+ description: asI18n(options.description)
6174
+ } : {}, {
6175
+ configSchema: (_options_configSchema = options.configSchema) != null ? _options_configSchema : {
6176
+ type: 'object',
6177
+ properties: {},
6178
+ required: []
6179
+ }
6180
+ }, options.icon ? {
6181
+ icon: options.icon
6182
+ } : {});
6183
+ }
6184
+ }
6185
+ class DecoratedAgentMiddlewareStrategy {
6186
+ async createMiddleware(options, context) {
6187
+ const tools = this.descriptor.tools.filter((item)=>item.middlewareProvider === this.provider).map((item)=>createAgentTool(this.instance, item, context, options));
6188
+ const extensions = await (this.instance.getMiddlewareExtensions == null ? void 0 : this.instance.getMiddlewareExtensions.call(this.instance, this.provider, options, context));
6189
+ return _extends({}, extensions != null ? extensions : {}, {
6190
+ name: this.provider,
6191
+ tools
6192
+ });
6193
+ }
6194
+ constructor(instance, descriptor, provider){
6195
+ var _descriptor_options_middlewares;
6196
+ this.instance = instance;
6197
+ this.descriptor = descriptor;
6198
+ this.provider = provider;
6199
+ const definition = (_descriptor_options_middlewares = descriptor.options.middlewares) == null ? void 0 : _descriptor_options_middlewares.find((item)=>item.provider === provider);
6200
+ if (!definition) throw new Error(`Middleware provider '${provider}' is not declared.`);
6201
+ this.meta = definition.meta;
6202
+ }
6203
+ }
6204
+ var _definitions = /*#__PURE__*/ _class_private_field_loose_key("_definitions");
6205
+ let DecoratedBuiltinToolset = class DecoratedBuiltinToolset extends BuiltinToolset {
6206
+ _validateCredentials() {
6207
+ return Promise.resolve();
6208
+ }
6209
+ async initTools() {
6210
+ return this.tools;
6211
+ }
6212
+ getMcpCapabilityDefinitions() {
6213
+ return _class_private_field_loose_base(this, _definitions)[_definitions];
6214
+ }
6215
+ getMcpCapabilitySource() {
6216
+ return _extends({}, this.pluginName ? {
6217
+ pluginName: this.pluginName
6218
+ } : {}, this.pluginVersion ? {
6219
+ pluginVersion: this.pluginVersion
6220
+ } : {});
6221
+ }
6222
+ constructor(instance, descriptor, toolset, params, pluginName, pluginVersion){
6223
+ var _descriptor_options_apps;
6224
+ super(descriptor.options.provider, toolset, params);
6225
+ Object.defineProperty(this, _definitions, {
6226
+ writable: true,
6227
+ value: void 0
6228
+ });
6229
+ this.pluginName = pluginName;
6230
+ this.pluginVersion = pluginVersion;
6231
+ this.tools = [];
6232
+ _class_private_field_loose_base(this, _definitions)[_definitions] = _extends({
6233
+ instructions: descriptor.options.instructions,
6234
+ tools: descriptor.tools.filter((item)=>!!item.options.mcp).map((item)=>createMcpTool(instance, item))
6235
+ }, ((_descriptor_options_apps = descriptor.options.apps) == null ? void 0 : _descriptor_options_apps.length) ? {
6236
+ apps: [
6237
+ ...descriptor.options.apps
6238
+ ]
6239
+ } : {});
6240
+ }
6241
+ };
6242
+ function createAgentTool(instance, descriptor, middlewareContext, middlewareOptions) {
6243
+ const invoke = getXpertToolMethod(instance, descriptor);
6244
+ return tool(async (input, config)=>{
6245
+ const parsedInput = await descriptor.options.inputSchema.parseAsync(input);
6246
+ const output = await invoke(parsedInput, agentExecutionContext(middlewareContext, middlewareOptions, config));
6247
+ const parsedOutput = descriptor.options.outputSchema ? await descriptor.options.outputSchema.parseAsync(output) : output;
6248
+ return stringifyDto(parsedOutput, descriptor.options.name);
6249
+ }, _extends({
6250
+ name: descriptor.options.name,
6251
+ description: descriptor.options.description,
6252
+ schema: descriptor.options.inputSchema,
6253
+ verboseParsingErrors: true
6254
+ }, descriptor.options.metadata ? {
6255
+ metadata: descriptor.options.metadata
6256
+ } : {}));
6257
+ }
6258
+ function createMcpTool(instance, descriptor) {
6259
+ const mcp = descriptor.options.mcp;
6260
+ const outputSchema = descriptor.options.outputSchema;
6261
+ if (!mcp || !outputSchema) throw new Error(`MCP Tool '${descriptor.options.name}' is incomplete.`);
6262
+ const invoke = getXpertToolMethod(instance, descriptor);
6263
+ var _mcp_visibility;
6264
+ return _extends({
6265
+ name: descriptor.options.name
6266
+ }, descriptor.options.title ? {
6267
+ title: descriptor.options.title
6268
+ } : {}, {
6269
+ description: descriptor.options.description,
6270
+ inputSchema: descriptor.options.inputSchema,
6271
+ outputSchema,
6272
+ exposure: {
6273
+ mcp: {
6274
+ eligible: true
6275
+ }
6276
+ },
6277
+ behavior: mcp.behavior,
6278
+ requiredContext: [
6279
+ ...mcp.requiredContext
6280
+ ],
6281
+ visibility: [
6282
+ ...(_mcp_visibility = mcp.visibility) != null ? _mcp_visibility : mcp.app ? [
6283
+ 'model',
6284
+ 'app'
6285
+ ] : [
6286
+ 'model'
6287
+ ]
6288
+ ]
6289
+ }, mcp.app ? {
6290
+ app: {
6291
+ resourceKey: mcp.app.resourceKey
6292
+ }
6293
+ } : {}, {
6294
+ execute: async (input, context)=>{
6295
+ const parsedInput = await descriptor.options.inputSchema.parseAsync(input);
6296
+ const output = await invoke(parsedInput, mcpExecutionContext(context));
6297
+ const parsedOutput = await outputSchema.parseAsync(output);
6298
+ const dto = jsonDto(parsedOutput, descriptor.options.name);
6299
+ var _descriptor_options_title;
6300
+ return {
6301
+ content: [
6302
+ {
6303
+ type: 'text',
6304
+ text: `${(_descriptor_options_title = descriptor.options.title) != null ? _descriptor_options_title : descriptor.options.name} completed. See structuredContent for the result.`
6305
+ }
6306
+ ],
6307
+ structuredContent: dto
6308
+ };
6309
+ }
6310
+ });
6311
+ }
6312
+ function agentExecutionContext(context, middlewareOptions, config) {
6313
+ const configurable = config.configurable;
6314
+ const requestId = readString(configurable, 'tool_call_id');
6315
+ const executionId = readString(configurable, 'executionId');
6316
+ const traceId = readString(configurable, 'traceId');
6317
+ return _extends({
6318
+ surface: 'middleware',
6319
+ tenantId: context.tenantId,
6320
+ organizationId: context.organizationId,
6321
+ principal: {
6322
+ type: 'user',
6323
+ id: context.userId,
6324
+ userId: context.userId
6325
+ },
6326
+ workspaceId: context.workspaceId,
6327
+ projectId: context.projectId,
6328
+ conversationId: context.conversationId,
6329
+ threadId: context.threadId,
6330
+ xpertId: context.xpertId,
6331
+ agentKey: context.agentKey
6332
+ }, executionId ? {
6333
+ executionId
6334
+ } : {}, requestId ? {
6335
+ requestId
6336
+ } : {}, traceId ? {
6337
+ traceId
6338
+ } : {}, {
6339
+ signal: config.signal,
6340
+ host: {
6341
+ models: {
6342
+ createModelClient: context.runtime.createModelClient,
6343
+ getModelProvider: context.runtime.getModelProvider
6344
+ }
6345
+ },
6346
+ middlewareOptions
6347
+ });
6348
+ }
6349
+ function mcpExecutionContext(context) {
6350
+ return {
6351
+ surface: 'mcp',
6352
+ tenantId: context.tenantId,
6353
+ organizationId: context.organizationId,
6354
+ principal: context.principal,
6355
+ workspaceId: context.workspaceId,
6356
+ projectId: context.projectId,
6357
+ conversationId: context.conversationId,
6358
+ threadId: readString(context, 'threadId'),
6359
+ xpertId: context.xpertId,
6360
+ agentKey: context.agentKey,
6361
+ executionId: context.executionId,
6362
+ requestId: context.requestId,
6363
+ traceId: context.traceId,
6364
+ signal: context.signal,
6365
+ host: context.host
6366
+ };
6367
+ }
6368
+ function stringifyDto(value, toolName) {
6369
+ const result = JSON.stringify(value);
6370
+ if (result === undefined) throw new Error(`Tool '${toolName}' returned a non-JSON value.`);
6371
+ return result;
6372
+ }
6373
+ function jsonDto(value, toolName) {
6374
+ return JSON.parse(stringifyDto(value, toolName));
6375
+ }
6376
+ function asI18n(value) {
6377
+ return {
6378
+ en_US: value,
6379
+ zh_Hans: value
6380
+ };
6381
+ }
6382
+ function readString(value, key) {
6383
+ if (!value || typeof value !== 'object') return undefined;
6384
+ const field = Reflect.get(value, key);
6385
+ return typeof field === 'string' && field ? field : undefined;
6386
+ }
6387
+
6388
+ /** Expands one decorated business provider into the existing Toolset and Middleware registries. */ let XpertToolProviderCoordinator = class XpertToolProviderCoordinator {
6389
+ onModuleInit() {
6390
+ this.subscription = this.bus.events$.subscribe((event)=>{
6391
+ if (event.type === 'UPSERT' && event.strategyType === XPERT_TOOL_PROVIDER) {
6392
+ this.expand(event.entry.instance);
6393
+ }
6394
+ });
6395
+ for (const wrapper of this.discovery.getProviders()){
6396
+ if (wrapper.instance) this.expand(wrapper.instance);
6397
+ }
6398
+ }
6399
+ onModuleDestroy() {
6400
+ var _this_subscription;
6401
+ (_this_subscription = this.subscription) == null ? void 0 : _this_subscription.unsubscribe();
6402
+ }
6403
+ expand(candidate) {
6404
+ if (!candidate || typeof candidate !== 'object' && typeof candidate !== 'function') return;
6405
+ const instance = candidate;
6406
+ if (this.processed.has(instance)) return;
6407
+ const target = resolveStrategyMetadataTarget(instance);
6408
+ if (!target || !Reflect.getMetadata(XPERT_TOOL_PROVIDER_METADATA, target)) return;
6409
+ const provider = instance;
6410
+ const descriptor = describeXpertToolProvider(provider);
6411
+ const source = this.providerRegistry.getSource(provider);
6412
+ const pluginName = source.kind === 'plugin' ? source.pluginName : undefined;
6413
+ const pluginVersion = source.kind === 'plugin' ? source.pluginVersion : undefined;
6414
+ const toolsetAdapter = new DecoratedToolsetStrategy(provider, pluginName, pluginVersion);
6415
+ var _descriptor_options_middlewares;
6416
+ const middlewareAdapters = ((_descriptor_options_middlewares = descriptor.options.middlewares) != null ? _descriptor_options_middlewares : []).filter((definition)=>descriptor.tools.some((item)=>item.middlewareProvider === definition.provider)).map((definition)=>({
6417
+ provider: definition.provider,
6418
+ strategy: new DecoratedAgentMiddlewareStrategy(provider, descriptor, definition.provider)
6419
+ }));
6420
+ try {
6421
+ this.toolsetRegistry.assertCanRegister(descriptor.options.provider, toolsetAdapter, source);
6422
+ for (const adapter of middlewareAdapters){
6423
+ this.middlewareRegistry.assertCanRegister(adapter.provider, adapter.strategy, source);
6424
+ }
6425
+ } catch (error) {
6426
+ this.providerRegistry.rollback(provider);
6427
+ throw error;
6428
+ }
6429
+ this.toolsetRegistry.register(descriptor.options.provider, toolsetAdapter, source);
6430
+ for (const adapter of middlewareAdapters){
6431
+ this.middlewareRegistry.register(adapter.provider, adapter.strategy, source);
6432
+ }
6433
+ this.processed.add(instance);
6434
+ }
6435
+ constructor(discovery, bus, providerRegistry, toolsetRegistry, middlewareRegistry){
6436
+ this.processed = new WeakSet();
6437
+ this.discovery = discovery;
6438
+ this.bus = bus;
6439
+ this.providerRegistry = providerRegistry;
6440
+ this.toolsetRegistry = toolsetRegistry;
6441
+ this.middlewareRegistry = middlewareRegistry;
6442
+ }
6443
+ };
6444
+ XpertToolProviderCoordinator = __decorate([
6445
+ Injectable(),
6446
+ __metadata("design:paramtypes", [
6447
+ DiscoveryService,
6448
+ StrategyBus,
6449
+ XpertToolProviderRegistry,
6450
+ ToolsetRegistry,
6451
+ AgentMiddlewareRegistry
6452
+ ])
6453
+ ], XpertToolProviderCoordinator);
6454
+
6455
+ export { ACCOUNT_BINDING_PERMISSION_SERVICE_TOKEN, AGENT_CHAT_DISPATCH_ERROR_STEER_TARGET_NOT_RUNNING, AGENT_CHAT_DISPATCH_MESSAGE_TYPE, AGENT_MIDDLEWARE_STRATEGY, AIModel, AIModelProviderNotFoundException, AIModelProviderRegistry, AIModelProviderStrategy, AI_MODEL_PROVIDER, AdapterDataSourceStrategy, AgentMiddlewareRegistry, AgentMiddlewareStrategy, AiModelNotFoundException, AssistantTaskRuntimeCapability, BOUND_IDENTITY_LOGIN_PERMISSION_SERVICE_TOKEN, BUILTIN_GLOBAL_SCOPE, BaseHTTPQueryRunner, BaseQueryRunner, BaseSQLQueryRunner, BaseSandbox, BaseStrategyRegistry, BuiltinToolset, CHAT_CHANNEL, CHAT_CHANNEL_TEXT_LIMITS, COLLABORATION_DOCUMENT_PROVIDER, CONNECTION_COMMAND_ROUTER_TOKEN, CONNECTOR_STRATEGY, CancelConversationCommand, ChatChannel, ChatChannelRegistry, ChatOAICompatReasoningModel, CollaborationDocumentProvider, CollaborationDocumentProviderRegistry, CollaborationRuntimeCapability, CommonParameterRules, ConnectorRuntimeCapability, ConnectorStrategyKey, ConnectorStrategyRegistry, CreateModelClientCommand, CredentialsValidateFailedError, DATASOURCE_STRATEGY, DBCreateTableMode, DBProtocolEnum, DBSyntaxEnum, DBTableAction, DBTableDataAction, DEFAULT_EXECUTION_CONFIG, DEFAULT_SANDBOX_EXECUTION_MAX_OUTPUT_BYTES, DEFAULT_SANDBOX_FILE_OPERATION_EXECUTION_OPTIONS, DEFAULT_SANDBOX_FILE_OPERATION_TIMEOUT_MS, DEFAULT_SANDBOX_FILE_OPERATION_TIMEOUT_SEC, DEFAULT_SANDBOX_FILE_SEARCH_EXECUTION_OPTIONS, DEFAULT_SANDBOX_FILE_SEARCH_TIMEOUT_MS, DEFAULT_SANDBOX_FILE_SEARCH_TIMEOUT_SEC, DEFAULT_SANDBOX_SHELL_EXECUTION_OPTIONS, DEFAULT_SANDBOX_SHELL_TIMEOUT_MS, DEFAULT_SANDBOX_SHELL_TIMEOUT_SEC, DOCUMENT_SOURCE_STRATEGY, DOCUMENT_TRANSFORMER_STRATEGY, DataSourceStrategy, DataSourceStrategyRegistry, DecoratedAgentMiddlewareStrategy, DecoratedToolsetStrategy, DocumentSourceRegistry, DocumentSourceStrategy, DocumentTransformerRegistry, DocumentTransformerStrategy, EVOLUTION_RUNTIME_SERVICE_TOKEN, EVOLUTION_TARGET_PROVIDER, EvolutionRuntimeCapability, EvolutionTargetProviderRegistry, EvolutionTargetProviderStrategy, FILE_STORAGE_PROVIDER, FILE_UPLOAD_TARGET_STRATEGY, FileRuntimeCapability, FileStorageProvider, FileStorageProviderRegistry, FileUploadTargetRegistry, FileUploadTargetStrategy, GLOBAL_ORGANIZATION_SCOPE, HANDOFF_PERMISSION_SERVICE_TOKEN, HANDOFF_PROCESSOR_STRATEGY, HANDOFF_QUEUE_SERVICE_TOKEN, HandoffProcessorRegistry, HandoffProcessorStrategy, IMAGE_UNDERSTANDING_STRATEGY, INTEGRATION_PERMISSION_SERVICE_TOKEN, INTEGRATION_STRATEGY, ImageGenerationModel, ImageUnderstandingRegistry, ImageUnderstandingStrategy, IntegrationStrategyKey, IntegrationStrategyRegistry, JUMP_TO_TARGETS, JsonSchemaValidator, KNOWLEDGE_STRATEGY, KnowledgeStrategyKey, KnowledgeStrategyRegistry, LLMUsage, LargeLanguageModel, MANAGED_CONNECTION_REGISTRY_TOKEN, MANAGED_QUEUE_HANDLER_REGISTRY_TOKEN, MANAGED_QUEUE_SERVICE_TOKEN, MCP_CAPABILITY_CHANGE_EVENT_TYPES, MODEL_OUTPUT_VALIDATION_ERROR_CODE, ModelOutputValidationError, ModelProvider, ORGANIZATION_METADATA_KEY, OpenAICompatibleReranker, PERMISSION_OPERATION_METADATA_KEY, PLUGIN_CONFIG_RESOLVER_TOKEN, PLUGIN_JOB_PROCESSOR_METADATA, PLUGIN_METADATA, PLUGIN_METADATA_KEY, PLUGIN_VERSION_METADATA_KEY, PLUGIN_WEBHOOK_AUTH_METADATA_KEY, PLUGIN_WEBHOOK_AUTH_SERVICE_TOKEN, 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, PluginJobProcessor, PluginWebhookAuth, PluginWebhookAuthGuard, RETRIEVER_STRATEGY, RequestContext, RequestContextMiddleware, RequirePermissionOperation, RerankModel, RetrieverRegistry, RetrieverStrategy, SANDBOX_PROVIDER, SANDBOX_RUNTIME_PROVIDER, SANDBOX_SHELL_TIMEOUT_LIMITS_SEC, SANDBOX_WORKSPACE_MAPPER, SKILL_SOURCE_PROVIDER, SPEECH_TO_TEXT_PERMISSION_SERVICE_TOKEN, SPEECH_TO_TEXT_SERVICE_TOKEN, SSOProviderRegistry, SSOProviderStrategyKey, SSO_BINDING_PERMISSION_SERVICE_TOKEN, SSO_PROVIDER, STRATEGY_META_KEY, SYSTEM_GLOBAL_SCOPE, SandboxProviderRegistry, SandboxProviderStrategy, SandboxRuntimeProviderRegistry, SandboxRuntimeProviderStrategy, SandboxWorkspaceMapperRegistry, SandboxWorkspaceMapperStrategy, SkillSourceProviderRegistry, SkillSourceProviderStrategy, Speech2TextChatModel, SpeechToTextModel, StrategyBus, TENANT_GLOBAL_SCOPE_PREFIX, TENANT_GLOBAL_SCOPE_SUFFIX, TEXT_SPLITTER_STRATEGY, TOOLSET_STRATEGY, TextEmbeddingModelManager, TextSplitterRegistry, TextSplitterStrategy, TextToSpeechModel, ToolsetRegistry, ToolsetStrategy, USER_PERMISSION_SERVICE_TOKEN, VECTOR_STORE_STRATEGY, VIDEO_GENERATION_PERMISSION_SERVICE_TOKEN, VIDEO_GENERATION_SERVICE_TOKEN, VIDEO_GENERATOR_FAMILIES, VIEW_EXTENSION_CACHE_SERVICE_TOKEN, VIEW_EXTENSION_PROVIDER, VectorStoreRegistry, VectorStoreStrategy, VideoGenerationModel, ViewExtensionProvider, ViewExtensionProviderRegistry, WORKFLOW_NODE_STRATEGY, WORKFLOW_TRIGGER_STRATEGY, WorkflowNodeRegistry, WorkflowNodeStrategy, WorkflowTriggerRegistry, WorkflowTriggerStrategy, WrapWorkflowNodeExecutionCommand, XPERT_AGENT_MIDDLEWARE_RUNTIME_TOKEN, XPERT_TOOL_METHOD_METADATA, XPERT_TOOL_PROVIDER, XPERT_TOOL_PROVIDER_METADATA, XpFileSystem, XpertServerPlugin, XpertTool, XpertToolProvider, XpertToolProviderCoordinator, XpertToolProviderRegistry, als, appendSandboxMessage, assertConnectorDefinition, buildSandboxTimeoutMessage, calcTokenUsage, calculateLLMUsagePrice, calculateModelPrice, calculateModelUsageCharge, chunkText, countTokensSafe, createI18nInstance, createPluginLogger, createRuntimeCapability, defineAgentMessageType, defineChannelMessageType, defineMcpApp, defineMcpCapabilities, defineMcpPrompt, defineMcpResource, defineMcpResourceTemplate, defineXpertTool, derivePluginArtifactNamespace, describeXpertToolProvider, downloadRemoteFile, formatSandboxTimeout, getDefaultTenantId, getErrorMessage, getModelContextSize, getPermissionOperationMetadata, getPositionList, getPositionMap, getRequestContext, getRequiredPermissionOperation, getTenantGlobalScopeKey, getXpertToolMethod, isDevelopmentSandboxRuntimeEnvironment, isModelOutputValidationError, isModelUsagePricingConfig, isRemoteFile, isSandboxBackend, isSandboxManagedServiceAdapter, isSandboxServiceProxyAdapter, isSandboxTerminalAdapter, isStrategyInstance, isStructuredMessageType, isTenantGlobalScopeKey, loadYamlFile, mergeCredentials, mergeParentChildChunks, normalizeContextSize, pluginArtifactTableName, processAsyncAIGCManagedJob, renderRemoteModuleIframeHtml, renderRemoteReactIframeHtml, renderRemoteVueIframeHtml, resolveModelUsagePricingSnapshot, resolveSandboxBackend, resolveSandboxExecutionOptions, resolveSandboxManagedServiceAdapter, resolveSandboxServiceProxyAdapter, resolveSandboxTerminalAdapter, resolveStrategyMetadataTarget, resolveTenantGlobalScopeKey, resolveTokenUsage, runWithRequestContext, secondsToMilliseconds, setDefaultTenantId, sumTokenUsage };