debug-agent-py 0.6.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.6.0 → debug_agent_py-0.7.1}/PKG-INFO +46 -6
  2. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/README.md +45 -5
  3. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/pyproject.toml +1 -1
  4. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/__init__.py +19 -2
  5. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/__init__.py +5 -0
  6. debug_agent_py-0.7.1/src/debug_agent/inspectors/build_info_inspector.py +193 -0
  7. debug_agent_py-0.7.1/src/debug_agent/inspectors/cpu_profile_inspector.py +160 -0
  8. debug_agent_py-0.7.1/src/debug_agent/inspectors/leak_detector_inspector.py +179 -0
  9. debug_agent_py-0.7.1/src/debug_agent/inspectors/service_registry_inspector.py +176 -0
  10. debug_agent_py-0.7.1/src/debug_agent/inspectors/snapshot_inspector.py +301 -0
  11. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/llm_client.py +4 -1
  12. debug_agent_py-0.7.1/src/debug_agent/middleware.py +351 -0
  13. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/system_prompt_builder.py +85 -8
  14. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent_py.egg-info/PKG-INFO +46 -6
  15. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent_py.egg-info/SOURCES.txt +5 -0
  16. debug_agent_py-0.6.0/src/debug_agent/middleware.py +0 -199
  17. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/setup.cfg +0 -0
  18. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/chat_session.py +0 -0
  19. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/config.py +0 -0
  20. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/context_compressor.py +0 -0
  21. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/engine.py +0 -0
  22. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/async_tasks.py +0 -0
  23. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/cache_inspector.py +0 -0
  24. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/celery.py +0 -0
  25. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/config_inspector.py +0 -0
  26. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/database.py +0 -0
  27. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/django.py +0 -0
  28. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/endpoint_test_inspector.py +0 -0
  29. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/error_tracking.py +0 -0
  30. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/fastapi_ext.py +0 -0
  31. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/fd_inspector.py +0 -0
  32. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/feature_flag_inspector.py +0 -0
  33. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/flask_ext.py +0 -0
  34. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/framework.py +0 -0
  35. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/health_inspector.py +0 -0
  36. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/http_client_inspector.py +0 -0
  37. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/http_tracker.py +0 -0
  38. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/jinja2.py +0 -0
  39. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/locks_inspector.py +0 -0
  40. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/logging_inspector.py +0 -0
  41. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/memory.py +0 -0
  42. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/metrics_inspector.py +0 -0
  43. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/migration_inspector.py +0 -0
  44. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/modules.py +0 -0
  45. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/pool_inspector.py +0 -0
  46. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/redis.py +0 -0
  47. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/runtime.py +0 -0
  48. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/scheduler_inspector.py +0 -0
  49. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/security_inspector.py +0 -0
  50. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/signals.py +0 -0
  51. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/system.py +0 -0
  52. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/threads.py +0 -0
  53. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/warnings_inspector.py +0 -0
  54. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/inspectors/websocket_inspector.py +0 -0
  55. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/tool_registry.py +0 -0
  56. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/web/__init__.py +0 -0
  57. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent/web/chat_page.py +0 -0
  58. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent_py.egg-info/dependency_links.txt +0 -0
  59. {debug_agent_py-0.6.0 → debug_agent_py-0.7.1}/src/debug_agent_py.egg-info/requires.txt +0 -0
  60. {debug_agent_py-0.6.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.6.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
@@ -52,12 +52,12 @@ Requires-Dist: pytest; extra == "dev"
52
52
  # Python Debug Agent
53
53
 
54
54
  [![debug-agent-py](https://img.shields.io/pypi/v/debug-agent-py.svg)](https://pypi.org/project/debug-agent-py/)
55
- ![Tools](https://img.shields.io/badge/tools-99-blue)
56
- ![Inspectors](https://img.shields.io/badge/inspectors-33-green)
55
+ ![Tools](https://img.shields.io/badge/tools-113-blue)
56
+ ![Inspectors](https://img.shields.io/badge/inspectors-38-green)
57
57
  ![Python](https://img.shields.io/badge/Python-3.9%2B-3776AB)
58
58
  ![PyPI](https://img.shields.io/badge/PyPI-debug--agent--py-3776AB)
59
59
 
60
- An AI-powered runtime debugging agent that embeds directly into your Python web application. Add one dependency, configure an LLM key, and chat with your live app at `/agent` to inspect memory, threads, GC, modules, database connections, Redis, Django models/URLs, Celery tasks, Flask extensions, Jinja2 templates, signals, routes, HTTP requests, and more — **99 diagnostic tools across 33 inspectors**.
60
+ An AI-powered runtime debugging agent that embeds directly into your Python web application. Add one dependency, configure an LLM key, and chat with your live app at `/agent` to inspect memory, threads, GC, modules, database connections, Redis, Django models/URLs, Celery tasks, Flask extensions, Jinja2 templates, signals, routes, HTTP requests, and more — **113 diagnostic tools across 38 inspectors**.
61
61
 
62
62
  ## Version Support
63
63
 
@@ -115,11 +115,11 @@ http://localhost:8000/agent
115
115
  - **Context compression** — automatically summarizes old conversation when token limit is approached
116
116
  - **Dark-themed chat UI** with full markdown rendering (tables, code blocks, lists)
117
117
  - **Max tool rounds** (25) with forced final summary when limit is reached
118
- - **99 diagnostic tools** across **33 inspectors**
118
+ - **113 diagnostic tools** across **38 inspectors**
119
119
  - Works with Flask, FastAPI, and Django
120
120
  - Zero external dependencies (no Datadog, no Grafana, no APM)
121
121
 
122
- ## Inspectors & Tools (99)
122
+ ## Inspectors & Tools (113)
123
123
 
124
124
  ### Memory Inspector
125
125
  | Tool | Description |
@@ -321,6 +321,40 @@ http://localhost:8000/agent
321
321
  | `detect_pool_leaks` | Heuristic leak detection (growing pool, high wait ratio, saturation) |
322
322
  | `get_pool_wait_stats` | Connection acquire wait stats (avg, P95, max wait, timeout count) |
323
323
 
324
+ ### CPU Profiler Inspector (v0.7.0)
325
+ | Tool | Description |
326
+ |------|-------------|
327
+ | `start_cpu_profile` | Start a CPU profiling session (cProfile/yappi) |
328
+ | `stop_cpu_profile` | Stop CPU profiling and return collected profile data |
329
+ | `get_top_functions` | Get top CPU-consuming functions from the current profile |
330
+
331
+ ### Memory Leak Detector Inspector (v0.7.0)
332
+ | Tool | Description |
333
+ |------|-------------|
334
+ | `take_heap_snapshot` | Capture a heap snapshot for leak analysis (tracemalloc) |
335
+ | `compare_heap_snapshots` | Compare two heap snapshots to identify object growth |
336
+ | `get_leak_candidates` | Identify objects likely to be memory leaks |
337
+
338
+ ### Deployment/Build Info Inspector (v0.7.0)
339
+ | Tool | Description |
340
+ |------|-------------|
341
+ | `get_build_info` | Build version, commit hash, and package metadata |
342
+ | `get_deployment_info` | Deployment environment, container, and orchestration metadata |
343
+ | `get_runtime_version` | Python interpreter version and implementation details |
344
+
345
+ ### Snapshot & Diff Inspector (v0.7.0)
346
+ | Tool | Description |
347
+ |------|-------------|
348
+ | `take_snapshot` | Capture a runtime state snapshot |
349
+ | `compare_snapshots` | Compare two snapshots to identify state changes |
350
+ | `list_snapshots` | List all saved snapshots with timestamps |
351
+
352
+ ### Service Registry Inspector (v0.7.0)
353
+ | Tool | Description |
354
+ |------|-------------|
355
+ | `get_registered_services` | List all registered application services |
356
+ | `get_service_dependencies` | Map service-to-service dependency graph |
357
+
324
358
  ## Custom Tools
325
359
 
326
360
  ```python
@@ -373,6 +407,12 @@ cd demo && python app.py
373
407
 
374
408
  [![debug-agent-py](https://img.shields.io/pypi/v/debug-agent-py.svg)](https://pypi.org/project/debug-agent-py/)
375
409
 
410
+ ## Built With
411
+
412
+ [![ggcode](https://img.shields.io/badge/built%20with-ggcode-blue)](https://github.com/topcheer/ggcode)
413
+
414
+ This project was built using [ggcode](https://github.com/topcheer/ggcode) — an AI coding assistant for terminal-based development.
415
+
376
416
  ## License
377
417
 
378
418
  MIT
@@ -1,12 +1,12 @@
1
1
  # Python Debug Agent
2
2
 
3
3
  [![debug-agent-py](https://img.shields.io/pypi/v/debug-agent-py.svg)](https://pypi.org/project/debug-agent-py/)
4
- ![Tools](https://img.shields.io/badge/tools-99-blue)
5
- ![Inspectors](https://img.shields.io/badge/inspectors-33-green)
4
+ ![Tools](https://img.shields.io/badge/tools-113-blue)
5
+ ![Inspectors](https://img.shields.io/badge/inspectors-38-green)
6
6
  ![Python](https://img.shields.io/badge/Python-3.9%2B-3776AB)
7
7
  ![PyPI](https://img.shields.io/badge/PyPI-debug--agent--py-3776AB)
8
8
 
9
- An AI-powered runtime debugging agent that embeds directly into your Python web application. Add one dependency, configure an LLM key, and chat with your live app at `/agent` to inspect memory, threads, GC, modules, database connections, Redis, Django models/URLs, Celery tasks, Flask extensions, Jinja2 templates, signals, routes, HTTP requests, and more — **99 diagnostic tools across 33 inspectors**.
9
+ An AI-powered runtime debugging agent that embeds directly into your Python web application. Add one dependency, configure an LLM key, and chat with your live app at `/agent` to inspect memory, threads, GC, modules, database connections, Redis, Django models/URLs, Celery tasks, Flask extensions, Jinja2 templates, signals, routes, HTTP requests, and more — **113 diagnostic tools across 38 inspectors**.
10
10
 
11
11
  ## Version Support
12
12
 
@@ -64,11 +64,11 @@ http://localhost:8000/agent
64
64
  - **Context compression** — automatically summarizes old conversation when token limit is approached
65
65
  - **Dark-themed chat UI** with full markdown rendering (tables, code blocks, lists)
66
66
  - **Max tool rounds** (25) with forced final summary when limit is reached
67
- - **99 diagnostic tools** across **33 inspectors**
67
+ - **113 diagnostic tools** across **38 inspectors**
68
68
  - Works with Flask, FastAPI, and Django
69
69
  - Zero external dependencies (no Datadog, no Grafana, no APM)
70
70
 
71
- ## Inspectors & Tools (99)
71
+ ## Inspectors & Tools (113)
72
72
 
73
73
  ### Memory Inspector
74
74
  | Tool | Description |
@@ -270,6 +270,40 @@ http://localhost:8000/agent
270
270
  | `detect_pool_leaks` | Heuristic leak detection (growing pool, high wait ratio, saturation) |
271
271
  | `get_pool_wait_stats` | Connection acquire wait stats (avg, P95, max wait, timeout count) |
272
272
 
273
+ ### CPU Profiler Inspector (v0.7.0)
274
+ | Tool | Description |
275
+ |------|-------------|
276
+ | `start_cpu_profile` | Start a CPU profiling session (cProfile/yappi) |
277
+ | `stop_cpu_profile` | Stop CPU profiling and return collected profile data |
278
+ | `get_top_functions` | Get top CPU-consuming functions from the current profile |
279
+
280
+ ### Memory Leak Detector Inspector (v0.7.0)
281
+ | Tool | Description |
282
+ |------|-------------|
283
+ | `take_heap_snapshot` | Capture a heap snapshot for leak analysis (tracemalloc) |
284
+ | `compare_heap_snapshots` | Compare two heap snapshots to identify object growth |
285
+ | `get_leak_candidates` | Identify objects likely to be memory leaks |
286
+
287
+ ### Deployment/Build Info Inspector (v0.7.0)
288
+ | Tool | Description |
289
+ |------|-------------|
290
+ | `get_build_info` | Build version, commit hash, and package metadata |
291
+ | `get_deployment_info` | Deployment environment, container, and orchestration metadata |
292
+ | `get_runtime_version` | Python interpreter version and implementation details |
293
+
294
+ ### Snapshot & Diff Inspector (v0.7.0)
295
+ | Tool | Description |
296
+ |------|-------------|
297
+ | `take_snapshot` | Capture a runtime state snapshot |
298
+ | `compare_snapshots` | Compare two snapshots to identify state changes |
299
+ | `list_snapshots` | List all saved snapshots with timestamps |
300
+
301
+ ### Service Registry Inspector (v0.7.0)
302
+ | Tool | Description |
303
+ |------|-------------|
304
+ | `get_registered_services` | List all registered application services |
305
+ | `get_service_dependencies` | Map service-to-service dependency graph |
306
+
273
307
  ## Custom Tools
274
308
 
275
309
  ```python
@@ -322,6 +356,12 @@ cd demo && python app.py
322
356
 
323
357
  [![debug-agent-py](https://img.shields.io/pypi/v/debug-agent-py.svg)](https://pypi.org/project/debug-agent-py/)
324
358
 
359
+ ## Built With
360
+
361
+ [![ggcode](https://img.shields.io/badge/built%20with-ggcode-blue)](https://github.com/topcheer/ggcode)
362
+
363
+ This project was built using [ggcode](https://github.com/topcheer/ggcode) — an AI coding assistant for terminal-based development.
364
+
325
365
  ## License
326
366
 
327
367
  MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "debug-agent-py"
7
- version = "0.6.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"}
@@ -2,6 +2,24 @@ 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('')
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
+
5
23
  from debug_agent.config import AgentConfig
6
24
  from debug_agent.tool_registry import debug_tool, ToolParam, registry
7
25
  from debug_agent.engine import DebugEngine, ChatCallback
@@ -10,11 +28,10 @@ from debug_agent.system_prompt_builder import SystemPromptBuilder
10
28
  from debug_agent.context_compressor import ContextCompressor, CompressionResult
11
29
  from debug_agent.llm_client import LLMClient, StreamHandler
12
30
 
13
- __version__ = "0.1.0"
14
31
  __all__ = [
15
32
  "AgentConfig", "debug_tool", "ToolParam", "registry", "DebugEngine", "ChatCallback",
16
33
  "ChatSession", "SystemPromptBuilder", "ContextCompressor", "CompressionResult",
17
- "LLMClient", "StreamHandler", "setup",
34
+ "LLMClient", "StreamHandler", "setup", "__version__",
18
35
  ]
19
36
 
20
37
 
@@ -2,8 +2,10 @@
2
2
 
3
3
  from debug_agent.inspectors import ( # noqa: F401
4
4
  async_tasks,
5
+ build_info_inspector,
5
6
  cache_inspector,
6
7
  celery,
8
+ cpu_profile_inspector,
7
9
  config_inspector,
8
10
  database,
9
11
  django,
@@ -18,6 +20,7 @@ from debug_agent.inspectors import ( # noqa: F401
18
20
  http_client_inspector,
19
21
  http_tracker,
20
22
  jinja2,
23
+ leak_detector_inspector,
21
24
  locks_inspector,
22
25
  logging_inspector,
23
26
  memory,
@@ -29,7 +32,9 @@ from debug_agent.inspectors import ( # noqa: F401
29
32
  runtime,
30
33
  scheduler_inspector,
31
34
  security_inspector,
35
+ service_registry_inspector,
32
36
  signals,
37
+ snapshot_inspector,
33
38
  system,
34
39
  threads,
35
40
  warnings_inspector,
@@ -0,0 +1,193 @@
1
+ """Build / deployment info inspector: Python build details, runtime versions, deployment metadata."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import platform
7
+ import socket
8
+ import sys
9
+ import time
10
+ from typing import Any
11
+
12
+ from debug_agent.tool_registry import debug_tool, ToolParam
13
+
14
+
15
+ # ─── Helpers ──────────────────────────────────────────────────────────────────
16
+
17
+
18
+ _PROCESS_START = time.time()
19
+
20
+
21
+ _ENV_VARS_OF_INTEREST = [
22
+ "APP_ENV",
23
+ "FLASK_ENV",
24
+ "DJANGO_SETTINGS_MODULE",
25
+ "NODE_ENV",
26
+ "ENVIRONMENT",
27
+ "STAGE",
28
+ ]
29
+
30
+
31
+ _RUNTIME_DEPS = [
32
+ "flask",
33
+ "django",
34
+ "fastapi",
35
+ "sqlalchemy",
36
+ "redis",
37
+ "celery",
38
+ "psycopg2",
39
+ "pymongo",
40
+ "uvicorn",
41
+ "gunicorn",
42
+ "requests",
43
+ "aiohttp",
44
+ "pydantic",
45
+ ]
46
+
47
+
48
+ def _detect_container() -> dict[str, Any]:
49
+ """Detect whether the process runs inside a container."""
50
+ container_type = None
51
+
52
+ if os.path.exists("/.dockerenv"):
53
+ container_type = "docker"
54
+ elif os.path.exists("/run/.containerenv"):
55
+ container_type = "podman"
56
+ else:
57
+ try:
58
+ with open("/proc/1/cgroup", "r") as f:
59
+ content = f.read()
60
+ if "docker" in content:
61
+ container_type = "docker"
62
+ elif "kubepods" in content:
63
+ container_type = "kubernetes"
64
+ elif "lxc" in content:
65
+ container_type = "lxc"
66
+ except (FileNotFoundError, IOError, OSError):
67
+ pass
68
+
69
+ return {
70
+ "in_container": container_type is not None,
71
+ "container_type": container_type,
72
+ }
73
+
74
+
75
+ def _get_uptime() -> float:
76
+ """Return process uptime in seconds."""
77
+ return round(time.time() - _PROCESS_START, 2)
78
+
79
+
80
+ def _get_package_versions() -> dict[str, str | None]:
81
+ """Return versions of installed packages via importlib.metadata."""
82
+ try:
83
+ from importlib.metadata import version as get_version, PackageNotFoundError
84
+ except ImportError:
85
+ return {}
86
+
87
+ result = {}
88
+ for pkg in _RUNTIME_DEPS:
89
+ try:
90
+ result[pkg] = get_version(pkg)
91
+ except PackageNotFoundError:
92
+ pass
93
+ except Exception:
94
+ pass
95
+ return result
96
+
97
+
98
+ # ─── Tools ────────────────────────────────────────────────────────────────────
99
+
100
+
101
+ @debug_tool(
102
+ "get_build_info",
103
+ "Get Python build details: version, implementation, build date, compiler, C API version",
104
+ )
105
+ def get_build_info() -> dict:
106
+ info: dict[str, Any] = {
107
+ "python_version": sys.version,
108
+ "version_info": {
109
+ "major": sys.version_info[0],
110
+ "minor": sys.version_info[1],
111
+ "micro": sys.version_info[2],
112
+ "releaselevel": sys.version_info[3],
113
+ "serial": sys.version_info[4],
114
+ },
115
+ "implementation": platform.python_implementation(),
116
+ "compiler": platform.python_compiler(),
117
+ "build_date": platform.python_build()[1] if len(platform.python_build()) > 1 else None,
118
+ "build_info_raw": platform.python_build()[0] if platform.python_build() else None,
119
+ "api_version": sys.api_version,
120
+ "hexversion": hex(sys.hexversion),
121
+ }
122
+
123
+ # C API version
124
+ try:
125
+ info["c_api_version"] = sys.api_version
126
+ except AttributeError:
127
+ pass
128
+
129
+ # Try to get installed package versions
130
+ pkg_versions = _get_package_versions()
131
+ if pkg_versions:
132
+ info["installed_packages"] = pkg_versions
133
+
134
+ return info
135
+
136
+
137
+ @debug_tool(
138
+ "get_deployment_info",
139
+ "Get deployment metadata: hostname, PID, uptime, container detection, platform, selected env vars",
140
+ )
141
+ def get_deployment_info() -> dict:
142
+ container = _detect_container()
143
+
144
+ selected_env: dict[str, str | None] = {}
145
+ for var in _ENV_VARS_OF_INTEREST:
146
+ selected_env[var] = os.environ.get(var)
147
+
148
+ return {
149
+ "hostname": socket.gethostname(),
150
+ "pid": os.getpid(),
151
+ "ppid": os.getppid(),
152
+ "uptime_seconds": _get_uptime(),
153
+ "platform": platform.platform(),
154
+ "architecture": platform.machine(),
155
+ "processor": platform.processor() or None,
156
+ "container_detected": container["in_container"],
157
+ "container_type": container["container_type"],
158
+ "working_directory": os.getcwd(),
159
+ "user": os.environ.get("USER") or os.environ.get("USERNAME"),
160
+ "environment_variables": {k: v for k, v in selected_env.items() if v is not None},
161
+ }
162
+
163
+
164
+ @debug_tool(
165
+ "get_runtime_version",
166
+ "Get versions of key runtime dependencies (flask, django, fastapi, sqlalchemy, redis, celery, etc.)",
167
+ )
168
+ def get_runtime_version() -> dict:
169
+ pkg_versions = _get_package_versions()
170
+
171
+ # Also try importing for modules that expose __version__
172
+ import_versions: dict[str, str | None] = {}
173
+ for dep in _RUNTIME_DEPS:
174
+ mod = sys.modules.get(dep)
175
+ if mod is not None:
176
+ ver = getattr(mod, "__version__", None)
177
+ if ver:
178
+ import_versions[dep] = ver
179
+
180
+ # Merge: prefer importlib.metadata, fall back to __version__
181
+ merged: dict[str, str | None] = {}
182
+ for dep in _RUNTIME_DEPS:
183
+ merged[dep] = pkg_versions.get(dep) or import_versions.get(dep)
184
+
185
+ installed = {k: v for k, v in merged.items() if v is not None}
186
+ not_installed = [k for k, v in merged.items() if v is None]
187
+
188
+ return {
189
+ "installed": installed,
190
+ "not_installed": not_installed,
191
+ "total_checked": len(_RUNTIME_DEPS),
192
+ "total_installed": len(installed),
193
+ }
@@ -0,0 +1,160 @@
1
+ """CPU profiler inspector: cProfile-based profiling with auto-stop and top-function analysis."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import cProfile
6
+ import io
7
+ import pstats
8
+ import threading
9
+ import time
10
+ from typing import Any
11
+
12
+ from debug_agent.tool_registry import debug_tool, ToolParam
13
+
14
+
15
+ # ─── Module-level state ───────────────────────────────────────────────────────
16
+
17
+ _profiler: cProfile.Profile | None = None
18
+ _last_stats: pstats.Stats | None = None
19
+ _timer: threading.Timer | None = None
20
+ _lock = threading.Lock()
21
+
22
+
23
+ # ─── Helpers ──────────────────────────────────────────────────────────────────
24
+
25
+
26
+ def _auto_stop() -> None:
27
+ """Auto-stop callback scheduled by ``threading.Timer``."""
28
+ global _profiler, _last_stats
29
+ with _lock:
30
+ if _profiler is not None:
31
+ try:
32
+ _profiler.disable()
33
+ except Exception:
34
+ pass
35
+ _last_stats = pstats.Stats(_profiler)
36
+ _profiler = None
37
+
38
+
39
+ def _extract_functions(stats: pstats.Stats, limit: int, sort_by: str) -> list[dict[str, Any]]:
40
+ """Extract top-N function entries from pstats as a list of dicts."""
41
+ sort_key_map = {
42
+ "cumulative": pstats.SortKey.CUMULATIVE,
43
+ "self": pstats.SortKey.TIME,
44
+ "calls": pstats.SortKey.CALLS,
45
+ }
46
+ key = sort_key_map.get(sort_by, pstats.SortKey.CUMULATIVE)
47
+ stats.sort_stats(key)
48
+
49
+ functions: list[dict[str, Any]] = []
50
+ for func, (cc, nc, tt, ct, callers) in stats.stats.items(): # type: ignore[attr-defined]
51
+ filename, line_no, func_name = func
52
+ functions.append({
53
+ "function": func_name,
54
+ "file": filename,
55
+ "line": line_no,
56
+ "cumulative_time": round(ct, 6),
57
+ "self_time": round(tt, 6),
58
+ "calls": nc,
59
+ "per_call_time": round(ct / nc, 6) if nc else 0,
60
+ })
61
+ if len(functions) >= limit:
62
+ break
63
+
64
+ return functions
65
+
66
+
67
+ # ─── Tools ────────────────────────────────────────────────────────────────────
68
+
69
+
70
+ @debug_tool(
71
+ "start_cpu_profile",
72
+ "Start CPU profiling with cProfile. Auto-stops after duration_seconds.",
73
+ {"duration_seconds": ToolParam("Auto-stop duration in seconds", required=False)},
74
+ )
75
+ def start_cpu_profile(
76
+ duration_seconds: int = ToolParam("Auto-stop duration in seconds", required=False),
77
+ ) -> dict:
78
+ global _profiler, _timer
79
+ with _lock:
80
+ if _profiler is not None:
81
+ return {"error": "Profiling already in progress. Call stop_cpu_profile first."}
82
+
83
+ _profiler = cProfile.Profile()
84
+ _profiler.enable()
85
+
86
+ duration = duration_seconds if duration_seconds and duration_seconds > 0 else 10
87
+ _timer = threading.Timer(duration, _auto_stop)
88
+ _timer.daemon = True
89
+ _timer.start()
90
+
91
+ return {
92
+ "status": "profiling started",
93
+ "duration_seconds": duration,
94
+ "message": f"CPU profiling started, will auto-stop in {duration}s.",
95
+ }
96
+
97
+
98
+ @debug_tool(
99
+ "stop_cpu_profile",
100
+ "Stop active CPU profiling and return top 20 functions sorted by cumulative time",
101
+ )
102
+ def stop_cpu_profile() -> dict:
103
+ global _profiler, _last_stats, _timer
104
+
105
+ with _lock:
106
+ # Cancel pending auto-stop if user stops manually
107
+ if _timer is not None:
108
+ _timer.cancel()
109
+ _timer = None
110
+
111
+ if _profiler is None and _last_stats is None:
112
+ return {"error": "No active profiling session. Call start_cpu_profile first."}
113
+
114
+ if _profiler is not None:
115
+ try:
116
+ _profiler.disable()
117
+ except Exception:
118
+ pass
119
+ _last_stats = pstats.Stats(_profiler)
120
+ _profiler = None
121
+
122
+ if _last_stats is None:
123
+ return {"error": "No profiling data available."}
124
+
125
+ top = _extract_functions(_last_stats, 20, "cumulative")
126
+ total_calls = _last_stats.total_calls # type: ignore[attr-defined]
127
+
128
+ return {
129
+ "status": "stopped",
130
+ "total_calls": total_calls,
131
+ "top_functions": top,
132
+ }
133
+
134
+
135
+ @debug_tool(
136
+ "get_top_functions",
137
+ "Return top N functions from the last CPU profile with configurable sort",
138
+ {
139
+ "limit": ToolParam("Max number of functions to return", required=False),
140
+ "sort_by": ToolParam("Sort key: cumulative, self, or calls", required=False),
141
+ },
142
+ )
143
+ def get_top_functions(
144
+ limit: int = ToolParam("Max number of functions to return", required=False),
145
+ sort_by: str = ToolParam("Sort key: cumulative, self, or calls", required=False),
146
+ ) -> dict:
147
+ global _last_stats
148
+
149
+ if _last_stats is None:
150
+ return {"error": "No profiling data available. Run start_cpu_profile then stop_cpu_profile first."}
151
+
152
+ n = limit if limit and limit > 0 else 20
153
+ sb = sort_by if sort_by in ("cumulative", "self", "calls") else "cumulative"
154
+
155
+ top = _extract_functions(_last_stats, n, sb)
156
+ return {
157
+ "sort_by": sb,
158
+ "limit": n,
159
+ "functions": top,
160
+ }