@xpert-ai/plugin-sdk 3.15.9 → 3.15.10

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
@@ -2775,6 +2775,10 @@ const KnowledgebaseDocumentsRuntimeCapability = createRuntimeCapability('platfor
2775
2775
  description: 'Upload, import, create, process, inspect, and delete persistent knowledgebase documents.'
2776
2776
  });
2777
2777
 
2778
+ const ArtifactsRuntimeCapability = createRuntimeCapability('platform.artifacts', {
2779
+ description: 'Create, version, preview, download, share, archive, and delete platform-managed plugin and Agent artifacts.'
2780
+ });
2781
+
2778
2782
  /** Stable source identifier for portable workspace file references. */ const WORKSPACE_FILES_SOURCE = 'platform.workspace.files';
2779
2783
  const WorkspaceFilesRuntimeCapability = createRuntimeCapability('platform.workspace.files', {
2780
2784
  description: 'Upload, understand, read, and delete raw files in Xpert workspace volumes.'
@@ -4666,4 +4670,410 @@ function escapeInlineScript(value) {
4666
4670
 
4667
4671
  const VIEW_EXTENSION_CACHE_SERVICE_TOKEN = 'XPERT_PLUGIN_VIEW_EXTENSION_CACHE_SERVICE';
4668
4672
 
4669
- export { ACCOUNT_BINDING_PERMISSION_SERVICE_TOKEN, AGENT_CHAT_DISPATCH_MESSAGE_TYPE, AGENT_MIDDLEWARE_STRATEGY, AIModelProviderNotFoundException, AIModelProviderRegistry, AIModelProviderStrategy, AI_MODEL_PROVIDER, ANALYTICS_PERMISSION_SERVICE_TOKEN, AdapterDataSourceStrategy, AgentMiddlewareRegistry, AgentMiddlewareStrategy, AiModelNotFoundException, AssistantTaskRuntimeCapability, BOUND_IDENTITY_LOGIN_PERMISSION_SERVICE_TOKEN, BUILTIN_GLOBAL_SCOPE, BaseHTTPQueryRunner, BaseQueryRunner, BaseSQLQueryRunner, BaseSandbox, BaseStrategyRegistry, BaseTool, BaseToolset, BuiltinToolset, CHAT_CHANNEL, CHAT_CHANNEL_TEXT_LIMITS, CONNECTION_COMMAND_ROUTER_TOKEN, CONNECTOR_STRATEGY, CancelConversationCommand, ChatChannel, ChatChannelRegistry, ChatOAICompatReasoningModel, 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, DefaultRuntimeCapabilityRegistry as DefaultAgentMiddlewareRuntimeCapabilityRegistry, DefaultRuntimeCapabilityRegistry, DocumentSourceRegistry, DocumentSourceStrategy, DocumentTransformerRegistry, DocumentTransformerStrategy, 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, ImageUnderstandingRegistry, ImageUnderstandingStrategy, IntegrationStrategyKey, IntegrationStrategyRegistry, JUMP_TO_TARGETS, JsonSchemaValidator, KNOWLEDGE_STRATEGY, KnowledgeStrategyKey, KnowledgeStrategyRegistry, KnowledgebaseDocumentsRuntimeCapability, KnowledgebaseRuntimeCapability, LLMUsage, LargeLanguageModel, MANAGED_CONNECTION_REGISTRY_TOKEN, MANAGED_QUEUE_HANDLER_REGISTRY_TOKEN, MANAGED_QUEUE_SERVICE_TOKEN, ModelProvider, ORGANIZATION_METADATA_KEY, OpenAICompatibleReranker, PERMISSION_OPERATION_METADATA_KEY, PLUGIN_CONFIG_RESOLVER_TOKEN, PLUGIN_JOB_PROCESSOR_METADATA, PLUGIN_METADATA, PLUGIN_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_SHELL_TIMEOUT_LIMITS_SEC, 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, 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, VIEW_EXTENSION_CACHE_SERVICE_TOKEN, VIEW_EXTENSION_PROVIDER, VectorStoreRegistry, VectorStoreStrategy, ViewExtensionProvider, ViewExtensionProviderRegistry, WORKFLOW_NODE_STRATEGY, WORKFLOW_TRIGGER_STRATEGY, WORKSPACE_FILES_SOURCE, WorkflowNodeRegistry, WorkflowNodeStrategy, WorkflowTriggerRegistry, WorkflowTriggerStrategy, WorkspaceFilesRuntimeCapability, WrapWorkflowNodeExecutionCommand, XPERT_RUNTIME_CAPABILITIES_TOKEN, XpFileSystem, XpertServerPlugin, als, appendSandboxMessage, buildSandboxTimeoutMessage, calcTokenUsage, chunkText, countTokensSafe, createI18nInstance, createPluginLogger, createRuntimeCapability, defineAgentMessageType, defineChannelMessageType, derivePluginArtifactNamespace, downloadRemoteFile, formatSandboxTimeout, getDefaultTenantId, getErrorMessage, getModelContextSize, getPermissionOperationMetadata, getPositionList, getPositionMap, getRequestContext, getRequiredPermissionOperation, getTenantGlobalScopeKey, isRemoteFile, isSandboxBackend, isSandboxManagedServiceAdapter, isSandboxServiceProxyAdapter, isSandboxTerminalAdapter, isStructuredMessageType, isTenantGlobalScopeKey, loadYamlFile, mergeCredentials, mergeParentChildChunks, normalizeContextSize, pluginArtifactTableName, renderRemoteModuleIframeHtml, renderRemoteReactIframeHtml, renderRemoteVueIframeHtml, resolveSandboxBackend, resolveSandboxExecutionOptions, resolveSandboxManagedServiceAdapter, resolveSandboxServiceProxyAdapter, resolveSandboxTerminalAdapter, resolveTenantGlobalScopeKey, runWithRequestContext, secondsToMilliseconds, setDefaultTenantId, sumTokenUsage };
4673
+ /** Platform-owned real-time collaboration capability available to scoped plugin runtimes. */ const CollaborationRuntimeCapability = createRuntimeCapability('platform.collaboration', {
4674
+ description: 'Create, synchronize, persist, authorize, and observe platform-managed real-time collaboration documents.'
4675
+ });
4676
+
4677
+ const COLLABORATION_DOCUMENT_PROVIDER = 'COLLABORATION_DOCUMENT_PROVIDER';
4678
+ /** Register a plugin adapter for one stable collaboration resource type. */ const CollaborationDocumentProvider = (providerKey)=>applyDecorators(SetMetadata(COLLABORATION_DOCUMENT_PROVIDER, providerKey), SetMetadata(STRATEGY_META_KEY, COLLABORATION_DOCUMENT_PROVIDER));
4679
+
4680
+ /** Discovers system and organization-scoped collaboration providers from loaded plugins. */ let CollaborationDocumentProviderRegistry = class CollaborationDocumentProviderRegistry extends BaseStrategyRegistry {
4681
+ constructor(discoveryService, reflector){
4682
+ super(COLLABORATION_DOCUMENT_PROVIDER, discoveryService, reflector);
4683
+ }
4684
+ };
4685
+ CollaborationDocumentProviderRegistry = __decorate([
4686
+ Injectable(),
4687
+ __metadata("design:paramtypes", [
4688
+ DiscoveryService,
4689
+ Reflector
4690
+ ])
4691
+ ], CollaborationDocumentProviderRegistry);
4692
+
4693
+ function createSocketIoTransportAdapter(socket) {
4694
+ return {
4695
+ get connected () {
4696
+ return socket.connected;
4697
+ },
4698
+ get clientId () {
4699
+ var _socket_id;
4700
+ return (_socket_id = socket.id) != null ? _socket_id : null;
4701
+ },
4702
+ connect: ()=>{
4703
+ socket.connect();
4704
+ },
4705
+ disconnect: ()=>{
4706
+ socket.disconnect();
4707
+ },
4708
+ emit: (event, payload = {})=>{
4709
+ socket.emit(event, payload);
4710
+ },
4711
+ on: (event, handler)=>{
4712
+ socket.on(event, handler);
4713
+ return ()=>{
4714
+ socket.off(event, handler);
4715
+ };
4716
+ }
4717
+ };
4718
+ }
4719
+ /** Wrap a caller-owned `Y.Doc` without passing it across the runtime capability boundary. */ function createYjsDocumentAdapter(document, yjs) {
4720
+ return {
4721
+ applyUpdate: (update, origin)=>yjs.applyUpdate(document, update, origin),
4722
+ encodeStateVector: ()=>yjs.encodeStateVector(document),
4723
+ mergeUpdates: (updates)=>yjs.mergeUpdates(updates),
4724
+ onUpdate: (handler)=>{
4725
+ document.on('update', handler);
4726
+ return ()=>document.off('update', handler);
4727
+ }
4728
+ };
4729
+ }
4730
+ /**
4731
+ * Keep per-client sessions for cursors while exposing one collaborator per stable actor identity.
4732
+ * This prevents a second tab owned by the same user from either duplicating or hiding that user.
4733
+ */ function createCollaborationPresenceStore(options = {}) {
4734
+ let selfClientId = null;
4735
+ let sessions = new Map();
4736
+ const readSnapshot = ()=>{
4737
+ const activeSessions = Array.from(sessions.values()).sort((left, right)=>right.updatedAt - left.updatedAt);
4738
+ const remoteSessions = activeSessions.filter((item)=>item.clientId !== selfClientId);
4739
+ const actors = new Map();
4740
+ for (const item of activeSessions)if (!actors.has(item.presenceId)) actors.set(item.presenceId, item);
4741
+ if (options.includeSelf !== false && options.selfActor) {
4742
+ const existing = activeSessions.find((item)=>{
4743
+ var _options_selfActor;
4744
+ return item.clientId === selfClientId || item.presenceId === ((_options_selfActor = options.selfActor) == null ? void 0 : _options_selfActor.presenceId);
4745
+ });
4746
+ actors.set(options.selfActor.presenceId, existing != null ? existing : actorPresence(options.selfActor, selfClientId));
4747
+ }
4748
+ const collaborators = Array.from(actors.values()).sort((left, right)=>{
4749
+ var _options_selfActor, _options_selfActor1;
4750
+ const leftSelf = left.presenceId === ((_options_selfActor = options.selfActor) == null ? void 0 : _options_selfActor.presenceId) ? 1 : 0;
4751
+ const rightSelf = right.presenceId === ((_options_selfActor1 = options.selfActor) == null ? void 0 : _options_selfActor1.presenceId) ? 1 : 0;
4752
+ return rightSelf - leftSelf || right.updatedAt - left.updatedAt;
4753
+ });
4754
+ return {
4755
+ selfClientId,
4756
+ sessions: activeSessions,
4757
+ remoteSessions,
4758
+ collaborators
4759
+ };
4760
+ };
4761
+ const publish = ()=>options.onChange == null ? void 0 : options.onChange.call(options, readSnapshot());
4762
+ return {
4763
+ setSelfClientId: (clientId)=>{
4764
+ selfClientId = clientId;
4765
+ publish();
4766
+ },
4767
+ replace: (items, clientId = selfClientId)=>{
4768
+ selfClientId = clientId;
4769
+ sessions = new Map(items.map((item)=>[
4770
+ item.clientId,
4771
+ item
4772
+ ]));
4773
+ publish();
4774
+ },
4775
+ upsert: (item)=>{
4776
+ sessions.set(item.clientId, item);
4777
+ publish();
4778
+ },
4779
+ remove: (clientId)=>{
4780
+ if (sessions.delete(clientId)) publish();
4781
+ },
4782
+ clear: ()=>{
4783
+ sessions.clear();
4784
+ selfClientId = null;
4785
+ publish();
4786
+ },
4787
+ snapshot: readSnapshot
4788
+ };
4789
+ }
4790
+ /**
4791
+ * Create a collaboration client with update batching, state-vector repair, presence heartbeat,
4792
+ * and reconnect synchronization. The caller retains ownership of the document and transport.
4793
+ */ function createCollaborationClient(options) {
4794
+ const remoteOrigin = Object.freeze({
4795
+ kind: 'platform.collaboration.remote'
4796
+ });
4797
+ const batchMs = positiveInteger(options.batchMs, 40);
4798
+ const syncIntervalMs = positiveInteger(options.syncIntervalMs, 2000);
4799
+ const presenceHeartbeatMs = positiveInteger(options.presenceHeartbeatMs, 5000);
4800
+ const presenceStaleMs = positiveInteger(options.presenceStaleMs, 15000);
4801
+ var _options_initialPresence;
4802
+ let presence = _extends({}, (_options_initialPresence = options.initialPresence) != null ? _options_initialPresence : {});
4803
+ let pending = [];
4804
+ let flushTimer;
4805
+ let syncTimer;
4806
+ let presenceTimer;
4807
+ let presenceCleanupTimer;
4808
+ var _options_transport_clientId;
4809
+ let selfClientId = (_options_transport_clientId = options.transport.clientId) != null ? _options_transport_clientId : null;
4810
+ let started = false;
4811
+ const cleanups = [];
4812
+ const presenceSeenAt = new Map();
4813
+ const reportError = (error)=>options.onError == null ? void 0 : options.onError.call(options, error instanceof Error ? error : new Error(String(error)));
4814
+ const emitPresence = ()=>options.transport.emit('presence', _extends({}, presence));
4815
+ // Merge the short burst of local Yjs transactions into one network update.
4816
+ const flush = ()=>{
4817
+ if (flushTimer) clearTimeout(flushTimer);
4818
+ flushTimer = undefined;
4819
+ if (!pending.length || !options.transport.connected) return;
4820
+ const updates = pending;
4821
+ pending = [];
4822
+ options.transport.emit('update', {
4823
+ updateBase64: bytesToBase64(options.document.mergeUpdates(updates)),
4824
+ origin: 'plugin-client'
4825
+ });
4826
+ };
4827
+ // A state vector lets the server return only bytes missing from this client.
4828
+ const requestSync = ()=>{
4829
+ if (!options.transport.connected) return;
4830
+ options.transport.emit('sync-request', {
4831
+ stateVectorBase64: bytesToBase64(options.document.encodeStateVector())
4832
+ });
4833
+ };
4834
+ // Mark server updates with `remoteOrigin` so the document observer does not send them back.
4835
+ const applyRemote = (payload)=>{
4836
+ const encoded = stringValue(payload['updateBase64']);
4837
+ if (!encoded) return;
4838
+ try {
4839
+ options.document.applyUpdate(base64ToBytes(encoded), remoteOrigin);
4840
+ } catch (error) {
4841
+ reportError(error);
4842
+ }
4843
+ };
4844
+ // Register listeners once, then start repair and presence heartbeats before opening the socket.
4845
+ const connect = ()=>{
4846
+ if (started) return;
4847
+ started = true;
4848
+ options.onConnectionChange == null ? void 0 : options.onConnectionChange.call(options, 'connecting');
4849
+ cleanups.push(options.document.onUpdate((update, origin)=>{
4850
+ if (origin === remoteOrigin) return;
4851
+ pending.push(update);
4852
+ if (!flushTimer) flushTimer = setTimeout(flush, batchMs);
4853
+ }));
4854
+ cleanups.push(options.transport.on('connect', ()=>{
4855
+ var _options_transport_clientId;
4856
+ selfClientId = (_options_transport_clientId = options.transport.clientId) != null ? _options_transport_clientId : selfClientId;
4857
+ options.onConnectionChange == null ? void 0 : options.onConnectionChange.call(options, 'connected');
4858
+ requestSync();
4859
+ emitPresence();
4860
+ }));
4861
+ cleanups.push(options.transport.on('disconnect', ()=>options.onConnectionChange == null ? void 0 : options.onConnectionChange.call(options, 'disconnected')));
4862
+ cleanups.push(options.transport.on('sync', applyRemote));
4863
+ cleanups.push(options.transport.on('update', applyRemote));
4864
+ cleanups.push(options.transport.on('update-ack', (payload)=>{
4865
+ const ack = parseAck(payload);
4866
+ if (ack) options.onAck == null ? void 0 : options.onAck.call(options, ack);
4867
+ }));
4868
+ cleanups.push(options.transport.on('presence', (payload)=>{
4869
+ const item = parsePresence(payload);
4870
+ if (item) {
4871
+ presenceSeenAt.set(item.clientId, Date.now());
4872
+ options.onPresence == null ? void 0 : options.onPresence.call(options, item);
4873
+ }
4874
+ }));
4875
+ cleanups.push(options.transport.on('presence-snapshot', (payload)=>{
4876
+ const rawItems = payload['items'];
4877
+ const items = Array.isArray(rawItems) ? rawItems.map(parsePresence).filter(isPresence) : [];
4878
+ var _stringValue, _ref;
4879
+ selfClientId = (_ref = (_stringValue = stringValue(payload['selfClientId'])) != null ? _stringValue : options.transport.clientId) != null ? _ref : selfClientId;
4880
+ presenceSeenAt.clear();
4881
+ for (const item of items)presenceSeenAt.set(item.clientId, Date.now());
4882
+ options.onPresenceSnapshot == null ? void 0 : options.onPresenceSnapshot.call(options, items, {
4883
+ selfClientId
4884
+ });
4885
+ }));
4886
+ cleanups.push(options.transport.on('presence-remove', (payload)=>{
4887
+ const clientId = stringValue(payload['clientId']);
4888
+ if (clientId) {
4889
+ presenceSeenAt.delete(clientId);
4890
+ options.onPresenceRemove == null ? void 0 : options.onPresenceRemove.call(options, clientId);
4891
+ }
4892
+ }));
4893
+ cleanups.push(options.transport.on('error', (payload)=>{
4894
+ var _stringValue;
4895
+ return reportError((_stringValue = stringValue(payload['message'])) != null ? _stringValue : 'Collaboration failed.');
4896
+ }));
4897
+ syncTimer = setInterval(requestSync, syncIntervalMs);
4898
+ presenceTimer = setInterval(emitPresence, presenceHeartbeatMs);
4899
+ presenceCleanupTimer = setInterval(()=>{
4900
+ const cutoff = Date.now() - presenceStaleMs;
4901
+ for (const [clientId, seenAt] of presenceSeenAt){
4902
+ if (clientId === selfClientId || seenAt >= cutoff) continue;
4903
+ presenceSeenAt.delete(clientId);
4904
+ options.onPresenceRemove == null ? void 0 : options.onPresenceRemove.call(options, clientId);
4905
+ }
4906
+ }, Math.min(5000, Math.max(1000, Math.floor(presenceStaleMs / 3))));
4907
+ options.transport.connect();
4908
+ };
4909
+ // Flush best-effort pending state and release all timers/listeners owned by this client.
4910
+ const disconnect = ()=>{
4911
+ var _cleanups_pop;
4912
+ if (!started) return;
4913
+ flush();
4914
+ started = false;
4915
+ if (flushTimer) clearTimeout(flushTimer);
4916
+ if (syncTimer) clearInterval(syncTimer);
4917
+ if (presenceTimer) clearInterval(presenceTimer);
4918
+ if (presenceCleanupTimer) clearInterval(presenceCleanupTimer);
4919
+ flushTimer = undefined;
4920
+ syncTimer = undefined;
4921
+ presenceTimer = undefined;
4922
+ presenceCleanupTimer = undefined;
4923
+ presenceSeenAt.clear();
4924
+ while(cleanups.length)(_cleanups_pop = cleanups.pop()) == null ? void 0 : _cleanups_pop();
4925
+ options.transport.disconnect();
4926
+ options.onConnectionChange == null ? void 0 : options.onConnectionChange.call(options, 'disconnected');
4927
+ };
4928
+ return {
4929
+ get selfClientId () {
4930
+ return selfClientId;
4931
+ },
4932
+ remoteOrigin,
4933
+ connect,
4934
+ disconnect,
4935
+ flush,
4936
+ requestSync,
4937
+ setPresence: (patch)=>{
4938
+ presence = _extends({}, presence, patch);
4939
+ if (options.transport.connected) emitPresence();
4940
+ }
4941
+ };
4942
+ }
4943
+ function actorPresence(actor, clientId) {
4944
+ return _extends({}, actor, {
4945
+ clientId: clientId != null ? clientId : `self:${actor.presenceId}`,
4946
+ pageId: null,
4947
+ pointer: null,
4948
+ focus: null,
4949
+ selection: null,
4950
+ viewport: null,
4951
+ mode: null,
4952
+ status: null,
4953
+ toolName: null,
4954
+ operationLabel: null,
4955
+ updatedAt: Date.now()
4956
+ });
4957
+ }
4958
+ /** Encode bytes in browsers without Node.js `Buffer`; chunks avoid argument-size limits. */ function bytesToBase64(bytes) {
4959
+ let binary = '';
4960
+ const chunkSize = 0x8000;
4961
+ for(let offset = 0; offset < bytes.length; offset += chunkSize){
4962
+ binary += String.fromCharCode(...bytes.subarray(offset, Math.min(offset + chunkSize, bytes.length)));
4963
+ }
4964
+ return globalThis.btoa(binary);
4965
+ }
4966
+ /** Decode base64 in browsers without requiring Node.js polyfills. */ function base64ToBytes(value) {
4967
+ const binary = globalThis.atob(value);
4968
+ const bytes = new Uint8Array(binary.length);
4969
+ for(let index = 0; index < binary.length; index += 1)bytes[index] = binary.charCodeAt(index);
4970
+ return bytes;
4971
+ }
4972
+ function parseAck(payload) {
4973
+ const documentId = stringValue(payload['documentId']);
4974
+ const stateVectorBase64 = stringValue(payload['stateVectorBase64']);
4975
+ const sequenceNumber = payload['sequenceNumber'];
4976
+ if (!documentId || !stateVectorBase64 || typeof sequenceNumber !== 'number') return null;
4977
+ const materializationStatus = payload['materializationStatus'];
4978
+ if (materializationStatus !== 'ready' && materializationStatus !== 'pending' && materializationStatus !== 'failed') return null;
4979
+ return {
4980
+ documentId,
4981
+ duplicate: payload['duplicate'] === true,
4982
+ sequenceNumber,
4983
+ updateId: stringValue(payload['updateId']),
4984
+ stateVectorBase64,
4985
+ materializationStatus
4986
+ };
4987
+ }
4988
+ function parsePresence(value) {
4989
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
4990
+ const item = value;
4991
+ const clientId = stringValue(item['clientId']);
4992
+ const presenceId = stringValue(item['presenceId']);
4993
+ const displayName = stringValue(item['displayName']);
4994
+ const color = stringValue(item['color']);
4995
+ const actorType = item['actorType'];
4996
+ if (!clientId || !presenceId || !displayName || !color || actorType !== 'user' && actorType !== 'agent' && actorType !== 'system') return null;
4997
+ return {
4998
+ clientId,
4999
+ presenceId,
5000
+ displayName,
5001
+ color,
5002
+ actorType,
5003
+ avatarUrl: nullableString(item['avatarUrl']),
5004
+ pageId: nullableString(item['pageId']),
5005
+ pointer: parsePointer(item['pointer']),
5006
+ focus: parseFocus(item['focus']),
5007
+ selection: parseSelection(item['selection']),
5008
+ viewport: parseViewport(item['viewport']),
5009
+ mode: nullableString(item['mode']),
5010
+ status: actorStatus(item['status']),
5011
+ toolName: nullableString(item['toolName']),
5012
+ operationLabel: nullableString(item['operationLabel']),
5013
+ updatedAt: typeof item['updatedAt'] === 'number' ? item['updatedAt'] : Date.now()
5014
+ };
5015
+ }
5016
+ function parsePointer(value) {
5017
+ const item = recordValue(value);
5018
+ if (!item || typeof item['x'] !== 'number' || typeof item['y'] !== 'number') return null;
5019
+ return {
5020
+ pageId: nullableString(item['pageId']),
5021
+ x: item['x'],
5022
+ y: item['y'],
5023
+ visible: item['visible'] !== false
5024
+ };
5025
+ }
5026
+ function parseFocus(value) {
5027
+ const item = recordValue(value);
5028
+ const kind = item && stringValue(item['kind']);
5029
+ if (!item || !kind) return null;
5030
+ return {
5031
+ kind,
5032
+ key: nullableString(item['key']),
5033
+ pageId: nullableString(item['pageId']),
5034
+ elementId: nullableString(item['elementId']),
5035
+ fieldKey: nullableString(item['fieldKey'])
5036
+ };
5037
+ }
5038
+ function parseSelection(value) {
5039
+ const item = recordValue(value);
5040
+ const kind = item == null ? void 0 : item['kind'];
5041
+ if (!item || kind !== 'text' && kind !== 'elements') return null;
5042
+ return {
5043
+ kind,
5044
+ fieldKey: nullableString(item['fieldKey']),
5045
+ elementIds: Array.isArray(item['elementIds']) ? item['elementIds'].filter((entry)=>typeof entry === 'string') : null,
5046
+ anchorRelativeBase64: nullableString(item['anchorRelativeBase64']),
5047
+ headRelativeBase64: nullableString(item['headRelativeBase64'])
5048
+ };
5049
+ }
5050
+ function parseViewport(value) {
5051
+ const item = recordValue(value);
5052
+ if (!item || typeof item['zoom'] !== 'number' || typeof item['width'] !== 'number' || typeof item['height'] !== 'number') return null;
5053
+ return {
5054
+ zoom: item['zoom'],
5055
+ width: item['width'],
5056
+ height: item['height']
5057
+ };
5058
+ }
5059
+ function recordValue(value) {
5060
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : null;
5061
+ }
5062
+ function isPresence(value) {
5063
+ return value !== null;
5064
+ }
5065
+ function stringValue(value) {
5066
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
5067
+ }
5068
+ function nullableString(value) {
5069
+ var _stringValue;
5070
+ return (_stringValue = stringValue(value)) != null ? _stringValue : null;
5071
+ }
5072
+ function actorStatus(value) {
5073
+ return value === 'thinking' || value === 'editing' || value === 'done' || value === 'failed' ? value : null;
5074
+ }
5075
+ function positiveInteger(value, fallback) {
5076
+ return Number.isFinite(value) && Number(value) > 0 ? Math.trunc(Number(value)) : fallback;
5077
+ }
5078
+
5079
+ export { ACCOUNT_BINDING_PERMISSION_SERVICE_TOKEN, AGENT_CHAT_DISPATCH_MESSAGE_TYPE, AGENT_MIDDLEWARE_STRATEGY, AIModelProviderNotFoundException, AIModelProviderRegistry, AIModelProviderStrategy, AI_MODEL_PROVIDER, ANALYTICS_PERMISSION_SERVICE_TOKEN, AdapterDataSourceStrategy, AgentMiddlewareRegistry, AgentMiddlewareStrategy, AiModelNotFoundException, ArtifactsRuntimeCapability, AssistantTaskRuntimeCapability, BOUND_IDENTITY_LOGIN_PERMISSION_SERVICE_TOKEN, BUILTIN_GLOBAL_SCOPE, BaseHTTPQueryRunner, BaseQueryRunner, BaseSQLQueryRunner, BaseSandbox, BaseStrategyRegistry, BaseTool, BaseToolset, 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, DefaultRuntimeCapabilityRegistry as DefaultAgentMiddlewareRuntimeCapabilityRegistry, DefaultRuntimeCapabilityRegistry, DocumentSourceRegistry, DocumentSourceStrategy, DocumentTransformerRegistry, DocumentTransformerStrategy, 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, ImageUnderstandingRegistry, ImageUnderstandingStrategy, IntegrationStrategyKey, IntegrationStrategyRegistry, JUMP_TO_TARGETS, JsonSchemaValidator, KNOWLEDGE_STRATEGY, KnowledgeStrategyKey, KnowledgeStrategyRegistry, KnowledgebaseDocumentsRuntimeCapability, KnowledgebaseRuntimeCapability, LLMUsage, LargeLanguageModel, MANAGED_CONNECTION_REGISTRY_TOKEN, MANAGED_QUEUE_HANDLER_REGISTRY_TOKEN, MANAGED_QUEUE_SERVICE_TOKEN, ModelProvider, ORGANIZATION_METADATA_KEY, OpenAICompatibleReranker, PERMISSION_OPERATION_METADATA_KEY, PLUGIN_CONFIG_RESOLVER_TOKEN, PLUGIN_JOB_PROCESSOR_METADATA, PLUGIN_METADATA, PLUGIN_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_SHELL_TIMEOUT_LIMITS_SEC, 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, 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, VIEW_EXTENSION_CACHE_SERVICE_TOKEN, VIEW_EXTENSION_PROVIDER, VectorStoreRegistry, VectorStoreStrategy, ViewExtensionProvider, ViewExtensionProviderRegistry, WORKFLOW_NODE_STRATEGY, WORKFLOW_TRIGGER_STRATEGY, WORKSPACE_FILES_SOURCE, WorkflowNodeRegistry, WorkflowNodeStrategy, WorkflowTriggerRegistry, WorkflowTriggerStrategy, WorkspaceFilesRuntimeCapability, WrapWorkflowNodeExecutionCommand, XPERT_RUNTIME_CAPABILITIES_TOKEN, XpFileSystem, XpertServerPlugin, als, appendSandboxMessage, base64ToBytes, buildSandboxTimeoutMessage, bytesToBase64, calcTokenUsage, chunkText, countTokensSafe, createCollaborationClient, createCollaborationPresenceStore, createI18nInstance, createPluginLogger, createRuntimeCapability, createSocketIoTransportAdapter, createYjsDocumentAdapter, defineAgentMessageType, defineChannelMessageType, derivePluginArtifactNamespace, downloadRemoteFile, formatSandboxTimeout, getDefaultTenantId, getErrorMessage, getModelContextSize, getPermissionOperationMetadata, getPositionList, getPositionMap, getRequestContext, getRequiredPermissionOperation, getTenantGlobalScopeKey, isRemoteFile, isSandboxBackend, isSandboxManagedServiceAdapter, isSandboxServiceProxyAdapter, isSandboxTerminalAdapter, isStructuredMessageType, isTenantGlobalScopeKey, loadYamlFile, mergeCredentials, mergeParentChildChunks, normalizeContextSize, pluginArtifactTableName, renderRemoteModuleIframeHtml, renderRemoteReactIframeHtml, renderRemoteVueIframeHtml, resolveSandboxBackend, resolveSandboxExecutionOptions, resolveSandboxManagedServiceAdapter, resolveSandboxServiceProxyAdapter, resolveSandboxTerminalAdapter, resolveTenantGlobalScopeKey, runWithRequestContext, secondsToMilliseconds, setDefaultTenantId, sumTokenUsage };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xpert-ai/plugin-sdk",
3
- "version": "3.15.9",
3
+ "version": "3.15.10",
4
4
  "license": "AGPL-3.0",
5
5
  "repository": {
6
6
  "type": "git",
@@ -17,7 +17,7 @@
17
17
  },
18
18
  "dependencies": {
19
19
  "@langchain/openai": "0.6.9",
20
- "@xpert-ai/contracts": "3.15.9",
20
+ "@xpert-ai/contracts": "3.15.10",
21
21
  "express": "^4.22.1",
22
22
  "js-tiktoken": "^1.0.21"
23
23
  },
package/src/index.d.ts CHANGED
@@ -23,3 +23,4 @@ export * from './lib/sandbox/index';
23
23
  export * from './lib/managed-connection/index';
24
24
  export * from './lib/managed-queue/index';
25
25
  export * from './lib/view-extension/index';
26
+ export * from './lib/collaboration/index';
@@ -0,0 +1,118 @@
1
+ import type { ApplyCollaborationUpdateResult, CollaborationPresencePatch, CollaborationSessionDescriptor, ICollaborationActor, ICollaborationPresence } from './types';
2
+ export type CollaborationTransportPayload = Record<string, unknown>;
3
+ export type CollaborationTransportHandler = (payload: CollaborationTransportPayload) => void;
4
+ /** Framework-neutral event transport used by the collaboration client. */
5
+ export interface CollaborationTransport {
6
+ readonly connected: boolean;
7
+ /** Socket/session identifier for this exact browser client, when the transport exposes one. */
8
+ readonly clientId?: string | null;
9
+ connect(): void;
10
+ disconnect(): void;
11
+ emit(event: string, payload?: CollaborationTransportPayload): void;
12
+ on(event: string, handler: CollaborationTransportHandler): () => void;
13
+ }
14
+ /** Minimal Socket.IO-compatible shape; keeps socket.io-client out of the SDK bundle. */
15
+ export interface CollaborationSocketLike {
16
+ readonly connected: boolean;
17
+ readonly id?: string;
18
+ connect(): unknown;
19
+ disconnect(): unknown;
20
+ emit(event: string, payload?: CollaborationTransportPayload): unknown;
21
+ on(event: string, handler: CollaborationTransportHandler): unknown;
22
+ off(event: string, handler: CollaborationTransportHandler): unknown;
23
+ }
24
+ /** Adapt a caller-owned Socket.IO client to the SDK's framework-neutral transport. */
25
+ export declare function createSocketIoTransportAdapter(socket: CollaborationSocketLike): CollaborationTransport;
26
+ export type CollaborationDocumentUpdateHandler = (update: Uint8Array, origin: unknown) => void;
27
+ /** Binary CRDT operations required by the generic collaboration client. */
28
+ export interface CollaborationBinaryDocumentAdapter {
29
+ applyUpdate(update: Uint8Array, origin: unknown): void;
30
+ encodeStateVector(): Uint8Array;
31
+ mergeUpdates(updates: Uint8Array[]): Uint8Array;
32
+ onUpdate(handler: CollaborationDocumentUpdateHandler): () => void;
33
+ }
34
+ /** Minimal observable Yjs document surface accepted by `createYjsDocumentAdapter`. */
35
+ export interface YjsDocumentLike {
36
+ on(event: 'update', handler: CollaborationDocumentUpdateHandler): void;
37
+ off(event: 'update', handler: CollaborationDocumentUpdateHandler): void;
38
+ }
39
+ /** Caller-supplied Yjs functions, avoiding a second Yjs runtime in plugin bundles. */
40
+ export interface YjsApiLike<TDocument extends YjsDocumentLike> {
41
+ applyUpdate(document: TDocument, update: Uint8Array, origin?: unknown): void;
42
+ encodeStateVector(document: TDocument): Uint8Array;
43
+ mergeUpdates(updates: Uint8Array[]): Uint8Array;
44
+ }
45
+ /** Wrap a caller-owned `Y.Doc` without passing it across the runtime capability boundary. */
46
+ export declare function createYjsDocumentAdapter<TDocument extends YjsDocumentLike>(document: TDocument, yjs: YjsApiLike<TDocument>): CollaborationBinaryDocumentAdapter;
47
+ /** Timings, callbacks, transport, and document adapter used by a browser client. */
48
+ export type CollaborationClientOptions = {
49
+ session: CollaborationSessionDescriptor;
50
+ transport: CollaborationTransport;
51
+ document: CollaborationBinaryDocumentAdapter;
52
+ initialPresence?: CollaborationPresencePatch;
53
+ batchMs?: number;
54
+ syncIntervalMs?: number;
55
+ presenceHeartbeatMs?: number;
56
+ /** Remove a presence locally when no refresh has been received within this interval. */
57
+ presenceStaleMs?: number;
58
+ onAck?: (ack: ApplyCollaborationUpdateResult) => void;
59
+ onPresence?: (presence: ICollaborationPresence) => void;
60
+ onPresenceSnapshot?: (items: ICollaborationPresence[], metadata: CollaborationPresenceSnapshotMetadata) => void;
61
+ onPresenceRemove?: (clientId: string) => void;
62
+ onConnectionChange?: (state: 'connecting' | 'connected' | 'disconnected') => void;
63
+ onError?: (error: Error) => void;
64
+ };
65
+ /** Lifecycle and presence controls returned by `createCollaborationClient`. */
66
+ export interface CollaborationClient {
67
+ /** Stable origin applied to remote updates so local observers can prevent echo loops. */
68
+ readonly remoteOrigin: object;
69
+ /** Socket id for this exact tab/device; distinct from the stable actor `presenceId`. */
70
+ readonly selfClientId: string | null;
71
+ connect(): void;
72
+ disconnect(): void;
73
+ flush(): void;
74
+ requestSync(): void;
75
+ setPresence(patch: CollaborationPresencePatch): void;
76
+ }
77
+ /** Connection-specific metadata delivered with a presence snapshot. */
78
+ export type CollaborationPresenceSnapshotMetadata = {
79
+ selfClientId: string | null;
80
+ };
81
+ /** Stable, framework-neutral view of active collaboration sessions and deduplicated actors. */
82
+ export type CollaborationPresenceStoreSnapshot = {
83
+ selfClientId: string | null;
84
+ /** Every active browser/Agent session keyed by `clientId`. */
85
+ sessions: ICollaborationPresence[];
86
+ /** Sessions excluding only this exact browser client. */
87
+ remoteSessions: ICollaborationPresence[];
88
+ /** One entry per actor identity, including the local actor when supplied. */
89
+ collaborators: ICollaborationPresence[];
90
+ };
91
+ export type CollaborationPresenceStoreOptions = {
92
+ selfActor?: ICollaborationActor | null;
93
+ includeSelf?: boolean;
94
+ onChange?: (snapshot: CollaborationPresenceStoreSnapshot) => void;
95
+ };
96
+ /** Mutable presence projection used by plugin UIs without coupling them to a framework. */
97
+ export interface CollaborationPresenceStore {
98
+ setSelfClientId(clientId: string | null): void;
99
+ replace(items: ICollaborationPresence[], selfClientId?: string | null): void;
100
+ upsert(item: ICollaborationPresence): void;
101
+ remove(clientId: string): void;
102
+ clear(): void;
103
+ snapshot(): CollaborationPresenceStoreSnapshot;
104
+ }
105
+ /**
106
+ * Keep per-client sessions for cursors while exposing one collaborator per stable actor identity.
107
+ * This prevents a second tab owned by the same user from either duplicating or hiding that user.
108
+ */
109
+ export declare function createCollaborationPresenceStore(options?: CollaborationPresenceStoreOptions): CollaborationPresenceStore;
110
+ /**
111
+ * Create a collaboration client with update batching, state-vector repair, presence heartbeat,
112
+ * and reconnect synchronization. The caller retains ownership of the document and transport.
113
+ */
114
+ export declare function createCollaborationClient(options: CollaborationClientOptions): CollaborationClient;
115
+ /** Encode bytes in browsers without Node.js `Buffer`; chunks avoid argument-size limits. */
116
+ export declare function bytesToBase64(bytes: Uint8Array): string;
117
+ /** Decode base64 in browsers without requiring Node.js polyfills. */
118
+ export declare function base64ToBytes(value: string): Uint8Array;
@@ -0,0 +1,5 @@
1
+ export * from './types';
2
+ export * from './runtime-capability';
3
+ export * from './provider.decorator';
4
+ export * from './provider.registry';
5
+ export * from './client';
@@ -0,0 +1,3 @@
1
+ export declare const COLLABORATION_DOCUMENT_PROVIDER = "COLLABORATION_DOCUMENT_PROVIDER";
2
+ /** Register a plugin adapter for one stable collaboration resource type. */
3
+ export declare const CollaborationDocumentProvider: (providerKey: string) => <TFunction extends Function, Y>(target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void;
@@ -0,0 +1,7 @@
1
+ import { DiscoveryService, Reflector } from '@nestjs/core';
2
+ import { BaseStrategyRegistry } from '../strategy';
3
+ import type { ICollaborationDocumentProvider } from './types';
4
+ /** Discovers system and organization-scoped collaboration providers from loaded plugins. */
5
+ export declare class CollaborationDocumentProviderRegistry extends BaseStrategyRegistry<ICollaborationDocumentProvider> {
6
+ constructor(discoveryService: DiscoveryService, reflector: Reflector);
7
+ }
@@ -0,0 +1,3 @@
1
+ import type { CollaborationApi } from './types';
2
+ /** Platform-owned real-time collaboration capability available to scoped plugin runtimes. */
3
+ export declare const CollaborationRuntimeCapability: import("../core/runtime-capability").RuntimeCapabilityKey<CollaborationApi>;