@xpert-ai/plugin-sdk 3.7.2 → 3.8.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.
Files changed (39) hide show
  1. package/index.cjs.js +773 -0
  2. package/index.esm.js +747 -1
  3. package/package.json +2 -1
  4. package/src/index.d.ts +2 -0
  5. package/src/lib/agent/handoff/agent-chat.contract.d.ts +20 -0
  6. package/src/lib/agent/handoff/handoff-processor.decorator.d.ts +11 -0
  7. package/src/lib/agent/handoff/handoff-processor.registry.d.ts +6 -0
  8. package/src/lib/agent/handoff/handoff.interface.d.ts +17 -0
  9. package/src/lib/agent/handoff/index.d.ts +6 -0
  10. package/src/lib/agent/handoff/message-type.d.ts +24 -0
  11. package/src/lib/agent/handoff/types.d.ts +110 -0
  12. package/src/lib/agent/index.d.ts +1 -0
  13. package/src/lib/agent/middleware/runtime.d.ts +2 -0
  14. package/src/lib/agent/middleware/strategy.interface.d.ts +5 -1
  15. package/src/lib/agent/middleware/types.d.ts +2 -2
  16. package/src/lib/ai-model/utils/index.d.ts +1 -0
  17. package/src/lib/ai-model/utils/limits.d.ts +4 -0
  18. package/src/lib/channel/cancel-conversation.command.d.ts +14 -0
  19. package/src/lib/channel/index.d.ts +4 -0
  20. package/src/lib/channel/strategy.decorator.d.ts +23 -0
  21. package/src/lib/channel/strategy.interface.d.ts +345 -0
  22. package/src/lib/channel/strategy.registry.d.ts +30 -0
  23. package/src/lib/core/permissions/analytics.d.ts +46 -0
  24. package/src/lib/core/{permissions.d.ts → permissions/general.d.ts} +9 -12
  25. package/src/lib/core/permissions/handoff.d.ts +36 -0
  26. package/src/lib/core/permissions/index.d.ts +24 -0
  27. package/src/lib/core/permissions/operation.d.ts +8 -0
  28. package/src/lib/core/permissions/user.d.ts +29 -0
  29. package/src/lib/integration/strategy.interface.d.ts +3 -1
  30. package/src/lib/sandbox/index.d.ts +8 -0
  31. package/src/lib/sandbox/protocol.d.ts +265 -0
  32. package/src/lib/sandbox/sandbox.d.ts +70 -0
  33. package/src/lib/sandbox/sandbox.decorator.d.ts +2 -0
  34. package/src/lib/sandbox/sandbox.interface.d.ts +38 -0
  35. package/src/lib/sandbox/sandbox.registry.d.ts +6 -0
  36. package/src/lib/toolset/strategy.interface.d.ts +2 -6
  37. package/src/lib/types.d.ts +7 -1
  38. package/src/lib/workflow/node/strategy.interface.d.ts +4 -2
  39. package/src/lib/workflow/trigger/strategy.interface.d.ts +13 -0
package/index.cjs.js CHANGED
@@ -30,6 +30,7 @@ var chat_models = require('@langchain/core/language_models/chat_models');
30
30
  var messages = require('@langchain/core/messages');
31
31
  var env = require('@langchain/core/utils/env');
32
32
  require('js-tiktoken');
33
+ var base = require('@langchain/core/language_models/base');
33
34
 
34
35
  function _interopNamespaceDefault(e) {
35
36
  var n = Object.create(null);
@@ -951,6 +952,52 @@ BuiltinToolset.provider = '';
951
952
  }
952
953
  }
953
954
 
955
+ /**
956
+ * System token for resolving integration read service from plugin context.
957
+ */ const INTEGRATION_PERMISSION_SERVICE_TOKEN = 'XPERT_PLUGIN_INTEGRATION_PERMISSION_SERVICE';
958
+
959
+ /**
960
+ * System token for resolving analytics permission service from plugin context.
961
+ */ const ANALYTICS_PERMISSION_SERVICE_TOKEN = 'XPERT_PLUGIN_ANALYTICS_PERMISSION_SERVICE';
962
+
963
+ const PERMISSION_OPERATION_METADATA_KEY = 'XPERT_PLUGIN_PERMISSION_OPERATION';
964
+ function RequirePermissionOperation(permissionType, operation) {
965
+ return (_target, _propertyKey, descriptor)=>{
966
+ const method = descriptor.value;
967
+ if (typeof method !== 'function') {
968
+ throw new Error('RequirePermissionOperation can only be applied to methods');
969
+ }
970
+ Reflect.defineMetadata(PERMISSION_OPERATION_METADATA_KEY, {
971
+ permissionType,
972
+ operation
973
+ }, method);
974
+ };
975
+ }
976
+ function getPermissionOperationMetadata(method) {
977
+ if (typeof method !== 'function') {
978
+ return undefined;
979
+ }
980
+ return Reflect.getMetadata(PERMISSION_OPERATION_METADATA_KEY, method);
981
+ }
982
+ function getRequiredPermissionOperation(method, permissionType) {
983
+ const metadata = getPermissionOperationMetadata(method);
984
+ if (!metadata || metadata.permissionType !== permissionType) {
985
+ return undefined;
986
+ }
987
+ return metadata.operation;
988
+ }
989
+
990
+ /**
991
+ * System token for resolving handoff queue service from plugin context.
992
+ */ const HANDOFF_PERMISSION_SERVICE_TOKEN = 'XPERT_PLUGIN_HANDOFF_PERMISSION_SERVICE';
993
+ /**
994
+ * Internal system token used by core to expose the handoff queue bridge.
995
+ */ const HANDOFF_QUEUE_SERVICE_TOKEN = 'XPERT_HANDOFF_QUEUE_SERVICE';
996
+
997
+ /**
998
+ * System token for resolving user permission service from plugin context.
999
+ */ const USER_PERMISSION_SERVICE_TOKEN = 'XPERT_PLUGIN_USER_PERMISSION_SERVICE';
1000
+
954
1001
  async function createI18nInstance(pluginDir, language) {
955
1002
  const instance = i18next.createInstance();
956
1003
  const i18nDir = path.join(pluginDir, 'i18n');
@@ -1365,6 +1412,18 @@ function AIModelProviderStrategy(provider) {
1365
1412
  if (file == null ? void 0 : file.startsWith('file:///')) {
1366
1413
  file = file.replace('file://', '');
1367
1414
  }
1415
+ // Strip :line:col suffix (e.g. "/path/file.js:37:5" -> "/path/file.js")
1416
+ if (file) {
1417
+ file = file.replace(/:\d+:\d+$/, '');
1418
+ }
1419
+ // Decode URL-encoded paths (e.g. Chinese characters: %E9%A1%B9%E7%9B%AE -> 项目)
1420
+ if (file) {
1421
+ try {
1422
+ file = decodeURIComponent(file);
1423
+ } catch (e) {
1424
+ // keep as-is if decode fails
1425
+ }
1426
+ }
1368
1427
  const dir = file ? path.dirname(file) : process.cwd();
1369
1428
  return function(target) {
1370
1429
  common.SetMetadata(STRATEGY_META_KEY, AI_MODEL_PROVIDER)(target);
@@ -2283,6 +2342,48 @@ class Speech2TextChatModel extends chat_models.BaseChatModel {
2283
2342
  return 0;
2284
2343
  }
2285
2344
 
2345
+ function getModelContextSize(input) {
2346
+ if (isCopilotModel(input)) {
2347
+ var _input_options;
2348
+ return normalizeContextSize((_input_options = input.options) == null ? void 0 : _input_options[contracts.ModelPropertyKey.CONTEXT_SIZE]);
2349
+ }
2350
+ // Backward compatibility for langchain <1.0.0
2351
+ if (input.metadata && "profile" in input.metadata) {
2352
+ const profile = input.metadata['profile'];
2353
+ if ("maxInputTokens" in profile && (typeof profile.maxInputTokens === "number" || profile.maxInputTokens == null)) {
2354
+ var _profile_maxInputTokens;
2355
+ return (_profile_maxInputTokens = profile.maxInputTokens) != null ? _profile_maxInputTokens : undefined;
2356
+ }
2357
+ }
2358
+ // Langchain v1.0.0+
2359
+ if ("profile" in input && typeof input.profile === "object" && input.profile && "maxInputTokens" in input.profile && (typeof input.profile.maxInputTokens === "number" || input.profile.maxInputTokens == null)) {
2360
+ var _input_profile_maxInputTokens;
2361
+ return (_input_profile_maxInputTokens = input.profile.maxInputTokens) != null ? _input_profile_maxInputTokens : undefined;
2362
+ }
2363
+ if ("model" in input && typeof input.model === "string") {
2364
+ return base.getModelContextSize(input.model);
2365
+ }
2366
+ if ("modelName" in input && typeof input.modelName === "string") {
2367
+ return base.getModelContextSize(input.modelName);
2368
+ }
2369
+ return undefined;
2370
+ }
2371
+ function isCopilotModel(input) {
2372
+ return typeof input === "object" && input !== null && !("invoke" in input);
2373
+ }
2374
+ function normalizeContextSize(value) {
2375
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) {
2376
+ return Math.floor(value);
2377
+ }
2378
+ if (typeof value === "string") {
2379
+ const parsed = Number.parseInt(value, 10);
2380
+ if (Number.isFinite(parsed) && parsed > 0) {
2381
+ return parsed;
2382
+ }
2383
+ }
2384
+ return undefined;
2385
+ }
2386
+
2286
2387
  /**
2287
2388
  * Get a Chat Model of copilot model and check it's token limitation, record the token usage
2288
2389
  */ class CreateModelClientCommand extends cqrs.Command {
@@ -2319,6 +2420,651 @@ exports.AgentMiddlewareRegistry = __decorate([
2319
2420
  "end"
2320
2421
  ];
2321
2422
 
2423
+ /**
2424
+ * Structured message types (suggested format):
2425
+ * - channel.{provider}.{action}.v{number}
2426
+ * - agent.{action}.v{number}
2427
+ * - system.{action}.v{number}
2428
+ * - plugin.{domain}.{action}.v{number}
2429
+ *
2430
+ * Note: At runtime, any string type is still allowed, facilitating dynamic extension by plugins.
2431
+ */ const SEGMENT_PATTERN = /^[a-z][a-z0-9_-]*$/i;
2432
+ const VERSION_PATTERN = /^v[1-9][0-9]*$/;
2433
+ function assertSegment(input, name) {
2434
+ if (!SEGMENT_PATTERN.test(input)) {
2435
+ throw new Error(`Invalid ${name} segment: "${input}"`);
2436
+ }
2437
+ }
2438
+ /**
2439
+ * Unified construction of channel message types to avoid manual string errors.
2440
+ * Example: channel.lark.inbound.v1
2441
+ */ function defineChannelMessageType(provider, action, version) {
2442
+ assertSegment(provider, 'provider');
2443
+ assertSegment(action, 'action');
2444
+ if (!Number.isInteger(version) || version <= 0) {
2445
+ throw new Error(`Invalid version: "${version}"`);
2446
+ }
2447
+ return `channel.${provider}.${action}.v${version}`;
2448
+ }
2449
+ /**
2450
+ * Unified construction of agent message types.
2451
+ * Example: agent.handoff.v1
2452
+ */ function defineAgentMessageType(action, version) {
2453
+ assertSegment(action, 'action');
2454
+ if (!Number.isInteger(version) || version <= 0) {
2455
+ throw new Error(`Invalid version: "${version}"`);
2456
+ }
2457
+ return `agent.${action}.v${version}`;
2458
+ }
2459
+ /**
2460
+ * Check if a type conforms to the structured naming convention (format only, no semantic validation).
2461
+ */ function isStructuredMessageType(type) {
2462
+ const parts = type.split('.');
2463
+ if (parts.length < 3) {
2464
+ return false;
2465
+ }
2466
+ const version = parts[parts.length - 1];
2467
+ if (!VERSION_PATTERN.test(version)) {
2468
+ return false;
2469
+ }
2470
+ return parts.slice(0, -1).every((part)=>SEGMENT_PATTERN.test(part));
2471
+ }
2472
+
2473
+ const AGENT_CHAT_DISPATCH_MESSAGE_TYPE = defineAgentMessageType('chat_dispatch', 1);
2474
+
2475
+ /**
2476
+ * Handoff Processor meta key。
2477
+ */ const HANDOFF_PROCESSOR_STRATEGY = 'HANDOFF_PROCESSOR_STRATEGY';
2478
+ /**
2479
+ * Declare on a provider:
2480
+ * 1) Which message types it handles
2481
+ * 2) Default execution policy (lane/timeout)
2482
+ */ function HandoffProcessorStrategy(provider, metadata) {
2483
+ var _metadata_types;
2484
+ if (!(metadata == null ? void 0 : (_metadata_types = metadata.types) == null ? void 0 : _metadata_types.length)) {
2485
+ throw new Error('HandoffProcessor requires at least one message type');
2486
+ }
2487
+ return common.applyDecorators(common.SetMetadata(HANDOFF_PROCESSOR_STRATEGY, provider), common.SetMetadata(STRATEGY_META_KEY, HANDOFF_PROCESSOR_STRATEGY));
2488
+ }
2489
+
2490
+ exports.HandoffProcessorRegistry = class HandoffProcessorRegistry extends BaseStrategyRegistry {
2491
+ constructor(discoveryService, reflector){
2492
+ super(HANDOFF_PROCESSOR_STRATEGY, discoveryService, reflector);
2493
+ }
2494
+ };
2495
+ exports.HandoffProcessorRegistry = __decorate([
2496
+ common.Injectable(),
2497
+ __metadata("design:type", Function),
2498
+ __metadata("design:paramtypes", [
2499
+ typeof core.DiscoveryService === "undefined" ? Object : core.DiscoveryService,
2500
+ typeof core.Reflector === "undefined" ? Object : core.Reflector
2501
+ ])
2502
+ ], exports.HandoffProcessorRegistry);
2503
+
2504
+ /**
2505
+ * Handoff execution types.
2506
+ *
2507
+ * Note:
2508
+ * - Two-gate lane/session permit logic has been removed.
2509
+ * - Lane is now an execution tag for observability and soft policy only.
2510
+ */ const DEFAULT_EXECUTION_CONFIG = {
2511
+ lanes: {
2512
+ main: 8,
2513
+ subagent: 16,
2514
+ cron: 4,
2515
+ nested: 8
2516
+ },
2517
+ runTtlMs: 10 * 60 * 1000
2518
+ };
2519
+
2520
+ /**
2521
+ * Common platform message length limits
2522
+ */ const CHAT_CHANNEL_TEXT_LIMITS = {
2523
+ lark: 4000,
2524
+ wecom: 2048,
2525
+ dingtalk: 4000,
2526
+ slack: 4000,
2527
+ telegram: 4096,
2528
+ discord: 2000
2529
+ };
2530
+ /**
2531
+ * Chunk long text by specified length
2532
+ *
2533
+ * @param text - Text to chunk
2534
+ * @param limit - Maximum characters per chunk
2535
+ * @param mode - Chunking mode: 'text' splits by character, 'markdown' tries to preserve paragraphs
2536
+ * @returns Array of chunked text
2537
+ */ function chunkText(text, limit, mode = 'text') {
2538
+ if (!text || text.length <= limit) {
2539
+ return [
2540
+ text
2541
+ ];
2542
+ }
2543
+ const chunks = [];
2544
+ if (mode === 'markdown') {
2545
+ // Markdown mode: try to split at paragraph boundaries
2546
+ const paragraphs = text.split(/\n\n+/);
2547
+ let currentChunk = '';
2548
+ for (const para of paragraphs){
2549
+ if (currentChunk.length + para.length + 2 <= limit) {
2550
+ currentChunk += (currentChunk ? '\n\n' : '') + para;
2551
+ } else if (para.length > limit) {
2552
+ // Paragraph itself is too long, need hard split
2553
+ if (currentChunk) {
2554
+ chunks.push(currentChunk);
2555
+ currentChunk = '';
2556
+ }
2557
+ let remaining = para;
2558
+ while(remaining.length > limit){
2559
+ chunks.push(remaining.slice(0, limit));
2560
+ remaining = remaining.slice(limit);
2561
+ }
2562
+ currentChunk = remaining;
2563
+ } else {
2564
+ if (currentChunk) {
2565
+ chunks.push(currentChunk);
2566
+ }
2567
+ currentChunk = para;
2568
+ }
2569
+ }
2570
+ if (currentChunk) {
2571
+ chunks.push(currentChunk);
2572
+ }
2573
+ } else {
2574
+ // Plain text mode: split directly by length
2575
+ let remaining = text;
2576
+ while(remaining.length > limit){
2577
+ chunks.push(remaining.slice(0, limit));
2578
+ remaining = remaining.slice(limit);
2579
+ }
2580
+ if (remaining) {
2581
+ chunks.push(remaining);
2582
+ }
2583
+ }
2584
+ return chunks;
2585
+ }
2586
+
2587
+ /**
2588
+ * Metadata key for chat channel
2589
+ */ const CHAT_CHANNEL = 'CHAT_CHANNEL';
2590
+ /**
2591
+ * Decorator for chat channel implementations
2592
+ *
2593
+ * Use this decorator to register a chat channel implementation.
2594
+ * The decorated class will be automatically discovered and registered
2595
+ * to ChatChannelRegistry on module initialization.
2596
+ *
2597
+ * @param type - The channel type identifier (e.g., 'lark', 'wecom', 'dingtalk')
2598
+ *
2599
+ * @example
2600
+ * ```typescript
2601
+ * @Injectable()
2602
+ * @ChatChannel('lark')
2603
+ * export class LarkChatChannel implements IChatChannel {
2604
+ * // Implementation
2605
+ * }
2606
+ * ```
2607
+ */ const ChatChannel = (type)=>common.SetMetadata(CHAT_CHANNEL, type);
2608
+
2609
+ exports.ChatChannelRegistry = class ChatChannelRegistry extends BaseStrategyRegistry {
2610
+ constructor(discoveryService, reflector){
2611
+ super(CHAT_CHANNEL, discoveryService, reflector);
2612
+ }
2613
+ };
2614
+ exports.ChatChannelRegistry = __decorate([
2615
+ common.Injectable(),
2616
+ __metadata("design:type", Function),
2617
+ __metadata("design:paramtypes", [
2618
+ typeof core.DiscoveryService === "undefined" ? Object : core.DiscoveryService,
2619
+ typeof core.Reflector === "undefined" ? Object : core.Reflector
2620
+ ])
2621
+ ], exports.ChatChannelRegistry);
2622
+
2623
+ class CancelConversationCommand {
2624
+ constructor(input){
2625
+ this.input = input;
2626
+ }
2627
+ }
2628
+ CancelConversationCommand.type = '[Chat Conversation] Cancel';
2629
+
2630
+ /**
2631
+ * Protocol definition for pluggable memory backends.
2632
+ *
2633
+ * This module defines the BackendProtocol that all backend implementations
2634
+ * must follow. Backends can store files in different locations (state, filesystem,
2635
+ * database, etc.) and provide a uniform interface for file operations.
2636
+ */ /**
2637
+ * Type guard to check if a backend supports execution.
2638
+ *
2639
+ * @param backend - Backend instance to check
2640
+ * @returns True if the backend implements SandboxBackendProtocol
2641
+ */ function isSandboxBackend(backend) {
2642
+ return typeof backend.execute === "function" && typeof backend.id === "string";
2643
+ }
2644
+
2645
+ /**
2646
+ * BaseSandbox: Abstract base class for sandbox backends with command execution.
2647
+ *
2648
+ * This class provides default implementations for all SandboxBackendProtocol
2649
+ * methods using shell commands executed via execute(). Concrete implementations
2650
+ * only need to implement the execute() method.
2651
+ *
2652
+ * Requires Node.js 20+ on the sandbox host.
2653
+ */ /**
2654
+ * Node.js command template for glob operations.
2655
+ * Uses web-standard atob() for base64 decoding.
2656
+ */ function buildGlobCommand(searchPath, pattern) {
2657
+ const pathB64 = btoa(searchPath);
2658
+ const patternB64 = btoa(pattern);
2659
+ return `node -e "
2660
+ const fs = require('fs');
2661
+ const path = require('path');
2662
+
2663
+ const searchPath = atob('${pathB64}');
2664
+ const pattern = atob('${patternB64}');
2665
+
2666
+ function globMatch(relativePath, pattern) {
2667
+ const regexPattern = pattern
2668
+ .replace(/\\*\\*/g, '<<<GLOBSTAR>>>')
2669
+ .replace(/\\*/g, '[^/]*')
2670
+ .replace(/\\?/g, '.')
2671
+ .replace(/<<<GLOBSTAR>>>/g, '.*');
2672
+ return new RegExp('^' + regexPattern + '$').test(relativePath);
2673
+ }
2674
+
2675
+ function walkDir(dir, baseDir, results) {
2676
+ try {
2677
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
2678
+ for (const entry of entries) {
2679
+ const fullPath = path.join(dir, entry.name);
2680
+ const relativePath = path.relative(baseDir, fullPath);
2681
+ if (entry.isDirectory()) {
2682
+ walkDir(fullPath, baseDir, results);
2683
+ } else if (globMatch(relativePath, pattern)) {
2684
+ const stat = fs.statSync(fullPath);
2685
+ console.log(JSON.stringify({
2686
+ path: relativePath,
2687
+ size: stat.size,
2688
+ mtime: stat.mtimeMs,
2689
+ isDir: false
2690
+ }));
2691
+ }
2692
+ }
2693
+ } catch (e) {
2694
+ // Silent failure for non-existent paths
2695
+ }
2696
+ }
2697
+
2698
+ try {
2699
+ process.chdir(searchPath);
2700
+ walkDir('.', '.', []);
2701
+ } catch (e) {
2702
+ // Silent failure for non-existent paths
2703
+ }
2704
+ "`;
2705
+ }
2706
+ /**
2707
+ * Node.js command template for listing directory contents.
2708
+ */ function buildLsCommand(dirPath) {
2709
+ const pathB64 = btoa(dirPath);
2710
+ return `node -e "
2711
+ const fs = require('fs');
2712
+ const path = require('path');
2713
+
2714
+ const dirPath = atob('${pathB64}');
2715
+
2716
+ try {
2717
+ const entries = fs.readdirSync(dirPath, { withFileTypes: true });
2718
+ for (const entry of entries) {
2719
+ const fullPath = path.join(dirPath, entry.name);
2720
+ const stat = fs.statSync(fullPath);
2721
+ console.log(JSON.stringify({
2722
+ path: entry.isDirectory() ? fullPath + '/' : fullPath,
2723
+ size: stat.size,
2724
+ mtime: stat.mtimeMs,
2725
+ isDir: entry.isDirectory()
2726
+ }));
2727
+ }
2728
+ } catch (e) {
2729
+ console.error('Error: ' + e.message);
2730
+ process.exit(1);
2731
+ }
2732
+ "`;
2733
+ }
2734
+ /**
2735
+ * Node.js command template for reading files.
2736
+ */ function buildReadCommand(filePath, offset, limit) {
2737
+ const pathB64 = btoa(filePath);
2738
+ // Coerce offset and limit to safe non-negative integers before embedding in the shell command.
2739
+ const safeOffset = Number.isFinite(offset) && offset > 0 ? Math.floor(offset) : 0;
2740
+ const safeLimit = Number.isFinite(limit) && limit > 0 && limit < Number.MAX_SAFE_INTEGER ? Math.floor(limit) : 0;
2741
+ return `node -e "
2742
+ const fs = require('fs');
2743
+
2744
+ const filePath = atob('${pathB64}');
2745
+ const offset = ${safeOffset};
2746
+ const limit = ${safeLimit};
2747
+
2748
+ if (!fs.existsSync(filePath)) {
2749
+ console.log('Error: File not found');
2750
+ process.exit(1);
2751
+ }
2752
+
2753
+ const stat = fs.statSync(filePath);
2754
+ if (stat.size === 0) {
2755
+ console.log('System reminder: File exists but has empty contents');
2756
+ process.exit(0);
2757
+ }
2758
+
2759
+ const content = fs.readFileSync(filePath, 'utf-8');
2760
+ const lines = content.split('\\n');
2761
+ const selected = lines.slice(offset, offset + limit);
2762
+
2763
+ for (let i = 0; i < selected.length; i++) {
2764
+ const lineNum = offset + i + 1;
2765
+ console.log(String(lineNum).padStart(6) + '\\t' + selected[i]);
2766
+ }
2767
+ "`;
2768
+ }
2769
+ /**
2770
+ * Node.js command template for writing files.
2771
+ */ function buildWriteCommand(filePath, content) {
2772
+ const pathB64 = btoa(filePath);
2773
+ const contentB64 = btoa(content);
2774
+ return `node -e "
2775
+ const fs = require('fs');
2776
+ const path = require('path');
2777
+
2778
+ const filePath = atob('${pathB64}');
2779
+ const content = atob('${contentB64}');
2780
+
2781
+ if (fs.existsSync(filePath)) {
2782
+ console.error('Error: File already exists');
2783
+ process.exit(1);
2784
+ }
2785
+
2786
+ const parentDir = path.dirname(filePath) || '.';
2787
+ fs.mkdirSync(parentDir, { recursive: true });
2788
+
2789
+ fs.writeFileSync(filePath, content, 'utf-8');
2790
+ console.log('OK');
2791
+ "`;
2792
+ }
2793
+ /**
2794
+ * Node.js command template for editing files.
2795
+ */ function buildEditCommand(filePath, oldStr, newStr, replaceAll) {
2796
+ const pathB64 = btoa(filePath);
2797
+ const oldB64 = btoa(oldStr);
2798
+ const newB64 = btoa(newStr);
2799
+ return `node -e "
2800
+ const fs = require('fs');
2801
+
2802
+ const filePath = atob('${pathB64}');
2803
+ const oldStr = atob('${oldB64}');
2804
+ const newStr = atob('${newB64}');
2805
+ const replaceAll = ${Boolean(replaceAll)};
2806
+
2807
+ let text;
2808
+ try {
2809
+ text = fs.readFileSync(filePath, 'utf-8');
2810
+ } catch (e) {
2811
+ process.exit(3);
2812
+ }
2813
+
2814
+ const count = text.split(oldStr).length - 1;
2815
+
2816
+ if (count === 0) {
2817
+ process.exit(1);
2818
+ }
2819
+ if (count > 1 && !replaceAll) {
2820
+ process.exit(2);
2821
+ }
2822
+
2823
+ const result = text.split(oldStr).join(newStr);
2824
+ fs.writeFileSync(filePath, result, 'utf-8');
2825
+ console.log(count);
2826
+ "`;
2827
+ }
2828
+ /**
2829
+ * Node.js command template for grep operations.
2830
+ */ function buildGrepCommand(pattern, searchPath, globPattern) {
2831
+ const patternB64 = btoa(pattern);
2832
+ const pathB64 = btoa(searchPath);
2833
+ const globB64 = globPattern ? btoa(globPattern) : "";
2834
+ return `node -e "
2835
+ const fs = require('fs');
2836
+ const path = require('path');
2837
+
2838
+ const pattern = atob('${patternB64}');
2839
+ const searchPath = atob('${pathB64}');
2840
+ const globPattern = ${globPattern ? `atob('${globB64}')` : "null"};
2841
+
2842
+ let regex;
2843
+ try {
2844
+ regex = new RegExp(pattern);
2845
+ } catch (e) {
2846
+ console.error('Invalid regex: ' + e.message);
2847
+ process.exit(1);
2848
+ }
2849
+
2850
+ function globMatch(filePath, pattern) {
2851
+ if (!pattern) return true;
2852
+ const regexPattern = pattern
2853
+ .replace(/\\*\\*/g, '<<<GLOBSTAR>>>')
2854
+ .replace(/\\*/g, '[^/]*')
2855
+ .replace(/\\?/g, '.')
2856
+ .replace(/<<<GLOBSTAR>>>/g, '.*');
2857
+ return new RegExp('^' + regexPattern + '$').test(filePath);
2858
+ }
2859
+
2860
+ function walkDir(dir, results) {
2861
+ try {
2862
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
2863
+ for (const entry of entries) {
2864
+ const fullPath = path.join(dir, entry.name);
2865
+ if (entry.isDirectory()) {
2866
+ walkDir(fullPath, results);
2867
+ } else {
2868
+ const relativePath = path.relative(searchPath, fullPath);
2869
+ if (globMatch(relativePath, globPattern)) {
2870
+ try {
2871
+ const content = fs.readFileSync(fullPath, 'utf-8');
2872
+ const lines = content.split('\\n');
2873
+ for (let i = 0; i < lines.length; i++) {
2874
+ if (regex.test(lines[i])) {
2875
+ console.log(JSON.stringify({
2876
+ path: fullPath,
2877
+ line: i + 1,
2878
+ text: lines[i]
2879
+ }));
2880
+ }
2881
+ }
2882
+ } catch (e) {
2883
+ // Skip unreadable files
2884
+ }
2885
+ }
2886
+ }
2887
+ }
2888
+ } catch (e) {
2889
+ // Skip unreadable directories
2890
+ }
2891
+ }
2892
+
2893
+ try {
2894
+ walkDir(searchPath, []);
2895
+ } catch (e) {
2896
+ // Silent failure
2897
+ }
2898
+ "`;
2899
+ }
2900
+ /**
2901
+ * Base sandbox implementation with execute() as the only abstract method.
2902
+ *
2903
+ * This class provides default implementations for all SandboxBackendProtocol
2904
+ * methods using shell commands executed via execute(). Concrete implementations
2905
+ * only need to implement the execute() method.
2906
+ *
2907
+ * Requires Node.js 20+ on the sandbox host.
2908
+ */ class BaseSandbox {
2909
+ /**
2910
+ * List files and directories in the specified directory (non-recursive).
2911
+ *
2912
+ * @param path - Absolute path to directory
2913
+ * @returns List of FileInfo objects for files and directories directly in the directory.
2914
+ */ async lsInfo(path) {
2915
+ const command = buildLsCommand(path);
2916
+ const result = await this.execute(command);
2917
+ if (result.exitCode !== 0) {
2918
+ return [];
2919
+ }
2920
+ const infos = [];
2921
+ const lines = result.output.trim().split("\n").filter(Boolean);
2922
+ for (const line of lines){
2923
+ try {
2924
+ const parsed = JSON.parse(line);
2925
+ infos.push({
2926
+ path: parsed.path,
2927
+ is_dir: parsed.isDir,
2928
+ size: parsed.size,
2929
+ modified_at: parsed.mtime ? new Date(parsed.mtime).toISOString() : undefined
2930
+ });
2931
+ } catch (e) {
2932
+ // Skip invalid JSON lines
2933
+ }
2934
+ }
2935
+ return infos;
2936
+ }
2937
+ /**
2938
+ * Read file content with line numbers.
2939
+ *
2940
+ * @param filePath - Absolute file path
2941
+ * @param offset - Line offset to start reading from (0-indexed)
2942
+ * @param limit - Maximum number of lines to read
2943
+ * @returns Formatted file content with line numbers, or error message
2944
+ */ async read(filePath, offset = 0, limit = 500) {
2945
+ const command = buildReadCommand(filePath, offset, limit);
2946
+ const result = await this.execute(command);
2947
+ if (result.exitCode !== 0) {
2948
+ return `Error: File '${filePath}' not found`;
2949
+ }
2950
+ return result.output;
2951
+ }
2952
+ /**
2953
+ * Structured search results or error string for invalid input.
2954
+ */ async grepRaw(pattern, path = "/", glob = null) {
2955
+ const command = buildGrepCommand(pattern, path, glob);
2956
+ const result = await this.execute(command);
2957
+ if (result.exitCode === 1) {
2958
+ // Check if it's a regex error
2959
+ if (result.output.includes("Invalid regex:")) {
2960
+ return result.output.trim();
2961
+ }
2962
+ }
2963
+ const matches = [];
2964
+ const lines = result.output.trim().split("\n").filter(Boolean);
2965
+ for (const line of lines){
2966
+ try {
2967
+ const parsed = JSON.parse(line);
2968
+ matches.push({
2969
+ path: parsed.path,
2970
+ line: parsed.line,
2971
+ text: parsed.text
2972
+ });
2973
+ } catch (e) {
2974
+ // Skip invalid JSON lines
2975
+ }
2976
+ }
2977
+ return matches;
2978
+ }
2979
+ /**
2980
+ * Structured glob matching returning FileInfo objects.
2981
+ */ async globInfo(pattern, path = "/") {
2982
+ const command = buildGlobCommand(path, pattern);
2983
+ const result = await this.execute(command);
2984
+ const infos = [];
2985
+ const lines = result.output.trim().split("\n").filter(Boolean);
2986
+ for (const line of lines){
2987
+ try {
2988
+ const parsed = JSON.parse(line);
2989
+ infos.push({
2990
+ path: parsed.path,
2991
+ is_dir: parsed.isDir,
2992
+ size: parsed.size,
2993
+ modified_at: parsed.mtime ? new Date(parsed.mtime).toISOString() : undefined
2994
+ });
2995
+ } catch (e) {
2996
+ // Skip invalid JSON lines
2997
+ }
2998
+ }
2999
+ return infos;
3000
+ }
3001
+ /**
3002
+ * Create a new file with content.
3003
+ */ async write(filePath, content) {
3004
+ const command = buildWriteCommand(filePath, content);
3005
+ const result = await this.execute(command);
3006
+ if (result.exitCode !== 0) {
3007
+ return {
3008
+ error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.`
3009
+ };
3010
+ }
3011
+ return {
3012
+ path: filePath,
3013
+ filesUpdate: null
3014
+ };
3015
+ }
3016
+ /**
3017
+ * Edit a file by replacing string occurrences.
3018
+ */ async edit(filePath, oldString, newString, replaceAll = false) {
3019
+ const command = buildEditCommand(filePath, oldString, newString, replaceAll);
3020
+ const result = await this.execute(command);
3021
+ switch(result.exitCode){
3022
+ case 0:
3023
+ {
3024
+ const occurrences = parseInt(result.output.trim(), 10) || 1;
3025
+ return {
3026
+ path: filePath,
3027
+ filesUpdate: null,
3028
+ occurrences
3029
+ };
3030
+ }
3031
+ case 1:
3032
+ return {
3033
+ error: `String not found in file '${filePath}'`
3034
+ };
3035
+ case 2:
3036
+ return {
3037
+ error: `Multiple occurrences found in '${filePath}'. Use replaceAll=true to replace all.`
3038
+ };
3039
+ case 3:
3040
+ return {
3041
+ error: `Error: File '${filePath}' not found`
3042
+ };
3043
+ default:
3044
+ return {
3045
+ error: `Unknown error editing file '${filePath}'`
3046
+ };
3047
+ }
3048
+ }
3049
+ }
3050
+
3051
+ const SANDBOX_PROVIDER = 'SANDBOX_PROVIDER';
3052
+ const SandboxProviderStrategy = (provider)=>common.applyDecorators(common.SetMetadata(SANDBOX_PROVIDER, provider), common.SetMetadata(STRATEGY_META_KEY, SANDBOX_PROVIDER));
3053
+
3054
+ exports.SandboxProviderRegistry = class SandboxProviderRegistry extends BaseStrategyRegistry {
3055
+ constructor(discoveryService, reflector){
3056
+ super(SANDBOX_PROVIDER, discoveryService, reflector);
3057
+ }
3058
+ };
3059
+ exports.SandboxProviderRegistry = __decorate([
3060
+ common.Injectable(),
3061
+ __metadata("design:type", Function),
3062
+ __metadata("design:paramtypes", [
3063
+ typeof core.DiscoveryService === "undefined" ? Object : core.DiscoveryService,
3064
+ typeof core.Reflector === "undefined" ? Object : core.Reflector
3065
+ ])
3066
+ ], exports.SandboxProviderRegistry);
3067
+
2322
3068
  Object.defineProperty(exports, "IColumnDef", {
2323
3069
  enumerable: true,
2324
3070
  get: function () { return contracts.IColumnDef; }
@@ -2335,32 +3081,45 @@ Object.defineProperty(exports, "TDocumentAsset", {
2335
3081
  enumerable: true,
2336
3082
  get: function () { return contracts.TDocumentAsset; }
2337
3083
  });
3084
+ exports.AGENT_CHAT_DISPATCH_MESSAGE_TYPE = AGENT_CHAT_DISPATCH_MESSAGE_TYPE;
2338
3085
  exports.AGENT_MIDDLEWARE_STRATEGY = AGENT_MIDDLEWARE_STRATEGY;
2339
3086
  exports.AIModelProviderNotFoundException = AIModelProviderNotFoundException;
2340
3087
  exports.AIModelProviderStrategy = AIModelProviderStrategy;
2341
3088
  exports.AI_MODEL_PROVIDER = AI_MODEL_PROVIDER;
3089
+ exports.ANALYTICS_PERMISSION_SERVICE_TOKEN = ANALYTICS_PERMISSION_SERVICE_TOKEN;
2342
3090
  exports.AdapterDataSourceStrategy = AdapterDataSourceStrategy;
2343
3091
  exports.AgentMiddlewareStrategy = AgentMiddlewareStrategy;
2344
3092
  exports.AiModelNotFoundException = AiModelNotFoundException;
2345
3093
  exports.BaseHTTPQueryRunner = BaseHTTPQueryRunner;
2346
3094
  exports.BaseQueryRunner = BaseQueryRunner;
2347
3095
  exports.BaseSQLQueryRunner = BaseSQLQueryRunner;
3096
+ exports.BaseSandbox = BaseSandbox;
2348
3097
  exports.BaseStrategyRegistry = BaseStrategyRegistry;
2349
3098
  exports.BaseTool = BaseTool;
2350
3099
  exports.BaseToolset = BaseToolset;
2351
3100
  exports.BuiltinToolset = BuiltinToolset;
3101
+ exports.CHAT_CHANNEL = CHAT_CHANNEL;
3102
+ exports.CHAT_CHANNEL_TEXT_LIMITS = CHAT_CHANNEL_TEXT_LIMITS;
3103
+ exports.CancelConversationCommand = CancelConversationCommand;
3104
+ exports.ChatChannel = ChatChannel;
2352
3105
  exports.ChatOAICompatReasoningModel = ChatOAICompatReasoningModel;
2353
3106
  exports.CommonParameterRules = CommonParameterRules;
2354
3107
  exports.CreateModelClientCommand = CreateModelClientCommand;
2355
3108
  exports.CredentialsValidateFailedError = CredentialsValidateFailedError;
2356
3109
  exports.DATASOURCE_STRATEGY = DATASOURCE_STRATEGY;
3110
+ exports.DEFAULT_EXECUTION_CONFIG = DEFAULT_EXECUTION_CONFIG;
2357
3111
  exports.DOCUMENT_SOURCE_STRATEGY = DOCUMENT_SOURCE_STRATEGY;
2358
3112
  exports.DOCUMENT_TRANSFORMER_STRATEGY = DOCUMENT_TRANSFORMER_STRATEGY;
2359
3113
  exports.DataSourceStrategy = DataSourceStrategy;
2360
3114
  exports.DocumentSourceStrategy = DocumentSourceStrategy;
2361
3115
  exports.DocumentTransformerStrategy = DocumentTransformerStrategy;
2362
3116
  exports.GLOBAL_ORGANIZATION_SCOPE = GLOBAL_ORGANIZATION_SCOPE;
3117
+ exports.HANDOFF_PERMISSION_SERVICE_TOKEN = HANDOFF_PERMISSION_SERVICE_TOKEN;
3118
+ exports.HANDOFF_PROCESSOR_STRATEGY = HANDOFF_PROCESSOR_STRATEGY;
3119
+ exports.HANDOFF_QUEUE_SERVICE_TOKEN = HANDOFF_QUEUE_SERVICE_TOKEN;
3120
+ exports.HandoffProcessorStrategy = HandoffProcessorStrategy;
2363
3121
  exports.IMAGE_UNDERSTANDING_STRATEGY = IMAGE_UNDERSTANDING_STRATEGY;
3122
+ exports.INTEGRATION_PERMISSION_SERVICE_TOKEN = INTEGRATION_PERMISSION_SERVICE_TOKEN;
2364
3123
  exports.INTEGRATION_STRATEGY = INTEGRATION_STRATEGY;
2365
3124
  exports.ImageUnderstandingStrategy = ImageUnderstandingStrategy;
2366
3125
  exports.IntegrationStrategyKey = IntegrationStrategyKey;
@@ -2372,6 +3131,7 @@ exports.LLMUsage = LLMUsage;
2372
3131
  exports.LargeLanguageModel = LargeLanguageModel;
2373
3132
  exports.ORGANIZATION_METADATA_KEY = ORGANIZATION_METADATA_KEY;
2374
3133
  exports.OpenAICompatibleReranker = OpenAICompatibleReranker;
3134
+ exports.PERMISSION_OPERATION_METADATA_KEY = PERMISSION_OPERATION_METADATA_KEY;
2375
3135
  exports.PLUGIN_METADATA = PLUGIN_METADATA;
2376
3136
  exports.PLUGIN_METADATA_KEY = PLUGIN_METADATA_KEY;
2377
3137
  exports.PROVIDE_AI_MODEL_LLM = PROVIDE_AI_MODEL_LLM;
@@ -2382,9 +3142,12 @@ exports.PROVIDE_AI_MODEL_TEXT_EMBEDDING = PROVIDE_AI_MODEL_TEXT_EMBEDDING;
2382
3142
  exports.PROVIDE_AI_MODEL_TTS = PROVIDE_AI_MODEL_TTS;
2383
3143
  exports.RETRIEVER_STRATEGY = RETRIEVER_STRATEGY;
2384
3144
  exports.RequestContext = RequestContext;
3145
+ exports.RequirePermissionOperation = RequirePermissionOperation;
2385
3146
  exports.RerankModel = RerankModel;
2386
3147
  exports.RetrieverStrategy = RetrieverStrategy;
3148
+ exports.SANDBOX_PROVIDER = SANDBOX_PROVIDER;
2387
3149
  exports.STRATEGY_META_KEY = STRATEGY_META_KEY;
3150
+ exports.SandboxProviderStrategy = SandboxProviderStrategy;
2388
3151
  exports.Speech2TextChatModel = Speech2TextChatModel;
2389
3152
  exports.SpeechToTextModel = SpeechToTextModel;
2390
3153
  exports.TEXT_SPLITTER_STRATEGY = TEXT_SPLITTER_STRATEGY;
@@ -2393,6 +3156,7 @@ exports.TextEmbeddingModelManager = TextEmbeddingModelManager;
2393
3156
  exports.TextSplitterStrategy = TextSplitterStrategy;
2394
3157
  exports.TextToSpeechModel = TextToSpeechModel;
2395
3158
  exports.ToolsetStrategy = ToolsetStrategy;
3159
+ exports.USER_PERMISSION_SERVICE_TOKEN = USER_PERMISSION_SERVICE_TOKEN;
2396
3160
  exports.VECTOR_STORE_STRATEGY = VECTOR_STORE_STRATEGY;
2397
3161
  exports.VectorStoreStrategy = VectorStoreStrategy;
2398
3162
  exports.WORKFLOW_NODE_STRATEGY = WORKFLOW_NODE_STRATEGY;
@@ -2404,17 +3168,26 @@ exports.XpFileSystem = XpFileSystem;
2404
3168
  exports.XpertServerPlugin = XpertServerPlugin;
2405
3169
  exports.als = als;
2406
3170
  exports.calcTokenUsage = calcTokenUsage;
3171
+ exports.chunkText = chunkText;
2407
3172
  exports.countTokensSafe = countTokensSafe;
2408
3173
  exports.createI18nInstance = createI18nInstance;
2409
3174
  exports.createPluginLogger = createPluginLogger;
3175
+ exports.defineAgentMessageType = defineAgentMessageType;
3176
+ exports.defineChannelMessageType = defineChannelMessageType;
2410
3177
  exports.downloadRemoteFile = downloadRemoteFile;
2411
3178
  exports.getErrorMessage = getErrorMessage;
3179
+ exports.getModelContextSize = getModelContextSize;
3180
+ exports.getPermissionOperationMetadata = getPermissionOperationMetadata;
2412
3181
  exports.getPositionList = getPositionList;
2413
3182
  exports.getPositionMap = getPositionMap;
2414
3183
  exports.getRequestContext = getRequestContext;
3184
+ exports.getRequiredPermissionOperation = getRequiredPermissionOperation;
2415
3185
  exports.isRemoteFile = isRemoteFile;
3186
+ exports.isSandboxBackend = isSandboxBackend;
3187
+ exports.isStructuredMessageType = isStructuredMessageType;
2416
3188
  exports.loadYamlFile = loadYamlFile;
2417
3189
  exports.mergeCredentials = mergeCredentials;
2418
3190
  exports.mergeParentChildChunks = mergeParentChildChunks;
3191
+ exports.normalizeContextSize = normalizeContextSize;
2419
3192
  exports.runWithRequestContext = runWithRequestContext;
2420
3193
  exports.sumTokenUsage = sumTokenUsage;