debug-agent-py 0.7.0__tar.gz → 0.8.0__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 (71) hide show
  1. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/PKG-INFO +77 -7
  2. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/README.md +75 -6
  3. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/pyproject.toml +2 -2
  4. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/__init__.py +7 -12
  5. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/chat_session.py +28 -1
  6. debug_agent_py-0.8.0/src/debug_agent/config.py +164 -0
  7. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/engine.py +71 -6
  8. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/cache_inspector.py +1 -0
  9. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/endpoint_test_inspector.py +117 -8
  10. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/leak_detector_inspector.py +4 -0
  11. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/logging_inspector.py +1 -0
  12. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/runtime.py +5 -1
  13. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/snapshot_inspector.py +4 -0
  14. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/llm_client.py +4 -1
  15. debug_agent_py-0.8.0/src/debug_agent/middleware.py +733 -0
  16. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/system_prompt_builder.py +85 -8
  17. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/tool_registry.py +74 -3
  18. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/web/chat_page.py +14 -4
  19. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent_py.egg-info/PKG-INFO +77 -7
  20. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent_py.egg-info/SOURCES.txt +11 -1
  21. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent_py.egg-info/requires.txt +1 -0
  22. debug_agent_py-0.8.0/tests/test_chat_page.py +18 -0
  23. debug_agent_py-0.8.0/tests/test_chat_session.py +61 -0
  24. debug_agent_py-0.8.0/tests/test_config.py +107 -0
  25. debug_agent_py-0.8.0/tests/test_engine.py +82 -0
  26. debug_agent_py-0.8.0/tests/test_hardening_unit.py +193 -0
  27. debug_agent_py-0.8.0/tests/test_middleware_asgi.py +198 -0
  28. debug_agent_py-0.8.0/tests/test_middleware_django.py +115 -0
  29. debug_agent_py-0.8.0/tests/test_middleware_flask.py +276 -0
  30. debug_agent_py-0.8.0/tests/test_mutating_tools.py +463 -0
  31. debug_agent_py-0.8.0/tests/test_tool_registry.py +57 -0
  32. debug_agent_py-0.7.0/src/debug_agent/config.py +0 -48
  33. debug_agent_py-0.7.0/src/debug_agent/middleware.py +0 -199
  34. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/setup.cfg +0 -0
  35. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/context_compressor.py +0 -0
  36. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/__init__.py +0 -0
  37. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/async_tasks.py +0 -0
  38. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/build_info_inspector.py +0 -0
  39. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/celery.py +0 -0
  40. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/config_inspector.py +0 -0
  41. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/cpu_profile_inspector.py +0 -0
  42. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/database.py +0 -0
  43. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/django.py +0 -0
  44. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/error_tracking.py +0 -0
  45. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/fastapi_ext.py +0 -0
  46. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/fd_inspector.py +0 -0
  47. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/feature_flag_inspector.py +0 -0
  48. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/flask_ext.py +0 -0
  49. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/framework.py +0 -0
  50. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/health_inspector.py +0 -0
  51. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/http_client_inspector.py +0 -0
  52. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/http_tracker.py +0 -0
  53. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/jinja2.py +0 -0
  54. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/locks_inspector.py +0 -0
  55. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/memory.py +0 -0
  56. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/metrics_inspector.py +0 -0
  57. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/migration_inspector.py +0 -0
  58. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/modules.py +0 -0
  59. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/pool_inspector.py +0 -0
  60. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/redis.py +0 -0
  61. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/scheduler_inspector.py +0 -0
  62. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/security_inspector.py +0 -0
  63. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/service_registry_inspector.py +0 -0
  64. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/signals.py +0 -0
  65. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/system.py +0 -0
  66. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/threads.py +0 -0
  67. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/warnings_inspector.py +0 -0
  68. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/inspectors/websocket_inspector.py +0 -0
  69. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent/web/__init__.py +0 -0
  70. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/src/debug_agent_py.egg-info/dependency_links.txt +0 -0
  71. {debug_agent_py-0.7.0 → debug_agent_py-0.8.0}/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.8.0
4
4
  Summary: AI-powered runtime debugging agent for Python web applications
5
5
  Author-email: ggcode <noreply@ggcode.dev>
6
6
  License: MIT
@@ -47,6 +47,7 @@ Provides-Extra: dev
47
47
  Requires-Dist: fastapi; extra == "dev"
48
48
  Requires-Dist: uvicorn; extra == "dev"
49
49
  Requires-Dist: flask; extra == "dev"
50
+ Requires-Dist: django; extra == "dev"
50
51
  Requires-Dist: pytest; extra == "dev"
51
52
 
52
53
  # Python Debug Agent
@@ -85,30 +86,53 @@ pip install debug-agent-py
85
86
 
86
87
  ```python
87
88
  from flask import Flask
88
- from debug_agent import setup_debug_agent
89
+ from debug_agent.middleware import create_flask_blueprint
89
90
 
90
91
  app = Flask(__name__)
91
92
 
92
- # One line to integrate
93
- setup_debug_agent(app)
93
+ # Mounts the UI at /agent plus /agent/api/{chat,clear,health,tools}
94
+ app.register_blueprint(create_flask_blueprint())
94
95
  ```
95
96
 
96
- ### 3. Configure LLM
97
+ Or with FastAPI:
98
+
99
+ ```python
100
+ from fastapi import FastAPI
101
+ from debug_agent.middleware import create_fastapi_router
102
+
103
+ app = FastAPI()
104
+
105
+ # Router already carries the /agent prefix; do not add it again
106
+ app.include_router(create_fastapi_router())
107
+ ```
108
+
109
+ Starlette and Django are supported the same way: `create_starlette_app()`
110
+ (mount it under your base path) and `create_django_urls()` (extend `urlpatterns`).
111
+
112
+ ### 3. Configure the LLM and access
97
113
 
98
114
  ```bash
99
115
  export LLM_API_KEY=your-key
100
116
  export LLM_BASE_URL=https://open.bigmodel.cn/api/coding/paas/v4 # default
101
117
  export LLM_MODEL=glm-5.2 # default
118
+
119
+ # Required on every agent route once set - see "Security in production"
120
+ export DEBUG_AGENT_API_KEY=$(openssl rand -hex 32)
102
121
  ```
103
122
 
104
- Supports any OpenAI-compatible endpoint.
123
+ Supports any OpenAI-compatible endpoint. All settings come from environment
124
+ variables (see [Configuration](#configuration)); nothing else needs to change in your code.
105
125
 
106
126
  ### 4. Run and open
107
127
 
108
128
  ```
109
- http://localhost:8000/agent
129
+ http://localhost:8000/agent?api_key=<DEBUG_AGENT_API_KEY>
110
130
  ```
111
131
 
132
+ With `DEBUG_AGENT_API_KEY` set, the UI and every `/agent/api/*` request require the
133
+ key (`Authorization: Bearer <key>`, `X-API-Key: <key>`, or the `api_key` query
134
+ parameter). Without it the agent runs with no auth - only do that on a developer laptop.
135
+
112
136
  ## Features
113
137
 
114
138
  - **Streaming AI responses** with real-time tool call badges (pending / success / error)
@@ -374,6 +398,52 @@ def check_redis():
374
398
  | `LLM_MODEL` | `glm-5.2` | Model name |
375
399
  | `LLM_MAX_TOOL_ROUNDS` | `25` | Max tool-calling rounds |
376
400
  | `LLM_CONTEXT_WINDOW_TOKENS` | `100000` | Context window size |
401
+ | `DEBUG_AGENT_ENABLED` | `true` | Set `false` to make every `/agent` route answer 404 |
402
+ | `DEBUG_AGENT_BASE_PATH` | `/agent` | Mount path |
403
+ | `DEBUG_AGENT_API_KEY` | *(empty = no auth)* | When set, the UI and all `/agent/api/*` require this key |
404
+ | `DEBUG_AGENT_CORS_ORIGIN` | `*` | `Access-Control-Allow-Origin`; with an API key set, `*` means same-origin only |
405
+ | `DEBUG_AGENT_MAX_SESSIONS` | `200` | In-memory session cap (least-recently-active evicted first) |
406
+ | `DEBUG_AGENT_SESSION_TTL_SECONDS` | `3600` | Drop a session's history after this much inactivity |
407
+ | `DEBUG_AGENT_MAX_HISTORY` | `100` | Stored messages per session (oldest whole rounds dropped) |
408
+ | `DEBUG_AGENT_MAX_BODY_BYTES` | `1048576` | Request body limit for POST endpoints (413 beyond) |
409
+ | `DEBUG_AGENT_RATE_LIMIT` | `60` | `POST /agent/api/chat` requests per client IP per minute (429 beyond) |
410
+ | `DEBUG_AGENT_ALLOW_MUTATING_TOOLS` | `false` | Opt in to tools with side effects: `trigger_gc`, `set_log_level`, `clear_cache`, and non-GET/HEAD/OPTIONS requests through `test_endpoint` / `batch_test_endpoints` |
411
+ | `DEBUG_AGENT_ENDPOINT_ALLOWED_HOSTS` | *(empty)* | Comma-separated extra hosts `test_endpoint` / `batch_test_endpoints` may target (exact host, case-insensitive). Loopback is always allowed; everything else is rejected |
412
+
413
+ ### Troubleshooting is read-only by default
414
+
415
+ Only read-only tools are offered to the model. Mutating tools are hidden from the
416
+ tool list (and from `/agent/api/tools`) and refused with a `disabled` error until
417
+ `DEBUG_AGENT_ALLOW_MUTATING_TOOLS=true`. Endpoint testing still works for
418
+ `GET`/`HEAD`/`OPTIONS` and only ever targets `http(s)` loopback hosts, plus any
419
+ host named in `DEBUG_AGENT_ENDPOINT_ALLOWED_HOSTS`; anything else is rejected
420
+ before a request is sent. Starting without `DEBUG_AGENT_API_KEY` logs a
421
+ one-line warning to the `debug_agent` logger; it does not change behaviour.
422
+
423
+ > **Upgrade note (breaking):** before this change the mutating tools above were
424
+ available by default. After upgrading they are hidden from the model and refused
425
+ with a `disabled` error; calls with `POST`/`PUT`/`PATCH`/`DELETE` through the
426
+ endpoint-testing tools are refused in the same way. Set
427
+ `DEBUG_AGENT_ALLOW_MUTATING_TOOLS=true` to restore the previous behaviour.
428
+
429
+ ### Security in production
430
+
431
+ By default the agent has **no authentication** and allows any origin — fine on a
432
+ developer laptop, not on a reachable port. Before exposing it:
433
+
434
+ ```bash
435
+ export DEBUG_AGENT_API_KEY=$(openssl rand -hex 32) # required on every agent route
436
+ export DEBUG_AGENT_ENABLED=false # or switch it off entirely in prod
437
+ ```
438
+
439
+ With a key set, present it as `Authorization: Bearer <key>`, `X-API-Key: <key>`,
440
+ or open the UI as `/agent?api_key=<key>` (the page then sends it as a Bearer
441
+ header on every request). CORS becomes same-origin only unless
442
+ `DEBUG_AGENT_CORS_ORIGIN` names an explicit origin. `POST /api/chat` is
443
+ rate-limited per client IP (first `X-Forwarded-For` hop when behind a proxy —
444
+ only trust it behind one you control). All of this applies to every mount:
445
+ Flask (`create_flask_blueprint`), FastAPI (`create_fastapi_router`), Starlette
446
+ (`create_starlette_app`) and Django (`create_django_urls`).
377
447
 
378
448
  ## Run the Demo
379
449
 
@@ -34,30 +34,53 @@ pip install debug-agent-py
34
34
 
35
35
  ```python
36
36
  from flask import Flask
37
- from debug_agent import setup_debug_agent
37
+ from debug_agent.middleware import create_flask_blueprint
38
38
 
39
39
  app = Flask(__name__)
40
40
 
41
- # One line to integrate
42
- setup_debug_agent(app)
41
+ # Mounts the UI at /agent plus /agent/api/{chat,clear,health,tools}
42
+ app.register_blueprint(create_flask_blueprint())
43
43
  ```
44
44
 
45
- ### 3. Configure LLM
45
+ Or with FastAPI:
46
+
47
+ ```python
48
+ from fastapi import FastAPI
49
+ from debug_agent.middleware import create_fastapi_router
50
+
51
+ app = FastAPI()
52
+
53
+ # Router already carries the /agent prefix; do not add it again
54
+ app.include_router(create_fastapi_router())
55
+ ```
56
+
57
+ Starlette and Django are supported the same way: `create_starlette_app()`
58
+ (mount it under your base path) and `create_django_urls()` (extend `urlpatterns`).
59
+
60
+ ### 3. Configure the LLM and access
46
61
 
47
62
  ```bash
48
63
  export LLM_API_KEY=your-key
49
64
  export LLM_BASE_URL=https://open.bigmodel.cn/api/coding/paas/v4 # default
50
65
  export LLM_MODEL=glm-5.2 # default
66
+
67
+ # Required on every agent route once set - see "Security in production"
68
+ export DEBUG_AGENT_API_KEY=$(openssl rand -hex 32)
51
69
  ```
52
70
 
53
- Supports any OpenAI-compatible endpoint.
71
+ Supports any OpenAI-compatible endpoint. All settings come from environment
72
+ variables (see [Configuration](#configuration)); nothing else needs to change in your code.
54
73
 
55
74
  ### 4. Run and open
56
75
 
57
76
  ```
58
- http://localhost:8000/agent
77
+ http://localhost:8000/agent?api_key=<DEBUG_AGENT_API_KEY>
59
78
  ```
60
79
 
80
+ With `DEBUG_AGENT_API_KEY` set, the UI and every `/agent/api/*` request require the
81
+ key (`Authorization: Bearer <key>`, `X-API-Key: <key>`, or the `api_key` query
82
+ parameter). Without it the agent runs with no auth - only do that on a developer laptop.
83
+
61
84
  ## Features
62
85
 
63
86
  - **Streaming AI responses** with real-time tool call badges (pending / success / error)
@@ -323,6 +346,52 @@ def check_redis():
323
346
  | `LLM_MODEL` | `glm-5.2` | Model name |
324
347
  | `LLM_MAX_TOOL_ROUNDS` | `25` | Max tool-calling rounds |
325
348
  | `LLM_CONTEXT_WINDOW_TOKENS` | `100000` | Context window size |
349
+ | `DEBUG_AGENT_ENABLED` | `true` | Set `false` to make every `/agent` route answer 404 |
350
+ | `DEBUG_AGENT_BASE_PATH` | `/agent` | Mount path |
351
+ | `DEBUG_AGENT_API_KEY` | *(empty = no auth)* | When set, the UI and all `/agent/api/*` require this key |
352
+ | `DEBUG_AGENT_CORS_ORIGIN` | `*` | `Access-Control-Allow-Origin`; with an API key set, `*` means same-origin only |
353
+ | `DEBUG_AGENT_MAX_SESSIONS` | `200` | In-memory session cap (least-recently-active evicted first) |
354
+ | `DEBUG_AGENT_SESSION_TTL_SECONDS` | `3600` | Drop a session's history after this much inactivity |
355
+ | `DEBUG_AGENT_MAX_HISTORY` | `100` | Stored messages per session (oldest whole rounds dropped) |
356
+ | `DEBUG_AGENT_MAX_BODY_BYTES` | `1048576` | Request body limit for POST endpoints (413 beyond) |
357
+ | `DEBUG_AGENT_RATE_LIMIT` | `60` | `POST /agent/api/chat` requests per client IP per minute (429 beyond) |
358
+ | `DEBUG_AGENT_ALLOW_MUTATING_TOOLS` | `false` | Opt in to tools with side effects: `trigger_gc`, `set_log_level`, `clear_cache`, and non-GET/HEAD/OPTIONS requests through `test_endpoint` / `batch_test_endpoints` |
359
+ | `DEBUG_AGENT_ENDPOINT_ALLOWED_HOSTS` | *(empty)* | Comma-separated extra hosts `test_endpoint` / `batch_test_endpoints` may target (exact host, case-insensitive). Loopback is always allowed; everything else is rejected |
360
+
361
+ ### Troubleshooting is read-only by default
362
+
363
+ Only read-only tools are offered to the model. Mutating tools are hidden from the
364
+ tool list (and from `/agent/api/tools`) and refused with a `disabled` error until
365
+ `DEBUG_AGENT_ALLOW_MUTATING_TOOLS=true`. Endpoint testing still works for
366
+ `GET`/`HEAD`/`OPTIONS` and only ever targets `http(s)` loopback hosts, plus any
367
+ host named in `DEBUG_AGENT_ENDPOINT_ALLOWED_HOSTS`; anything else is rejected
368
+ before a request is sent. Starting without `DEBUG_AGENT_API_KEY` logs a
369
+ one-line warning to the `debug_agent` logger; it does not change behaviour.
370
+
371
+ > **Upgrade note (breaking):** before this change the mutating tools above were
372
+ available by default. After upgrading they are hidden from the model and refused
373
+ with a `disabled` error; calls with `POST`/`PUT`/`PATCH`/`DELETE` through the
374
+ endpoint-testing tools are refused in the same way. Set
375
+ `DEBUG_AGENT_ALLOW_MUTATING_TOOLS=true` to restore the previous behaviour.
376
+
377
+ ### Security in production
378
+
379
+ By default the agent has **no authentication** and allows any origin — fine on a
380
+ developer laptop, not on a reachable port. Before exposing it:
381
+
382
+ ```bash
383
+ export DEBUG_AGENT_API_KEY=$(openssl rand -hex 32) # required on every agent route
384
+ export DEBUG_AGENT_ENABLED=false # or switch it off entirely in prod
385
+ ```
386
+
387
+ With a key set, present it as `Authorization: Bearer <key>`, `X-API-Key: <key>`,
388
+ or open the UI as `/agent?api_key=<key>` (the page then sends it as a Bearer
389
+ header on every request). CORS becomes same-origin only unless
390
+ `DEBUG_AGENT_CORS_ORIGIN` names an explicit origin. `POST /api/chat` is
391
+ rate-limited per client IP (first `X-Forwarded-For` hop when behind a proxy —
392
+ only trust it behind one you control). All of this applies to every mount:
393
+ Flask (`create_flask_blueprint`), FastAPI (`create_fastapi_router`), Starlette
394
+ (`create_starlette_app`) and Django (`create_django_urls`).
326
395
 
327
396
  ## Run the Demo
328
397
 
@@ -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.8.0"
8
8
  description = "AI-powered runtime debugging agent for Python web applications"
9
9
  readme = "README.md"
10
10
  license = {text = "MIT"}
@@ -37,7 +37,7 @@ sqlalchemy = ["sqlalchemy>=2.0", "flask-sqlalchemy>=3.0"]
37
37
  redis = ["redis>=5.0"]
38
38
  celery = ["celery>=5.3"]
39
39
  demo = ["flask>=2.3", "sqlalchemy>=2.0", "flask-sqlalchemy>=3.0", "redis>=5.0", "celery>=5.3", "gunicorn>=21.2"]
40
- dev = ["fastapi", "uvicorn", "flask", "pytest"]
40
+ dev = ["fastapi", "uvicorn", "flask", "django", "pytest"]
41
41
 
42
42
  [project.urls]
43
43
  Homepage = "https://github.com/topcheer/python-debug-agent"
@@ -2,16 +2,12 @@ from __future__ import annotations
2
2
 
3
3
  """Debug Agent — AI-powered runtime debugging for Python applications."""
4
4
 
5
- import sys as _sys
6
-
7
- # ggcode promotional message — shown once on first import
8
- if not hasattr(_sys, '_debug_agent_ggcode_shown'):
9
- _sys._debug_agent_ggcode_shown = True
10
- _print = print
11
- _print('')
12
- _print(' This package was built with ggcode — an AI coding assistant.')
13
- _print(' https://github.com/topcheer/ggcode')
14
- _print('')
5
+ # Read version from package metadata (falls back to pyproject.toml value)
6
+ try:
7
+ from importlib.metadata import version as _pkg_version
8
+ __version__ = _pkg_version("debug-agent-py")
9
+ except Exception:
10
+ __version__ = "0.0.0"
15
11
 
16
12
  from debug_agent.config import AgentConfig
17
13
  from debug_agent.tool_registry import debug_tool, ToolParam, registry
@@ -21,11 +17,10 @@ from debug_agent.system_prompt_builder import SystemPromptBuilder
21
17
  from debug_agent.context_compressor import ContextCompressor, CompressionResult
22
18
  from debug_agent.llm_client import LLMClient, StreamHandler
23
19
 
24
- __version__ = "0.1.0"
25
20
  __all__ = [
26
21
  "AgentConfig", "debug_tool", "ToolParam", "registry", "DebugEngine", "ChatCallback",
27
22
  "ChatSession", "SystemPromptBuilder", "ContextCompressor", "CompressionResult",
28
- "LLMClient", "StreamHandler", "setup",
23
+ "LLMClient", "StreamHandler", "setup", "__version__",
29
24
  ]
30
25
 
31
26
 
@@ -5,11 +5,14 @@ from __future__ import annotations
5
5
  import time
6
6
  from typing import Any
7
7
 
8
+ # Per-session message cap unless configured otherwise.
9
+ DEFAULT_MAX_HISTORY = 100
10
+
8
11
 
9
12
  class ChatSession:
10
13
  """Manages conversation history and cumulative token usage."""
11
14
 
12
- def __init__(self, session_id: str):
15
+ def __init__(self, session_id: str, max_history: int = DEFAULT_MAX_HISTORY):
13
16
  self.session_id = session_id
14
17
  self.created_at = time.time()
15
18
  self.messages: list[dict[str, Any]] = []
@@ -19,14 +22,38 @@ class ChatSession:
19
22
  self.cumulative_prompt_tokens: int = 0
20
23
  self.cumulative_completion_tokens: int = 0
21
24
 
25
+ # Caps len(messages); 0 means unlimited.
26
+ self.max_history = max_history
27
+
22
28
  def add_message(self, message: dict[str, Any]):
23
29
  self.messages.append(message)
30
+ self._trim_history()
24
31
  self.last_active_at = time.time()
25
32
 
26
33
  def replace_messages(self, new_messages: list[dict[str, Any]]):
27
34
  self.messages = new_messages
28
35
  self.last_active_at = time.time()
29
36
 
37
+ def _trim_history(self):
38
+ """Drop the oldest whole rounds until len(messages) <= max_history.
39
+
40
+ Cuts only happen at a ``user`` message boundary so the remaining history
41
+ never starts with an assistant tool_call or an orphaned tool result
42
+ (which the LLM API rejects). If no safe cut point exists the history is
43
+ left untouched.
44
+ """
45
+ if self.max_history <= 0 or len(self.messages) <= self.max_history:
46
+ return
47
+ while len(self.messages) > self.max_history:
48
+ cut = -1
49
+ for i in range(1, len(self.messages)):
50
+ if self.messages[i].get("role") == "user":
51
+ cut = i
52
+ break
53
+ if cut < 0:
54
+ return
55
+ self.messages = self.messages[cut:]
56
+
30
57
  def record_token_usage(self, usage: dict | None):
31
58
  if not usage:
32
59
  return
@@ -0,0 +1,164 @@
1
+ """Configuration for Debug Agent."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from dataclasses import InitVar, dataclass, field
7
+
8
+ _TRUE_VALUES = {"1", "t", "true", "yes", "on"}
9
+ _FALSE_VALUES = {"0", "f", "false", "no", "off"}
10
+
11
+
12
+ def _env_int(key: str, default: int) -> int:
13
+ """Read an integer env var; unset, malformed or negative values fall back to the default."""
14
+ raw = os.getenv(key)
15
+ if not raw:
16
+ return default
17
+ try:
18
+ value = int(raw)
19
+ except ValueError:
20
+ return default
21
+ return value if value >= 0 else default
22
+
23
+
24
+ def _env_bool(key: str, default: bool) -> bool:
25
+ """Read a boolean env var; unset or unrecognised values fall back to the default."""
26
+ raw = os.getenv(key)
27
+ if not raw:
28
+ return default
29
+ lowered = raw.strip().lower()
30
+ if lowered in _TRUE_VALUES:
31
+ return True
32
+ if lowered in _FALSE_VALUES:
33
+ return False
34
+ return default
35
+
36
+
37
+ def _install_secret_accessor(cls, doc: str):
38
+ """Make ``cls.api_key`` both an init parameter and a read/write attribute.
39
+
40
+ The key is declared as an ``InitVar`` so it is not a dataclass field (it is
41
+ excluded from ``dataclasses.asdict`` and ``repr``) and is stored as
42
+ ``_api_key`` by ``__post_init__``. dataclasses resets the class attribute of
43
+ an InitVar to its default while it processes the class, so the accessor
44
+ cannot live inside the class body and is installed afterwards.
45
+ """
46
+
47
+ def _get(self) -> str:
48
+ return self._api_key
49
+
50
+ def _set(self, value):
51
+ self._api_key = value or ""
52
+
53
+ setattr(cls, "api_key", property(_get, _set, doc=doc))
54
+
55
+
56
+ @dataclass
57
+ class LLMConfig:
58
+ """LLM provider settings. ``api_key`` is init-only and never serialised (see AgentConfig)."""
59
+
60
+ base_url: str = "https://open.bigmodel.cn/api/coding/paas/v4"
61
+ # LLM secret. Init-only (InitVar), stored as ``_api_key``: not a dataclass
62
+ # field, so excluded from dataclasses.asdict and repr. Accessor installed below.
63
+ api_key: InitVar[str] = ""
64
+ model: str = "glm-5.2"
65
+ temperature: float = 0.3
66
+ max_tokens: int = 4096
67
+ max_tool_rounds: int = 25
68
+ timeout_seconds: int = 120
69
+ max_retries: int = 3
70
+ retry_base_delay_ms: int = 1000
71
+ retry_max_delay_ms: int = 30000
72
+ context_window_tokens: int = 100000
73
+
74
+ def __post_init__(self, api_key: str):
75
+ self._api_key = api_key or ""
76
+
77
+
78
+ @dataclass
79
+ class AgentConfig:
80
+ """All configuration for the debug agent (agent-level hardening + LLM settings).
81
+
82
+ ``api_key`` is an init-only value: it can be passed to the constructor (or
83
+ ``dataclasses.replace``) but is stored as ``_api_key`` so that neither ``repr``
84
+ nor ``dataclasses.asdict`` ever serialises the secret.
85
+ """
86
+
87
+ # false -> every agent endpoint answers 404 (nothing is mounted).
88
+ enabled: bool = True
89
+ base_path: str = "/agent"
90
+
91
+ # When non-empty, the UI page and ALL /api/* require the key. Empty = no auth.
92
+ # InitVar, stored as ``_api_key``: neither a dataclass field (so excluded
93
+ # from dataclasses.asdict) nor part of repr. Accessor installed below.
94
+ api_key: InitVar[str] = ""
95
+
96
+ # Access-Control-Allow-Origin. With api_key set, "*" emits no CORS headers.
97
+ cors_origin: str = "*"
98
+
99
+ # In-memory session table cap (LRU eviction; 0 = unlimited) and idle TTL in
100
+ # seconds after which a session starts with fresh history (0 = never).
101
+ max_sessions: int = 200
102
+ session_ttl_seconds: int = 3600
103
+
104
+ # Stored messages per session; oldest whole rounds dropped (0 = unlimited).
105
+ max_history_messages: int = 100
106
+
107
+ # POST body size limit in bytes (413 beyond; 0 = unlimited).
108
+ max_body_bytes: int = 1048576
109
+
110
+ # POST /api/chat requests per client IP per minute (0 = unlimited).
111
+ rate_limit_per_minute: int = 60
112
+
113
+ # Opt in to tools with side effects (trigger_gc, set_log_level, clear_cache
114
+ # and non-GET/HEAD/OPTIONS requests through test_endpoint). Off by default:
115
+ # troubleshooting is read-only.
116
+ allow_mutating_tools: bool = False
117
+
118
+ llm: LLMConfig = field(default_factory=LLMConfig)
119
+
120
+ def __post_init__(self, api_key: str):
121
+ self._api_key = api_key or ""
122
+
123
+ @classmethod
124
+ def from_env(cls) -> AgentConfig:
125
+ return cls(
126
+ enabled=_env_bool("DEBUG_AGENT_ENABLED", True),
127
+ base_path=os.getenv("DEBUG_AGENT_BASE_PATH", "/agent"),
128
+ api_key=os.getenv("DEBUG_AGENT_API_KEY", ""),
129
+ cors_origin=os.getenv("DEBUG_AGENT_CORS_ORIGIN", "*"),
130
+ max_sessions=_env_int("DEBUG_AGENT_MAX_SESSIONS", 200),
131
+ session_ttl_seconds=_env_int("DEBUG_AGENT_SESSION_TTL_SECONDS", 3600),
132
+ max_history_messages=_env_int("DEBUG_AGENT_MAX_HISTORY", 100),
133
+ max_body_bytes=_env_int("DEBUG_AGENT_MAX_BODY_BYTES", 1048576),
134
+ rate_limit_per_minute=_env_int("DEBUG_AGENT_RATE_LIMIT", 60),
135
+ allow_mutating_tools=_env_bool("DEBUG_AGENT_ALLOW_MUTATING_TOOLS", False),
136
+ llm=LLMConfig(
137
+ base_url=os.getenv("LLM_BASE_URL", "https://open.bigmodel.cn/api/coding/paas/v4"),
138
+ api_key=os.getenv("LLM_API_KEY") or os.getenv("OPENAI_API_KEY", ""),
139
+ model=os.getenv("LLM_MODEL", "glm-5.2"),
140
+ temperature=float(os.getenv("LLM_TEMPERATURE", "0.3")),
141
+ max_tokens=int(os.getenv("LLM_MAX_TOKENS", "4096")),
142
+ max_tool_rounds=int(os.getenv("LLM_MAX_TOOL_ROUNDS", "25")),
143
+ timeout_seconds=int(os.getenv("LLM_TIMEOUT_SECONDS", "120")),
144
+ max_retries=int(os.getenv("LLM_MAX_RETRIES", "3")),
145
+ retry_base_delay_ms=int(os.getenv("LLM_RETRY_BASE_DELAY_MS", "1000")),
146
+ retry_max_delay_ms=int(os.getenv("LLM_RETRY_MAX_DELAY_MS", "30000")),
147
+ context_window_tokens=int(os.getenv("LLM_CONTEXT_WINDOW_TOKENS", "100000")),
148
+ ),
149
+ )
150
+
151
+
152
+ def _get_api_key(self: AgentConfig) -> str:
153
+ return self._api_key
154
+
155
+
156
+ def _set_api_key(self: AgentConfig, value: str):
157
+ self._api_key = value or ""
158
+
159
+
160
+ _install_secret_accessor(LLMConfig, "The LLM provider API key (never included in repr/asdict).")
161
+
162
+ AgentConfig.api_key = property(
163
+ _get_api_key, _set_api_key, doc="The configured agent API key (never included in repr/asdict)."
164
+ )
@@ -7,6 +7,8 @@ from __future__ import annotations
7
7
 
8
8
  import json
9
9
  import logging
10
+ import threading
11
+ import time
10
12
  from typing import Any
11
13
 
12
14
  from debug_agent.chat_session import ChatSession
@@ -18,6 +20,32 @@ from debug_agent.tool_registry import registry
18
20
 
19
21
  logger = logging.getLogger("debug_agent")
20
22
 
23
+ # The unauthenticated warning is emitted once per process, however many engines
24
+ # are constructed (mirrors warnOnce in go-debug-agent).
25
+ _warn_lock = threading.Lock()
26
+ _warned_unauthenticated = False
27
+
28
+
29
+ def _warn_if_unauthenticated(config: AgentConfig):
30
+ """Log a one-line warning when the agent is mounted without an API key.
31
+
32
+ Anyone who can reach the port can then drive the LLM and every diagnostic
33
+ tool. This does not change behaviour - only the operator can decide whether
34
+ the port is reachable. Goes to the ``debug_agent`` logger, never stdout.
35
+ """
36
+ global _warned_unauthenticated
37
+ if config.api_key:
38
+ return
39
+ with _warn_lock:
40
+ if _warned_unauthenticated:
41
+ return
42
+ _warned_unauthenticated = True
43
+ logger.warning(
44
+ "[debug-agent] WARNING: DEBUG_AGENT_API_KEY is not set - the agent UI and API are "
45
+ "unauthenticated; anyone who can reach this port can drive the LLM and diagnostic "
46
+ "tools (safe on localhost only)."
47
+ )
48
+
21
49
 
22
50
  class ChatCallback:
23
51
  """Engine to UI streaming callback."""
@@ -61,6 +89,13 @@ class DebugEngine:
61
89
  self.llm = LLMClient(config.llm)
62
90
  self.tools = registry
63
91
  self._sessions: dict[str, ChatSession] = {}
92
+ # Guards the session table (worker threads call the engine concurrently).
93
+ self._sessions_lock = threading.RLock()
94
+
95
+ # Applied before the system prompt is built so hidden (mutating) tools
96
+ # are neither advertised to the LLM nor listed in the prompt.
97
+ registry.set_allow_mutating_tools(config.allow_mutating_tools)
98
+ _warn_if_unauthenticated(config)
64
99
 
65
100
  self.prompt_builder = SystemPromptBuilder(registry)
66
101
  self.system_prompt = self.prompt_builder.build()
@@ -78,14 +113,44 @@ class DebugEngine:
78
113
  self._run_tool_loop(session, callback)
79
114
 
80
115
  def clear_session(self, session_id: str = "default"):
81
- session = self._sessions.get(session_id)
82
- if session:
83
- session.clear()
116
+ with self._sessions_lock:
117
+ session = self._sessions.get(session_id)
118
+ if session:
119
+ session.clear()
84
120
 
85
121
  def _get_or_create_session(self, session_id: str) -> ChatSession:
86
- if session_id not in self._sessions:
87
- self._sessions[session_id] = ChatSession(session_id)
88
- return self._sessions[session_id]
122
+ if not session_id:
123
+ session_id = "default"
124
+ with self._sessions_lock:
125
+ session = self._sessions.get(session_id)
126
+ if session is not None:
127
+ if self._session_expired(session):
128
+ # Idle beyond the TTL: drop the stale history and start over.
129
+ session = self._new_session(session_id)
130
+ self._sessions[session_id] = session
131
+ return session
132
+
133
+ session = self._new_session(session_id)
134
+ self._sessions[session_id] = session
135
+ self._evict_overflow_sessions()
136
+ return session
137
+
138
+ def _new_session(self, session_id: str) -> ChatSession:
139
+ return ChatSession(session_id, max_history=self.config.max_history_messages)
140
+
141
+ def _session_expired(self, session: ChatSession) -> bool:
142
+ ttl = self.config.session_ttl_seconds
143
+ return ttl > 0 and time.time() - session.last_active_at > ttl
144
+
145
+ def _evict_overflow_sessions(self):
146
+ """Keep the session table within max_sessions by dropping the
147
+ least-recently-active session. 0 disables the cap.
148
+ """
149
+ cap = self.config.max_sessions
150
+ if cap <= 0 or len(self._sessions) <= cap:
151
+ return
152
+ oldest_id = min(self._sessions, key=lambda sid: self._sessions[sid].last_active_at)
153
+ del self._sessions[oldest_id]
89
154
 
90
155
  # ==================== Core Tool-Calling Loop ====================
91
156
 
@@ -199,6 +199,7 @@ def get_cache_keys(
199
199
  @debug_tool(
200
200
  "clear_cache",
201
201
  "Clear a registered cache (lru_cache: cache_clear, cachetools/django: clear)",
202
+ mutating=True,
202
203
  )
203
204
  def clear_cache(
204
205
  name: str = ToolParam("Cache name"),