agenthealth 0.13.2__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,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
141
+ the 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,69 @@
1
+ Metadata-Version: 2.4
2
+ Name: agenthealth
3
+ Version: 0.13.2
4
+ Summary: Typed synchronous and asynchronous Python access to the AgentHealth CLI
5
+ Author: TheAgentHealth
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/TheAgentHealth/agenthealth
8
+ Project-URL: Documentation, https://github.com/TheAgentHealth/agenthealth/blob/main/docs/python-sdk.md
9
+ Project-URL: Issues, https://github.com/TheAgentHealth/agenthealth/issues
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Typing :: Typed
13
+ Requires-Python: >=3.10
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: jsonschema<5,>=4.18
17
+ Requires-Dist: PyYAML<7,>=6
18
+ Dynamic: license-file
19
+
20
+ # AgentHealth Python SDK
21
+
22
+ Typed synchronous and asynchronous access to AgentHealth's Go CLI. This package
23
+ preserves AHS v1 results, diagnostic codes, dependency relationships and graph
24
+ IDs. Health failures return results; tool failures raise exceptions.
25
+
26
+ Install the package with `pip install agenthealth` once published. Install a
27
+ verified AgentHealth CLI of the same software version separately and put it on
28
+ PATH, or pass its absolute path. Installation and imports never download or
29
+ execute a binary. This first SDK targets Python 3.10+ and CLI v0.13.2.
30
+
31
+ ```python
32
+ from agenthealth import Client, HealthStatus
33
+
34
+ client = Client(binary="/usr/local/bin/agenthealth", timeout=30)
35
+ report = client.check(target_type="http", endpoint="http://localhost:8080/health")
36
+ print(report.status, report.exit_code)
37
+ if report.status == HealthStatus.HEALTHY:
38
+ print(report.result.target.name)
39
+ ```
40
+
41
+ ```python
42
+ from agenthealth import async_check
43
+
44
+ async def probe():
45
+ return await async_check("agenthealth.yaml")
46
+ ```
47
+
48
+ Use `Configuration` for Python dictionaries or `load_config` for JSON/YAML.
49
+ The same configuration supports all implemented CLI adapters, explicit active
50
+ checks, nested dependencies and graph references. Credentials stay in configured
51
+ references. Configuration is trusted executable input: MCP stdio can launch
52
+ programs and endpoints can reach private networks. Loading validates schema;
53
+ Go validates graph semantics at execution.
54
+
55
+ The SDK checks the exact CLI version, bounds configuration and output, enforces
56
+ an overall deadline and stops checks on timeout/cancellation. POSIX checks use
57
+ a dedicated process group to clean up descendants. On Windows termination
58
+ covers the CLI process; detached stdio descendants require operator lifecycle
59
+ controls. CLI stderr is never included in exceptions.
60
+
61
+ The SDK does not aggregate health independently, run OAuth login, register
62
+ Python adapters, or auto-install the CLI. `report.results` preserves ordered
63
+ roots, including each dependency projection. `to_dict()` preserves additional
64
+ result fields. Relative paths retain the caller's working directory, matching
65
+ the CLI; `Configuration(data, base_dir=...)` selects a different directory.
66
+
67
+ Source implementation is pre-1.0; PyPI availability is recorded separately in
68
+ the repository capability status. See the repository's Python SDK guide for
69
+ installation, release setup, errors and examples.
@@ -0,0 +1,50 @@
1
+ # AgentHealth Python SDK
2
+
3
+ Typed synchronous and asynchronous access to AgentHealth's Go CLI. This package
4
+ preserves AHS v1 results, diagnostic codes, dependency relationships and graph
5
+ IDs. Health failures return results; tool failures raise exceptions.
6
+
7
+ Install the package with `pip install agenthealth` once published. Install a
8
+ verified AgentHealth CLI of the same software version separately and put it on
9
+ PATH, or pass its absolute path. Installation and imports never download or
10
+ execute a binary. This first SDK targets Python 3.10+ and CLI v0.13.2.
11
+
12
+ ```python
13
+ from agenthealth import Client, HealthStatus
14
+
15
+ client = Client(binary="/usr/local/bin/agenthealth", timeout=30)
16
+ report = client.check(target_type="http", endpoint="http://localhost:8080/health")
17
+ print(report.status, report.exit_code)
18
+ if report.status == HealthStatus.HEALTHY:
19
+ print(report.result.target.name)
20
+ ```
21
+
22
+ ```python
23
+ from agenthealth import async_check
24
+
25
+ async def probe():
26
+ return await async_check("agenthealth.yaml")
27
+ ```
28
+
29
+ Use `Configuration` for Python dictionaries or `load_config` for JSON/YAML.
30
+ The same configuration supports all implemented CLI adapters, explicit active
31
+ checks, nested dependencies and graph references. Credentials stay in configured
32
+ references. Configuration is trusted executable input: MCP stdio can launch
33
+ programs and endpoints can reach private networks. Loading validates schema;
34
+ Go validates graph semantics at execution.
35
+
36
+ The SDK checks the exact CLI version, bounds configuration and output, enforces
37
+ an overall deadline and stops checks on timeout/cancellation. POSIX checks use
38
+ a dedicated process group to clean up descendants. On Windows termination
39
+ covers the CLI process; detached stdio descendants require operator lifecycle
40
+ controls. CLI stderr is never included in exceptions.
41
+
42
+ The SDK does not aggregate health independently, run OAuth login, register
43
+ Python adapters, or auto-install the CLI. `report.results` preserves ordered
44
+ roots, including each dependency projection. `to_dict()` preserves additional
45
+ result fields. Relative paths retain the caller's working directory, matching
46
+ the CLI; `Configuration(data, base_dir=...)` selects a different directory.
47
+
48
+ Source implementation is pre-1.0; PyPI availability is recorded separately in
49
+ the repository capability status. See the repository's Python SDK guide for
50
+ installation, release setup, errors and examples.
@@ -0,0 +1,30 @@
1
+ [build-system]
2
+ requires = ["setuptools==80.9.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "agenthealth"
7
+ version = "0.13.2"
8
+ description = "Typed synchronous and asynchronous Python access to the AgentHealth CLI"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ authors = [{name = "TheAgentHealth"}]
14
+ dependencies = ["jsonschema>=4.18,<5", "PyYAML>=6,<7"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Programming Language :: Python :: 3",
18
+ "Typing :: Typed",
19
+ ]
20
+
21
+ [project.urls]
22
+ Homepage = "https://github.com/TheAgentHealth/agenthealth"
23
+ Documentation = "https://github.com/TheAgentHealth/agenthealth/blob/main/docs/python-sdk.md"
24
+ Issues = "https://github.com/TheAgentHealth/agenthealth/issues"
25
+
26
+ [tool.setuptools.packages.find]
27
+ where = ["src"]
28
+
29
+ [tool.setuptools.package-data]
30
+ agenthealth = ["py.typed", "schemas/*.json"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,12 @@
1
+ """AgentHealth Python SDK. Installation does not install the CLI."""
2
+ from .client import Client, async_check, check
3
+ from .config import Configuration, load_config
4
+ from .errors import (AgentHealthError, BinaryNotFoundError, CheckTimeoutError,
5
+ CompatibilityError, ConfigurationError, ExecutionError, OutputError)
6
+ from .models import CheckEntry, CheckReport, HealthResult, HealthStatus, Relationship, Target
7
+ from .version import __version__
8
+
9
+ __all__ = ["Client", "check", "async_check", "Configuration", "load_config", "CheckEntry",
10
+ "CheckReport", "HealthResult", "HealthStatus", "Relationship", "Target",
11
+ "AgentHealthError", "BinaryNotFoundError", "CheckTimeoutError", "CompatibilityError",
12
+ "ConfigurationError", "ExecutionError", "OutputError", "__version__"]
@@ -0,0 +1,199 @@
1
+ """Bounded CLI execution with native async cancellation and no shell invocation."""
2
+ import asyncio
3
+ from contextlib import contextmanager
4
+ import json
5
+ import math
6
+ import os
7
+ import re
8
+ from pathlib import Path
9
+ import shutil
10
+ import signal
11
+ import tempfile
12
+ import time
13
+ from typing import Any, Mapping, Sequence
14
+
15
+ from .config import Configuration, load_config
16
+ from .errors import (BinaryNotFoundError, CheckTimeoutError, CompatibilityError,
17
+ ConfigurationError, ExecutionError, OutputError)
18
+ from .models import CheckReport, parse_report
19
+ from .version import __version__
20
+
21
+ MAX_OUTPUT_BYTES = 16 * 1024 * 1024
22
+ MAX_DIAGNOSTIC_BYTES = 64 * 1024
23
+
24
+
25
+ async def _signal_group(process: asyncio.subprocess.Process, sig: int) -> None:
26
+ try:
27
+ os.killpg(process.pid, sig)
28
+ except ProcessLookupError:
29
+ pass
30
+ except PermissionError:
31
+ # Darwin can report EPERM for an already-exited process group. Confirm
32
+ # root exit before accepting it; a live permission failure remains fatal.
33
+ if process.returncode is None:
34
+ try:
35
+ await asyncio.wait_for(process.wait(), 1)
36
+ except asyncio.TimeoutError:
37
+ raise ExecutionError("Unable to stop AgentHealth CLI process") from None
38
+
39
+
40
+ async def _stop(process: asyncio.subprocess.Process) -> None:
41
+ # Kill the dedicated process group even if the root exited, so an MCP stdio
42
+ # descendant cannot retain credentials or the temporary output descriptors.
43
+ try:
44
+ if os.name == "posix":
45
+ await _signal_group(process, signal.SIGTERM)
46
+ elif process.returncode is None:
47
+ process.terminate()
48
+ except ProcessLookupError:
49
+ pass
50
+ try:
51
+ await asyncio.wait_for(process.wait(), 1)
52
+ except asyncio.TimeoutError:
53
+ pass
54
+ finally:
55
+ try:
56
+ if os.name == "posix":
57
+ await _signal_group(process, signal.SIGKILL)
58
+ elif process.returncode is None:
59
+ process.kill()
60
+ except ProcessLookupError:
61
+ pass
62
+ await process.wait()
63
+
64
+
65
+ async def _run(command: list[str], *, timeout: float, cwd: Path,
66
+ environment: Mapping[str, str] | None) -> tuple[int, bytes]:
67
+ env = None if environment is None else {**os.environ, **environment}
68
+ with tempfile.TemporaryFile() as output, tempfile.TemporaryFile() as diagnostic:
69
+ try:
70
+ process = await asyncio.create_subprocess_exec(
71
+ *command, stdin=asyncio.subprocess.DEVNULL, stdout=output, stderr=diagnostic,
72
+ cwd=cwd, env=env, start_new_session=os.name == "posix")
73
+ except OSError:
74
+ raise BinaryNotFoundError("Unable to start AgentHealth CLI") from None
75
+ deadline = time.monotonic() + timeout
76
+ try:
77
+ while True:
78
+ if (os.fstat(output.fileno()).st_size > MAX_OUTPUT_BYTES or
79
+ os.fstat(diagnostic.fileno()).st_size > MAX_DIAGNOSTIC_BYTES):
80
+ raise OutputError("AgentHealth output exceeded the SDK limit")
81
+ if process.returncode is not None:
82
+ break
83
+ remaining = deadline - time.monotonic()
84
+ if remaining <= 0:
85
+ raise CheckTimeoutError("AgentHealth check deadline expired")
86
+ await asyncio.sleep(min(0.02, remaining))
87
+ output.seek(0)
88
+ return process.returncode, output.read(MAX_OUTPUT_BYTES + 1)
89
+ finally:
90
+ # A separate task keeps cleanup alive if another cancellation arrives.
91
+ cleanup = asyncio.create_task(_stop(process))
92
+ try:
93
+ await asyncio.shield(cleanup)
94
+ except asyncio.CancelledError:
95
+ await cleanup
96
+ raise
97
+
98
+
99
+ @contextmanager
100
+ def _config_file(configuration: Configuration):
101
+ with tempfile.TemporaryDirectory(prefix="agenthealth-sdk-") as directory:
102
+ path = Path(directory) / "configuration.json"
103
+ # Directory mode is 0700; file is never passed in command text or stderr.
104
+ descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
105
+ with os.fdopen(descriptor, "w") as stream:
106
+ json.dump(configuration.to_dict(), stream, allow_nan=False)
107
+ yield path
108
+
109
+
110
+ def _configuration(config: Configuration | Mapping[str, Any] | str | Path | None,
111
+ target_type: str | None, endpoint: str | None, name: str,
112
+ checks: Sequence[str] | None, options: Mapping[str, Any] | None) -> Configuration:
113
+ if config is not None:
114
+ if target_type is not None or endpoint is not None or checks is not None or options is not None:
115
+ raise ConfigurationError("Choose a configuration or individual target arguments")
116
+ if isinstance(config, Configuration):
117
+ return config
118
+ if isinstance(config, Mapping):
119
+ return Configuration(config)
120
+ return load_config(config)
121
+ if target_type is None or endpoint is None:
122
+ raise ConfigurationError("A configuration or target_type and endpoint are required")
123
+ target: dict[str, Any] = dict(options or {})
124
+ if any(key in target for key in ("name", "type", "endpoint", "checks")):
125
+ raise ConfigurationError("Target options must not override named arguments")
126
+ target.update(name=name, type=target_type, endpoint=endpoint)
127
+ if checks is not None:
128
+ target["checks"] = list(checks)
129
+ return Configuration({"version": "v1", "targets": [target]})
130
+
131
+
132
+ class Client:
133
+ """Use an installed CLI of exactly the SDK version; never download or execute
134
+ a binary at import/install time. Pass a verified binary path when pinning it.
135
+ """
136
+
137
+ def __init__(self, binary: str | Path = "agenthealth", *, timeout: float = 30,
138
+ environment: Mapping[str, str] | None = None):
139
+ if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or not math.isfinite(timeout) or timeout <= 0:
140
+ raise ValueError("timeout must be a positive finite number")
141
+ self.binary = str(binary)
142
+ self.timeout = timeout
143
+ self.environment = None if environment is None else dict(environment)
144
+
145
+ async def async_check(self, config: Configuration | Mapping[str, Any] | str | Path | None = None,
146
+ *, target_type: str | None = None, endpoint: str | None = None,
147
+ name: str = "target", checks: Sequence[str] | None = None,
148
+ options: Mapping[str, Any] | None = None) -> CheckReport:
149
+ configuration = _configuration(config, target_type, endpoint, name, checks, options)
150
+ # Resolve before changing cwd; relative explicit binary paths retain their meaning.
151
+ binary = shutil.which(self.binary)
152
+ if binary is None:
153
+ raise BinaryNotFoundError("AgentHealth CLI executable was not found")
154
+ binary = str(Path(binary).resolve())
155
+ deadline = time.monotonic() + self.timeout
156
+ code, version = await _run([binary, "version"], timeout=min(self.timeout, 5),
157
+ cwd=configuration.base_dir, environment=self.environment)
158
+ cli_version = re.sub(r"(a|b|rc)([0-9]+)$", r"-\1.\2", __version__)
159
+ if code != 0 or version.strip() != f"agenthealth v{cli_version}".encode():
160
+ raise CompatibilityError("AgentHealth CLI must match the SDK software version")
161
+ remaining = deadline - time.monotonic()
162
+ if remaining <= 0:
163
+ raise CheckTimeoutError("AgentHealth check deadline expired")
164
+ with _config_file(configuration) as path:
165
+ code, output = await _run([binary, "check", "--format", "json", "--", str(path)],
166
+ timeout=remaining, cwd=configuration.base_dir,
167
+ environment=self.environment)
168
+ if code not in range(6):
169
+ raise ExecutionError("AgentHealth CLI execution failed")
170
+ return parse_report(output, code)
171
+
172
+ def check(self, config: Configuration | Mapping[str, Any] | str | Path | None = None,
173
+ *, target_type: str | None = None, endpoint: str | None = None,
174
+ name: str = "target", checks: Sequence[str] | None = None,
175
+ options: Mapping[str, Any] | None = None) -> CheckReport:
176
+ try:
177
+ asyncio.get_running_loop()
178
+ except RuntimeError:
179
+ return asyncio.run(self.async_check(config, target_type=target_type, endpoint=endpoint,
180
+ name=name, checks=checks, options=options))
181
+ raise RuntimeError("Use await client.async_check() inside an event loop")
182
+
183
+
184
+ def check(config: Configuration | Mapping[str, Any] | str | Path | None = None, *,
185
+ target_type: str | None = None, endpoint: str | None = None, name: str = "target",
186
+ checks: Sequence[str] | None = None, options: Mapping[str, Any] | None = None,
187
+ binary: str | Path = "agenthealth", timeout: float = 30,
188
+ environment: Mapping[str, str] | None = None) -> CheckReport:
189
+ return Client(binary, timeout=timeout, environment=environment).check(
190
+ config, target_type=target_type, endpoint=endpoint, name=name, checks=checks, options=options)
191
+
192
+
193
+ async def async_check(config: Configuration | Mapping[str, Any] | str | Path | None = None, *,
194
+ target_type: str | None = None, endpoint: str | None = None, name: str = "target",
195
+ checks: Sequence[str] | None = None, options: Mapping[str, Any] | None = None,
196
+ binary: str | Path = "agenthealth", timeout: float = 30,
197
+ environment: Mapping[str, str] | None = None) -> CheckReport:
198
+ return await Client(binary, timeout=timeout, environment=environment).async_check(
199
+ config, target_type=target_type, endpoint=endpoint, name=name, checks=checks, options=options)
@@ -0,0 +1,71 @@
1
+ """Load trusted configuration without executing checks or resolving credentials."""
2
+ from copy import deepcopy
3
+ from importlib.resources import files
4
+ import json
5
+ from pathlib import Path
6
+ from typing import Any, Mapping
7
+
8
+ from jsonschema import Draft202012Validator
9
+ import yaml
10
+
11
+ from .errors import ConfigurationError
12
+
13
+ MAX_CONFIG_BYTES = 4 * 1024 * 1024
14
+
15
+
16
+ def validator(name: str) -> Draft202012Validator:
17
+ schema = json.loads(files("agenthealth").joinpath("schemas", name + ".schema.json").read_text())
18
+ return Draft202012Validator(schema)
19
+
20
+
21
+ class Configuration:
22
+ """A validated copy of an AHS v1 document; semantic validation stays in Go."""
23
+
24
+ def __init__(self, data: Mapping[str, Any], *, base_dir: str | Path | None = None):
25
+ try:
26
+ document = json.loads(json.dumps(dict(data), allow_nan=False))
27
+ validator("configuration").validate(document)
28
+ if len(json.dumps(document).encode()) > MAX_CONFIG_BYTES:
29
+ raise ValueError()
30
+ except Exception:
31
+ # Schema/parser exceptions may contain credentials and configured values.
32
+ raise ConfigurationError("Invalid AgentHealth configuration") from None
33
+ self._data = document
34
+ self.base_dir = Path(base_dir).resolve() if base_dir is not None else Path.cwd()
35
+
36
+ def to_dict(self) -> dict[str, Any]:
37
+ return deepcopy(self._data)
38
+
39
+
40
+ class _UniqueLoader(yaml.SafeLoader):
41
+ pass
42
+
43
+
44
+ def _mapping(loader: _UniqueLoader, node: yaml.MappingNode, deep: bool = False):
45
+ result = {}
46
+ for key_node, value_node in node.value:
47
+ key = loader.construct_object(key_node, deep=deep)
48
+ if key in result:
49
+ raise ValueError("Duplicate YAML key")
50
+ result[key] = loader.construct_object(value_node, deep=deep)
51
+ return result
52
+
53
+
54
+ _UniqueLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, _mapping)
55
+
56
+
57
+ def load_config(path: str | Path) -> Configuration:
58
+ """Read bounded JSON/YAML. Relative credential/token paths use the caller's cwd,
59
+ matching CLI behavior. Pass base_dir explicitly to Configuration to change it.
60
+ """
61
+ try:
62
+ with Path(path).open("rb") as stream:
63
+ data = stream.read(MAX_CONFIG_BYTES + 1)
64
+ if len(data) > MAX_CONFIG_BYTES:
65
+ raise ValueError()
66
+ document = yaml.load(data, Loader=_UniqueLoader)
67
+ if not isinstance(document, dict):
68
+ raise ValueError()
69
+ return Configuration(document)
70
+ except Exception:
71
+ raise ConfigurationError("Unable to load AgentHealth configuration") from None
@@ -0,0 +1,29 @@
1
+ """Tool failures are exceptions; health failures remain results."""
2
+
3
+
4
+ class AgentHealthError(Exception):
5
+ """Base class for SDK/tool errors. Messages never include CLI diagnostics."""
6
+
7
+
8
+ class ConfigurationError(AgentHealthError):
9
+ """Unreadable or invalid SDK configuration."""
10
+
11
+
12
+ class BinaryNotFoundError(AgentHealthError):
13
+ """The requested CLI executable could not be started."""
14
+
15
+
16
+ class CompatibilityError(AgentHealthError):
17
+ """The CLI software version does not match the SDK."""
18
+
19
+
20
+ class ExecutionError(AgentHealthError):
21
+ """The CLI failed to execute or returned exit code 6."""
22
+
23
+
24
+ class CheckTimeoutError(AgentHealthError):
25
+ """The SDK deadline expired; the CLI was stopped."""
26
+
27
+
28
+ class OutputError(AgentHealthError):
29
+ """The CLI returned oversized or invalid machine output."""