@theagenthealth/agenthealth 0.0.0 → 0.15.0

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.
package/LICENSE ADDED
@@ -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.
package/README.md ADDED
@@ -0,0 +1,62 @@
1
+ # AgentHealth JavaScript / TypeScript SDK
2
+
3
+ Node.js ESM SDK wrapping the reference Go CLI. Node **22.14+** is required.
4
+ Browsers, CommonJS `require`, automatic binary downloads and install scripts are
5
+ not supported. All implemented adapters and graph configurations use the same
6
+ AHS v1 configuration and result contracts as the CLI.
7
+
8
+ ```sh
9
+ npm install @theagenthealth/agenthealth@0.15.0
10
+ ```
11
+
12
+ Install and verify CLI **v0.15.0** separately using the
13
+ [installation guide](../../docs/installation.md). The SDK never downloads or
14
+ executes binaries at import/install time. A mismatched CLI raises
15
+ `CompatibilityError` before running checks.
16
+
17
+ ```js
18
+ import { check } from '@theagenthealth/agenthealth';
19
+
20
+ const report = await check({
21
+ version: 'v1',
22
+ targets: [{ name: 'api', type: 'http', endpoint: 'http://localhost:8080/health',
23
+ checks: ['reachability'] }]
24
+ }, { binary: 'agenthealth', timeout: 30000 });
25
+ console.log(report.status, report.results);
26
+ ```
27
+
28
+ `check(config, options)` and `new Client(options).check(config, { signal })`
29
+ return promises. Config can be an AHS configuration object, a `Configuration`,
30
+ or a JSON/YAML filename. `loadConfig(path)` validates without executing checks.
31
+ `new Configuration(data, { baseDir })` explicitly changes the working directory;
32
+ otherwise relative credential/token paths use the caller's cwd, like the CLI.
33
+ Configuration files are trusted input: MCP stdio and explicitly enabled active
34
+ checks can execute configured programs or interactions.
35
+
36
+ `timeout` is an overall subprocess budget in **milliseconds**, default 30000,
37
+ including version probing (capped at five seconds). Pass an `AbortSignal` for
38
+ cancellation and `environment` for explicit environment overrides. Temporary
39
+ configuration directories are private, with files mode 0600 on POSIX. The SDK
40
+ caps configuration at 4 MiB, stdout at 16 MiB and stderr at 64 KiB. Errors never
41
+ include raw CLI output or configured values. POSIX cleanup kills the subprocess
42
+ group, including descendants; Windows cleanup terminates the direct CLI process
43
+ and does not guarantee termination of MCP descendants.
44
+
45
+ Health exit codes **0–5 resolve** to `{ results, exitCode, status, spec_version }`;
46
+ tool failures (including exit 6), malformed results, deadline expiration and
47
+ cancellation reject with exported `AgentHealthError` subclasses. Root order,
48
+ node IDs, dependency relationship/critical metadata, named peer/path checks,
49
+ diagnostic codes and additional result evidence are preserved. `status` is the
50
+ CLI aggregate status; the SDK does not recompute dependency policies.
51
+
52
+ `TargetConfiguration` intentionally permits protocol options validated by the
53
+ bundled canonical schema. Result interfaces type shared fields; additional
54
+ adapter evidence stays available as `unknown`. Experimental AHP serving remains
55
+ a CLI/server capability, rather than an SDK HTTP server.
56
+
57
+ See the [SDK guide](../../docs/javascript-sdk.md),
58
+ [example](../../examples/javascript-sdk/README.md), and
59
+ [Phase 16 impact review](../../docs/phase-16-alignment.md).
60
+
61
+ Source release target: v0.15.0. Requires the matching CLI; model/LLM
62
+ configuration is supported through the canonical schema.
package/index.d.ts ADDED
@@ -0,0 +1,71 @@
1
+ export const version: string;
2
+ export type HealthStatus = 'HEALTHY' | 'DEGRADED' | 'UNHEALTHY' | 'UNREACHABLE' | 'MISCONFIGURED' | 'UNKNOWN';
3
+ export const healthStates: readonly HealthStatus[];
4
+ export type Relationship = 'supporting' | 'downstream' | 'path' | 'gateway' | 'router';
5
+ export type TargetType = 'agent' | 'multi-agent' | 'a2a' | 'mcp' | 'tool' | 'model' | 'llm' | 'http' | 'api' | 'vector-store' | 'database' | 'runtime' | 'gateway' | 'router' | 'custom';
6
+ export interface CheckEntry {
7
+ status: HealthStatus;
8
+ message?: string;
9
+ code?: string;
10
+ steps?: Partial<Record<'dns' | 'tcp' | 'tls' | 'http', HealthStatus>>;
11
+ [evidence: string]: unknown;
12
+ }
13
+ export interface HealthResult {
14
+ target: { name: string; type: TargetType; id?: string; [evidence: string]: unknown };
15
+ status: HealthStatus;
16
+ checks: Record<string, CheckEntry>;
17
+ dependencies: HealthResult[];
18
+ relationship?: Relationship;
19
+ critical?: boolean;
20
+ latency_ms?: number | null;
21
+ [evidence: string]: unknown;
22
+ }
23
+ export interface CheckReport {
24
+ results: HealthResult[];
25
+ exitCode: number;
26
+ status: HealthStatus;
27
+ spec_version: 'v1';
28
+ }
29
+ /** Schema validated; protocol-specific options use the canonical configuration schema. */
30
+ export interface TargetConfiguration {
31
+ name: string;
32
+ type: TargetType;
33
+ endpoint?: string;
34
+ checks?: string[];
35
+ id?: string;
36
+ [option: string]: unknown;
37
+ }
38
+ export interface ConfigurationDocument {
39
+ version: 'v1';
40
+ targets: TargetConfiguration[];
41
+ [option: string]: unknown;
42
+ }
43
+ export interface ConfigurationOptions { baseDir?: string }
44
+ export class Configuration {
45
+ constructor(data: ConfigurationDocument, options?: ConfigurationOptions);
46
+ readonly baseDir: string;
47
+ toJSON(): ConfigurationDocument;
48
+ }
49
+ export function loadConfig(path: string, options?: ConfigurationOptions): Promise<Configuration>;
50
+ export interface ClientOptions {
51
+ binary?: string;
52
+ /** Overall subprocess budget, in milliseconds; default 30000. */
53
+ timeout?: number;
54
+ environment?: Record<string, string | undefined>;
55
+ }
56
+ export interface CheckOptions { signal?: AbortSignal }
57
+ export type ConfigurationInput = Configuration | ConfigurationDocument | string;
58
+ export class Client {
59
+ constructor(options?: ClientOptions);
60
+ check(config: ConfigurationInput, options?: CheckOptions): Promise<CheckReport>;
61
+ }
62
+ export function check(config: ConfigurationInput, options?: ClientOptions & CheckOptions): Promise<CheckReport>;
63
+ export function parseReport(output: string, exitCode: number): CheckReport;
64
+ export class AgentHealthError extends Error {}
65
+ export class ConfigurationError extends AgentHealthError {}
66
+ export class BinaryNotFoundError extends AgentHealthError {}
67
+ export class CompatibilityError extends AgentHealthError {}
68
+ export class ExecutionError extends AgentHealthError {}
69
+ export class OutputError extends AgentHealthError {}
70
+ export class CheckTimeoutError extends AgentHealthError {}
71
+ export class CheckAbortedError extends AgentHealthError {}
package/index.js CHANGED
@@ -1 +1,167 @@
1
- module.exports = {};
1
+ /** Node.js-only wrapper. The Go reference CLI owns health semantics. */
2
+ import { spawn } from 'node:child_process';
3
+ import { mkdtemp, readFile, writeFile, rm, open } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { resolve, join } from 'node:path';
6
+ import { performance } from 'node:perf_hooks';
7
+ import Ajv2020 from 'ajv/dist/2020.js';
8
+ import { parseDocument } from 'yaml';
9
+
10
+ export const version = '0.15.0';
11
+ export const healthStates = Object.freeze(['HEALTHY', 'DEGRADED', 'UNHEALTHY', 'UNREACHABLE', 'MISCONFIGURED', 'UNKNOWN']);
12
+ export class AgentHealthError extends Error {
13
+ constructor(message) { super(message); this.name = new.target.name; }
14
+ }
15
+ export class ConfigurationError extends AgentHealthError {}
16
+ export class BinaryNotFoundError extends AgentHealthError {}
17
+ export class CompatibilityError extends AgentHealthError {}
18
+ export class ExecutionError extends AgentHealthError {}
19
+ export class OutputError extends AgentHealthError {}
20
+ export class CheckTimeoutError extends AgentHealthError {}
21
+ export class CheckAbortedError extends AgentHealthError {}
22
+ const ajv = new Ajv2020({ strict: false, allErrors: false });
23
+ const validators = {};
24
+ for (const name of ['configuration', 'result']) {
25
+ validators[name] = ajv.compile(JSON.parse(await readFile(new URL(`./schemas/${name}.schema.json`, import.meta.url), 'utf8')));
26
+ }
27
+ const MAX_CONFIG = 4 * 1024 * 1024;
28
+ const MAX_OUTPUT = 16 * 1024 * 1024;
29
+ const MAX_DIAGNOSTIC = 64 * 1024;
30
+ function serialize(data) {
31
+ // Reject values JSON would silently discard or turn into null.
32
+ return JSON.stringify(data, (_, value) => {
33
+ if (value === undefined || typeof value === 'function' || typeof value === 'symbol' ||
34
+ (typeof value === 'number' && !Number.isFinite(value))) throw new Error();
35
+ return value;
36
+ });
37
+ }
38
+ export class Configuration {
39
+ #data;
40
+ constructor(data, { baseDir = process.cwd() } = {}) {
41
+ try {
42
+ const text = serialize(data);
43
+ if (Buffer.byteLength(text) > MAX_CONFIG) throw new Error();
44
+ this.#data = JSON.parse(text);
45
+ if (!validators.configuration(this.#data)) throw new Error();
46
+ this.baseDir = resolve(baseDir);
47
+ Object.freeze(this);
48
+ } catch { throw new ConfigurationError('Invalid AgentHealth configuration'); }
49
+ }
50
+ toJSON() { return structuredClone(this.#data); }
51
+ }
52
+ export async function loadConfig(path, options) {
53
+ try {
54
+ const file = await open(path, 'r');
55
+ let bytes;
56
+ try {
57
+ const buffer = Buffer.alloc(MAX_CONFIG + 1);
58
+ let total = 0;
59
+ while (total < buffer.length) {
60
+ const { bytesRead } = await file.read(buffer, total, buffer.length - total, total);
61
+ if (!bytesRead) break;
62
+ total += bytesRead;
63
+ }
64
+ bytes = buffer.subarray(0, total);
65
+ } finally { await file.close(); }
66
+ if (bytes.length > MAX_CONFIG) throw new Error();
67
+ const document = parseDocument(bytes.toString('utf8'), { uniqueKeys: true });
68
+ if (document.errors.length) throw new Error();
69
+ return new Configuration(document.toJS({ maxAliasCount: 50 }), options);
70
+ } catch { throw new ConfigurationError('Unable to load AgentHealth configuration'); }
71
+ }
72
+ export function parseReport(output, exitCode) {
73
+ try {
74
+ if (Buffer.byteLength(output) > MAX_OUTPUT || !Number.isInteger(exitCode) || exitCode < 0 || exitCode > 5) throw new Error();
75
+ const document = JSON.parse(output);
76
+ if (!validators.result(document) || document.spec_version !== 'v1') throw new Error();
77
+ const results = document.results ?? [document];
78
+ if (Math.max(...results.map(result => healthStates.indexOf(result.status))) !== exitCode) throw new Error();
79
+ return { results, exitCode, status: healthStates[exitCode], spec_version: 'v1' };
80
+ } catch { throw new OutputError('Invalid AgentHealth result or exit-code contract'); }
81
+ }
82
+ async function run(binary, args, { cwd, environment, deadline, signal }) {
83
+ if (signal?.aborted) throw new CheckAbortedError('AgentHealth check aborted');
84
+ if (performance.now() >= deadline) throw new CheckTimeoutError('AgentHealth check deadline expired');
85
+ return new Promise((accept, reject) => {
86
+ let child;
87
+ try { child = spawn(binary, args, { cwd, env: { ...process.env, ...environment }, shell: false,
88
+ detached: process.platform !== 'win32', windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
89
+ } catch { reject(new ExecutionError('Unable to start AgentHealth CLI')); return; }
90
+ let chunks = [], size = 0, diagnosticSize = 0, failure, timer, killTimer;
91
+ function kill(sig) {
92
+ try {
93
+ if (process.platform === 'win32') child.kill(sig);
94
+ else process.kill(-child.pid, sig);
95
+ } catch { /* The process/group has already exited. */ }
96
+ }
97
+ function stop(error) {
98
+ failure ??= error;
99
+ kill('SIGTERM');
100
+ killTimer ??= setTimeout(() => kill('SIGKILL'), 1000);
101
+ }
102
+ const abort = () => stop(new CheckAbortedError('AgentHealth check aborted'));
103
+ signal?.addEventListener('abort', abort, { once: true });
104
+ // Close the abort race between the initial check and listener registration.
105
+ if (signal?.aborted) abort();
106
+ timer = setTimeout(() => stop(new CheckTimeoutError('AgentHealth check deadline expired')),
107
+ Math.max(1, deadline - performance.now()));
108
+ child.stdout.on('data', chunk => {
109
+ size += chunk.length;
110
+ if (size > MAX_OUTPUT) stop(new OutputError('AgentHealth output exceeded the SDK limit'));
111
+ else if (!failure) chunks.push(chunk);
112
+ });
113
+ child.stderr.on('data', chunk => {
114
+ diagnosticSize += chunk.length;
115
+ if (diagnosticSize > MAX_DIAGNOSTIC) stop(new OutputError('AgentHealth output exceeded the SDK limit'));
116
+ });
117
+ child.on('error', () => { failure ??= new BinaryNotFoundError('Unable to start AgentHealth CLI'); });
118
+ child.on('exit', () => {
119
+ // Descendants may retain pipe descriptors after their parent exits.
120
+ kill('SIGKILL');
121
+ });
122
+ child.on('close', code => {
123
+ clearTimeout(timer); clearTimeout(killTimer);
124
+ signal?.removeEventListener('abort', abort);
125
+ kill('SIGKILL');
126
+ if (failure) reject(failure);
127
+ else accept({ code, output: Buffer.concat(chunks).toString('utf8') });
128
+ });
129
+ });
130
+ }
131
+ export class Client {
132
+ constructor({ binary = 'agenthealth', timeout = 30000, environment = {} } = {}) {
133
+ if (!Number.isFinite(timeout) || timeout <= 0 || timeout > 2147483647) throw new RangeError('timeout must be between 0 and 2147483647 milliseconds');
134
+ if (typeof binary !== 'string' || !binary) throw new TypeError('binary must be an executable name or path');
135
+ this.binary = /[/\\]/.test(binary) ? resolve(binary) : binary;
136
+ this.timeout = timeout;
137
+ this.environment = { ...environment };
138
+ }
139
+ async check(config, { signal } = {}) {
140
+ const configuration = config instanceof Configuration ? config : typeof config === 'string' ? await loadConfig(config) : new Configuration(config);
141
+ const options = { cwd: configuration.baseDir, environment: this.environment,
142
+ deadline: performance.now() + this.timeout, signal };
143
+ const cli = await run(this.binary, ['version'], { ...options, deadline: Math.min(options.deadline, performance.now() + 5000) });
144
+ if (cli.code !== 0 || cli.output.trim() !== `agenthealth v${version}`) throw new CompatibilityError('AgentHealth CLI must match the SDK software version');
145
+ let directory, report, failure;
146
+ try {
147
+ directory = await mkdtemp(join(tmpdir(), 'agenthealth-js-'));
148
+ const path = join(directory, 'configuration.json');
149
+ await writeFile(path, JSON.stringify(configuration.toJSON()), { mode: 0o600, flag: 'wx' });
150
+ const { code, output } = await run(this.binary, ['check', '--format', 'json', '--', path], options);
151
+ if (!Number.isInteger(code) || code < 0 || code > 5) throw new ExecutionError('AgentHealth CLI execution failed');
152
+ report = parseReport(output, code);
153
+ } catch (error) {
154
+ failure = error instanceof AgentHealthError ? error : new ExecutionError('Unable to prepare AgentHealth CLI execution');
155
+ } finally {
156
+ if (directory) {
157
+ try { await rm(directory, { recursive: true, force: true }); }
158
+ catch { failure ??= new ExecutionError('Unable to clean up AgentHealth CLI execution'); }
159
+ }
160
+ }
161
+ if (failure) throw failure;
162
+ return report;
163
+ }
164
+ }
165
+ export function check(config, options = {}) {
166
+ return new Client(options).check(config, { signal: options.signal });
167
+ }
package/package.json CHANGED
@@ -1,15 +1,45 @@
1
1
  {
2
2
  "name": "@theagenthealth/agenthealth",
3
- "version": "0.0.0",
4
- "description": "Universal Agent Health Protocol - Initial Package",
5
- "main": "index.js",
6
- "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1"
8
- },
9
- "keywords": [],
10
- "author": "",
3
+ "version": "0.15.0",
4
+ "description": "Typed Node.js SDK for the AgentHealth reference CLI",
11
5
  "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "./index.js",
8
+ "types": "./index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./index.d.ts",
12
+ "import": "./index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "index.js",
17
+ "index.d.ts",
18
+ "schemas",
19
+ "README.md",
20
+ "LICENSE"
21
+ ],
22
+ "engines": {
23
+ "node": ">=22.14.0"
24
+ },
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/TheAgentHealth/agenthealth.git",
28
+ "directory": "sdk/javascript"
29
+ },
12
30
  "publishConfig": {
13
31
  "access": "public"
32
+ },
33
+ "scripts": {
34
+ "test": "node --test test/*.test.js",
35
+ "typecheck": "tsc --noEmit --strict --module nodenext --target es2022 test/types.ts"
36
+ },
37
+ "dependencies": {
38
+ "ajv": "8.20.0",
39
+ "yaml": "2.9.1"
40
+ },
41
+ "devDependencies": {
42
+ "@types/node": "22.18.6",
43
+ "typescript": "5.9.3"
14
44
  }
15
45
  }