@hilbras/sdk 3.2.0 → 3.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 +83 -2
- package/dist/client/client.d.ts +39 -9
- package/dist/client/client.js +101 -44
- package/dist/config/config-resolver.d.ts +3 -0
- package/dist/config/config-resolver.js +187 -0
- package/dist/config/config-schema.d.ts +69 -0
- package/dist/config/config-schema.js +56 -0
- package/dist/config/config.d.ts +10 -17
- package/dist/config/config.js +37 -135
- package/dist/config/index.d.ts +11 -0
- package/dist/config/index.js +8 -0
- package/dist/config/resolved-config.d.ts +15 -0
- package/dist/config/resolved-config.js +60 -0
- package/dist/config/schema.d.ts +5 -59
- package/dist/config/schema.js +4 -28
- package/dist/config/sources/defaults.d.ts +2 -0
- package/dist/config/sources/defaults.js +10 -0
- package/dist/config/sources/environment.d.ts +4 -0
- package/dist/config/sources/environment.js +114 -0
- package/dist/config/sources/file.d.ts +6 -0
- package/dist/config/sources/file.js +33 -0
- package/dist/config/sources/runtime.d.ts +3 -0
- package/dist/config/sources/runtime.js +7 -0
- package/dist/features/agent/tool-loop.d.ts +9 -0
- package/dist/features/agent/tool-loop.js +25 -0
- package/dist/index.d.ts +15 -1
- package/dist/index.js +10 -0
- package/dist/middleware/middleware.d.ts +10 -0
- package/dist/middleware/middleware.js +15 -6
- package/dist/providers/registry.d.ts +9 -0
- package/dist/providers/registry.js +37 -0
- package/dist/security/authorization.d.ts +180 -0
- package/dist/security/authorization.js +355 -0
- package/dist/security/rate-limiter.d.ts +11 -0
- package/dist/security/rate-limiter.js +14 -0
- package/dist/security/rbac.d.ts +29 -41
- package/dist/security/rbac.js +172 -90
- package/dist/security/replay-guard.d.ts +51 -0
- package/dist/security/replay-guard.js +86 -0
- package/dist/security/request-signer.d.ts +88 -22
- package/dist/security/request-signer.js +185 -76
- package/dist/security/tool-policy.d.ts +53 -0
- package/dist/security/tool-policy.js +97 -0
- package/dist/transport/middleware-transport.js +9 -0
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
<p align="center">
|
|
2
|
-
<img src="https://img.shields.io/badge/version-3.
|
|
2
|
+
<img src="https://img.shields.io/badge/version-3.4.0-blue" alt="version">
|
|
3
3
|
<img src="https://img.shields.io/badge/license-MIT-green" alt="license">
|
|
4
4
|
<img src="https://img.shields.io/badge/node-%3E%3D18-brightgreen" alt="node">
|
|
5
5
|
<img src="https://img.shields.io/badge/types-strict-blueviolet" alt="types">
|
|
6
|
-
<img src="https://img.shields.io/badge/tests-
|
|
6
|
+
<img src="https://img.shields.io/badge/tests-1797%20passing-brightgreen" alt="tests">
|
|
7
7
|
<img src="https://img.shields.io/badge/runtime%20deps-zero-brightgreen" alt="zero deps">
|
|
8
8
|
</p>
|
|
9
9
|
|
|
@@ -166,6 +166,27 @@ const transport = new MiddlewareTransport(
|
|
|
166
166
|
|
|
167
167
|
---
|
|
168
168
|
|
|
169
|
+
## Configuration
|
|
170
|
+
|
|
171
|
+
v3.3 adds a typed configuration resolver with explicit precedence and
|
|
172
|
+
secret-safe diagnostics:
|
|
173
|
+
|
|
174
|
+
```typescript
|
|
175
|
+
import { HilbrasClient, createRuntimeSource } from "@hilbras/sdk";
|
|
176
|
+
|
|
177
|
+
const client = new HilbrasClient({
|
|
178
|
+
configSources: [
|
|
179
|
+
createRuntimeSource({ temperature: 0.3, maxRetries: 2 }),
|
|
180
|
+
],
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
console.log(client.getConfigDiagnostics());
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
See [Configuration](docs/configuration.md) and the [v3.2 migration guide](docs/migration-from-v3.2.md).
|
|
187
|
+
|
|
188
|
+
---
|
|
189
|
+
|
|
169
190
|
## Features at a glance
|
|
170
191
|
|
|
171
192
|
| Feature | Summary | Docs |
|
|
@@ -188,6 +209,8 @@ const transport = new MiddlewareTransport(
|
|
|
188
209
|
| **Error redaction** | API keys auto-redacted from provider error bodies | [Security](docs/security.md#error-redaction-in-provider-responses) |
|
|
189
210
|
| **Reasoning normalization** | Detect & normalize `<thinking>` / `<reasoning>` tags and native fields | [API Reference](docs/api-reference.md) |
|
|
190
211
|
| **Per-client tokenizer** | Scoped BPE tokenizer per client instance — no global singletons | [API Reference](docs/api-reference.md) |
|
|
212
|
+
| **Configuration resolver** | Typed layered configuration with strict validation and redacted diagnostics | [Configuration](docs/configuration.md) |
|
|
213
|
+
| **Authorization enforcement** | RBAC that actually evaluates, enforced tool policy, body-bound request signing with replay protection | [Security](docs/security.md) |
|
|
191
214
|
| **Middleware pipeline** | Transport-level middleware: auth headers, logging, custom request/response transforms | [API Reference](docs/api-reference.md) |
|
|
192
215
|
| **Agent framework** | ToolLoopAgent, ReActAgent, PlanAndExecuteAgent with approval, budget, cost tracking | [Agent](docs/agent.md) |
|
|
193
216
|
| **Evaluation** | LLM output evaluation with built-in metrics (exact_match, similarity, toxicity) | [Eval](docs/eval.md) |
|
|
@@ -203,6 +226,64 @@ const transport = new MiddlewareTransport(
|
|
|
203
226
|
|
|
204
227
|
---
|
|
205
228
|
|
|
229
|
+
## What's New in v3.4.0
|
|
230
|
+
|
|
231
|
+
**Authorization now enforces.** `config.rbac` was accepted by the configuration
|
|
232
|
+
resolver but read by nothing, and even when the RBAC middleware was wired up
|
|
233
|
+
manually its permission check was unreachable: it read `provider` from the
|
|
234
|
+
request body, which no adapter sends. RBAC now resolves the provider from the
|
|
235
|
+
request URL, maps caller identity onto a role, and enforces the result. A
|
|
236
|
+
configured `rbac` block is enforced by the client automatically, and a malformed
|
|
237
|
+
policy is rejected at construction instead of degrading to "no restrictions".
|
|
238
|
+
|
|
239
|
+
**Tool policy is enforced.** `allowedTools` and `deniedTools` were declared,
|
|
240
|
+
overlap-checked, and then ignored. The client now rejects a request that names a
|
|
241
|
+
denied tool, and `ToolLoopAgent` refuses to execute one. See `getToolPolicy()`.
|
|
242
|
+
|
|
243
|
+
**Request signing binds the body.** The HMAC signature covered the method, path,
|
|
244
|
+
and configured headers, but not the request body: the body digest was emitted as
|
|
245
|
+
an unsigned header, and `verify()` trusted a received digest header rather than
|
|
246
|
+
recomputing it. The new `v2` profile binds the body, the key id, and a nonce,
|
|
247
|
+
and recomputes the digest from the received bytes. The `v1` wire format is
|
|
248
|
+
frozen and unchanged, so existing verifiers keep working.
|
|
249
|
+
|
|
250
|
+
**Replay protection.** `ReplayGuard` adds a signed-timestamp window and a
|
|
251
|
+
bounded seen-signature cache. `RequestSigner.verifyFresh()` composes the two.
|
|
252
|
+
|
|
253
|
+
**Middleware and transport fixes.** `composeMiddlewares` used a shared cursor
|
|
254
|
+
that permanently exhausted the chain, so any stage after a retry was skipped on
|
|
255
|
+
every later attempt — a signature computed at T0 was reused unchanged for
|
|
256
|
+
attempts 2..N. Composition now re-enters per attempt. Streaming a non-2xx
|
|
257
|
+
response now throws instead of yielding an empty stream, and signed requests no
|
|
258
|
+
longer emit both `Content-Type` and `content-type`.
|
|
259
|
+
|
|
260
|
+
**Compatibility.** No export is removed. `checkPermission`, `RBACRole`,
|
|
261
|
+
`RBACConfig`, `RequestSigner`, and `signingMiddleware` keep their signatures.
|
|
262
|
+
One intentional behavior change: a malformed `config.rbac` now fails at
|
|
263
|
+
construction. See the [v3.3 migration guide](docs/migration-from-v3.3.md).
|
|
264
|
+
|
|
265
|
+
**Audit.** All 20 audited findings, with a finding-to-test map in
|
|
266
|
+
[`HILBRAS-SDK-FULL-AUDIT.md`](HILBRAS-SDK-FULL-AUDIT.md) and
|
|
267
|
+
[`SPEC-v3.4.0-security.md`](SPEC-v3.4.0-security.md).
|
|
268
|
+
|
|
269
|
+
---
|
|
270
|
+
|
|
271
|
+
## What's New in v3.3.0
|
|
272
|
+
|
|
273
|
+
**Canonical configuration** — `resolveConfig()` now provides deterministic layered configuration with defaults, file sources, environment sources, and runtime/client values. The client resolves configuration once during construction.
|
|
274
|
+
|
|
275
|
+
**Validation and diagnostics** — configuration values receive strict numeric, boolean, enum, provider, authentication, and SSRF validation. `getConfigDiagnostics()` reports safe, actionable diagnostics without exposing credentials.
|
|
276
|
+
|
|
277
|
+
**Secret-safe snapshots** — `getConfigSnapshot()` returns a redacted configuration projection suitable for tooling and logs. The usable resolved configuration is kept separate from the safe view.
|
|
278
|
+
|
|
279
|
+
**Compatibility** — `loadConfig()`, `createConfig()`, `validateConfig()`, and `sdkConfig` remain supported. See the [v3.2 migration guide](docs/migration-from-v3.2.md) for incremental adoption.
|
|
280
|
+
|
|
281
|
+
**Documentation and examples** — added a configuration guide, migration guide, API reference section, and runtime/file configuration examples.
|
|
282
|
+
|
|
283
|
+
See [`CHANGELOG.md`](CHANGELOG.md) and [`HILBRAS-SDK-FULL-AUDIT.md`](HILBRAS-SDK-FULL-AUDIT.md) for the complete release and audit details.
|
|
284
|
+
|
|
285
|
+
---
|
|
286
|
+
|
|
206
287
|
## What's New in v3.2.0
|
|
207
288
|
|
|
208
289
|
**Execution stabilization** — the client now delegates request preparation and provider attempts to an internal execution layer. `RequestContext`, `ExecutionResult`, `RequestExecutor`, and `RequestPipeline` establish explicit logical-request and attempt boundaries without adding public exports or changing the supported `complete()`/`stream()` APIs.
|
package/dist/client/client.d.ts
CHANGED
|
@@ -18,6 +18,11 @@ import type { ExecutionPolicy } from "../types/policy.js";
|
|
|
18
18
|
import type { TaskRequirement } from "../types/router.js";
|
|
19
19
|
import type { StructuredOutputConfig, StreamObjectOptions, SchemaValidator } from "../types/schema.js";
|
|
20
20
|
import type { EmbeddingResult, ImageResult, SpeechResult, TranscriptionResult, RerankResult } from "../types/multi-modal.js";
|
|
21
|
+
import type { ConfigDiagnostic, ConfigSource, SafeSDKConfig } from "../config/config-schema.js";
|
|
22
|
+
import { type ResolvedSDKConfig } from "../config/resolved-config.js";
|
|
23
|
+
import type { SDKConfig } from "../config/schema.js";
|
|
24
|
+
import type { AuthorizationDiagnostic } from "../security/authorization.js";
|
|
25
|
+
import { ToolPolicy } from "../security/tool-policy.js";
|
|
21
26
|
import { AdapterRegistry } from "../providers/adapter-registry.js";
|
|
22
27
|
import { ModelRouter } from "../router/model-router.js";
|
|
23
28
|
import type { StructuredLogger } from "../telemetry/structured-logger.js";
|
|
@@ -75,6 +80,16 @@ export interface HilbrasClientConfig {
|
|
|
75
80
|
* `sessionBudget`, `perRequestBudget`.
|
|
76
81
|
*/
|
|
77
82
|
sdkConfig?: import("../config/schema.js").SDKConfig;
|
|
83
|
+
/**
|
|
84
|
+
* Canonical v3.3 configuration input. Sources are resolved once during
|
|
85
|
+
* construction using defaults < file/environment sources < runtime values.
|
|
86
|
+
* Existing `sdkConfig` remains supported as a compatibility alias.
|
|
87
|
+
*/
|
|
88
|
+
config?: Partial<SDKConfig>;
|
|
89
|
+
/** Explicit configuration sources for the canonical resolver. */
|
|
90
|
+
configSources?: ConfigSource[];
|
|
91
|
+
/** An already-resolved configuration, primarily for framework adapters. */
|
|
92
|
+
resolvedConfig?: ResolvedSDKConfig;
|
|
78
93
|
/**
|
|
79
94
|
* v1.1.0: Optional telemetry sinks. When provided, the client automatically
|
|
80
95
|
* forwards lifecycle events to the configured sinks.
|
|
@@ -108,6 +123,7 @@ export declare class HilbrasClient implements AsyncDisposable {
|
|
|
108
123
|
private _adapterRegistry;
|
|
109
124
|
private _adapters;
|
|
110
125
|
private _defaultPolicy;
|
|
126
|
+
private _resolvedConfig;
|
|
111
127
|
private _router;
|
|
112
128
|
private _hooks;
|
|
113
129
|
private _requestCounter;
|
|
@@ -118,16 +134,9 @@ export declare class HilbrasClient implements AsyncDisposable {
|
|
|
118
134
|
private _plugins;
|
|
119
135
|
private _requestExecutor;
|
|
120
136
|
private _requestPipeline;
|
|
137
|
+
private _toolPolicy;
|
|
138
|
+
private _authorizationDiagnostics;
|
|
121
139
|
constructor(config?: HilbrasClientConfig);
|
|
122
|
-
/**
|
|
123
|
-
* Map the legacy SDKConfig fields (maxRetries, requestTimeoutMs,
|
|
124
|
-
* circuitBreakerEnabled/Threshold/ResetMs) to an ExecutionPolicy.
|
|
125
|
-
* Unrecognized fields are left undefined; the per-request policy
|
|
126
|
-
* resolver fills in defaults.
|
|
127
|
-
*/
|
|
128
|
-
private _policyFromSDK;
|
|
129
|
-
/** Map the legacy SDKConfig budget fields to a BudgetConfig. */
|
|
130
|
-
private _budgetFromSDK;
|
|
131
140
|
/** Subscribe to lifecycle events. Returns an unsubscribe function. */
|
|
132
141
|
on<T extends HookEvent = HookEvent>(event: T["type"], listener: HookListener<T>): () => void;
|
|
133
142
|
/** Remove a specific listener */
|
|
@@ -163,6 +172,27 @@ export declare class HilbrasClient implements AsyncDisposable {
|
|
|
163
172
|
removeProvider(name: string): void;
|
|
164
173
|
getProvider(name: string): ProviderConfig | undefined;
|
|
165
174
|
listProviders(): ProviderConfig[];
|
|
175
|
+
/** Return a redacted snapshot of the resolved client configuration. */
|
|
176
|
+
getConfigSnapshot(): SafeSDKConfig;
|
|
177
|
+
/** Return configuration diagnostics without secret values. */
|
|
178
|
+
getConfigDiagnostics(): ConfigDiagnostic[];
|
|
179
|
+
/**
|
|
180
|
+
* Return the enforced tool policy derived from `allowedTools` and
|
|
181
|
+
* `deniedTools`. Pass it to a `ToolLoopAgent` to make tool execution obey the
|
|
182
|
+
* same policy the client admits requests under.
|
|
183
|
+
*/
|
|
184
|
+
getToolPolicy(): ToolPolicy;
|
|
185
|
+
/**
|
|
186
|
+
* Return the redacted authorization decision log in decision order, bounded
|
|
187
|
+
* to the most recent entries. Empty when no `rbac` policy is configured.
|
|
188
|
+
*/
|
|
189
|
+
getAuthorizationDiagnostics(): AuthorizationDiagnostic[];
|
|
190
|
+
/**
|
|
191
|
+
* Throw when any of the supplied tool names is not permitted by the client's
|
|
192
|
+
* tool policy. Called on the request-admission path so a request that would
|
|
193
|
+
* use a denied tool fails before a provider call is made.
|
|
194
|
+
*/
|
|
195
|
+
private _assertToolsAllowed;
|
|
166
196
|
/**
|
|
167
197
|
* Add a provider from the built-in catalog with one line.
|
|
168
198
|
*
|
package/dist/client/client.js
CHANGED
|
@@ -11,6 +11,11 @@
|
|
|
11
11
|
*/
|
|
12
12
|
import { RequestExecutor } from "../core/execution/request-executor.js";
|
|
13
13
|
import { RequestPipeline } from "../core/execution/request-pipeline.js";
|
|
14
|
+
import { resolveConfig } from "../config/config-resolver.js";
|
|
15
|
+
import { budgetFromConfig, policyFromConfig } from "../config/resolved-config.js";
|
|
16
|
+
import { createRBACMiddleware } from "../security/rbac.js";
|
|
17
|
+
import { ToolPolicy } from "../security/tool-policy.js";
|
|
18
|
+
import { composeMiddlewares } from "../middleware/middleware.js";
|
|
14
19
|
import { ProviderRegistry } from "../providers/registry.js";
|
|
15
20
|
import { cloneProviderConfig } from "../config/provider-config.js";
|
|
16
21
|
import { FetchTransport } from "../transport/fetch.js";
|
|
@@ -30,12 +35,18 @@ import { BudgetTracker } from "../cost/tracker.js";
|
|
|
30
35
|
import { estimateTokens } from "../tokens/counter.js";
|
|
31
36
|
import { getProviderCatalog, getModelsForProvider, listProviders } from "../catalog/index.js";
|
|
32
37
|
import { PluginRegistry } from "../plugin/registry.js";
|
|
38
|
+
/**
|
|
39
|
+
* Maximum number of authorization diagnostics retained per client. Older
|
|
40
|
+
* entries are dropped so a long-lived client cannot grow without bound.
|
|
41
|
+
*/
|
|
42
|
+
const AUTHORIZATION_DIAGNOSTIC_LIMIT = 200;
|
|
33
43
|
export class HilbrasClient {
|
|
34
44
|
_registry = new ProviderRegistry();
|
|
35
45
|
_transport;
|
|
36
46
|
_adapterRegistry;
|
|
37
47
|
_adapters = new Map();
|
|
38
48
|
_defaultPolicy;
|
|
49
|
+
_resolvedConfig;
|
|
39
50
|
_router;
|
|
40
51
|
_hooks = new ClientHooks();
|
|
41
52
|
_requestCounter = 0;
|
|
@@ -46,23 +57,58 @@ export class HilbrasClient {
|
|
|
46
57
|
_plugins = new PluginRegistry();
|
|
47
58
|
_requestExecutor;
|
|
48
59
|
_requestPipeline;
|
|
60
|
+
_toolPolicy;
|
|
61
|
+
_authorizationDiagnostics = [];
|
|
49
62
|
constructor(config) {
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
if (config?.middleware) {
|
|
53
|
-
this._transport = new MiddlewareTransport(this._transport, config.middleware);
|
|
54
|
-
}
|
|
63
|
+
const baseTransport = config?.transport ?? new FetchTransport();
|
|
64
|
+
this._transport = baseTransport;
|
|
55
65
|
this._adapterRegistry = config?.adapterRegistry ?? getDefaultAdapterRegistry();
|
|
56
66
|
this._router = new ModelRouter();
|
|
57
67
|
this._allowInsecureUrls = config?.allowInsecureUrls ?? false;
|
|
58
68
|
this._allowPrivateNetwork = config?.allowPrivateNetwork ?? false;
|
|
59
69
|
this._tokenizer = config?.tokenizer ?? null;
|
|
60
|
-
//
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
70
|
+
// v3.3.0: resolve layered configuration exactly once at construction.
|
|
71
|
+
const inputConfig = config?.config ?? config?.sdkConfig;
|
|
72
|
+
this._resolvedConfig = config?.resolvedConfig ?? resolveConfig({
|
|
73
|
+
sources: config?.configSources,
|
|
74
|
+
overrides: inputConfig,
|
|
75
|
+
strict: true,
|
|
76
|
+
});
|
|
77
|
+
const resolvedSdk = this._resolvedConfig.values;
|
|
78
|
+
this._defaultPolicy = config?.policy ?? policyFromConfig(resolvedSdk);
|
|
79
|
+
const sdkBudget = budgetFromConfig(resolvedSdk);
|
|
65
80
|
this._budgetTracker = new BudgetTracker(config?.budget ?? sdkBudget);
|
|
81
|
+
// v3.4.0: allowedTools / deniedTools become enforceable. They were part of
|
|
82
|
+
// the schema from the start but nothing consulted them.
|
|
83
|
+
this._toolPolicy = new ToolPolicy({
|
|
84
|
+
allowedTools: resolvedSdk.allowedTools,
|
|
85
|
+
deniedTools: resolvedSdk.deniedTools,
|
|
86
|
+
});
|
|
87
|
+
// v3.4.0: a configured `rbac` block is now live. Provider resolution is
|
|
88
|
+
// read lazily from the registry so providers added after construction are
|
|
89
|
+
// covered by the same policy.
|
|
90
|
+
const middlewareChain = [];
|
|
91
|
+
if (resolvedSdk.rbac) {
|
|
92
|
+
middlewareChain.push(createRBACMiddleware(resolvedSdk.rbac, () => null, {
|
|
93
|
+
resolveProviderByUrl: (url) => this._registry.findByUrl(url),
|
|
94
|
+
resolveBudget: () => ({ spent: this._budgetTracker.report().totalActual }),
|
|
95
|
+
onDiagnostic: (diagnostic) => {
|
|
96
|
+
this._authorizationDiagnostics.push(diagnostic);
|
|
97
|
+
if (this._authorizationDiagnostics.length > AUTHORIZATION_DIAGNOSTIC_LIMIT) {
|
|
98
|
+
this._authorizationDiagnostics.splice(0, this._authorizationDiagnostics.length - AUTHORIZATION_DIAGNOSTIC_LIMIT);
|
|
99
|
+
}
|
|
100
|
+
},
|
|
101
|
+
}));
|
|
102
|
+
}
|
|
103
|
+
// v2.5.0: Wrap transport with middleware pipeline when provided
|
|
104
|
+
if (config?.middleware)
|
|
105
|
+
middlewareChain.push(config.middleware);
|
|
106
|
+
if (middlewareChain.length === 1) {
|
|
107
|
+
this._transport = new MiddlewareTransport(baseTransport, middlewareChain[0]);
|
|
108
|
+
}
|
|
109
|
+
else if (middlewareChain.length > 1) {
|
|
110
|
+
this._transport = new MiddlewareTransport(baseTransport, composeMiddlewares(...middlewareChain));
|
|
111
|
+
}
|
|
66
112
|
this._requestExecutor = new RequestExecutor({
|
|
67
113
|
policy: {
|
|
68
114
|
resolve: (policy) => resolvePolicy(policy ?? this._defaultPolicy),
|
|
@@ -86,8 +132,8 @@ export class HilbrasClient {
|
|
|
86
132
|
},
|
|
87
133
|
});
|
|
88
134
|
// v1.1.0: Register providers from SDKConfig if provided
|
|
89
|
-
if (
|
|
90
|
-
for (const provider of
|
|
135
|
+
if (resolvedSdk.providers.length > 0) {
|
|
136
|
+
for (const provider of resolvedSdk.providers) {
|
|
91
137
|
if (!this._registry.get(provider.name)) {
|
|
92
138
|
this.addProvider(provider);
|
|
93
139
|
}
|
|
@@ -101,38 +147,6 @@ export class HilbrasClient {
|
|
|
101
147
|
config.telemetry.openTelemetry.instrumentClient(this);
|
|
102
148
|
}
|
|
103
149
|
}
|
|
104
|
-
/**
|
|
105
|
-
* Map the legacy SDKConfig fields (maxRetries, requestTimeoutMs,
|
|
106
|
-
* circuitBreakerEnabled/Threshold/ResetMs) to an ExecutionPolicy.
|
|
107
|
-
* Unrecognized fields are left undefined; the per-request policy
|
|
108
|
-
* resolver fills in defaults.
|
|
109
|
-
*/
|
|
110
|
-
_policyFromSDK(sdk) {
|
|
111
|
-
const policy = {};
|
|
112
|
-
if (sdk.maxRetries !== undefined) {
|
|
113
|
-
policy.retry = { maxRetries: sdk.maxRetries };
|
|
114
|
-
}
|
|
115
|
-
if (sdk.requestTimeoutMs !== undefined) {
|
|
116
|
-
policy.timeout = { requestTimeoutMs: sdk.requestTimeoutMs };
|
|
117
|
-
}
|
|
118
|
-
if (sdk.circuitBreakerEnabled !== undefined || sdk.circuitBreakerThreshold !== undefined || sdk.circuitBreakerResetMs !== undefined) {
|
|
119
|
-
policy.circuitBreaker = {
|
|
120
|
-
enabled: sdk.circuitBreakerEnabled,
|
|
121
|
-
failureThreshold: sdk.circuitBreakerThreshold,
|
|
122
|
-
timeoutMs: sdk.circuitBreakerResetMs,
|
|
123
|
-
};
|
|
124
|
-
}
|
|
125
|
-
return policy;
|
|
126
|
-
}
|
|
127
|
-
/** Map the legacy SDKConfig budget fields to a BudgetConfig. */
|
|
128
|
-
_budgetFromSDK(sdk) {
|
|
129
|
-
const budget = {};
|
|
130
|
-
if (sdk.sessionBudget !== undefined)
|
|
131
|
-
budget.sessionBudget = sdk.sessionBudget;
|
|
132
|
-
if (sdk.perRequestBudget !== undefined)
|
|
133
|
-
budget.perRequestBudget = sdk.perRequestBudget;
|
|
134
|
-
return budget;
|
|
135
|
-
}
|
|
136
150
|
/** Subscribe to lifecycle events. Returns an unsubscribe function. */
|
|
137
151
|
on(event, listener) {
|
|
138
152
|
return this._hooks.on(event, listener);
|
|
@@ -214,6 +228,41 @@ export class HilbrasClient {
|
|
|
214
228
|
listProviders() {
|
|
215
229
|
return this._registry.list();
|
|
216
230
|
}
|
|
231
|
+
/** Return a redacted snapshot of the resolved client configuration. */
|
|
232
|
+
getConfigSnapshot() {
|
|
233
|
+
return this._resolvedConfig.safeSnapshot();
|
|
234
|
+
}
|
|
235
|
+
/** Return configuration diagnostics without secret values. */
|
|
236
|
+
getConfigDiagnostics() {
|
|
237
|
+
return this._resolvedConfig.diagnostics.map((diagnostic) => ({ ...diagnostic }));
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Return the enforced tool policy derived from `allowedTools` and
|
|
241
|
+
* `deniedTools`. Pass it to a `ToolLoopAgent` to make tool execution obey the
|
|
242
|
+
* same policy the client admits requests under.
|
|
243
|
+
*/
|
|
244
|
+
getToolPolicy() {
|
|
245
|
+
return this._toolPolicy;
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Return the redacted authorization decision log in decision order, bounded
|
|
249
|
+
* to the most recent entries. Empty when no `rbac` policy is configured.
|
|
250
|
+
*/
|
|
251
|
+
getAuthorizationDiagnostics() {
|
|
252
|
+
return this._authorizationDiagnostics.map((diagnostic) => ({ ...diagnostic }));
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Throw when any of the supplied tool names is not permitted by the client's
|
|
256
|
+
* tool policy. Called on the request-admission path so a request that would
|
|
257
|
+
* use a denied tool fails before a provider call is made.
|
|
258
|
+
*/
|
|
259
|
+
_assertToolsAllowed(toolNames) {
|
|
260
|
+
if (this._toolPolicy.isEmpty())
|
|
261
|
+
return;
|
|
262
|
+
const violation = this._toolPolicy.checkAll(toolNames);
|
|
263
|
+
if (violation)
|
|
264
|
+
throw new Error(violation.reason ?? "tool is not permitted by policy");
|
|
265
|
+
}
|
|
217
266
|
/**
|
|
218
267
|
* Add a provider from the built-in catalog with one line.
|
|
219
268
|
*
|
|
@@ -442,6 +491,10 @@ export class HilbrasClient {
|
|
|
442
491
|
async complete(params) {
|
|
443
492
|
const requestId = this._nextRequestId();
|
|
444
493
|
const startTime = performance.now();
|
|
494
|
+
// v3.4.0: reject a request that would use a tool the policy forbids before
|
|
495
|
+
// any provider call is made.
|
|
496
|
+
if (params.tools)
|
|
497
|
+
this._assertToolsAllowed(params.tools.map((tool) => tool.function.name));
|
|
445
498
|
this._emit({ type: "request.start", requestId, timestamp: startTime, provider: params.provider, model: params.model, task: params.task });
|
|
446
499
|
// Resolve provider + model — either explicit or via router
|
|
447
500
|
const resolved_ = this._resolveProviderModel({ ...params, hasOutput: !!params.output });
|
|
@@ -630,6 +683,10 @@ export class HilbrasClient {
|
|
|
630
683
|
const maxSteps = params.maxSteps ?? 1;
|
|
631
684
|
const messages = this._normalizeMessages(params.messages);
|
|
632
685
|
const allowedToolNames = new Set((params.tools ?? []).map((tool) => tool.function.name));
|
|
686
|
+
// v3.4.0: tool policy is enforced on the tool-execution path, because a
|
|
687
|
+
// denied tool must not run even though the provider already saw its schema.
|
|
688
|
+
if (params.tools)
|
|
689
|
+
this._assertToolsAllowed([...allowedToolNames]);
|
|
633
690
|
let currentMessages = [...messages];
|
|
634
691
|
for (let step = 0; step < maxSteps; step++) {
|
|
635
692
|
let stepText = "";
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import { DEFAULT_CONFIG } from "./schema.js";
|
|
2
|
+
import { createDefaultsSource } from "./sources/defaults.js";
|
|
3
|
+
import { createRuntimeSource } from "./sources/runtime.js";
|
|
4
|
+
import { createResolvedConfig } from "./resolved-config.js";
|
|
5
|
+
import { CONFIG_KEYS, cloneConfigValue, } from "./config-schema.js";
|
|
6
|
+
import { validateBaseUrl } from "../security/url-guard.js";
|
|
7
|
+
import { validateRbacConfig } from "../security/authorization.js";
|
|
8
|
+
import { ConfigurationError } from "../errors/index.js";
|
|
9
|
+
const LOG_LEVELS = new Set(["none", "error", "info", "debug"]);
|
|
10
|
+
function isPlainObject(value) {
|
|
11
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
12
|
+
}
|
|
13
|
+
function errorDiagnostic(source, code, path, message) {
|
|
14
|
+
return { code, path, message, severity: "error", source };
|
|
15
|
+
}
|
|
16
|
+
function warningDiagnostic(source, code, path, message) {
|
|
17
|
+
return { code, path, message, severity: "warning", source };
|
|
18
|
+
}
|
|
19
|
+
function mergePlainObjects(base, override) {
|
|
20
|
+
const result = { ...base };
|
|
21
|
+
for (const [key, value] of Object.entries(override)) {
|
|
22
|
+
if (key === "__proto__" || key === "constructor" || key === "prototype")
|
|
23
|
+
continue;
|
|
24
|
+
if (value === undefined)
|
|
25
|
+
continue;
|
|
26
|
+
if (isPlainObject(result[key]) && isPlainObject(value)) {
|
|
27
|
+
result[key] = mergePlainObjects(result[key], value);
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
result[key] = cloneConfigValue(value);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return result;
|
|
34
|
+
}
|
|
35
|
+
function mergeValues(base, override, source, rejectUnknownKeys, diagnostics, fieldSources) {
|
|
36
|
+
const result = cloneConfigValue(base);
|
|
37
|
+
for (const [key, value] of Object.entries(override)) {
|
|
38
|
+
if (!CONFIG_KEYS.has(key)) {
|
|
39
|
+
diagnostics.push((rejectUnknownKeys ? errorDiagnostic : warningDiagnostic)(source, "CONFIG_UNKNOWN_KEY", key, `unknown configuration key '${key}' was ignored`));
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
if (value === undefined)
|
|
43
|
+
continue;
|
|
44
|
+
const current = result[key];
|
|
45
|
+
if (isPlainObject(current) && isPlainObject(value)) {
|
|
46
|
+
result[key] = mergePlainObjects(current, value);
|
|
47
|
+
}
|
|
48
|
+
else {
|
|
49
|
+
result[key] = cloneConfigValue(value);
|
|
50
|
+
}
|
|
51
|
+
fieldSources[key] = source;
|
|
52
|
+
}
|
|
53
|
+
return result;
|
|
54
|
+
}
|
|
55
|
+
function validateValues(values, source) {
|
|
56
|
+
const diagnostics = [];
|
|
57
|
+
const numberFields = [
|
|
58
|
+
["temperature", "temperature", (value) => Number.isFinite(value) && value >= 0 && value <= 2],
|
|
59
|
+
["maxTokens", "maxTokens", (value) => Number.isInteger(value) && value > 0],
|
|
60
|
+
["requestTimeoutMs", "requestTimeoutMs", (value) => Number.isInteger(value) && value >= 1000],
|
|
61
|
+
["maxRetries", "maxRetries", (value) => Number.isInteger(value) && value >= 0],
|
|
62
|
+
["circuitBreakerThreshold", "circuitBreakerThreshold", (value) => Number.isInteger(value) && value > 0],
|
|
63
|
+
["circuitBreakerResetMs", "circuitBreakerResetMs", (value) => Number.isInteger(value) && value >= 0],
|
|
64
|
+
];
|
|
65
|
+
for (const [field, path, valid] of numberFields) {
|
|
66
|
+
if (!valid(values[field])) {
|
|
67
|
+
diagnostics.push(errorDiagnostic(source, "CONFIG_INVALID_VALUE", path, `${path} has an invalid value`));
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (!LOG_LEVELS.has(values.logLevel)) {
|
|
71
|
+
diagnostics.push(errorDiagnostic(source, "CONFIG_INVALID_ENUM", "logLevel", "logLevel must be none, error, info, or debug"));
|
|
72
|
+
}
|
|
73
|
+
if (!Array.isArray(values.providers)) {
|
|
74
|
+
diagnostics.push(errorDiagnostic(source, "CONFIG_INVALID_TYPE", "providers", "providers must be an array"));
|
|
75
|
+
return diagnostics;
|
|
76
|
+
}
|
|
77
|
+
const names = new Set();
|
|
78
|
+
values.providers.forEach((provider, index) => {
|
|
79
|
+
const path = `providers[${index}]`;
|
|
80
|
+
if (!provider || typeof provider !== "object") {
|
|
81
|
+
diagnostics.push(errorDiagnostic(source, "CONFIG_INVALID_TYPE", path, "provider must be an object"));
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
if (!provider.name || typeof provider.name !== "string") {
|
|
85
|
+
diagnostics.push(errorDiagnostic(source, "CONFIG_INVALID_VALUE", `${path}.name`, "provider name is required"));
|
|
86
|
+
}
|
|
87
|
+
else if (names.has(provider.name)) {
|
|
88
|
+
diagnostics.push(errorDiagnostic(source, "CONFIG_DUPLICATE_PROVIDER", `${path}.name`, "provider names must be unique"));
|
|
89
|
+
}
|
|
90
|
+
else {
|
|
91
|
+
names.add(provider.name);
|
|
92
|
+
}
|
|
93
|
+
if (typeof provider.adapter !== "string" || provider.adapter.length === 0) {
|
|
94
|
+
diagnostics.push(errorDiagnostic(source, "CONFIG_INVALID_VALUE", `${path}.adapter`, "provider adapter is required"));
|
|
95
|
+
}
|
|
96
|
+
if (!Array.isArray(provider.models)) {
|
|
97
|
+
diagnostics.push(errorDiagnostic(source, "CONFIG_INVALID_TYPE", `${path}.models`, "provider models must be an array"));
|
|
98
|
+
}
|
|
99
|
+
if (typeof provider.baseUrl !== "string") {
|
|
100
|
+
diagnostics.push(errorDiagnostic(source, "CONFIG_INVALID_VALUE", `${path}.baseUrl`, "provider baseUrl is required"));
|
|
101
|
+
}
|
|
102
|
+
else {
|
|
103
|
+
const guard = validateBaseUrl(provider.baseUrl, { allowInsecure: !!provider.allowInsecure });
|
|
104
|
+
if (!guard.ok) {
|
|
105
|
+
diagnostics.push(errorDiagnostic(source, "CONFIG_UNSAFE_PROVIDER_URL", `${path}.baseUrl`, `provider URL rejected by security policy: ${guard.reason}`));
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
const auth = provider.authentication;
|
|
109
|
+
if (!auth || typeof auth !== "object" || typeof auth.type !== "string") {
|
|
110
|
+
diagnostics.push(errorDiagnostic(source, "CONFIG_INVALID_AUTH", `${path}.authentication`, "provider authentication is required"));
|
|
111
|
+
}
|
|
112
|
+
else if (auth.type === "bearer" && (typeof auth.apiKey !== "string" || auth.apiKey.length === 0)) {
|
|
113
|
+
diagnostics.push(errorDiagnostic(source, "CONFIG_INVALID_AUTH", `${path}.authentication.apiKey`, "bearer authentication requires an API key"));
|
|
114
|
+
}
|
|
115
|
+
else if (auth.type === "header" && (typeof auth.name !== "string" || typeof auth.value !== "string")) {
|
|
116
|
+
diagnostics.push(errorDiagnostic(source, "CONFIG_INVALID_AUTH", `${path}.authentication`, "header authentication requires name and value"));
|
|
117
|
+
}
|
|
118
|
+
else if (auth.type !== "bearer" && auth.type !== "header" && auth.type !== "none") {
|
|
119
|
+
diagnostics.push(errorDiagnostic(source, "CONFIG_INVALID_AUTH", `${path}.authentication.type`, "unsupported authentication type"));
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
if (Array.isArray(values.allowedTools) && Array.isArray(values.deniedTools)) {
|
|
123
|
+
const denied = new Set(values.deniedTools);
|
|
124
|
+
const overlap = values.allowedTools.filter((tool) => denied.has(tool));
|
|
125
|
+
if (overlap.length > 0) {
|
|
126
|
+
diagnostics.push(errorDiagnostic(source, "CONFIG_TOOL_POLICY_CONFLICT", "allowedTools", "allowedTools and deniedTools must not overlap"));
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
// A malformed authorization policy is rejected as configuration rather than
|
|
130
|
+
// degrading to "no restrictions" at request time.
|
|
131
|
+
if (values.rbac !== undefined) {
|
|
132
|
+
for (const issue of validateRbacConfig(values.rbac, "rbac")) {
|
|
133
|
+
diagnostics.push({
|
|
134
|
+
code: issue.code,
|
|
135
|
+
message: issue.message,
|
|
136
|
+
path: issue.path,
|
|
137
|
+
severity: issue.severity,
|
|
138
|
+
source,
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return diagnostics;
|
|
143
|
+
}
|
|
144
|
+
function throwForDiagnostics(diagnostics) {
|
|
145
|
+
const errors = diagnostics.filter((diagnostic) => diagnostic.severity === "error");
|
|
146
|
+
if (errors.length === 0)
|
|
147
|
+
return;
|
|
148
|
+
const summary = errors.slice(0, 3).map((diagnostic) => `${diagnostic.path}: ${diagnostic.message}`).join("; ");
|
|
149
|
+
throw new ConfigurationError(`Configuration resolution failed: ${summary}`, "Check the configuration source, value types, and provider security policy.");
|
|
150
|
+
}
|
|
151
|
+
export function resolveConfig(options = {}) {
|
|
152
|
+
const strict = options.strict ?? true;
|
|
153
|
+
const rejectUnknownKeys = options.rejectUnknownKeys ?? false;
|
|
154
|
+
const diagnostics = [];
|
|
155
|
+
const fieldSources = {};
|
|
156
|
+
const suppliedSources = options.sources ?? [];
|
|
157
|
+
const sources = [
|
|
158
|
+
createDefaultsSource(),
|
|
159
|
+
...suppliedSources.filter((source) => source.kind !== "defaults"),
|
|
160
|
+
...(options.overrides ? [createRuntimeSource(options.overrides)] : []),
|
|
161
|
+
];
|
|
162
|
+
let values = cloneConfigValue(DEFAULT_CONFIG);
|
|
163
|
+
for (const source of sources) {
|
|
164
|
+
let loaded;
|
|
165
|
+
try {
|
|
166
|
+
loaded = source.load();
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
diagnostics.push(errorDiagnostic(source.kind, "CONFIG_SOURCE_FAILED", "$", `configuration source '${source.kind}' failed`));
|
|
170
|
+
if (strict)
|
|
171
|
+
throwForDiagnostics(diagnostics);
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
diagnostics.push(...(loaded.diagnostics ?? []));
|
|
175
|
+
if (loaded.diagnostics?.some((diagnostic) => diagnostic.severity === "error")) {
|
|
176
|
+
if (strict)
|
|
177
|
+
throwForDiagnostics(diagnostics);
|
|
178
|
+
// In compatibility mode retain valid fields from the source while
|
|
179
|
+
// surfacing the invalid ones as diagnostics.
|
|
180
|
+
}
|
|
181
|
+
values = mergeValues(values, loaded.values, source.kind, rejectUnknownKeys, diagnostics, fieldSources);
|
|
182
|
+
}
|
|
183
|
+
diagnostics.push(...validateValues(values, "runtime"));
|
|
184
|
+
if (strict)
|
|
185
|
+
throwForDiagnostics(diagnostics);
|
|
186
|
+
return createResolvedConfig(values, sources.map((source) => source.kind), diagnostics, fieldSources);
|
|
187
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Canonical configuration contracts for the v3.3 resolver.
|
|
3
|
+
*
|
|
4
|
+
* This module owns `SDKConfig` and `DEFAULT_CONFIG`. `schema.ts` re-exports
|
|
5
|
+
* these symbols for compatibility with existing imports.
|
|
6
|
+
*/
|
|
7
|
+
import type { ProviderConfig, Authentication } from "../types/providers.js";
|
|
8
|
+
export type ConfigSourceKind = "defaults" | "file" | "environment" | "runtime";
|
|
9
|
+
export type ConfigDiagnosticSeverity = "info" | "warning" | "error";
|
|
10
|
+
export interface ConfigDiagnostic {
|
|
11
|
+
code: string;
|
|
12
|
+
message: string;
|
|
13
|
+
path: string;
|
|
14
|
+
severity: ConfigDiagnosticSeverity;
|
|
15
|
+
source: ConfigSourceKind;
|
|
16
|
+
}
|
|
17
|
+
export interface ConfigSourceResult {
|
|
18
|
+
values: Partial<SDKConfig>;
|
|
19
|
+
diagnostics?: ConfigDiagnostic[];
|
|
20
|
+
}
|
|
21
|
+
export interface ConfigSource {
|
|
22
|
+
kind: ConfigSourceKind;
|
|
23
|
+
load(): ConfigSourceResult;
|
|
24
|
+
}
|
|
25
|
+
export interface ConfigResolutionOptions {
|
|
26
|
+
sources?: ConfigSource[];
|
|
27
|
+
overrides?: Partial<SDKConfig>;
|
|
28
|
+
strict?: boolean;
|
|
29
|
+
rejectUnknownKeys?: boolean;
|
|
30
|
+
}
|
|
31
|
+
export type SafeProviderConfig = Omit<ProviderConfig, "authentication" | "extraHeaders"> & {
|
|
32
|
+
authentication: {
|
|
33
|
+
type: Authentication["type"];
|
|
34
|
+
};
|
|
35
|
+
extraHeaders?: Record<string, string>;
|
|
36
|
+
};
|
|
37
|
+
export type SafeSDKConfig = Omit<SDKConfig, "providers"> & {
|
|
38
|
+
providers: SafeProviderConfig[];
|
|
39
|
+
};
|
|
40
|
+
/** Application-level SDK configuration. */
|
|
41
|
+
export interface SDKConfig {
|
|
42
|
+
defaultProvider: string;
|
|
43
|
+
defaultModel: string;
|
|
44
|
+
temperature: number;
|
|
45
|
+
maxTokens: number;
|
|
46
|
+
stream: boolean;
|
|
47
|
+
toolsEnabled: boolean;
|
|
48
|
+
reasoningEnabled: boolean;
|
|
49
|
+
logLevel: "none" | "error" | "info" | "debug";
|
|
50
|
+
requestTimeoutMs: number;
|
|
51
|
+
maxRetries: number;
|
|
52
|
+
circuitBreakerEnabled: boolean;
|
|
53
|
+
circuitBreakerThreshold: number;
|
|
54
|
+
circuitBreakerResetMs: number;
|
|
55
|
+
promptCaching: boolean;
|
|
56
|
+
workspaceDir: string;
|
|
57
|
+
providers: ProviderConfig[];
|
|
58
|
+
allowedTools: string[];
|
|
59
|
+
deniedTools: string[];
|
|
60
|
+
sessionBudget?: number;
|
|
61
|
+
perRequestBudget?: number;
|
|
62
|
+
rbac?: import("../security/rbac.js").RBACConfig;
|
|
63
|
+
costAlerts?: import("../cost/alerts.js").CostAlertConfig;
|
|
64
|
+
sla?: Array<import("../telemetry/sla.js").SLADefinition>;
|
|
65
|
+
}
|
|
66
|
+
export declare const DEFAULT_CONFIG: SDKConfig;
|
|
67
|
+
export declare const CONFIG_KEYS: Set<string>;
|
|
68
|
+
export declare function cloneConfigValue<T>(value: T): T;
|
|
69
|
+
export declare function isConfigKey(key: string): key is keyof SDKConfig;
|