debug-agent-py 0.4.0__tar.gz → 0.5.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 (48) hide show
  1. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/PKG-INFO +19 -3
  2. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/README.md +18 -2
  3. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/pyproject.toml +1 -1
  4. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/__init__.py +2 -0
  5. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/inspectors/__init__.py +5 -0
  6. debug_agent_py-0.5.1/src/debug_agent/inspectors/error_tracking.py +205 -0
  7. debug_agent_py-0.5.1/src/debug_agent/inspectors/health_inspector.py +124 -0
  8. debug_agent_py-0.5.1/src/debug_agent/inspectors/scheduler_inspector.py +227 -0
  9. debug_agent_py-0.5.1/src/debug_agent/inspectors/security_inspector.py +251 -0
  10. debug_agent_py-0.5.1/src/debug_agent/inspectors/websocket_inspector.py +225 -0
  11. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent_py.egg-info/PKG-INFO +19 -3
  12. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent_py.egg-info/SOURCES.txt +5 -0
  13. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/setup.cfg +0 -0
  14. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/chat_session.py +0 -0
  15. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/config.py +0 -0
  16. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/context_compressor.py +0 -0
  17. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/engine.py +0 -0
  18. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/inspectors/async_tasks.py +0 -0
  19. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/inspectors/cache_inspector.py +0 -0
  20. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/inspectors/celery.py +0 -0
  21. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/inspectors/database.py +0 -0
  22. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/inspectors/django.py +0 -0
  23. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/inspectors/fastapi_ext.py +0 -0
  24. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/inspectors/fd_inspector.py +0 -0
  25. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/inspectors/flask_ext.py +0 -0
  26. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/inspectors/framework.py +0 -0
  27. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/inspectors/http_client_inspector.py +0 -0
  28. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/inspectors/http_tracker.py +0 -0
  29. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/inspectors/jinja2.py +0 -0
  30. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/inspectors/logging_inspector.py +0 -0
  31. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/inspectors/memory.py +0 -0
  32. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/inspectors/metrics_inspector.py +0 -0
  33. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/inspectors/modules.py +0 -0
  34. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/inspectors/redis.py +0 -0
  35. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/inspectors/runtime.py +0 -0
  36. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/inspectors/signals.py +0 -0
  37. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/inspectors/system.py +0 -0
  38. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/inspectors/threads.py +0 -0
  39. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/inspectors/warnings_inspector.py +0 -0
  40. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/llm_client.py +0 -0
  41. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/middleware.py +0 -0
  42. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/system_prompt_builder.py +0 -0
  43. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/tool_registry.py +0 -0
  44. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/web/__init__.py +0 -0
  45. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent/web/chat_page.py +0 -0
  46. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent_py.egg-info/dependency_links.txt +0 -0
  47. {debug_agent_py-0.4.0 → debug_agent_py-0.5.1}/src/debug_agent_py.egg-info/requires.txt +0 -0
  48. {debug_agent_py-0.4.0 → debug_agent_py-0.5.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.4.0
3
+ Version: 0.5.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,11 +52,27 @@ 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-68-blue)
56
- ![Inspectors](https://img.shields.io/badge/inspectors-24-green)
55
+ ![Tools](https://img.shields.io/badge/tools-82-blue)
56
+ ![Inspectors](https://img.shields.io/badge/inspectors-27-green)
57
+ ![Python](https://img.shields.io/badge/Python-3.9%2B-3776AB)
58
+ ![PyPI](https://img.shields.io/badge/PyPI-debug--agent--py-3776AB)
57
59
 
58
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 — **68 diagnostic tools across 24 inspectors**.
59
61
 
62
+ ## Version Support
63
+
64
+ | Python Version | Status |
65
+ |----------------|--------|
66
+ | 3.8 | Not supported |
67
+ | 3.9 | Minimum supported |
68
+ | 3.10 | Supported |
69
+ | 3.11 | Supported |
70
+ | 3.12 | Supported |
71
+ | 3.13 | Supported |
72
+ | 3.14 | Tested |
73
+
74
+ > Uses `from __future__ import annotations` so `X | Y` union types work on Python 3.9+. Optional dependencies (Flask, SQLAlchemy, Redis, Celery) are not required at install time.
75
+
60
76
  ## Quick Start
61
77
 
62
78
  ### 1. Install
@@ -1,11 +1,27 @@
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-68-blue)
5
- ![Inspectors](https://img.shields.io/badge/inspectors-24-green)
4
+ ![Tools](https://img.shields.io/badge/tools-82-blue)
5
+ ![Inspectors](https://img.shields.io/badge/inspectors-27-green)
6
+ ![Python](https://img.shields.io/badge/Python-3.9%2B-3776AB)
7
+ ![PyPI](https://img.shields.io/badge/PyPI-debug--agent--py-3776AB)
6
8
 
7
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 — **68 diagnostic tools across 24 inspectors**.
8
10
 
11
+ ## Version Support
12
+
13
+ | Python Version | Status |
14
+ |----------------|--------|
15
+ | 3.8 | Not supported |
16
+ | 3.9 | Minimum supported |
17
+ | 3.10 | Supported |
18
+ | 3.11 | Supported |
19
+ | 3.12 | Supported |
20
+ | 3.13 | Supported |
21
+ | 3.14 | Tested |
22
+
23
+ > Uses `from __future__ import annotations` so `X | Y` union types work on Python 3.9+. Optional dependencies (Flask, SQLAlchemy, Redis, Celery) are not required at install time.
24
+
9
25
  ## Quick Start
10
26
 
11
27
  ### 1. Install
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "debug-agent-py"
7
- version = "0.4.0"
7
+ version = "0.5.1"
8
8
  description = "AI-powered runtime debugging agent for Python web applications"
9
9
  readme = "README.md"
10
10
  license = {text = "MIT"}
@@ -1,3 +1,5 @@
1
+ from __future__ import annotations
2
+
1
3
  """Debug Agent — AI-powered runtime debugging for Python applications."""
2
4
 
3
5
  from debug_agent.config import AgentConfig
@@ -6,10 +6,12 @@ from debug_agent.inspectors import ( # noqa: F401
6
6
  celery,
7
7
  database,
8
8
  django,
9
+ error_tracking,
9
10
  fastapi_ext,
10
11
  fd_inspector,
11
12
  flask_ext,
12
13
  framework,
14
+ health_inspector,
13
15
  http_client_inspector,
14
16
  http_tracker,
15
17
  jinja2,
@@ -19,8 +21,11 @@ from debug_agent.inspectors import ( # noqa: F401
19
21
  modules,
20
22
  redis,
21
23
  runtime,
24
+ scheduler_inspector,
25
+ security_inspector,
22
26
  signals,
23
27
  system,
24
28
  threads,
25
29
  warnings_inspector,
30
+ websocket_inspector,
26
31
  )
@@ -0,0 +1,205 @@
1
+ """Error tracking inspector: capture and analyse unhandled exceptions.
2
+
3
+ Installs a global ``sys.excepthook`` and provides helpers to hook into
4
+ Flask / WSGI for request-scoped errors. A ring buffer (max 50) keeps the
5
+ most recent exceptions for inspection.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import sys
12
+ import threading
13
+ import time
14
+ import traceback as tb_mod
15
+ from collections import Counter, deque
16
+ from datetime import datetime, timezone
17
+ from typing import Any
18
+
19
+ from debug_agent.tool_registry import debug_tool, ToolParam
20
+
21
+
22
+ # ─── Ring buffer & state ──────────────────────────────────────────────────────
23
+
24
+ _MAX_BUFFER = 50
25
+ _error_buffer: deque = deque(maxlen=_MAX_BUFFER)
26
+ _buffer_lock = threading.Lock()
27
+ _original_excepthook = sys.excepthook
28
+ _installed = False
29
+
30
+
31
+ # ─── Capture helpers ──────────────────────────────────────────────────────────
32
+
33
+
34
+ def capture_error(
35
+ exc_type: type,
36
+ value: BaseException,
37
+ tb: Any,
38
+ request_path: str | None = None,
39
+ ) -> None:
40
+ """Append an exception to the ring buffer."""
41
+ entry = {
42
+ "timestamp": datetime.now(timezone.utc).isoformat(),
43
+ "epoch": time.time(),
44
+ "type": exc_type.__name__ if exc_type else "Unknown",
45
+ "message": str(value),
46
+ "traceback": "".join(tb_mod.format_exception(exc_type, value, tb)),
47
+ "request_path": request_path,
48
+ }
49
+ with _buffer_lock:
50
+ _error_buffer.append(entry)
51
+
52
+
53
+ def _excepthook(exc_type, value, tb): # noqa: A002 (tb shadows stdlib name)
54
+ """Replacement sys.excepthook that records the exception before delegating."""
55
+ capture_error(exc_type, value, tb)
56
+ _original_excepthook(exc_type, value, tb)
57
+
58
+
59
+ def install_error_hooks() -> None:
60
+ """Install the global ``sys.excepthook`` override (idempotent)."""
61
+ global _installed
62
+ if _installed:
63
+ return
64
+ sys.excepthook = _excepthook
65
+ _installed = True
66
+
67
+
68
+ def install_flask_error_handler(app: Any) -> None:
69
+ """Register a catch-all Flask error handler that records exceptions."""
70
+ try:
71
+ from flask import request, jsonify # type: ignore
72
+ except ImportError:
73
+ return
74
+
75
+ @app.errorhandler(Exception)
76
+ def _capture_flask_error(e): # noqa: ANN202
77
+ capture_error(
78
+ type(e), e, e.__traceback__,
79
+ request_path=request.path if request else None,
80
+ )
81
+ # Re-raise so existing handlers / Flask defaults still apply
82
+ try:
83
+ return app.handle_exception(e)
84
+ except Exception:
85
+ return jsonify({"error": type(e).__name__, "message": str(e)}), 500
86
+
87
+
88
+ def install_wsgi_middleware(app: Any) -> Any:
89
+ """Wrap a WSGI app so unhandled exceptions are captured."""
90
+
91
+ def middleware(environ, start_response):
92
+ try:
93
+ return app(environ, start_response)
94
+ except Exception as exc:
95
+ capture_error(
96
+ type(exc), exc, exc.__traceback__,
97
+ request_path=environ.get("PATH_INFO"),
98
+ )
99
+ raise
100
+
101
+ return middleware
102
+
103
+
104
+ # Auto-install the global excepthook on import
105
+ install_error_hooks()
106
+
107
+
108
+ # ─── Tools ────────────────────────────────────────────────────────────────────
109
+
110
+
111
+ def _get_all() -> list[dict]:
112
+ with _buffer_lock:
113
+ return list(_error_buffer)
114
+
115
+
116
+ @debug_tool(
117
+ "get_recent_errors",
118
+ "Get recent unhandled exceptions from the in-memory ring buffer (max 50)",
119
+ )
120
+ def get_recent_errors(
121
+ limit: int = ToolParam("Max results to return", required=False),
122
+ ) -> dict:
123
+ errors = _get_all()
124
+ if limit:
125
+ errors = errors[-limit:]
126
+ return {
127
+ "total_captured": len(_error_buffer),
128
+ "buffer_max": _MAX_BUFFER,
129
+ "errors": list(reversed(errors)),
130
+ }
131
+
132
+
133
+ @debug_tool(
134
+ "get_error_stats",
135
+ "Get error statistics: total, rate per minute, top error types",
136
+ )
137
+ def get_error_stats() -> dict:
138
+ errors = _get_all()
139
+ if not errors:
140
+ return {"total": 0, "message": "No errors captured yet"}
141
+
142
+ now = time.time()
143
+ oldest = min(e["epoch"] for e in errors)
144
+ elapsed_minutes = max((now - oldest) / 60, 1 / 60) # avoid div-by-zero
145
+
146
+ type_counts = Counter(e["type"] for e in errors)
147
+
148
+ return {
149
+ "total": len(errors),
150
+ "buffer_max": _MAX_BUFFER,
151
+ "rate_per_minute": round(len(errors) / elapsed_minutes, 2),
152
+ "time_window_minutes": round(elapsed_minutes, 1),
153
+ "top_error_types": type_counts.most_common(10),
154
+ }
155
+
156
+
157
+ @debug_tool(
158
+ "get_error_patterns",
159
+ "Group similar errors by exception type and message pattern",
160
+ )
161
+ def get_error_patterns() -> dict:
162
+ errors = _get_all()
163
+ if not errors:
164
+ return {"patterns": [], "message": "No errors captured yet"}
165
+
166
+ def _normalise_message(msg: str) -> str:
167
+ """Collapse variable parts of an error message for grouping."""
168
+ import re
169
+ # Replace IDs, numbers, hex, file paths, and quoted strings
170
+ msg = re.sub(r"\b[0-9a-f]{8,}\b", "<hex>", msg, flags=re.IGNORECASE)
171
+ msg = re.sub(r"\b\d+\b", "<N>", msg)
172
+ msg = re.sub(r"/[/^\s]+", "<path>", msg)
173
+ msg = re.sub(r"'[^']*'", "'<str>'", msg)
174
+ msg = re.sub(r'"[^"]*"', '"<str>"', msg)
175
+ return msg[:200]
176
+
177
+ groups: dict[str, dict[str, Any]] = {}
178
+ for err in errors:
179
+ pattern_key = f"{err['type']}: {_normalise_message(err['message'])}"
180
+ if pattern_key not in groups:
181
+ groups[pattern_key] = {
182
+ "pattern": pattern_key,
183
+ "count": 0,
184
+ "type": err["type"],
185
+ "example_message": err["message"],
186
+ "first_seen": err["timestamp"],
187
+ "last_seen": err["timestamp"],
188
+ "request_paths": set(),
189
+ }
190
+ g = groups[pattern_key]
191
+ g["count"] += 1
192
+ g["last_seen"] = err["timestamp"]
193
+ if err.get("request_path"):
194
+ g["request_paths"].add(err["request_path"])
195
+
196
+ # Sort by count desc and convert sets to lists
197
+ sorted_groups = sorted(groups.values(), key=lambda x: -x["count"])
198
+ for g in sorted_groups:
199
+ g["request_paths"] = sorted(g["request_paths"])
200
+
201
+ return {
202
+ "pattern_count": len(sorted_groups),
203
+ "total_errors": len(errors),
204
+ "patterns": sorted_groups,
205
+ }
@@ -0,0 +1,124 @@
1
+ """Health inspector: pluggable health checks with UP / DOWN / DEGRADED status.
2
+
3
+ Register health checks via decorator:
4
+
5
+ from debug_agent.inspectors.health_inspector import register_health_check
6
+
7
+ @register_health_check("database")
8
+ def check_database():
9
+ # ... run check ...
10
+ return {"status": "UP", "details": {"latency_ms": 2.1}}
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import time
16
+ from typing import Any, Callable
17
+
18
+ from debug_agent.tool_registry import debug_tool, ToolParam
19
+
20
+
21
+ # ─── Registration ─────────────────────────────────────────────────────────────
22
+
23
+ _health_checks: dict[str, Callable[..., Any]] = {}
24
+
25
+
26
+ def register_health_check(name: str):
27
+ """Decorator: register *fn* as a health check under *name*."""
28
+
29
+ def decorator(fn: Callable[..., Any]) -> Callable[..., Any]:
30
+ _health_checks[name] = fn
31
+ return fn
32
+
33
+ return decorator
34
+
35
+
36
+ # ─── Helpers ──────────────────────────────────────────────────────────────────
37
+
38
+
39
+ _VALID_STATUSES = {"UP", "DOWN", "DEGRADED"}
40
+
41
+
42
+ def _run_check(name: str, fn: Callable[..., Any]) -> dict:
43
+ start = time.time()
44
+ try:
45
+ result = fn()
46
+ elapsed_ms = round((time.time() - start) * 1000, 2)
47
+
48
+ if isinstance(result, dict):
49
+ status = str(result.get("status", "UP")).upper()
50
+ if status not in _VALID_STATUSES:
51
+ status = "UP"
52
+ return {
53
+ "name": name,
54
+ "status": status,
55
+ "latency_ms": elapsed_ms,
56
+ "details": result.get("details", {k: v for k, v in result.items() if k != "status"}),
57
+ }
58
+
59
+ # Non-dict truthy / falsy results
60
+ if result in _VALID_STATUSES:
61
+ status = result
62
+ elif result:
63
+ status = "UP"
64
+ else:
65
+ status = "DOWN"
66
+ return {"name": name, "status": status, "latency_ms": elapsed_ms}
67
+
68
+ except Exception as exc:
69
+ elapsed_ms = round((time.time() - start) * 1000, 2)
70
+ return {
71
+ "name": name,
72
+ "status": "DOWN",
73
+ "latency_ms": elapsed_ms,
74
+ "error": f"{type(exc).__name__}: {exc}",
75
+ }
76
+
77
+
78
+ # ─── Tools ────────────────────────────────────────────────────────────────────
79
+
80
+
81
+ @debug_tool(
82
+ "get_health_status",
83
+ "Run all registered health checks and return UP/DOWN/DEGRADED per component",
84
+ )
85
+ def get_health_status() -> dict:
86
+ if not _health_checks:
87
+ return {
88
+ "components": [],
89
+ "overall": "UNKNOWN",
90
+ "message": "No health checks registered. Use @register_health_check(name).",
91
+ }
92
+
93
+ results = [_run_check(name, fn) for name, fn in _health_checks.items()]
94
+
95
+ statuses = [r["status"] for r in results]
96
+ if all(s == "UP" for s in statuses):
97
+ overall = "UP"
98
+ elif any(s == "DOWN" for s in statuses):
99
+ overall = "DOWN"
100
+ else:
101
+ overall = "DEGRADED"
102
+
103
+ return {
104
+ "overall": overall,
105
+ "components_checked": len(results),
106
+ "components": results,
107
+ }
108
+
109
+
110
+ @debug_tool(
111
+ "get_health_detail",
112
+ "Deep-dive into a specific health check component",
113
+ )
114
+ def get_health_detail(
115
+ component_name: str = ToolParam("Name of the health check component to inspect"),
116
+ ) -> dict:
117
+ fn = _health_checks.get(component_name)
118
+ if fn is None:
119
+ return {
120
+ "error": f"No health check registered for '{component_name}'",
121
+ "available": list(_health_checks.keys()),
122
+ }
123
+
124
+ return _run_check(component_name, fn)
@@ -0,0 +1,227 @@
1
+ """Scheduler inspector: scheduled jobs from APScheduler, Celery beat, or custom.
2
+
3
+ Register custom scheduled jobs at runtime:
4
+
5
+ from debug_agent.inspectors.scheduler_inspector import register_scheduled_job
6
+ register_scheduled_job("cleanup", "every 30s")
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from datetime import datetime, timezone
12
+ from typing import Any
13
+
14
+ from debug_agent.tool_registry import debug_tool, ToolParam
15
+
16
+
17
+ # ─── Registration ─────────────────────────────────────────────────────────────
18
+
19
+ _scheduled_jobs: dict[str, dict[str, Any]] = {}
20
+
21
+
22
+ def register_scheduled_job(name: str, schedule: str, job_fn=None) -> None:
23
+ """Register a scheduled job for introspection.
24
+
25
+ *schedule* is a human-readable string (e.g. ``"every 30s"``, ``"*/5 * * * *"``).
26
+ *job_fn* is optional — pass the actual callable for richer introspection.
27
+ """
28
+ _scheduled_jobs[name] = {
29
+ "schedule": schedule,
30
+ "next_run": None,
31
+ "last_run": None,
32
+ "last_status": None,
33
+ "history": [],
34
+ "job_fn": job_fn,
35
+ }
36
+
37
+
38
+ def record_job_run(name: str, status: str, details: Any = None) -> None:
39
+ """Record an execution for a registered job (call from the scheduler loop)."""
40
+ job = _scheduled_jobs.get(name)
41
+ if job is None:
42
+ return
43
+ now = datetime.now(timezone.utc).isoformat()
44
+ job["last_run"] = now
45
+ job["last_status"] = status
46
+ job["history"].append({"timestamp": now, "status": status, "details": details})
47
+ # Cap history to last 100 runs
48
+ if len(job["history"]) > 100:
49
+ job["history"] = job["history"][-100:]
50
+
51
+
52
+ def set_next_run(name: str, next_run: str | None) -> None:
53
+ """Update the *next_run* timestamp for a registered job."""
54
+ job = _scheduled_jobs.get(name)
55
+ if job is not None:
56
+ job["next_run"] = next_run
57
+
58
+
59
+ # ─── Framework auto-detection ─────────────────────────────────────────────────
60
+
61
+
62
+ def _detect_apscheduler() -> list[dict] | None:
63
+ try:
64
+ from apscheduler.schedulers.base import BaseScheduler # type: ignore
65
+
66
+ results: list[dict] = []
67
+ for scheduler in _find_instances(BaseScheduler):
68
+ for job in scheduler.get_jobs(): # type: ignore[attr-defined]
69
+ results.append({
70
+ "name": str(job.id),
71
+ "schedule": str(job.trigger),
72
+ "next_run": job.next_run_time.isoformat() if job.next_run_time else None,
73
+ "func": str(job.func),
74
+ "source": "APScheduler",
75
+ })
76
+ return results if results else None
77
+ except Exception:
78
+ return None
79
+
80
+
81
+ def _detect_celery_beat() -> list[dict] | None:
82
+ try:
83
+ from celery import Celery # type: ignore
84
+
85
+ results: list[dict] = []
86
+ for app in _find_instances(Celery):
87
+ beat = getattr(app.conf, "beat_schedule", None)
88
+ if not beat:
89
+ continue
90
+ for task_name, entry in beat.items():
91
+ results.append({
92
+ "name": task_name,
93
+ "schedule": str(entry.get("schedule", "")),
94
+ "task": entry.get("task", ""),
95
+ "source": "Celery Beat",
96
+ })
97
+ return results if results else None
98
+ except Exception:
99
+ return None
100
+
101
+
102
+ def _find_instances(base_cls: type) -> list:
103
+ """Scan gc objects for live instances of *base_cls* (best-effort)."""
104
+ try:
105
+ import gc
106
+ return [obj for obj in gc.get_objects() if isinstance(obj, base_cls)]
107
+ except Exception:
108
+ return []
109
+
110
+
111
+ # ─── Tools ────────────────────────────────────────────────────────────────────
112
+
113
+
114
+ @debug_tool(
115
+ "get_scheduled_jobs",
116
+ "List scheduled jobs from APScheduler, Celery beat, or custom registrations",
117
+ )
118
+ def get_scheduled_jobs() -> dict:
119
+ jobs: list[dict] = []
120
+
121
+ # Registered custom jobs
122
+ for name, job in _scheduled_jobs.items():
123
+ jobs.append({
124
+ "name": name,
125
+ "schedule": job.get("schedule"),
126
+ "next_run": job.get("next_run"),
127
+ "last_run": job.get("last_run"),
128
+ "last_status": job.get("last_status"),
129
+ "source": "custom",
130
+ })
131
+
132
+ # APScheduler
133
+ aps = _detect_apscheduler()
134
+ if aps:
135
+ jobs.extend(aps)
136
+
137
+ # Celery beat
138
+ beat = _detect_celery_beat()
139
+ if beat:
140
+ jobs.extend(beat)
141
+
142
+ if not jobs:
143
+ return {
144
+ "jobs": [],
145
+ "count": 0,
146
+ "message": (
147
+ "No scheduled jobs found. Use register_scheduled_job(name, schedule) "
148
+ "or install APScheduler / configure Celery beat."
149
+ ),
150
+ }
151
+
152
+ return {"count": len(jobs), "jobs": jobs}
153
+
154
+
155
+ @debug_tool(
156
+ "get_job_history",
157
+ "Get execution history for a specific scheduled job",
158
+ )
159
+ def get_job_history(
160
+ job_name: str = ToolParam("Name of the scheduled job"),
161
+ limit: int = ToolParam("Max history entries to return", required=False),
162
+ ) -> dict:
163
+ job = _scheduled_jobs.get(job_name)
164
+ if job is None:
165
+ return {
166
+ "error": f"No custom job registered for '{job_name}'",
167
+ "note": "History is only tracked for jobs registered via register_scheduled_job().",
168
+ "available": list(_scheduled_jobs.keys()),
169
+ }
170
+
171
+ history = job.get("history", [])
172
+ if limit:
173
+ history = history[-limit:]
174
+
175
+ return {
176
+ "job_name": job_name,
177
+ "schedule": job.get("schedule"),
178
+ "last_run": job.get("last_run"),
179
+ "last_status": job.get("last_status"),
180
+ "total_runs": len(job.get("history", [])),
181
+ "history": list(reversed(history)),
182
+ }
183
+
184
+
185
+ # ─── Convenience: execute + record a job on demand ─────────────────────────────
186
+
187
+
188
+ def run_job(name: str) -> Any:
189
+ """Execute a registered job by name, record the outcome, and return its result."""
190
+ job = _scheduled_jobs.get(name)
191
+ if job is None:
192
+ raise KeyError(f"No scheduled job registered for '{name}'")
193
+ fn = job.get("job_fn")
194
+ if fn is None:
195
+ raise ValueError(f"Job '{name}' has no callable attached")
196
+ try:
197
+ result = fn()
198
+ record_job_run(name, "success", details=str(result) if result is not None else None)
199
+ return result
200
+ except Exception:
201
+ import traceback
202
+ record_job_run(name, "failed", details=traceback.format_exc())
203
+ raise
204
+
205
+
206
+ @debug_tool(
207
+ "run_scheduled_job_now",
208
+ "Manually trigger a registered scheduled job and record its result",
209
+ )
210
+ def run_scheduled_job_now(
211
+ job_name: str = ToolParam("Name of the registered scheduled job to trigger"),
212
+ ) -> dict:
213
+ job = _scheduled_jobs.get(job_name)
214
+ if job is None:
215
+ return {
216
+ "error": f"No scheduled job registered for '{job_name}'",
217
+ "available": list(_scheduled_jobs.keys()),
218
+ }
219
+ if job.get("job_fn") is None:
220
+ return {
221
+ "error": f"Job '{job_name}' has no callable attached (metadata-only registration)",
222
+ }
223
+ try:
224
+ result = run_job(job_name)
225
+ return {"job_name": job_name, "status": "success", "result": str(result)}
226
+ except Exception as exc:
227
+ return {"job_name": job_name, "status": "failed", "error": str(exc)}