Module: DebugAgent::MiddlewareCore

Defined in:
lib/debug_agent/middleware.rb

Overview

Shared routing logic used by both RackMiddleware class and Middleware lambda

Class Method Summary collapse

Class Method Details

.call(env, app, engine, config) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
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
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/debug_agent/middleware.rb', line 70

def self.call(env, app, engine, config)
  path = env['PATH_INFO']
  method = env['REQUEST_METHOD']
  base = config.base_path

  # Chat UI
  if path == base || path == "#{base}/"
    if method == 'GET'
      html = ChatPage.render(base)
      return [200, { 'Content-Type' => 'text/html; charset=utf-8' }, [html]]
    end
  end

  # SSE streaming chat
  if path == "#{base}/api/chat" && method == 'POST'
    body = JSON.parse(env['rack.input'].read)
    message = body['message'] || ''
    session_id = body['sessionId'] || "session-#{Time.now.to_i}"

    cb = SseCallback.new
    engine.chat(message, session_id, cb)

    stream = cb.events.map { |event_type, data| "event: #{event_type}\ndata: #{data}\n\n" }.join

    return [200, {
      'Content-Type' => 'text/event-stream',
      'Cache-Control' => 'no-cache',
      'Connection' => 'keep-alive'
    }, [stream]]
  end

  # Clear conversation
  if path == "#{base}/api/clear" && method == 'POST'
    body = JSON.parse(env['rack.input'].read)
    session_id = body['sessionId'] || ''
    engine.clear_session(session_id) if session_id && !session_id.empty?
    return [200, { 'Content-Type' => 'application/json' }, [JSON.generate({ status: 'cleared' })]]
  end

  # Health check
  if path == "#{base}/api/health" && method == 'GET'
    return [200, { 'Content-Type' => 'application/json' }, [JSON.generate({ status: 'ok', agent: 'ruby-debug-agent' })]]
  end

  # List tools
  if path == "#{base}/api/tools" && method == 'GET'
    return [200, { 'Content-Type' => 'application/json' }, [JSON.generate({ tools: engine.tools.all_schemas })]]
  end

  # Pass through to the wrapped app
  if app
    app.call(env)
  else
    [404, { 'Content-Type' => 'text/plain' }, ['Not Found']]
  end
end