@novtia-npm/airg-client 0.0.0-stage → 0.4.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/README.md +142 -3
- package/dist/cjs/index.d.ts +261 -0
- package/dist/cjs/index.js +310 -0
- package/dist/esm/index.js +303 -0
- package/dist/esm/package.json +3 -0
- package/package.json +43 -6
package/README.md
CHANGED
|
@@ -1,3 +1,142 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# @novtia-npm/airg-client
|
|
2
|
+
|
|
3
|
+
TypeScript/JavaScript client for the **AI Runtime Governor** – a runtime governance layer for AI agents.
|
|
4
|
+
|
|
5
|
+
The Governor evaluates every tool invocation against configurable policies and
|
|
6
|
+
returns an **allow / block / review** decision before the tool executes.
|
|
7
|
+
|
|
8
|
+
## Installation
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
npm install @novtia-npm/airg-client
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
Requires Node 18 or later (it uses the built-in `fetch`). Earlier versions were
|
|
15
|
+
published to GitHub Packages as `@othnielobasi/airg-client`; use
|
|
16
|
+
`@novtia-npm/airg-client` from npm instead.
|
|
17
|
+
|
|
18
|
+
## Quick start
|
|
19
|
+
|
|
20
|
+
```typescript
|
|
21
|
+
import { GovernorClient, GovernorBlockedError } from "@novtia-npm/airg-client";
|
|
22
|
+
|
|
23
|
+
const gov = new GovernorClient();
|
|
24
|
+
// Reads GOVERNOR_URL and GOVERNOR_API_KEY from environment automatically
|
|
25
|
+
|
|
26
|
+
try {
|
|
27
|
+
const decision = await gov.evaluate("issue_refund", { order_id: "A-1001", amount: 40, currency: "GBP" });
|
|
28
|
+
console.log(decision.decision); // "allow" | "review"
|
|
29
|
+
console.log(decision.risk_score); // 0 – 100
|
|
30
|
+
console.log(decision.explanation);
|
|
31
|
+
} catch (err) {
|
|
32
|
+
if (err instanceof GovernorBlockedError) {
|
|
33
|
+
console.error("Blocked:", err.message);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Configuration
|
|
39
|
+
|
|
40
|
+
| Option | Env variable | Default | Description |
|
|
41
|
+
|---|---|---|---|
|
|
42
|
+
| `baseUrl` | `GOVERNOR_URL` | `http://localhost:8000` | Base URL of the Governor service |
|
|
43
|
+
| `apiKey` | `GOVERNOR_API_KEY` | *(empty)* | API key (`airg_…`) sent as `X-API-Key` header |
|
|
44
|
+
| `timeoutMs` | — | `10000` | Request timeout in milliseconds |
|
|
45
|
+
|
|
46
|
+
Environment variables are read automatically when options are not provided.
|
|
47
|
+
|
|
48
|
+
## API
|
|
49
|
+
|
|
50
|
+
### `new GovernorClient(options?)`
|
|
51
|
+
|
|
52
|
+
Create a client instance. All options are optional.
|
|
53
|
+
|
|
54
|
+
### `client.evaluate(tool, args, context?, options?) → Promise<GovernorDecision>`
|
|
55
|
+
|
|
56
|
+
Evaluate a tool call. Throws `GovernorBlockedError` if the decision is `"block"`.
|
|
57
|
+
|
|
58
|
+
**Review decisions.** By default (`reviewMode: "hold"`, since 0.4.0) a
|
|
59
|
+
`"review"` decision waits up to `holdTimeoutSeconds` (default 60, capped at
|
|
60
|
+
300 by the Governor) for a reviewer. The call returns only if the action is
|
|
61
|
+
approved; otherwise it throws `GovernorReviewRejectedError` or
|
|
62
|
+
`GovernorReviewExpiredError`, so your code does not run it.
|
|
63
|
+
|
|
64
|
+
```typescript
|
|
65
|
+
await gov.evaluate("wire_transfer", { amount: 250000 }, undefined, { holdTimeoutSeconds: 120 });
|
|
66
|
+
// resolves once approved; throws GovernorReviewRejectedError or GovernorReviewExpiredError otherwise
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
To get the decision back at once instead, pass `{ reviewMode: "proceed" }`.
|
|
70
|
+
Your code must then not run the action until a reviewer approves it; the
|
|
71
|
+
client logs a warning the first time this happens.
|
|
72
|
+
|
|
73
|
+
**Upgrading from 0.3.x:** `evaluate` used to return `"review"` decisions
|
|
74
|
+
immediately. Code that handles reviews itself should pass
|
|
75
|
+
`{ reviewMode: "proceed" }`.
|
|
76
|
+
|
|
77
|
+
### `client.governedCall(tool, args, context?, options?) → Promise<GovernorDecision>`
|
|
78
|
+
|
|
79
|
+
Alias for `evaluate`, with the same review handling.
|
|
80
|
+
|
|
81
|
+
### `client.getStatus() → Promise<object>`
|
|
82
|
+
|
|
83
|
+
Fetch the current admin status (kill switch state, etc.).
|
|
84
|
+
|
|
85
|
+
### `client.getSummary() → Promise<object>`
|
|
86
|
+
|
|
87
|
+
Fetch the governor summary (total actions, block rate, etc.).
|
|
88
|
+
|
|
89
|
+
### `client.ingestSpans(spans) → Promise<IngestResult>`
|
|
90
|
+
|
|
91
|
+
Batch-ingest agent trace spans (up to 500). Idempotent — duplicate `span_id` values are silently skipped.
|
|
92
|
+
|
|
93
|
+
Valid span kinds: `agent`, `llm`, `tool`, `governance`, `retrieval`, `chain`, `custom`.
|
|
94
|
+
|
|
95
|
+
Returns `{ inserted, skipped }`.
|
|
96
|
+
|
|
97
|
+
```ts
|
|
98
|
+
await gov.ingestSpans([
|
|
99
|
+
{ trace_id: "t-123", span_id: "s-1", kind: "agent", name: "main", start_time: new Date().toISOString() },
|
|
100
|
+
{ trace_id: "t-123", span_id: "s-2", kind: "llm", name: "gpt-4", start_time: new Date().toISOString(), parent_span_id: "s-1" },
|
|
101
|
+
]);
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### `client.listTraces(options?) → Promise<TraceListItem[]>`
|
|
105
|
+
|
|
106
|
+
List traces. Optional filters: `agent_id`, `session_id`, `has_blocks`, `limit`, `offset`.
|
|
107
|
+
|
|
108
|
+
### `client.getTrace(traceId) → Promise<TraceDetail>`
|
|
109
|
+
|
|
110
|
+
Full trace detail — all spans plus correlated governance decisions.
|
|
111
|
+
|
|
112
|
+
### `client.deleteTrace(traceId) → Promise<DeleteTraceResult>`
|
|
113
|
+
|
|
114
|
+
Delete all spans for a trace. Returns `{ trace_id, spans_deleted }`.
|
|
115
|
+
|
|
116
|
+
### `GovernorBlockedError`
|
|
117
|
+
|
|
118
|
+
Error thrown when the Governor blocks a tool invocation. Has a `.decision` property
|
|
119
|
+
with the full `GovernorDecision` object.
|
|
120
|
+
|
|
121
|
+
## Trace correlation
|
|
122
|
+
|
|
123
|
+
Pass `trace_id` and `span_id` in the `context` parameter of `evaluate()` to auto-create
|
|
124
|
+
a governance span in the agent's trace tree:
|
|
125
|
+
|
|
126
|
+
```ts
|
|
127
|
+
const decision = await gov.evaluate("issue_refund", { order_id: "A-1001", amount: 40 }, {
|
|
128
|
+
trace_id: "t-123",
|
|
129
|
+
span_id: "s-2", // governance span will be a child of this span
|
|
130
|
+
agent_id: "my-agent",
|
|
131
|
+
});
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
## Requirements
|
|
135
|
+
|
|
136
|
+
- Node.js ≥ 18 (uses built-in `fetch`)
|
|
137
|
+
- Zero runtime dependencies
|
|
138
|
+
|
|
139
|
+
## License
|
|
140
|
+
|
|
141
|
+
MIT — see [LICENSE](../LICENSE).
|
|
142
|
+
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @novtia-npm/airg-client
|
|
3
|
+
* =========================
|
|
4
|
+
* TypeScript client for the AI Runtime Governor – a runtime governance layer
|
|
5
|
+
* for AI agents.
|
|
6
|
+
*
|
|
7
|
+
* The Governor evaluates every tool invocation against configurable policies
|
|
8
|
+
* and returns an **allow / block / review** decision before the tool executes.
|
|
9
|
+
*
|
|
10
|
+
* Also provides trace observability: ingest agent trace spans, query traces,
|
|
11
|
+
* and correlate governance decisions with the agent's execution timeline.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```ts
|
|
15
|
+
* import { GovernorClient } from "@novtia-npm/airg-client";
|
|
16
|
+
*
|
|
17
|
+
* const gov = new GovernorClient({
|
|
18
|
+
* baseUrl: "https://api.airg.nov-tia.com",
|
|
19
|
+
* apiKey: "airg_your_key_here",
|
|
20
|
+
* });
|
|
21
|
+
*
|
|
22
|
+
* const decision = await gov.evaluate("shell_exec", { command: "ls -la" });
|
|
23
|
+
* console.log(decision.decision); // "allow" | "block" | "review"
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
/** Decision returned by the Governor for a tool evaluation. */
|
|
27
|
+
export interface GovernorDecision {
|
|
28
|
+
decision: "allow" | "block" | "review";
|
|
29
|
+
risk_score: number;
|
|
30
|
+
explanation: string;
|
|
31
|
+
policy_ids: string[];
|
|
32
|
+
modified_args: Record<string, unknown> | null;
|
|
33
|
+
/** Additional fields the server may return. */
|
|
34
|
+
[key: string]: unknown;
|
|
35
|
+
}
|
|
36
|
+
/** How {@link GovernorClient.evaluate} handles a `"review"` decision. */
|
|
37
|
+
export type ReviewMode = "hold" | "proceed";
|
|
38
|
+
/** Options for {@link GovernorClient.evaluate}. */
|
|
39
|
+
export interface EvaluateOptions {
|
|
40
|
+
/**
|
|
41
|
+
* `"hold"` waits for a reviewer and returns only if the action is approved;
|
|
42
|
+
* otherwise it throws. `"proceed"` returns the `"review"` decision at once,
|
|
43
|
+
* and the caller must not run the action until it is approved.
|
|
44
|
+
* @default "hold"
|
|
45
|
+
*/
|
|
46
|
+
reviewMode?: ReviewMode;
|
|
47
|
+
/**
|
|
48
|
+
* Seconds to wait for a reviewer. The Governor caps this at 300.
|
|
49
|
+
* @default 60
|
|
50
|
+
*/
|
|
51
|
+
holdTimeoutSeconds?: number;
|
|
52
|
+
/**
|
|
53
|
+
* Seconds between the Governor's checks while waiting (0.5 to 5).
|
|
54
|
+
* @default 1
|
|
55
|
+
*/
|
|
56
|
+
holdPollIntervalSeconds?: number;
|
|
57
|
+
}
|
|
58
|
+
/** Options for constructing a {@link GovernorClient}. */
|
|
59
|
+
export interface GovernorClientOptions {
|
|
60
|
+
/**
|
|
61
|
+
* Base URL of the Governor service.
|
|
62
|
+
* @default process.env.GOVERNOR_URL ?? "http://localhost:8000"
|
|
63
|
+
*/
|
|
64
|
+
baseUrl?: string;
|
|
65
|
+
/**
|
|
66
|
+
* API key (`airg_…`) sent as the `X-API-Key` header.
|
|
67
|
+
* @default process.env.GOVERNOR_API_KEY ?? ""
|
|
68
|
+
*/
|
|
69
|
+
apiKey?: string;
|
|
70
|
+
/**
|
|
71
|
+
* Request timeout in milliseconds.
|
|
72
|
+
* @default 10_000
|
|
73
|
+
*/
|
|
74
|
+
timeoutMs?: number;
|
|
75
|
+
/**
|
|
76
|
+
* Maximum number of retry attempts for transient failures (502, 503, 504, 429).
|
|
77
|
+
* @default 3
|
|
78
|
+
*/
|
|
79
|
+
maxRetries?: number;
|
|
80
|
+
}
|
|
81
|
+
/** Valid span kinds for agent traces. */
|
|
82
|
+
export type SpanKind = "agent" | "llm" | "tool" | "governance" | "retrieval" | "chain" | "custom";
|
|
83
|
+
/** A single span to ingest into the trace system. */
|
|
84
|
+
export interface SpanInput {
|
|
85
|
+
trace_id: string;
|
|
86
|
+
span_id: string;
|
|
87
|
+
parent_span_id?: string | null;
|
|
88
|
+
kind: SpanKind;
|
|
89
|
+
name: string;
|
|
90
|
+
status?: "ok" | "error";
|
|
91
|
+
start_time: string;
|
|
92
|
+
end_time?: string | null;
|
|
93
|
+
duration_ms?: number | null;
|
|
94
|
+
agent_id?: string | null;
|
|
95
|
+
session_id?: string | null;
|
|
96
|
+
attributes?: Record<string, unknown> | null;
|
|
97
|
+
input?: string | null;
|
|
98
|
+
output?: string | null;
|
|
99
|
+
events?: Array<Record<string, unknown>> | null;
|
|
100
|
+
}
|
|
101
|
+
/** Result of a batch ingest call. */
|
|
102
|
+
export interface IngestResult {
|
|
103
|
+
inserted: number;
|
|
104
|
+
skipped: number;
|
|
105
|
+
}
|
|
106
|
+
/** Summary of a trace returned by list. */
|
|
107
|
+
export interface TraceListItem {
|
|
108
|
+
trace_id: string;
|
|
109
|
+
agent_id: string | null;
|
|
110
|
+
session_id: string | null;
|
|
111
|
+
span_count: number;
|
|
112
|
+
governance_count: number;
|
|
113
|
+
root_span_name: string | null;
|
|
114
|
+
start_time: string;
|
|
115
|
+
end_time: string | null;
|
|
116
|
+
total_duration_ms: number | null;
|
|
117
|
+
has_errors: boolean;
|
|
118
|
+
has_blocks: boolean;
|
|
119
|
+
}
|
|
120
|
+
/** Full trace detail with all spans and governance decisions. */
|
|
121
|
+
export interface TraceDetail {
|
|
122
|
+
trace_id: string;
|
|
123
|
+
agent_id: string | null;
|
|
124
|
+
session_id: string | null;
|
|
125
|
+
spans: Array<Record<string, unknown>>;
|
|
126
|
+
governance_decisions: Array<Record<string, unknown>>;
|
|
127
|
+
span_count: number;
|
|
128
|
+
governance_count: number;
|
|
129
|
+
start_time: string | null;
|
|
130
|
+
end_time: string | null;
|
|
131
|
+
total_duration_ms: number | null;
|
|
132
|
+
has_errors: boolean;
|
|
133
|
+
has_blocks: boolean;
|
|
134
|
+
}
|
|
135
|
+
/** Delete result. */
|
|
136
|
+
export interface DeleteTraceResult {
|
|
137
|
+
trace_id: string;
|
|
138
|
+
spans_deleted: number;
|
|
139
|
+
}
|
|
140
|
+
/** Optional filters for listing traces. */
|
|
141
|
+
export interface TraceListOptions {
|
|
142
|
+
agent_id?: string;
|
|
143
|
+
session_id?: string;
|
|
144
|
+
has_blocks?: boolean;
|
|
145
|
+
limit?: number;
|
|
146
|
+
offset?: number;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Thrown when the Governor blocks a tool invocation.
|
|
150
|
+
*/
|
|
151
|
+
export declare class GovernorBlockedError extends Error {
|
|
152
|
+
readonly decision: GovernorDecision;
|
|
153
|
+
constructor(tool: string, decision: GovernorDecision);
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Thrown when a reviewer rejects an action that needed approval.
|
|
157
|
+
*/
|
|
158
|
+
export declare class GovernorReviewRejectedError extends Error {
|
|
159
|
+
readonly decision: GovernorDecision;
|
|
160
|
+
constructor(tool: string, decision: GovernorDecision, note?: string | null);
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Thrown when an action that needed approval was not approved: the wait timed
|
|
164
|
+
* out, the request expired, or there was no approval request to wait for.
|
|
165
|
+
*/
|
|
166
|
+
export declare class GovernorReviewExpiredError extends Error {
|
|
167
|
+
readonly decision: GovernorDecision;
|
|
168
|
+
constructor(message: string, decision: GovernorDecision);
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Stateless HTTP client for the AI Runtime Governor service.
|
|
172
|
+
*
|
|
173
|
+
* Uses the built-in `fetch` API (Node 18+, all modern browsers).
|
|
174
|
+
*/
|
|
175
|
+
export declare class GovernorClient {
|
|
176
|
+
readonly baseUrl: string;
|
|
177
|
+
readonly apiKey: string;
|
|
178
|
+
private readonly timeoutMs;
|
|
179
|
+
private readonly maxRetries;
|
|
180
|
+
private reviewWarningShown;
|
|
181
|
+
private static readonly RETRYABLE_STATUS;
|
|
182
|
+
constructor(options?: GovernorClientOptions);
|
|
183
|
+
private headers;
|
|
184
|
+
private request;
|
|
185
|
+
/**
|
|
186
|
+
* Evaluate a tool call against the Governor.
|
|
187
|
+
*
|
|
188
|
+
* A `"review"` decision waits for a reviewer by default and returns only if
|
|
189
|
+
* the action is approved. Pass `{ reviewMode: "proceed" }` to get the
|
|
190
|
+
* decision back at once instead.
|
|
191
|
+
*
|
|
192
|
+
* @returns The full decision object.
|
|
193
|
+
* @throws {GovernorBlockedError} if the decision is `"block"`.
|
|
194
|
+
* @throws {GovernorReviewRejectedError} if a reviewer rejects the action.
|
|
195
|
+
* @throws {GovernorReviewExpiredError} if the action is not approved in time
|
|
196
|
+
* or cannot be approved.
|
|
197
|
+
*/
|
|
198
|
+
evaluate(tool: string, args: Record<string, unknown>, context?: Record<string, unknown>, options?: EvaluateOptions): Promise<GovernorDecision>;
|
|
199
|
+
/**
|
|
200
|
+
* Convenience alias for {@link evaluate}, with the same review handling.
|
|
201
|
+
*/
|
|
202
|
+
governedCall(tool: string, args: Record<string, unknown>, context?: Record<string, unknown>, options?: EvaluateOptions): Promise<GovernorDecision>;
|
|
203
|
+
/**
|
|
204
|
+
* Fetch the current admin status (kill switch state, etc.).
|
|
205
|
+
*/
|
|
206
|
+
getStatus(): Promise<Record<string, unknown>>;
|
|
207
|
+
/**
|
|
208
|
+
* Fetch the governor summary (total actions, block rate, etc.).
|
|
209
|
+
*/
|
|
210
|
+
getSummary(): Promise<Record<string, unknown>>;
|
|
211
|
+
/**
|
|
212
|
+
* Batch-ingest agent trace spans.
|
|
213
|
+
*
|
|
214
|
+
* Valid span kinds: agent, llm, tool, governance, retrieval, chain, custom.
|
|
215
|
+
* Duplicate `span_id` values are silently skipped (idempotent).
|
|
216
|
+
*
|
|
217
|
+
* @param spans Array of span objects (up to 500).
|
|
218
|
+
* @returns `{ inserted, skipped }` counts.
|
|
219
|
+
*/
|
|
220
|
+
ingestSpans(spans: SpanInput[]): Promise<IngestResult>;
|
|
221
|
+
/**
|
|
222
|
+
* List traces with optional filters.
|
|
223
|
+
*
|
|
224
|
+
* @returns Array of trace summaries.
|
|
225
|
+
*/
|
|
226
|
+
listTraces(options?: TraceListOptions): Promise<TraceListItem[]>;
|
|
227
|
+
/**
|
|
228
|
+
* Fetch full trace detail — all spans plus correlated governance decisions.
|
|
229
|
+
*
|
|
230
|
+
* @param traceId The trace identifier.
|
|
231
|
+
*/
|
|
232
|
+
getTrace(traceId: string): Promise<TraceDetail>;
|
|
233
|
+
/**
|
|
234
|
+
* Delete all spans for a trace (action log entries are preserved).
|
|
235
|
+
*
|
|
236
|
+
* @param traceId The trace identifier.
|
|
237
|
+
* @returns `{ trace_id, spans_deleted }`.
|
|
238
|
+
*/
|
|
239
|
+
deleteTrace(traceId: string): Promise<DeleteTraceResult>;
|
|
240
|
+
/**
|
|
241
|
+
* Scan agent response text for injection, PII leakage, and other threats
|
|
242
|
+
* before sending to users.
|
|
243
|
+
*
|
|
244
|
+
* @returns Object with `safe`, `risk_score`, `findings`, and `sanitized_text`.
|
|
245
|
+
*/
|
|
246
|
+
scanOutput(text: string, options?: {
|
|
247
|
+
agent_id?: string;
|
|
248
|
+
session_id?: string;
|
|
249
|
+
context?: Record<string, unknown>;
|
|
250
|
+
}): Promise<Record<string, unknown>>;
|
|
251
|
+
/**
|
|
252
|
+
* Submit a tool execution result for post-execution verification.
|
|
253
|
+
*
|
|
254
|
+
* @param actionId The action_id from the original evaluate call.
|
|
255
|
+
* @param tool The tool name.
|
|
256
|
+
* @param result The tool execution result.
|
|
257
|
+
* @returns Verification verdict with findings.
|
|
258
|
+
*/
|
|
259
|
+
verify(actionId: number, tool: string, result: Record<string, unknown>, context?: Record<string, unknown>): Promise<Record<string, unknown>>;
|
|
260
|
+
}
|
|
261
|
+
export default GovernorClient;
|
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* @novtia-npm/airg-client
|
|
4
|
+
* =========================
|
|
5
|
+
* TypeScript client for the AI Runtime Governor – a runtime governance layer
|
|
6
|
+
* for AI agents.
|
|
7
|
+
*
|
|
8
|
+
* The Governor evaluates every tool invocation against configurable policies
|
|
9
|
+
* and returns an **allow / block / review** decision before the tool executes.
|
|
10
|
+
*
|
|
11
|
+
* Also provides trace observability: ingest agent trace spans, query traces,
|
|
12
|
+
* and correlate governance decisions with the agent's execution timeline.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```ts
|
|
16
|
+
* import { GovernorClient } from "@novtia-npm/airg-client";
|
|
17
|
+
*
|
|
18
|
+
* const gov = new GovernorClient({
|
|
19
|
+
* baseUrl: "https://api.airg.nov-tia.com",
|
|
20
|
+
* apiKey: "airg_your_key_here",
|
|
21
|
+
* });
|
|
22
|
+
*
|
|
23
|
+
* const decision = await gov.evaluate("shell_exec", { command: "ls -la" });
|
|
24
|
+
* console.log(decision.decision); // "allow" | "block" | "review"
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
28
|
+
exports.GovernorClient = exports.GovernorReviewExpiredError = exports.GovernorReviewRejectedError = exports.GovernorBlockedError = void 0;
|
|
29
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
// Errors
|
|
31
|
+
// ---------------------------------------------------------------------------
|
|
32
|
+
/**
|
|
33
|
+
* Thrown when the Governor blocks a tool invocation.
|
|
34
|
+
*/
|
|
35
|
+
class GovernorBlockedError extends Error {
|
|
36
|
+
constructor(tool, decision) {
|
|
37
|
+
super(`Governor blocked tool '${tool}': ${decision.explanation ?? "no reason given"}`);
|
|
38
|
+
this.name = "GovernorBlockedError";
|
|
39
|
+
this.decision = decision;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
exports.GovernorBlockedError = GovernorBlockedError;
|
|
43
|
+
/**
|
|
44
|
+
* Thrown when a reviewer rejects an action that needed approval.
|
|
45
|
+
*/
|
|
46
|
+
class GovernorReviewRejectedError extends Error {
|
|
47
|
+
constructor(tool, decision, note) {
|
|
48
|
+
super(`Review for tool '${tool}' was rejected: ${note ?? "no reason given"}`);
|
|
49
|
+
this.name = "GovernorReviewRejectedError";
|
|
50
|
+
this.decision = decision;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
exports.GovernorReviewRejectedError = GovernorReviewRejectedError;
|
|
54
|
+
/**
|
|
55
|
+
* Thrown when an action that needed approval was not approved: the wait timed
|
|
56
|
+
* out, the request expired, or there was no approval request to wait for.
|
|
57
|
+
*/
|
|
58
|
+
class GovernorReviewExpiredError extends Error {
|
|
59
|
+
constructor(message, decision) {
|
|
60
|
+
super(message);
|
|
61
|
+
this.name = "GovernorReviewExpiredError";
|
|
62
|
+
this.decision = decision;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
exports.GovernorReviewExpiredError = GovernorReviewExpiredError;
|
|
66
|
+
// ---------------------------------------------------------------------------
|
|
67
|
+
// Client
|
|
68
|
+
// ---------------------------------------------------------------------------
|
|
69
|
+
/**
|
|
70
|
+
* Stateless HTTP client for the AI Runtime Governor service.
|
|
71
|
+
*
|
|
72
|
+
* Uses the built-in `fetch` API (Node 18+, all modern browsers).
|
|
73
|
+
*/
|
|
74
|
+
class GovernorClient {
|
|
75
|
+
constructor(options = {}) {
|
|
76
|
+
this.reviewWarningShown = false;
|
|
77
|
+
const env = typeof process !== "undefined" ? process.env : {};
|
|
78
|
+
this.baseUrl = (options.baseUrl ?? env.GOVERNOR_URL ?? "http://localhost:8000").replace(/\/+$/, "");
|
|
79
|
+
this.apiKey = options.apiKey ?? env.GOVERNOR_API_KEY ?? "";
|
|
80
|
+
this.timeoutMs = options.timeoutMs ?? 10000;
|
|
81
|
+
this.maxRetries = options.maxRetries ?? 3;
|
|
82
|
+
}
|
|
83
|
+
// ── Internal helpers ────────────────────────────────────────
|
|
84
|
+
headers() {
|
|
85
|
+
const h = { "Content-Type": "application/json" };
|
|
86
|
+
if (this.apiKey) {
|
|
87
|
+
h["X-API-Key"] = this.apiKey;
|
|
88
|
+
}
|
|
89
|
+
return h;
|
|
90
|
+
}
|
|
91
|
+
async request(method, path, body, options = {}) {
|
|
92
|
+
let lastError;
|
|
93
|
+
const maxRetries = options.maxRetries ?? this.maxRetries;
|
|
94
|
+
const timeoutMs = options.timeoutMs ?? this.timeoutMs;
|
|
95
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
96
|
+
const url = `${this.baseUrl}${path}`;
|
|
97
|
+
const controller = new AbortController();
|
|
98
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
99
|
+
try {
|
|
100
|
+
const res = await fetch(url, {
|
|
101
|
+
method,
|
|
102
|
+
headers: this.headers(),
|
|
103
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
104
|
+
signal: controller.signal,
|
|
105
|
+
});
|
|
106
|
+
if (GovernorClient.RETRYABLE_STATUS.has(res.status) && attempt < maxRetries) {
|
|
107
|
+
let delay = Math.min(2 ** attempt * 500, 8000);
|
|
108
|
+
if (res.status === 429) {
|
|
109
|
+
const retryAfter = res.headers.get("Retry-After");
|
|
110
|
+
if (retryAfter)
|
|
111
|
+
delay = Math.min(parseFloat(retryAfter) * 1000, 30000);
|
|
112
|
+
}
|
|
113
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (!res.ok) {
|
|
117
|
+
const text = await res.text().catch(() => "");
|
|
118
|
+
throw new Error(`Governor API ${method} ${path} returned ${res.status}: ${text}`);
|
|
119
|
+
}
|
|
120
|
+
return (await res.json());
|
|
121
|
+
}
|
|
122
|
+
catch (err) {
|
|
123
|
+
lastError = err;
|
|
124
|
+
if (err.name === "AbortError" && attempt < maxRetries) {
|
|
125
|
+
await new Promise((r) => setTimeout(r, Math.min(2 ** attempt * 500, 8000)));
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
if (attempt >= maxRetries)
|
|
129
|
+
throw err;
|
|
130
|
+
}
|
|
131
|
+
finally {
|
|
132
|
+
clearTimeout(timer);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
throw lastError;
|
|
136
|
+
}
|
|
137
|
+
// ── Public API ──────────────────────────────────────────────
|
|
138
|
+
/**
|
|
139
|
+
* Evaluate a tool call against the Governor.
|
|
140
|
+
*
|
|
141
|
+
* A `"review"` decision waits for a reviewer by default and returns only if
|
|
142
|
+
* the action is approved. Pass `{ reviewMode: "proceed" }` to get the
|
|
143
|
+
* decision back at once instead.
|
|
144
|
+
*
|
|
145
|
+
* @returns The full decision object.
|
|
146
|
+
* @throws {GovernorBlockedError} if the decision is `"block"`.
|
|
147
|
+
* @throws {GovernorReviewRejectedError} if a reviewer rejects the action.
|
|
148
|
+
* @throws {GovernorReviewExpiredError} if the action is not approved in time
|
|
149
|
+
* or cannot be approved.
|
|
150
|
+
*/
|
|
151
|
+
async evaluate(tool, args, context, options = {}) {
|
|
152
|
+
const reviewMode = options.reviewMode ?? "hold";
|
|
153
|
+
if (reviewMode !== "hold" && reviewMode !== "proceed") {
|
|
154
|
+
throw new Error(`reviewMode must be "hold" or "proceed", got "${String(reviewMode)}"`);
|
|
155
|
+
}
|
|
156
|
+
const result = await this.request("POST", "/actions/evaluate", { tool, args, context: context ?? null });
|
|
157
|
+
if (result.decision === "block") {
|
|
158
|
+
throw new GovernorBlockedError(tool, result);
|
|
159
|
+
}
|
|
160
|
+
if (result.decision !== "review") {
|
|
161
|
+
return result;
|
|
162
|
+
}
|
|
163
|
+
if (reviewMode === "proceed") {
|
|
164
|
+
if (!this.reviewWarningShown) {
|
|
165
|
+
this.reviewWarningShown = true;
|
|
166
|
+
console.warn(`Governor returned "review" for tool '${tool}' and reviewMode is "proceed", so this ` +
|
|
167
|
+
"call returned without waiting for approval. Do not run the action until it is " +
|
|
168
|
+
'approved, or use reviewMode "hold" to wait for a reviewer.');
|
|
169
|
+
}
|
|
170
|
+
return result;
|
|
171
|
+
}
|
|
172
|
+
const escalationId = result.escalation_id;
|
|
173
|
+
if (escalationId === undefined || escalationId === null || escalationId === "") {
|
|
174
|
+
// Nothing to wait for means nobody can approve it: fail closed.
|
|
175
|
+
throw new GovernorReviewExpiredError(`Review for tool '${tool}' has no approval request to wait for`, result);
|
|
176
|
+
}
|
|
177
|
+
const timeout = Math.max(1, Math.min(Math.floor(options.holdTimeoutSeconds ?? 60), 300));
|
|
178
|
+
const poll = Math.max(0.5, Math.min(options.holdPollIntervalSeconds ?? 1, 5));
|
|
179
|
+
let hold;
|
|
180
|
+
try {
|
|
181
|
+
hold = await this.request("POST", `/escalation/queue/${encodeURIComponent(String(escalationId))}/hold` +
|
|
182
|
+
`?timeout_seconds=${timeout}&poll_interval=${poll}`, undefined, { timeoutMs: (timeout + 10) * 1000, maxRetries: 0 });
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
hold = { status: "pending", timed_out: true };
|
|
186
|
+
}
|
|
187
|
+
const reviewed = {
|
|
188
|
+
...result,
|
|
189
|
+
review_status: hold.status ?? "unknown",
|
|
190
|
+
review_resolved_by: hold.resolved_by ?? null,
|
|
191
|
+
review_resolution_note: hold.resolution_note ?? null,
|
|
192
|
+
};
|
|
193
|
+
if (hold.status === "rejected") {
|
|
194
|
+
throw new GovernorReviewRejectedError(tool, reviewed, hold.resolution_note);
|
|
195
|
+
}
|
|
196
|
+
if (hold.status !== "approved") {
|
|
197
|
+
// Only an explicit approval lets the caller go ahead.
|
|
198
|
+
throw new GovernorReviewExpiredError(hold.timed_out
|
|
199
|
+
? `Review for tool '${tool}' timed out after ${timeout}s`
|
|
200
|
+
: `Review for tool '${tool}' ended as '${String(hold.status)}', not approved`, reviewed);
|
|
201
|
+
}
|
|
202
|
+
return reviewed;
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Convenience alias for {@link evaluate}, with the same review handling.
|
|
206
|
+
*/
|
|
207
|
+
async governedCall(tool, args, context, options = {}) {
|
|
208
|
+
return this.evaluate(tool, args, context, options);
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Fetch the current admin status (kill switch state, etc.).
|
|
212
|
+
*/
|
|
213
|
+
async getStatus() {
|
|
214
|
+
return this.request("GET", "/admin/status");
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Fetch the governor summary (total actions, block rate, etc.).
|
|
218
|
+
*/
|
|
219
|
+
async getSummary() {
|
|
220
|
+
return this.request("GET", "/summary/overview");
|
|
221
|
+
}
|
|
222
|
+
// ── Trace observability ─────────────────────────────────────
|
|
223
|
+
/**
|
|
224
|
+
* Batch-ingest agent trace spans.
|
|
225
|
+
*
|
|
226
|
+
* Valid span kinds: agent, llm, tool, governance, retrieval, chain, custom.
|
|
227
|
+
* Duplicate `span_id` values are silently skipped (idempotent).
|
|
228
|
+
*
|
|
229
|
+
* @param spans Array of span objects (up to 500).
|
|
230
|
+
* @returns `{ inserted, skipped }` counts.
|
|
231
|
+
*/
|
|
232
|
+
async ingestSpans(spans) {
|
|
233
|
+
return this.request("POST", "/traces/ingest", { spans });
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* List traces with optional filters.
|
|
237
|
+
*
|
|
238
|
+
* @returns Array of trace summaries.
|
|
239
|
+
*/
|
|
240
|
+
async listTraces(options) {
|
|
241
|
+
const params = new URLSearchParams();
|
|
242
|
+
if (options?.agent_id)
|
|
243
|
+
params.set("agent_id", options.agent_id);
|
|
244
|
+
if (options?.session_id)
|
|
245
|
+
params.set("session_id", options.session_id);
|
|
246
|
+
if (options?.has_blocks !== undefined)
|
|
247
|
+
params.set("has_blocks", String(options.has_blocks));
|
|
248
|
+
if (options?.limit !== undefined)
|
|
249
|
+
params.set("limit", String(options.limit));
|
|
250
|
+
if (options?.offset !== undefined)
|
|
251
|
+
params.set("offset", String(options.offset));
|
|
252
|
+
const qs = params.toString();
|
|
253
|
+
return this.request("GET", `/traces${qs ? `?${qs}` : ""}`);
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Fetch full trace detail — all spans plus correlated governance decisions.
|
|
257
|
+
*
|
|
258
|
+
* @param traceId The trace identifier.
|
|
259
|
+
*/
|
|
260
|
+
async getTrace(traceId) {
|
|
261
|
+
return this.request("GET", `/traces/${encodeURIComponent(traceId)}`);
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Delete all spans for a trace (action log entries are preserved).
|
|
265
|
+
*
|
|
266
|
+
* @param traceId The trace identifier.
|
|
267
|
+
* @returns `{ trace_id, spans_deleted }`.
|
|
268
|
+
*/
|
|
269
|
+
async deleteTrace(traceId) {
|
|
270
|
+
return this.request("DELETE", `/traces/${encodeURIComponent(traceId)}`);
|
|
271
|
+
}
|
|
272
|
+
// ── Output scanning ─────────────────────────────────────────
|
|
273
|
+
/**
|
|
274
|
+
* Scan agent response text for injection, PII leakage, and other threats
|
|
275
|
+
* before sending to users.
|
|
276
|
+
*
|
|
277
|
+
* @returns Object with `safe`, `risk_score`, `findings`, and `sanitized_text`.
|
|
278
|
+
*/
|
|
279
|
+
async scanOutput(text, options) {
|
|
280
|
+
const payload = { text };
|
|
281
|
+
if (options?.agent_id)
|
|
282
|
+
payload.agent_id = options.agent_id;
|
|
283
|
+
if (options?.session_id)
|
|
284
|
+
payload.session_id = options.session_id;
|
|
285
|
+
if (options?.context)
|
|
286
|
+
payload.context = options.context;
|
|
287
|
+
return this.request("POST", "/actions/scan-output", payload);
|
|
288
|
+
}
|
|
289
|
+
// ── Verification ────────────────────────────────────────────
|
|
290
|
+
/**
|
|
291
|
+
* Submit a tool execution result for post-execution verification.
|
|
292
|
+
*
|
|
293
|
+
* @param actionId The action_id from the original evaluate call.
|
|
294
|
+
* @param tool The tool name.
|
|
295
|
+
* @param result The tool execution result.
|
|
296
|
+
* @returns Verification verdict with findings.
|
|
297
|
+
*/
|
|
298
|
+
async verify(actionId, tool, result, context) {
|
|
299
|
+
return this.request("POST", "/actions/verify", {
|
|
300
|
+
action_id: actionId,
|
|
301
|
+
tool,
|
|
302
|
+
result,
|
|
303
|
+
context: context ?? null,
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
exports.GovernorClient = GovernorClient;
|
|
308
|
+
GovernorClient.RETRYABLE_STATUS = new Set([502, 503, 504, 429]);
|
|
309
|
+
// Default export for convenience
|
|
310
|
+
exports.default = GovernorClient;
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @novtia-npm/airg-client
|
|
3
|
+
* =========================
|
|
4
|
+
* TypeScript client for the AI Runtime Governor – a runtime governance layer
|
|
5
|
+
* for AI agents.
|
|
6
|
+
*
|
|
7
|
+
* The Governor evaluates every tool invocation against configurable policies
|
|
8
|
+
* and returns an **allow / block / review** decision before the tool executes.
|
|
9
|
+
*
|
|
10
|
+
* Also provides trace observability: ingest agent trace spans, query traces,
|
|
11
|
+
* and correlate governance decisions with the agent's execution timeline.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```ts
|
|
15
|
+
* import { GovernorClient } from "@novtia-npm/airg-client";
|
|
16
|
+
*
|
|
17
|
+
* const gov = new GovernorClient({
|
|
18
|
+
* baseUrl: "https://api.airg.nov-tia.com",
|
|
19
|
+
* apiKey: "airg_your_key_here",
|
|
20
|
+
* });
|
|
21
|
+
*
|
|
22
|
+
* const decision = await gov.evaluate("shell_exec", { command: "ls -la" });
|
|
23
|
+
* console.log(decision.decision); // "allow" | "block" | "review"
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
// ---------------------------------------------------------------------------
|
|
27
|
+
// Errors
|
|
28
|
+
// ---------------------------------------------------------------------------
|
|
29
|
+
/**
|
|
30
|
+
* Thrown when the Governor blocks a tool invocation.
|
|
31
|
+
*/
|
|
32
|
+
export class GovernorBlockedError extends Error {
|
|
33
|
+
constructor(tool, decision) {
|
|
34
|
+
super(`Governor blocked tool '${tool}': ${decision.explanation ?? "no reason given"}`);
|
|
35
|
+
this.name = "GovernorBlockedError";
|
|
36
|
+
this.decision = decision;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Thrown when a reviewer rejects an action that needed approval.
|
|
41
|
+
*/
|
|
42
|
+
export class GovernorReviewRejectedError extends Error {
|
|
43
|
+
constructor(tool, decision, note) {
|
|
44
|
+
super(`Review for tool '${tool}' was rejected: ${note ?? "no reason given"}`);
|
|
45
|
+
this.name = "GovernorReviewRejectedError";
|
|
46
|
+
this.decision = decision;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Thrown when an action that needed approval was not approved: the wait timed
|
|
51
|
+
* out, the request expired, or there was no approval request to wait for.
|
|
52
|
+
*/
|
|
53
|
+
export class GovernorReviewExpiredError extends Error {
|
|
54
|
+
constructor(message, decision) {
|
|
55
|
+
super(message);
|
|
56
|
+
this.name = "GovernorReviewExpiredError";
|
|
57
|
+
this.decision = decision;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
// ---------------------------------------------------------------------------
|
|
61
|
+
// Client
|
|
62
|
+
// ---------------------------------------------------------------------------
|
|
63
|
+
/**
|
|
64
|
+
* Stateless HTTP client for the AI Runtime Governor service.
|
|
65
|
+
*
|
|
66
|
+
* Uses the built-in `fetch` API (Node 18+, all modern browsers).
|
|
67
|
+
*/
|
|
68
|
+
export class GovernorClient {
|
|
69
|
+
constructor(options = {}) {
|
|
70
|
+
this.reviewWarningShown = false;
|
|
71
|
+
const env = typeof process !== "undefined" ? process.env : {};
|
|
72
|
+
this.baseUrl = (options.baseUrl ?? env.GOVERNOR_URL ?? "http://localhost:8000").replace(/\/+$/, "");
|
|
73
|
+
this.apiKey = options.apiKey ?? env.GOVERNOR_API_KEY ?? "";
|
|
74
|
+
this.timeoutMs = options.timeoutMs ?? 10000;
|
|
75
|
+
this.maxRetries = options.maxRetries ?? 3;
|
|
76
|
+
}
|
|
77
|
+
// ── Internal helpers ────────────────────────────────────────
|
|
78
|
+
headers() {
|
|
79
|
+
const h = { "Content-Type": "application/json" };
|
|
80
|
+
if (this.apiKey) {
|
|
81
|
+
h["X-API-Key"] = this.apiKey;
|
|
82
|
+
}
|
|
83
|
+
return h;
|
|
84
|
+
}
|
|
85
|
+
async request(method, path, body, options = {}) {
|
|
86
|
+
let lastError;
|
|
87
|
+
const maxRetries = options.maxRetries ?? this.maxRetries;
|
|
88
|
+
const timeoutMs = options.timeoutMs ?? this.timeoutMs;
|
|
89
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
90
|
+
const url = `${this.baseUrl}${path}`;
|
|
91
|
+
const controller = new AbortController();
|
|
92
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
93
|
+
try {
|
|
94
|
+
const res = await fetch(url, {
|
|
95
|
+
method,
|
|
96
|
+
headers: this.headers(),
|
|
97
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
98
|
+
signal: controller.signal,
|
|
99
|
+
});
|
|
100
|
+
if (GovernorClient.RETRYABLE_STATUS.has(res.status) && attempt < maxRetries) {
|
|
101
|
+
let delay = Math.min(2 ** attempt * 500, 8000);
|
|
102
|
+
if (res.status === 429) {
|
|
103
|
+
const retryAfter = res.headers.get("Retry-After");
|
|
104
|
+
if (retryAfter)
|
|
105
|
+
delay = Math.min(parseFloat(retryAfter) * 1000, 30000);
|
|
106
|
+
}
|
|
107
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (!res.ok) {
|
|
111
|
+
const text = await res.text().catch(() => "");
|
|
112
|
+
throw new Error(`Governor API ${method} ${path} returned ${res.status}: ${text}`);
|
|
113
|
+
}
|
|
114
|
+
return (await res.json());
|
|
115
|
+
}
|
|
116
|
+
catch (err) {
|
|
117
|
+
lastError = err;
|
|
118
|
+
if (err.name === "AbortError" && attempt < maxRetries) {
|
|
119
|
+
await new Promise((r) => setTimeout(r, Math.min(2 ** attempt * 500, 8000)));
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
if (attempt >= maxRetries)
|
|
123
|
+
throw err;
|
|
124
|
+
}
|
|
125
|
+
finally {
|
|
126
|
+
clearTimeout(timer);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
throw lastError;
|
|
130
|
+
}
|
|
131
|
+
// ── Public API ──────────────────────────────────────────────
|
|
132
|
+
/**
|
|
133
|
+
* Evaluate a tool call against the Governor.
|
|
134
|
+
*
|
|
135
|
+
* A `"review"` decision waits for a reviewer by default and returns only if
|
|
136
|
+
* the action is approved. Pass `{ reviewMode: "proceed" }` to get the
|
|
137
|
+
* decision back at once instead.
|
|
138
|
+
*
|
|
139
|
+
* @returns The full decision object.
|
|
140
|
+
* @throws {GovernorBlockedError} if the decision is `"block"`.
|
|
141
|
+
* @throws {GovernorReviewRejectedError} if a reviewer rejects the action.
|
|
142
|
+
* @throws {GovernorReviewExpiredError} if the action is not approved in time
|
|
143
|
+
* or cannot be approved.
|
|
144
|
+
*/
|
|
145
|
+
async evaluate(tool, args, context, options = {}) {
|
|
146
|
+
const reviewMode = options.reviewMode ?? "hold";
|
|
147
|
+
if (reviewMode !== "hold" && reviewMode !== "proceed") {
|
|
148
|
+
throw new Error(`reviewMode must be "hold" or "proceed", got "${String(reviewMode)}"`);
|
|
149
|
+
}
|
|
150
|
+
const result = await this.request("POST", "/actions/evaluate", { tool, args, context: context ?? null });
|
|
151
|
+
if (result.decision === "block") {
|
|
152
|
+
throw new GovernorBlockedError(tool, result);
|
|
153
|
+
}
|
|
154
|
+
if (result.decision !== "review") {
|
|
155
|
+
return result;
|
|
156
|
+
}
|
|
157
|
+
if (reviewMode === "proceed") {
|
|
158
|
+
if (!this.reviewWarningShown) {
|
|
159
|
+
this.reviewWarningShown = true;
|
|
160
|
+
console.warn(`Governor returned "review" for tool '${tool}' and reviewMode is "proceed", so this ` +
|
|
161
|
+
"call returned without waiting for approval. Do not run the action until it is " +
|
|
162
|
+
'approved, or use reviewMode "hold" to wait for a reviewer.');
|
|
163
|
+
}
|
|
164
|
+
return result;
|
|
165
|
+
}
|
|
166
|
+
const escalationId = result.escalation_id;
|
|
167
|
+
if (escalationId === undefined || escalationId === null || escalationId === "") {
|
|
168
|
+
// Nothing to wait for means nobody can approve it: fail closed.
|
|
169
|
+
throw new GovernorReviewExpiredError(`Review for tool '${tool}' has no approval request to wait for`, result);
|
|
170
|
+
}
|
|
171
|
+
const timeout = Math.max(1, Math.min(Math.floor(options.holdTimeoutSeconds ?? 60), 300));
|
|
172
|
+
const poll = Math.max(0.5, Math.min(options.holdPollIntervalSeconds ?? 1, 5));
|
|
173
|
+
let hold;
|
|
174
|
+
try {
|
|
175
|
+
hold = await this.request("POST", `/escalation/queue/${encodeURIComponent(String(escalationId))}/hold` +
|
|
176
|
+
`?timeout_seconds=${timeout}&poll_interval=${poll}`, undefined, { timeoutMs: (timeout + 10) * 1000, maxRetries: 0 });
|
|
177
|
+
}
|
|
178
|
+
catch {
|
|
179
|
+
hold = { status: "pending", timed_out: true };
|
|
180
|
+
}
|
|
181
|
+
const reviewed = {
|
|
182
|
+
...result,
|
|
183
|
+
review_status: hold.status ?? "unknown",
|
|
184
|
+
review_resolved_by: hold.resolved_by ?? null,
|
|
185
|
+
review_resolution_note: hold.resolution_note ?? null,
|
|
186
|
+
};
|
|
187
|
+
if (hold.status === "rejected") {
|
|
188
|
+
throw new GovernorReviewRejectedError(tool, reviewed, hold.resolution_note);
|
|
189
|
+
}
|
|
190
|
+
if (hold.status !== "approved") {
|
|
191
|
+
// Only an explicit approval lets the caller go ahead.
|
|
192
|
+
throw new GovernorReviewExpiredError(hold.timed_out
|
|
193
|
+
? `Review for tool '${tool}' timed out after ${timeout}s`
|
|
194
|
+
: `Review for tool '${tool}' ended as '${String(hold.status)}', not approved`, reviewed);
|
|
195
|
+
}
|
|
196
|
+
return reviewed;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Convenience alias for {@link evaluate}, with the same review handling.
|
|
200
|
+
*/
|
|
201
|
+
async governedCall(tool, args, context, options = {}) {
|
|
202
|
+
return this.evaluate(tool, args, context, options);
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Fetch the current admin status (kill switch state, etc.).
|
|
206
|
+
*/
|
|
207
|
+
async getStatus() {
|
|
208
|
+
return this.request("GET", "/admin/status");
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Fetch the governor summary (total actions, block rate, etc.).
|
|
212
|
+
*/
|
|
213
|
+
async getSummary() {
|
|
214
|
+
return this.request("GET", "/summary/overview");
|
|
215
|
+
}
|
|
216
|
+
// ── Trace observability ─────────────────────────────────────
|
|
217
|
+
/**
|
|
218
|
+
* Batch-ingest agent trace spans.
|
|
219
|
+
*
|
|
220
|
+
* Valid span kinds: agent, llm, tool, governance, retrieval, chain, custom.
|
|
221
|
+
* Duplicate `span_id` values are silently skipped (idempotent).
|
|
222
|
+
*
|
|
223
|
+
* @param spans Array of span objects (up to 500).
|
|
224
|
+
* @returns `{ inserted, skipped }` counts.
|
|
225
|
+
*/
|
|
226
|
+
async ingestSpans(spans) {
|
|
227
|
+
return this.request("POST", "/traces/ingest", { spans });
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* List traces with optional filters.
|
|
231
|
+
*
|
|
232
|
+
* @returns Array of trace summaries.
|
|
233
|
+
*/
|
|
234
|
+
async listTraces(options) {
|
|
235
|
+
const params = new URLSearchParams();
|
|
236
|
+
if (options?.agent_id)
|
|
237
|
+
params.set("agent_id", options.agent_id);
|
|
238
|
+
if (options?.session_id)
|
|
239
|
+
params.set("session_id", options.session_id);
|
|
240
|
+
if (options?.has_blocks !== undefined)
|
|
241
|
+
params.set("has_blocks", String(options.has_blocks));
|
|
242
|
+
if (options?.limit !== undefined)
|
|
243
|
+
params.set("limit", String(options.limit));
|
|
244
|
+
if (options?.offset !== undefined)
|
|
245
|
+
params.set("offset", String(options.offset));
|
|
246
|
+
const qs = params.toString();
|
|
247
|
+
return this.request("GET", `/traces${qs ? `?${qs}` : ""}`);
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Fetch full trace detail — all spans plus correlated governance decisions.
|
|
251
|
+
*
|
|
252
|
+
* @param traceId The trace identifier.
|
|
253
|
+
*/
|
|
254
|
+
async getTrace(traceId) {
|
|
255
|
+
return this.request("GET", `/traces/${encodeURIComponent(traceId)}`);
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Delete all spans for a trace (action log entries are preserved).
|
|
259
|
+
*
|
|
260
|
+
* @param traceId The trace identifier.
|
|
261
|
+
* @returns `{ trace_id, spans_deleted }`.
|
|
262
|
+
*/
|
|
263
|
+
async deleteTrace(traceId) {
|
|
264
|
+
return this.request("DELETE", `/traces/${encodeURIComponent(traceId)}`);
|
|
265
|
+
}
|
|
266
|
+
// ── Output scanning ─────────────────────────────────────────
|
|
267
|
+
/**
|
|
268
|
+
* Scan agent response text for injection, PII leakage, and other threats
|
|
269
|
+
* before sending to users.
|
|
270
|
+
*
|
|
271
|
+
* @returns Object with `safe`, `risk_score`, `findings`, and `sanitized_text`.
|
|
272
|
+
*/
|
|
273
|
+
async scanOutput(text, options) {
|
|
274
|
+
const payload = { text };
|
|
275
|
+
if (options?.agent_id)
|
|
276
|
+
payload.agent_id = options.agent_id;
|
|
277
|
+
if (options?.session_id)
|
|
278
|
+
payload.session_id = options.session_id;
|
|
279
|
+
if (options?.context)
|
|
280
|
+
payload.context = options.context;
|
|
281
|
+
return this.request("POST", "/actions/scan-output", payload);
|
|
282
|
+
}
|
|
283
|
+
// ── Verification ────────────────────────────────────────────
|
|
284
|
+
/**
|
|
285
|
+
* Submit a tool execution result for post-execution verification.
|
|
286
|
+
*
|
|
287
|
+
* @param actionId The action_id from the original evaluate call.
|
|
288
|
+
* @param tool The tool name.
|
|
289
|
+
* @param result The tool execution result.
|
|
290
|
+
* @returns Verification verdict with findings.
|
|
291
|
+
*/
|
|
292
|
+
async verify(actionId, tool, result, context) {
|
|
293
|
+
return this.request("POST", "/actions/verify", {
|
|
294
|
+
action_id: actionId,
|
|
295
|
+
tool,
|
|
296
|
+
result,
|
|
297
|
+
context: context ?? null,
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
GovernorClient.RETRYABLE_STATUS = new Set([502, 503, 504, 429]);
|
|
302
|
+
// Default export for convenience
|
|
303
|
+
export default GovernorClient;
|
package/package.json
CHANGED
|
@@ -1,6 +1,43 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@novtia-npm/airg-client",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "@novtia-npm/airg-client",
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "TypeScript/JavaScript client for the AI Runtime Governor – runtime governance for AI agents",
|
|
5
|
+
"main": "dist/cjs/index.js",
|
|
6
|
+
"module": "dist/esm/index.js",
|
|
7
|
+
"types": "dist/cjs/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"import": "./dist/esm/index.js",
|
|
11
|
+
"require": "./dist/cjs/index.js",
|
|
12
|
+
"types": "./dist/cjs/index.d.ts"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist"
|
|
17
|
+
],
|
|
18
|
+
"scripts": {
|
|
19
|
+
"build": "tsc -p tsconfig.json && tsc -p tsconfig.esm.json && node scripts/mark-esm.mjs",
|
|
20
|
+
"test": "npm run build && node --test tests/client.test.mjs",
|
|
21
|
+
"prepublishOnly": "npm run build"
|
|
22
|
+
},
|
|
23
|
+
"keywords": [
|
|
24
|
+
"airg",
|
|
25
|
+
"governor",
|
|
26
|
+
"ai-safety",
|
|
27
|
+
"agent-governance",
|
|
28
|
+
"runtime-governance"
|
|
29
|
+
],
|
|
30
|
+
"author": "NOVTIA LTD",
|
|
31
|
+
"license": "MIT",
|
|
32
|
+
"homepage": "https://developers.airg.nov-tia.com/",
|
|
33
|
+
"engines": {
|
|
34
|
+
"node": ">=18.0.0"
|
|
35
|
+
},
|
|
36
|
+
"publishConfig": {
|
|
37
|
+
"access": "public"
|
|
38
|
+
},
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@types/node": "^25.3.2",
|
|
41
|
+
"typescript": "^5.4.0"
|
|
42
|
+
}
|
|
43
|
+
}
|