kestrel-feature-observability 0.1.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.
@@ -0,0 +1,2 @@
1
+ __pycache__/
2
+ *.pyc
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.4
2
+ Name: kestrel-feature-observability
3
+ Version: 0.1.0
4
+ Summary: Lifecycle event observability feature for Kestrel Sovereign — hook-driven logging with shared Prometheus registry
5
+ Project-URL: Homepage, https://kestrelsovereign.com
6
+ Project-URL: Source, https://github.com/KestrelSovereignAI/kestrel-feature-observability
7
+ Project-URL: Issues, https://github.com/KestrelSovereignAI/kestrel-feature-observability/issues
8
+ Author: UncleSaurus
9
+ Maintainer: UncleSaurus
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: agents,ai,kestrel,metrics,observability,prometheus
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: MacOS
16
+ Classifier: Operating System :: Microsoft :: Windows
17
+ Classifier: Operating System :: POSIX :: Linux
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
23
+ Classifier: Topic :: System :: Monitoring
24
+ Requires-Python: <3.14,>=3.11
25
+ Requires-Dist: kestrel-sovereign-sdk<1,>=0.3
26
+ Provides-Extra: metrics
27
+ Requires-Dist: kestrel-sovereign-sdk[metrics]<1,>=0.3; extra == 'metrics'
28
+ Provides-Extra: test
29
+ Requires-Dist: kestrel-sovereign-sdk[metrics]<1,>=0.3; extra == 'test'
30
+ Requires-Dist: pytest-asyncio>=1.1.0; extra == 'test'
31
+ Requires-Dist: pytest>=8.0.0; extra == 'test'
32
+ Description-Content-Type: text/markdown
33
+
34
+ # kestrel-feature-observability
35
+
36
+ Lifecycle event observability for Kestrel Sovereign agents. Attaches an `ObservabilityHook` to the agent's hook system; every lifecycle event is logged to the agent's `observability_store`. Prometheus metrics emit through the SDK's shared registry, so a single `/metrics` scrape stays coherent across the framework + every feature package.
37
+
38
+ ## Installation
39
+
40
+ ```bash
41
+ uv pip install kestrel-feature-observability
42
+ ```
43
+
44
+ For real Prometheus output:
45
+
46
+ ```bash
47
+ uv pip install 'kestrel-feature-observability[metrics]'
48
+ ```
49
+
50
+ The feature is auto-discovered by Kestrel Sovereign via the `kestrel_sovereign.features` entry point — install it alongside `kestrel-sovereign` and `ObservabilityFeature` registers itself at startup.
51
+
52
+ ## Tools
53
+
54
+ | Tool | Category | Description |
55
+ |------|----------|-------------|
56
+ | `observability_summary` | DATA_ACCESS | Recent metric and error counts |
57
+ | `observability_query` | DATA_ACCESS | Query lifecycle events by type and time window |
58
+ | `observability_session` | DATA_ACCESS | Per-session event timeline |
59
+
60
+ ## Privacy
61
+
62
+ The hook is observational — it never blocks, denies, or modifies. User-message content is **not** logged (only length); tool errors are truncated to 200 chars; exceptions in the hook are swallowed so they cannot affect agent operation.
63
+
64
+ ## Dependencies
65
+
66
+ - `kestrel-sovereign-sdk>=0.3,<1` — base `Feature`, `tool`, `ToolCategory`, `Hook`, and shared `metrics` module
67
+ - Optional `[metrics]` extra → `kestrel-sovereign-sdk[metrics]` → `prometheus-client`
68
+
69
+ No runtime dependency on `kestrel-sovereign` itself; the feature accesses `agent.observability_store` via duck typing, so it works against any host that provides one.
70
+
71
+ ## Development
72
+
73
+ ```bash
74
+ uv pip install -e '.[test]'
75
+ uv run pytest
76
+ ```
77
+
78
+ ## License
79
+
80
+ Apache-2.0
@@ -0,0 +1,47 @@
1
+ # kestrel-feature-observability
2
+
3
+ Lifecycle event observability for Kestrel Sovereign agents. Attaches an `ObservabilityHook` to the agent's hook system; every lifecycle event is logged to the agent's `observability_store`. Prometheus metrics emit through the SDK's shared registry, so a single `/metrics` scrape stays coherent across the framework + every feature package.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ uv pip install kestrel-feature-observability
9
+ ```
10
+
11
+ For real Prometheus output:
12
+
13
+ ```bash
14
+ uv pip install 'kestrel-feature-observability[metrics]'
15
+ ```
16
+
17
+ The feature is auto-discovered by Kestrel Sovereign via the `kestrel_sovereign.features` entry point — install it alongside `kestrel-sovereign` and `ObservabilityFeature` registers itself at startup.
18
+
19
+ ## Tools
20
+
21
+ | Tool | Category | Description |
22
+ |------|----------|-------------|
23
+ | `observability_summary` | DATA_ACCESS | Recent metric and error counts |
24
+ | `observability_query` | DATA_ACCESS | Query lifecycle events by type and time window |
25
+ | `observability_session` | DATA_ACCESS | Per-session event timeline |
26
+
27
+ ## Privacy
28
+
29
+ The hook is observational — it never blocks, denies, or modifies. User-message content is **not** logged (only length); tool errors are truncated to 200 chars; exceptions in the hook are swallowed so they cannot affect agent operation.
30
+
31
+ ## Dependencies
32
+
33
+ - `kestrel-sovereign-sdk>=0.3,<1` — base `Feature`, `tool`, `ToolCategory`, `Hook`, and shared `metrics` module
34
+ - Optional `[metrics]` extra → `kestrel-sovereign-sdk[metrics]` → `prometheus-client`
35
+
36
+ No runtime dependency on `kestrel-sovereign` itself; the feature accesses `agent.observability_store` via duck typing, so it works against any host that provides one.
37
+
38
+ ## Development
39
+
40
+ ```bash
41
+ uv pip install -e '.[test]'
42
+ uv run pytest
43
+ ```
44
+
45
+ ## License
46
+
47
+ Apache-2.0
@@ -0,0 +1,34 @@
1
+ """
2
+ Kestrel Feature: Observability — lifecycle event logging via hook system.
3
+
4
+ Extracted from kestrel-sovereign as a standalone feature package.
5
+ Registers ``ObservabilityFeature`` via the ``kestrel_sovereign.features``
6
+ entry-point group; auto-discovered when installed alongside
7
+ kestrel-sovereign.
8
+
9
+ The feature attaches an ``ObservabilityHook`` to the agent's hook
10
+ system. Every lifecycle event is logged to the agent's
11
+ ``observability_store`` (provided by the host framework). All
12
+ mutations of Prometheus metrics happen via ``kestrel_sdk.metrics``,
13
+ so the feature shares the framework's metric registry — a single
14
+ ``/metrics`` scrape stays coherent.
15
+
16
+ Install with the [metrics] extra to enable real Prometheus output:
17
+
18
+ uv pip install 'kestrel-feature-observability[metrics]'
19
+
20
+ Without prometheus-client installed, metric handles are no-ops and
21
+ the hook still logs to the observability store.
22
+ """
23
+
24
+ from importlib.metadata import PackageNotFoundError, version as _version
25
+
26
+ from .feature import ObservabilityFeature
27
+ from .hook import ObservabilityHook
28
+
29
+ try:
30
+ __version__ = _version("kestrel-feature-observability")
31
+ except PackageNotFoundError:
32
+ __version__ = "0.0.0+local"
33
+
34
+ __all__ = ["ObservabilityFeature", "ObservabilityHook", "__version__"]
@@ -0,0 +1,135 @@
1
+ """
2
+ Kestrel Observability Feature - Always-on lifecycle event observability.
3
+
4
+ Auto-discovers via the feature system, registers the ObservabilityHook
5
+ to log all lifecycle events to ObservabilityStore, and exposes tool
6
+ commands for querying observability data at runtime.
7
+ """
8
+
9
+ import logging
10
+ from typing import Any, Dict, List, Optional
11
+
12
+ from kestrel_sdk.features.base import Feature, tool
13
+ from kestrel_feature_observability.hook import ObservabilityHook
14
+ from kestrel_sdk.hooks.base import Hook
15
+ from kestrel_sdk.tools.base import ToolCategory
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ class ObservabilityFeature(Feature):
21
+ """Always-on observability via hook system. Logs all lifecycle events to ObservabilityStore."""
22
+
23
+ def __init__(self, agent):
24
+ super().__init__(agent)
25
+ self._hook: Optional[ObservabilityHook] = None
26
+
27
+ @property
28
+ def tool_description(self) -> str:
29
+ return "Lifecycle event observability and monitoring"
30
+
31
+ def get_router(self):
32
+ """Return the Observability HTTP router for dynamic mounting.
33
+
34
+ The router is defined in endpoints/observability.py and mounted by
35
+ the server only when ObservabilityFeature is discovered and enabled.
36
+ """
37
+ from endpoints.observability import router
38
+ return router
39
+
40
+ async def initialize(self):
41
+ """Create the ObservabilityHook (auto-registered via get_hooks)."""
42
+ self._hook = ObservabilityHook(agent=self.agent)
43
+
44
+ def get_hooks(self) -> List[Hook]:
45
+ """Return the observability hook for auto-registration."""
46
+ if self._hook:
47
+ return [self._hook]
48
+ return []
49
+
50
+ async def shutdown(self):
51
+ """Clean up hook reference on shutdown."""
52
+ self._hook = None
53
+
54
+ @tool(
55
+ "obs_status",
56
+ "Show observability event counts",
57
+ category=ToolCategory.SYSTEM,
58
+ command_prefix="!obs",
59
+ )
60
+ async def obs_status(self) -> Dict[str, Any]:
61
+ """Show observability summary: event counts by type, recent errors."""
62
+ store = getattr(self.agent, "observability_store", None)
63
+ if not store:
64
+ return {"error": "ObservabilityStore not available"}
65
+
66
+ from datetime import datetime, timedelta, timezone
67
+
68
+ since = datetime.now(timezone.utc) - timedelta(hours=1)
69
+ events = await store.query_events(event_type="metric", since=since, limit=1000)
70
+
71
+ # Count by hook event type
72
+ counts: Dict[str, int] = {}
73
+ for e in events:
74
+ hook_event = e.metadata.get("hook_event", "unknown") if e.metadata else "unknown"
75
+ metric_name = e.metadata.get("metric_name", "") if e.metadata else ""
76
+ if metric_name.startswith("hook."):
77
+ counts[hook_event] = counts.get(hook_event, 0) + 1
78
+
79
+ # Recent errors
80
+ error_events = await store.query_events(event_type="error", since=since, limit=10)
81
+ recent_errors: List[Dict[str, Any]] = []
82
+ for e in error_events:
83
+ recent_errors.append({
84
+ "timestamp": str(e.timestamp),
85
+ "error_message": e.error_message,
86
+ "metadata": e.metadata,
87
+ })
88
+
89
+ return {
90
+ "time_window": "last 1 hour",
91
+ "hook_event_counts": counts,
92
+ "total_hook_events": sum(counts.values()),
93
+ "recent_errors": recent_errors,
94
+ }
95
+
96
+ @tool(
97
+ "obs_events",
98
+ "Query recent observability events",
99
+ category=ToolCategory.SYSTEM,
100
+ command_prefix="!obs-events",
101
+ )
102
+ async def obs_events(self, event_type: str = "", limit: int = 20) -> Dict[str, Any]:
103
+ """Query recent events, optionally filtered by type.
104
+
105
+ Args:
106
+ event_type: Filter by event type (e.g., 'metric', 'error', 'tool_call')
107
+ limit: Maximum events to return
108
+ """
109
+ store = getattr(self.agent, "observability_store", None)
110
+ if not store:
111
+ return {"error": "ObservabilityStore not available"}
112
+
113
+ events = await store.query_events(
114
+ event_type=event_type if event_type else None,
115
+ limit=limit,
116
+ )
117
+
118
+ event_dicts: List[Dict[str, Any]] = []
119
+ for e in events:
120
+ event_dicts.append({
121
+ "event_id": e.event_id,
122
+ "timestamp": str(e.timestamp),
123
+ "agent_name": e.agent_name,
124
+ "event_type": e.event_type,
125
+ "tool_name": e.tool_name,
126
+ "duration_ms": e.duration_ms,
127
+ "success": e.success,
128
+ "error_message": e.error_message,
129
+ "metadata": e.metadata,
130
+ })
131
+
132
+ return {
133
+ "events": event_dicts,
134
+ "count": len(event_dicts),
135
+ }
@@ -0,0 +1,118 @@
1
+ """
2
+ Kestrel Observability Hook - Default observer for all lifecycle events.
3
+
4
+ Writes structured entries to ObservabilityStore for every hook event.
5
+ This hook is purely observational: it never blocks, denies, or modifies
6
+ anything. Exceptions are swallowed to avoid affecting agent operation.
7
+ """
8
+
9
+ import logging
10
+ from typing import Any, Dict
11
+
12
+ from kestrel_sdk.hooks.base import Hook, HookEvent, HookInput, HookOutput
13
+ from kestrel_sdk.metrics import (
14
+ PROMETHEUS_AVAILABLE,
15
+ HOOK_EVENTS,
16
+ TOOL_CALLS,
17
+ TOOL_DURATION,
18
+ )
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ # Maps hook event names to ObservabilityStore event types
23
+ EVENT_TYPE_MAP = {
24
+ "SessionStart": "lifecycle",
25
+ "UserPromptSubmit": "lifecycle",
26
+ "PreToolUse": "tool_call",
27
+ "PostToolUse": "tool_response",
28
+ "PreSubagentCall": "subagent_call",
29
+ "PostSubagentCall": "subagent_response",
30
+ "Stop": "lifecycle",
31
+ }
32
+
33
+
34
+ class ObservabilityHook(Hook):
35
+ """Default observer for all lifecycle events. Writes to ObservabilityStore."""
36
+
37
+ def __init__(self, agent):
38
+ super().__init__(
39
+ name="observability",
40
+ events=list(HookEvent), # ALL events
41
+ priority=999, # Run LAST — after security, audit, etc.
42
+ timeout=5.0,
43
+ )
44
+ self.agent = agent
45
+
46
+ async def execute(self, input: HookInput) -> HookOutput:
47
+ """Log the event to ObservabilityStore. Never blocks."""
48
+ try:
49
+ store = getattr(self.agent, "observability_store", None)
50
+ if not store:
51
+ logger.warning(
52
+ "ObservabilityHook: observability_store not initialized — "
53
+ "event '%s' dropped. This usually means the hook fired "
54
+ "before store setup completed.",
55
+ input.hook_event_name,
56
+ )
57
+ return HookOutput.allow()
58
+
59
+ agent_name = getattr(self.agent, "agent_name", "unknown")
60
+ event_type = input.hook_event_name
61
+ # Classify the hook event into a broader category for querying
62
+ event_category = EVENT_TYPE_MAP.get(event_type, "lifecycle")
63
+
64
+ metadata: Dict[str, Any] = {
65
+ "hook_event": event_type,
66
+ "event_category": event_category,
67
+ "session_id": input.session_id,
68
+ }
69
+
70
+ # Enrich metadata based on event type
71
+ if input.tool_name:
72
+ metadata["tool_name"] = input.tool_name
73
+ if input.feature_name:
74
+ metadata["feature_name"] = input.feature_name
75
+ if input.user_message:
76
+ metadata["user_message_length"] = len(input.user_message)
77
+ # Don't log full user message — privacy
78
+ if input.execution_time_ms is not None:
79
+ metadata["execution_time_ms"] = input.execution_time_ms
80
+ if input.tool_response:
81
+ success = (
82
+ input.tool_response.get("success", True)
83
+ if isinstance(input.tool_response, dict)
84
+ else True
85
+ )
86
+ metadata["success"] = success
87
+ if not success and isinstance(input.tool_response, dict):
88
+ metadata["error"] = str(
89
+ input.tool_response.get("error", "")
90
+ )[:200]
91
+
92
+ await store.log_metric(
93
+ agent_name=agent_name,
94
+ metric_name=f"hook.{event_type}",
95
+ metric_value=1,
96
+ metadata=metadata,
97
+ )
98
+
99
+ # --- Prometheus counters (fire-and-forget, same try/except) ---
100
+ if PROMETHEUS_AVAILABLE:
101
+ HOOK_EVENTS.labels(event_type=event_type).inc()
102
+
103
+ # Tool metrics from PostToolUse events
104
+ if event_type == "PostToolUse" and input.tool_name:
105
+ success = metadata.get("success", True)
106
+ TOOL_CALLS.labels(
107
+ tool_name=input.tool_name, success=str(success)
108
+ ).inc()
109
+ if input.execution_time_ms is not None:
110
+ TOOL_DURATION.labels(
111
+ tool_name=input.tool_name
112
+ ).observe(input.execution_time_ms / 1000)
113
+
114
+ except Exception as e:
115
+ # Never let observability failures affect agent operation
116
+ logger.debug(f"ObservabilityHook error (non-fatal): {e}")
117
+
118
+ return HookOutput.allow() # NEVER block
@@ -0,0 +1,69 @@
1
+ [project]
2
+ name = "kestrel-feature-observability"
3
+ version = "0.1.0"
4
+ description = "Lifecycle event observability feature for Kestrel Sovereign — hook-driven logging with shared Prometheus registry"
5
+ readme = "README.md"
6
+ requires-python = ">=3.11,<3.14"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "UncleSaurus" }]
10
+ maintainers = [{ name = "UncleSaurus" }]
11
+ keywords = [
12
+ "ai",
13
+ "agents",
14
+ "kestrel",
15
+ "observability",
16
+ "prometheus",
17
+ "metrics",
18
+ ]
19
+ classifiers = [
20
+ "Development Status :: 4 - Beta",
21
+ "Intended Audience :: Developers",
22
+ "Programming Language :: Python :: 3",
23
+ "Programming Language :: Python :: 3.11",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Programming Language :: Python :: 3.13",
26
+ "Operating System :: POSIX :: Linux",
27
+ "Operating System :: MacOS",
28
+ "Operating System :: Microsoft :: Windows",
29
+ "Topic :: System :: Monitoring",
30
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
31
+ ]
32
+ dependencies = [
33
+ "kestrel-sovereign-sdk>=0.3,<1",
34
+ ]
35
+
36
+ [project.optional-dependencies]
37
+ # Pulls prometheus-client through the SDK's [metrics] extra so the
38
+ # feature shares the framework's CollectorRegistry. Without this
39
+ # extra installed, the feature still logs to the observability
40
+ # store; only the Prometheus side becomes a no-op.
41
+ metrics = [
42
+ "kestrel-sovereign-sdk[metrics]>=0.3,<1",
43
+ ]
44
+ test = [
45
+ "pytest>=8.0.0",
46
+ "pytest-asyncio>=1.1.0",
47
+ "kestrel-sovereign-sdk[metrics]>=0.3,<1",
48
+ ]
49
+
50
+ [project.urls]
51
+ Homepage = "https://kestrelsovereign.com"
52
+ Source = "https://github.com/KestrelSovereignAI/kestrel-feature-observability"
53
+ Issues = "https://github.com/KestrelSovereignAI/kestrel-feature-observability/issues"
54
+
55
+ [project.entry-points."kestrel_sovereign.features"]
56
+ ObservabilityFeature = "kestrel_feature_observability.feature:ObservabilityFeature"
57
+
58
+ [build-system]
59
+ requires = ["hatchling"]
60
+ build-backend = "hatchling.build"
61
+
62
+ [tool.hatch.build.targets.wheel]
63
+ packages = ["kestrel_feature_observability"]
64
+
65
+ [tool.hatch.build.targets.sdist]
66
+ include = ["kestrel_feature_observability/**/*", "README.md", "LICENSE", "pyproject.toml"]
67
+
68
+ [tool.pytest.ini_options]
69
+ asyncio_mode = "auto"