@xpert-ai/plugin-sdk 3.15.10 → 3.15.12

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.cjs.js CHANGED
@@ -3,6 +3,7 @@
3
3
  var common = require('@nestjs/common');
4
4
  var constants = require('@nestjs/common/constants');
5
5
  var lodashEs = require('lodash-es');
6
+ var collaborationClient = require('./collaboration-client.cjs2.js');
6
7
  var core = require('@nestjs/core');
7
8
  var rxjs = require('rxjs');
8
9
  var contracts = require('@xpert-ai/contracts');
@@ -151,28 +152,17 @@ function resolveTenantGlobalScopeKey(tenantId) {
151
152
  return GLOBAL_ORGANIZATION_SCOPE;
152
153
  }
153
154
 
154
- function _extends() {
155
- _extends = Object.assign || function assign(target) {
156
- for(var i = 1; i < arguments.length; i++){
157
- var source = arguments[i];
158
- for(var key in source)if (Object.prototype.hasOwnProperty.call(source, key)) target[key] = source[key];
159
- }
160
- return target;
161
- };
162
- return _extends.apply(this, arguments);
163
- }
164
-
165
155
  function createPluginLogger(scope, baseMeta = {}) {
166
156
  const nestLogger = new common.Logger(scope);
167
157
  const wrap = (level, msg, meta)=>{
168
158
  var // Maintain alignment with the Nest Logger interface
169
159
  _nestLogger_level;
170
- const payload = meta ? _extends({}, baseMeta, meta) : baseMeta;
160
+ const payload = meta ? collaborationClient._extends({}, baseMeta, meta) : baseMeta;
171
161
  (_nestLogger_level = nestLogger[level]) == null ? void 0 : _nestLogger_level.call(nestLogger, msg + (Object.keys(payload).length ? ` ${JSON.stringify(payload)}` : ''));
172
162
  };
173
163
  return {
174
164
  child (meta) {
175
- return createPluginLogger(scope, _extends({}, baseMeta, meta));
165
+ return createPluginLogger(scope, collaborationClient._extends({}, baseMeta, meta));
176
166
  },
177
167
  debug: (msg, meta)=>wrap('debug', msg, meta),
178
168
  log: (msg, meta)=>wrap('log', msg, meta),
@@ -539,10 +529,12 @@ class BaseStrategyRegistry {
539
529
  }
540
530
  }
541
531
  upsert(instance) {
542
- const type = this.reflector.get(this.strategyKey, instance.constructor);
532
+ const target = resolveStrategyMetadataTarget(instance);
533
+ if (!target) {
534
+ return;
535
+ }
536
+ const type = this.reflector.get(this.strategyKey, target);
543
537
  if (type) {
544
- var _instance_metatype;
545
- const target = (_instance_metatype = instance.metatype) != null ? _instance_metatype : instance.constructor;
546
538
  const pluginName = this.reflector.get(PLUGIN_METADATA_KEY, target);
547
539
  var _this_reflector_get;
548
540
  const organizationId = (_this_reflector_get = this.reflector.get(ORGANIZATION_METADATA_KEY, target)) != null ? _this_reflector_get : pluginName ? GLOBAL_ORGANIZATION_SCOPE : BUILTIN_GLOBAL_SCOPE;
@@ -650,6 +642,23 @@ __decorate([
650
642
  common.Inject(exports.StrategyBus),
651
643
  __metadata("design:type", exports.StrategyBus)
652
644
  ], BaseStrategyRegistry.prototype, "bus", void 0);
645
+ /** Returns whether a discovered provider can carry decorator metadata. */ function isStrategyInstance(instance) {
646
+ return typeof instance === 'object' && instance !== null || typeof instance === 'function';
647
+ }
648
+ /** Resolves the class used for plugin and organization metadata without reflecting over primitive provider values. */ function resolveStrategyMetadataTarget(instance) {
649
+ if (!isStrategyInstance(instance)) {
650
+ return null;
651
+ }
652
+ if (typeof instance === 'function') {
653
+ return instance;
654
+ }
655
+ const metatype = instance.metatype;
656
+ if (typeof metatype === 'function') {
657
+ return metatype;
658
+ }
659
+ const constructor = instance.constructor;
660
+ return typeof constructor === 'function' ? constructor : null;
661
+ }
653
662
 
654
663
  exports.IntegrationStrategyRegistry = class IntegrationStrategyRegistry extends BaseStrategyRegistry {
655
664
  constructor(discoveryService, reflector){
@@ -1005,7 +1014,7 @@ class BuiltinToolset extends BaseToolset {
1005
1014
  *
1006
1015
  * @returns Credentials schema
1007
1016
  */ getCredentialsSchema() {
1008
- return _extends({}, this.credentialsSchema);
1017
+ return collaborationClient._extends({}, this.credentialsSchema);
1009
1018
  }
1010
1019
  /**
1011
1020
  * Get toolset entity
@@ -1318,7 +1327,7 @@ class JsonSchemaValidator {
1318
1327
  const PLUGIN_WEBHOOK_AUTH_METADATA_KEY = 'xpert:plugin:webhook-auth';
1319
1328
  const PLUGIN_WEBHOOK_AUTH_SERVICE_TOKEN = 'XPERT_PLUGIN_WEBHOOK_AUTH_SERVICE';
1320
1329
  function PluginWebhookAuth(metadata = {}) {
1321
- return common.SetMetadata(PLUGIN_WEBHOOK_AUTH_METADATA_KEY, _extends({
1330
+ return common.SetMetadata(PLUGIN_WEBHOOK_AUTH_METADATA_KEY, collaborationClient._extends({
1322
1331
  integrationParam: 'id',
1323
1332
  secretQueryParam: 'secret'
1324
1333
  }, metadata));
@@ -1352,7 +1361,7 @@ exports.PluginWebhookAuthGuard = class PluginWebhookAuthGuard {
1352
1361
  }
1353
1362
  request.user = principalContext.user;
1354
1363
  var _request_headers;
1355
- request.headers = _extends({}, (_request_headers = request.headers) != null ? _request_headers : {}, principalContext.headers);
1364
+ request.headers = collaborationClient._extends({}, (_request_headers = request.headers) != null ? _request_headers : {}, principalContext.headers);
1356
1365
  return true;
1357
1366
  }
1358
1367
  resolveMetadata(context) {
@@ -2067,7 +2076,7 @@ const CommonParameterRules = [
2067
2076
  }
2068
2077
  ];
2069
2078
  function mergeCredentials(credentials, modelProperties) {
2070
- return _extends({}, credentials != null ? credentials : {}, modelProperties != null ? modelProperties : {});
2079
+ return collaborationClient._extends({}, credentials != null ? credentials : {}, modelProperties != null ? modelProperties : {});
2071
2080
  }
2072
2081
 
2073
2082
  var AIModel_1;
@@ -2163,7 +2172,7 @@ let AIModel = AIModel_1 = class AIModel {
2163
2172
  try {
2164
2173
  const defaultParameterName = valueOf(DefaultParameterName, parameterRule.use_template);
2165
2174
  const defaultParameterRule = getDefaultParameterRuleVariableMap(defaultParameterName);
2166
- const copyDefaultParameterRule = _extends({}, defaultParameterRule, parameterRule);
2175
+ const copyDefaultParameterRule = collaborationClient._extends({}, defaultParameterRule, parameterRule);
2167
2176
  parameterRule = copyDefaultParameterRule;
2168
2177
  } catch (error) {
2169
2178
  // Handle error if necessary
@@ -2714,7 +2723,7 @@ class Speech2TextChatModel extends chat_models.BaseChatModel {
2714
2723
  if (!apiKey) {
2715
2724
  throw new Error(`Tongyi API key not found. Please set the DASHSCOPE_API_KEY environment variable or pass the key into "apiKey" field.`);
2716
2725
  }
2717
- super(_extends({}, fields));
2726
+ super(collaborationClient._extends({}, fields));
2718
2727
  this.fields = fields;
2719
2728
  this.apiKey = apiKey;
2720
2729
  }
@@ -2804,6 +2813,37 @@ const WorkspaceFilesRuntimeCapability = createRuntimeCapability('platform.worksp
2804
2813
  description: 'Upload, understand, read, and delete raw files in Xpert workspace volumes.'
2805
2814
  });
2806
2815
 
2816
+ /** Stable machine-readable failures emitted by the Sandbox Jobs capability. */ const SANDBOX_JOB_ERROR_CODES = [
2817
+ 'SANDBOX_ACTION_UNAVAILABLE',
2818
+ 'SANDBOX_ACTION_INVALID',
2819
+ 'SANDBOX_PROFILE_UNAVAILABLE',
2820
+ 'SANDBOX_RUNTIME_UNAVAILABLE',
2821
+ 'SANDBOX_VERSION_MISMATCH',
2822
+ 'SANDBOX_CAPACITY_UNAVAILABLE',
2823
+ 'SANDBOX_START_FAILED',
2824
+ 'BROWSER_LAUNCH_FAILED',
2825
+ 'EXPORT_TIMEOUT',
2826
+ 'EXPORT_OOM',
2827
+ 'EXPORT_INPUT_INVALID',
2828
+ 'EXPORT_OUTPUT_INVALID',
2829
+ 'SANDBOX_CANCELLED'
2830
+ ];
2831
+ /** Error carrying retry policy and Job identity across plugin queue handlers. */ class SandboxJobRuntimeError extends Error {
2832
+ constructor(code, message, retryable, jobId){
2833
+ super(message);
2834
+ this.code = code;
2835
+ this.retryable = retryable;
2836
+ this.jobId = jobId;
2837
+ this.name = 'SandboxJobRuntimeError';
2838
+ }
2839
+ }
2840
+ /** Narrows an unknown failure to the structured Sandbox Jobs runtime error contract. */ function isSandboxJobRuntimeError(error) {
2841
+ return error instanceof SandboxJobRuntimeError;
2842
+ }
2843
+ /** Runtime capability key used to resolve SandboxJobsApi from the platform registry. */ const SandboxJobsRuntimeCapability = createRuntimeCapability('platform.sandbox.jobs', {
2844
+ description: 'Run registered plugin actions in isolated, short-lived Sandbox Runtime jobs.'
2845
+ });
2846
+
2807
2847
  const SKILL_SOURCE_PROVIDER = 'SKILL_SOURCE_PROVIDER';
2808
2848
  const SkillSourceProviderStrategy = (provider)=>common.applyDecorators(common.SetMetadata(SKILL_SOURCE_PROVIDER, provider), common.SetMetadata(STRATEGY_META_KEY, SKILL_SOURCE_PROVIDER));
2809
2849
 
@@ -4169,6 +4209,76 @@ function resolveSandboxTerminalAdapter(sandbox) {
4169
4209
  return isSandboxTerminalAdapter(candidate) ? candidate : null;
4170
4210
  }
4171
4211
 
4212
+ const SANDBOX_RUNTIME_PROVIDER = 'SANDBOX_RUNTIME_PROVIDER';
4213
+ /** Marks a built-in or system-plugin class as a named Sandbox Runtime Provider strategy. */ const SandboxRuntimeProviderStrategy = (provider)=>common.applyDecorators(common.SetMetadata(SANDBOX_RUNTIME_PROVIDER, provider), common.SetMetadata(STRATEGY_META_KEY, SANDBOX_RUNTIME_PROVIDER));
4214
+
4215
+ var SandboxRuntimeProviderRegistry_1;
4216
+ /** Discovers Runtime Provider strategies and rejects organization-scoped executable infrastructure. */ exports.SandboxRuntimeProviderRegistry = SandboxRuntimeProviderRegistry_1 = class SandboxRuntimeProviderRegistry extends BaseStrategyRegistry {
4217
+ upsert(instance) {
4218
+ const target = resolveStrategyMetadataTarget(instance);
4219
+ if (!target) {
4220
+ return;
4221
+ }
4222
+ if (!this.reflector.get(SANDBOX_RUNTIME_PROVIDER, target)) {
4223
+ return;
4224
+ }
4225
+ const pluginName = this.reflector.get(PLUGIN_METADATA_KEY, target);
4226
+ var _this_reflector_get;
4227
+ const scope = (_this_reflector_get = this.reflector.get(ORGANIZATION_METADATA_KEY, target)) != null ? _this_reflector_get : BUILTIN_GLOBAL_SCOPE;
4228
+ if (pluginName && scope !== SYSTEM_GLOBAL_SCOPE) {
4229
+ this.runtimeLogger.warn(`Ignored Sandbox Runtime Provider from non-system plugin ${pluginName} in scope ${scope}.`);
4230
+ return;
4231
+ }
4232
+ super.upsert(instance);
4233
+ }
4234
+ constructor(discoveryService, reflector){
4235
+ super(SANDBOX_RUNTIME_PROVIDER, discoveryService, reflector);
4236
+ this.runtimeLogger = new common.Logger(SandboxRuntimeProviderRegistry_1.name);
4237
+ }
4238
+ };
4239
+ exports.SandboxRuntimeProviderRegistry = SandboxRuntimeProviderRegistry_1 = __decorate([
4240
+ common.Injectable(),
4241
+ __metadata("design:paramtypes", [
4242
+ core.DiscoveryService,
4243
+ core.Reflector
4244
+ ])
4245
+ ], exports.SandboxRuntimeProviderRegistry);
4246
+
4247
+ const SANDBOX_WORKSPACE_MAPPER = 'SANDBOX_WORKSPACE_MAPPER';
4248
+ /** Associates a workspace path mapper with a named Runtime Provider strategy. */ const SandboxWorkspaceMapperStrategy = (provider)=>common.applyDecorators(common.SetMetadata(SANDBOX_WORKSPACE_MAPPER, provider), common.SetMetadata(STRATEGY_META_KEY, SANDBOX_WORKSPACE_MAPPER));
4249
+
4250
+ var SandboxWorkspaceMapperRegistry_1;
4251
+ /** Discovers Provider path mappers while enforcing the same system-level trust boundary as Providers. */ exports.SandboxWorkspaceMapperRegistry = SandboxWorkspaceMapperRegistry_1 = class SandboxWorkspaceMapperRegistry extends BaseStrategyRegistry {
4252
+ upsert(instance) {
4253
+ const target = resolveStrategyMetadataTarget(instance);
4254
+ if (!target) {
4255
+ return;
4256
+ }
4257
+ if (!this.reflector.get(SANDBOX_WORKSPACE_MAPPER, target)) {
4258
+ return;
4259
+ }
4260
+ const pluginName = this.reflector.get(PLUGIN_METADATA_KEY, target);
4261
+ var _this_reflector_get;
4262
+ const scope = (_this_reflector_get = this.reflector.get(ORGANIZATION_METADATA_KEY, target)) != null ? _this_reflector_get : BUILTIN_GLOBAL_SCOPE;
4263
+ if (pluginName && scope !== SYSTEM_GLOBAL_SCOPE) {
4264
+ this.mapperLogger.warn(`Ignored Sandbox Workspace Mapper from non-system plugin ${pluginName} in scope ${scope}.`);
4265
+ return;
4266
+ }
4267
+ super.upsert(instance);
4268
+ }
4269
+ constructor(discoveryService, reflector){
4270
+ super(SANDBOX_WORKSPACE_MAPPER, discoveryService, reflector);
4271
+ this.mapperLogger = new common.Logger(SandboxWorkspaceMapperRegistry_1.name);
4272
+ }
4273
+ };
4274
+ exports.SandboxWorkspaceMapperRegistry = SandboxWorkspaceMapperRegistry_1 = __decorate([
4275
+ common.Injectable(),
4276
+ __metadata("design:paramtypes", [
4277
+ core.DiscoveryService,
4278
+ core.Reflector
4279
+ ])
4280
+ ], exports.SandboxWorkspaceMapperRegistry);
4281
+
4172
4282
  const MANAGED_CONNECTION_REGISTRY_TOKEN = 'XPERT_MANAGED_CONNECTION_REGISTRY';
4173
4283
  const CONNECTION_COMMAND_ROUTER_TOKEN = 'XPERT_CONNECTION_COMMAND_ROUTER';
4174
4284
 
@@ -4196,7 +4306,7 @@ function normalizePluginJobProcessorMetadata(options) {
4196
4306
  if (concurrency !== undefined && (!Number.isFinite(concurrency) || concurrency <= 0)) {
4197
4307
  throw new Error('PluginJobProcessor concurrency must be a positive number');
4198
4308
  }
4199
- return _extends({
4309
+ return collaborationClient._extends({
4200
4310
  pluginName,
4201
4311
  queueName,
4202
4312
  jobName
@@ -4710,392 +4820,12 @@ exports.CollaborationDocumentProviderRegistry = __decorate([
4710
4820
  ])
4711
4821
  ], exports.CollaborationDocumentProviderRegistry);
4712
4822
 
4713
- function createSocketIoTransportAdapter(socket) {
4714
- return {
4715
- get connected () {
4716
- return socket.connected;
4717
- },
4718
- get clientId () {
4719
- var _socket_id;
4720
- return (_socket_id = socket.id) != null ? _socket_id : null;
4721
- },
4722
- connect: ()=>{
4723
- socket.connect();
4724
- },
4725
- disconnect: ()=>{
4726
- socket.disconnect();
4727
- },
4728
- emit: (event, payload = {})=>{
4729
- socket.emit(event, payload);
4730
- },
4731
- on: (event, handler)=>{
4732
- socket.on(event, handler);
4733
- return ()=>{
4734
- socket.off(event, handler);
4735
- };
4736
- }
4737
- };
4738
- }
4739
- /** Wrap a caller-owned `Y.Doc` without passing it across the runtime capability boundary. */ function createYjsDocumentAdapter(document, yjs) {
4740
- return {
4741
- applyUpdate: (update, origin)=>yjs.applyUpdate(document, update, origin),
4742
- encodeStateVector: ()=>yjs.encodeStateVector(document),
4743
- mergeUpdates: (updates)=>yjs.mergeUpdates(updates),
4744
- onUpdate: (handler)=>{
4745
- document.on('update', handler);
4746
- return ()=>document.off('update', handler);
4747
- }
4748
- };
4749
- }
4750
- /**
4751
- * Keep per-client sessions for cursors while exposing one collaborator per stable actor identity.
4752
- * This prevents a second tab owned by the same user from either duplicating or hiding that user.
4753
- */ function createCollaborationPresenceStore(options = {}) {
4754
- let selfClientId = null;
4755
- let sessions = new Map();
4756
- const readSnapshot = ()=>{
4757
- const activeSessions = Array.from(sessions.values()).sort((left, right)=>right.updatedAt - left.updatedAt);
4758
- const remoteSessions = activeSessions.filter((item)=>item.clientId !== selfClientId);
4759
- const actors = new Map();
4760
- for (const item of activeSessions)if (!actors.has(item.presenceId)) actors.set(item.presenceId, item);
4761
- if (options.includeSelf !== false && options.selfActor) {
4762
- const existing = activeSessions.find((item)=>{
4763
- var _options_selfActor;
4764
- return item.clientId === selfClientId || item.presenceId === ((_options_selfActor = options.selfActor) == null ? void 0 : _options_selfActor.presenceId);
4765
- });
4766
- actors.set(options.selfActor.presenceId, existing != null ? existing : actorPresence(options.selfActor, selfClientId));
4767
- }
4768
- const collaborators = Array.from(actors.values()).sort((left, right)=>{
4769
- var _options_selfActor, _options_selfActor1;
4770
- const leftSelf = left.presenceId === ((_options_selfActor = options.selfActor) == null ? void 0 : _options_selfActor.presenceId) ? 1 : 0;
4771
- const rightSelf = right.presenceId === ((_options_selfActor1 = options.selfActor) == null ? void 0 : _options_selfActor1.presenceId) ? 1 : 0;
4772
- return rightSelf - leftSelf || right.updatedAt - left.updatedAt;
4773
- });
4774
- return {
4775
- selfClientId,
4776
- sessions: activeSessions,
4777
- remoteSessions,
4778
- collaborators
4779
- };
4780
- };
4781
- const publish = ()=>options.onChange == null ? void 0 : options.onChange.call(options, readSnapshot());
4782
- return {
4783
- setSelfClientId: (clientId)=>{
4784
- selfClientId = clientId;
4785
- publish();
4786
- },
4787
- replace: (items, clientId = selfClientId)=>{
4788
- selfClientId = clientId;
4789
- sessions = new Map(items.map((item)=>[
4790
- item.clientId,
4791
- item
4792
- ]));
4793
- publish();
4794
- },
4795
- upsert: (item)=>{
4796
- sessions.set(item.clientId, item);
4797
- publish();
4798
- },
4799
- remove: (clientId)=>{
4800
- if (sessions.delete(clientId)) publish();
4801
- },
4802
- clear: ()=>{
4803
- sessions.clear();
4804
- selfClientId = null;
4805
- publish();
4806
- },
4807
- snapshot: readSnapshot
4808
- };
4809
- }
4810
- /**
4811
- * Create a collaboration client with update batching, state-vector repair, presence heartbeat,
4812
- * and reconnect synchronization. The caller retains ownership of the document and transport.
4813
- */ function createCollaborationClient(options) {
4814
- const remoteOrigin = Object.freeze({
4815
- kind: 'platform.collaboration.remote'
4816
- });
4817
- const batchMs = positiveInteger(options.batchMs, 40);
4818
- const syncIntervalMs = positiveInteger(options.syncIntervalMs, 2000);
4819
- const presenceHeartbeatMs = positiveInteger(options.presenceHeartbeatMs, 5000);
4820
- const presenceStaleMs = positiveInteger(options.presenceStaleMs, 15000);
4821
- var _options_initialPresence;
4822
- let presence = _extends({}, (_options_initialPresence = options.initialPresence) != null ? _options_initialPresence : {});
4823
- let pending = [];
4824
- let flushTimer;
4825
- let syncTimer;
4826
- let presenceTimer;
4827
- let presenceCleanupTimer;
4828
- var _options_transport_clientId;
4829
- let selfClientId = (_options_transport_clientId = options.transport.clientId) != null ? _options_transport_clientId : null;
4830
- let started = false;
4831
- const cleanups = [];
4832
- const presenceSeenAt = new Map();
4833
- const reportError = (error)=>options.onError == null ? void 0 : options.onError.call(options, error instanceof Error ? error : new Error(String(error)));
4834
- const emitPresence = ()=>options.transport.emit('presence', _extends({}, presence));
4835
- // Merge the short burst of local Yjs transactions into one network update.
4836
- const flush = ()=>{
4837
- if (flushTimer) clearTimeout(flushTimer);
4838
- flushTimer = undefined;
4839
- if (!pending.length || !options.transport.connected) return;
4840
- const updates = pending;
4841
- pending = [];
4842
- options.transport.emit('update', {
4843
- updateBase64: bytesToBase64(options.document.mergeUpdates(updates)),
4844
- origin: 'plugin-client'
4845
- });
4846
- };
4847
- // A state vector lets the server return only bytes missing from this client.
4848
- const requestSync = ()=>{
4849
- if (!options.transport.connected) return;
4850
- options.transport.emit('sync-request', {
4851
- stateVectorBase64: bytesToBase64(options.document.encodeStateVector())
4852
- });
4853
- };
4854
- // Mark server updates with `remoteOrigin` so the document observer does not send them back.
4855
- const applyRemote = (payload)=>{
4856
- const encoded = stringValue(payload['updateBase64']);
4857
- if (!encoded) return;
4858
- try {
4859
- options.document.applyUpdate(base64ToBytes(encoded), remoteOrigin);
4860
- } catch (error) {
4861
- reportError(error);
4862
- }
4863
- };
4864
- // Register listeners once, then start repair and presence heartbeats before opening the socket.
4865
- const connect = ()=>{
4866
- if (started) return;
4867
- started = true;
4868
- options.onConnectionChange == null ? void 0 : options.onConnectionChange.call(options, 'connecting');
4869
- cleanups.push(options.document.onUpdate((update, origin)=>{
4870
- if (origin === remoteOrigin) return;
4871
- pending.push(update);
4872
- if (!flushTimer) flushTimer = setTimeout(flush, batchMs);
4873
- }));
4874
- cleanups.push(options.transport.on('connect', ()=>{
4875
- var _options_transport_clientId;
4876
- selfClientId = (_options_transport_clientId = options.transport.clientId) != null ? _options_transport_clientId : selfClientId;
4877
- options.onConnectionChange == null ? void 0 : options.onConnectionChange.call(options, 'connected');
4878
- requestSync();
4879
- emitPresence();
4880
- }));
4881
- cleanups.push(options.transport.on('disconnect', ()=>options.onConnectionChange == null ? void 0 : options.onConnectionChange.call(options, 'disconnected')));
4882
- cleanups.push(options.transport.on('sync', applyRemote));
4883
- cleanups.push(options.transport.on('update', applyRemote));
4884
- cleanups.push(options.transport.on('update-ack', (payload)=>{
4885
- const ack = parseAck(payload);
4886
- if (ack) options.onAck == null ? void 0 : options.onAck.call(options, ack);
4887
- }));
4888
- cleanups.push(options.transport.on('presence', (payload)=>{
4889
- const item = parsePresence(payload);
4890
- if (item) {
4891
- presenceSeenAt.set(item.clientId, Date.now());
4892
- options.onPresence == null ? void 0 : options.onPresence.call(options, item);
4893
- }
4894
- }));
4895
- cleanups.push(options.transport.on('presence-snapshot', (payload)=>{
4896
- const rawItems = payload['items'];
4897
- const items = Array.isArray(rawItems) ? rawItems.map(parsePresence).filter(isPresence) : [];
4898
- var _stringValue, _ref;
4899
- selfClientId = (_ref = (_stringValue = stringValue(payload['selfClientId'])) != null ? _stringValue : options.transport.clientId) != null ? _ref : selfClientId;
4900
- presenceSeenAt.clear();
4901
- for (const item of items)presenceSeenAt.set(item.clientId, Date.now());
4902
- options.onPresenceSnapshot == null ? void 0 : options.onPresenceSnapshot.call(options, items, {
4903
- selfClientId
4904
- });
4905
- }));
4906
- cleanups.push(options.transport.on('presence-remove', (payload)=>{
4907
- const clientId = stringValue(payload['clientId']);
4908
- if (clientId) {
4909
- presenceSeenAt.delete(clientId);
4910
- options.onPresenceRemove == null ? void 0 : options.onPresenceRemove.call(options, clientId);
4911
- }
4912
- }));
4913
- cleanups.push(options.transport.on('error', (payload)=>{
4914
- var _stringValue;
4915
- return reportError((_stringValue = stringValue(payload['message'])) != null ? _stringValue : 'Collaboration failed.');
4916
- }));
4917
- syncTimer = setInterval(requestSync, syncIntervalMs);
4918
- presenceTimer = setInterval(emitPresence, presenceHeartbeatMs);
4919
- presenceCleanupTimer = setInterval(()=>{
4920
- const cutoff = Date.now() - presenceStaleMs;
4921
- for (const [clientId, seenAt] of presenceSeenAt){
4922
- if (clientId === selfClientId || seenAt >= cutoff) continue;
4923
- presenceSeenAt.delete(clientId);
4924
- options.onPresenceRemove == null ? void 0 : options.onPresenceRemove.call(options, clientId);
4925
- }
4926
- }, Math.min(5000, Math.max(1000, Math.floor(presenceStaleMs / 3))));
4927
- options.transport.connect();
4928
- };
4929
- // Flush best-effort pending state and release all timers/listeners owned by this client.
4930
- const disconnect = ()=>{
4931
- var _cleanups_pop;
4932
- if (!started) return;
4933
- flush();
4934
- started = false;
4935
- if (flushTimer) clearTimeout(flushTimer);
4936
- if (syncTimer) clearInterval(syncTimer);
4937
- if (presenceTimer) clearInterval(presenceTimer);
4938
- if (presenceCleanupTimer) clearInterval(presenceCleanupTimer);
4939
- flushTimer = undefined;
4940
- syncTimer = undefined;
4941
- presenceTimer = undefined;
4942
- presenceCleanupTimer = undefined;
4943
- presenceSeenAt.clear();
4944
- while(cleanups.length)(_cleanups_pop = cleanups.pop()) == null ? void 0 : _cleanups_pop();
4945
- options.transport.disconnect();
4946
- options.onConnectionChange == null ? void 0 : options.onConnectionChange.call(options, 'disconnected');
4947
- };
4948
- return {
4949
- get selfClientId () {
4950
- return selfClientId;
4951
- },
4952
- remoteOrigin,
4953
- connect,
4954
- disconnect,
4955
- flush,
4956
- requestSync,
4957
- setPresence: (patch)=>{
4958
- presence = _extends({}, presence, patch);
4959
- if (options.transport.connected) emitPresence();
4960
- }
4961
- };
4962
- }
4963
- function actorPresence(actor, clientId) {
4964
- return _extends({}, actor, {
4965
- clientId: clientId != null ? clientId : `self:${actor.presenceId}`,
4966
- pageId: null,
4967
- pointer: null,
4968
- focus: null,
4969
- selection: null,
4970
- viewport: null,
4971
- mode: null,
4972
- status: null,
4973
- toolName: null,
4974
- operationLabel: null,
4975
- updatedAt: Date.now()
4976
- });
4977
- }
4978
- /** Encode bytes in browsers without Node.js `Buffer`; chunks avoid argument-size limits. */ function bytesToBase64(bytes) {
4979
- let binary = '';
4980
- const chunkSize = 0x8000;
4981
- for(let offset = 0; offset < bytes.length; offset += chunkSize){
4982
- binary += String.fromCharCode(...bytes.subarray(offset, Math.min(offset + chunkSize, bytes.length)));
4983
- }
4984
- return globalThis.btoa(binary);
4985
- }
4986
- /** Decode base64 in browsers without requiring Node.js polyfills. */ function base64ToBytes(value) {
4987
- const binary = globalThis.atob(value);
4988
- const bytes = new Uint8Array(binary.length);
4989
- for(let index = 0; index < binary.length; index += 1)bytes[index] = binary.charCodeAt(index);
4990
- return bytes;
4991
- }
4992
- function parseAck(payload) {
4993
- const documentId = stringValue(payload['documentId']);
4994
- const stateVectorBase64 = stringValue(payload['stateVectorBase64']);
4995
- const sequenceNumber = payload['sequenceNumber'];
4996
- if (!documentId || !stateVectorBase64 || typeof sequenceNumber !== 'number') return null;
4997
- const materializationStatus = payload['materializationStatus'];
4998
- if (materializationStatus !== 'ready' && materializationStatus !== 'pending' && materializationStatus !== 'failed') return null;
4999
- return {
5000
- documentId,
5001
- duplicate: payload['duplicate'] === true,
5002
- sequenceNumber,
5003
- updateId: stringValue(payload['updateId']),
5004
- stateVectorBase64,
5005
- materializationStatus
5006
- };
5007
- }
5008
- function parsePresence(value) {
5009
- if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
5010
- const item = value;
5011
- const clientId = stringValue(item['clientId']);
5012
- const presenceId = stringValue(item['presenceId']);
5013
- const displayName = stringValue(item['displayName']);
5014
- const color = stringValue(item['color']);
5015
- const actorType = item['actorType'];
5016
- if (!clientId || !presenceId || !displayName || !color || actorType !== 'user' && actorType !== 'agent' && actorType !== 'system') return null;
5017
- return {
5018
- clientId,
5019
- presenceId,
5020
- displayName,
5021
- color,
5022
- actorType,
5023
- avatarUrl: nullableString(item['avatarUrl']),
5024
- pageId: nullableString(item['pageId']),
5025
- pointer: parsePointer(item['pointer']),
5026
- focus: parseFocus(item['focus']),
5027
- selection: parseSelection(item['selection']),
5028
- viewport: parseViewport(item['viewport']),
5029
- mode: nullableString(item['mode']),
5030
- status: actorStatus(item['status']),
5031
- toolName: nullableString(item['toolName']),
5032
- operationLabel: nullableString(item['operationLabel']),
5033
- updatedAt: typeof item['updatedAt'] === 'number' ? item['updatedAt'] : Date.now()
5034
- };
5035
- }
5036
- function parsePointer(value) {
5037
- const item = recordValue(value);
5038
- if (!item || typeof item['x'] !== 'number' || typeof item['y'] !== 'number') return null;
5039
- return {
5040
- pageId: nullableString(item['pageId']),
5041
- x: item['x'],
5042
- y: item['y'],
5043
- visible: item['visible'] !== false
5044
- };
5045
- }
5046
- function parseFocus(value) {
5047
- const item = recordValue(value);
5048
- const kind = item && stringValue(item['kind']);
5049
- if (!item || !kind) return null;
5050
- return {
5051
- kind,
5052
- key: nullableString(item['key']),
5053
- pageId: nullableString(item['pageId']),
5054
- elementId: nullableString(item['elementId']),
5055
- fieldKey: nullableString(item['fieldKey'])
5056
- };
5057
- }
5058
- function parseSelection(value) {
5059
- const item = recordValue(value);
5060
- const kind = item == null ? void 0 : item['kind'];
5061
- if (!item || kind !== 'text' && kind !== 'elements') return null;
5062
- return {
5063
- kind,
5064
- fieldKey: nullableString(item['fieldKey']),
5065
- elementIds: Array.isArray(item['elementIds']) ? item['elementIds'].filter((entry)=>typeof entry === 'string') : null,
5066
- anchorRelativeBase64: nullableString(item['anchorRelativeBase64']),
5067
- headRelativeBase64: nullableString(item['headRelativeBase64'])
5068
- };
5069
- }
5070
- function parseViewport(value) {
5071
- const item = recordValue(value);
5072
- if (!item || typeof item['zoom'] !== 'number' || typeof item['width'] !== 'number' || typeof item['height'] !== 'number') return null;
5073
- return {
5074
- zoom: item['zoom'],
5075
- width: item['width'],
5076
- height: item['height']
5077
- };
5078
- }
5079
- function recordValue(value) {
5080
- return value && typeof value === 'object' && !Array.isArray(value) ? value : null;
5081
- }
5082
- function isPresence(value) {
5083
- return value !== null;
5084
- }
5085
- function stringValue(value) {
5086
- return typeof value === 'string' && value.trim() ? value.trim() : undefined;
5087
- }
5088
- function nullableString(value) {
5089
- var _stringValue;
5090
- return (_stringValue = stringValue(value)) != null ? _stringValue : null;
5091
- }
5092
- function actorStatus(value) {
5093
- return value === 'thinking' || value === 'editing' || value === 'done' || value === 'failed' ? value : null;
5094
- }
5095
- function positiveInteger(value, fallback) {
5096
- return Number.isFinite(value) && Number(value) > 0 ? Math.trunc(Number(value)) : fallback;
5097
- }
5098
-
4823
+ exports.base64ToBytes = collaborationClient.base64ToBytes;
4824
+ exports.bytesToBase64 = collaborationClient.bytesToBase64;
4825
+ exports.createCollaborationClient = collaborationClient.createCollaborationClient;
4826
+ exports.createCollaborationPresenceStore = collaborationClient.createCollaborationPresenceStore;
4827
+ exports.createSocketIoTransportAdapter = collaborationClient.createSocketIoTransportAdapter;
4828
+ exports.createYjsDocumentAdapter = collaborationClient.createYjsDocumentAdapter;
5099
4829
  Object.defineProperty(exports, "ASSISTANT_CHAT_SEND_MESSAGE_COMMAND", {
5100
4830
  enumerable: true,
5101
4831
  get: function () { return contracts.ASSISTANT_CHAT_SEND_MESSAGE_COMMAND; }
@@ -5208,8 +4938,11 @@ exports.RequestContext = RequestContext;
5208
4938
  exports.RequirePermissionOperation = RequirePermissionOperation;
5209
4939
  exports.RerankModel = RerankModel;
5210
4940
  exports.RetrieverStrategy = RetrieverStrategy;
4941
+ exports.SANDBOX_JOB_ERROR_CODES = SANDBOX_JOB_ERROR_CODES;
5211
4942
  exports.SANDBOX_PROVIDER = SANDBOX_PROVIDER;
4943
+ exports.SANDBOX_RUNTIME_PROVIDER = SANDBOX_RUNTIME_PROVIDER;
5212
4944
  exports.SANDBOX_SHELL_TIMEOUT_LIMITS_SEC = SANDBOX_SHELL_TIMEOUT_LIMITS_SEC;
4945
+ exports.SANDBOX_WORKSPACE_MAPPER = SANDBOX_WORKSPACE_MAPPER;
5213
4946
  exports.SKILL_SOURCE_PROVIDER = SKILL_SOURCE_PROVIDER;
5214
4947
  exports.SPEECH_TO_TEXT_PERMISSION_SERVICE_TOKEN = SPEECH_TO_TEXT_PERMISSION_SERVICE_TOKEN;
5215
4948
  exports.SPEECH_TO_TEXT_SERVICE_TOKEN = SPEECH_TO_TEXT_SERVICE_TOKEN;
@@ -5218,7 +4951,11 @@ exports.SSO_BINDING_PERMISSION_SERVICE_TOKEN = SSO_BINDING_PERMISSION_SERVICE_TO
5218
4951
  exports.SSO_PROVIDER = SSO_PROVIDER;
5219
4952
  exports.STRATEGY_META_KEY = STRATEGY_META_KEY;
5220
4953
  exports.SYSTEM_GLOBAL_SCOPE = SYSTEM_GLOBAL_SCOPE;
4954
+ exports.SandboxJobRuntimeError = SandboxJobRuntimeError;
4955
+ exports.SandboxJobsRuntimeCapability = SandboxJobsRuntimeCapability;
5221
4956
  exports.SandboxProviderStrategy = SandboxProviderStrategy;
4957
+ exports.SandboxRuntimeProviderStrategy = SandboxRuntimeProviderStrategy;
4958
+ exports.SandboxWorkspaceMapperStrategy = SandboxWorkspaceMapperStrategy;
5222
4959
  exports.SkillSourceProviderStrategy = SkillSourceProviderStrategy;
5223
4960
  exports.Speech2TextChatModel = Speech2TextChatModel;
5224
4961
  exports.SpeechToTextModel = SpeechToTextModel;
@@ -5248,19 +4985,13 @@ exports.XpFileSystem = XpFileSystem;
5248
4985
  exports.XpertServerPlugin = XpertServerPlugin;
5249
4986
  exports.als = als;
5250
4987
  exports.appendSandboxMessage = appendSandboxMessage;
5251
- exports.base64ToBytes = base64ToBytes;
5252
4988
  exports.buildSandboxTimeoutMessage = buildSandboxTimeoutMessage;
5253
- exports.bytesToBase64 = bytesToBase64;
5254
4989
  exports.calcTokenUsage = calcTokenUsage;
5255
4990
  exports.chunkText = chunkText;
5256
4991
  exports.countTokensSafe = countTokensSafe;
5257
- exports.createCollaborationClient = createCollaborationClient;
5258
- exports.createCollaborationPresenceStore = createCollaborationPresenceStore;
5259
4992
  exports.createI18nInstance = createI18nInstance;
5260
4993
  exports.createPluginLogger = createPluginLogger;
5261
4994
  exports.createRuntimeCapability = createRuntimeCapability;
5262
- exports.createSocketIoTransportAdapter = createSocketIoTransportAdapter;
5263
- exports.createYjsDocumentAdapter = createYjsDocumentAdapter;
5264
4995
  exports.defineAgentMessageType = defineAgentMessageType;
5265
4996
  exports.defineChannelMessageType = defineChannelMessageType;
5266
4997
  exports.derivePluginArtifactNamespace = derivePluginArtifactNamespace;
@@ -5277,9 +5008,11 @@ exports.getRequiredPermissionOperation = getRequiredPermissionOperation;
5277
5008
  exports.getTenantGlobalScopeKey = getTenantGlobalScopeKey;
5278
5009
  exports.isRemoteFile = isRemoteFile;
5279
5010
  exports.isSandboxBackend = isSandboxBackend;
5011
+ exports.isSandboxJobRuntimeError = isSandboxJobRuntimeError;
5280
5012
  exports.isSandboxManagedServiceAdapter = isSandboxManagedServiceAdapter;
5281
5013
  exports.isSandboxServiceProxyAdapter = isSandboxServiceProxyAdapter;
5282
5014
  exports.isSandboxTerminalAdapter = isSandboxTerminalAdapter;
5015
+ exports.isStrategyInstance = isStrategyInstance;
5283
5016
  exports.isStructuredMessageType = isStructuredMessageType;
5284
5017
  exports.isTenantGlobalScopeKey = isTenantGlobalScopeKey;
5285
5018
  exports.loadYamlFile = loadYamlFile;
@@ -5295,6 +5028,7 @@ exports.resolveSandboxExecutionOptions = resolveSandboxExecutionOptions;
5295
5028
  exports.resolveSandboxManagedServiceAdapter = resolveSandboxManagedServiceAdapter;
5296
5029
  exports.resolveSandboxServiceProxyAdapter = resolveSandboxServiceProxyAdapter;
5297
5030
  exports.resolveSandboxTerminalAdapter = resolveSandboxTerminalAdapter;
5031
+ exports.resolveStrategyMetadataTarget = resolveStrategyMetadataTarget;
5298
5032
  exports.resolveTenantGlobalScopeKey = resolveTenantGlobalScopeKey;
5299
5033
  exports.runWithRequestContext = runWithRequestContext;
5300
5034
  exports.secondsToMilliseconds = secondsToMilliseconds;