debug-agent-py 0.7.0__tar.gz → 0.7.1__tar.gz

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 (60) hide show
  1. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/PKG-INFO +1 -1
  2. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/pyproject.toml +1 -1
  3. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/__init__.py +8 -2
  4. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/leak_detector_inspector.py +4 -0
  5. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/snapshot_inspector.py +4 -0
  6. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/llm_client.py +4 -1
  7. debug_agent_py-0.7.1/src/debug_agent/middleware.py +351 -0
  8. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/system_prompt_builder.py +85 -8
  9. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent_py.egg-info/PKG-INFO +1 -1
  10. debug_agent_py-0.7.0/src/debug_agent/middleware.py +0 -199
  11. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/README.md +0 -0
  12. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/setup.cfg +0 -0
  13. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/chat_session.py +0 -0
  14. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/config.py +0 -0
  15. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/context_compressor.py +0 -0
  16. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/engine.py +0 -0
  17. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/__init__.py +0 -0
  18. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/async_tasks.py +0 -0
  19. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/build_info_inspector.py +0 -0
  20. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/cache_inspector.py +0 -0
  21. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/celery.py +0 -0
  22. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/config_inspector.py +0 -0
  23. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/cpu_profile_inspector.py +0 -0
  24. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/database.py +0 -0
  25. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/django.py +0 -0
  26. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/endpoint_test_inspector.py +0 -0
  27. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/error_tracking.py +0 -0
  28. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/fastapi_ext.py +0 -0
  29. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/fd_inspector.py +0 -0
  30. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/feature_flag_inspector.py +0 -0
  31. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/flask_ext.py +0 -0
  32. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/framework.py +0 -0
  33. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/health_inspector.py +0 -0
  34. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/http_client_inspector.py +0 -0
  35. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/http_tracker.py +0 -0
  36. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/jinja2.py +0 -0
  37. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/locks_inspector.py +0 -0
  38. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/logging_inspector.py +0 -0
  39. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/memory.py +0 -0
  40. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/metrics_inspector.py +0 -0
  41. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/migration_inspector.py +0 -0
  42. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/modules.py +0 -0
  43. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/pool_inspector.py +0 -0
  44. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/redis.py +0 -0
  45. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/runtime.py +0 -0
  46. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/scheduler_inspector.py +0 -0
  47. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/security_inspector.py +0 -0
  48. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/service_registry_inspector.py +0 -0
  49. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/signals.py +0 -0
  50. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/system.py +0 -0
  51. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/threads.py +0 -0
  52. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/warnings_inspector.py +0 -0
  53. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/websocket_inspector.py +0 -0
  54. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/tool_registry.py +0 -0
  55. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/web/__init__.py +0 -0
  56. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent/web/chat_page.py +0 -0
  57. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent_py.egg-info/SOURCES.txt +0 -0
  58. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent_py.egg-info/dependency_links.txt +0 -0
  59. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent_py.egg-info/requires.txt +0 -0
  60. {debug_agent_py-0.7.0 → debug_agent_py-0.7.1}/src/debug_agent_py.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: debug-agent-py
3
- Version: 0.7.0
3
+ Version: 0.7.1
4
4
  Summary: AI-powered runtime debugging agent for Python web applications
5
5
  Author-email: ggcode <noreply@ggcode.dev>
6
6
  License: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "debug-agent-py"
7
- version = "0.7.0"
7
+ version = "0.7.1"
8
8
  description = "AI-powered runtime debugging agent for Python web applications"
9
9
  readme = "README.md"
10
10
  license = {text = "MIT"}
@@ -13,6 +13,13 @@ if not hasattr(_sys, '_debug_agent_ggcode_shown'):
13
13
  _print(' https://github.com/topcheer/ggcode')
14
14
  _print('')
15
15
 
16
+ # Read version from package metadata (falls back to pyproject.toml value)
17
+ try:
18
+ from importlib.metadata import version as _pkg_version
19
+ __version__ = _pkg_version("debug-agent-py")
20
+ except Exception:
21
+ __version__ = "0.0.0"
22
+
16
23
  from debug_agent.config import AgentConfig
17
24
  from debug_agent.tool_registry import debug_tool, ToolParam, registry
18
25
  from debug_agent.engine import DebugEngine, ChatCallback
@@ -21,11 +28,10 @@ from debug_agent.system_prompt_builder import SystemPromptBuilder
21
28
  from debug_agent.context_compressor import ContextCompressor, CompressionResult
22
29
  from debug_agent.llm_client import LLMClient, StreamHandler
23
30
 
24
- __version__ = "0.1.0"
25
31
  __all__ = [
26
32
  "AgentConfig", "debug_tool", "ToolParam", "registry", "DebugEngine", "ChatCallback",
27
33
  "ChatSession", "SystemPromptBuilder", "ContextCompressor", "CompressionResult",
28
- "LLMClient", "StreamHandler", "setup",
34
+ "LLMClient", "StreamHandler", "setup", "__version__",
29
35
  ]
30
36
 
31
37
 
@@ -60,6 +60,10 @@ def take_heap_snapshot() -> dict:
60
60
  snap_id = _next_id
61
61
  _next_id += 1
62
62
  summary = _snapshot_summary(snap)
63
+ # Enforce max 50 heap snapshots to prevent unbounded memory growth
64
+ if len(_snapshots) >= 50:
65
+ oldest = min(_snapshots.keys())
66
+ del _snapshots[oldest]
63
67
  _snapshots[snap_id] = {
64
68
  "id": snap_id,
65
69
  "snapshot": snap,
@@ -210,6 +210,10 @@ def take_snapshot() -> dict:
210
210
  snap_id = _next_id
211
211
  _next_id += 1
212
212
 
213
+ # Enforce max 100 snapshots to prevent unbounded growth
214
+ if len(_snapshots) >= 100:
215
+ oldest = min(_snapshots.keys())
216
+ del _snapshots[oldest]
213
217
  _snapshots[snap_id] = {
214
218
  "id": snap_id,
215
219
  "timestamp": time.time(),
@@ -28,7 +28,10 @@ class LLMClient:
28
28
 
29
29
  def __init__(self, config: LLMConfig):
30
30
  self.cfg = config
31
- self.client = httpx.Client(timeout=config.timeout_seconds)
31
+ self.client = httpx.Client(
32
+ timeout=config.timeout_seconds,
33
+ limits=httpx.Limits(max_connections=8, max_keepalive_connections=4),
34
+ )
32
35
 
33
36
  # ==================== Non-Streaming ====================
34
37
 
@@ -0,0 +1,351 @@
1
+ """Framework integration: FastAPI, Starlette, Flask, Django middleware.
2
+
3
+ SSE events (Spring-aligned):
4
+ content, tool_start, tool_result, done, error, context_compressed
5
+
6
+ Endpoints:
7
+ GET /agent — Chat UI
8
+ POST /agent/api/chat — SSE streaming chat
9
+ POST /agent/api/clear — Clear conversation
10
+ GET /agent/api/health — Health check
11
+ GET /agent/api/tools — List available tools
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import queue
18
+ import threading
19
+ from typing import Any, Generator
20
+
21
+ from debug_agent.config import AgentConfig
22
+ from debug_agent.engine import DebugEngine, ChatCallback
23
+ from debug_agent.web.chat_page import render as render_chat_page
24
+
25
+ import logging
26
+ _logger = logging.getLogger(__name__)
27
+
28
+ # ==================== CORS Helper ====================
29
+
30
+ CORS_HEADERS = {
31
+ "Access-Control-Allow-Origin": "*",
32
+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
33
+ "Access-Control-Allow-Headers": "Content-Type, Authorization",
34
+ }
35
+
36
+
37
+ # ==================== Real-time SSE Callback ====================
38
+
39
+ class StreamingSseCallback(ChatCallback):
40
+ """Bridges engine callbacks to a thread-safe queue for real-time SSE streaming.
41
+
42
+ Unlike the old SseCallback that buffered all events, this pushes each event
43
+ to a queue immediately, allowing the SSE generator to yield in real-time.
44
+ """
45
+
46
+ _SENTINEL = object()
47
+
48
+ def __init__(self):
49
+ self._queue: queue.Queue = queue.Queue()
50
+
51
+ def on_content(self, chunk: str):
52
+ self._queue.put(("content", json.dumps(chunk)))
53
+
54
+ def on_tool_start(self, tool_name: str, args: str):
55
+ self._queue.put(("tool_start", tool_name))
56
+
57
+ def on_tool_result(self, tool_name: str, result: str):
58
+ self._queue.put(("tool_result", f"{tool_name}: {result}"))
59
+
60
+ def on_complete(self):
61
+ self._queue.put(("done", ""))
62
+ self._queue.put(self._SENTINEL)
63
+
64
+ def on_error(self, message: str):
65
+ self._queue.put(("error", message))
66
+ self._queue.put(self._SENTINEL)
67
+
68
+ def on_context_compressed(self, original_tokens: int, compressed_tokens: int, removed_rounds: int):
69
+ info = json.dumps({"originalTokens": original_tokens, "compressedTokens": compressed_tokens, "removedRounds": removed_rounds})
70
+ self._queue.put(("context_compressed", info))
71
+
72
+ def stream(self) -> Generator[str, None, None]:
73
+ """Generator that yields SSE lines in real-time as events arrive."""
74
+ while True:
75
+ item = self._queue.get(timeout=300) # 5-min timeout
76
+ if item is self._SENTINEL:
77
+ break
78
+ event_type, data = item
79
+ yield f"event: {event_type}\ndata: {data}\n\n"
80
+
81
+
82
+ # ==================== FastAPI ====================
83
+
84
+ def create_fastapi_router(config: AgentConfig | None = None):
85
+ """Create a FastAPI APIRouter with all debug agent endpoints."""
86
+ from fastapi import APIRouter, Request
87
+ from fastapi.responses import HTMLResponse, StreamingResponse, JSONResponse
88
+ from debug_agent import inspectors # noqa: F401
89
+
90
+ cfg = config or AgentConfig.from_env()
91
+ engine = DebugEngine(cfg)
92
+ router = APIRouter(prefix=cfg.base_path, tags=["Debug Agent"])
93
+
94
+ @router.options("/{path:path}")
95
+ async def cors_preflight(path: str):
96
+ return JSONResponse({}, headers=CORS_HEADERS)
97
+
98
+ @router.get("", response_class=HTMLResponse)
99
+ async def chat_page():
100
+ return HTMLResponse(render_chat_page(cfg.base_path), headers=CORS_HEADERS)
101
+
102
+ @router.get("/")
103
+ async def chat_page_slash():
104
+ return HTMLResponse(render_chat_page(cfg.base_path), headers=CORS_HEADERS)
105
+
106
+ @router.post("/api/chat")
107
+ async def chat(request: Request):
108
+ body = await request.json()
109
+ message = body.get("message", "")
110
+ session_id = body.get("sessionId", f"session-{id(request)}")
111
+
112
+ cb = StreamingSseCallback()
113
+
114
+ def run_engine():
115
+ try:
116
+ engine.chat(message, session_id, cb)
117
+ except Exception as e:
118
+ _logger.error("Engine error: %s", e)
119
+ cb.on_error(str(e))
120
+
121
+ worker = threading.Thread(target=run_engine, daemon=True)
122
+ worker.start()
123
+
124
+ return StreamingResponse(cb.stream(), media_type="text/event-stream", headers=CORS_HEADERS)
125
+
126
+ @router.post("/api/clear")
127
+ async def clear_conversation(request: Request):
128
+ body = await request.json()
129
+ session_id = body.get("sessionId", "")
130
+ if session_id:
131
+ engine.clear_session(session_id)
132
+ return JSONResponse({"status": "cleared"}, headers=CORS_HEADERS)
133
+
134
+ @router.get("/api/health")
135
+ async def health():
136
+ return JSONResponse({"status": "ok", "agent": "python-debug-agent"}, headers=CORS_HEADERS)
137
+
138
+ @router.get("/api/tools")
139
+ async def list_tools():
140
+ return JSONResponse({"tools": engine.tools.all_schemas()}, headers=CORS_HEADERS)
141
+
142
+ return router
143
+
144
+
145
+ # ==================== Starlette ====================
146
+
147
+ def create_starlette_app(config: AgentConfig | None = None):
148
+ from starlette.applications import Starlette
149
+ from starlette.responses import HTMLResponse, StreamingResponse, JSONResponse
150
+ from starlette.routing import Route
151
+ from debug_agent import inspectors # noqa: F401
152
+
153
+ cfg = config or AgentConfig.from_env()
154
+ engine = DebugEngine(cfg)
155
+
156
+ async def chat_page(request):
157
+ return HTMLResponse(render_chat_page(cfg.base_path), headers=CORS_HEADERS)
158
+
159
+ async def chat(request):
160
+ body = await request.json()
161
+ message = body.get("message", "")
162
+ session_id = body.get("sessionId", f"session-{id(request)}")
163
+
164
+ cb = StreamingSseCallback()
165
+
166
+ def run_engine():
167
+ try:
168
+ engine.chat(message, session_id, cb)
169
+ except Exception as e:
170
+ _logger.error("Engine error: %s", e)
171
+ cb.on_error(str(e))
172
+
173
+ worker = threading.Thread(target=run_engine, daemon=True)
174
+ worker.start()
175
+
176
+ return StreamingResponse(cb.stream(), media_type="text/event-stream", headers=CORS_HEADERS)
177
+
178
+ async def clear(request):
179
+ body = await request.json()
180
+ session_id = body.get("sessionId", "")
181
+ if session_id:
182
+ engine.clear_session(session_id)
183
+ return JSONResponse({"status": "cleared"}, headers=CORS_HEADERS)
184
+
185
+ async def health(request):
186
+ return JSONResponse({"status": "ok", "agent": "python-debug-agent"}, headers=CORS_HEADERS)
187
+
188
+ async def tools(request):
189
+ return JSONResponse({"tools": engine.tools.all_schemas()}, headers=CORS_HEADERS)
190
+
191
+ async def cors_options(request):
192
+ return JSONResponse({}, headers=CORS_HEADERS)
193
+
194
+ routes = [
195
+ Route("/", chat_page),
196
+ Route("/api/chat", chat, methods=["POST"]),
197
+ Route("/api/clear", clear, methods=["POST"]),
198
+ Route("/api/health", health),
199
+ Route("/api/tools", tools),
200
+ Route("/{path:path}", cors_options, methods=["OPTIONS"]),
201
+ ]
202
+ return Starlette(routes=routes)
203
+
204
+
205
+ # ==================== Flask ====================
206
+
207
+ def create_flask_blueprint(config: AgentConfig | None = None):
208
+ from flask import Blueprint, Response, request, jsonify
209
+ from debug_agent import inspectors # noqa: F401
210
+
211
+ cfg = config or AgentConfig.from_env()
212
+ engine = DebugEngine(cfg)
213
+
214
+ bp = Blueprint("debug_agent", __name__, url_prefix=cfg.base_path)
215
+
216
+ @bp.after_request
217
+ def add_cors_headers(response):
218
+ response.headers["Access-Control-Allow-Origin"] = "*"
219
+ response.headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS"
220
+ response.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization"
221
+ return response
222
+
223
+ @bp.route("", methods=["GET", "OPTIONS"])
224
+ @bp.route("/", methods=["GET", "OPTIONS"])
225
+ def chat_page():
226
+ if request.method == "OPTIONS":
227
+ return "", 204
228
+ return render_chat_page(cfg.base_path)
229
+
230
+ @bp.route("/api/chat", methods=["POST", "OPTIONS"])
231
+ def chat():
232
+ if request.method == "OPTIONS":
233
+ return "", 204
234
+
235
+ message = request.json.get("message", "")
236
+ session_id = request.json.get("sessionId", f"session-{id(request)}")
237
+
238
+ cb = StreamingSseCallback()
239
+
240
+ def run_engine():
241
+ try:
242
+ engine.chat(message, session_id, cb)
243
+ except Exception as e:
244
+ _logger.error("Engine error: %s", e)
245
+ cb.on_error(str(e))
246
+
247
+ worker = threading.Thread(target=run_engine, daemon=True)
248
+ worker.start()
249
+
250
+ return Response(cb.stream(), mimetype="text/event-stream",
251
+ headers={"Cache-Control": "no-cache", "Connection": "keep-alive"})
252
+
253
+ @bp.route("/api/clear", methods=["POST", "OPTIONS"])
254
+ def clear():
255
+ if request.method == "OPTIONS":
256
+ return "", 204
257
+ session_id = request.json.get("sessionId", "")
258
+ if session_id:
259
+ engine.clear_session(session_id)
260
+ return jsonify({"status": "cleared"})
261
+
262
+ @bp.route("/api/health", methods=["GET"])
263
+ def health():
264
+ return jsonify({"status": "ok", "agent": "python-debug-agent"})
265
+
266
+ @bp.route("/api/tools", methods=["GET"])
267
+ def tools():
268
+ return jsonify({"tools": engine.tools.all_schemas()})
269
+
270
+ return bp
271
+
272
+
273
+ # ==================== Django ====================
274
+
275
+ def create_django_urls(config: AgentConfig | None = None):
276
+ """Return a list of URL patterns for Django integration.
277
+
278
+ Usage in urls.py:
279
+ from debug_agent.middleware import create_django_urls
280
+ urlpatterns += create_django_urls()
281
+ """
282
+ from django.http import HttpResponse, JsonResponse, StreamingHttpResponse
283
+ from django.urls import path
284
+ from django.views.decorators.csrf import csrf_exempt
285
+ import json as _json
286
+ from debug_agent import inspectors # noqa: F401
287
+
288
+ cfg = config or AgentConfig.from_env()
289
+ engine = DebugEngine(cfg)
290
+ base = cfg.base_path.strip("/")
291
+
292
+ def _cors(response):
293
+ response["Access-Control-Allow-Origin"] = "*"
294
+ response["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS"
295
+ response["Access-Control-Allow-Headers"] = "Content-Type, Authorization"
296
+ return response
297
+
298
+ @csrf_exempt
299
+ def chat_page(request):
300
+ if request.method == "OPTIONS":
301
+ return _cors(HttpResponse(status=204))
302
+ return _cors(HttpResponse(render_chat_page(cfg.base_path)))
303
+
304
+ @csrf_exempt
305
+ def chat(request):
306
+ if request.method == "OPTIONS":
307
+ return _cors(HttpResponse(status=204))
308
+ body = _json.loads(request.body or b"{}")
309
+ message = body.get("message", "")
310
+ session_id = body.get("sessionId", f"session-{id(request)}")
311
+
312
+ cb = StreamingSseCallback()
313
+
314
+ def run_engine():
315
+ try:
316
+ engine.chat(message, session_id, cb)
317
+ except Exception as e:
318
+ _logger.error("Engine error: %s", e)
319
+ cb.on_error(str(e))
320
+
321
+ worker = threading.Thread(target=run_engine, daemon=True)
322
+ worker.start()
323
+
324
+ response = StreamingHttpResponse(cb.stream(), content_type="text/event-stream")
325
+ return _cors(response)
326
+
327
+ @csrf_exempt
328
+ def clear(request):
329
+ if request.method == "OPTIONS":
330
+ return _cors(HttpResponse(status=204))
331
+ body = _json.loads(request.body or b"{}")
332
+ session_id = body.get("sessionId", "")
333
+ if session_id:
334
+ engine.clear_session(session_id)
335
+ return _cors(JsonResponse({"status": "cleared"}))
336
+
337
+ @csrf_exempt
338
+ def health(request):
339
+ return _cors(JsonResponse({"status": "ok", "agent": "python-debug-agent"}))
340
+
341
+ @csrf_exempt
342
+ def tools(request):
343
+ return _cors(JsonResponse({"tools": engine.tools.all_schemas()}, json_dumps_params={"default": str}))
344
+
345
+ return [
346
+ path(f"{base}/", chat_page),
347
+ path(f"{base}/api/chat", chat),
348
+ path(f"{base}/api/clear", clear),
349
+ path(f"{base}/api/health", health),
350
+ path(f"{base}/api/tools", tools),
351
+ ]
@@ -5,34 +5,111 @@ from __future__ import annotations
5
5
  from debug_agent.tool_registry import registry
6
6
 
7
7
  CATEGORY_MAP = {
8
+ # Memory & GC
8
9
  "heap": "Memory & GC",
9
10
  "gc": "Memory & GC",
10
11
  "memory": "Memory & GC",
11
12
  "tracemalloc": "Memory & GC",
12
13
  "object_count": "Memory & GC",
13
14
  "ref_cycle": "Memory & GC",
15
+ "leak": "Memory & GC",
16
+ "snapshot": "Memory & Snapshots",
17
+ "compare": "Memory & Snapshots",
18
+ # Process & Runtime
14
19
  "process": "Process Info",
15
20
  "runtime": "Runtime Info",
16
- "thread": "Threads",
17
21
  "system": "System Info",
18
22
  "cpu": "System Info",
19
23
  "disk": "System Info",
20
24
  "uptime": "System Info",
25
+ "pid": "Process Info",
26
+ # Threads & Locks
27
+ "thread": "Threads & Locks",
28
+ "lock": "Threads & Locks",
29
+ "deadlock": "Threads & Locks",
30
+ "contention": "Threads & Locks",
31
+ "async": "Async Tasks",
32
+ "event_loop": "Async Tasks",
33
+ # Framework
21
34
  "routes": "Framework",
22
35
  "middleware": "Framework",
36
+ "framework": "Framework",
37
+ "flask": "Framework",
38
+ "django": "Framework",
39
+ "fastapi": "Framework",
40
+ "signals": "Framework",
41
+ # HTTP
23
42
  "recent": "HTTP Requests",
24
43
  "slow": "HTTP Requests",
25
- "error": "HTTP Requests",
26
44
  "request": "HTTP Requests",
45
+ "http": "HTTP Requests",
46
+ "outbound": "HTTP Requests",
47
+ # Database
48
+ "sqlalchemy": "Database",
49
+ "db": "Database",
50
+ "migration": "Database Migration",
51
+ "pending": "Database Migration",
52
+ # Modules & Dependencies
27
53
  "module": "Modules",
28
54
  "import": "Modules",
29
- "environment": "Environment & Config",
30
- "installed": "Dependencies",
31
- "sqlalchemy": "Database",
32
- "db_": "Database",
33
- "async": "Async Tasks",
34
- "event_loop": "Async Tasks",
35
55
  "package": "Dependencies",
56
+ "installed": "Dependencies",
57
+ "environment": "Environment & Config",
58
+ # Configuration
59
+ "config": "Configuration",
60
+ "env": "Configuration",
61
+ # Cache
62
+ "cache": "Cache",
63
+ # Health & Security
64
+ "health": "Health Checks",
65
+ "auth": "Security",
66
+ "cors": "Security",
67
+ # Error Tracking
68
+ "error": "Error Tracking",
69
+ "warning": "Error Tracking",
70
+ "exception": "Error Tracking",
71
+ # WebSocket
72
+ "ws": "WebSocket",
73
+ "websocket": "WebSocket",
74
+ # Profiling
75
+ "start": "Profiling",
76
+ "stop": "Profiling",
77
+ "top": "Profiling",
78
+ "profile": "Profiling",
79
+ # Feature Flags
80
+ "feature": "Feature Flags",
81
+ "flag": "Feature Flags",
82
+ "evaluate": "Feature Flags",
83
+ # Endpoint Testing
84
+ "test": "Endpoint Testing",
85
+ "batch": "Endpoint Testing",
86
+ "endpoint": "Endpoint Testing",
87
+ "coverage": "Endpoint Testing",
88
+ # Connection Pool
89
+ "pool": "Connection Pool",
90
+ "connection": "Connection Pool",
91
+ # File Descriptors
92
+ "fd": "File Descriptors",
93
+ "handle": "File Descriptors",
94
+ # Metrics
95
+ "metric": "Metrics",
96
+ "counter": "Metrics",
97
+ # Build & Deployment
98
+ "build": "Build & Deployment",
99
+ "deployment": "Build & Deployment",
100
+ "version": "Build & Deployment",
101
+ # Service Registry
102
+ "registered": "Service Registry",
103
+ "service": "Service Registry",
104
+ # Celery / Queue
105
+ "celery": "Job Queue",
106
+ "queue": "Job Queue",
107
+ "task": "Async Tasks",
108
+ "job": "Job Queue",
109
+ # Redis
110
+ "redis": "Redis",
111
+ # Logging
112
+ "log": "Logging",
36
113
  }
37
114
 
38
115
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: debug-agent-py
3
- Version: 0.7.0
3
+ Version: 0.7.1
4
4
  Summary: AI-powered runtime debugging agent for Python web applications
5
5
  Author-email: ggcode <noreply@ggcode.dev>
6
6
  License: MIT
@@ -1,199 +0,0 @@
1
- """Framework integration: FastAPI, Starlette, Flask middleware.
2
-
3
- SSE events (Spring-aligned):
4
- content, tool_start, tool_result, done, error, context_compressed
5
-
6
- Endpoints:
7
- GET /agent — Chat UI
8
- POST /agent/api/chat — SSE streaming chat
9
- POST /agent/api/clear — Clear conversation
10
- GET /agent/api/health — Health check
11
- GET /agent/api/tools — List available tools
12
- """
13
-
14
- from __future__ import annotations
15
-
16
- import json
17
- from typing import Any
18
-
19
- from debug_agent.config import AgentConfig
20
- from debug_agent.engine import DebugEngine, ChatCallback
21
- from debug_agent.web.chat_page import render as render_chat_page
22
-
23
-
24
- # ==================== SSE Callback ====================
25
-
26
- class SseCallback(ChatCallback):
27
- """Bridges engine callbacks to SSE event lines."""
28
-
29
- def __init__(self):
30
- self.events: list[tuple[str, str]] = []
31
-
32
- def on_content(self, chunk: str):
33
- self.events.append(("content", json.dumps(chunk)))
34
-
35
- def on_tool_start(self, tool_name: str, args: str):
36
- self.events.append(("tool_start", tool_name))
37
-
38
- def on_tool_result(self, tool_name: str, result: str):
39
- self.events.append(("tool_result", f"{tool_name}: {result}"))
40
-
41
- def on_complete(self):
42
- self.events.append(("done", ""))
43
-
44
- def on_error(self, message: str):
45
- self.events.append(("error", message))
46
-
47
- def on_context_compressed(self, original_tokens: int, compressed_tokens: int, removed_rounds: int):
48
- info = json.dumps({"originalTokens": original_tokens, "compressedTokens": compressed_tokens, "removedRounds": removed_rounds})
49
- self.events.append(("context_compressed", info))
50
-
51
-
52
- # ==================== FastAPI ====================
53
-
54
- def create_fastapi_router(config: AgentConfig | None = None):
55
- """Create a FastAPI APIRouter with all debug agent endpoints."""
56
- from fastapi import APIRouter, Request
57
- from fastapi.responses import HTMLResponse, StreamingResponse
58
- from debug_agent import inspectors # noqa: F401
59
-
60
- cfg = config or AgentConfig.from_env()
61
- engine = DebugEngine(cfg)
62
- router = APIRouter(prefix=cfg.base_path, tags=["Debug Agent"])
63
-
64
- @router.get("", response_class=HTMLResponse)
65
- async def chat_page():
66
- return render_chat_page(cfg.base_path)
67
-
68
- @router.get("/")
69
- async def chat_page_slash():
70
- return render_chat_page(cfg.base_path)
71
-
72
- @router.post("/api/chat")
73
- async def chat(request: Request):
74
- body = await request.json()
75
- message = body.get("message", "")
76
- session_id = body.get("sessionId", f"session-{id(request)}")
77
-
78
- def event_stream():
79
- cb = SseCallback()
80
- engine.chat(message, session_id, cb)
81
- for event_type, data in cb.events:
82
- yield f"event: {event_type}\ndata: {data}\n\n"
83
-
84
- return StreamingResponse(event_stream(), media_type="text/event-stream")
85
-
86
- @router.post("/api/clear")
87
- async def clear_conversation(request: Request):
88
- body = await request.json()
89
- session_id = body.get("sessionId", "")
90
- if session_id:
91
- engine.clear_session(session_id)
92
- return {"status": "cleared"}
93
-
94
- @router.get("/api/health")
95
- async def health():
96
- return {"status": "ok", "agent": "python-debug-agent"}
97
-
98
- @router.get("/api/tools")
99
- async def list_tools():
100
- return {"tools": engine.tools.all_schemas()}
101
-
102
- return router
103
-
104
-
105
- # ==================== Starlette ====================
106
-
107
- def create_starlette_app(config: AgentConfig | None = None):
108
- from starlette.applications import Starlette
109
- from starlette.responses import HTMLResponse, StreamingResponse, JSONResponse
110
- from starlette.routing import Route
111
- from debug_agent import inspectors # noqa: F401
112
-
113
- cfg = config or AgentConfig.from_env()
114
- engine = DebugEngine(cfg)
115
-
116
- async def chat_page(request):
117
- return HTMLResponse(render_chat_page(cfg.base_path))
118
-
119
- async def chat(request):
120
- body = await request.json()
121
- message = body.get("message", "")
122
- session_id = body.get("sessionId", f"session-{id(request)}")
123
-
124
- def event_stream():
125
- cb = SseCallback()
126
- engine.chat(message, session_id, cb)
127
- for event_type, data in cb.events:
128
- yield f"event: {event_type}\ndata: {data}\n\n"
129
-
130
- return StreamingResponse(event_stream(), media_type="text/event-stream")
131
-
132
- async def clear(request):
133
- body = await request.json()
134
- session_id = body.get("sessionId", "")
135
- if session_id:
136
- engine.clear_session(session_id)
137
- return JSONResponse({"status": "cleared"})
138
-
139
- async def health(request):
140
- return JSONResponse({"status": "ok", "agent": "python-debug-agent"})
141
-
142
- async def tools(request):
143
- return JSONResponse({"tools": engine.tools.all_schemas()})
144
-
145
- routes = [
146
- Route("/", chat_page),
147
- Route("/api/chat", chat, methods=["POST"]),
148
- Route("/api/clear", clear, methods=["POST"]),
149
- Route("/api/health", health),
150
- Route("/api/tools", tools),
151
- ]
152
- return Starlette(routes=routes)
153
-
154
-
155
- # ==================== Flask ====================
156
-
157
- def create_flask_blueprint(config: AgentConfig | None = None):
158
- from flask import Blueprint, Response, request, jsonify
159
- from debug_agent import inspectors # noqa: F401
160
-
161
- cfg = config or AgentConfig.from_env()
162
- engine = DebugEngine(cfg)
163
-
164
- bp = Blueprint("debug_agent", __name__, url_prefix=cfg.base_path)
165
-
166
- @bp.route("", methods=["GET"])
167
- @bp.route("/", methods=["GET"])
168
- def chat_page():
169
- return render_chat_page(cfg.base_path)
170
-
171
- @bp.route("/api/chat", methods=["POST"])
172
- def chat():
173
- message = request.json.get("message", "")
174
- session_id = request.json.get("sessionId", f"session-{id(request)}")
175
-
176
- def generate():
177
- cb = SseCallback()
178
- engine.chat(message, session_id, cb)
179
- for event_type, data in cb.events:
180
- yield f"event: {event_type}\ndata: {data}\n\n"
181
-
182
- return Response(generate(), mimetype="text/event-stream")
183
-
184
- @bp.route("/api/clear", methods=["POST"])
185
- def clear():
186
- session_id = request.json.get("sessionId", "")
187
- if session_id:
188
- engine.clear_session(session_id)
189
- return jsonify({"status": "cleared"})
190
-
191
- @bp.route("/api/health", methods=["GET"])
192
- def health():
193
- return jsonify({"status": "ok", "agent": "python-debug-agent"})
194
-
195
- @bp.route("/api/tools", methods=["GET"])
196
- def tools():
197
- return jsonify({"tools": engine.tools.all_schemas()})
198
-
199
- return bp
File without changes
File without changes