@xpert-ai/plugin-sdk 3.7.2 → 3.8.1

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 +1282 -0
  2. package/index.esm.js +1256 -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 +383 -0
  32. package/src/lib/sandbox/sandbox.d.ts +103 -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.
@@ -510,6 +511,7 @@ WorkflowNodeRegistry = __decorate([
510
511
  ])
511
512
  ], WorkflowNodeRegistry);
512
513
 
514
+ const COMMAND_METADATA$1 = '__command__';
513
515
  /**
514
516
  * Wrap Workflow Node Execution Command
515
517
  */ class WrapWorkflowNodeExecutionCommand extends Command {
@@ -520,6 +522,9 @@ WorkflowNodeRegistry = __decorate([
520
522
  }
521
523
  }
522
524
  WrapWorkflowNodeExecutionCommand.type = '[Workflow] Wrap Workflow Node Execution';
525
+ Reflect.defineMetadata(COMMAND_METADATA$1, {
526
+ id: WrapWorkflowNodeExecutionCommand.type
527
+ }, WrapWorkflowNodeExecutionCommand);
523
528
 
524
529
  const VECTOR_STORE_STRATEGY = 'VECTOR_STORE_STRATEGY';
525
530
  const VectorStoreStrategy = (provider)=>applyDecorators(SetMetadata(VECTOR_STORE_STRATEGY, provider), SetMetadata(STRATEGY_META_KEY, VECTOR_STORE_STRATEGY));
@@ -931,6 +936,52 @@ BuiltinToolset.provider = '';
931
936
  }
932
937
  }
933
938
 
939
+ /**
940
+ * System token for resolving integration read service from plugin context.
941
+ */ const INTEGRATION_PERMISSION_SERVICE_TOKEN = 'XPERT_PLUGIN_INTEGRATION_PERMISSION_SERVICE';
942
+
943
+ /**
944
+ * System token for resolving analytics permission service from plugin context.
945
+ */ const ANALYTICS_PERMISSION_SERVICE_TOKEN = 'XPERT_PLUGIN_ANALYTICS_PERMISSION_SERVICE';
946
+
947
+ const PERMISSION_OPERATION_METADATA_KEY = 'XPERT_PLUGIN_PERMISSION_OPERATION';
948
+ function RequirePermissionOperation(permissionType, operation) {
949
+ return (_target, _propertyKey, descriptor)=>{
950
+ const method = descriptor.value;
951
+ if (typeof method !== 'function') {
952
+ throw new Error('RequirePermissionOperation can only be applied to methods');
953
+ }
954
+ Reflect.defineMetadata(PERMISSION_OPERATION_METADATA_KEY, {
955
+ permissionType,
956
+ operation
957
+ }, method);
958
+ };
959
+ }
960
+ function getPermissionOperationMetadata(method) {
961
+ if (typeof method !== 'function') {
962
+ return undefined;
963
+ }
964
+ return Reflect.getMetadata(PERMISSION_OPERATION_METADATA_KEY, method);
965
+ }
966
+ function getRequiredPermissionOperation(method, permissionType) {
967
+ const metadata = getPermissionOperationMetadata(method);
968
+ if (!metadata || metadata.permissionType !== permissionType) {
969
+ return undefined;
970
+ }
971
+ return metadata.operation;
972
+ }
973
+
974
+ /**
975
+ * System token for resolving handoff queue service from plugin context.
976
+ */ const HANDOFF_PERMISSION_SERVICE_TOKEN = 'XPERT_PLUGIN_HANDOFF_PERMISSION_SERVICE';
977
+ /**
978
+ * Internal system token used by core to expose the handoff queue bridge.
979
+ */ const HANDOFF_QUEUE_SERVICE_TOKEN = 'XPERT_HANDOFF_QUEUE_SERVICE';
980
+
981
+ /**
982
+ * System token for resolving user permission service from plugin context.
983
+ */ const USER_PERMISSION_SERVICE_TOKEN = 'XPERT_PLUGIN_USER_PERMISSION_SERVICE';
984
+
934
985
  async function createI18nInstance(pluginDir, language) {
935
986
  const instance = createInstance();
936
987
  const i18nDir = path__default.join(pluginDir, 'i18n');
@@ -1345,6 +1396,18 @@ function AIModelProviderStrategy(provider) {
1345
1396
  if (file == null ? void 0 : file.startsWith('file:///')) {
1346
1397
  file = file.replace('file://', '');
1347
1398
  }
1399
+ // Strip :line:col suffix (e.g. "/path/file.js:37:5" -> "/path/file.js")
1400
+ if (file) {
1401
+ file = file.replace(/:\d+:\d+$/, '');
1402
+ }
1403
+ // Decode URL-encoded paths (e.g. Chinese characters: %E9%A1%B9%E7%9B%AE -> 项目)
1404
+ if (file) {
1405
+ try {
1406
+ file = decodeURIComponent(file);
1407
+ } catch (e) {
1408
+ // keep as-is if decode fails
1409
+ }
1410
+ }
1348
1411
  const dir = file ? path__default.dirname(file) : process.cwd();
1349
1412
  return function(target) {
1350
1413
  SetMetadata(STRATEGY_META_KEY, AI_MODEL_PROVIDER)(target);
@@ -2263,6 +2326,49 @@ class Speech2TextChatModel extends BaseChatModel {
2263
2326
  return 0;
2264
2327
  }
2265
2328
 
2329
+ function getModelContextSize(input) {
2330
+ if (isCopilotModel(input)) {
2331
+ var _input_options;
2332
+ return normalizeContextSize((_input_options = input.options) == null ? void 0 : _input_options[ModelPropertyKey.CONTEXT_SIZE]);
2333
+ }
2334
+ // Backward compatibility for langchain <1.0.0
2335
+ if (input.metadata && "profile" in input.metadata) {
2336
+ const profile = input.metadata['profile'];
2337
+ if ("maxInputTokens" in profile && (typeof profile.maxInputTokens === "number" || profile.maxInputTokens == null)) {
2338
+ var _profile_maxInputTokens;
2339
+ return (_profile_maxInputTokens = profile.maxInputTokens) != null ? _profile_maxInputTokens : undefined;
2340
+ }
2341
+ }
2342
+ // Langchain v1.0.0+
2343
+ if ("profile" in input && typeof input.profile === "object" && input.profile && "maxInputTokens" in input.profile && (typeof input.profile.maxInputTokens === "number" || input.profile.maxInputTokens == null)) {
2344
+ var _input_profile_maxInputTokens;
2345
+ return (_input_profile_maxInputTokens = input.profile.maxInputTokens) != null ? _input_profile_maxInputTokens : undefined;
2346
+ }
2347
+ if ("model" in input && typeof input.model === "string") {
2348
+ return getModelContextSize$1(input.model);
2349
+ }
2350
+ if ("modelName" in input && typeof input.modelName === "string") {
2351
+ return getModelContextSize$1(input.modelName);
2352
+ }
2353
+ return undefined;
2354
+ }
2355
+ function isCopilotModel(input) {
2356
+ return typeof input === "object" && input !== null && !("invoke" in input);
2357
+ }
2358
+ function normalizeContextSize(value) {
2359
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) {
2360
+ return Math.floor(value);
2361
+ }
2362
+ if (typeof value === "string") {
2363
+ const parsed = Number.parseInt(value, 10);
2364
+ if (Number.isFinite(parsed) && parsed > 0) {
2365
+ return parsed;
2366
+ }
2367
+ }
2368
+ return undefined;
2369
+ }
2370
+
2371
+ const COMMAND_METADATA = '__command__';
2266
2372
  /**
2267
2373
  * Get a Chat Model of copilot model and check it's token limitation, record the token usage
2268
2374
  */ class CreateModelClientCommand extends Command {
@@ -2273,6 +2379,9 @@ class Speech2TextChatModel extends BaseChatModel {
2273
2379
  }
2274
2380
  }
2275
2381
  CreateModelClientCommand.type = '[AI Model] Create Model Client';
2382
+ Reflect.defineMetadata(COMMAND_METADATA, {
2383
+ id: CreateModelClientCommand.type
2384
+ }, CreateModelClientCommand);
2276
2385
 
2277
2386
  const AGENT_MIDDLEWARE_STRATEGY = 'AGENT_MIDDLEWARE_STRATEGY';
2278
2387
  const AgentMiddlewareStrategy = (provider)=>applyDecorators(SetMetadata(AGENT_MIDDLEWARE_STRATEGY, provider), SetMetadata(STRATEGY_META_KEY, AGENT_MIDDLEWARE_STRATEGY));
@@ -2299,4 +2408,1150 @@ AgentMiddlewareRegistry = __decorate([
2299
2408
  "end"
2300
2409
  ];
2301
2410
 
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 };
2411
+ /**
2412
+ * Structured message types (suggested format):
2413
+ * - channel.{provider}.{action}.v{number}
2414
+ * - agent.{action}.v{number}
2415
+ * - system.{action}.v{number}
2416
+ * - plugin.{domain}.{action}.v{number}
2417
+ *
2418
+ * Note: At runtime, any string type is still allowed, facilitating dynamic extension by plugins.
2419
+ */ const SEGMENT_PATTERN = /^[a-z][a-z0-9_-]*$/i;
2420
+ const VERSION_PATTERN = /^v[1-9][0-9]*$/;
2421
+ function assertSegment(input, name) {
2422
+ if (!SEGMENT_PATTERN.test(input)) {
2423
+ throw new Error(`Invalid ${name} segment: "${input}"`);
2424
+ }
2425
+ }
2426
+ /**
2427
+ * Unified construction of channel message types to avoid manual string errors.
2428
+ * Example: channel.lark.inbound.v1
2429
+ */ function defineChannelMessageType(provider, action, version) {
2430
+ assertSegment(provider, 'provider');
2431
+ assertSegment(action, 'action');
2432
+ if (!Number.isInteger(version) || version <= 0) {
2433
+ throw new Error(`Invalid version: "${version}"`);
2434
+ }
2435
+ return `channel.${provider}.${action}.v${version}`;
2436
+ }
2437
+ /**
2438
+ * Unified construction of agent message types.
2439
+ * Example: agent.handoff.v1
2440
+ */ function defineAgentMessageType(action, version) {
2441
+ assertSegment(action, 'action');
2442
+ if (!Number.isInteger(version) || version <= 0) {
2443
+ throw new Error(`Invalid version: "${version}"`);
2444
+ }
2445
+ return `agent.${action}.v${version}`;
2446
+ }
2447
+ /**
2448
+ * Check if a type conforms to the structured naming convention (format only, no semantic validation).
2449
+ */ function isStructuredMessageType(type) {
2450
+ const parts = type.split('.');
2451
+ if (parts.length < 3) {
2452
+ return false;
2453
+ }
2454
+ const version = parts[parts.length - 1];
2455
+ if (!VERSION_PATTERN.test(version)) {
2456
+ return false;
2457
+ }
2458
+ return parts.slice(0, -1).every((part)=>SEGMENT_PATTERN.test(part));
2459
+ }
2460
+
2461
+ const AGENT_CHAT_DISPATCH_MESSAGE_TYPE = defineAgentMessageType('chat_dispatch', 1);
2462
+
2463
+ /**
2464
+ * Handoff Processor meta key。
2465
+ */ const HANDOFF_PROCESSOR_STRATEGY = 'HANDOFF_PROCESSOR_STRATEGY';
2466
+ /**
2467
+ * Declare on a provider:
2468
+ * 1) Which message types it handles
2469
+ * 2) Default execution policy (lane/timeout)
2470
+ */ function HandoffProcessorStrategy(provider, metadata) {
2471
+ var _metadata_types;
2472
+ if (!(metadata == null ? void 0 : (_metadata_types = metadata.types) == null ? void 0 : _metadata_types.length)) {
2473
+ throw new Error('HandoffProcessor requires at least one message type');
2474
+ }
2475
+ return applyDecorators(SetMetadata(HANDOFF_PROCESSOR_STRATEGY, provider), SetMetadata(STRATEGY_META_KEY, HANDOFF_PROCESSOR_STRATEGY));
2476
+ }
2477
+
2478
+ let HandoffProcessorRegistry = class HandoffProcessorRegistry extends BaseStrategyRegistry {
2479
+ constructor(discoveryService, reflector){
2480
+ super(HANDOFF_PROCESSOR_STRATEGY, discoveryService, reflector);
2481
+ }
2482
+ };
2483
+ HandoffProcessorRegistry = __decorate([
2484
+ Injectable(),
2485
+ __metadata("design:type", Function),
2486
+ __metadata("design:paramtypes", [
2487
+ typeof DiscoveryService === "undefined" ? Object : DiscoveryService,
2488
+ typeof Reflector === "undefined" ? Object : Reflector
2489
+ ])
2490
+ ], HandoffProcessorRegistry);
2491
+
2492
+ /**
2493
+ * Handoff execution types.
2494
+ *
2495
+ * Note:
2496
+ * - Two-gate lane/session permit logic has been removed.
2497
+ * - Lane is now an execution tag for observability and soft policy only.
2498
+ */ const DEFAULT_EXECUTION_CONFIG = {
2499
+ lanes: {
2500
+ main: 8,
2501
+ subagent: 16,
2502
+ cron: 4,
2503
+ nested: 8
2504
+ },
2505
+ runTtlMs: 10 * 60 * 1000
2506
+ };
2507
+
2508
+ /**
2509
+ * Common platform message length limits
2510
+ */ const CHAT_CHANNEL_TEXT_LIMITS = {
2511
+ lark: 4000,
2512
+ wecom: 2048,
2513
+ dingtalk: 4000,
2514
+ slack: 4000,
2515
+ telegram: 4096,
2516
+ discord: 2000
2517
+ };
2518
+ /**
2519
+ * Chunk long text by specified length
2520
+ *
2521
+ * @param text - Text to chunk
2522
+ * @param limit - Maximum characters per chunk
2523
+ * @param mode - Chunking mode: 'text' splits by character, 'markdown' tries to preserve paragraphs
2524
+ * @returns Array of chunked text
2525
+ */ function chunkText(text, limit, mode = 'text') {
2526
+ if (!text || text.length <= limit) {
2527
+ return [
2528
+ text
2529
+ ];
2530
+ }
2531
+ const chunks = [];
2532
+ if (mode === 'markdown') {
2533
+ // Markdown mode: try to split at paragraph boundaries
2534
+ const paragraphs = text.split(/\n\n+/);
2535
+ let currentChunk = '';
2536
+ for (const para of paragraphs){
2537
+ if (currentChunk.length + para.length + 2 <= limit) {
2538
+ currentChunk += (currentChunk ? '\n\n' : '') + para;
2539
+ } else if (para.length > limit) {
2540
+ // Paragraph itself is too long, need hard split
2541
+ if (currentChunk) {
2542
+ chunks.push(currentChunk);
2543
+ currentChunk = '';
2544
+ }
2545
+ let remaining = para;
2546
+ while(remaining.length > limit){
2547
+ chunks.push(remaining.slice(0, limit));
2548
+ remaining = remaining.slice(limit);
2549
+ }
2550
+ currentChunk = remaining;
2551
+ } else {
2552
+ if (currentChunk) {
2553
+ chunks.push(currentChunk);
2554
+ }
2555
+ currentChunk = para;
2556
+ }
2557
+ }
2558
+ if (currentChunk) {
2559
+ chunks.push(currentChunk);
2560
+ }
2561
+ } else {
2562
+ // Plain text mode: split directly by length
2563
+ let remaining = text;
2564
+ while(remaining.length > limit){
2565
+ chunks.push(remaining.slice(0, limit));
2566
+ remaining = remaining.slice(limit);
2567
+ }
2568
+ if (remaining) {
2569
+ chunks.push(remaining);
2570
+ }
2571
+ }
2572
+ return chunks;
2573
+ }
2574
+
2575
+ /**
2576
+ * Metadata key for chat channel
2577
+ */ const CHAT_CHANNEL = 'CHAT_CHANNEL';
2578
+ /**
2579
+ * Decorator for chat channel implementations
2580
+ *
2581
+ * Use this decorator to register a chat channel implementation.
2582
+ * The decorated class will be automatically discovered and registered
2583
+ * to ChatChannelRegistry on module initialization.
2584
+ *
2585
+ * @param type - The channel type identifier (e.g., 'lark', 'wecom', 'dingtalk')
2586
+ *
2587
+ * @example
2588
+ * ```typescript
2589
+ * @Injectable()
2590
+ * @ChatChannel('lark')
2591
+ * export class LarkChatChannel implements IChatChannel {
2592
+ * // Implementation
2593
+ * }
2594
+ * ```
2595
+ */ const ChatChannel = (type)=>SetMetadata(CHAT_CHANNEL, type);
2596
+
2597
+ let ChatChannelRegistry = class ChatChannelRegistry extends BaseStrategyRegistry {
2598
+ constructor(discoveryService, reflector){
2599
+ super(CHAT_CHANNEL, discoveryService, reflector);
2600
+ }
2601
+ };
2602
+ ChatChannelRegistry = __decorate([
2603
+ Injectable(),
2604
+ __metadata("design:type", Function),
2605
+ __metadata("design:paramtypes", [
2606
+ typeof DiscoveryService === "undefined" ? Object : DiscoveryService,
2607
+ typeof Reflector === "undefined" ? Object : Reflector
2608
+ ])
2609
+ ], ChatChannelRegistry);
2610
+
2611
+ class CancelConversationCommand {
2612
+ constructor(input){
2613
+ this.input = input;
2614
+ }
2615
+ }
2616
+ CancelConversationCommand.type = '[Chat Conversation] Cancel';
2617
+
2618
+ /**
2619
+ * Protocol definition for pluggable memory backends.
2620
+ *
2621
+ * This module defines the BackendProtocol that all backend implementations
2622
+ * must follow. Backends can store files in different locations (state, filesystem,
2623
+ * database, etc.) and provide a uniform interface for file operations.
2624
+ */ /**
2625
+ * Type guard to check if a backend supports execution.
2626
+ *
2627
+ * @param backend - Backend instance to check
2628
+ * @returns True if the backend implements SandboxBackendProtocol
2629
+ */ function isSandboxBackend(backend) {
2630
+ return typeof backend.execute === "function" && typeof backend.id === "string";
2631
+ }
2632
+
2633
+ /**
2634
+ * BaseSandbox: Abstract base class for sandbox backends with command execution.
2635
+ *
2636
+ * This class provides default implementations for all SandboxBackendProtocol
2637
+ * methods using shell commands executed via execute(). Concrete implementations
2638
+ * only need to implement the execute() method.
2639
+ *
2640
+ * Requires Node.js 20+ on the sandbox host.
2641
+ */ const MAX_LINE_LENGTH = 500;
2642
+ const MAX_GREP_LINE_LENGTH = 2000;
2643
+ const GREP_RESULT_LIMIT = 100;
2644
+ const GLOB_RESULT_LIMIT = 100;
2645
+ const WRITE_EXISTS_OUTPUT = "Error: File already exists";
2646
+ /**
2647
+ * UTF-8 safe Base64 encoding function.
2648
+ * Replaces btoa() which only supports Latin1 characters.
2649
+ */ function utf8ToBase64(str) {
2650
+ return Buffer.from(str, 'utf-8').toString('base64');
2651
+ }
2652
+ /**
2653
+ * Format glob results into human-readable output.
2654
+ */ function formatGlobOutput(files, pattern) {
2655
+ const limit = GLOB_RESULT_LIMIT;
2656
+ const truncated = files.length > limit;
2657
+ const finalFiles = truncated ? files.slice(0, limit) : files;
2658
+ if (finalFiles.length === 0) {
2659
+ return "No files found";
2660
+ }
2661
+ const lines = [];
2662
+ for (const file of finalFiles){
2663
+ lines.push(file.path);
2664
+ }
2665
+ if (truncated) {
2666
+ lines.push("");
2667
+ lines.push("(Results truncated. Consider using a more specific path or pattern.)");
2668
+ }
2669
+ return lines.join("\n");
2670
+ }
2671
+ /**
2672
+ * Format grep matches into human-readable output grouped by file.
2673
+ */ function formatGrepOutput(matches) {
2674
+ const limit = GREP_RESULT_LIMIT;
2675
+ const truncated = matches.length > limit;
2676
+ const finalMatches = truncated ? matches.slice(0, limit) : matches;
2677
+ if (finalMatches.length === 0) {
2678
+ return "No matches found";
2679
+ }
2680
+ const lines = [
2681
+ `Found ${finalMatches.length} matches`
2682
+ ];
2683
+ let currentFile = "";
2684
+ for (const match of finalMatches){
2685
+ if (currentFile !== match.path) {
2686
+ if (currentFile !== "") {
2687
+ lines.push("");
2688
+ }
2689
+ currentFile = match.path;
2690
+ lines.push(`${match.path}:`);
2691
+ }
2692
+ const text = match.text.length > MAX_GREP_LINE_LENGTH ? match.text.substring(0, MAX_GREP_LINE_LENGTH) + "..." : match.text;
2693
+ lines.push(` Line ${match.line}: ${text}`);
2694
+ }
2695
+ if (truncated) {
2696
+ lines.push("");
2697
+ lines.push("(Results truncated. Consider using a more specific path or pattern.)");
2698
+ }
2699
+ return lines.join("\n");
2700
+ }
2701
+ /**
2702
+ * Node.js command template for glob operations.
2703
+ * Uses web-standard atob() for base64 decoding.
2704
+ */ function buildGlobCommand(searchPath, pattern) {
2705
+ const pathB64 = utf8ToBase64(searchPath);
2706
+ const patternB64 = utf8ToBase64(pattern);
2707
+ return `node -e "
2708
+ const fs = require('fs');
2709
+ const path = require('path');
2710
+
2711
+ const searchPath = Buffer.from('${pathB64}', 'base64').toString('utf-8');
2712
+ const pattern = Buffer.from('${patternB64}', 'base64').toString('utf-8');
2713
+
2714
+ function globMatch(relativePath, pattern) {
2715
+ const regexPattern = pattern
2716
+ .replace(/\\*\\*/g, '<<<GLOBSTAR>>>')
2717
+ .replace(/\\*/g, '[^/]*')
2718
+ .replace(/\\?/g, '.')
2719
+ .replace(/<<<GLOBSTAR>>>/g, '.*');
2720
+ return new RegExp('^' + regexPattern + '$').test(relativePath);
2721
+ }
2722
+
2723
+ function walkDir(dir, baseDir, results) {
2724
+ try {
2725
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
2726
+ for (const entry of entries) {
2727
+ const fullPath = path.join(dir, entry.name);
2728
+ const relativePath = path.relative(baseDir, fullPath);
2729
+ if (entry.isDirectory()) {
2730
+ walkDir(fullPath, baseDir, results);
2731
+ } else if (globMatch(relativePath, pattern)) {
2732
+ const stat = fs.statSync(fullPath);
2733
+ console.log(JSON.stringify({
2734
+ path: relativePath,
2735
+ size: stat.size,
2736
+ mtime: stat.mtimeMs,
2737
+ isDir: false
2738
+ }));
2739
+ }
2740
+ }
2741
+ } catch (e) {
2742
+ // Silent failure for non-existent paths
2743
+ }
2744
+ }
2745
+
2746
+ try {
2747
+ process.chdir(searchPath);
2748
+ walkDir('.', '.', []);
2749
+ } catch (e) {
2750
+ // Silent failure for non-existent paths
2751
+ }
2752
+ "`;
2753
+ }
2754
+ /**
2755
+ * Node.js command template for listing directory contents.
2756
+ */ function buildLsCommand(dirPath) {
2757
+ const pathB64 = utf8ToBase64(dirPath);
2758
+ return `node -e "
2759
+ const fs = require('fs');
2760
+ const path = require('path');
2761
+
2762
+ const dirPath = Buffer.from('${pathB64}', 'base64').toString('utf-8');
2763
+
2764
+ try {
2765
+ const entries = fs.readdirSync(dirPath, { withFileTypes: true });
2766
+ for (const entry of entries) {
2767
+ const fullPath = path.join(dirPath, entry.name);
2768
+ const stat = fs.statSync(fullPath);
2769
+ console.log(JSON.stringify({
2770
+ path: entry.isDirectory() ? fullPath + '/' : fullPath,
2771
+ size: stat.size,
2772
+ mtime: stat.mtimeMs,
2773
+ isDir: entry.isDirectory()
2774
+ }));
2775
+ }
2776
+ } catch (e) {
2777
+ console.error('Error: ' + e.message);
2778
+ process.exit(1);
2779
+ }
2780
+ "`;
2781
+ }
2782
+ const INDENTATION_SPACES = 2;
2783
+ const MAX_ENTRY_LENGTH = 500;
2784
+ /**
2785
+ * Node.js command template for recursive directory listing with depth control.
2786
+ */ function buildListDirCommand(dirPath, offset, limit, depth) {
2787
+ const pathB64 = utf8ToBase64(dirPath);
2788
+ const safeOffset = Number.isFinite(offset) && offset > 0 ? Math.floor(offset) : 1;
2789
+ const safeLimit = Number.isFinite(limit) && limit > 0 ? Math.floor(limit) : 25;
2790
+ const safeDepth = Number.isFinite(depth) && depth > 0 ? Math.floor(depth) : 2;
2791
+ return `node -e "
2792
+ const fs = require('fs');
2793
+ const path = require('path');
2794
+
2795
+ const dirPath = Buffer.from('${pathB64}', 'base64').toString('utf-8');
2796
+ const offset = ${safeOffset};
2797
+ const limit = ${safeLimit};
2798
+ const maxDepth = ${safeDepth};
2799
+ const INDENTATION_SPACES = ${INDENTATION_SPACES};
2800
+ const MAX_ENTRY_LENGTH = ${MAX_ENTRY_LENGTH};
2801
+
2802
+ if (!path.isAbsolute(dirPath)) {
2803
+ console.error('Error: dir_path must be an absolute path');
2804
+ process.exit(1);
2805
+ }
2806
+
2807
+ if (!fs.existsSync(dirPath)) {
2808
+ console.error('Error: Directory not found');
2809
+ process.exit(1);
2810
+ }
2811
+
2812
+ if (!fs.statSync(dirPath).isDirectory()) {
2813
+ console.error('Error: Path is not a directory');
2814
+ process.exit(1);
2815
+ }
2816
+
2817
+ function collectEntries(currentPath, relativePrefix, remainingDepth, entries) {
2818
+ if (remainingDepth === 0) return;
2819
+
2820
+ try {
2821
+ const dirEntries = fs.readdirSync(currentPath, { withFileTypes: true });
2822
+ const sortedEntries = dirEntries
2823
+ .map(entry => {
2824
+ const fullPath = path.join(currentPath, entry.name);
2825
+ const relativePath = path.join(relativePrefix, entry.name);
2826
+ const displayName = entry.name.length > MAX_ENTRY_LENGTH
2827
+ ? entry.name.substring(0, MAX_ENTRY_LENGTH)
2828
+ : entry.name;
2829
+
2830
+ let kind = 'file';
2831
+ if (entry.isSymbolicLink()) kind = 'symlink';
2832
+ else if (entry.isDirectory()) kind = 'directory';
2833
+
2834
+ return {
2835
+ fullPath,
2836
+ relativePath,
2837
+ displayName,
2838
+ kind,
2839
+ depth: relativePrefix.split(path.sep).filter(Boolean).length
2840
+ };
2841
+ })
2842
+ .sort((a, b) => a.relativePath.localeCompare(b.relativePath));
2843
+
2844
+ for (const entry of sortedEntries) {
2845
+ entries.push(entry);
2846
+ if (entry.kind === 'directory' && remainingDepth > 1) {
2847
+ collectEntries(entry.fullPath, entry.relativePath, remainingDepth - 1, entries);
2848
+ }
2849
+ }
2850
+ } catch (e) {
2851
+ // Skip unreadable directories
2852
+ }
2853
+ }
2854
+
2855
+ const allEntries = [];
2856
+ collectEntries(dirPath, '', maxDepth, allEntries);
2857
+
2858
+ if (allEntries.length === 0) {
2859
+ console.log('Absolute path: ' + dirPath);
2860
+ console.log('(Empty directory)');
2861
+ process.exit(0);
2862
+ }
2863
+
2864
+ const startIndex = offset - 1;
2865
+ if (startIndex >= allEntries.length) {
2866
+ console.error('Error: offset exceeds directory entry count');
2867
+ process.exit(1);
2868
+ }
2869
+
2870
+ const endIndex = Math.min(startIndex + limit, allEntries.length);
2871
+ const selectedEntries = allEntries.slice(startIndex, endIndex);
2872
+
2873
+ console.log('Absolute path: ' + dirPath);
2874
+
2875
+ for (const entry of selectedEntries) {
2876
+ const indent = ' '.repeat(entry.depth * INDENTATION_SPACES);
2877
+ let name = entry.displayName;
2878
+ if (entry.kind === 'directory') name += '/';
2879
+ else if (entry.kind === 'symlink') name += '@';
2880
+ console.log(indent + name);
2881
+ }
2882
+
2883
+ if (endIndex < allEntries.length) {
2884
+ console.log('More than ' + limit + ' entries found');
2885
+ }
2886
+ "`;
2887
+ }
2888
+ const TAB_WIDTH = 4;
2889
+ const COMMENT_PREFIXES = [
2890
+ '#',
2891
+ '//',
2892
+ '--'
2893
+ ];
2894
+ /**
2895
+ * Node.js command template for slice mode reading.
2896
+ */ function buildSliceReadCommand(filePath, offset, limit) {
2897
+ const pathB64 = utf8ToBase64(filePath);
2898
+ const safeOffset = Number.isFinite(offset) && offset > 0 ? Math.floor(offset) - 1 : 0;
2899
+ const safeLimit = Number.isFinite(limit) && limit > 0 && limit < Number.MAX_SAFE_INTEGER ? Math.floor(limit) : 2000;
2900
+ return `node -e "
2901
+ const fs = require('fs');
2902
+ const MAX_LINE_LENGTH = ${MAX_LINE_LENGTH};
2903
+
2904
+ const filePath = Buffer.from('${pathB64}', 'base64').toString('utf-8');
2905
+ const offset = ${safeOffset};
2906
+ const limit = ${safeLimit};
2907
+
2908
+ if (!fs.existsSync(filePath)) {
2909
+ console.log('Error: File not found');
2910
+ process.exit(1);
2911
+ }
2912
+
2913
+ const stat = fs.statSync(filePath);
2914
+ if (stat.size === 0) {
2915
+ console.log('System reminder: File exists but has empty contents');
2916
+ process.exit(0);
2917
+ }
2918
+
2919
+ const content = fs.readFileSync(filePath, 'utf-8');
2920
+ const lines = content.split('\\n');
2921
+
2922
+ if (offset >= lines.length) {
2923
+ console.log('Error: offset exceeds file length');
2924
+ process.exit(1);
2925
+ }
2926
+
2927
+ const selected = lines.slice(offset, offset + limit);
2928
+
2929
+ for (let i = 0; i < selected.length; i++) {
2930
+ const lineNum = offset + i + 1;
2931
+ let line = selected[i];
2932
+ if (line.length > MAX_LINE_LENGTH) {
2933
+ line = line.substring(0, MAX_LINE_LENGTH);
2934
+ }
2935
+ console.log('L' + lineNum + ': ' + line);
2936
+ }
2937
+ "`;
2938
+ }
2939
+ /**
2940
+ * Node.js command template for indentation mode reading.
2941
+ */ function buildIndentationReadCommand(filePath, offset, limit, options) {
2942
+ const pathB64 = utf8ToBase64(filePath);
2943
+ const safeOffset = Number.isFinite(offset) && offset > 0 ? Math.floor(offset) : 1;
2944
+ const safeLimit = Number.isFinite(limit) && limit > 0 && limit < Number.MAX_SAFE_INTEGER ? Math.floor(limit) : 2000;
2945
+ var _options_anchor_line;
2946
+ const anchorLine = (_options_anchor_line = options.anchor_line) != null ? _options_anchor_line : safeOffset;
2947
+ var _options_max_levels;
2948
+ const maxLevels = (_options_max_levels = options.max_levels) != null ? _options_max_levels : 0;
2949
+ var _options_include_siblings;
2950
+ const includeSiblings = (_options_include_siblings = options.include_siblings) != null ? _options_include_siblings : false;
2951
+ var _options_include_header;
2952
+ const includeHeader = (_options_include_header = options.include_header) != null ? _options_include_header : true;
2953
+ var _options_max_lines;
2954
+ const maxLines = (_options_max_lines = options.max_lines) != null ? _options_max_lines : safeLimit;
2955
+ return `node -e "
2956
+ const fs = require('fs');
2957
+ const MAX_LINE_LENGTH = ${MAX_LINE_LENGTH};
2958
+ const TAB_WIDTH = ${TAB_WIDTH};
2959
+ const COMMENT_PREFIXES = ${JSON.stringify(COMMENT_PREFIXES)};
2960
+
2961
+ const filePath = Buffer.from('${pathB64}', 'base64').toString('utf-8');
2962
+ const anchorLine = ${anchorLine};
2963
+ const limit = ${safeLimit};
2964
+ const maxLevels = ${maxLevels};
2965
+ const includeSiblings = ${includeSiblings};
2966
+ const includeHeader = ${includeHeader};
2967
+ const maxLines = ${maxLines};
2968
+
2969
+ if (!fs.existsSync(filePath)) {
2970
+ console.log('Error: File not found');
2971
+ process.exit(1);
2972
+ }
2973
+
2974
+ const content = fs.readFileSync(filePath, 'utf-8');
2975
+ const rawLines = content.split('\\n');
2976
+
2977
+ if (rawLines.length === 0 || anchorLine > rawLines.length) {
2978
+ console.log('Error: anchor_line exceeds file length');
2979
+ process.exit(1);
2980
+ }
2981
+
2982
+ function measureIndent(line) {
2983
+ let indent = 0;
2984
+ for (const c of line) {
2985
+ if (c === ' ') indent++;
2986
+ else if (c === '\\t') indent += TAB_WIDTH;
2987
+ else break;
2988
+ }
2989
+ return indent;
2990
+ }
2991
+
2992
+ function isBlank(line) { return line.trim() === ''; }
2993
+ function isComment(line) { return COMMENT_PREFIXES.some(p => line.trim().startsWith(p)); }
2994
+ function formatLine(line) { return line.length > MAX_LINE_LENGTH ? line.substring(0, MAX_LINE_LENGTH) : line; }
2995
+
2996
+ const records = rawLines.map((raw, i) => ({
2997
+ number: i + 1,
2998
+ raw,
2999
+ display: formatLine(raw),
3000
+ indent: measureIndent(raw)
3001
+ }));
3002
+
3003
+ const effectiveIndents = [];
3004
+ let prevIndent = 0;
3005
+ for (const r of records) {
3006
+ if (isBlank(r.raw)) {
3007
+ effectiveIndents.push(prevIndent);
3008
+ } else {
3009
+ prevIndent = r.indent;
3010
+ effectiveIndents.push(prevIndent);
3011
+ }
3012
+ }
3013
+
3014
+ const anchorIndex = anchorLine - 1;
3015
+ const anchorIndent = effectiveIndents[anchorIndex];
3016
+ const minIndent = maxLevels === 0 ? 0 : Math.max(0, anchorIndent - maxLevels * TAB_WIDTH);
3017
+ const finalLimit = Math.min(limit, maxLines, records.length);
3018
+
3019
+ if (finalLimit === 1) {
3020
+ console.log('L' + records[anchorIndex].number + ': ' + records[anchorIndex].display);
3021
+ process.exit(0);
3022
+ }
3023
+
3024
+ const out = [records[anchorIndex]];
3025
+ let i = anchorIndex - 1;
3026
+ let j = anchorIndex + 1;
3027
+ let iCounterMinIndent = 0;
3028
+ let jCounterMinIndent = 0;
3029
+
3030
+ while (out.length < finalLimit) {
3031
+ let progressed = 0;
3032
+
3033
+ if (i >= 0) {
3034
+ if (effectiveIndents[i] >= minIndent) {
3035
+ out.unshift(records[i]);
3036
+ progressed++;
3037
+ const curI = i;
3038
+ i--;
3039
+
3040
+ if (effectiveIndents[curI] === minIndent && !includeSiblings) {
3041
+ const allowHeaderComment = includeHeader && isComment(records[curI].raw);
3042
+ const canTakeLine = allowHeaderComment || iCounterMinIndent === 0;
3043
+ if (canTakeLine) {
3044
+ iCounterMinIndent++;
3045
+ } else {
3046
+ out.shift();
3047
+ progressed--;
3048
+ i = -1;
3049
+ }
3050
+ }
3051
+
3052
+ if (out.length >= finalLimit) break;
3053
+ } else {
3054
+ i = -1;
3055
+ }
3056
+ }
3057
+
3058
+ if (j < records.length) {
3059
+ if (effectiveIndents[j] >= minIndent) {
3060
+ out.push(records[j]);
3061
+ progressed++;
3062
+ const curJ = j;
3063
+ j++;
3064
+
3065
+ if (effectiveIndents[curJ] === minIndent && !includeSiblings) {
3066
+ if (jCounterMinIndent > 0) {
3067
+ out.pop();
3068
+ progressed--;
3069
+ j = records.length;
3070
+ }
3071
+ jCounterMinIndent++;
3072
+ }
3073
+ } else {
3074
+ j = records.length;
3075
+ }
3076
+ }
3077
+
3078
+ if (progressed === 0) break;
3079
+ }
3080
+
3081
+ while (out.length > 0 && isBlank(out[0].raw)) out.shift();
3082
+ while (out.length > 0 && isBlank(out[out.length - 1].raw)) out.pop();
3083
+
3084
+ for (const r of out) {
3085
+ console.log('L' + r.number + ': ' + r.display);
3086
+ }
3087
+ "`;
3088
+ }
3089
+ /**
3090
+ * Node.js command template for writing files.
3091
+ */ function buildWriteCommand(filePath, content) {
3092
+ const pathB64 = utf8ToBase64(filePath);
3093
+ const contentB64 = utf8ToBase64(content);
3094
+ return `node -e "
3095
+ const fs = require('fs');
3096
+ const path = require('path');
3097
+
3098
+ const filePath = Buffer.from('${pathB64}', 'base64').toString('utf-8');
3099
+ const content = Buffer.from('${contentB64}', 'base64').toString('utf-8');
3100
+
3101
+ if (fs.existsSync(filePath)) {
3102
+ console.error('${WRITE_EXISTS_OUTPUT}');
3103
+ process.exit(1);
3104
+ }
3105
+
3106
+ const parentDir = path.dirname(filePath) || '.';
3107
+ fs.mkdirSync(parentDir, { recursive: true });
3108
+
3109
+ fs.writeFileSync(filePath, content, 'utf-8');
3110
+ console.log('OK');
3111
+ "`;
3112
+ }
3113
+ function buildExistsCommand(filePath) {
3114
+ const pathB64 = utf8ToBase64(filePath);
3115
+ return `node -e "
3116
+ const fs = require('fs');
3117
+ const filePath = Buffer.from('${pathB64}', 'base64').toString('utf-8');
3118
+ process.exit(fs.existsSync(filePath) ? 0 : 1);
3119
+ "`;
3120
+ }
3121
+ /**
3122
+ * Node.js command template for appending to files.
3123
+ */ function buildAppendCommand(filePath, content) {
3124
+ const pathB64 = utf8ToBase64(filePath);
3125
+ const contentB64 = utf8ToBase64(content);
3126
+ return `node -e "
3127
+ const fs = require('fs');
3128
+ const path = require('path');
3129
+
3130
+ const filePath = Buffer.from('${pathB64}', 'base64').toString('utf-8');
3131
+ const content = Buffer.from('${contentB64}', 'base64').toString('utf-8');
3132
+
3133
+ const parentDir = path.dirname(filePath) || '.';
3134
+ fs.mkdirSync(parentDir, { recursive: true });
3135
+
3136
+ fs.appendFileSync(filePath, content, 'utf-8');
3137
+ console.log('OK');
3138
+ "`;
3139
+ }
3140
+ /**
3141
+ * Node.js command template for editing files.
3142
+ */ function buildEditCommand(filePath, oldStr, newStr, replaceAll) {
3143
+ const pathB64 = utf8ToBase64(filePath);
3144
+ const oldB64 = utf8ToBase64(oldStr);
3145
+ const newB64 = utf8ToBase64(newStr);
3146
+ return `node -e "
3147
+ const fs = require('fs');
3148
+
3149
+ const filePath = Buffer.from('${pathB64}', 'base64').toString('utf-8');
3150
+ const oldStr = Buffer.from('${oldB64}', 'base64').toString('utf-8');
3151
+ const newStr = Buffer.from('${newB64}', 'base64').toString('utf-8');
3152
+ const replaceAll = ${Boolean(replaceAll)};
3153
+
3154
+ let text;
3155
+ try {
3156
+ text = fs.readFileSync(filePath, 'utf-8');
3157
+ } catch (e) {
3158
+ process.exit(3);
3159
+ }
3160
+
3161
+ const count = text.split(oldStr).length - 1;
3162
+
3163
+ if (count === 0) {
3164
+ process.exit(1);
3165
+ }
3166
+ if (count > 1 && !replaceAll) {
3167
+ process.exit(2);
3168
+ }
3169
+
3170
+ const result = text.split(oldStr).join(newStr);
3171
+ fs.writeFileSync(filePath, result, 'utf-8');
3172
+ console.log(count);
3173
+ "`;
3174
+ }
3175
+ /**
3176
+ * Node.js command template for grep operations.
3177
+ */ function buildGrepCommand(pattern, searchPath, globPattern) {
3178
+ const patternB64 = utf8ToBase64(pattern);
3179
+ const pathB64 = utf8ToBase64(searchPath);
3180
+ const globB64 = globPattern ? utf8ToBase64(globPattern) : "";
3181
+ return `node -e "
3182
+ const fs = require('fs');
3183
+ const path = require('path');
3184
+
3185
+ const pattern = Buffer.from('${patternB64}', 'base64').toString('utf-8');
3186
+ const searchPath = Buffer.from('${pathB64}', 'base64').toString('utf-8');
3187
+ const globPattern = ${globPattern ? `Buffer.from('${globB64}', 'base64').toString('utf-8')` : "null"};
3188
+
3189
+ let regex;
3190
+ try {
3191
+ regex = new RegExp(pattern);
3192
+ } catch (e) {
3193
+ console.error('Invalid regex: ' + e.message);
3194
+ process.exit(1);
3195
+ }
3196
+
3197
+ function globMatch(filePath, pattern) {
3198
+ if (!pattern) return true;
3199
+ const regexPattern = pattern
3200
+ .replace(/\\*\\*/g, '<<<GLOBSTAR>>>')
3201
+ .replace(/\\*/g, '[^/]*')
3202
+ .replace(/\\?/g, '.')
3203
+ .replace(/<<<GLOBSTAR>>>/g, '.*');
3204
+ return new RegExp('^' + regexPattern + '$').test(filePath);
3205
+ }
3206
+
3207
+ function walkDir(dir, results) {
3208
+ try {
3209
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
3210
+ for (const entry of entries) {
3211
+ const fullPath = path.join(dir, entry.name);
3212
+ if (entry.isDirectory()) {
3213
+ walkDir(fullPath, results);
3214
+ } else {
3215
+ const relativePath = path.relative(searchPath, fullPath);
3216
+ if (globMatch(relativePath, globPattern)) {
3217
+ try {
3218
+ const content = fs.readFileSync(fullPath, 'utf-8');
3219
+ const lines = content.split('\\n');
3220
+ for (let i = 0; i < lines.length; i++) {
3221
+ if (regex.test(lines[i])) {
3222
+ console.log(JSON.stringify({
3223
+ path: fullPath,
3224
+ line: i + 1,
3225
+ text: lines[i]
3226
+ }));
3227
+ }
3228
+ }
3229
+ } catch (e) {
3230
+ // Skip unreadable files
3231
+ }
3232
+ }
3233
+ }
3234
+ }
3235
+ } catch (e) {
3236
+ // Skip unreadable directories
3237
+ }
3238
+ }
3239
+
3240
+ try {
3241
+ walkDir(searchPath, []);
3242
+ } catch (e) {
3243
+ // Silent failure
3244
+ }
3245
+ "`;
3246
+ }
3247
+ /**
3248
+ * Base sandbox implementation with execute() as the only abstract method.
3249
+ *
3250
+ * This class provides default implementations for all SandboxBackendProtocol
3251
+ * methods using shell commands executed via execute(). Concrete implementations
3252
+ * only need to implement the execute() method.
3253
+ *
3254
+ * Requires Node.js 20+ on the sandbox host.
3255
+ */ class BaseSandbox {
3256
+ async streamExecute(command, onLine) {
3257
+ const result = await this.execute(command);
3258
+ if (result.output) {
3259
+ onLine(result.output);
3260
+ }
3261
+ return result;
3262
+ }
3263
+ /**
3264
+ * List files and directories in the specified directory (non-recursive).
3265
+ *
3266
+ * @param path - Absolute path to directory
3267
+ * @returns List of FileInfo objects for files and directories directly in the directory.
3268
+ */ async lsInfo(path) {
3269
+ const command = buildLsCommand(path);
3270
+ const result = await this.execute(command);
3271
+ if (result.exitCode !== 0) {
3272
+ return [];
3273
+ }
3274
+ const infos = [];
3275
+ const lines = result.output.trim().split("\n").filter(Boolean);
3276
+ for (const line of lines){
3277
+ try {
3278
+ const parsed = JSON.parse(line);
3279
+ infos.push({
3280
+ path: parsed.path,
3281
+ is_dir: parsed.isDir,
3282
+ size: parsed.size,
3283
+ modified_at: parsed.mtime ? new Date(parsed.mtime).toISOString() : undefined
3284
+ });
3285
+ } catch (e) {
3286
+ // Skip invalid JSON lines
3287
+ }
3288
+ }
3289
+ return infos;
3290
+ }
3291
+ /**
3292
+ * List directory contents recursively with depth control and pagination.
3293
+ *
3294
+ * @param dirPath - Absolute path to directory
3295
+ * @param offset - 1-indexed entry number to start from (default: 1)
3296
+ * @param limit - Maximum number of entries to return (default: 25)
3297
+ * @param depth - Maximum depth to traverse (default: 2)
3298
+ * @returns Human-readable directory tree with indentation
3299
+ */ async listDir(dirPath, offset = 1, limit = 25, depth = 2) {
3300
+ if (offset < 1) {
3301
+ return "Error: offset must be a 1-indexed entry number";
3302
+ }
3303
+ if (limit < 1) {
3304
+ return "Error: limit must be greater than zero";
3305
+ }
3306
+ if (depth < 1) {
3307
+ return "Error: depth must be greater than zero";
3308
+ }
3309
+ const command = buildListDirCommand(dirPath, offset, limit, depth);
3310
+ const result = await this.execute(command);
3311
+ if (result.exitCode !== 0) {
3312
+ return result.output || `Error: Failed to list directory '${dirPath}'`;
3313
+ }
3314
+ return result.output;
3315
+ }
3316
+ /**
3317
+ * Read file content with line numbers.
3318
+ *
3319
+ * @param filePath - Absolute file path
3320
+ * @param offset - Line offset to start reading from (1-indexed)
3321
+ * @param limit - Maximum number of lines to read
3322
+ * @param mode - Read mode: 'slice' (default) or 'indentation'
3323
+ * @param indentation - Configuration for indentation mode
3324
+ * @returns Formatted file content with line numbers, or error message
3325
+ */ async read(filePath, offset = 1, limit = 2000, mode = 'slice', indentation) {
3326
+ const command = mode === 'indentation' ? buildIndentationReadCommand(filePath, offset, limit, indentation != null ? indentation : {}) : buildSliceReadCommand(filePath, offset, limit);
3327
+ const result = await this.execute(command);
3328
+ if (result.exitCode !== 0) {
3329
+ return result.output || `Error: File '${filePath}' not found`;
3330
+ }
3331
+ return result.output;
3332
+ }
3333
+ /**
3334
+ * Structured search results or error string for invalid input.
3335
+ */ async grepRaw(pattern, path = "/", include = null) {
3336
+ const command = buildGrepCommand(pattern, path, include);
3337
+ const result = await this.execute(command);
3338
+ if (result.exitCode === 1) {
3339
+ // Check if it's a regex error
3340
+ if (result.output.includes("Invalid regex:")) {
3341
+ return result.output.trim();
3342
+ }
3343
+ }
3344
+ const matches = [];
3345
+ const lines = result.output.trim().split("\n").filter(Boolean);
3346
+ for (const line of lines){
3347
+ try {
3348
+ const parsed = JSON.parse(line);
3349
+ matches.push({
3350
+ path: parsed.path,
3351
+ line: parsed.line,
3352
+ text: parsed.text
3353
+ });
3354
+ } catch (e) {
3355
+ // Skip invalid JSON lines
3356
+ }
3357
+ }
3358
+ return matches;
3359
+ }
3360
+ /**
3361
+ * Search file contents for a regex pattern, returning human-readable output.
3362
+ */ async grep(pattern, path = "/", include = null) {
3363
+ const result = await this.grepRaw(pattern, path, include);
3364
+ if (typeof result === "string") {
3365
+ return result;
3366
+ }
3367
+ if (result.length === 0) {
3368
+ return "No matches found";
3369
+ }
3370
+ return formatGrepOutput(result);
3371
+ }
3372
+ /**
3373
+ * Structured glob matching returning FileInfo objects.
3374
+ */ async globInfo(pattern, path = "/") {
3375
+ const command = buildGlobCommand(path, pattern);
3376
+ const result = await this.execute(command);
3377
+ const infos = [];
3378
+ const lines = result.output.trim().split("\n").filter(Boolean);
3379
+ for (const line of lines){
3380
+ try {
3381
+ const parsed = JSON.parse(line);
3382
+ infos.push({
3383
+ path: parsed.path,
3384
+ is_dir: parsed.isDir,
3385
+ size: parsed.size,
3386
+ modified_at: parsed.mtime ? new Date(parsed.mtime).toISOString() : undefined
3387
+ });
3388
+ } catch (e) {
3389
+ // Skip invalid JSON lines
3390
+ }
3391
+ }
3392
+ return infos;
3393
+ }
3394
+ /**
3395
+ * Find files matching a glob pattern, returning human-readable output.
3396
+ */ async glob(pattern, path = "/") {
3397
+ const files = await this.globInfo(pattern, path);
3398
+ if (files.length === 0) {
3399
+ return "No files found";
3400
+ }
3401
+ return formatGlobOutput(files);
3402
+ }
3403
+ /**
3404
+ * Create a new file with content.
3405
+ */ async write(filePath, content) {
3406
+ const command = buildWriteCommand(filePath, content);
3407
+ const result = await this.execute(command);
3408
+ if (result.exitCode !== 0) {
3409
+ const output = (result.output || "").trim();
3410
+ if (output.includes(WRITE_EXISTS_OUTPUT)) {
3411
+ return {
3412
+ error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.`
3413
+ };
3414
+ }
3415
+ const fallback = await this.writeViaUpload(filePath, content);
3416
+ if (!fallback.error) {
3417
+ return fallback;
3418
+ }
3419
+ return {
3420
+ error: output ? `Failed to write file '${filePath}': ${output}` : `Failed to write file '${filePath}'.`
3421
+ };
3422
+ }
3423
+ return {
3424
+ path: filePath,
3425
+ filesUpdate: null
3426
+ };
3427
+ }
3428
+ async writeViaUpload(filePath, content) {
3429
+ const existsCheck = await this.execute(buildExistsCommand(filePath));
3430
+ if (existsCheck.exitCode === 0) {
3431
+ return {
3432
+ error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.`
3433
+ };
3434
+ }
3435
+ const uploads = await this.uploadFiles([
3436
+ [
3437
+ filePath,
3438
+ Buffer.from(content, "utf-8")
3439
+ ]
3440
+ ]);
3441
+ const first = uploads[0];
3442
+ if (!first) {
3443
+ return {
3444
+ error: `Failed to write file '${filePath}': upload returned no result.`
3445
+ };
3446
+ }
3447
+ if (first.error) {
3448
+ return {
3449
+ error: `Failed to write file '${filePath}': ${first.error}`
3450
+ };
3451
+ }
3452
+ return {
3453
+ path: filePath,
3454
+ filesUpdate: null
3455
+ };
3456
+ }
3457
+ /**
3458
+ * Append content to a file. Creates the file if it doesn't exist.
3459
+ */ async append(filePath, content) {
3460
+ const command = buildAppendCommand(filePath, content);
3461
+ const result = await this.execute(command);
3462
+ if (result.exitCode !== 0) {
3463
+ const output = (result.output || "").trim();
3464
+ return {
3465
+ error: output ? `Failed to append to file '${filePath}': ${output}` : `Failed to append to file '${filePath}'.`
3466
+ };
3467
+ }
3468
+ return {
3469
+ path: filePath,
3470
+ filesUpdate: null
3471
+ };
3472
+ }
3473
+ /**
3474
+ * Edit a file by replacing string occurrences.
3475
+ */ async edit(filePath, oldString, newString, replaceAll = false) {
3476
+ const command = buildEditCommand(filePath, oldString, newString, replaceAll);
3477
+ const result = await this.execute(command);
3478
+ switch(result.exitCode){
3479
+ case 0:
3480
+ {
3481
+ const occurrences = parseInt(result.output.trim(), 10) || 1;
3482
+ return {
3483
+ path: filePath,
3484
+ filesUpdate: null,
3485
+ occurrences
3486
+ };
3487
+ }
3488
+ case 1:
3489
+ return {
3490
+ error: `String not found in file '${filePath}'`
3491
+ };
3492
+ case 2:
3493
+ return {
3494
+ error: `Multiple occurrences found in '${filePath}'. Use replaceAll=true to replace all.`
3495
+ };
3496
+ case 3:
3497
+ return {
3498
+ error: `Error: File '${filePath}' not found`
3499
+ };
3500
+ default:
3501
+ return {
3502
+ error: `Unknown error editing file '${filePath}'`
3503
+ };
3504
+ }
3505
+ }
3506
+ /**
3507
+ * Perform multiple sequential edits on a single file.
3508
+ * All edits are applied sequentially, with each edit operating on the result of the previous edit.
3509
+ * All edits must succeed for the operation to succeed (atomic).
3510
+ */ async multiEdit(filePath, edits) {
3511
+ if (!edits || edits.length === 0) {
3512
+ return {
3513
+ error: "No edits provided"
3514
+ };
3515
+ }
3516
+ const results = [];
3517
+ for (const edit of edits){
3518
+ var _edit_replaceAll;
3519
+ const result = await this.edit(filePath, edit.oldString, edit.newString, (_edit_replaceAll = edit.replaceAll) != null ? _edit_replaceAll : false);
3520
+ results.push(result);
3521
+ // If any edit fails, return immediately with error
3522
+ if (result.error) {
3523
+ return {
3524
+ error: `Multi-edit failed at edit ${results.length}: ${result.error}`,
3525
+ path: filePath,
3526
+ filesUpdate: null,
3527
+ results
3528
+ };
3529
+ }
3530
+ }
3531
+ // All edits succeeded
3532
+ return {
3533
+ path: filePath,
3534
+ filesUpdate: null,
3535
+ results
3536
+ };
3537
+ }
3538
+ }
3539
+
3540
+ const SANDBOX_PROVIDER = 'SANDBOX_PROVIDER';
3541
+ const SandboxProviderStrategy = (provider)=>applyDecorators(SetMetadata(SANDBOX_PROVIDER, provider), SetMetadata(STRATEGY_META_KEY, SANDBOX_PROVIDER));
3542
+
3543
+ let SandboxProviderRegistry = class SandboxProviderRegistry extends BaseStrategyRegistry {
3544
+ constructor(discoveryService, reflector){
3545
+ super(SANDBOX_PROVIDER, discoveryService, reflector);
3546
+ }
3547
+ };
3548
+ SandboxProviderRegistry = __decorate([
3549
+ Injectable(),
3550
+ __metadata("design:type", Function),
3551
+ __metadata("design:paramtypes", [
3552
+ typeof DiscoveryService === "undefined" ? Object : DiscoveryService,
3553
+ typeof Reflector === "undefined" ? Object : Reflector
3554
+ ])
3555
+ ], SandboxProviderRegistry);
3556
+
3557
+ 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 };