debug-agent 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 3e6a7d1a5a0a33669a5e1b1c830761c5bf5a7a0b339e58328d29c7af1621dda4
4
- data.tar.gz: 5beda4ad577f6598bcfd967e6124e819ebcbd853e00e5291a14baa08a7750ba4
3
+ metadata.gz: 3765ed2a5d8a59ed8e2dbe9fbc5d2242495e010efba4572eae92812dd5e8a364
4
+ data.tar.gz: 64244f052df523defa0b948e6c1198a36b137398f3bed04e481ad6fdda572322
5
5
  SHA512:
6
- metadata.gz: a4e5b1d103102c3446309f51b5d27dc689ff0a83bd32ab83eb4d800befd3fb72b4efbe0ae57362acc225974b36ec8b3f95ee24e7f1323dec9287f119a13c116c
7
- data.tar.gz: b4105c3b8e1f29d7df9dce15c10852f6c7cf6eb2b9797dfd71fa0f8b5ea56989d9a34386e0b9166a5987c199ec86da5b1a5be8bdf3c084d1f30ed01f074b2f76
6
+ metadata.gz: e9986fd62e11d4bd221cd913f538b851593d7edc85be8f622b32f6a72ab14be8cdadd8ac496dbc11bd402ee24d0e09253f2a2cfc5e60b1140e5f9896077a1256
7
+ data.tar.gz: e8e8edb65859072215d97edc08ae4942bcd90972666ea50fec1491e050970c0540df1fa48cb89ba8a2ee890f71d41c30f417aeb6ccffeb3b036844bf8d1526c1
data/README.md CHANGED
@@ -292,6 +292,13 @@ require 'debug_agent'
292
292
  DebugAgent.register_tool('check_redis', 'Check Redis connection') do
293
293
  { connected: true }
294
294
  end
295
+
296
+ # Tools with side effects are hidden and refused until
297
+ # DEBUG_AGENT_ALLOW_MUTATING_TOOLS=true (see Troubleshooting is read-only by default):
298
+ DebugAgent.mutating_tool('purge_tmp', 'Remove temporary files') do
299
+ { purged: true }
300
+ end
301
+ # or equivalently: DebugAgent.register_tool('purge_tmp', 'Remove temporary files', mutating: true) { ... }
295
302
  ```
296
303
 
297
304
  ## Configuration
@@ -303,6 +310,66 @@ end
303
310
  | `LLM_MODEL` | `glm-5.2` | Model name |
304
311
  | `LLM_MAX_TOOL_ROUNDS` | `25` | Max tool-calling rounds |
305
312
  | `LLM_CONTEXT_WINDOW_TOKENS` | `100000` | Context window size |
313
+ | `DEBUG_AGENT_ENABLED` | `true` | Set `false` to disable the agent: every `/agent` route is passed through to the app as if not mounted |
314
+ | `DEBUG_AGENT_BASE_PATH` | `/agent` | Mount path |
315
+ | `DEBUG_AGENT_API_KEY` | *(empty = no auth)* | When set, the UI and all `/agent/api/*` require this key |
316
+ | `DEBUG_AGENT_CORS_ORIGIN` | `*` | `Access-Control-Allow-Origin`; with an API key set, `*` means same-origin only |
317
+ | `DEBUG_AGENT_MAX_SESSIONS` | `200` | In-memory session cap (least-recently-active evicted first) |
318
+ | `DEBUG_AGENT_SESSION_TTL_SECONDS` | `3600` | Drop a session's history after this much inactivity |
319
+ | `DEBUG_AGENT_MAX_HISTORY` | `100` | Stored messages per session (oldest whole rounds dropped) |
320
+ | `DEBUG_AGENT_MAX_BODY_BYTES` | `1048576` | Request body limit for POST endpoints (413 beyond) |
321
+ | `DEBUG_AGENT_RATE_LIMIT` | `60` | `POST /agent/api/chat` requests per client IP per minute (429 beyond) |
322
+ | `DEBUG_AGENT_ALLOW_MUTATING_TOOLS` | `false` | Opt in to tools with side effects: `trigger_gc`, `force_gc`, `set_log_level`, `clear_cache`, and non-GET/HEAD/OPTIONS requests through `test_endpoint` / `batch_test_endpoints` |
323
+
324
+ ### Troubleshooting is read-only by default
325
+
326
+ Only read-only tools are offered to the model. Mutating tools are hidden from the
327
+ tool list (and from `/agent/api/tools`) and refused with a `disabled` error until
328
+ `DEBUG_AGENT_ALLOW_MUTATING_TOOLS=true`:
329
+
330
+ ```bash
331
+ export DEBUG_AGENT_ALLOW_MUTATING_TOOLS=true
332
+ ```
333
+
334
+ | Tool | Side effect |
335
+ |------|-------------|
336
+ | `trigger_gc`, `force_gc` | Run a garbage collection in the app process |
337
+ | `set_log_level` | Changes a registered logger's level |
338
+ | `clear_cache` | Removes all entries of a registered cache |
339
+ | `test_endpoint`, `batch_test_endpoints` | Non-`GET`/`HEAD`/`OPTIONS` requests to the app (`GET`/`HEAD`/`OPTIONS` always work) |
340
+
341
+ Endpoint testing only ever targets the app's own `localhost` port: a `path` that
342
+ does not start with `/` (or starts with `//`) is rejected, so the request can
343
+ never be redirected to another host. Starting without `DEBUG_AGENT_API_KEY`
344
+ logs a one-line warning to stderr; it does not change behaviour.
345
+
346
+ > **Upgrade note (breaking):** before this change the mutating tools above were
347
+ available by default. After upgrading they are hidden from the model and refused
348
+ with a `disabled` error; calls with `POST`/`PUT`/`PATCH`/`DELETE` through the
349
+ endpoint-testing tools are refused in the same way. Set
350
+ `DEBUG_AGENT_ALLOW_MUTATING_TOOLS=true` to restore the previous behaviour.
351
+
352
+ ### Security in production
353
+
354
+ By default the agent has **no authentication** and allows any origin — fine on a
355
+ developer laptop, not on a reachable port. Before exposing it:
356
+
357
+ ```bash
358
+ export DEBUG_AGENT_API_KEY=$(openssl rand -hex 32) # required on every agent route
359
+ export DEBUG_AGENT_ENABLED=false # or switch it off entirely in prod
360
+ ```
361
+
362
+ With a key set, present it as `Authorization: Bearer <key>`, `X-API-Key: <key>`,
363
+ or open the UI as `/agent?api_key=<key>` (the page then sends it as a Bearer
364
+ header). CORS becomes same-origin only unless `DEBUG_AGENT_CORS_ORIGIN` names an
365
+ explicit origin. `POST /api/chat` is rate-limited per client IP (first
366
+ `X-Forwarded-For` hop when behind a proxy — only trust it behind one you control).
367
+
368
+ ### Running the tests
369
+
370
+ ```bash
371
+ bundle exec rspec
372
+ ```
306
373
 
307
374
  ## Run the Demo
308
375
 
@@ -248,6 +248,15 @@ module DebugAgent
248
248
  const sessionId = 'session-' + Math.random().toString(36).substring(2, 11);
249
249
  const BASE_PATH = window.location.pathname;
250
250
 
251
+ // When the agent is protected by an API key, open the UI as /agent?api_key=...
252
+ // and every request below carries it as a Bearer header.
253
+ const AGENT_KEY = new URLSearchParams(location.search).get('api_key') || '';
254
+ function agentHeaders() {
255
+ const h = {'Content-Type': 'application/json'};
256
+ if (AGENT_KEY) h['Authorization'] = 'Bearer ' + AGENT_KEY;
257
+ return h;
258
+ }
259
+
251
260
  const chatMessages = document.getElementById('chat-messages');
252
261
  const chatContainer = document.getElementById('chat-container');
253
262
  const input = document.getElementById('input');
@@ -271,7 +280,7 @@ module DebugAgent
271
280
  e.preventDefault();
272
281
  if (confirm('Clear conversation history?')) {
273
282
  fetch(BASE_PATH + '/api/clear', {
274
- method: 'POST', headers: {'Content-Type':'application/json'},
283
+ method: 'POST', headers: agentHeaders(),
275
284
  body: JSON.stringify({sessionId: sessionId})
276
285
  }).then(() => {
277
286
  chatMessages.innerHTML = '';
@@ -494,7 +503,7 @@ module DebugAgent
494
503
  try {
495
504
  const response = await fetch(BASE_PATH + '/api/chat', {
496
505
  method: 'POST',
497
- headers: {'Content-Type': 'application/json'},
506
+ headers: agentHeaders(),
498
507
  body: JSON.stringify({message: text, sessionId: sessionId})
499
508
  });
500
509
  if (!response.ok) throw new Error('HTTP ' + response.status);
@@ -1,11 +1,19 @@
1
1
  require 'time'
2
2
 
3
3
  module DebugAgent
4
+ # defaultMaxHistory is the per-session message cap unless configured otherwise.
5
+ DEFAULT_MAX_HISTORY = 100
6
+
4
7
  class ChatSession
5
8
  attr_accessor :session_id, :messages, :last_token_usage,
6
- :cumulative_prompt_tokens, :cumulative_completion_tokens
9
+ :cumulative_prompt_tokens, :cumulative_completion_tokens,
10
+ :last_active_at
11
+ attr_reader :created_at
12
+
13
+ # MaxHistory caps messages.length; 0 means unlimited.
14
+ attr_accessor :max_history
7
15
 
8
- def initialize(session_id)
16
+ def initialize(session_id, max_history = DEFAULT_MAX_HISTORY)
9
17
  @session_id = session_id
10
18
  @messages = []
11
19
  @created_at = Time.now
@@ -13,10 +21,12 @@ module DebugAgent
13
21
  @last_token_usage = nil
14
22
  @cumulative_prompt_tokens = 0
15
23
  @cumulative_completion_tokens = 0
24
+ @max_history = max_history.nil? ? DEFAULT_MAX_HISTORY : max_history
16
25
  end
17
26
 
18
27
  def add_message(msg)
19
28
  @messages << msg
29
+ trim_history
20
30
  @last_active_at = Time.now
21
31
  end
22
32
 
@@ -25,6 +35,27 @@ module DebugAgent
25
35
  @last_active_at = Time.now
26
36
  end
27
37
 
38
+ # trimHistory drops the oldest whole rounds until messages.length <= max_history.
39
+ # Cuts only happen at a `user` message boundary so the remaining history never
40
+ # starts with an assistant tool_call or an orphaned tool result (which the LLM
41
+ # API rejects). If no safe cut point exists the history is left untouched.
42
+ def trim_history
43
+ return if @max_history.nil? || @max_history <= 0 || @messages.length <= @max_history
44
+
45
+ while @messages.length > @max_history
46
+ cut = nil
47
+ (1...@messages.length).each do |i|
48
+ if @messages[i]['role'] == 'user'
49
+ cut = i
50
+ break
51
+ end
52
+ end
53
+ return if cut.nil?
54
+
55
+ @messages = @messages[cut..-1]
56
+ end
57
+ end
58
+
28
59
  def record_token_usage(usage)
29
60
  return unless usage
30
61
  @last_token_usage = usage
@@ -1,3 +1,5 @@
1
+ require 'json'
2
+
1
3
  module DebugAgent
2
4
  LLMConfig = Struct.new(
3
5
  :base_url, :api_key, :model, :temperature, :max_tokens,
@@ -19,16 +21,122 @@ module DebugAgent
19
21
  self.context_window_tokens ||= 100_000
20
22
  self
21
23
  end
24
+
25
+ # The LLM api key is a secret: keep it out of inspect/serialization output.
26
+ def to_h
27
+ super.tap { |h| h[:api_key] = '[REDACTED]' unless h[:api_key].to_s.empty? }
28
+ end
29
+
30
+ def to_json(*args)
31
+ to_h.to_json(*args)
32
+ end
33
+
34
+ def inspect
35
+ fields = to_h.map { |field, value| "#{field}=#{value.inspect}" }
36
+ "#<struct #{self.class.name} #{fields.join(', ')}>"
37
+ end
22
38
  end
23
39
 
24
- Config = Struct.new(:enabled, :base_path, :llm, keyword_init: true) do
40
+ # Agent configuration, env-driven (see Config.from_env).
41
+ #
42
+ # Hardening fields:
43
+ # api_key non-empty → UI and all /api/* require the key
44
+ # cors_origin Access-Control-Allow-Origin (see MiddlewareCore.cors_headers)
45
+ # max_sessions session table cap (LRU eviction); 0 = unlimited
46
+ # session_ttl_seconds idle > ttl → fresh history on next use; 0 = never
47
+ # max_history_messages stored messages per session (whole rounds); 0 = unlimited
48
+ # max_body_bytes POST body limit (413 beyond)
49
+ # rate_limit_per_minute POST /api/chat per client IP; 0 = unlimited
50
+ # allow_mutating_tools true → tools with side effects (trigger_gc,
51
+ # set_log_level, clear_cache, non-GET/HEAD/OPTIONS
52
+ # test_endpoint requests) are offered and run.
53
+ # false (default) → hidden from the LLM and refused.
54
+ #
55
+ # Every field is optional: a nil value falls back to DEFAULTS.
56
+ Config = Struct.new(
57
+ :enabled, :base_path, :llm,
58
+ :api_key, :cors_origin, :max_sessions, :session_ttl_seconds,
59
+ :max_history_messages, :max_body_bytes, :rate_limit_per_minute,
60
+ :allow_mutating_tools,
61
+ keyword_init: true
62
+ ) do
25
63
  def self.from_env
26
- llm = LLMConfig.new.defaults!
27
64
  new(
28
- enabled: ENV.fetch('DEBUG_AGENT_ENABLED', 'true') == 'true',
65
+ enabled: env_bool('DEBUG_AGENT_ENABLED', true),
29
66
  base_path: ENV.fetch('DEBUG_AGENT_BASE_PATH', '/agent'),
30
- llm: llm
67
+ api_key: ENV.fetch('DEBUG_AGENT_API_KEY', ''),
68
+ cors_origin: ENV.fetch('DEBUG_AGENT_CORS_ORIGIN', '*'),
69
+ max_sessions: env_int('DEBUG_AGENT_MAX_SESSIONS', 200),
70
+ session_ttl_seconds: env_int('DEBUG_AGENT_SESSION_TTL_SECONDS', 3600),
71
+ max_history_messages: env_int('DEBUG_AGENT_MAX_HISTORY', 100),
72
+ max_body_bytes: env_int('DEBUG_AGENT_MAX_BODY_BYTES', 1_048_576),
73
+ rate_limit_per_minute: env_int('DEBUG_AGENT_RATE_LIMIT', 60),
74
+ allow_mutating_tools: env_bool('DEBUG_AGENT_ALLOW_MUTATING_TOOLS', false),
75
+ llm: LLMConfig.new.defaults!
31
76
  )
32
77
  end
78
+
79
+ # Integer env value; unset, malformed or negative values fall back to the
80
+ # default (0 is valid and means "unlimited" / "off").
81
+ def self.env_int(key, default)
82
+ raw = ENV[key]
83
+ return default if raw.nil? || raw.strip.empty?
84
+
85
+ n = Integer(raw.strip, 10)
86
+ n.negative? ? default : n
87
+ rescue ArgumentError
88
+ default
89
+ end
90
+
91
+ # Boolean env value (same spellings as Go's strconv.ParseBool); unset or
92
+ # unparseable values fall back to the default.
93
+ def self.env_bool(key, default)
94
+ raw = ENV[key]
95
+ return default if raw.nil? || raw.strip.empty?
96
+
97
+ case raw.strip.downcase
98
+ when 'true', '1', 't' then true
99
+ when 'false', '0', 'f' then false
100
+ else default
101
+ end
102
+ end
103
+
104
+ # Fields a caller leaves out (nil) get their default, so configs built
105
+ # before the hardening fields existed keep the default behaviour.
106
+ def initialize(*args, &block)
107
+ super
108
+ Config::DEFAULTS.each { |field, value| self[field] = value if self[field].nil? }
109
+ self.llm = LLMConfig.new.defaults! if self.llm.nil?
110
+ end
111
+
112
+ # The agent api key is a secret: it is never included in to_h / to_json /
113
+ # inspect output.
114
+ def to_h
115
+ members.each_with_object({}) do |field, hash|
116
+ hash[field] = self[field] unless field == :api_key
117
+ end
118
+ end
119
+
120
+ def to_json(*args)
121
+ to_h.to_json(*args)
122
+ end
123
+
124
+ def inspect
125
+ fields = to_h.map { |field, value| "#{field}=#{value.inspect}" }
126
+ "#<struct #{self.class.name} #{fields.join(', ')}>"
127
+ end
33
128
  end
129
+
130
+ Config::DEFAULTS = {
131
+ enabled: true,
132
+ base_path: '/agent',
133
+ api_key: '',
134
+ cors_origin: '*',
135
+ max_sessions: 200,
136
+ session_ttl_seconds: 3600,
137
+ max_history_messages: 100,
138
+ max_body_bytes: 1_048_576,
139
+ rate_limit_per_minute: 60,
140
+ allow_mutating_tools: false
141
+ }.freeze
34
142
  end
@@ -34,6 +34,8 @@ module DebugAgent
34
34
 
35
35
  def initialize(config = nil)
36
36
  @config = config || Config.from_env
37
+ DebugAgent.set_allow_mutating_tools(@config.allow_mutating_tools)
38
+ DebugAgent.warn_if_unauthenticated(@config)
37
39
  @llm = LLMClient.new(@config.llm)
38
40
  @tools = REGISTRY
39
41
 
@@ -64,11 +66,57 @@ module DebugAgent
64
66
  end
65
67
  end
66
68
 
69
+ # Number of live sessions (diagnostics / tests).
70
+ def session_count
71
+ @mutex.synchronize { @sessions.length }
72
+ end
73
+
67
74
  private
68
75
 
69
76
  def get_or_create_session(session_id)
77
+ session_id = 'default' if session_id.nil? || session_id.empty?
78
+
70
79
  @mutex.synchronize do
71
- @sessions[session_id] ||= ChatSession.new(session_id)
80
+ session = @sessions[session_id]
81
+ if session
82
+ if session_expired?(session)
83
+ # Idle beyond the TTL: drop the stale history and start over.
84
+ session = new_session(session_id)
85
+ @sessions[session_id] = session
86
+ end
87
+ return session
88
+ end
89
+
90
+ session = new_session(session_id)
91
+ @sessions[session_id] = session
92
+ evict_overflow_sessions
93
+ session
94
+ end
95
+ end
96
+
97
+ def new_session(session_id)
98
+ ChatSession.new(session_id, @config.max_history_messages)
99
+ end
100
+
101
+ def session_expired?(session)
102
+ ttl = @config.session_ttl_seconds
103
+ return false if ttl.nil? || ttl <= 0
104
+
105
+ Time.now - session.last_active_at > ttl
106
+ end
107
+
108
+ # Keeps the session table within max_sessions by dropping the
109
+ # least-recently-active sessions. 0 (or nil) disables the cap.
110
+ # Caller holds @mutex.
111
+ def evict_overflow_sessions
112
+ max = @config.max_sessions
113
+ return if max.nil? || max <= 0
114
+
115
+ while @sessions.length > max
116
+ oldest_id = @sessions.min_by { |_id, s| s.last_active_at }&.first
117
+ break if oldest_id.nil?
118
+
119
+ @sessions.delete(oldest_id)
72
120
  end
73
121
  end
74
122
 
@@ -159,4 +207,24 @@ module DebugAgent
159
207
  cb.on_complete
160
208
  end
161
209
  end
210
+
211
+ UNAUTHENTICATED_WARNING = '[debug-agent] WARNING: DEBUG_AGENT_API_KEY is not set - the agent UI and API ' \
212
+ 'are unauthenticated; anyone who can reach this port can drive the LLM and ' \
213
+ 'diagnostic tools (safe on localhost only).'.freeze
214
+
215
+ class << self
216
+ # Emits a one-line startup warning (stderr only) the first time an engine
217
+ # is created without an API key: anyone who can reach the port can then
218
+ # drive the LLM and every diagnostic tool. Does not change behaviour - only
219
+ # the operator can decide whether the port is reachable. Nothing is printed
220
+ # when a key is configured.
221
+ def warn_if_unauthenticated(config)
222
+ key = config.respond_to?(:api_key) ? config.api_key.to_s : ''
223
+ return unless key.empty?
224
+ return if @unauthenticated_warned
225
+
226
+ @unauthenticated_warned = true
227
+ warn UNAUTHENTICATED_WARNING
228
+ end
229
+ end
162
230
  end
@@ -154,7 +154,8 @@ module DebugAgent
154
154
 
155
155
  register_tool('clear_cache',
156
156
  'Clear a registered cache (destructive: removes all entries)',
157
- name: { type: 'string', description: 'Registered cache name (optional, defaults to first)', required: false }) do |name: nil|
157
+ name: { type: 'string', description: 'Registered cache name (optional, defaults to first)', required: false },
158
+ mutating: true) do |name: nil|
158
159
  if caches.empty?
159
160
  next { error: 'No caches registered. Call DebugAgent.register_cache(:name, cache).' }
160
161
  end
@@ -54,6 +54,10 @@ module DebugAgent
54
54
  port = app_port
55
55
  host = app_host
56
56
 
57
+ # The URL is built from a fixed host/port; the path is the only
58
+ # caller-controlled part, so it must stay an absolute path on this host
59
+ # (rejects "@evil.com/x", "//evil.com", absolute URLs, backslashes,
60
+ # control characters).
57
61
  uri = URI("http://#{host}:#{port}#{path}")
58
62
  http = Net::HTTP.new(uri.host, uri.port)
59
63
  http.read_timeout = 30
@@ -100,6 +104,24 @@ module DebugAgent
100
104
  rescue => e
101
105
  { error: "Request failed: #{e.message}", method: method, path: path }
102
106
  end
107
+
108
+ # True for an absolute path that cannot move the request to another host.
109
+ def valid_endpoint_path?(path)
110
+ path.is_a?(String) && path.start_with?('/') &&
111
+ !path.start_with?('//') && path !~ /[\\\s\x00-\x1f\x7f]/
112
+ end
113
+
114
+ def endpoint_path_error
115
+ { error: 'path must be relative and start with /' }
116
+ end
117
+
118
+ def mutating_method_refused?(method)
119
+ !DebugAgent.safe_http_method?(method) && !DebugAgent.mutating_tools_allowed?
120
+ end
121
+
122
+ def endpoint_disabled_error(method, path)
123
+ { error: "#{method} #{path} is #{DebugAgent::MUTATING_DISABLED}" }
124
+ end
103
125
  end
104
126
 
105
127
  register_tool('test_endpoint',
@@ -109,11 +131,15 @@ module DebugAgent
109
131
  path: { type: 'string', description: 'Request path (e.g. /api/orders)', required: true },
110
132
  headers: { type: 'object', description: 'Optional HTTP headers as key-value pairs (e.g. {"X-API-Key": "demo-key-12345"})', required: false },
111
133
  body: { type: 'string', description: 'Optional request body (JSON string for POST/PUT)', required: false }) do |method:, path:, headers: nil, body: nil|
112
- method_up = method.to_s.upcase
134
+ method_up = method.to_s.strip.upcase
135
+ method_up = 'GET' if method_up.empty?
113
136
  unless %w[GET POST PUT DELETE PATCH HEAD OPTIONS].include?(method_up)
114
137
  next { error: "Unsupported HTTP method: #{method}. Use GET, POST, PUT, DELETE, PATCH, HEAD, or OPTIONS." }
115
138
  end
116
139
 
140
+ next endpoint_path_error unless valid_endpoint_path?(path)
141
+ next endpoint_disabled_error(method_up, path) if mutating_method_refused?(method_up)
142
+
117
143
  result = perform_http_request(method_up, path, headers, body)
118
144
 
119
145
  if result[:error]
@@ -146,6 +172,14 @@ module DebugAgent
146
172
  next { method: method, path: '(missing)', error: 'Missing required field: path' }
147
173
  end
148
174
 
175
+ # Per-entry refusals: the remaining entries still run.
176
+ unless valid_endpoint_path?(path)
177
+ next { method: method, path: path, error: endpoint_path_error[:error], passed: false }
178
+ end
179
+ if mutating_method_refused?(method)
180
+ next { method: method, path: path, error: endpoint_disabled_error(method, path)[:error], passed: false }
181
+ end
182
+
149
183
  http_result = perform_http_request(method, path, headers, body)
150
184
 
151
185
  if http_result[:error]
@@ -115,8 +115,8 @@ module DebugAgent
115
115
  { error: e.message }
116
116
  end
117
117
 
118
- register_tool('force_gc',
119
- 'Trigger a full garbage collection (GC.start with full_mark) and show before/after comparison') do
118
+ mutating_tool('force_gc',
119
+ 'Trigger a full garbage collection (GC.start with full_mark) and show before/after comparison') do
120
120
  before_stats = GC.stat
121
121
  before_objects = ObjectSpace.count_objects.values.sum
122
122
 
@@ -140,7 +140,8 @@ module DebugAgent
140
140
  register_tool('set_log_level',
141
141
  "Dynamically change a registered logger's level",
142
142
  logger_name: { type: 'string', description: 'Registered logger name' },
143
- level: { type: 'string', description: 'One of: debug, info, warn, error, fatal' }) do |logger_name:, level:|
143
+ level: { type: 'string', description: 'One of: debug, info, warn, error, fatal' },
144
+ mutating: true) do |logger_name:, level:|
144
145
  logger = loggers[logger_name.to_s]
145
146
  next({ error: "No logger registered under '#{logger_name}'" }) unless logger
146
147
  next({ error: 'Logger does not respond to level=' }) unless logger.respond_to?(:level=)
@@ -29,7 +29,7 @@ module DebugAgent
29
29
  }
30
30
  end
31
31
 
32
- register_tool('trigger_gc', 'Trigger GC and show before/after comparison') do
32
+ register_tool('trigger_gc', 'Trigger GC and show before/after comparison', mutating: true) do
33
33
  before = ObjectSpace.count_objects.values.sum
34
34
  GC.start
35
35
  after = ObjectSpace.count_objects.values.sum
@@ -1,4 +1,6 @@
1
1
  require 'json'
2
+ require 'digest'
3
+ require 'uri'
2
4
  require_relative 'chat_page'
3
5
 
4
6
  module DebugAgent
@@ -66,12 +68,22 @@ module DebugAgent
66
68
  def initialize(app, config = nil)
67
69
  @app = app
68
70
  @config = config || Config.from_env
69
- @engine = DebugEngine.new(@config)
71
+ if @config.enabled
72
+ @engine = DebugEngine.new(@config)
73
+ @limiter = RateLimiter.new(@config.rate_limit_per_minute)
74
+ else
75
+ # Hardening: DEBUG_AGENT_ENABLED=false is enforced at mount time. Nothing
76
+ # is built and the wrapped app is served as if the agent were not mounted.
77
+ @engine = nil
78
+ @limiter = nil
79
+ end
70
80
  DebugAgent.app = app
71
81
  end
72
82
 
73
83
  def call(env)
74
- MiddlewareCore.call(env, @app, @engine, @config)
84
+ return MiddlewareCore.pass_through(env, @app) unless @engine
85
+
86
+ MiddlewareCore.call(env, @app, @engine, @config, @limiter)
75
87
  end
76
88
  end
77
89
 
@@ -79,44 +91,114 @@ module DebugAgent
79
91
  # Create a lambda-based middleware (for non-Sinatra Rack apps)
80
92
  def self.new(app = nil, config = nil)
81
93
  config_obj = config || Config.from_env
94
+ unless config_obj.enabled
95
+ # Disabled at mount time: pass through to the app as if not mounted.
96
+ return lambda { |env| MiddlewareCore.pass_through(env, app) }
97
+ end
98
+
82
99
  engine = DebugEngine.new(config_obj)
100
+ limiter = RateLimiter.new(config_obj.rate_limit_per_minute)
83
101
  DebugAgent.app = app
84
102
 
85
103
  lambda do |env|
86
- MiddlewareCore.call(env, app, engine, config_obj)
104
+ MiddlewareCore.call(env, app, engine, config_obj, limiter)
105
+ end
106
+ end
107
+
108
+ # Sinatra helper: `register DebugAgent::Middleware` mounts the Rack middleware
109
+ # (equivalent to `use DebugAgent::RackMiddleware`). A disabled agent is never mounted.
110
+ def self.registered(app)
111
+ return unless Config.from_env.enabled
112
+
113
+ app.use DebugAgent::RackMiddleware
114
+ end
115
+ end
116
+
117
+ # Fixed-window per-IP rate limiter (requests per minute) for POST /api/chat.
118
+ class RateLimiter
119
+ WINDOW_SECONDS = 60
120
+ MAX_TRACKED_IPS = 10_000
121
+
122
+ def initialize(limit)
123
+ @limit = limit.nil? ? 0 : limit
124
+ @mutex = Mutex.new
125
+ @hits = {}
126
+ end
127
+
128
+ def allow?(ip)
129
+ return true if @limit <= 0
130
+
131
+ now = Time.now
132
+ @mutex.synchronize do
133
+ # Bound memory: reset the table if an attacker sprays source addresses.
134
+ @hits = {} if @hits.length > MAX_TRACKED_IPS
135
+ window = @hits[ip]
136
+ if window.nil? || now - window[0] >= WINDOW_SECONDS
137
+ @hits[ip] = [now, 1]
138
+ true
139
+ else
140
+ window[1] += 1
141
+ window[1] <= @limit
142
+ end
87
143
  end
88
144
  end
89
145
  end
90
146
 
91
147
  # Shared routing logic used by both RackMiddleware class and Middleware lambda
92
148
  module MiddlewareCore
93
- CORS_HEADERS = {
94
- 'Access-Control-Allow-Origin' => '*',
95
- 'Access-Control-Allow-Methods' => 'GET, POST, OPTIONS',
96
- 'Access-Control-Allow-Headers' => 'Content-Type, Authorization',
97
- }.freeze
149
+ CORS_METHODS = 'GET, POST, OPTIONS'
150
+ CORS_ALLOW_HEADERS = 'Content-Type, Authorization, X-API-Key'
151
+
152
+ BodyResult = Struct.new(:status, :error, :body, keyword_init: true) do
153
+ def ok?
154
+ status.nil?
155
+ end
156
+ end
157
+
158
+ # Hardening, all controlled through Config (see config.rb):
159
+ # - enabled=false → the agent is not mounted (pass-through / 404).
160
+ # - api_key set → UI and /api/* require the key (Bearer / X-API-Key /
161
+ # ?api_key=); otherwise 401. With a key set, CORS is same-origin only
162
+ # unless cors_origin is configured explicitly.
163
+ # - max_body_bytes → oversized POST bodies answer 413, malformed JSON 400.
164
+ # - rate_limit_per_minute → POST /api/chat is limited per client IP (429).
165
+ def self.call(env, app, engine, config, limiter = nil)
166
+ base = config.base_path.to_s.sub(%r{/+\z}, '')
167
+ path = env['PATH_INFO'].to_s
168
+ method = env['REQUEST_METHOD'].to_s.upcase
169
+ return pass_through(env, app) unless agent_path?(path, base)
170
+
171
+ headers = cors_headers(config)
98
172
 
99
- def self.call(env, app, engine, config)
100
- path = env['PATH_INFO']
101
- method = env['REQUEST_METHOD']
102
- base = config.base_path
173
+ # CORS preflight for all agent routes. Never requires auth: browsers send
174
+ # no custom headers here. (204 carries no body and no Content-Length.)
175
+ return [204, headers, []] if method == 'OPTIONS'
103
176
 
104
- # CORS preflight for all agent routes
105
- if path.start_with?(base) && method == 'OPTIONS'
106
- return [204, CORS_HEADERS.merge('Content-Length' => '0'), []]
177
+ unless authorized?(env, config.api_key)
178
+ return json_response(401, { 'error' => 'unauthorized' }, headers)
107
179
  end
108
180
 
109
181
  # Chat UI
110
182
  if path == base || path == "#{base}/"
111
183
  if method == 'GET'
112
184
  html = ChatPage.render(base)
113
- return [200, { 'Content-Type' => 'text/html; charset=utf-8' }.merge(CORS_HEADERS), [html]]
185
+ return [200, { 'content-type' => 'text/html; charset=utf-8' }.merge(headers), [html]]
114
186
  end
115
187
  end
116
188
 
117
189
  # SSE streaming chat — real-time streaming via Rack response body
118
- if path == "#{base}/api/chat" && method == 'POST'
119
- body = JSON.parse(env['rack.input'].read)
190
+ if path == "#{base}/api/chat"
191
+ return json_response(405, { 'error' => 'method not allowed' }, headers) unless method == 'POST'
192
+
193
+ (limiter ||= RateLimiter.new(config.rate_limit_per_minute))
194
+ unless limiter.allow?(client_ip(env))
195
+ return json_response(429, { 'error' => 'rate limit exceeded, retry later' }, headers)
196
+ end
197
+
198
+ parsed = read_json_body(env, config.max_body_bytes)
199
+ return json_response(parsed.status, { 'error' => parsed.error }, headers) unless parsed.ok?
200
+
201
+ body = parsed.body
120
202
  message = body['message'] || ''
121
203
  session_id = body['sessionId'] || "session-#{Time.now.to_i}"
122
204
 
@@ -135,36 +217,191 @@ module DebugAgent
135
217
  streaming_body = cb.streaming_enum
136
218
 
137
219
  return [200, {
138
- 'Content-Type' => 'text/event-stream',
139
- 'Cache-Control' => 'no-cache',
140
- 'Connection' => 'keep-alive',
141
- }.merge(CORS_HEADERS), streaming_body]
220
+ 'content-type' => 'text/event-stream',
221
+ 'cache-control' => 'no-cache',
222
+ 'connection' => 'keep-alive',
223
+ }.merge(headers), streaming_body]
142
224
  end
143
225
 
144
226
  # Clear conversation
145
- if path == "#{base}/api/clear" && method == 'POST'
146
- body = JSON.parse(env['rack.input'].read)
147
- session_id = body['sessionId'] || ''
227
+ if path == "#{base}/api/clear"
228
+ return json_response(405, { 'error' => 'method not allowed' }, headers) unless method == 'POST'
229
+
230
+ parsed = read_json_body(env, config.max_body_bytes)
231
+ return json_response(parsed.status, { 'error' => parsed.error }, headers) unless parsed.ok?
232
+
233
+ session_id = parsed.body['sessionId'] || ''
148
234
  engine.clear_session(session_id) if session_id && !session_id.empty?
149
- return [200, { 'Content-Type' => 'application/json' }.merge(CORS_HEADERS), [JSON.generate({ status: 'cleared' })]]
235
+ return [200, { 'content-type' => 'application/json' }.merge(headers), [JSON.generate({ status: 'cleared' })]]
150
236
  end
151
237
 
152
238
  # Health check
153
239
  if path == "#{base}/api/health" && method == 'GET'
154
- return [200, { 'Content-Type' => 'application/json' }.merge(CORS_HEADERS), [JSON.generate({ status: 'ok', agent: 'ruby-debug-agent' })]]
240
+ return [200, { 'content-type' => 'application/json' }.merge(headers), [JSON.generate({ status: 'ok', agent: 'ruby-debug-agent' })]]
155
241
  end
156
242
 
157
243
  # List tools
158
244
  if path == "#{base}/api/tools" && method == 'GET'
159
- return [200, { 'Content-Type' => 'application/json' }.merge(CORS_HEADERS), [JSON.generate({ tools: engine.tools.all_schemas })]]
245
+ return [200, { 'content-type' => 'application/json' }.merge(headers), [JSON.generate({ tools: engine.tools.all_schemas })]]
160
246
  end
161
247
 
162
- # Pass through to the wrapped app
248
+ pass_through(env, app)
249
+ end
250
+
251
+ # Hand the request to the wrapped app as if the agent were not mounted.
252
+ def self.pass_through(env, app)
163
253
  if app
164
254
  app.call(env)
165
255
  else
166
- [404, { 'Content-Type' => 'text/plain' }, ['Not Found']]
256
+ [404, { 'content-type' => 'text/plain' }, ['Not Found']]
167
257
  end
168
258
  end
259
+
260
+ # Only the mount path itself and everything beneath it belong to the agent.
261
+ def self.agent_path?(path, base)
262
+ return true if base.empty?
263
+
264
+ path == base || path.start_with?("#{base}/")
265
+ end
266
+
267
+ # authorized? reports whether the request carries the configured API key.
268
+ # An empty configured key disables auth entirely.
269
+ def self.authorized?(env, api_key)
270
+ return true if api_key.nil? || api_key.empty?
271
+
272
+ presented = env['HTTP_X_API_KEY'].to_s
273
+ if presented.empty?
274
+ auth = env['HTTP_AUTHORIZATION'].to_s
275
+ presented = auth.delete_prefix('Bearer ').strip if auth.start_with?('Bearer ')
276
+ end
277
+ presented = query_param(env, 'api_key').to_s if presented.empty?
278
+ return false if presented.empty?
279
+
280
+ secure_compare(presented, api_key)
281
+ end
282
+
283
+ # Constant-time comparison. Both sides are hashed first so the compare runs
284
+ # over a fixed 32-byte length - a different-length key never bails out early.
285
+ # Uses Rack::Utils.secure_compare when rack is loadable, else a manual
286
+ # constant-time byte loop.
287
+ def self.secure_compare(presented, expected)
288
+ left = Digest::SHA256.digest(presented.to_s)
289
+ right = Digest::SHA256.digest(expected.to_s)
290
+ rack_compare = rack_secure_compare
291
+ return rack_compare.call(left, right) if rack_compare
292
+
293
+ constant_time_equal?(left, right)
294
+ end
295
+
296
+ # => Rack::Utils.secure_compare (when rack is loadable), else nil.
297
+ # Resolved lazily, once per thread; `false` caches "not available".
298
+ def self.rack_secure_compare
299
+ cached = Thread.current[:debug_agent_rack_compare]
300
+ return nil if cached == false
301
+ return cached unless cached.nil?
302
+
303
+ begin
304
+ require 'rack'
305
+ rack_compare = Rack::Utils.respond_to?(:secure_compare) ? Rack::Utils.method(:secure_compare) : false
306
+ rescue LoadError, StandardError
307
+ rack_compare = false
308
+ end
309
+ Thread.current[:debug_agent_rack_compare] = rack_compare
310
+ rack_compare == false ? nil : rack_compare
311
+ end
312
+
313
+ def self.constant_time_equal?(left, right)
314
+ a = left.to_s.unpack('C*')
315
+ b = right.to_s.unpack('C*')
316
+ result = a.length ^ b.length
317
+ [a.length, b.length].max.times { |i| result |= (a[i] || 0) ^ (b[i] || 0) }
318
+ result.zero?
319
+ end
320
+
321
+ # cors_headers applies the configured CORS policy. With auth enabled and the
322
+ # default wildcard origin, no CORS headers are emitted (same-origin only),
323
+ # because a wildcard origin must never be combined with a bearer-protected endpoint.
324
+ def self.cors_headers(config)
325
+ origin = config.cors_origin.to_s
326
+ origin = '*' if origin.empty?
327
+ return {} if origin == '*' && !config.api_key.to_s.empty?
328
+
329
+ headers = {
330
+ 'access-control-allow-origin' => origin,
331
+ 'access-control-allow-methods' => CORS_METHODS,
332
+ 'access-control-allow-headers' => CORS_ALLOW_HEADERS,
333
+ }
334
+ headers['vary'] = 'Origin' if origin != '*'
335
+ headers
336
+ end
337
+
338
+ # read_json_body reads a JSON object with the configured size limit.
339
+ # Returns a BodyResult carrying either the parsed body or the 413/400 to write.
340
+ def self.read_json_body(env, max_bytes)
341
+ raw, error = read_limited_body(env, max_bytes)
342
+ return BodyResult.new(status: 413, error: error) if raw.nil?
343
+
344
+ begin
345
+ body = JSON.parse(raw)
346
+ rescue JSON::ParserError, TypeError
347
+ return BodyResult.new(status: 400, error: 'invalid JSON body')
348
+ end
349
+ return BodyResult.new(status: 400, error: 'invalid JSON body') unless body.is_a?(Hash)
350
+
351
+ BodyResult.new(body: body)
352
+ end
353
+
354
+ def self.read_limited_body(env, max_bytes)
355
+ limited = !max_bytes.nil? && max_bytes.positive?
356
+ if limited
357
+ declared = env['CONTENT_LENGTH'].to_s
358
+ return [nil, 'request body too large'] if declared.match?(/\A\d+\z/) && declared.to_i > max_bytes
359
+ end
360
+
361
+ input = env['rack.input']
362
+ raw = if input.respond_to?(:read)
363
+ limited ? input.read(max_bytes + 1) : input.read
364
+ else
365
+ ''
366
+ end
367
+ raw = raw.to_s
368
+ return [nil, 'request body too large'] if limited && raw.bytesize > max_bytes
369
+
370
+ [raw, nil]
371
+ end
372
+
373
+ def self.query_param(env, name)
374
+ env['QUERY_STRING'].to_s.split('&').each do |pair|
375
+ key, value = pair.split('=', 2)
376
+ next if decode_component(key) != name
377
+
378
+ return decode_component(value.to_s)
379
+ end
380
+ nil
381
+ end
382
+
383
+ def self.decode_component(value)
384
+ URI.decode_www_form_component(value.to_s)
385
+ rescue ArgumentError
386
+ value.to_s
387
+ end
388
+
389
+ def self.client_ip(env)
390
+ forwarded = env['HTTP_X_FORWARDED_FOR'].to_s
391
+ return forwarded.split(',').first.strip unless forwarded.empty?
392
+
393
+ addr = env['REMOTE_ADDR'].to_s
394
+ if addr.start_with?('[')
395
+ addr[1, addr.index(']') - 1] || addr
396
+ elsif addr.count(':') == 1
397
+ addr.split(':').first
398
+ else
399
+ addr
400
+ end
401
+ end
402
+
403
+ def self.json_response(status, payload, extra_headers = {})
404
+ [status, { 'content-type' => 'application/json' }.merge(extra_headers), [JSON.generate(payload)]]
405
+ end
169
406
  end
170
407
  end
@@ -7,7 +7,12 @@ module DebugAgent
7
7
  end
8
8
  end
9
9
 
10
- ToolDefinition = Struct.new(:name, :description, :func, :params, keyword_init: true)
10
+ # ToolDefinition.mutating marks tools that change runtime state, affect
11
+ # business data, or call the host app with a non-safe HTTP method (see
12
+ # DebugAgent.safe_http_method?). Mutating tools are hidden from the LLM and
13
+ # from /api/tools and refused by ToolRegistry#execute unless
14
+ # DEBUG_AGENT_ALLOW_MUTATING_TOOLS=true.
15
+ ToolDefinition = Struct.new(:name, :description, :func, :params, :mutating, keyword_init: true)
11
16
 
12
17
  class ToolRegistry
13
18
  def initialize
@@ -22,14 +27,22 @@ module DebugAgent
22
27
  @tools[name]
23
28
  end
24
29
 
30
+ # Schemas for every tool the LLM may call. Mutating tools are omitted
31
+ # while they are disabled.
25
32
  def all_schemas
26
- @tools.values.map(&:to_schema)
33
+ visible_tools.map(&:to_schema)
27
34
  end
28
35
 
36
+ # Runs a registered tool by name. Mutating tools are refused while they
37
+ # are disabled; tool errors are returned as a structured {error: ...} hash.
29
38
  def execute(name, args)
30
39
  tool = @tools[name]
31
40
  return { error: "Unknown tool: #{name}" } unless tool
32
41
 
42
+ if tool.mutating && !DebugAgent.mutating_tools_allowed?
43
+ return { error: "#{name} is #{MUTATING_DISABLED}" }
44
+ end
45
+
33
46
  begin
34
47
  result = tool.func.call(**args)
35
48
  result
@@ -38,8 +51,21 @@ module DebugAgent
38
51
  end
39
52
  end
40
53
 
54
+ # Names of the tools the LLM may call (mutating tools omitted while off).
41
55
  def names
42
- @tools.keys
56
+ visible_tools.map(&:name)
57
+ end
58
+
59
+ def mutating?(name)
60
+ tool = @tools[name]
61
+ tool ? tool.mutating == true : false
62
+ end
63
+
64
+ private
65
+
66
+ def visible_tools
67
+ allowed = DebugAgent.mutating_tools_allowed?
68
+ @tools.values.reject { |tool| tool.mutating && !allowed }
43
69
  end
44
70
  end
45
71
 
@@ -74,22 +100,61 @@ module DebugAgent
74
100
  # Patch Struct to include schema method
75
101
  ToolDefinition.prepend(ToolDefinitionExt)
76
102
 
103
+ # Refusal message for a mutating tool while mutating tools are off.
104
+ MUTATING_DISABLED = 'disabled: this tool changes state and mutating tools are off ' \
105
+ '(set DEBUG_AGENT_ALLOW_MUTATING_TOOLS=true)'.freeze
106
+
77
107
  # Global registry singleton
78
108
  REGISTRY = ToolRegistry.new
79
109
 
110
+ SAFE_HTTP_METHODS = ['', 'GET', 'HEAD', 'OPTIONS'].freeze
111
+
80
112
  module ClassMethods
81
113
  def registry
82
114
  REGISTRY
83
115
  end
84
116
 
85
- def register_tool(name, description, params = {}, &block)
86
- tool = ToolDefinition.new(
117
+ # Registers a read-only tool. Pass mutating: true for a tool with side
118
+ # effects (or use mutating_tool): it is then hidden and refused until
119
+ # set_allow_mutating_tools(true) / DEBUG_AGENT_ALLOW_MUTATING_TOOLS=true.
120
+ #
121
+ # DebugAgent.register_tool('purge_tmp', 'Remove tmp files', mutating: true) { ... }
122
+ def register_tool(name, description, params = nil, mutating: false, **extra_params, &block)
123
+ REGISTRY.register(build_tool(name, description, params, extra_params, mutating, block))
124
+ end
125
+
126
+ # Registers a tool with side effects (GC, log level, cache clears,
127
+ # non-safe HTTP to the host app) - see ToolDefinition.mutating.
128
+ def mutating_tool(name, description, params = nil, **extra_params, &block)
129
+ REGISTRY.register(build_tool(name, description, params, extra_params, true, block))
130
+ end
131
+
132
+ # Enables or disables mutating tools for the global registry.
133
+ def set_allow_mutating_tools(allowed)
134
+ @allow_mutating_tools = allowed ? true : false
135
+ end
136
+
137
+ # Whether mutating tools are currently enabled (default: false).
138
+ def mutating_tools_allowed?
139
+ @allow_mutating_tools == true
140
+ end
141
+
142
+ # Whether an HTTP method is read-only (GET/HEAD/OPTIONS; empty = GET).
143
+ def safe_http_method?(method)
144
+ SAFE_HTTP_METHODS.include?(method.to_s.strip.upcase)
145
+ end
146
+
147
+ private
148
+
149
+ def build_tool(name, description, params, extra_params, mutating, block)
150
+ params = (params || {}).merge(extra_params || {})
151
+ ToolDefinition.new(
87
152
  name: name,
88
153
  description: description,
89
154
  func: block,
90
- params: params
155
+ params: params,
156
+ mutating: mutating ? true : false
91
157
  )
92
- REGISTRY.register(tool)
93
158
  end
94
159
  end
95
160
 
@@ -1,3 +1,3 @@
1
1
  module DebugAgent
2
- VERSION = '0.7.1'.freeze
2
+ VERSION = '0.8.0'.freeze
3
3
  end
data/lib/debug_agent.rb CHANGED
@@ -50,15 +50,6 @@ require_relative 'debug_agent/inspectors/service_registry'
50
50
  module DebugAgent
51
51
  class Error < StandardError; end
52
52
 
53
- # ggcode promotional message — shown once on first require
54
- unless defined?(@_ggcode_banner_shown)
55
- @_ggcode_banner_shown = true
56
- puts ""
57
- puts " This package was built with ggcode — an AI coding assistant."
58
- puts " https://github.com/topcheer/ggcode"
59
- puts ""
60
- end
61
-
62
53
  # Process start time for uptime tracking
63
54
  PROCESS_START_TIME = Time.now
64
55
 
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: debug-agent
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.7.1
4
+ version: 0.8.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - ggcode
@@ -226,7 +226,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
226
226
  - !ruby/object:Gem::Version
227
227
  version: '0'
228
228
  requirements: []
229
- rubygems_version: 4.0.10
229
+ rubygems_version: 4.0.20
230
230
  specification_version: 4
231
231
  summary: AI-powered runtime debugging agent for Ruby applications
232
232
  test_files: []