@xpert-ai/plugin-sdk 3.35.0 → 3.37.0
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/agent-results.cjs.js +5 -3
- package/agent-results.esm.js +2 -2
- package/analytics-result.cjs.js +64 -27
- package/analytics-result.esm.js +62 -28
- package/analytics.cjs.js +157 -15
- package/analytics.esm.js +154 -17
- package/artifact-document.cjs.js +9 -3
- package/artifact-document.esm.js +9 -3
- package/collaboration-client.cjs.js +274 -140
- package/collaboration-client.esm.js +273 -141
- package/docs/README.md +23 -0
- package/index.cjs.js +227 -10
- package/index.esm.js +198 -13
- package/package.json +8 -2
- package/remote-component.cjs.default.js +1 -0
- package/remote-component.cjs.js +143 -0
- package/remote-component.cjs.mjs +2 -0
- package/remote-component.d.ts +1 -0
- package/remote-component.esm.js +139 -0
- package/results.cjs.js +2 -14
- package/results.esm.js +2 -12
- package/src/analytics.d.ts +2 -0
- package/src/collaboration-client.d.ts +1 -0
- package/src/index.d.ts +1 -0
- package/src/lib/agent/handoff/agent-runtime-message.contract.d.ts +24 -24
- package/src/lib/agent/middleware/strategy.interface.d.ts +4 -0
- package/src/lib/agent/runtime/capability.d.ts +2 -0
- package/src/lib/agent/runtime/cli-model-profile.d.ts +14 -1
- package/src/lib/agent/runtime/dispatch.d.ts +79 -79
- package/src/lib/agent/runtime/execution-runner.d.ts +19 -10
- package/src/lib/agent/runtime/pipeline-scope.d.ts +4 -4
- package/src/lib/agent/runtime/results.d.ts +14 -234
- package/src/lib/agent/runtime/types.d.ts +19 -0
- package/src/lib/agent-event/index.d.ts +89 -0
- package/src/lib/agent-event/journal.d.ts +30 -0
- package/src/lib/artifact-document/dependencies.d.ts +3 -3
- package/src/lib/artifact-document/protocol.d.ts +2 -2
- package/src/lib/artifact-document/scheduler.d.ts +3 -0
- package/src/lib/artifact-type/definition.schema.d.ts +11 -39
- package/src/lib/assistant-capability/middleware.d.ts +2 -1
- package/src/lib/channel/strategy.interface.d.ts +20 -0
- package/src/lib/collaboration/client.d.ts +6 -59
- package/src/lib/collaboration/index.d.ts +1 -0
- package/src/lib/collaboration/operations-client.d.ts +23 -0
- package/src/lib/collaboration/presence.d.ts +36 -0
- package/src/lib/collaboration/provider.registry.d.ts +2 -2
- package/src/lib/collaboration/transport.d.ts +24 -0
- package/src/lib/collaboration/types.d.ts +57 -5
- package/src/lib/content-resource/catalog.d.ts +40 -2
- package/src/lib/content-resource/editor.d.ts +36 -1
- package/src/lib/data/analytics/analysis-evidence.d.ts +757 -0
- package/src/lib/data/analytics/analytics-certification.d.ts +64 -0
- package/src/lib/data/analytics/analytics-provider.d.ts +9 -0
- package/src/lib/data/analytics/analytics-value.d.ts +5 -0
- package/src/lib/data/analytics/index.d.ts +1 -0
- package/src/lib/evolution/runtime-capability.d.ts +1 -0
- package/src/lib/project-pipeline/adapters.d.ts +9 -2
- package/src/lib/project-pipeline/registry.d.ts +59 -48
- package/src/lib/project-task/acceptance.d.ts +13 -1
- package/src/lib/project-task/index.d.ts +4 -2
- package/src/lib/runtime/capabilities/project-configuration.d.ts +2 -0
- package/src/lib/view-extension/index.d.ts +1 -0
- package/src/lib/view-extension/provider.interface.d.ts +51 -0
- package/src/lib/view-extension/workbench-decision.d.ts +10 -0
- package/src/remote-component.d.ts +13 -0
package/index.esm.js
CHANGED
|
@@ -2,8 +2,8 @@ import { Module, applyDecorators, SetMetadata, HttpException, HttpStatus, BadReq
|
|
|
2
2
|
import { MODULE_METADATA } from '@nestjs/common/constants.js';
|
|
3
3
|
import { pick } from 'lodash-es';
|
|
4
4
|
import { dispatchCustomEvent } from '@langchain/core/callbacks/dispatch';
|
|
5
|
-
import { ChatMessageEventTypeEnum, createResourceCardContent, LanguagesEnum, parseAnalyticsDiagnostic, ParameterType, AiModelTypeEnum, PriceType, FetchFrom, ModelPropertyKey, readModelConfiguration, ModelFeature, isDiscoverableModelType, configurationFromModel, SecretTokenBindingType, projectTaskExecutionContextSchema, projectTaskExecutionReferenceSchema, agentRuntimeProgressSchema, agentInvocationTerminalStatusSchema, projectPipelineWorkContextSchema, WorkflowNodeTypeEnum, iconDefinitionSchema, MCP_REQUIRED_CONTEXTS, MCP_CAPABILITY_APPROVAL_MODES, MCP_TOOL_RISKS, MCP_TOOL_SIDE_EFFECTS, MCP_TOOL_IDEMPOTENCY, MCP_CAPABILITY_VISIBILITIES, PLUGIN_COMPONENT_TYPE, projectPipelineContributionSchema, projectPipelineRefSchema } from '@xpert-ai/contracts';
|
|
6
|
-
export { ASSISTANT_CHAT_SEND_MESSAGE_COMMAND, ASSISTANT_CONTEXT_SET_COMMAND, agentOutputDeliverySchema, agentResultPathSchema, configurationFromModel, createResourceCardContent, parseResourceCard, projectPipelineContributionSchema, resourceCardId } from '@xpert-ai/contracts';
|
|
5
|
+
import { ChatMessageEventTypeEnum, createResourceCardContent, LanguagesEnum, parseAnalyticsDiagnostic, ParameterType, AiModelTypeEnum, PriceType, FetchFrom, ModelPropertyKey, readModelConfiguration, ModelFeature, isDiscoverableModelType, configurationFromModel, SecretTokenBindingType, projectTaskExecutionContextSchema, projectTaskExecutionReferenceSchema, agentRuntimeProgressSchema, agentInvocationTerminalStatusSchema, projectPipelineWorkContextSchema, WorkflowNodeTypeEnum, iconDefinitionSchema, MCP_REQUIRED_CONTEXTS, MCP_CAPABILITY_APPROVAL_MODES, MCP_TOOL_RISKS, MCP_TOOL_SIDE_EFFECTS, MCP_TOOL_IDEMPOTENCY, MCP_CAPABILITY_VISIBILITIES, PLUGIN_COMPONENT_TYPE, projectPipelineContributionSchema, projectPipelineRefSchema, pluginAgentEventSchema, agentEventDecisionSchema } from '@xpert-ai/contracts';
|
|
6
|
+
export { ASSISTANT_CHAT_SEND_MESSAGE_COMMAND, ASSISTANT_CONTEXT_SET_COMMAND, agentDeliveryRecoverySchema, agentEventDecisionSchema, agentEventRefSchema, agentOutputDeliverySchema, agentResultPathSchema, configurationFromModel, createResourceCardContent, humanDecisionInputSchema, humanDecisionSchema, parseResourceCard, pluginAgentEventSchema, projectPipelineContributionSchema, resourceCardId } from '@xpert-ai/contracts';
|
|
7
7
|
import { DiscoveryService, Reflector } from '@nestjs/core';
|
|
8
8
|
import { Subject, filter } from 'rxjs';
|
|
9
9
|
import { _ as _extends } from './_extends.esm.js';
|
|
@@ -29,7 +29,7 @@ import Ajv from 'ajv';
|
|
|
29
29
|
import schemaDraft04 from 'ajv/dist/refs/json-schema-draft-06.json';
|
|
30
30
|
import * as _axios from 'axios';
|
|
31
31
|
export { DataSourceRuntimeCapability } from './data-workbench.esm.js';
|
|
32
|
-
export {
|
|
32
|
+
export { c as analyticsBindingObjectSchema, d as analyticsBindingSchema, a as analyticsCertificationSchema, e as analyticsControlsSchema, f as analyticsDiscoveryRequestObjectSchema, g as analyticsDiscoveryRequestSchema, h as analyticsDiscoveryResultSchema, b as analyticsFieldSchema, j as analyticsOptionsSchema, k as analyticsParameterSchema, l as analyticsQueryRequestSchema, m as analyticsSourceKey, n as analyticsSourceRefSchema, o as normalizeAnalyticsResult, p as parseAnalyticsCertification, r as resolveAnalyticsParameters, v as validateAnalyticsBinding } from './analytics-result.esm.js';
|
|
33
33
|
import { BaseCallbackHandler } from '@langchain/core/callbacks/base';
|
|
34
34
|
import { ChatGenerationChunk } from '@langchain/core/outputs';
|
|
35
35
|
import { isBaseMessage, isAIMessage, isAIMessageChunk, AIMessage } from '@langchain/core/messages';
|
|
@@ -40,12 +40,12 @@ import { getEnvironmentVariable } from '@langchain/core/utils/env';
|
|
|
40
40
|
export { ModelProviderHttpClient, ModelProviderHttpError } from './model-provider-http-client.esm.js';
|
|
41
41
|
import { getEncodingNameForModel, encodingForModel, getEncoding } from 'js-tiktoken';
|
|
42
42
|
import { z as z$1 } from 'zod';
|
|
43
|
-
export { A as
|
|
43
|
+
export { A as AGENT_TASK_REPORT_MAX_BYTES, a as AGENT_TASK_RESULTS_FEATURE, b as agentResultItemSchema } from './results.esm.js';
|
|
44
44
|
import { assertConnectorDefinition } from './connector.esm.js';
|
|
45
45
|
export { CONNECTOR_AUTHORIZATION_MODES, CONNECTOR_SCOPE_TYPES, getConnectorAuthMethods, getConnectorAuthorizationModes } from './connector.esm.js';
|
|
46
46
|
import { isAbsolute, relative, resolve, sep } from 'node:path';
|
|
47
47
|
import { _ as _object_without_properties_loose$2 } from './_object_without_properties_loose.esm.js';
|
|
48
|
-
export { base64ToBytes, bytesToBase64, createCollaborationClient, createCollaborationPresenceStore, createSocketIoTransportAdapter, createYjsDocumentAdapter } from './collaboration-client.esm.js';
|
|
48
|
+
export { base64ToBytes, bytesToBase64, createCollaborationClient, createCollaborationPresenceStore, createOperationCollaborationClient, createSocketIoTransportAdapter, createYjsDocumentAdapter, parseCollaborationPresence } from './collaboration-client.esm.js';
|
|
49
49
|
import { createHash } from 'crypto';
|
|
50
50
|
import { tool } from '@langchain/core/tools';
|
|
51
51
|
|
|
@@ -4779,11 +4779,11 @@ while True:
|
|
|
4779
4779
|
function middleware(node) {
|
|
4780
4780
|
return node.type === 'workflow' && node.entity.type === WorkflowNodeTypeEnum.MIDDLEWARE;
|
|
4781
4781
|
}
|
|
4782
|
-
function hasAssistantMiddleware(draft, provider)
|
|
4783
|
-
|
|
4784
|
-
|
|
4785
|
-
|
|
4786
|
-
|
|
4782
|
+
function hasAssistantMiddleware(draft, provider, agentKey = (()=>{
|
|
4783
|
+
var _draft_team_agent;
|
|
4784
|
+
return (_draft_team_agent = draft.team.agent) == null ? void 0 : _draft_team_agent.key;
|
|
4785
|
+
})()) {
|
|
4786
|
+
return draft.nodes.some((node)=>middleware(node) && node.entity.provider === provider && draft.connections.some((edge)=>edge.type === 'workflow' && edge.from === agentKey && edge.to.split('/')[0] === node.key));
|
|
4787
4787
|
}
|
|
4788
4788
|
/** Compose only the draft graph. The platform records the contribution for safe removal.
|
|
4789
4789
|
* No Project, permission, external resource or implicit replacement is created here. */ function applyAssistantMiddleware(draft, input) {
|
|
@@ -4823,8 +4823,9 @@ function hasAssistantMiddleware(draft, provider) {
|
|
|
4823
4823
|
required: true
|
|
4824
4824
|
});
|
|
4825
4825
|
var _agent_entity_options_middlewares_order;
|
|
4826
|
-
agent.entity.options = _extends({}, agent.entity.options, {
|
|
4827
|
-
parallelToolCalls: false
|
|
4826
|
+
agent.entity.options = _extends({}, agent.entity.options, input.preserveToolConcurrency ? {} : {
|
|
4827
|
+
parallelToolCalls: false
|
|
4828
|
+
}, {
|
|
4828
4829
|
middlewares: _extends({}, (_agent_entity_options = agent.entity.options) == null ? void 0 : _agent_entity_options.middlewares, {
|
|
4829
4830
|
order: [
|
|
4830
4831
|
...(_agent_entity_options_middlewares_order = (_agent_entity_options1 = agent.entity.options) == null ? void 0 : (_agent_entity_options_middlewares = _agent_entity_options1.middlewares) == null ? void 0 : _agent_entity_options_middlewares.order) != null ? _agent_entity_options_middlewares_order : [],
|
|
@@ -6885,6 +6886,13 @@ const ViewMiddlewareRuntimeCapability = createRuntimeCapability('platform.view.m
|
|
|
6885
6886
|
description: 'Resolve a View capability through its authorized Assistant middleware and scoped runtime.'
|
|
6886
6887
|
});
|
|
6887
6888
|
|
|
6889
|
+
/**
|
|
6890
|
+
* Lets a plugin's server-side View provider submit a human decision during an authorized
|
|
6891
|
+
* assistant or project workbench action. The host takes the actor and plugin identity from
|
|
6892
|
+
* the current action and routes the submission to their active source binding.
|
|
6893
|
+
* The event source checks who can decide the business matter and records the choice.
|
|
6894
|
+
*/ const WorkbenchDecisionCapability = createRuntimeCapability('platform.view.workbench-decision');
|
|
6895
|
+
|
|
6888
6896
|
const ARTIFACT_PRESENTATION_PROVIDER = 'ARTIFACT_PRESENTATION_PROVIDER';
|
|
6889
6897
|
const artifactPresentationKey = (source)=>`${source.pluginName}:${source.resourceType}`;
|
|
6890
6898
|
/** Registers a read-only renderer for an explicit Artifact source, independently of Workbench actions. */ const ArtifactPresentationProvider = (source)=>applyDecorators(SetMetadata(ARTIFACT_PRESENTATION_PROVIDER, artifactPresentationKey(source)), SetMetadata(STRATEGY_META_KEY, ARTIFACT_PRESENTATION_PROVIDER));
|
|
@@ -7177,6 +7185,9 @@ EvolutionTargetProviderRegistry = __decorate([
|
|
|
7177
7185
|
], EvolutionTargetProviderRegistry);
|
|
7178
7186
|
|
|
7179
7187
|
const EVOLUTION_RUNTIME_SERVICE_TOKEN = 'XPERT_EVOLUTION_RUNTIME_SERVICE';
|
|
7188
|
+
const ExecutionReviewRuntimeCapability = createRuntimeCapability('platform.agent-evolution.execution-review', {
|
|
7189
|
+
description: 'Human review of executions within the authorized project and Assistant.'
|
|
7190
|
+
});
|
|
7180
7191
|
/** Capability for inspecting and publishing source baselines within an authorized organization. */ const EvolutionBaselineRuntimeCapability = createRuntimeCapability('platform.agent-evolution.baselines', {
|
|
7181
7192
|
description: 'Inspect and initialize organization rule baselines with administrator authorization and revision checks.'
|
|
7182
7193
|
});
|
|
@@ -11401,4 +11412,178 @@ Reflect.defineMetadata('__command__', {
|
|
|
11401
11412
|
id: ImportDefaultAgentPluginsCommand.type
|
|
11402
11413
|
}, ImportDefaultAgentPluginsCommand);
|
|
11403
11414
|
|
|
11404
|
-
export { ACCOUNT_BINDING_PERMISSION_SERVICE_TOKEN, AGENT_CHAT_DISPATCH_ERROR_STEER_TARGET_NOT_RUNNING, AGENT_CHAT_DISPATCH_MESSAGE_TYPE, AGENT_MIDDLEWARE_STRATEGY, AGENT_PROCESS_SUPERVISOR, AGENT_RUNTIME_EVENT_MESSAGE_TYPE, AGENT_RUNTIME_STRATEGY, AIModel, AIModelProviderNotFoundException, AIModelProviderRegistry, AIModelProviderStrategy, AI_MODEL_PROVIDER, ANALYTICS_PROVIDER, ARTIFACT_PRESENTATION_PROVIDER, ARTIFACT_TYPE_PROVIDER, ASSISTANT_CAPABILITY_PROVIDER, AdapterDataSourceStrategy, AgentExecutionRunnerCapability, AgentExecutionRunnerFactoryCapability, AgentInvocationRuntimeCapability, AgentMiddlewareRegistry, AgentMiddlewareStrategy, AgentRuntimeDeploymentCapability, AgentRuntimeFactoryCapability, AgentRuntimeRegistry, AgentRuntimeStrategy, AiModelNotFoundException, AnalyticsDefinitionAuthoringCapability, AnalyticsProvider, AnalyticsProviderError, AnalyticsProviderRegistry, AnalyticsRuntimeCapability, ArtifactPresentationProvider, ArtifactPresentationRegistry, ArtifactTypeProvider, ArtifactTypeRegistry, AssistantCapabilityProvider, AssistantCapabilityProviderRegistry, AssistantTaskRuntimeCapability, BOUND_IDENTITY_LOGIN_PERMISSION_SERVICE_TOKEN, BUILTIN_GLOBAL_SCOPE, BaseHTTPQueryRunner, BaseQueryRunner, BaseSQLQueryRunner, BaseSandbox, BaseStrategyRegistry, BuiltinToolset, CHAT_CHANNEL, CHAT_CHANNEL_TEXT_LIMITS, CLI_MODEL_TOKEN_REFERENCE, COLLABORATION_DOCUMENT_PROVIDER, CONNECTION_COMMAND_ROUTER_TOKEN, CONNECTOR_STRATEGY, CONTENT_RESOURCE_PROVIDER, CancelConversationCommand, ChatChannel, ChatChannelRegistry, ChatOAICompatReasoningModel, CliModelProfilesCapability, CollaborationDocumentProvider, CollaborationDocumentProviderRegistry, CollaborationRuntimeCapability, CommonParameterRules, ConnectorDocumentsRuntimeCapability, ConnectorRuntimeCapability, ConnectorRuntimeFactoryCapability, ConnectorStrategyKey, ConnectorStrategyRegistry, ContentDocumentsRuntimeCapability, ContentEditorProvider, ContentEditorRegistry, ContentEditorsRuntimeCapability, ContentReferencesRuntimeCapability, ContentResourceProvider, ContentResourceProviderRegistry, ContentResourcesRuntimeCapability, 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, EvolutionBaselineRuntimeCapability, EvolutionChangeRuntimeCapability, EvolutionRuntimeCapability, EvolutionTargetProviderRegistry, EvolutionTargetProviderStrategy, ExecutionObservabilityRuntimeCapability, FILE_ARTIFACT_TYPE, 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, ImportDefaultAgentPluginsCommand, IntegrationStrategyKey, IntegrationStrategyRegistry, JUMP_TO_TARGETS, JsonSchemaValidator, KEYWORD_ANALYZER_STRATEGY, KNOWLEDGE_STRATEGY, KeywordAnalyzerRegistry, KeywordAnalyzerStrategy, KnowledgeDocumentVisualAssetsRuntimeCapability, KnowledgeDocumentVisualAssetsRuntimeFactoryCapability, KnowledgeGraphRuntimeCapability, KnowledgeStrategyKey, KnowledgeStrategyRegistry, KnowledgebaseDocumentsRuntimeCapability, KnowledgebaseProvisioningRuntimeCapability, KnowledgebaseRuntimeCapability, LLMUsage, LargeLanguageModel, ListAnalyticsSourcesCommand, MANAGED_CONNECTION_REGISTRY_TOKEN, MANAGED_QUEUE_HANDLER_REGISTRY_TOKEN, MANAGED_QUEUE_SERVICE_TOKEN, MCP_CAPABILITY_CHANGE_EVENT_TYPES, MODEL_OUTPUT_VALIDATION_ERROR_CODE, ModelExecutionEnvironmentCapability, ModelOutputValidationError, ModelProvider, ORGANIZATION_METADATA_KEY, OpenAICompatibleEmbeddings, 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, PROJECT_PIPELINE_CONTRIBUTION, PROJECT_PIPELINE_PROJECTION_PROVIDER, PROJECT_PIPELINE_RUNTIME_ADAPTER, PROJECT_TASK_PROVIDER, PROJECT_TYPE_PROVIDER, 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, ProjectPipelineAnalyticsRuntimeCapability, ProjectPipelineCatalogRuntimeCapability, ProjectPipelineCommandsRuntimeCapability, ProjectPipelineConfigurationRuntimeCapability, ProjectPipelineContributionRegistry, ProjectPipelineContributor, ProjectPipelineEvidenceRuntimeCapability, ProjectPipelinePortfolioRuntimeCapability, ProjectPipelineProjectionProvider, ProjectPipelineProjectionProviderRegistry, ProjectPipelineProviderActionsRuntimeCapability, ProjectPipelineRuntimeAdapterProvider, ProjectPipelineRuntimeAdapterRegistry, ProjectPipelinesRuntimeCapability, ProjectTaskProvider, ProjectTaskProviderRegistry, ProjectTasksRuntimeCapability, ProjectTypeProvider, ProjectTypeProviderRegistry, RESOURCE_CARD_EVENT, RESOURCE_CARD_PROVIDER, RETRIEVER_STRATEGY, RequestContext, RequestContextMiddleware, RequirePermissionOperation, RerankModel, ResolveAnalyticsSourceCommand, ResolveConnectorIntegrationQuery, ResourceCardProvider, ResourceCardProviderRegistry, 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, ShellModelExecutionSourceCapability, 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, ViewMiddlewareRuntimeCapability, WORKFLOW_NODE_STRATEGY, WORKFLOW_TRIGGER_STRATEGY, WorkflowNodeRegistry, WorkflowNodeStrategy, WorkflowTriggerRegistry, WorkflowTriggerStrategy, WorkspaceFilesRuntimeCapability, WrapWorkflowNodeExecutionCommand, XPERT_AGENT_MIDDLEWARE_RUNTIME_TOKEN, XPERT_TOOL_METHOD_METADATA, XPERT_TOOL_PROVIDER, XPERT_TOOL_PROVIDER_METADATA, XPERT_TOOL_RESULT_FORMAT_VERSION, XpFileSystem, XpertPrompt, XpertResource, XpertResourceTemplate, XpertServerPlugin, XpertTool, XpertToolProvider, XpertToolProviderCoordinator, XpertToolProviderRegistry, agentInvocationDispatchContextSchema, agentRuntimeConsumptionStateSchema, agentRuntimeDeliveryStateSchema, agentRuntimeDeploymentSpecSchema, agentRuntimeEventMessageId, agentRuntimeEventSchema, agentRuntimeReplyTargetSchema, agentRuntimeResultClaimSchema, agentRuntimeResultConsumptionKey, als, appendSandboxMessage, applyAssistantMiddleware, applyModelConfiguration, applyModelContextSize, artifactPresentationKey, artifactTypeKey, assertConnectorDefinition, assertXpertToolProviderClaims, buildSandboxTimeoutMessage, calcTokenUsage, calculateLLMUsagePrice, calculateModelPrice, calculateModelUsageCharge, canonicalEvolutionJson, chunkText, countTextTokens, countTokensSafe, createI18nInstance, createMutationEvidence, createPluginLogger, createRuntimeCapability, defineAgentMessageType, defineChannelMessageType, defineMcpApp, defineMcpCapabilities, defineMcpPrompt, defineMcpResource, defineMcpResourceTemplate, defineXpertTool, derivePluginArtifactNamespace, describeXpertToolProvider, discoverOpenAIModels, downloadRemoteFile, emitResourceCard, formatSandboxTimeout, getDefaultTenantId, getErrorMessage, getModelContextSize, getPermissionOperationMetadata, getPositionList, getPositionMap, getRequestContext, getRequiredPermissionOperation, getTenantGlobalScopeKey, getXpertToolMethod, hasAssistantMiddleware, hashEvolutionValue, isAgentInvocationTerminal, isDevelopmentSandboxRuntimeEnvironment, isExecutionObservationSession, isFileContentEditor, isModelOutputValidationError, isModelUsagePricingConfig, isPluginArtifactNamespace, isRemoteFile, isResourceContentEditor, isSandboxBackend, isSandboxManagedServiceAdapter, isSandboxServiceProxyAdapter, isSandboxTerminalAdapter, isStrategyInstance, isStructuredMessageType, isTenantGlobalScopeKey, isTextContentEditor, jsonEncodedSchema, knowledgebaseActions, loadYamlFile, managedAgentRuntimeSchema, mergeCredentials, mergeModelRequirements, mergeParentChildChunks, nativeModelTransport, normalizeContextSize, normalizeTokenUsage, pluginArtifactTableName, prepareToolResult, processAsyncAIGCManagedJob, projectPipelineInvocationScopeSchema, readAnalyticsProviderDiagnostic, renderRemoteModuleIframeHtml, renderRemoteReactIframeHtml, renderRemoteVueIframeHtml, resolveModelUsagePricingSnapshot, resolveSandboxBackend, resolveSandboxExecutionOptions, resolveSandboxManagedServiceAdapter, resolveSandboxServiceProxyAdapter, resolveSandboxTerminalAdapter, resolveStrategyMetadataTarget, resolveTenantGlobalScopeKey, resolveTokenUsage, resolveTokenUsageCandidates, resolveXpertMcpExtensions, runWithRequestContext, runtimeToolProviderComponent, secondsToMilliseconds, setDefaultTenantId, sumTokenUsage, supportsContentModel, taskWaitReason, textTokenBoundaries, validateAnalyticsPayload };
|
|
11415
|
+
function agentEventDigest(value) {
|
|
11416
|
+
const sorted = JSON.stringify(value, (_key, item)=>{
|
|
11417
|
+
if (item && typeof item === 'object' && !Array.isArray(item)) return Object.fromEntries(Object.entries(item).sort(([a], [b])=>a < b ? -1 : a > b ? 1 : 0));
|
|
11418
|
+
return item;
|
|
11419
|
+
});
|
|
11420
|
+
return createHash$1('sha256').update(sorted).digest('hex');
|
|
11421
|
+
}
|
|
11422
|
+
/** PostgreSQL source journal scoped to one plugin's own route and fact tables. */ class PluginEventJournal {
|
|
11423
|
+
async lock(tx, origin) {
|
|
11424
|
+
await tx.query('SELECT pg_advisory_xact_lock(hashtextextended($1,0))', [
|
|
11425
|
+
JSON.stringify([
|
|
11426
|
+
this.routes,
|
|
11427
|
+
origin.tenantId,
|
|
11428
|
+
origin.organizationId,
|
|
11429
|
+
origin.ref
|
|
11430
|
+
])
|
|
11431
|
+
]);
|
|
11432
|
+
}
|
|
11433
|
+
async configure(tx, ctx, enabled) {
|
|
11434
|
+
const origin = {
|
|
11435
|
+
tenantId: ctx.tenantId,
|
|
11436
|
+
organizationId: ctx.organizationId,
|
|
11437
|
+
ref: ctx.sourceBindingRef
|
|
11438
|
+
};
|
|
11439
|
+
await this.lock(tx, origin);
|
|
11440
|
+
const [route] = await tx.query(`SELECT * FROM ${this.routes} WHERE tenant=$1 AND org=$2 AND ref=$3`, [
|
|
11441
|
+
origin.tenantId,
|
|
11442
|
+
origin.organizationId,
|
|
11443
|
+
origin.ref
|
|
11444
|
+
]);
|
|
11445
|
+
if (route && (route.binding !== ctx.bindingId || route.revision > ctx.bindingRevision)) throw new Error('source_binding_changed');
|
|
11446
|
+
await tx.query(`INSERT INTO ${this.routes}(binding,tenant,org,ref,revision,enabled) VALUES($1,$2,$3,$4,$5,$6)
|
|
11447
|
+
ON CONFLICT(binding) DO UPDATE SET revision=EXCLUDED.revision,enabled=EXCLUDED.enabled`, [
|
|
11448
|
+
ctx.bindingId,
|
|
11449
|
+
ctx.tenantId,
|
|
11450
|
+
ctx.organizationId,
|
|
11451
|
+
ctx.sourceBindingRef,
|
|
11452
|
+
ctx.bindingRevision,
|
|
11453
|
+
enabled
|
|
11454
|
+
]);
|
|
11455
|
+
}
|
|
11456
|
+
async route(tx, origin) {
|
|
11457
|
+
await this.lock(tx, origin);
|
|
11458
|
+
const [route] = await tx.query(`SELECT * FROM ${this.routes} WHERE tenant=$1 AND org=$2 AND ref=$3`, [
|
|
11459
|
+
origin.tenantId,
|
|
11460
|
+
origin.organizationId,
|
|
11461
|
+
origin.ref
|
|
11462
|
+
]);
|
|
11463
|
+
return route;
|
|
11464
|
+
}
|
|
11465
|
+
async capture(tx, route, data, snapshot, factKey, revision) {
|
|
11466
|
+
const event = pluginAgentEventSchema.parse(_extends({}, data, {
|
|
11467
|
+
bindingRevision: route.revision,
|
|
11468
|
+
fact: {
|
|
11469
|
+
key: factKey,
|
|
11470
|
+
revision,
|
|
11471
|
+
sha256: agentEventDigest(snapshot)
|
|
11472
|
+
}
|
|
11473
|
+
}));
|
|
11474
|
+
const [existing] = await tx.query(`SELECT event FROM ${this.facts} WHERE binding=$1 AND source=$2`, [
|
|
11475
|
+
route.binding,
|
|
11476
|
+
event.sourceEventId
|
|
11477
|
+
]);
|
|
11478
|
+
if (existing) {
|
|
11479
|
+
if (existing.event.type !== event.type || existing.event.schemaVersion !== event.schemaVersion || existing.event.fact.key !== event.fact.key || existing.event.fact.revision !== event.fact.revision || existing.event.fact.sha256 !== event.fact.sha256 || existing.event.subject.key !== event.subject.key || existing.event.subject.kind !== event.subject.kind) throw new Error('event_source_conflict');
|
|
11480
|
+
return true;
|
|
11481
|
+
}
|
|
11482
|
+
if (!route.enabled) return false;
|
|
11483
|
+
await tx.query(`INSERT INTO ${this.facts}(id,binding,source,event,snapshot) VALUES($1,$2,$3,$4,$5)`, [
|
|
11484
|
+
randomUUID(),
|
|
11485
|
+
route.binding,
|
|
11486
|
+
event.sourceEventId,
|
|
11487
|
+
event,
|
|
11488
|
+
JSON.stringify(snapshot)
|
|
11489
|
+
]);
|
|
11490
|
+
return true;
|
|
11491
|
+
}
|
|
11492
|
+
async drain(db, ctx, publisher, limit) {
|
|
11493
|
+
const scope = [
|
|
11494
|
+
ctx.bindingId,
|
|
11495
|
+
ctx.tenantId,
|
|
11496
|
+
ctx.organizationId,
|
|
11497
|
+
ctx.sourceBindingRef,
|
|
11498
|
+
ctx.bindingRevision
|
|
11499
|
+
];
|
|
11500
|
+
// The current worker may reconcile older facts (including a lost receipt ACK), never a later revision.
|
|
11501
|
+
const routeScope = 'r.binding=$1 AND r.tenant=$2 AND r.org=$3 AND r.ref=$4 AND r.revision=$5';
|
|
11502
|
+
const facts = await db.query(`SELECT f.id,f.event FROM ${this.facts} f JOIN ${this.routes} r USING(binding)
|
|
11503
|
+
WHERE ${routeScope} AND (f.event->>'bindingRevision')::numeric <= r.revision AND f.receipt IS NULL
|
|
11504
|
+
AND (f.error IS NULL OR (f.error='binding_changed' AND f.event->>'bindingRevision'=r.revision::text))
|
|
11505
|
+
ORDER BY f.seq LIMIT $6`, [
|
|
11506
|
+
...scope,
|
|
11507
|
+
limit
|
|
11508
|
+
]);
|
|
11509
|
+
for (const fact of facts){
|
|
11510
|
+
ctx.signal.throwIfAborted();
|
|
11511
|
+
const result = await publisher.publish(fact.event);
|
|
11512
|
+
if (result.status === 'rejected') {
|
|
11513
|
+
// The host may already have advanced or may still be enabling this revision.
|
|
11514
|
+
if (result.code === 'binding_changed' && fact.event.bindingRevision === ctx.bindingRevision) return {
|
|
11515
|
+
more: false
|
|
11516
|
+
};
|
|
11517
|
+
await db.query(`WITH current_route AS (SELECT r.binding FROM ${this.routes} r WHERE ${routeScope} FOR SHARE)
|
|
11518
|
+
UPDATE ${this.facts} f SET error=$7 FROM current_route r
|
|
11519
|
+
WHERE f.binding=r.binding AND f.id=$6 AND f.receipt IS NULL`, [
|
|
11520
|
+
...scope,
|
|
11521
|
+
fact.id,
|
|
11522
|
+
result.code
|
|
11523
|
+
]);
|
|
11524
|
+
} else {
|
|
11525
|
+
// A committed host receipt remains authoritative even if the route changed while awaiting its ACK.
|
|
11526
|
+
await db.query(`UPDATE ${this.facts} SET receipt=$2,error=NULL WHERE id=$1 AND binding=$3 AND (receipt IS NULL OR receipt=$2)`, [
|
|
11527
|
+
fact.id,
|
|
11528
|
+
result.receiptId,
|
|
11529
|
+
ctx.bindingId
|
|
11530
|
+
]);
|
|
11531
|
+
}
|
|
11532
|
+
}
|
|
11533
|
+
return {
|
|
11534
|
+
more: facts.length === limit
|
|
11535
|
+
};
|
|
11536
|
+
}
|
|
11537
|
+
async decide(tx, ctx, delivery, apply) {
|
|
11538
|
+
const [fact] = await tx.query(`SELECT f.* FROM ${this.facts} f JOIN ${this.routes} r USING(binding)
|
|
11539
|
+
WHERE r.binding=$1 AND r.tenant=$2 AND r.org=$3 AND r.ref=$4 AND r.revision=$5 AND f.source=$6
|
|
11540
|
+
FOR SHARE OF r FOR UPDATE OF f`, [
|
|
11541
|
+
ctx.bindingId,
|
|
11542
|
+
ctx.tenantId,
|
|
11543
|
+
ctx.organizationId,
|
|
11544
|
+
ctx.sourceBindingRef,
|
|
11545
|
+
ctx.bindingRevision,
|
|
11546
|
+
delivery.event.sourceEventId
|
|
11547
|
+
]);
|
|
11548
|
+
if (!fact || fact.event.bindingRevision !== ctx.bindingRevision || agentEventDigest(fact.event) !== agentEventDigest(delivery.event) || agentEventDigest(fact.snapshot) !== delivery.event.fact.sha256 || fact.receipt && fact.receipt !== delivery.receiptId) return {
|
|
11549
|
+
status: 'blocked',
|
|
11550
|
+
reasonCode: 'source_binding_changed'
|
|
11551
|
+
};
|
|
11552
|
+
if (fact.decision) return agentEventDecisionSchema.parse(fact.decision);
|
|
11553
|
+
const partition = JSON.stringify([
|
|
11554
|
+
ctx.bindingId,
|
|
11555
|
+
delivery.event.subject.kind,
|
|
11556
|
+
delivery.event.subject.key
|
|
11557
|
+
]);
|
|
11558
|
+
await tx.query('SELECT pg_advisory_xact_lock(hashtextextended($1,0))', [
|
|
11559
|
+
partition
|
|
11560
|
+
]);
|
|
11561
|
+
const [newer] = await tx.query(`SELECT EXISTS(SELECT 1 FROM ${this.facts} WHERE binding=$1
|
|
11562
|
+
AND event->'subject'=$2::jsonb AND fence>$3::bigint) AS exists`, [
|
|
11563
|
+
ctx.bindingId,
|
|
11564
|
+
JSON.stringify(delivery.event.subject),
|
|
11565
|
+
delivery.fence
|
|
11566
|
+
]);
|
|
11567
|
+
if (newer.exists) throw new Error('stale_event_fence');
|
|
11568
|
+
ctx.signal.throwIfAborted();
|
|
11569
|
+
const result = agentEventDecisionSchema.parse(await apply(fact.snapshot));
|
|
11570
|
+
ctx.signal.throwIfAborted();
|
|
11571
|
+
await tx.query(`UPDATE ${this.facts} SET decision=$2,receipt=$3,fence=$4 WHERE id=$1`, [
|
|
11572
|
+
fact.id,
|
|
11573
|
+
result,
|
|
11574
|
+
delivery.receiptId,
|
|
11575
|
+
delivery.fence
|
|
11576
|
+
]);
|
|
11577
|
+
return result;
|
|
11578
|
+
}
|
|
11579
|
+
constructor(prefix){
|
|
11580
|
+
if (!/^[a-z][a-z0-9_]{1,45}$/.test(prefix)) throw new Error('invalid_event_journal_prefix');
|
|
11581
|
+
this.routes = prefix + '_route';
|
|
11582
|
+
this.facts = prefix + '_fact';
|
|
11583
|
+
}
|
|
11584
|
+
}
|
|
11585
|
+
|
|
11586
|
+
const AGENT_EVENT_SOURCE = 'XPERT_AGENT_EVENT_SOURCE_V1';
|
|
11587
|
+
const AgentEventSourceStrategy = (key)=>applyDecorators(SetMetadata(AGENT_EVENT_SOURCE, key), SetMetadata(STRATEGY_META_KEY, AGENT_EVENT_SOURCE));
|
|
11588
|
+
|
|
11589
|
+
export { ACCOUNT_BINDING_PERMISSION_SERVICE_TOKEN, AGENT_CHAT_DISPATCH_ERROR_STEER_TARGET_NOT_RUNNING, AGENT_CHAT_DISPATCH_MESSAGE_TYPE, AGENT_EVENT_SOURCE, AGENT_MIDDLEWARE_STRATEGY, AGENT_PROCESS_SUPERVISOR, AGENT_RUNTIME_EVENT_MESSAGE_TYPE, AGENT_RUNTIME_STRATEGY, AIModel, AIModelProviderNotFoundException, AIModelProviderRegistry, AIModelProviderStrategy, AI_MODEL_PROVIDER, ANALYTICS_PROVIDER, ARTIFACT_PRESENTATION_PROVIDER, ARTIFACT_TYPE_PROVIDER, ASSISTANT_CAPABILITY_PROVIDER, AdapterDataSourceStrategy, AgentEventSourceStrategy, AgentExecutionRunnerCapability, AgentExecutionRunnerFactoryCapability, AgentInvocationRuntimeCapability, AgentMiddlewareRegistry, AgentMiddlewareStrategy, AgentRuntimeDeploymentCapability, AgentRuntimeFactoryCapability, AgentRuntimeRegistry, AgentRuntimeStrategy, AiModelNotFoundException, AnalyticsDefinitionAuthoringCapability, AnalyticsProvider, AnalyticsProviderError, AnalyticsProviderRegistry, AnalyticsRuntimeCapability, ArtifactPresentationProvider, ArtifactPresentationRegistry, ArtifactTypeProvider, ArtifactTypeRegistry, AssistantCapabilityProvider, AssistantCapabilityProviderRegistry, AssistantTaskRuntimeCapability, BOUND_IDENTITY_LOGIN_PERMISSION_SERVICE_TOKEN, BUILTIN_GLOBAL_SCOPE, BaseHTTPQueryRunner, BaseQueryRunner, BaseSQLQueryRunner, BaseSandbox, BaseStrategyRegistry, BuiltinToolset, CHAT_CHANNEL, CHAT_CHANNEL_TEXT_LIMITS, CLI_MODEL_TOKEN_REFERENCE, COLLABORATION_DOCUMENT_PROVIDER, CONNECTION_COMMAND_ROUTER_TOKEN, CONNECTOR_STRATEGY, CONTENT_RESOURCE_PROVIDER, CancelConversationCommand, ChatChannel, ChatChannelRegistry, ChatOAICompatReasoningModel, CliModelProfilesCapability, CollaborationDocumentProvider, CollaborationDocumentProviderRegistry, CollaborationRuntimeCapability, CommonParameterRules, ConnectorDocumentsRuntimeCapability, ConnectorRuntimeCapability, ConnectorRuntimeFactoryCapability, ConnectorStrategyKey, ConnectorStrategyRegistry, ContentDocumentsRuntimeCapability, ContentEditorProvider, ContentEditorRegistry, ContentEditorsRuntimeCapability, ContentReferencesRuntimeCapability, ContentResourceProvider, ContentResourceProviderRegistry, ContentResourcesRuntimeCapability, 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, EvolutionBaselineRuntimeCapability, EvolutionChangeRuntimeCapability, EvolutionRuntimeCapability, EvolutionTargetProviderRegistry, EvolutionTargetProviderStrategy, ExecutionObservabilityRuntimeCapability, ExecutionReviewRuntimeCapability, FILE_ARTIFACT_TYPE, 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, ImportDefaultAgentPluginsCommand, IntegrationStrategyKey, IntegrationStrategyRegistry, JUMP_TO_TARGETS, JsonSchemaValidator, KEYWORD_ANALYZER_STRATEGY, KNOWLEDGE_STRATEGY, KeywordAnalyzerRegistry, KeywordAnalyzerStrategy, KnowledgeDocumentVisualAssetsRuntimeCapability, KnowledgeDocumentVisualAssetsRuntimeFactoryCapability, KnowledgeGraphRuntimeCapability, KnowledgeStrategyKey, KnowledgeStrategyRegistry, KnowledgebaseDocumentsRuntimeCapability, KnowledgebaseProvisioningRuntimeCapability, KnowledgebaseRuntimeCapability, LLMUsage, LargeLanguageModel, ListAnalyticsSourcesCommand, MANAGED_CONNECTION_REGISTRY_TOKEN, MANAGED_QUEUE_HANDLER_REGISTRY_TOKEN, MANAGED_QUEUE_SERVICE_TOKEN, MCP_CAPABILITY_CHANGE_EVENT_TYPES, MODEL_OUTPUT_VALIDATION_ERROR_CODE, ModelExecutionEnvironmentCapability, ModelOutputValidationError, ModelProvider, ORGANIZATION_METADATA_KEY, OpenAICompatibleEmbeddings, 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, PROJECT_PIPELINE_CONTRIBUTION, PROJECT_PIPELINE_PROJECTION_PROVIDER, PROJECT_PIPELINE_RUNTIME_ADAPTER, PROJECT_TASK_PROVIDER, PROJECT_TYPE_PROVIDER, 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, PluginEventJournal, PluginJobProcessor, PluginWebhookAuth, PluginWebhookAuthGuard, ProjectPipelineAnalyticsRuntimeCapability, ProjectPipelineCatalogRuntimeCapability, ProjectPipelineCommandsRuntimeCapability, ProjectPipelineConfigurationRuntimeCapability, ProjectPipelineContributionRegistry, ProjectPipelineContributor, ProjectPipelineEvidenceRuntimeCapability, ProjectPipelinePortfolioRuntimeCapability, ProjectPipelineProjectionProvider, ProjectPipelineProjectionProviderRegistry, ProjectPipelineProviderActionsRuntimeCapability, ProjectPipelineRuntimeAdapterProvider, ProjectPipelineRuntimeAdapterRegistry, ProjectPipelinesRuntimeCapability, ProjectTaskProvider, ProjectTaskProviderRegistry, ProjectTasksRuntimeCapability, ProjectTypeProvider, ProjectTypeProviderRegistry, RESOURCE_CARD_EVENT, RESOURCE_CARD_PROVIDER, RETRIEVER_STRATEGY, RequestContext, RequestContextMiddleware, RequirePermissionOperation, RerankModel, ResolveAnalyticsSourceCommand, ResolveConnectorIntegrationQuery, ResourceCardProvider, ResourceCardProviderRegistry, 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, ShellModelExecutionSourceCapability, 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, ViewMiddlewareRuntimeCapability, WORKFLOW_NODE_STRATEGY, WORKFLOW_TRIGGER_STRATEGY, WorkbenchDecisionCapability, WorkflowNodeRegistry, WorkflowNodeStrategy, WorkflowTriggerRegistry, WorkflowTriggerStrategy, WorkspaceFilesRuntimeCapability, WrapWorkflowNodeExecutionCommand, XPERT_AGENT_MIDDLEWARE_RUNTIME_TOKEN, XPERT_TOOL_METHOD_METADATA, XPERT_TOOL_PROVIDER, XPERT_TOOL_PROVIDER_METADATA, XPERT_TOOL_RESULT_FORMAT_VERSION, XpFileSystem, XpertPrompt, XpertResource, XpertResourceTemplate, XpertServerPlugin, XpertTool, XpertToolProvider, XpertToolProviderCoordinator, XpertToolProviderRegistry, agentEventDigest, agentInvocationDispatchContextSchema, agentRuntimeConsumptionStateSchema, agentRuntimeDeliveryStateSchema, agentRuntimeDeploymentSpecSchema, agentRuntimeEventMessageId, agentRuntimeEventSchema, agentRuntimeReplyTargetSchema, agentRuntimeResultClaimSchema, agentRuntimeResultConsumptionKey, als, appendSandboxMessage, applyAssistantMiddleware, applyModelConfiguration, applyModelContextSize, artifactPresentationKey, artifactTypeKey, assertConnectorDefinition, assertXpertToolProviderClaims, buildSandboxTimeoutMessage, calcTokenUsage, calculateLLMUsagePrice, calculateModelPrice, calculateModelUsageCharge, canonicalEvolutionJson, chunkText, countTextTokens, countTokensSafe, createI18nInstance, createMutationEvidence, createPluginLogger, createRuntimeCapability, defineAgentMessageType, defineChannelMessageType, defineMcpApp, defineMcpCapabilities, defineMcpPrompt, defineMcpResource, defineMcpResourceTemplate, defineXpertTool, derivePluginArtifactNamespace, describeXpertToolProvider, discoverOpenAIModels, downloadRemoteFile, emitResourceCard, formatSandboxTimeout, getDefaultTenantId, getErrorMessage, getModelContextSize, getPermissionOperationMetadata, getPositionList, getPositionMap, getRequestContext, getRequiredPermissionOperation, getTenantGlobalScopeKey, getXpertToolMethod, hasAssistantMiddleware, hashEvolutionValue, isAgentInvocationTerminal, isDevelopmentSandboxRuntimeEnvironment, isExecutionObservationSession, isFileContentEditor, isModelOutputValidationError, isModelUsagePricingConfig, isPluginArtifactNamespace, isRemoteFile, isResourceContentEditor, isSandboxBackend, isSandboxManagedServiceAdapter, isSandboxServiceProxyAdapter, isSandboxTerminalAdapter, isStrategyInstance, isStructuredMessageType, isTenantGlobalScopeKey, isTextContentEditor, jsonEncodedSchema, knowledgebaseActions, loadYamlFile, managedAgentRuntimeSchema, mergeCredentials, mergeModelRequirements, mergeParentChildChunks, nativeModelTransport, normalizeContextSize, normalizeTokenUsage, pluginArtifactTableName, prepareToolResult, processAsyncAIGCManagedJob, projectPipelineInvocationScopeSchema, readAnalyticsProviderDiagnostic, renderRemoteModuleIframeHtml, renderRemoteReactIframeHtml, renderRemoteVueIframeHtml, resolveModelUsagePricingSnapshot, resolveSandboxBackend, resolveSandboxExecutionOptions, resolveSandboxManagedServiceAdapter, resolveSandboxServiceProxyAdapter, resolveSandboxTerminalAdapter, resolveStrategyMetadataTarget, resolveTenantGlobalScopeKey, resolveTokenUsage, resolveTokenUsageCandidates, resolveXpertMcpExtensions, runWithRequestContext, runtimeToolProviderComponent, secondsToMilliseconds, setDefaultTenantId, sumTokenUsage, supportsContentModel, taskWaitReason, textTokenBoundaries, validateAnalyticsPayload };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xpert-ai/plugin-sdk",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.37.0",
|
|
4
4
|
"license": "AGPL-3.0",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -37,6 +37,12 @@
|
|
|
37
37
|
"import": "./data-workbench.cjs.mjs",
|
|
38
38
|
"default": "./data-workbench.cjs.js"
|
|
39
39
|
},
|
|
40
|
+
"./remote-component": {
|
|
41
|
+
"module": "./remote-component.esm.js",
|
|
42
|
+
"types": "./remote-component.d.ts",
|
|
43
|
+
"import": "./remote-component.cjs.mjs",
|
|
44
|
+
"default": "./remote-component.cjs.js"
|
|
45
|
+
},
|
|
40
46
|
"./artifact-document": {
|
|
41
47
|
"module": "./artifact-document.esm.js",
|
|
42
48
|
"types": "./artifact-document.d.ts",
|
|
@@ -74,7 +80,7 @@
|
|
|
74
80
|
},
|
|
75
81
|
"dependencies": {
|
|
76
82
|
"@langchain/openai": "0.6.9",
|
|
77
|
-
"@xpert-ai/contracts": "3.
|
|
83
|
+
"@xpert-ai/contracts": "3.37.0",
|
|
78
84
|
"express": "^4.22.1",
|
|
79
85
|
"js-tiktoken": "^1.0.21"
|
|
80
86
|
},
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
exports._default = require('./remote-component.cjs.js').default;
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var _extends = require('./_extends.cjs.js');
|
|
4
|
+
var contextEvent = require('@xpert-ai/contracts/context-event');
|
|
5
|
+
var v3 = require('zod/v3');
|
|
6
|
+
|
|
7
|
+
const channel = 'xpertai.remote_component';
|
|
8
|
+
const envelope = v3.z.object({
|
|
9
|
+
channel: v3.z.literal(channel),
|
|
10
|
+
protocolVersion: v3.z.literal(1),
|
|
11
|
+
type: v3.z.string(),
|
|
12
|
+
instanceId: v3.z.string().min(1),
|
|
13
|
+
scopeRevision: v3.z.number().int().nonnegative().optional(),
|
|
14
|
+
event: v3.z.unknown().optional(),
|
|
15
|
+
requestId: v3.z.string().optional(),
|
|
16
|
+
data: v3.z.unknown().optional(),
|
|
17
|
+
result: v3.z.unknown().optional(),
|
|
18
|
+
message: v3.z.string().optional(),
|
|
19
|
+
locale: v3.z.string().optional(),
|
|
20
|
+
theme: v3.z.object({
|
|
21
|
+
mode: v3.z.string().optional(),
|
|
22
|
+
density: v3.z.enum([
|
|
23
|
+
'default',
|
|
24
|
+
'compact'
|
|
25
|
+
]).optional(),
|
|
26
|
+
tokens: v3.z.record(v3.z.union([
|
|
27
|
+
v3.z.string(),
|
|
28
|
+
v3.z.number()
|
|
29
|
+
])).optional()
|
|
30
|
+
}).optional()
|
|
31
|
+
});
|
|
32
|
+
let scope;
|
|
33
|
+
let disconnect;
|
|
34
|
+
const pending = new Map();
|
|
35
|
+
function invalidate(message) {
|
|
36
|
+
for (const call of pending.values()){
|
|
37
|
+
window.clearTimeout(call.timer);
|
|
38
|
+
call.reject(new Error(message));
|
|
39
|
+
}
|
|
40
|
+
pending.clear();
|
|
41
|
+
}
|
|
42
|
+
/** Subscribe before rendering. The returned cleanup releases the listener and all outstanding requests. */ function connect(init, contextChanged) {
|
|
43
|
+
disconnect == null ? void 0 : disconnect();
|
|
44
|
+
const receive = (event)=>{
|
|
45
|
+
if (event.source !== window.parent) return;
|
|
46
|
+
const parsed = envelope.safeParse(event.data);
|
|
47
|
+
if (!parsed.success) return;
|
|
48
|
+
const message = parsed.data;
|
|
49
|
+
if (message.type === 'init') {
|
|
50
|
+
var _message_scopeRevision, _scope_revision;
|
|
51
|
+
if ((scope == null ? void 0 : scope.instanceId) === message.instanceId && ((_message_scopeRevision = message.scopeRevision) != null ? _message_scopeRevision : -1) < ((_scope_revision = scope.revision) != null ? _scope_revision : -1)) return;
|
|
52
|
+
const changed = (scope == null ? void 0 : scope.instanceId) !== message.instanceId || (scope == null ? void 0 : scope.revision) !== message.scopeRevision;
|
|
53
|
+
if (changed) {
|
|
54
|
+
invalidate('View context changed');
|
|
55
|
+
scope = {
|
|
56
|
+
instanceId: message.instanceId,
|
|
57
|
+
revision: message.scopeRevision
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
var _message_locale;
|
|
61
|
+
init({
|
|
62
|
+
locale: (_message_locale = message.locale) != null ? _message_locale : 'en-US',
|
|
63
|
+
theme: message.theme
|
|
64
|
+
}, changed);
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (!scope || message.instanceId !== scope.instanceId) return;
|
|
68
|
+
if (message.type === 'hostEvent') {
|
|
69
|
+
const context = contextEvent.viewContextEventSchema.safeParse(message.event);
|
|
70
|
+
var _scope_revision1;
|
|
71
|
+
if (context.success && context.data.data.revision > ((_scope_revision1 = scope.revision) != null ? _scope_revision1 : -1)) {
|
|
72
|
+
invalidate('View context changed');
|
|
73
|
+
scope = {
|
|
74
|
+
instanceId: scope.instanceId,
|
|
75
|
+
revision: context.data.data.revision
|
|
76
|
+
};
|
|
77
|
+
contextChanged();
|
|
78
|
+
}
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
if (!message.requestId || message.scopeRevision !== undefined && message.scopeRevision !== scope.revision) return;
|
|
82
|
+
const call = pending.get(message.requestId);
|
|
83
|
+
if (!call) return;
|
|
84
|
+
pending.delete(message.requestId);
|
|
85
|
+
window.clearTimeout(call.timer);
|
|
86
|
+
var _message_message;
|
|
87
|
+
if (message.type === 'error') call.reject(new Error((_message_message = message.message) != null ? _message_message : 'Request failed'));
|
|
88
|
+
else call.resolve('data' in message ? message.data : message.result);
|
|
89
|
+
};
|
|
90
|
+
window.addEventListener('message', receive);
|
|
91
|
+
window.parent.postMessage({
|
|
92
|
+
channel,
|
|
93
|
+
protocolVersion: 1,
|
|
94
|
+
type: 'ready'
|
|
95
|
+
}, '*');
|
|
96
|
+
const close = ()=>{
|
|
97
|
+
if (disconnect !== close) return;
|
|
98
|
+
disconnect = undefined;
|
|
99
|
+
window.removeEventListener('message', receive);
|
|
100
|
+
scope = undefined;
|
|
101
|
+
invalidate('View closed');
|
|
102
|
+
};
|
|
103
|
+
disconnect = close;
|
|
104
|
+
return close;
|
|
105
|
+
}
|
|
106
|
+
function request(type, body = {}) {
|
|
107
|
+
if (!scope) return Promise.reject(new Error('View is not connected'));
|
|
108
|
+
const { instanceId, revision } = scope;
|
|
109
|
+
const requestId = crypto.randomUUID();
|
|
110
|
+
return new Promise((resolve, reject)=>{
|
|
111
|
+
const timer = window.setTimeout(()=>{
|
|
112
|
+
pending.delete(requestId);
|
|
113
|
+
reject(new Error('Request timed out'));
|
|
114
|
+
}, 30000);
|
|
115
|
+
pending.set(requestId, {
|
|
116
|
+
resolve,
|
|
117
|
+
reject,
|
|
118
|
+
timer
|
|
119
|
+
});
|
|
120
|
+
try {
|
|
121
|
+
window.parent.postMessage(_extends._extends({}, body, {
|
|
122
|
+
channel,
|
|
123
|
+
protocolVersion: 1,
|
|
124
|
+
instanceId,
|
|
125
|
+
scopeRevision: revision,
|
|
126
|
+
type,
|
|
127
|
+
requestId
|
|
128
|
+
}), '*');
|
|
129
|
+
} catch (error) {
|
|
130
|
+
window.clearTimeout(timer);
|
|
131
|
+
pending.delete(requestId);
|
|
132
|
+
reject(error);
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
/** Bind a request before asynchronous preparation, so a context switch cannot redirect it. */ function scopedRequest() {
|
|
137
|
+
const captured = scope;
|
|
138
|
+
return (type, body)=>captured && captured === scope ? request(type, body) : Promise.reject(new Error('View context changed'));
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
exports.connect = connect;
|
|
142
|
+
exports.request = request;
|
|
143
|
+
exports.scopedRequest = scopedRequest;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./src/remote-component";
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { _ as _extends } from './_extends.esm.js';
|
|
2
|
+
import { viewContextEventSchema } from '@xpert-ai/contracts/context-event';
|
|
3
|
+
import { z } from 'zod/v3';
|
|
4
|
+
|
|
5
|
+
const channel = 'xpertai.remote_component';
|
|
6
|
+
const envelope = z.object({
|
|
7
|
+
channel: z.literal(channel),
|
|
8
|
+
protocolVersion: z.literal(1),
|
|
9
|
+
type: z.string(),
|
|
10
|
+
instanceId: z.string().min(1),
|
|
11
|
+
scopeRevision: z.number().int().nonnegative().optional(),
|
|
12
|
+
event: z.unknown().optional(),
|
|
13
|
+
requestId: z.string().optional(),
|
|
14
|
+
data: z.unknown().optional(),
|
|
15
|
+
result: z.unknown().optional(),
|
|
16
|
+
message: z.string().optional(),
|
|
17
|
+
locale: z.string().optional(),
|
|
18
|
+
theme: z.object({
|
|
19
|
+
mode: z.string().optional(),
|
|
20
|
+
density: z.enum([
|
|
21
|
+
'default',
|
|
22
|
+
'compact'
|
|
23
|
+
]).optional(),
|
|
24
|
+
tokens: z.record(z.union([
|
|
25
|
+
z.string(),
|
|
26
|
+
z.number()
|
|
27
|
+
])).optional()
|
|
28
|
+
}).optional()
|
|
29
|
+
});
|
|
30
|
+
let scope;
|
|
31
|
+
let disconnect;
|
|
32
|
+
const pending = new Map();
|
|
33
|
+
function invalidate(message) {
|
|
34
|
+
for (const call of pending.values()){
|
|
35
|
+
window.clearTimeout(call.timer);
|
|
36
|
+
call.reject(new Error(message));
|
|
37
|
+
}
|
|
38
|
+
pending.clear();
|
|
39
|
+
}
|
|
40
|
+
/** Subscribe before rendering. The returned cleanup releases the listener and all outstanding requests. */ function connect(init, contextChanged) {
|
|
41
|
+
disconnect == null ? void 0 : disconnect();
|
|
42
|
+
const receive = (event)=>{
|
|
43
|
+
if (event.source !== window.parent) return;
|
|
44
|
+
const parsed = envelope.safeParse(event.data);
|
|
45
|
+
if (!parsed.success) return;
|
|
46
|
+
const message = parsed.data;
|
|
47
|
+
if (message.type === 'init') {
|
|
48
|
+
var _message_scopeRevision, _scope_revision;
|
|
49
|
+
if ((scope == null ? void 0 : scope.instanceId) === message.instanceId && ((_message_scopeRevision = message.scopeRevision) != null ? _message_scopeRevision : -1) < ((_scope_revision = scope.revision) != null ? _scope_revision : -1)) return;
|
|
50
|
+
const changed = (scope == null ? void 0 : scope.instanceId) !== message.instanceId || (scope == null ? void 0 : scope.revision) !== message.scopeRevision;
|
|
51
|
+
if (changed) {
|
|
52
|
+
invalidate('View context changed');
|
|
53
|
+
scope = {
|
|
54
|
+
instanceId: message.instanceId,
|
|
55
|
+
revision: message.scopeRevision
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
var _message_locale;
|
|
59
|
+
init({
|
|
60
|
+
locale: (_message_locale = message.locale) != null ? _message_locale : 'en-US',
|
|
61
|
+
theme: message.theme
|
|
62
|
+
}, changed);
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
if (!scope || message.instanceId !== scope.instanceId) return;
|
|
66
|
+
if (message.type === 'hostEvent') {
|
|
67
|
+
const context = viewContextEventSchema.safeParse(message.event);
|
|
68
|
+
var _scope_revision1;
|
|
69
|
+
if (context.success && context.data.data.revision > ((_scope_revision1 = scope.revision) != null ? _scope_revision1 : -1)) {
|
|
70
|
+
invalidate('View context changed');
|
|
71
|
+
scope = {
|
|
72
|
+
instanceId: scope.instanceId,
|
|
73
|
+
revision: context.data.data.revision
|
|
74
|
+
};
|
|
75
|
+
contextChanged();
|
|
76
|
+
}
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
if (!message.requestId || message.scopeRevision !== undefined && message.scopeRevision !== scope.revision) return;
|
|
80
|
+
const call = pending.get(message.requestId);
|
|
81
|
+
if (!call) return;
|
|
82
|
+
pending.delete(message.requestId);
|
|
83
|
+
window.clearTimeout(call.timer);
|
|
84
|
+
var _message_message;
|
|
85
|
+
if (message.type === 'error') call.reject(new Error((_message_message = message.message) != null ? _message_message : 'Request failed'));
|
|
86
|
+
else call.resolve('data' in message ? message.data : message.result);
|
|
87
|
+
};
|
|
88
|
+
window.addEventListener('message', receive);
|
|
89
|
+
window.parent.postMessage({
|
|
90
|
+
channel,
|
|
91
|
+
protocolVersion: 1,
|
|
92
|
+
type: 'ready'
|
|
93
|
+
}, '*');
|
|
94
|
+
const close = ()=>{
|
|
95
|
+
if (disconnect !== close) return;
|
|
96
|
+
disconnect = undefined;
|
|
97
|
+
window.removeEventListener('message', receive);
|
|
98
|
+
scope = undefined;
|
|
99
|
+
invalidate('View closed');
|
|
100
|
+
};
|
|
101
|
+
disconnect = close;
|
|
102
|
+
return close;
|
|
103
|
+
}
|
|
104
|
+
function request(type, body = {}) {
|
|
105
|
+
if (!scope) return Promise.reject(new Error('View is not connected'));
|
|
106
|
+
const { instanceId, revision } = scope;
|
|
107
|
+
const requestId = crypto.randomUUID();
|
|
108
|
+
return new Promise((resolve, reject)=>{
|
|
109
|
+
const timer = window.setTimeout(()=>{
|
|
110
|
+
pending.delete(requestId);
|
|
111
|
+
reject(new Error('Request timed out'));
|
|
112
|
+
}, 30000);
|
|
113
|
+
pending.set(requestId, {
|
|
114
|
+
resolve,
|
|
115
|
+
reject,
|
|
116
|
+
timer
|
|
117
|
+
});
|
|
118
|
+
try {
|
|
119
|
+
window.parent.postMessage(_extends({}, body, {
|
|
120
|
+
channel,
|
|
121
|
+
protocolVersion: 1,
|
|
122
|
+
instanceId,
|
|
123
|
+
scopeRevision: revision,
|
|
124
|
+
type,
|
|
125
|
+
requestId
|
|
126
|
+
}), '*');
|
|
127
|
+
} catch (error) {
|
|
128
|
+
window.clearTimeout(timer);
|
|
129
|
+
pending.delete(requestId);
|
|
130
|
+
reject(error);
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
/** Bind a request before asynchronous preparation, so a context switch cannot redirect it. */ function scopedRequest() {
|
|
135
|
+
const captured = scope;
|
|
136
|
+
return (type, body)=>captured && captured === scope ? request(type, body) : Promise.reject(new Error('View context changed'));
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export { connect, request, scopedRequest };
|