Class: LanguageOperator::Agent::WebServer
- Inherits:
-
Object
- Object
- LanguageOperator::Agent::WebServer
- Defined in:
- lib/language_operator/agent/web_server.rb
Overview
Web Server for Reactive Agents
Enables agents to receive HTTP requests (webhooks, API calls) and respond to them. Agents in :reactive mode run an HTTP server that listens for incoming requests and triggers agent execution.
Instance Attribute Summary collapse
-
#agent ⇒ Object
readonly
Returns the value of attribute agent.
-
#port ⇒ Object
readonly
Returns the value of attribute port.
Instance Method Summary collapse
-
#add_directory_to_tar(tar, source_path, archive_path) ⇒ Object
Add directory to tar archive recursively.
-
#cleanup ⇒ void
Cleanup executor pool and connections.
-
#get_file_info(full_path, requested_path) ⇒ Object
Get file information.
-
#handle_request(env) ⇒ Array
Handle incoming HTTP request.
-
#handle_workspace_delete(context) ⇒ Object
Handle DELETE /api/v1/workspace/files - delete file.
-
#handle_workspace_download(context) ⇒ Object
Handle GET /api/v1/workspace/files/download - download file or directory as tar.gz.
-
#handle_workspace_list(context) ⇒ Object
Handle GET /api/v1/workspace/files - list directory contents.
-
#handle_workspace_upload(context) ⇒ Object
Handle POST /api/v1/workspace/files - upload file.
-
#handle_workspace_view(context) ⇒ Object
Handle GET /api/v1/workspace/files/view - view file contents.
-
#initialize(agent, port: nil) ⇒ WebServer
constructor
Initialize the web server.
-
#list_directory_contents(full_path, requested_path) ⇒ Object
List directory contents.
-
#parse_multipart(body, boundary) ⇒ Object
Parse multipart form data.
-
#register_chat_endpoint(agent) ⇒ void
Register chat completion endpoint.
-
#register_execute_endpoint(agent, agent_def = nil) ⇒ void
Register execution trigger endpoint.
-
#register_mcp_tools(mcp_server_def) ⇒ void
Register MCP tools.
-
#register_route(path, method: :post, authentication: nil, validations: nil, &handler) ⇒ void
Register a webhook route.
-
#register_workspace_endpoints(agent) ⇒ Object
Register workspace file management endpoints.
-
#route_exists?(path, method) ⇒ Boolean
Check if a route exists.
-
#sanitize_workspace_path(path) ⇒ Object
Sanitize workspace path to prevent directory traversal attacks.
-
#start ⇒ void
Start the HTTP server.
-
#workspace_error_response(status, error_type, message) ⇒ Object
Generate workspace error response.
Constructor Details
#initialize(agent, port: nil) ⇒ WebServer
Initialize the web server
29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/language_operator/agent/web_server.rb', line 29 def initialize(agent, port: nil) @agent = agent @port = port || ENV.fetch('PORT', '8080').to_i @routes = {} @mcp_server = nil @mcp_transport = nil @execution_state = nil # Initialized when register_execute_endpoint called # Initialize executor pool to prevent MCP connection leaks @executor_pool_size = ENV.fetch('EXECUTOR_POOL_SIZE', '4').to_i @executor_pool = setup_executor_pool setup_default_routes end |
Instance Attribute Details
#agent ⇒ Object (readonly)
Returns the value of attribute agent.
23 24 25 |
# File 'lib/language_operator/agent/web_server.rb', line 23 def agent @agent end |
#port ⇒ Object (readonly)
Returns the value of attribute port.
23 24 25 |
# File 'lib/language_operator/agent/web_server.rb', line 23 def port @port end |
Instance Method Details
#add_directory_to_tar(tar, source_path, archive_path) ⇒ Object
Add directory to tar archive recursively
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 |
# File 'lib/language_operator/agent/web_server.rb', line 499 def add_directory_to_tar(tar, source_path, archive_path) Dir.entries(source_path).each do |entry| next if entry.start_with?('.') full_path = File.join(source_path, entry) tar_path = File.join(archive_path, entry) if File.directory?(full_path) tar.mkdir(tar_path, 0755) add_directory_to_tar(tar, full_path, tar_path) else tar.add_file(tar_path, 0644) do |io| io.write(File.binread(full_path)) end end end end |
#cleanup ⇒ void
This method returns an undefined value.
Cleanup executor pool and connections
Properly closes all executors in the pool and their MCP connections to prevent resource leaks during server shutdown.
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 |
# File 'lib/language_operator/agent/web_server.rb', line 557 def cleanup return unless @executor_pool # Drain and cleanup all executors in the pool executors_cleaned = 0 until @executor_pool.empty? executor = @executor_pool.pop unless @executor_pool.empty? if executor executor.cleanup_connections executors_cleaned += 1 end end puts "Cleaned up #{executors_cleaned} executors from pool" end |
#get_file_info(full_path, requested_path) ⇒ Object
Get file information
455 456 457 458 459 460 461 462 463 464 465 |
# File 'lib/language_operator/agent/web_server.rb', line 455 def get_file_info(full_path, requested_path) { status: 200, body: { path: requested_path, size: File.size(full_path), type: 'file' }, headers: { 'Content-Type' => 'application/json' } } end |
#handle_request(env) ⇒ Array
Handle incoming HTTP request
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 |
# File 'lib/language_operator/agent/web_server.rb', line 533 def handle_request(env) request = Rack::Request.new(env) path = request.path method = request.request_method.downcase.to_sym # Try to find a matching route route_key = normalize_route_key(path, method) route_config = @routes[route_key] if route_config execute_handler(route_config, request) else not_found_response(path, method) end rescue StandardError => e error_response(e) end |
#handle_workspace_delete(context) ⇒ Object
Handle DELETE /api/v1/workspace/files - delete file
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 |
# File 'lib/language_operator/agent/web_server.rb', line 326 def handle_workspace_delete(context) request = context[:request] path = request.params['path'] return workspace_error_response(400, 'BadRequest', 'path parameter required') unless path # Sanitize path to prevent directory traversal safe_path = sanitize_workspace_path(path) full_path = File.join(@workspace_path, safe_path) return workspace_error_response(404, 'NotFound', "File not found: #{path}") unless File.exist?(full_path) # Delete file or directory if File.directory?(full_path) FileUtils.rm_rf(full_path) else File.delete(full_path) end { status: 200, body: { message: 'File deleted successfully', path: path }, headers: { 'Content-Type' => 'application/json' } } rescue StandardError => e workspace_error_response(500, 'DeleteError', "Deletion failed: #{e.}") end |
#handle_workspace_download(context) ⇒ Object
Handle GET /api/v1/workspace/files/download - download file or directory as tar.gz
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 |
# File 'lib/language_operator/agent/web_server.rb', line 358 def handle_workspace_download(context) request = context[:request] path = request.params['path'] return workspace_error_response(400, 'BadRequest', 'path parameter required') unless path # Sanitize path to prevent directory traversal safe_path = sanitize_workspace_path(path) full_path = File.join(@workspace_path, safe_path) return workspace_error_response(404, 'NotFound', "Path not found: #{path}") unless File.exist?(full_path) if File.file?(full_path) # Single file download content = File.binread(full_path) filename = File.basename(full_path) { status: 200, body: content, headers: { 'Content-Type' => 'application/octet-stream', 'Content-Disposition' => "attachment; filename=\"#{filename}\"" } } else # Directory download as tar.gz require 'tempfile' require 'zlib' require 'rubygems/package' Tempfile.create(['workspace', '.tar.gz']) do |temp_file| Zlib::GzipWriter.open(temp_file.path) do |gz| Gem::Package::TarWriter.new(gz) do |tar| add_directory_to_tar(tar, full_path, safe_path) end end content = File.binread(temp_file.path) filename = "#{File.basename(path)}.tar.gz" { status: 200, body: content, headers: { 'Content-Type' => 'application/gzip', 'Content-Disposition' => "attachment; filename=\"#{filename}\"" } } end end rescue StandardError => e workspace_error_response(500, 'DownloadError', "Download failed: #{e.}") end |
#handle_workspace_list(context) ⇒ Object
Handle GET /api/v1/workspace/files - list directory contents
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 |
# File 'lib/language_operator/agent/web_server.rb', line 221 def handle_workspace_list(context) request = context[:request] path = request.params['path'] || '/' # Sanitize path to prevent directory traversal safe_path = sanitize_workspace_path(path) full_path = File.join(@workspace_path, safe_path) return workspace_error_response(404, 'NotFound', "Path not found: #{path}") unless File.exist?(full_path) if File.directory?(full_path) list_directory_contents(full_path, path) else # If it's a file, return file info get_file_info(full_path, path) end rescue StandardError => e workspace_error_response(500, 'InternalError', e.) end |
#handle_workspace_upload(context) ⇒ Object
Handle POST /api/v1/workspace/files - upload file
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 |
# File 'lib/language_operator/agent/web_server.rb', line 277 def handle_workspace_upload(context) request = context[:request] # Parse multipart form data if request.content_type&.start_with?('multipart/form-data') boundary = request.content_type.split('boundary=')[1] return workspace_error_response(400, 'BadRequest', 'Missing boundary in multipart data') unless boundary # Parse the multipart data body = request.body.read parts = parse_multipart(body, boundary) file_part = parts.find { |part| part[:name] == 'file' } path_param = parts.find { |part| part[:name] == 'path' }&.dig(:content) return workspace_error_response(400, 'BadRequest', 'file parameter required') unless file_part return workspace_error_response(400, 'BadRequest', 'path parameter required') unless path_param # Sanitize path to prevent directory traversal safe_path = sanitize_workspace_path(path_param) full_path = File.join(@workspace_path, safe_path) # Check file size (limit to 100MB) content = file_part[:content] return workspace_error_response(413, 'FileTooLarge', 'File too large (max 100MB)') if content.bytesize > 100 * 1024 * 1024 # Create directory if it doesn't exist FileUtils.mkdir_p(File.dirname(full_path)) # Write file File.binwrite(full_path, content) { status: 201, body: { message: 'File uploaded successfully', path: path_param, size: content.bytesize }, headers: { 'Content-Type' => 'application/json' } } else workspace_error_response(400, 'BadRequest', 'Expected multipart/form-data') end rescue StandardError => e workspace_error_response(500, 'UploadError', "Upload failed: #{e.}") end |
#handle_workspace_view(context) ⇒ Object
Handle GET /api/v1/workspace/files/view - view file contents
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 |
# File 'lib/language_operator/agent/web_server.rb', line 242 def handle_workspace_view(context) request = context[:request] path = request.params['path'] return workspace_error_response(400, 'BadRequest', 'path parameter required') unless path # Sanitize path to prevent directory traversal safe_path = sanitize_workspace_path(path) full_path = File.join(@workspace_path, safe_path) return workspace_error_response(404, 'NotFound', "File not found: #{path}") unless File.exist?(full_path) return workspace_error_response(400, 'BadRequest', "Path is not a file: #{path}") unless File.file?(full_path) # Check file size (limit to 10MB for API responses) file_size = File.size(full_path) return workspace_error_response(413, 'FileTooLarge', 'File too large for viewing (max 10MB)') if file_size > 10 * 1024 * 1024 # Read file contents contents = File.read(full_path) { status: 200, body: { path: path, size: file_size, contents: contents }, headers: { 'Content-Type' => 'application/json' } } rescue StandardError => e workspace_error_response(500, 'InternalError', e.) end |
#list_directory_contents(full_path, requested_path) ⇒ Object
List directory contents
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 |
# File 'lib/language_operator/agent/web_server.rb', line 431 def list_directory_contents(full_path, requested_path) entries = Dir.entries(full_path).reject { |entry| entry.start_with?('.') } files = entries.map do |entry| entry_path = File.join(full_path, entry) { name: entry, type: File.directory?(entry_path) ? 'directory' : 'file', size: File.file?(entry_path) ? File.size(entry_path) : nil, path: File.join(requested_path, entry).sub(%r{^/+}, '') } end { status: 200, body: { path: requested_path, files: files }, headers: { 'Content-Type' => 'application/json' } } end |
#parse_multipart(body, boundary) ⇒ Object
Parse multipart form data
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 |
# File 'lib/language_operator/agent/web_server.rb', line 468 def parse_multipart(body, boundary) parts = [] boundary = "--#{boundary}" sections = body.split(boundary) sections[1..-2]&.each do |section| next if section.strip.empty? lines = section.split("\r\n") content_disposition = lines.find { |line| line.include?('Content-Disposition') } next unless content_disposition name_match = content_disposition.match(/name="([^"]+)"/) next unless name_match name = name_match[1] # Find empty line separating headers from content content_start = lines.index('') next unless content_start content = lines[(content_start + 1)..-1].join("\r\n") content = content[0..-3] if content.end_with?("\r\n") # Remove trailing CRLF parts << { name: name, content: content } end parts end |
#register_chat_endpoint(agent) ⇒ void
This method returns an undefined value.
Register chat completion endpoint
Sets up OpenAI-compatible chat completion endpoint for all agents. Every agent automatically gets identity-aware chat capabilities.
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 |
# File 'lib/language_operator/agent/web_server.rb', line 122 def register_chat_endpoint(agent) @chat_agent = agent # Create simple chat configuration (identity awareness always enabled) @chat_config = { model_name: ENV.fetch('AGENT_NAME', agent.config&.dig('agent', 'name') || 'agent'), system_prompt: build_default_system_prompt(agent), temperature: 0.7, max_tokens: 2000 } # Register OpenAI-compatible endpoint register_route('/v1/chat/completions', method: :post) do |context| handle_chat_completion(context) end # Also register models endpoint for compatibility register_route('/v1/models', method: :get) do |_context| { object: 'list', data: [ { id: @chat_config[:model_name], object: 'model', created: Time.now.to_i, owned_by: 'language-operator', permission: [], root: @chat_config[:model_name], parent: nil } ] } end puts "Registered identity-aware chat endpoint as model: #{@chat_config[:model_name]}" end |
#register_execute_endpoint(agent, agent_def = nil) ⇒ void
This method returns an undefined value.
Register execution trigger endpoint
Enables scheduled/reactive agents to execute tasks via HTTP POST. Prevents concurrent executions via ExecutionState.
167 168 169 170 171 172 173 174 175 176 177 178 179 |
# File 'lib/language_operator/agent/web_server.rb', line 167 def register_execute_endpoint(agent, agent_def = nil) require_relative 'execution_state' @execute_agent = agent @execute_agent_def = agent_def @execution_state = LanguageOperator::Agent::ExecutionState.new register_route('/api/v1/execute', method: :post) do |context| handle_execute_request(context) end puts 'Registered /api/v1/execute endpoint for triggered execution' end |
#register_mcp_tools(mcp_server_def) ⇒ void
This method returns an undefined value.
Register MCP tools
Sets up MCP protocol endpoints for tool discovery and execution. Tools defined in the agent will be exposed via MCP protocol.
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
# File 'lib/language_operator/agent/web_server.rb', line 88 def register_mcp_tools(mcp_server_def) require_relative '../dsl/adapter' # Convert tool definitions to MCP::Tool classes mcp_tools = mcp_server_def.all_tools.map do |tool_def| Dsl::Adapter.tool_definition_to_mcp_tool(tool_def) end # Create MCP server @mcp_server = MCP::Server.new( name: mcp_server_def.server_name, version: LanguageOperator::VERSION, tools: mcp_tools ) # Create the Streamable HTTP transport @mcp_transport = MCP::Server::Transports::StreamableHTTPTransport.new(@mcp_server) @mcp_server.transport = @mcp_transport # Register MCP endpoint register_route('/mcp', method: :post) do |context| handle_mcp_request(context[:request]) end puts "Registered #{mcp_tools.size} MCP tools" end |
#register_route(path, method: :post, authentication: nil, validations: nil, &handler) ⇒ void
This method returns an undefined value.
Register a webhook route
64 65 66 67 68 69 70 |
# File 'lib/language_operator/agent/web_server.rb', line 64 def register_route(path, method: :post, authentication: nil, validations: nil, &handler) @routes[normalize_route_key(path, method)] = { handler: handler, authentication: authentication, validations: validations || [] } end |
#register_workspace_endpoints(agent) ⇒ Object
Register workspace file management endpoints
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 |
# File 'lib/language_operator/agent/web_server.rb', line 184 def register_workspace_endpoints(agent) return unless agent.workspace_available? @workspace_agent = agent @workspace_path = agent.workspace_path # List directory contents register_route('/api/v1/workspace/files', method: :get) do |context| handle_workspace_list(context) end # View file contents register_route('/api/v1/workspace/files/view', method: :get) do |context| handle_workspace_view(context) end # Upload file register_route('/api/v1/workspace/files', method: :post) do |context| handle_workspace_upload(context) end # Delete file register_route('/api/v1/workspace/files', method: :delete) do |context| handle_workspace_delete(context) end # Download file/directory register_route('/api/v1/workspace/files/download', method: :get) do |context| handle_workspace_download(context) end puts 'Registered /api/v1/workspace/* endpoints for file management' end |
#route_exists?(path, method) ⇒ Boolean
Check if a route exists
77 78 79 |
# File 'lib/language_operator/agent/web_server.rb', line 77 def route_exists?(path, method) @routes.key?(normalize_route_key(path, method)) end |
#sanitize_workspace_path(path) ⇒ Object
Sanitize workspace path to prevent directory traversal attacks
416 417 418 419 420 421 422 423 424 425 426 427 428 |
# File 'lib/language_operator/agent/web_server.rb', line 416 def sanitize_workspace_path(path) # Remove leading slash and resolve relative paths clean_path = path.sub(%r{^/+}, '') # Resolve and normalize the path normalized = File.(clean_path, '/') # Ensure it doesn't escape the root return '' if normalized == '/' || !normalized.start_with?('/') # Remove leading slash for joining with workspace_path normalized[1..] end |
#start ⇒ void
This method returns an undefined value.
Start the HTTP server
47 48 49 50 51 52 53 54 |
# File 'lib/language_operator/agent/web_server.rb', line 47 def start puts "Starting Agent HTTP server on http://0.0.0.0:#{@port}" puts "Agent: #{@agent.class.name}" puts 'Mode: reactive' # Start the server with Puma Rackup::Handler.get('puma').run(rack_app, Port: @port, Host: '0.0.0.0') end |
#workspace_error_response(status, error_type, message) ⇒ Object
Generate workspace error response
518 519 520 521 522 523 524 525 526 527 |
# File 'lib/language_operator/agent/web_server.rb', line 518 def workspace_error_response(status, error_type, ) { status: status, body: { error: error_type, message: }, headers: { 'Content-Type' => 'application/json' } } end |