sub-agents-mcp 0.1.2

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 (75) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +265 -0
  3. package/dist/agents/AgentManager.d.ts +58 -0
  4. package/dist/agents/AgentManager.d.ts.map +1 -0
  5. package/dist/agents/AgentManager.js +182 -0
  6. package/dist/agents/AgentManager.js.map +1 -0
  7. package/dist/config/ServerConfig.d.ts +34 -0
  8. package/dist/config/ServerConfig.d.ts.map +1 -0
  9. package/dist/config/ServerConfig.js +54 -0
  10. package/dist/config/ServerConfig.js.map +1 -0
  11. package/dist/execution/AgentExecutor.d.ts +114 -0
  12. package/dist/execution/AgentExecutor.d.ts.map +1 -0
  13. package/dist/execution/AgentExecutor.js +234 -0
  14. package/dist/execution/AgentExecutor.js.map +1 -0
  15. package/dist/execution/ExecutionLimits.d.ts +141 -0
  16. package/dist/execution/ExecutionLimits.d.ts.map +1 -0
  17. package/dist/execution/ExecutionLimits.js +231 -0
  18. package/dist/execution/ExecutionLimits.js.map +1 -0
  19. package/dist/execution/McpRequestTimeout.d.ts +166 -0
  20. package/dist/execution/McpRequestTimeout.d.ts.map +1 -0
  21. package/dist/execution/McpRequestTimeout.js +278 -0
  22. package/dist/execution/McpRequestTimeout.js.map +1 -0
  23. package/dist/execution/PromptController.d.ts +92 -0
  24. package/dist/execution/PromptController.d.ts.map +1 -0
  25. package/dist/execution/PromptController.js +130 -0
  26. package/dist/execution/PromptController.js.map +1 -0
  27. package/dist/execution/StreamProcessor.d.ts +23 -0
  28. package/dist/execution/StreamProcessor.d.ts.map +1 -0
  29. package/dist/execution/StreamProcessor.js +51 -0
  30. package/dist/execution/StreamProcessor.js.map +1 -0
  31. package/dist/execution/TimeoutManager.d.ts +159 -0
  32. package/dist/execution/TimeoutManager.d.ts.map +1 -0
  33. package/dist/execution/TimeoutManager.js +283 -0
  34. package/dist/execution/TimeoutManager.js.map +1 -0
  35. package/dist/index.d.ts +10 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +51 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/resources/AgentResources.d.ts +104 -0
  40. package/dist/resources/AgentResources.d.ts.map +1 -0
  41. package/dist/resources/AgentResources.js +315 -0
  42. package/dist/resources/AgentResources.js.map +1 -0
  43. package/dist/server/McpServer.d.ts +138 -0
  44. package/dist/server/McpServer.d.ts.map +1 -0
  45. package/dist/server/McpServer.js +373 -0
  46. package/dist/server/McpServer.js.map +1 -0
  47. package/dist/tools/RunAgentTool.d.ts +140 -0
  48. package/dist/tools/RunAgentTool.d.ts.map +1 -0
  49. package/dist/tools/RunAgentTool.js +371 -0
  50. package/dist/tools/RunAgentTool.js.map +1 -0
  51. package/dist/types/AgentDefinition.d.ts +33 -0
  52. package/dist/types/AgentDefinition.d.ts.map +1 -0
  53. package/dist/types/AgentDefinition.js +3 -0
  54. package/dist/types/AgentDefinition.js.map +1 -0
  55. package/dist/types/ExecutionParams.d.ts +48 -0
  56. package/dist/types/ExecutionParams.d.ts.map +1 -0
  57. package/dist/types/ExecutionParams.js +3 -0
  58. package/dist/types/ExecutionParams.js.map +1 -0
  59. package/dist/types/ServerConfig.d.ts +39 -0
  60. package/dist/types/ServerConfig.d.ts.map +1 -0
  61. package/dist/types/ServerConfig.js +3 -0
  62. package/dist/types/ServerConfig.js.map +1 -0
  63. package/dist/types/index.d.ts +19 -0
  64. package/dist/types/index.d.ts.map +1 -0
  65. package/dist/types/index.js +3 -0
  66. package/dist/types/index.js.map +1 -0
  67. package/dist/utils/ErrorHandler.d.ts +86 -0
  68. package/dist/utils/ErrorHandler.d.ts.map +1 -0
  69. package/dist/utils/ErrorHandler.js +99 -0
  70. package/dist/utils/ErrorHandler.js.map +1 -0
  71. package/dist/utils/Logger.d.ts +99 -0
  72. package/dist/utils/Logger.d.ts.map +1 -0
  73. package/dist/utils/Logger.js +151 -0
  74. package/dist/utils/Logger.js.map +1 -0
  75. package/package.json +92 -0
@@ -0,0 +1,114 @@
1
+ import type { ExecutionParams } from '../types/ExecutionParams';
2
+ import { Logger } from '../utils/Logger';
3
+ /**
4
+ * Detailed execution result that includes performance metrics and method information.
5
+ * Extends the basic ExecutionResult with additional monitoring capabilities.
6
+ */
7
+ export interface AgentExecutionResult {
8
+ /**
9
+ * Standard output from the agent execution.
10
+ * Contains the agent's response or execution result.
11
+ */
12
+ stdout: string;
13
+ /**
14
+ * Standard error output from the agent execution.
15
+ * Contains error messages and diagnostic information.
16
+ */
17
+ stderr: string;
18
+ /**
19
+ * Exit code returned by the agent process.
20
+ * 0 indicates success, non-zero indicates failure.
21
+ */
22
+ exitCode: number;
23
+ /**
24
+ * Total execution time in milliseconds.
25
+ * Used for performance monitoring and optimization.
26
+ */
27
+ executionTime: number;
28
+ /**
29
+ * Whether a result JSON was successfully obtained from the agent.
30
+ * True when StreamProcessor detects a valid JSON response.
31
+ */
32
+ hasResult?: boolean;
33
+ /**
34
+ * The parsed JSON result from the agent if available.
35
+ * Contains the structured response data when hasResult is true.
36
+ */
37
+ resultJson?: unknown;
38
+ }
39
+ /**
40
+ * Simplified execution configuration.
41
+ */
42
+ export interface ExecutionConfig {
43
+ /**
44
+ * Maximum execution timeout in milliseconds.
45
+ * Default: 5 minutes (300000ms)
46
+ */
47
+ executionTimeout: number;
48
+ /**
49
+ * Type of agent to use for execution.
50
+ * 'cursor' or 'claude'
51
+ */
52
+ agentType: 'cursor' | 'claude';
53
+ }
54
+ export declare const DEFAULT_EXECUTION_TIMEOUT = 300000;
55
+ /**
56
+ * Creates a complete ExecutionConfig with the provided agent type.
57
+ * @param agentType - The type of agent to use
58
+ * @param overrides - Optional overrides for thresholds
59
+ */
60
+ export declare function createExecutionConfig(agentType: 'cursor' | 'claude', overrides?: Partial<Omit<ExecutionConfig, 'agentType'>>): ExecutionConfig;
61
+ /**
62
+ * AgentExecutor class implements execution strategy for running Claude Code agents.
63
+ * Uses child_process.spawn for proper TTY handling and stdin/stdout streaming.
64
+ * Includes performance monitoring and timeout management.
65
+ */
66
+ export declare class AgentExecutor {
67
+ private readonly config;
68
+ private readonly logger;
69
+ /**
70
+ * Creates a new AgentExecutor instance.
71
+ *
72
+ * @param config - Execution configuration including CLI command and thresholds
73
+ * @param logger - Optional Logger instance for structured logging
74
+ */
75
+ constructor(config: ExecutionConfig, logger?: Logger);
76
+ /**
77
+ * Executes an agent with the specified parameters using spawn strategy.
78
+ *
79
+ * This method implements the core execution logic using spawn for proper TTY
80
+ * handling and streaming. It includes comprehensive performance monitoring.
81
+ *
82
+ * @param params - Execution parameters including agent name, prompt, and options
83
+ * @returns Promise resolving to detailed execution result with performance metrics
84
+ * @throws {Error} When agent execution fails or parameters are invalid
85
+ *
86
+ * @example
87
+ * ```typescript
88
+ * const executor = new AgentExecutor()
89
+ * const result = await executor.executeAgent({
90
+ * agent: "code-helper",
91
+ * prompt: "Review this code",
92
+ * cwd: "/project"
93
+ * })
94
+ * console.log(`Execution took ${result.executionTime}ms using ${result.executionMethod}`)
95
+ * ```
96
+ */
97
+ executeAgent(params: ExecutionParams): Promise<AgentExecutionResult>;
98
+ /**
99
+ * Executes an agent using child_process.spawn for proper TTY handling.
100
+ *
101
+ * @private
102
+ * @param params - Execution parameters
103
+ * @returns Promise resolving to execution result
104
+ */
105
+ private executeWithSpawn;
106
+ /**
107
+ * Generates a unique request ID for tracking execution requests.
108
+ *
109
+ * @private
110
+ * @returns Unique request identifier
111
+ */
112
+ private generateRequestId;
113
+ }
114
+ //# sourceMappingURL=AgentExecutor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AgentExecutor.d.ts","sourceRoot":"","sources":["../../src/execution/AgentExecutor.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAA;AAChE,OAAO,EAAiB,MAAM,EAAE,MAAM,kBAAkB,CAAA;AAGxD;;;GAGG;AACH,MAAM,WAAW,oBAAoB;IACnC;;;OAGG;IACH,MAAM,EAAE,MAAM,CAAA;IAEd;;;OAGG;IACH,MAAM,EAAE,MAAM,CAAA;IAEd;;;OAGG;IACH,QAAQ,EAAE,MAAM,CAAA;IAEhB;;;OAGG;IACH,aAAa,EAAE,MAAM,CAAA;IAErB;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAA;IAEnB;;;OAGG;IACH,UAAU,CAAC,EAAE,OAAO,CAAA;CACrB;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B;;;OAGG;IACH,gBAAgB,EAAE,MAAM,CAAA;IAExB;;;OAGG;IACH,SAAS,EAAE,QAAQ,GAAG,QAAQ,CAAA;CAC/B;AAED,eAAO,MAAM,yBAAyB,SAAS,CAAA;AAE/C;;;;GAIG;AACH,wBAAgB,qBAAqB,CACnC,SAAS,EAAE,QAAQ,GAAG,QAAQ,EAC9B,SAAS,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC,eAAe,EAAE,WAAW,CAAC,CAAC,GACtD,eAAe,CAMjB;AAED;;;;GAIG;AACH,qBAAa,aAAa;IACxB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAiB;IACxC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAQ;IAE/B;;;;;OAKG;gBACS,MAAM,EAAE,eAAe,EAAE,MAAM,CAAC,EAAE,MAAM;IAMpD;;;;;;;;;;;;;;;;;;;;OAoBG;IACG,YAAY,CAAC,MAAM,EAAE,eAAe,GAAG,OAAO,CAAC,oBAAoB,CAAC;IA+E1E;;;;;;OAMG;YACW,gBAAgB;IAqH9B;;;;;OAKG;IACH,OAAO,CAAC,iBAAiB;CAG1B"}
@@ -0,0 +1,234 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AgentExecutor = exports.DEFAULT_EXECUTION_TIMEOUT = void 0;
4
+ exports.createExecutionConfig = createExecutionConfig;
5
+ const node_child_process_1 = require("node:child_process");
6
+ const Logger_1 = require("../utils/Logger");
7
+ const StreamProcessor_1 = require("./StreamProcessor");
8
+ exports.DEFAULT_EXECUTION_TIMEOUT = 300000; // 5 minutes
9
+ /**
10
+ * Creates a complete ExecutionConfig with the provided agent type.
11
+ * @param agentType - The type of agent to use
12
+ * @param overrides - Optional overrides for thresholds
13
+ */
14
+ function createExecutionConfig(agentType, overrides) {
15
+ return {
16
+ executionTimeout: exports.DEFAULT_EXECUTION_TIMEOUT,
17
+ ...overrides,
18
+ agentType,
19
+ };
20
+ }
21
+ /**
22
+ * AgentExecutor class implements execution strategy for running Claude Code agents.
23
+ * Uses child_process.spawn for proper TTY handling and stdin/stdout streaming.
24
+ * Includes performance monitoring and timeout management.
25
+ */
26
+ class AgentExecutor {
27
+ /**
28
+ * Creates a new AgentExecutor instance.
29
+ *
30
+ * @param config - Execution configuration including CLI command and thresholds
31
+ * @param logger - Optional Logger instance for structured logging
32
+ */
33
+ constructor(config, logger) {
34
+ this.config = config;
35
+ // Use provided logger or create new one with LOG_LEVEL env var
36
+ this.logger = logger || new Logger_1.Logger(process.env['LOG_LEVEL'] || 'info');
37
+ }
38
+ /**
39
+ * Executes an agent with the specified parameters using spawn strategy.
40
+ *
41
+ * This method implements the core execution logic using spawn for proper TTY
42
+ * handling and streaming. It includes comprehensive performance monitoring.
43
+ *
44
+ * @param params - Execution parameters including agent name, prompt, and options
45
+ * @returns Promise resolving to detailed execution result with performance metrics
46
+ * @throws {Error} When agent execution fails or parameters are invalid
47
+ *
48
+ * @example
49
+ * ```typescript
50
+ * const executor = new AgentExecutor()
51
+ * const result = await executor.executeAgent({
52
+ * agent: "code-helper",
53
+ * prompt: "Review this code",
54
+ * cwd: "/project"
55
+ * })
56
+ * console.log(`Execution took ${result.executionTime}ms using ${result.executionMethod}`)
57
+ * ```
58
+ */
59
+ async executeAgent(params) {
60
+ // Input validation
61
+ if (!params || !params.agent || !params.prompt) {
62
+ const error = 'Invalid execution parameters: agent and prompt are required';
63
+ this.logger.error('Agent execution failed during validation', undefined, { error, params });
64
+ throw new Error(error);
65
+ }
66
+ if (params.agent.length === 0 || params.prompt.length === 0) {
67
+ const error = 'Invalid execution parameters: agent and prompt cannot be empty';
68
+ this.logger.error('Agent execution failed during validation', undefined, { error, params });
69
+ throw new Error(error);
70
+ }
71
+ const startTime = Date.now();
72
+ const requestId = this.generateRequestId();
73
+ this.logger.info('Starting agent execution', {
74
+ requestId,
75
+ agent: params.agent,
76
+ promptLength: params.prompt.length,
77
+ cwd: params.cwd,
78
+ extraArgs: params.extra_args?.length || 0,
79
+ });
80
+ try {
81
+ // Add minimal delay to ensure execution time is measurable
82
+ await new Promise((resolve) => setTimeout(resolve, 1));
83
+ // Use spawn method for proper TTY handling
84
+ // Execute using spawn for proper TTY handling
85
+ const result = await this.executeWithSpawn(params);
86
+ const executionTime = Date.now() - startTime;
87
+ this.logger.info('Agent execution completed', {
88
+ requestId,
89
+ exitCode: result.exitCode,
90
+ executionTime,
91
+ hasResult: result.hasResult,
92
+ });
93
+ return {
94
+ stdout: result.stdout,
95
+ stderr: result.stderr,
96
+ exitCode: result.exitCode,
97
+ executionTime,
98
+ ...(result.hasResult !== undefined && { hasResult: result.hasResult }),
99
+ ...(result.resultJson !== undefined && { resultJson: result.resultJson }),
100
+ };
101
+ }
102
+ catch (error) {
103
+ const executionTime = Date.now() - startTime;
104
+ this.logger.error('Agent execution failed', error instanceof Error ? error : undefined, {
105
+ requestId,
106
+ executionTime,
107
+ });
108
+ // Re-throw enhancement errors
109
+ if (error instanceof Error &&
110
+ (error.message.includes('enhance') || error.message.includes('Enhancement'))) {
111
+ throw error;
112
+ }
113
+ // Return error result for execution failures
114
+ return {
115
+ stdout: '',
116
+ stderr: error instanceof Error ? error.message : 'Unknown execution error',
117
+ exitCode: 1,
118
+ executionTime,
119
+ hasResult: false,
120
+ resultJson: undefined,
121
+ };
122
+ }
123
+ }
124
+ /**
125
+ * Executes an agent using child_process.spawn for proper TTY handling.
126
+ *
127
+ * @private
128
+ * @param params - Execution parameters
129
+ * @returns Promise resolving to execution result
130
+ */
131
+ async executeWithSpawn(params) {
132
+ return new Promise((resolve) => {
133
+ // Generate command and args - both CLIs use the same interface
134
+ const formattedPrompt = `[System Context]\n${params.agent}\n\n[User Prompt]\n${params.prompt}`;
135
+ const args = ['--output-format', 'json', '-p', formattedPrompt];
136
+ // Determine command based on agent type
137
+ const command = this.config.agentType === 'claude' ? 'claude' : 'cursor-agent';
138
+ // Add API key for cursor-cli if available
139
+ if (this.config.agentType === 'cursor' && process.env['CLI_API_KEY']) {
140
+ args.push('-a', process.env['CLI_API_KEY']);
141
+ }
142
+ this.logger.debug('Executing with spawn', {
143
+ command,
144
+ cwd: params.cwd || process.cwd(),
145
+ });
146
+ // Spawn process
147
+ const childProcess = (0, node_child_process_1.spawn)(command, args, {
148
+ cwd: params.cwd || process.cwd(),
149
+ stdio: ['ignore', 'pipe', 'pipe'], // stdin set to 'ignore' as cursor-agent receives prompt via args
150
+ shell: false,
151
+ env: process.env,
152
+ });
153
+ // Initialize stream processor and buffers
154
+ const streamProcessor = new StreamProcessor_1.StreamProcessor();
155
+ let stdout = '';
156
+ let stderr = '';
157
+ let stdoutBuffer = '';
158
+ // No need to handle stdin as it's set to 'ignore'
159
+ const executionTimeout = setTimeout(() => {
160
+ this.logger.warn('Execution timeout reached', {
161
+ timeout: this.config.executionTimeout,
162
+ });
163
+ childProcess.kill('SIGTERM');
164
+ // Get any result collected so far
165
+ const result = streamProcessor.getResult();
166
+ resolve({
167
+ stdout: result ? JSON.stringify(result) : stdout,
168
+ stderr: stderr || `Execution timeout: ${this.config.executionTimeout}ms`,
169
+ exitCode: 124, // Standard timeout exit code
170
+ hasResult: result !== null,
171
+ resultJson: result !== null ? result : undefined,
172
+ });
173
+ }, this.config.executionTimeout);
174
+ // Handle stdout stream with simplified processing
175
+ childProcess.stdout?.on('data', (data) => {
176
+ const chunk = data.toString();
177
+ stdout += chunk;
178
+ stdoutBuffer += chunk;
179
+ // Process complete lines
180
+ const lines = stdoutBuffer.split('\n');
181
+ stdoutBuffer = lines.pop() || ''; // Keep incomplete line in buffer
182
+ for (const line of lines) {
183
+ // Process line returns true when final JSON is detected
184
+ const isComplete = streamProcessor.processLine(line);
185
+ if (isComplete) {
186
+ // Processing complete, kill the process
187
+ childProcess.kill('SIGTERM');
188
+ break;
189
+ }
190
+ }
191
+ });
192
+ // Handle stderr stream
193
+ childProcess.stderr?.on('data', (data) => {
194
+ stderr += data.toString();
195
+ });
196
+ childProcess.on('close', (code) => {
197
+ clearTimeout(executionTimeout);
198
+ // Get the final result JSON
199
+ const result = streamProcessor.getResult();
200
+ resolve({
201
+ stdout: result ? JSON.stringify(result) : stdout,
202
+ stderr,
203
+ exitCode: code || 0,
204
+ hasResult: result !== null,
205
+ resultJson: result !== null ? result : undefined,
206
+ });
207
+ });
208
+ // Handle process errors
209
+ childProcess.on('error', (error) => {
210
+ clearTimeout(executionTimeout);
211
+ // Get any result collected before error
212
+ const result = streamProcessor.getResult();
213
+ resolve({
214
+ stdout: result ? JSON.stringify(result) : stdout,
215
+ stderr: stderr || error.message,
216
+ exitCode: 1,
217
+ hasResult: result !== null,
218
+ resultJson: result !== null ? result : undefined,
219
+ });
220
+ });
221
+ });
222
+ }
223
+ /**
224
+ * Generates a unique request ID for tracking execution requests.
225
+ *
226
+ * @private
227
+ * @returns Unique request identifier
228
+ */
229
+ generateRequestId() {
230
+ return `req_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;
231
+ }
232
+ }
233
+ exports.AgentExecutor = AgentExecutor;
234
+ //# sourceMappingURL=AgentExecutor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AgentExecutor.js","sourceRoot":"","sources":["../../src/execution/AgentExecutor.ts"],"names":[],"mappings":";;;AAuEA,sDASC;AAhFD,2DAA6D;AAE7D,6CAAwD;AACxD,uDAAmD;AA6DtC,QAAA,yBAAyB,GAAG,MAAM,CAAA,CAAC,YAAY;AAE5D;;;;GAIG;AACH,SAAgB,qBAAqB,CACnC,SAA8B,EAC9B,SAAuD;IAEvD,OAAO;QACL,gBA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AC;oBACN,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM;oBAChD,MAAM;oBACN,QAAQ,EAAE,IAAI,IAAI,CAAC;oBACnB,SAAS,EAAE,MAAM,KAAK,IAAI;oBAC1B,UAAU,EAAE,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS;iBACjD,CAAC,CAAA;YACJ,CAAC,CAAC,CAAA;YAEF,wBAAwB;YACxB,YAAY,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,KAAY,EAAE,EAAE;gBACxC,YAAY,CAAC,gBAAgB,CAAC,CAAA;gBAE9B,wCAAwC;gBACxC,MAAM,MAAM,GAAG,eAAe,CAAC,SAAS,EAAE,CAAA;gBAE1C,OAAO,CAAC;oBACN,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM;oBAChD,MAAM,EAAE,MAAM,IAAI,KAAK,CAAC,OAAO;oBAC/B,QAAQ,EAAE,CAAC;oBACX,SAAS,EAAE,MAAM,KAAK,IAAI;oBAC1B,UAAU,EAAE,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS;iBACjD,CAAC,CAAA;YACJ,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;IACJ,CAAC;IAED;;;;;OAKG;IACK,iBAAiB;QACvB,OAAO,OAAO,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,CAAA;IACvE,CAAC;CACF;AAzPD,sCAyPC"}
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Execution limits configuration and enforcement for agent execution.
3
+ *
4
+ * Provides configurable limits for resource usage including memory, concurrency,
5
+ * execution time, and output size to ensure system stability and prevent abuse.
6
+ */
7
+ /**
8
+ * Configuration interface for execution limits.
9
+ */
10
+ export interface ExecutionLimitsConfig {
11
+ /** Maximum number of concurrent agent executions (default: 5) */
12
+ maxConcurrentExecutions: number;
13
+ /** Maximum memory usage per execution in MB (default: 100) */
14
+ maxMemoryUsageMB: number;
15
+ /** Maximum output size in bytes (default: 1MB) */
16
+ maxOutputSizeBytes: number;
17
+ /** Maximum execution time in milliseconds (default: 90000) */
18
+ maxExecutionTimeMs: number;
19
+ /** Enable resource monitoring (default: true) */
20
+ enableResourceMonitoring: boolean;
21
+ }
22
+ /**
23
+ * Resource usage statistics for monitoring.
24
+ */
25
+ export interface ResourceUsage {
26
+ /** Current memory usage in MB */
27
+ memoryUsageMB: number;
28
+ /** Current number of active executions */
29
+ activeExecutions: number;
30
+ /** Current output size in bytes */
31
+ outputSizeBytes: number;
32
+ /** Execution time elapsed in milliseconds */
33
+ executionTimeMs: number;
34
+ }
35
+ /**
36
+ * Default execution limits configuration.
37
+ */
38
+ export declare const DEFAULT_EXECUTION_LIMITS: ExecutionLimitsConfig;
39
+ /**
40
+ * Execution limits enforcer for resource constraint management.
41
+ *
42
+ * Monitors and enforces limits on concurrent executions, memory usage,
43
+ * output size, and execution time to prevent resource exhaustion.
44
+ */
45
+ export declare class ExecutionLimits {
46
+ private readonly config;
47
+ private activeExecutions;
48
+ /**
49
+ * Creates a new ExecutionLimits instance.
50
+ *
51
+ * @param config - Execution limits configuration (uses defaults if not provided)
52
+ */
53
+ constructor(config?: Partial<ExecutionLimitsConfig>);
54
+ /**
55
+ * Checks if a new execution can be started within limits.
56
+ *
57
+ * @param executionId - Unique identifier for the execution
58
+ * @throws {ResourceLimitError} When concurrent execution limit is exceeded
59
+ */
60
+ checkConcurrencyLimit(executionId: string): void;
61
+ /**
62
+ * Registers a new execution as active.
63
+ *
64
+ * @param executionId - Unique identifier for the execution
65
+ */
66
+ registerExecution(executionId: string): void;
67
+ /**
68
+ * Unregisters an execution as completed.
69
+ *
70
+ * @param executionId - Unique identifier for the execution
71
+ */
72
+ unregisterExecution(executionId: string): void;
73
+ /**
74
+ * Checks if memory usage is within limits.
75
+ *
76
+ * @param memoryUsageMB - Current memory usage in MB
77
+ * @throws {ResourceLimitError} When memory limit is exceeded
78
+ */
79
+ checkMemoryLimit(memoryUsageMB: number): void;
80
+ /**
81
+ * Checks if output size is within limits.
82
+ *
83
+ * @param outputSizeBytes - Current output size in bytes
84
+ * @throws {ResourceLimitError} When output size limit is exceeded
85
+ */
86
+ checkOutputSizeLimit(outputSizeBytes: number): void;
87
+ /**
88
+ * Gets current resource usage statistics.
89
+ *
90
+ * @param currentMemoryMB - Current memory usage in MB
91
+ * @param currentOutputBytes - Current output size in bytes
92
+ * @param executionTimeMs - Current execution time in milliseconds
93
+ * @returns Resource usage statistics
94
+ */
95
+ getResourceUsage(currentMemoryMB?: number, currentOutputBytes?: number, executionTimeMs?: number): ResourceUsage;
96
+ /**
97
+ * Gets the current configuration.
98
+ *
99
+ * @returns Execution limits configuration
100
+ */
101
+ getConfig(): ExecutionLimitsConfig;
102
+ /**
103
+ * Gets the number of active executions.
104
+ *
105
+ * @returns Number of active executions
106
+ */
107
+ getActiveExecutionCount(): number;
108
+ /**
109
+ * Checks if resource monitoring is enabled.
110
+ *
111
+ * @returns True if resource monitoring is enabled
112
+ */
113
+ isResourceMonitoringEnabled(): boolean;
114
+ /**
115
+ * Gets adaptive resource limits based on current system state.
116
+ *
117
+ * @param systemMemoryMB - Current available system memory in MB
118
+ * @param systemLoad - Current system load (0-1)
119
+ * @returns Adjusted execution limits configuration
120
+ */
121
+ getAdaptiveLimits(systemMemoryMB: number, systemLoad?: number): ExecutionLimitsConfig;
122
+ /**
123
+ * Monitors resource usage and suggests optimizations.
124
+ *
125
+ * @param currentUsage - Current resource usage
126
+ * @returns Resource optimization suggestions
127
+ */
128
+ analyzeResourceUsage(currentUsage: ResourceUsage): {
129
+ recommendations: string[];
130
+ severity: 'low' | 'medium' | 'high';
131
+ shouldThrottle: boolean;
132
+ };
133
+ /**
134
+ * Creates execution limits optimized for specific operation types.
135
+ *
136
+ * @param operationType - Type of operation (light, standard, heavy)
137
+ * @returns Optimized execution limits configuration
138
+ */
139
+ createOptimizedConfig(operationType: 'light' | 'standard' | 'heavy'): ExecutionLimitsConfig;
140
+ }
141
+ //# sourceMappingURL=ExecutionLimits.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ExecutionLimits.d.ts","sourceRoot":"","sources":["../../src/execution/ExecutionLimits.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC,iEAAiE;IACjE,uBAAuB,EAAE,MAAM,CAAA;IAE/B,8DAA8D;IAC9D,gBAAgB,EAAE,MAAM,CAAA;IAExB,kDAAkD;IAClD,kBAAkB,EAAE,MAAM,CAAA;IAE1B,8DAA8D;IAC9D,kBAAkB,EAAE,MAAM,CAAA;IAE1B,iDAAiD;IACjD,wBAAwB,EAAE,OAAO,CAAA;CAClC;AAED;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,iCAAiC;IACjC,aAAa,EAAE,MAAM,CAAA;IAErB,0CAA0C;IAC1C,gBAAgB,EAAE,MAAM,CAAA;IAExB,mCAAmC;IACnC,eAAe,EAAE,MAAM,CAAA;IAEvB,6CAA6C;IAC7C,eAAe,EAAE,MAAM,CAAA;CACxB;AAED;;GAEG;AACH,eAAO,MAAM,wBAAwB,EAAE,qBAMtC,CAAA;AAED;;;;;GAKG;AACH,qBAAa,eAAe;IAC1B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAuB;IAC9C,OAAO,CAAC,gBAAgB,CAAyB;IAEjD;;;;OAIG;gBACS,MAAM,GAAE,OAAO,CAAC,qBAAqB,CAAM;IAIvD;;;;;OAKG;IACH,qBAAqB,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI;IAehD;;;;OAIG;IACH,iBAAiB,CAAC,WAAW,E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