@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.esm.js CHANGED
@@ -32,6 +32,7 @@ import { BaseChatModel } from '@langchain/core/language_models/chat_models';
32
32
  import { AIMessage } from '@langchain/core/messages';
33
33
  import { getEnvironmentVariable } from '@langchain/core/utils/env';
34
34
  import 'js-tiktoken';
35
+ import { getModelContextSize as getModelContextSize$1 } from '@langchain/core/language_models/base';
35
36
 
36
37
  /**
37
38
  * Metadata keys used in plugins for defining various aspects like entities, subscribers, and configurations.
@@ -931,6 +932,52 @@ BuiltinToolset.provider = '';
931
932
  }
932
933
  }
933
934
 
935
+ /**
936
+ * System token for resolving integration read service from plugin context.
937
+ */ const INTEGRATION_PERMISSION_SERVICE_TOKEN = 'XPERT_PLUGIN_INTEGRATION_PERMISSION_SERVICE';
938
+
939
+ /**
940
+ * System token for resolving analytics permission service from plugin context.
941
+ */ const ANALYTICS_PERMISSION_SERVICE_TOKEN = 'XPERT_PLUGIN_ANALYTICS_PERMISSION_SERVICE';
942
+
943
+ const PERMISSION_OPERATION_METADATA_KEY = 'XPERT_PLUGIN_PERMISSION_OPERATION';
944
+ function RequirePermissionOperation(permissionType, operation) {
945
+ return (_target, _propertyKey, descriptor)=>{
946
+ const method = descriptor.value;
947
+ if (typeof method !== 'function') {
948
+ throw new Error('RequirePermissionOperation can only be applied to methods');
949
+ }
950
+ Reflect.defineMetadata(PERMISSION_OPERATION_METADATA_KEY, {
951
+ permissionType,
952
+ operation
953
+ }, method);
954
+ };
955
+ }
956
+ function getPermissionOperationMetadata(method) {
957
+ if (typeof method !== 'function') {
958
+ return undefined;
959
+ }
960
+ return Reflect.getMetadata(PERMISSION_OPERATION_METADATA_KEY, method);
961
+ }
962
+ function getRequiredPermissionOperation(method, permissionType) {
963
+ const metadata = getPermissionOperationMetadata(method);
964
+ if (!metadata || metadata.permissionType !== permissionType) {
965
+ return undefined;
966
+ }
967
+ return metadata.operation;
968
+ }
969
+
970
+ /**
971
+ * System token for resolving handoff queue service from plugin context.
972
+ */ const HANDOFF_PERMISSION_SERVICE_TOKEN = 'XPERT_PLUGIN_HANDOFF_PERMISSION_SERVICE';
973
+ /**
974
+ * Internal system token used by core to expose the handoff queue bridge.
975
+ */ const HANDOFF_QUEUE_SERVICE_TOKEN = 'XPERT_HANDOFF_QUEUE_SERVICE';
976
+
977
+ /**
978
+ * System token for resolving user permission service from plugin context.
979
+ */ const USER_PERMISSION_SERVICE_TOKEN = 'XPERT_PLUGIN_USER_PERMISSION_SERVICE';
980
+
934
981
  async function createI18nInstance(pluginDir, language) {
935
982
  const instance = createInstance();
936
983
  const i18nDir = path__default.join(pluginDir, 'i18n');
@@ -1345,6 +1392,18 @@ function AIModelProviderStrategy(provider) {
1345
1392
  if (file == null ? void 0 : file.startsWith('file:///')) {
1346
1393
  file = file.replace('file://', '');
1347
1394
  }
1395
+ // Strip :line:col suffix (e.g. "/path/file.js:37:5" -> "/path/file.js")
1396
+ if (file) {
1397
+ file = file.replace(/:\d+:\d+$/, '');
1398
+ }
1399
+ // Decode URL-encoded paths (e.g. Chinese characters: %E9%A1%B9%E7%9B%AE -> 项目)
1400
+ if (file) {
1401
+ try {
1402
+ file = decodeURIComponent(file);
1403
+ } catch (e) {
1404
+ // keep as-is if decode fails
1405
+ }
1406
+ }
1348
1407
  const dir = file ? path__default.dirname(file) : process.cwd();
1349
1408
  return function(target) {
1350
1409
  SetMetadata(STRATEGY_META_KEY, AI_MODEL_PROVIDER)(target);
@@ -2263,6 +2322,48 @@ class Speech2TextChatModel extends BaseChatModel {
2263
2322
  return 0;
2264
2323
  }
2265
2324
 
2325
+ function getModelContextSize(input) {
2326
+ if (isCopilotModel(input)) {
2327
+ var _input_options;
2328
+ return normalizeContextSize((_input_options = input.options) == null ? void 0 : _input_options[ModelPropertyKey.CONTEXT_SIZE]);
2329
+ }
2330
+ // Backward compatibility for langchain <1.0.0
2331
+ if (input.metadata && "profile" in input.metadata) {
2332
+ const profile = input.metadata['profile'];
2333
+ if ("maxInputTokens" in profile && (typeof profile.maxInputTokens === "number" || profile.maxInputTokens == null)) {
2334
+ var _profile_maxInputTokens;
2335
+ return (_profile_maxInputTokens = profile.maxInputTokens) != null ? _profile_maxInputTokens : undefined;
2336
+ }
2337
+ }
2338
+ // Langchain v1.0.0+
2339
+ if ("profile" in input && typeof input.profile === "object" && input.profile && "maxInputTokens" in input.profile && (typeof input.profile.maxInputTokens === "number" || input.profile.maxInputTokens == null)) {
2340
+ var _input_profile_maxInputTokens;
2341
+ return (_input_profile_maxInputTokens = input.profile.maxInputTokens) != null ? _input_profile_maxInputTokens : undefined;
2342
+ }
2343
+ if ("model" in input && typeof input.model === "string") {
2344
+ return getModelContextSize$1(input.model);
2345
+ }
2346
+ if ("modelName" in input && typeof input.modelName === "string") {
2347
+ return getModelContextSize$1(input.modelName);
2348
+ }
2349
+ return undefined;
2350
+ }
2351
+ function isCopilotModel(input) {
2352
+ return typeof input === "object" && input !== null && !("invoke" in input);
2353
+ }
2354
+ function normalizeContextSize(value) {
2355
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) {
2356
+ return Math.floor(value);
2357
+ }
2358
+ if (typeof value === "string") {
2359
+ const parsed = Number.parseInt(value, 10);
2360
+ if (Number.isFinite(parsed) && parsed > 0) {
2361
+ return parsed;
2362
+ }
2363
+ }
2364
+ return undefined;
2365
+ }
2366
+
2266
2367
  /**
2267
2368
  * Get a Chat Model of copilot model and check it's token limitation, record the token usage
2268
2369
  */ class CreateModelClientCommand extends Command {
@@ -2299,4 +2400,649 @@ AgentMiddlewareRegistry = __decorate([
2299
2400
  "end"
2300
2401
  ];
2301
2402
 
2302
- export { AGENT_MIDDLEWARE_STRATEGY, AIModelProviderNotFoundException, AIModelProviderRegistry, AIModelProviderStrategy, AI_MODEL_PROVIDER, AdapterDataSourceStrategy, AgentMiddlewareRegistry, AgentMiddlewareStrategy, AiModelNotFoundException, BaseHTTPQueryRunner, BaseQueryRunner, BaseSQLQueryRunner, BaseStrategyRegistry, BaseTool, BaseToolset, BuiltinToolset, ChatOAICompatReasoningModel, CommonParameterRules, CreateModelClientCommand, CredentialsValidateFailedError, DATASOURCE_STRATEGY, DBCreateTableMode, DBProtocolEnum, DBSyntaxEnum, DBTableAction, DBTableDataAction, DOCUMENT_SOURCE_STRATEGY, DOCUMENT_TRANSFORMER_STRATEGY, DataSourceStrategy, DataSourceStrategyRegistry, DocumentSourceRegistry, DocumentSourceStrategy, DocumentTransformerRegistry, DocumentTransformerStrategy, GLOBAL_ORGANIZATION_SCOPE, IMAGE_UNDERSTANDING_STRATEGY, INTEGRATION_STRATEGY, ImageUnderstandingRegistry, ImageUnderstandingStrategy, IntegrationStrategyKey, IntegrationStrategyRegistry, JUMP_TO_TARGETS, JsonSchemaValidator, KNOWLEDGE_STRATEGY, KnowledgeStrategyKey, KnowledgeStrategyRegistry, LLMUsage, LargeLanguageModel, ModelProvider, ORGANIZATION_METADATA_KEY, OpenAICompatibleReranker, PLUGIN_METADATA, PLUGIN_METADATA_KEY, 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, RETRIEVER_STRATEGY, RequestContext, RequestContextMiddleware, RerankModel, RetrieverRegistry, RetrieverStrategy, STRATEGY_META_KEY, Speech2TextChatModel, SpeechToTextModel, StrategyBus, TEXT_SPLITTER_STRATEGY, TOOLSET_STRATEGY, TextEmbeddingModelManager, TextSplitterRegistry, TextSplitterStrategy, TextToSpeechModel, ToolsetRegistry, ToolsetStrategy, VECTOR_STORE_STRATEGY, VectorStoreRegistry, VectorStoreStrategy, WORKFLOW_NODE_STRATEGY, WORKFLOW_TRIGGER_STRATEGY, WorkflowNodeRegistry, WorkflowNodeStrategy, WorkflowTriggerRegistry, WorkflowTriggerStrategy, WrapWorkflowNodeExecutionCommand, XpFileSystem, XpertServerPlugin, als, calcTokenUsage, countTokensSafe, createI18nInstance, createPluginLogger, downloadRemoteFile, getErrorMessage, getPositionList, getPositionMap, getRequestContext, isRemoteFile, loadYamlFile, mergeCredentials, mergeParentChildChunks, runWithRequestContext, sumTokenUsage };
2403
+ /**
2404
+ * Structured message types (suggested format):
2405
+ * - channel.{provider}.{action}.v{number}
2406
+ * - agent.{action}.v{number}
2407
+ * - system.{action}.v{number}
2408
+ * - plugin.{domain}.{action}.v{number}
2409
+ *
2410
+ * Note: At runtime, any string type is still allowed, facilitating dynamic extension by plugins.
2411
+ */ const SEGMENT_PATTERN = /^[a-z][a-z0-9_-]*$/i;
2412
+ const VERSION_PATTERN = /^v[1-9][0-9]*$/;
2413
+ function assertSegment(input, name) {
2414
+ if (!SEGMENT_PATTERN.test(input)) {
2415
+ throw new Error(`Invalid ${name} segment: "${input}"`);
2416
+ }
2417
+ }
2418
+ /**
2419
+ * Unified construction of channel message types to avoid manual string errors.
2420
+ * Example: channel.lark.inbound.v1
2421
+ */ function defineChannelMessageType(provider, action, version) {
2422
+ assertSegment(provider, 'provider');
2423
+ assertSegment(action, 'action');
2424
+ if (!Number.isInteger(version) || version <= 0) {
2425
+ throw new Error(`Invalid version: "${version}"`);
2426
+ }
2427
+ return `channel.${provider}.${action}.v${version}`;
2428
+ }
2429
+ /**
2430
+ * Unified construction of agent message types.
2431
+ * Example: agent.handoff.v1
2432
+ */ function defineAgentMessageType(action, version) {
2433
+ assertSegment(action, 'action');
2434
+ if (!Number.isInteger(version) || version <= 0) {
2435
+ throw new Error(`Invalid version: "${version}"`);
2436
+ }
2437
+ return `agent.${action}.v${version}`;
2438
+ }
2439
+ /**
2440
+ * Check if a type conforms to the structured naming convention (format only, no semantic validation).
2441
+ */ function isStructuredMessageType(type) {
2442
+ const parts = type.split('.');
2443
+ if (parts.length < 3) {
2444
+ return false;
2445
+ }
2446
+ const version = parts[parts.length - 1];
2447
+ if (!VERSION_PATTERN.test(version)) {
2448
+ return false;
2449
+ }
2450
+ return parts.slice(0, -1).every((part)=>SEGMENT_PATTERN.test(part));
2451
+ }
2452
+
2453
+ const AGENT_CHAT_DISPATCH_MESSAGE_TYPE = defineAgentMessageType('chat_dispatch', 1);
2454
+
2455
+ /**
2456
+ * Handoff Processor meta key。
2457
+ */ const HANDOFF_PROCESSOR_STRATEGY = 'HANDOFF_PROCESSOR_STRATEGY';
2458
+ /**
2459
+ * Declare on a provider:
2460
+ * 1) Which message types it handles
2461
+ * 2) Default execution policy (lane/timeout)
2462
+ */ function HandoffProcessorStrategy(provider, metadata) {
2463
+ var _metadata_types;
2464
+ if (!(metadata == null ? void 0 : (_metadata_types = metadata.types) == null ? void 0 : _metadata_types.length)) {
2465
+ throw new Error('HandoffProcessor requires at least one message type');
2466
+ }
2467
+ return applyDecorators(SetMetadata(HANDOFF_PROCESSOR_STRATEGY, provider), SetMetadata(STRATEGY_META_KEY, HANDOFF_PROCESSOR_STRATEGY));
2468
+ }
2469
+
2470
+ let HandoffProcessorRegistry = class HandoffProcessorRegistry extends BaseStrategyRegistry {
2471
+ constructor(discoveryService, reflector){
2472
+ super(HANDOFF_PROCESSOR_STRATEGY, discoveryService, reflector);
2473
+ }
2474
+ };
2475
+ HandoffProcessorRegistry = __decorate([
2476
+ Injectable(),
2477
+ __metadata("design:type", Function),
2478
+ __metadata("design:paramtypes", [
2479
+ typeof DiscoveryService === "undefined" ? Object : DiscoveryService,
2480
+ typeof Reflector === "undefined" ? Object : Reflector
2481
+ ])
2482
+ ], HandoffProcessorRegistry);
2483
+
2484
+ /**
2485
+ * Handoff execution types.
2486
+ *
2487
+ * Note:
2488
+ * - Two-gate lane/session permit logic has been removed.
2489
+ * - Lane is now an execution tag for observability and soft policy only.
2490
+ */ const DEFAULT_EXECUTION_CONFIG = {
2491
+ lanes: {
2492
+ main: 8,
2493
+ subagent: 16,
2494
+ cron: 4,
2495
+ nested: 8
2496
+ },
2497
+ runTtlMs: 10 * 60 * 1000
2498
+ };
2499
+
2500
+ /**
2501
+ * Common platform message length limits
2502
+ */ const CHAT_CHANNEL_TEXT_LIMITS = {
2503
+ lark: 4000,
2504
+ wecom: 2048,
2505
+ dingtalk: 4000,
2506
+ slack: 4000,
2507
+ telegram: 4096,
2508
+ discord: 2000
2509
+ };
2510
+ /**
2511
+ * Chunk long text by specified length
2512
+ *
2513
+ * @param text - Text to chunk
2514
+ * @param limit - Maximum characters per chunk
2515
+ * @param mode - Chunking mode: 'text' splits by character, 'markdown' tries to preserve paragraphs
2516
+ * @returns Array of chunked text
2517
+ */ function chunkText(text, limit, mode = 'text') {
2518
+ if (!text || text.length <= limit) {
2519
+ return [
2520
+ text
2521
+ ];
2522
+ }
2523
+ const chunks = [];
2524
+ if (mode === 'markdown') {
2525
+ // Markdown mode: try to split at paragraph boundaries
2526
+ const paragraphs = text.split(/\n\n+/);
2527
+ let currentChunk = '';
2528
+ for (const para of paragraphs){
2529
+ if (currentChunk.length + para.length + 2 <= limit) {
2530
+ currentChunk += (currentChunk ? '\n\n' : '') + para;
2531
+ } else if (para.length > limit) {
2532
+ // Paragraph itself is too long, need hard split
2533
+ if (currentChunk) {
2534
+ chunks.push(currentChunk);
2535
+ currentChunk = '';
2536
+ }
2537
+ let remaining = para;
2538
+ while(remaining.length > limit){
2539
+ chunks.push(remaining.slice(0, limit));
2540
+ remaining = remaining.slice(limit);
2541
+ }
2542
+ currentChunk = remaining;
2543
+ } else {
2544
+ if (currentChunk) {
2545
+ chunks.push(currentChunk);
2546
+ }
2547
+ currentChunk = para;
2548
+ }
2549
+ }
2550
+ if (currentChunk) {
2551
+ chunks.push(currentChunk);
2552
+ }
2553
+ } else {
2554
+ // Plain text mode: split directly by length
2555
+ let remaining = text;
2556
+ while(remaining.length > limit){
2557
+ chunks.push(remaining.slice(0, limit));
2558
+ remaining = remaining.slice(limit);
2559
+ }
2560
+ if (remaining) {
2561
+ chunks.push(remaining);
2562
+ }
2563
+ }
2564
+ return chunks;
2565
+ }
2566
+
2567
+ /**
2568
+ * Metadata key for chat channel
2569
+ */ const CHAT_CHANNEL = 'CHAT_CHANNEL';
2570
+ /**
2571
+ * Decorator for chat channel implementations
2572
+ *
2573
+ * Use this decorator to register a chat channel implementation.
2574
+ * The decorated class will be automatically discovered and registered
2575
+ * to ChatChannelRegistry on module initialization.
2576
+ *
2577
+ * @param type - The channel type identifier (e.g., 'lark', 'wecom', 'dingtalk')
2578
+ *
2579
+ * @example
2580
+ * ```typescript
2581
+ * @Injectable()
2582
+ * @ChatChannel('lark')
2583
+ * export class LarkChatChannel implements IChatChannel {
2584
+ * // Implementation
2585
+ * }
2586
+ * ```
2587
+ */ const ChatChannel = (type)=>SetMetadata(CHAT_CHANNEL, type);
2588
+
2589
+ let ChatChannelRegistry = class ChatChannelRegistry extends BaseStrategyRegistry {
2590
+ constructor(discoveryService, reflector){
2591
+ super(CHAT_CHANNEL, discoveryService, reflector);
2592
+ }
2593
+ };
2594
+ ChatChannelRegistry = __decorate([
2595
+ Injectable(),
2596
+ __metadata("design:type", Function),
2597
+ __metadata("design:paramtypes", [
2598
+ typeof DiscoveryService === "undefined" ? Object : DiscoveryService,
2599
+ typeof Reflector === "undefined" ? Object : Reflector
2600
+ ])
2601
+ ], ChatChannelRegistry);
2602
+
2603
+ class CancelConversationCommand {
2604
+ constructor(input){
2605
+ this.input = input;
2606
+ }
2607
+ }
2608
+ CancelConversationCommand.type = '[Chat Conversation] Cancel';
2609
+
2610
+ /**
2611
+ * Protocol definition for pluggable memory backends.
2612
+ *
2613
+ * This module defines the BackendProtocol that all backend implementations
2614
+ * must follow. Backends can store files in different locations (state, filesystem,
2615
+ * database, etc.) and provide a uniform interface for file operations.
2616
+ */ /**
2617
+ * Type guard to check if a backend supports execution.
2618
+ *
2619
+ * @param backend - Backend instance to check
2620
+ * @returns True if the backend implements SandboxBackendProtocol
2621
+ */ function isSandboxBackend(backend) {
2622
+ return typeof backend.execute === "function" && typeof backend.id === "string";
2623
+ }
2624
+
2625
+ /**
2626
+ * BaseSandbox: Abstract base class for sandbox backends with command execution.
2627
+ *
2628
+ * This class provides default implementations for all SandboxBackendProtocol
2629
+ * methods using shell commands executed via execute(). Concrete implementations
2630
+ * only need to implement the execute() method.
2631
+ *
2632
+ * Requires Node.js 20+ on the sandbox host.
2633
+ */ /**
2634
+ * Node.js command template for glob operations.
2635
+ * Uses web-standard atob() for base64 decoding.
2636
+ */ function buildGlobCommand(searchPath, pattern) {
2637
+ const pathB64 = btoa(searchPath);
2638
+ const patternB64 = btoa(pattern);
2639
+ return `node -e "
2640
+ const fs = require('fs');
2641
+ const path = require('path');
2642
+
2643
+ const searchPath = atob('${pathB64}');
2644
+ const pattern = atob('${patternB64}');
2645
+
2646
+ function globMatch(relativePath, pattern) {
2647
+ const regexPattern = pattern
2648
+ .replace(/\\*\\*/g, '<<<GLOBSTAR>>>')
2649
+ .replace(/\\*/g, '[^/]*')
2650
+ .replace(/\\?/g, '.')
2651
+ .replace(/<<<GLOBSTAR>>>/g, '.*');
2652
+ return new RegExp('^' + regexPattern + '$').test(relativePath);
2653
+ }
2654
+
2655
+ function walkDir(dir, baseDir, results) {
2656
+ try {
2657
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
2658
+ for (const entry of entries) {
2659
+ const fullPath = path.join(dir, entry.name);
2660
+ const relativePath = path.relative(baseDir, fullPath);
2661
+ if (entry.isDirectory()) {
2662
+ walkDir(fullPath, baseDir, results);
2663
+ } else if (globMatch(relativePath, pattern)) {
2664
+ const stat = fs.statSync(fullPath);
2665
+ console.log(JSON.stringify({
2666
+ path: relativePath,
2667
+ size: stat.size,
2668
+ mtime: stat.mtimeMs,
2669
+ isDir: false
2670
+ }));
2671
+ }
2672
+ }
2673
+ } catch (e) {
2674
+ // Silent failure for non-existent paths
2675
+ }
2676
+ }
2677
+
2678
+ try {
2679
+ process.chdir(searchPath);
2680
+ walkDir('.', '.', []);
2681
+ } catch (e) {
2682
+ // Silent failure for non-existent paths
2683
+ }
2684
+ "`;
2685
+ }
2686
+ /**
2687
+ * Node.js command template for listing directory contents.
2688
+ */ function buildLsCommand(dirPath) {
2689
+ const pathB64 = btoa(dirPath);
2690
+ return `node -e "
2691
+ const fs = require('fs');
2692
+ const path = require('path');
2693
+
2694
+ const dirPath = atob('${pathB64}');
2695
+
2696
+ try {
2697
+ const entries = fs.readdirSync(dirPath, { withFileTypes: true });
2698
+ for (const entry of entries) {
2699
+ const fullPath = path.join(dirPath, entry.name);
2700
+ const stat = fs.statSync(fullPath);
2701
+ console.log(JSON.stringify({
2702
+ path: entry.isDirectory() ? fullPath + '/' : fullPath,
2703
+ size: stat.size,
2704
+ mtime: stat.mtimeMs,
2705
+ isDir: entry.isDirectory()
2706
+ }));
2707
+ }
2708
+ } catch (e) {
2709
+ console.error('Error: ' + e.message);
2710
+ process.exit(1);
2711
+ }
2712
+ "`;
2713
+ }
2714
+ /**
2715
+ * Node.js command template for reading files.
2716
+ */ function buildReadCommand(filePath, offset, limit) {
2717
+ const pathB64 = btoa(filePath);
2718
+ // Coerce offset and limit to safe non-negative integers before embedding in the shell command.
2719
+ const safeOffset = Number.isFinite(offset) && offset > 0 ? Math.floor(offset) : 0;
2720
+ const safeLimit = Number.isFinite(limit) && limit > 0 && limit < Number.MAX_SAFE_INTEGER ? Math.floor(limit) : 0;
2721
+ return `node -e "
2722
+ const fs = require('fs');
2723
+
2724
+ const filePath = atob('${pathB64}');
2725
+ const offset = ${safeOffset};
2726
+ const limit = ${safeLimit};
2727
+
2728
+ if (!fs.existsSync(filePath)) {
2729
+ console.log('Error: File not found');
2730
+ process.exit(1);
2731
+ }
2732
+
2733
+ const stat = fs.statSync(filePath);
2734
+ if (stat.size === 0) {
2735
+ console.log('System reminder: File exists but has empty contents');
2736
+ process.exit(0);
2737
+ }
2738
+
2739
+ const content = fs.readFileSync(filePath, 'utf-8');
2740
+ const lines = content.split('\\n');
2741
+ const selected = lines.slice(offset, offset + limit);
2742
+
2743
+ for (let i = 0; i < selected.length; i++) {
2744
+ const lineNum = offset + i + 1;
2745
+ console.log(String(lineNum).padStart(6) + '\\t' + selected[i]);
2746
+ }
2747
+ "`;
2748
+ }
2749
+ /**
2750
+ * Node.js command template for writing files.
2751
+ */ function buildWriteCommand(filePath, content) {
2752
+ const pathB64 = btoa(filePath);
2753
+ const contentB64 = btoa(content);
2754
+ return `node -e "
2755
+ const fs = require('fs');
2756
+ const path = require('path');
2757
+
2758
+ const filePath = atob('${pathB64}');
2759
+ const content = atob('${contentB64}');
2760
+
2761
+ if (fs.existsSync(filePath)) {
2762
+ console.error('Error: File already exists');
2763
+ process.exit(1);
2764
+ }
2765
+
2766
+ const parentDir = path.dirname(filePath) || '.';
2767
+ fs.mkdirSync(parentDir, { recursive: true });
2768
+
2769
+ fs.writeFileSync(filePath, content, 'utf-8');
2770
+ console.log('OK');
2771
+ "`;
2772
+ }
2773
+ /**
2774
+ * Node.js command template for editing files.
2775
+ */ function buildEditCommand(filePath, oldStr, newStr, replaceAll) {
2776
+ const pathB64 = btoa(filePath);
2777
+ const oldB64 = btoa(oldStr);
2778
+ const newB64 = btoa(newStr);
2779
+ return `node -e "
2780
+ const fs = require('fs');
2781
+
2782
+ const filePath = atob('${pathB64}');
2783
+ const oldStr = atob('${oldB64}');
2784
+ const newStr = atob('${newB64}');
2785
+ const replaceAll = ${Boolean(replaceAll)};
2786
+
2787
+ let text;
2788
+ try {
2789
+ text = fs.readFileSync(filePath, 'utf-8');
2790
+ } catch (e) {
2791
+ process.exit(3);
2792
+ }
2793
+
2794
+ const count = text.split(oldStr).length - 1;
2795
+
2796
+ if (count === 0) {
2797
+ process.exit(1);
2798
+ }
2799
+ if (count > 1 && !replaceAll) {
2800
+ process.exit(2);
2801
+ }
2802
+
2803
+ const result = text.split(oldStr).join(newStr);
2804
+ fs.writeFileSync(filePath, result, 'utf-8');
2805
+ console.log(count);
2806
+ "`;
2807
+ }
2808
+ /**
2809
+ * Node.js command template for grep operations.
2810
+ */ function buildGrepCommand(pattern, searchPath, globPattern) {
2811
+ const patternB64 = btoa(pattern);
2812
+ const pathB64 = btoa(searchPath);
2813
+ const globB64 = globPattern ? btoa(globPattern) : "";
2814
+ return `node -e "
2815
+ const fs = require('fs');
2816
+ const path = require('path');
2817
+
2818
+ const pattern = atob('${patternB64}');
2819
+ const searchPath = atob('${pathB64}');
2820
+ const globPattern = ${globPattern ? `atob('${globB64}')` : "null"};
2821
+
2822
+ let regex;
2823
+ try {
2824
+ regex = new RegExp(pattern);
2825
+ } catch (e) {
2826
+ console.error('Invalid regex: ' + e.message);
2827
+ process.exit(1);
2828
+ }
2829
+
2830
+ function globMatch(filePath, pattern) {
2831
+ if (!pattern) return true;
2832
+ const regexPattern = pattern
2833
+ .replace(/\\*\\*/g, '<<<GLOBSTAR>>>')
2834
+ .replace(/\\*/g, '[^/]*')
2835
+ .replace(/\\?/g, '.')
2836
+ .replace(/<<<GLOBSTAR>>>/g, '.*');
2837
+ return new RegExp('^' + regexPattern + '$').test(filePath);
2838
+ }
2839
+
2840
+ function walkDir(dir, results) {
2841
+ try {
2842
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
2843
+ for (const entry of entries) {
2844
+ const fullPath = path.join(dir, entry.name);
2845
+ if (entry.isDirectory()) {
2846
+ walkDir(fullPath, results);
2847
+ } else {
2848
+ const relativePath = path.relative(searchPath, fullPath);
2849
+ if (globMatch(relativePath, globPattern)) {
2850
+ try {
2851
+ const content = fs.readFileSync(fullPath, 'utf-8');
2852
+ const lines = content.split('\\n');
2853
+ for (let i = 0; i < lines.length; i++) {
2854
+ if (regex.test(lines[i])) {
2855
+ console.log(JSON.stringify({
2856
+ path: fullPath,
2857
+ line: i + 1,
2858
+ text: lines[i]
2859
+ }));
2860
+ }
2861
+ }
2862
+ } catch (e) {
2863
+ // Skip unreadable files
2864
+ }
2865
+ }
2866
+ }
2867
+ }
2868
+ } catch (e) {
2869
+ // Skip unreadable directories
2870
+ }
2871
+ }
2872
+
2873
+ try {
2874
+ walkDir(searchPath, []);
2875
+ } catch (e) {
2876
+ // Silent failure
2877
+ }
2878
+ "`;
2879
+ }
2880
+ /**
2881
+ * Base sandbox implementation with execute() as the only abstract method.
2882
+ *
2883
+ * This class provides default implementations for all SandboxBackendProtocol
2884
+ * methods using shell commands executed via execute(). Concrete implementations
2885
+ * only need to implement the execute() method.
2886
+ *
2887
+ * Requires Node.js 20+ on the sandbox host.
2888
+ */ class BaseSandbox {
2889
+ /**
2890
+ * List files and directories in the specified directory (non-recursive).
2891
+ *
2892
+ * @param path - Absolute path to directory
2893
+ * @returns List of FileInfo objects for files and directories directly in the directory.
2894
+ */ async lsInfo(path) {
2895
+ const command = buildLsCommand(path);
2896
+ const result = await this.execute(command);
2897
+ if (result.exitCode !== 0) {
2898
+ return [];
2899
+ }
2900
+ const infos = [];
2901
+ const lines = result.output.trim().split("\n").filter(Boolean);
2902
+ for (const line of lines){
2903
+ try {
2904
+ const parsed = JSON.parse(line);
2905
+ infos.push({
2906
+ path: parsed.path,
2907
+ is_dir: parsed.isDir,
2908
+ size: parsed.size,
2909
+ modified_at: parsed.mtime ? new Date(parsed.mtime).toISOString() : undefined
2910
+ });
2911
+ } catch (e) {
2912
+ // Skip invalid JSON lines
2913
+ }
2914
+ }
2915
+ return infos;
2916
+ }
2917
+ /**
2918
+ * Read file content with line numbers.
2919
+ *
2920
+ * @param filePath - Absolute file path
2921
+ * @param offset - Line offset to start reading from (0-indexed)
2922
+ * @param limit - Maximum number of lines to read
2923
+ * @returns Formatted file content with line numbers, or error message
2924
+ */ async read(filePath, offset = 0, limit = 500) {
2925
+ const command = buildReadCommand(filePath, offset, limit);
2926
+ const result = await this.execute(command);
2927
+ if (result.exitCode !== 0) {
2928
+ return `Error: File '${filePath}' not found`;
2929
+ }
2930
+ return result.output;
2931
+ }
2932
+ /**
2933
+ * Structured search results or error string for invalid input.
2934
+ */ async grepRaw(pattern, path = "/", glob = null) {
2935
+ const command = buildGrepCommand(pattern, path, glob);
2936
+ const result = await this.execute(command);
2937
+ if (result.exitCode === 1) {
2938
+ // Check if it's a regex error
2939
+ if (result.output.includes("Invalid regex:")) {
2940
+ return result.output.trim();
2941
+ }
2942
+ }
2943
+ const matches = [];
2944
+ const lines = result.output.trim().split("\n").filter(Boolean);
2945
+ for (const line of lines){
2946
+ try {
2947
+ const parsed = JSON.parse(line);
2948
+ matches.push({
2949
+ path: parsed.path,
2950
+ line: parsed.line,
2951
+ text: parsed.text
2952
+ });
2953
+ } catch (e) {
2954
+ // Skip invalid JSON lines
2955
+ }
2956
+ }
2957
+ return matches;
2958
+ }
2959
+ /**
2960
+ * Structured glob matching returning FileInfo objects.
2961
+ */ async globInfo(pattern, path = "/") {
2962
+ const command = buildGlobCommand(path, pattern);
2963
+ const result = await this.execute(command);
2964
+ const infos = [];
2965
+ const lines = result.output.trim().split("\n").filter(Boolean);
2966
+ for (const line of lines){
2967
+ try {
2968
+ const parsed = JSON.parse(line);
2969
+ infos.push({
2970
+ path: parsed.path,
2971
+ is_dir: parsed.isDir,
2972
+ size: parsed.size,
2973
+ modified_at: parsed.mtime ? new Date(parsed.mtime).toISOString() : undefined
2974
+ });
2975
+ } catch (e) {
2976
+ // Skip invalid JSON lines
2977
+ }
2978
+ }
2979
+ return infos;
2980
+ }
2981
+ /**
2982
+ * Create a new file with content.
2983
+ */ async write(filePath, content) {
2984
+ const command = buildWriteCommand(filePath, content);
2985
+ const result = await this.execute(command);
2986
+ if (result.exitCode !== 0) {
2987
+ return {
2988
+ error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.`
2989
+ };
2990
+ }
2991
+ return {
2992
+ path: filePath,
2993
+ filesUpdate: null
2994
+ };
2995
+ }
2996
+ /**
2997
+ * Edit a file by replacing string occurrences.
2998
+ */ async edit(filePath, oldString, newString, replaceAll = false) {
2999
+ const command = buildEditCommand(filePath, oldString, newString, replaceAll);
3000
+ const result = await this.execute(command);
3001
+ switch(result.exitCode){
3002
+ case 0:
3003
+ {
3004
+ const occurrences = parseInt(result.output.trim(), 10) || 1;
3005
+ return {
3006
+ path: filePath,
3007
+ filesUpdate: null,
3008
+ occurrences
3009
+ };
3010
+ }
3011
+ case 1:
3012
+ return {
3013
+ error: `String not found in file '${filePath}'`
3014
+ };
3015
+ case 2:
3016
+ return {
3017
+ error: `Multiple occurrences found in '${filePath}'. Use replaceAll=true to replace all.`
3018
+ };
3019
+ case 3:
3020
+ return {
3021
+ error: `Error: File '${filePath}' not found`
3022
+ };
3023
+ default:
3024
+ return {
3025
+ error: `Unknown error editing file '${filePath}'`
3026
+ };
3027
+ }
3028
+ }
3029
+ }
3030
+
3031
+ const SANDBOX_PROVIDER = 'SANDBOX_PROVIDER';
3032
+ const SandboxProviderStrategy = (provider)=>applyDecorators(SetMetadata(SANDBOX_PROVIDER, provider), SetMetadata(STRATEGY_META_KEY, SANDBOX_PROVIDER));
3033
+
3034
+ let SandboxProviderRegistry = class SandboxProviderRegistry extends BaseStrategyRegistry {
3035
+ constructor(discoveryService, reflector){
3036
+ super(SANDBOX_PROVIDER, discoveryService, reflector);
3037
+ }
3038
+ };
3039
+ SandboxProviderRegistry = __decorate([
3040
+ Injectable(),
3041
+ __metadata("design:type", Function),
3042
+ __metadata("design:paramtypes", [
3043
+ typeof DiscoveryService === "undefined" ? Object : DiscoveryService,
3044
+ typeof Reflector === "undefined" ? Object : Reflector
3045
+ ])
3046
+ ], SandboxProviderRegistry);
3047
+
3048
+ export { AGENT_CHAT_DISPATCH_MESSAGE_TYPE, AGENT_MIDDLEWARE_STRATEGY, AIModelProviderNotFoundException, AIModelProviderRegistry, AIModelProviderStrategy, AI_MODEL_PROVIDER, ANALYTICS_PERMISSION_SERVICE_TOKEN, AdapterDataSourceStrategy, AgentMiddlewareRegistry, AgentMiddlewareStrategy, AiModelNotFoundException, BaseHTTPQueryRunner, BaseQueryRunner, BaseSQLQueryRunner, BaseSandbox, BaseStrategyRegistry, BaseTool, BaseToolset, BuiltinToolset, CHAT_CHANNEL, CHAT_CHANNEL_TEXT_LIMITS, CancelConversationCommand, ChatChannel, ChatChannelRegistry, ChatOAICompatReasoningModel, CommonParameterRules, CreateModelClientCommand, CredentialsValidateFailedError, DATASOURCE_STRATEGY, DBCreateTableMode, DBProtocolEnum, DBSyntaxEnum, DBTableAction, DBTableDataAction, DEFAULT_EXECUTION_CONFIG, DOCUMENT_SOURCE_STRATEGY, DOCUMENT_TRANSFORMER_STRATEGY, DataSourceStrategy, DataSourceStrategyRegistry, DocumentSourceRegistry, DocumentSourceStrategy, DocumentTransformerRegistry, DocumentTransformerStrategy, 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, LLMUsage, LargeLanguageModel, ModelProvider, ORGANIZATION_METADATA_KEY, OpenAICompatibleReranker, PERMISSION_OPERATION_METADATA_KEY, PLUGIN_METADATA, PLUGIN_METADATA_KEY, 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, RETRIEVER_STRATEGY, RequestContext, RequestContextMiddleware, RequirePermissionOperation, RerankModel, RetrieverRegistry, RetrieverStrategy, SANDBOX_PROVIDER, STRATEGY_META_KEY, SandboxProviderRegistry, SandboxProviderStrategy, Speech2TextChatModel, SpeechToTextModel, StrategyBus, TEXT_SPLITTER_STRATEGY, TOOLSET_STRATEGY, TextEmbeddingModelManager, TextSplitterRegistry, TextSplitterStrategy, TextToSpeechModel, ToolsetRegistry, ToolsetStrategy, USER_PERMISSION_SERVICE_TOKEN, VECTOR_STORE_STRATEGY, VectorStoreRegistry, VectorStoreStrategy, WORKFLOW_NODE_STRATEGY, WORKFLOW_TRIGGER_STRATEGY, WorkflowNodeRegistry, WorkflowNodeStrategy, WorkflowTriggerRegistry, WorkflowTriggerStrategy, WrapWorkflowNodeExecutionCommand, XpFileSystem, XpertServerPlugin, als, calcTokenUsage, chunkText, countTokensSafe, createI18nInstance, createPluginLogger, defineAgentMessageType, defineChannelMessageType, downloadRemoteFile, getErrorMessage, getModelContextSize, getPermissionOperationMetadata, getPositionList, getPositionMap, getRequestContext, getRequiredPermissionOperation, isRemoteFile, isSandboxBackend, isStructuredMessageType, loadYamlFile, mergeCredentials, mergeParentChildChunks, normalizeContextSize, runWithRequestContext, sumTokenUsage };