@hilbras/sdk 3.2.0 → 3.3.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 CHANGED
@@ -1,9 +1,9 @@
1
1
  <p align="center">
2
- <img src="https://img.shields.io/badge/version-3.2.0-blue" alt="version">
2
+ <img src="https://img.shields.io/badge/version-3.3.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-1645%20passing-brightgreen" alt="tests">
6
+ <img src="https://img.shields.io/badge/tests-1662%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,7 @@ 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) |
191
213
  | **Middleware pipeline** | Transport-level middleware: auth headers, logging, custom request/response transforms | [API Reference](docs/api-reference.md) |
192
214
  | **Agent framework** | ToolLoopAgent, ReActAgent, PlanAndExecuteAgent with approval, budget, cost tracking | [Agent](docs/agent.md) |
193
215
  | **Evaluation** | LLM output evaluation with built-in metrics (exact_match, similarity, toxicity) | [Eval](docs/eval.md) |
@@ -203,6 +225,22 @@ const transport = new MiddlewareTransport(
203
225
 
204
226
  ---
205
227
 
228
+ ## What's New in v3.3.0
229
+
230
+ **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.
231
+
232
+ **Validation and diagnostics** — configuration values receive strict numeric, boolean, enum, provider, authentication, and SSRF validation. `getConfigDiagnostics()` reports safe, actionable diagnostics without exposing credentials.
233
+
234
+ **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.
235
+
236
+ **Compatibility** — `loadConfig()`, `createConfig()`, `validateConfig()`, and `sdkConfig` remain supported. See the [v3.2 migration guide](docs/migration-from-v3.2.md) for incremental adoption.
237
+
238
+ **Documentation and examples** — added a configuration guide, migration guide, API reference section, and runtime/file configuration examples.
239
+
240
+ See [`CHANGELOG.md`](CHANGELOG.md) and [`HILBRAS-SDK-FULL-AUDIT.md`](HILBRAS-SDK-FULL-AUDIT.md) for the complete release and audit details.
241
+
242
+ ---
243
+
206
244
  ## What's New in v3.2.0
207
245
 
208
246
  **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.
@@ -18,6 +18,9 @@ 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";
21
24
  import { AdapterRegistry } from "../providers/adapter-registry.js";
22
25
  import { ModelRouter } from "../router/model-router.js";
23
26
  import type { StructuredLogger } from "../telemetry/structured-logger.js";
@@ -75,6 +78,16 @@ export interface HilbrasClientConfig {
75
78
  * `sessionBudget`, `perRequestBudget`.
76
79
  */
77
80
  sdkConfig?: import("../config/schema.js").SDKConfig;
81
+ /**
82
+ * Canonical v3.3 configuration input. Sources are resolved once during
83
+ * construction using defaults < file/environment sources < runtime values.
84
+ * Existing `sdkConfig` remains supported as a compatibility alias.
85
+ */
86
+ config?: Partial<SDKConfig>;
87
+ /** Explicit configuration sources for the canonical resolver. */
88
+ configSources?: ConfigSource[];
89
+ /** An already-resolved configuration, primarily for framework adapters. */
90
+ resolvedConfig?: ResolvedSDKConfig;
78
91
  /**
79
92
  * v1.1.0: Optional telemetry sinks. When provided, the client automatically
80
93
  * forwards lifecycle events to the configured sinks.
@@ -108,6 +121,7 @@ export declare class HilbrasClient implements AsyncDisposable {
108
121
  private _adapterRegistry;
109
122
  private _adapters;
110
123
  private _defaultPolicy;
124
+ private _resolvedConfig;
111
125
  private _router;
112
126
  private _hooks;
113
127
  private _requestCounter;
@@ -119,15 +133,6 @@ export declare class HilbrasClient implements AsyncDisposable {
119
133
  private _requestExecutor;
120
134
  private _requestPipeline;
121
135
  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
136
  /** Subscribe to lifecycle events. Returns an unsubscribe function. */
132
137
  on<T extends HookEvent = HookEvent>(event: T["type"], listener: HookListener<T>): () => void;
133
138
  /** Remove a specific listener */
@@ -163,6 +168,10 @@ export declare class HilbrasClient implements AsyncDisposable {
163
168
  removeProvider(name: string): void;
164
169
  getProvider(name: string): ProviderConfig | undefined;
165
170
  listProviders(): ProviderConfig[];
171
+ /** Return a redacted snapshot of the resolved client configuration. */
172
+ getConfigSnapshot(): SafeSDKConfig;
173
+ /** Return configuration diagnostics without secret values. */
174
+ getConfigDiagnostics(): ConfigDiagnostic[];
166
175
  /**
167
176
  * Add a provider from the built-in catalog with one line.
168
177
  *
@@ -11,6 +11,8 @@
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";
14
16
  import { ProviderRegistry } from "../providers/registry.js";
15
17
  import { cloneProviderConfig } from "../config/provider-config.js";
16
18
  import { FetchTransport } from "../transport/fetch.js";
@@ -36,6 +38,7 @@ export class HilbrasClient {
36
38
  _adapterRegistry;
37
39
  _adapters = new Map();
38
40
  _defaultPolicy;
41
+ _resolvedConfig;
39
42
  _router;
40
43
  _hooks = new ClientHooks();
41
44
  _requestCounter = 0;
@@ -57,11 +60,16 @@ export class HilbrasClient {
57
60
  this._allowInsecureUrls = config?.allowInsecureUrls ?? false;
58
61
  this._allowPrivateNetwork = config?.allowPrivateNetwork ?? false;
59
62
  this._tokenizer = config?.tokenizer ?? null;
60
- // v0.10.0 PR-5: derive policy + budget from sdkConfig when not
61
- // explicitly provided. Precedence: explicit > sdkConfig > defaults.
62
- const sdk = config?.sdkConfig;
63
- this._defaultPolicy = config?.policy ?? (sdk ? this._policyFromSDK(sdk) : undefined);
64
- const sdkBudget = sdk ? this._budgetFromSDK(sdk) : undefined;
63
+ // v3.3.0: resolve layered configuration exactly once at construction.
64
+ const inputConfig = config?.config ?? config?.sdkConfig;
65
+ this._resolvedConfig = config?.resolvedConfig ?? resolveConfig({
66
+ sources: config?.configSources,
67
+ overrides: inputConfig,
68
+ strict: true,
69
+ });
70
+ const resolvedSdk = this._resolvedConfig.values;
71
+ this._defaultPolicy = config?.policy ?? policyFromConfig(resolvedSdk);
72
+ const sdkBudget = budgetFromConfig(resolvedSdk);
65
73
  this._budgetTracker = new BudgetTracker(config?.budget ?? sdkBudget);
66
74
  this._requestExecutor = new RequestExecutor({
67
75
  policy: {
@@ -86,8 +94,8 @@ export class HilbrasClient {
86
94
  },
87
95
  });
88
96
  // v1.1.0: Register providers from SDKConfig if provided
89
- if (sdk?.providers?.length) {
90
- for (const provider of sdk.providers) {
97
+ if (resolvedSdk.providers.length > 0) {
98
+ for (const provider of resolvedSdk.providers) {
91
99
  if (!this._registry.get(provider.name)) {
92
100
  this.addProvider(provider);
93
101
  }
@@ -101,38 +109,6 @@ export class HilbrasClient {
101
109
  config.telemetry.openTelemetry.instrumentClient(this);
102
110
  }
103
111
  }
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
112
  /** Subscribe to lifecycle events. Returns an unsubscribe function. */
137
113
  on(event, listener) {
138
114
  return this._hooks.on(event, listener);
@@ -214,6 +190,14 @@ export class HilbrasClient {
214
190
  listProviders() {
215
191
  return this._registry.list();
216
192
  }
193
+ /** Return a redacted snapshot of the resolved client configuration. */
194
+ getConfigSnapshot() {
195
+ return this._resolvedConfig.safeSnapshot();
196
+ }
197
+ /** Return configuration diagnostics without secret values. */
198
+ getConfigDiagnostics() {
199
+ return this._resolvedConfig.diagnostics.map((diagnostic) => ({ ...diagnostic }));
200
+ }
217
201
  /**
218
202
  * Add a provider from the built-in catalog with one line.
219
203
  *
@@ -0,0 +1,3 @@
1
+ import { type ResolvedSDKConfig } from "./resolved-config.js";
2
+ import { type ConfigResolutionOptions } from "./config-schema.js";
3
+ export declare function resolveConfig(options?: ConfigResolutionOptions): ResolvedSDKConfig;
@@ -0,0 +1,173 @@
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 { ConfigurationError } from "../errors/index.js";
8
+ const LOG_LEVELS = new Set(["none", "error", "info", "debug"]);
9
+ function isPlainObject(value) {
10
+ return !!value && typeof value === "object" && !Array.isArray(value);
11
+ }
12
+ function errorDiagnostic(source, code, path, message) {
13
+ return { code, path, message, severity: "error", source };
14
+ }
15
+ function warningDiagnostic(source, code, path, message) {
16
+ return { code, path, message, severity: "warning", source };
17
+ }
18
+ function mergePlainObjects(base, override) {
19
+ const result = { ...base };
20
+ for (const [key, value] of Object.entries(override)) {
21
+ if (key === "__proto__" || key === "constructor" || key === "prototype")
22
+ continue;
23
+ if (value === undefined)
24
+ continue;
25
+ if (isPlainObject(result[key]) && isPlainObject(value)) {
26
+ result[key] = mergePlainObjects(result[key], value);
27
+ }
28
+ else {
29
+ result[key] = cloneConfigValue(value);
30
+ }
31
+ }
32
+ return result;
33
+ }
34
+ function mergeValues(base, override, source, rejectUnknownKeys, diagnostics, fieldSources) {
35
+ const result = cloneConfigValue(base);
36
+ for (const [key, value] of Object.entries(override)) {
37
+ if (!CONFIG_KEYS.has(key)) {
38
+ diagnostics.push((rejectUnknownKeys ? errorDiagnostic : warningDiagnostic)(source, "CONFIG_UNKNOWN_KEY", key, `unknown configuration key '${key}' was ignored`));
39
+ continue;
40
+ }
41
+ if (value === undefined)
42
+ continue;
43
+ const current = result[key];
44
+ if (isPlainObject(current) && isPlainObject(value)) {
45
+ result[key] = mergePlainObjects(current, value);
46
+ }
47
+ else {
48
+ result[key] = cloneConfigValue(value);
49
+ }
50
+ fieldSources[key] = source;
51
+ }
52
+ return result;
53
+ }
54
+ function validateValues(values, source) {
55
+ const diagnostics = [];
56
+ const numberFields = [
57
+ ["temperature", "temperature", (value) => Number.isFinite(value) && value >= 0 && value <= 2],
58
+ ["maxTokens", "maxTokens", (value) => Number.isInteger(value) && value > 0],
59
+ ["requestTimeoutMs", "requestTimeoutMs", (value) => Number.isInteger(value) && value >= 1000],
60
+ ["maxRetries", "maxRetries", (value) => Number.isInteger(value) && value >= 0],
61
+ ["circuitBreakerThreshold", "circuitBreakerThreshold", (value) => Number.isInteger(value) && value > 0],
62
+ ["circuitBreakerResetMs", "circuitBreakerResetMs", (value) => Number.isInteger(value) && value >= 0],
63
+ ];
64
+ for (const [field, path, valid] of numberFields) {
65
+ if (!valid(values[field])) {
66
+ diagnostics.push(errorDiagnostic(source, "CONFIG_INVALID_VALUE", path, `${path} has an invalid value`));
67
+ }
68
+ }
69
+ if (!LOG_LEVELS.has(values.logLevel)) {
70
+ diagnostics.push(errorDiagnostic(source, "CONFIG_INVALID_ENUM", "logLevel", "logLevel must be none, error, info, or debug"));
71
+ }
72
+ if (!Array.isArray(values.providers)) {
73
+ diagnostics.push(errorDiagnostic(source, "CONFIG_INVALID_TYPE", "providers", "providers must be an array"));
74
+ return diagnostics;
75
+ }
76
+ const names = new Set();
77
+ values.providers.forEach((provider, index) => {
78
+ const path = `providers[${index}]`;
79
+ if (!provider || typeof provider !== "object") {
80
+ diagnostics.push(errorDiagnostic(source, "CONFIG_INVALID_TYPE", path, "provider must be an object"));
81
+ return;
82
+ }
83
+ if (!provider.name || typeof provider.name !== "string") {
84
+ diagnostics.push(errorDiagnostic(source, "CONFIG_INVALID_VALUE", `${path}.name`, "provider name is required"));
85
+ }
86
+ else if (names.has(provider.name)) {
87
+ diagnostics.push(errorDiagnostic(source, "CONFIG_DUPLICATE_PROVIDER", `${path}.name`, "provider names must be unique"));
88
+ }
89
+ else {
90
+ names.add(provider.name);
91
+ }
92
+ if (typeof provider.adapter !== "string" || provider.adapter.length === 0) {
93
+ diagnostics.push(errorDiagnostic(source, "CONFIG_INVALID_VALUE", `${path}.adapter`, "provider adapter is required"));
94
+ }
95
+ if (!Array.isArray(provider.models)) {
96
+ diagnostics.push(errorDiagnostic(source, "CONFIG_INVALID_TYPE", `${path}.models`, "provider models must be an array"));
97
+ }
98
+ if (typeof provider.baseUrl !== "string") {
99
+ diagnostics.push(errorDiagnostic(source, "CONFIG_INVALID_VALUE", `${path}.baseUrl`, "provider baseUrl is required"));
100
+ }
101
+ else {
102
+ const guard = validateBaseUrl(provider.baseUrl, { allowInsecure: !!provider.allowInsecure });
103
+ if (!guard.ok) {
104
+ diagnostics.push(errorDiagnostic(source, "CONFIG_UNSAFE_PROVIDER_URL", `${path}.baseUrl`, `provider URL rejected by security policy: ${guard.reason}`));
105
+ }
106
+ }
107
+ const auth = provider.authentication;
108
+ if (!auth || typeof auth !== "object" || typeof auth.type !== "string") {
109
+ diagnostics.push(errorDiagnostic(source, "CONFIG_INVALID_AUTH", `${path}.authentication`, "provider authentication is required"));
110
+ }
111
+ else if (auth.type === "bearer" && (typeof auth.apiKey !== "string" || auth.apiKey.length === 0)) {
112
+ diagnostics.push(errorDiagnostic(source, "CONFIG_INVALID_AUTH", `${path}.authentication.apiKey`, "bearer authentication requires an API key"));
113
+ }
114
+ else if (auth.type === "header" && (typeof auth.name !== "string" || typeof auth.value !== "string")) {
115
+ diagnostics.push(errorDiagnostic(source, "CONFIG_INVALID_AUTH", `${path}.authentication`, "header authentication requires name and value"));
116
+ }
117
+ else if (auth.type !== "bearer" && auth.type !== "header" && auth.type !== "none") {
118
+ diagnostics.push(errorDiagnostic(source, "CONFIG_INVALID_AUTH", `${path}.authentication.type`, "unsupported authentication type"));
119
+ }
120
+ });
121
+ if (Array.isArray(values.allowedTools) && Array.isArray(values.deniedTools)) {
122
+ const denied = new Set(values.deniedTools);
123
+ const overlap = values.allowedTools.filter((tool) => denied.has(tool));
124
+ if (overlap.length > 0) {
125
+ diagnostics.push(errorDiagnostic(source, "CONFIG_TOOL_POLICY_CONFLICT", "allowedTools", "allowedTools and deniedTools must not overlap"));
126
+ }
127
+ }
128
+ return diagnostics;
129
+ }
130
+ function throwForDiagnostics(diagnostics) {
131
+ const errors = diagnostics.filter((diagnostic) => diagnostic.severity === "error");
132
+ if (errors.length === 0)
133
+ return;
134
+ const summary = errors.slice(0, 3).map((diagnostic) => `${diagnostic.path}: ${diagnostic.message}`).join("; ");
135
+ throw new ConfigurationError(`Configuration resolution failed: ${summary}`, "Check the configuration source, value types, and provider security policy.");
136
+ }
137
+ export function resolveConfig(options = {}) {
138
+ const strict = options.strict ?? true;
139
+ const rejectUnknownKeys = options.rejectUnknownKeys ?? false;
140
+ const diagnostics = [];
141
+ const fieldSources = {};
142
+ const suppliedSources = options.sources ?? [];
143
+ const sources = [
144
+ createDefaultsSource(),
145
+ ...suppliedSources.filter((source) => source.kind !== "defaults"),
146
+ ...(options.overrides ? [createRuntimeSource(options.overrides)] : []),
147
+ ];
148
+ let values = cloneConfigValue(DEFAULT_CONFIG);
149
+ for (const source of sources) {
150
+ let loaded;
151
+ try {
152
+ loaded = source.load();
153
+ }
154
+ catch {
155
+ diagnostics.push(errorDiagnostic(source.kind, "CONFIG_SOURCE_FAILED", "$", `configuration source '${source.kind}' failed`));
156
+ if (strict)
157
+ throwForDiagnostics(diagnostics);
158
+ continue;
159
+ }
160
+ diagnostics.push(...(loaded.diagnostics ?? []));
161
+ if (loaded.diagnostics?.some((diagnostic) => diagnostic.severity === "error")) {
162
+ if (strict)
163
+ throwForDiagnostics(diagnostics);
164
+ // In compatibility mode retain valid fields from the source while
165
+ // surfacing the invalid ones as diagnostics.
166
+ }
167
+ values = mergeValues(values, loaded.values, source.kind, rejectUnknownKeys, diagnostics, fieldSources);
168
+ }
169
+ diagnostics.push(...validateValues(values, "runtime"));
170
+ if (strict)
171
+ throwForDiagnostics(diagnostics);
172
+ return createResolvedConfig(values, sources.map((source) => source.kind), diagnostics, fieldSources);
173
+ }
@@ -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;
@@ -0,0 +1,56 @@
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
+ export const DEFAULT_CONFIG = {
8
+ defaultProvider: "",
9
+ defaultModel: "gpt-4o",
10
+ temperature: 0.7,
11
+ maxTokens: 4096,
12
+ stream: true,
13
+ toolsEnabled: true,
14
+ reasoningEnabled: false,
15
+ logLevel: "none",
16
+ requestTimeoutMs: 120_000,
17
+ maxRetries: 3,
18
+ circuitBreakerEnabled: true,
19
+ circuitBreakerThreshold: 5,
20
+ circuitBreakerResetMs: 60_000,
21
+ promptCaching: true,
22
+ workspaceDir: typeof process !== "undefined" && typeof process.cwd === "function" ? process.cwd() : "/",
23
+ providers: [],
24
+ allowedTools: [],
25
+ deniedTools: [],
26
+ };
27
+ const OPTIONAL_CONFIG_KEYS = [
28
+ "sessionBudget",
29
+ "perRequestBudget",
30
+ "rbac",
31
+ "costAlerts",
32
+ "sla",
33
+ ];
34
+ export const CONFIG_KEYS = new Set([
35
+ ...Object.keys(DEFAULT_CONFIG),
36
+ ...OPTIONAL_CONFIG_KEYS,
37
+ ]);
38
+ const BLOCKED_KEYS = new Set(["__proto__", "constructor", "prototype"]);
39
+ export function cloneConfigValue(value) {
40
+ if (Array.isArray(value)) {
41
+ return value.map((item) => cloneConfigValue(item));
42
+ }
43
+ if (value && typeof value === "object") {
44
+ const result = {};
45
+ for (const [key, item] of Object.entries(value)) {
46
+ if (BLOCKED_KEYS.has(key))
47
+ continue;
48
+ result[key] = cloneConfigValue(item);
49
+ }
50
+ return result;
51
+ }
52
+ return value;
53
+ }
54
+ export function isConfigKey(key) {
55
+ return CONFIG_KEYS.has(key) && !BLOCKED_KEYS.has(key);
56
+ }
@@ -1,29 +1,22 @@
1
1
  /**
2
- * @hilbras/sdk — Configuration Loader
2
+ * @hilbras/sdk — Configuration compatibility facade
3
3
  *
4
- * Loads configuration from multiple sources with precedence:
5
- * Runtime overrides > Environment variables > File config > Defaults
6
- *
7
- * The env loader maps the legacy `HILBRAS_PROVIDER_*` variables to the
8
- * canonical `ProviderConfig` shape (introduced in v0.10.0) and runs every
9
- * `baseUrl` through `validateBaseUrl` so an env-var-based SSRF bypass is
10
- * not possible. The API key is captured for redacted error messages; it
11
- * is *not* stored as a plain string on the loaded config — the loader
12
- * forces it into the `authentication` field which is the public contract.
4
+ * New code should use `resolveConfig()` and explicit configuration sources.
5
+ * These functions remain as the v3.2-compatible API surface.
13
6
  */
14
7
  import type { SDKConfig } from "./schema.js";
15
8
  /**
16
- * Load configuration with layered precedence:
17
- * 1. Defaults
18
- * 2. File config (if provided)
19
- * 3. Environment variables
20
- * 4. Runtime overrides
9
+ * Load configuration with the legacy precedence and permissive file behavior:
10
+ * defaults < file < environment < runtime overrides.
21
11
  */
22
12
  export declare function loadConfig(options?: {
23
13
  configPath?: string;
24
14
  overrides?: Partial<SDKConfig>;
25
15
  }): SDKConfig;
26
- /** Create a fresh config with overrides (no env or file loading) */
16
+ /** Create a fresh config with overrides (no environment or file loading). */
27
17
  export declare function createConfig(overrides?: Partial<SDKConfig>): SDKConfig;
28
- /** Validate a config (returns null if valid, error message if invalid) */
18
+ /**
19
+ * Validate a config using the legacy string-or-null contract.
20
+ * New code should inspect `resolveConfig().diagnostics` instead.
21
+ */
29
22
  export declare function validateConfig(config: SDKConfig): string | null;
@@ -1,147 +1,50 @@
1
1
  /**
2
- * @hilbras/sdk — Configuration Loader
2
+ * @hilbras/sdk — Configuration compatibility facade
3
3
  *
4
- * Loads configuration from multiple sources with precedence:
5
- * Runtime overrides > Environment variables > File config > Defaults
6
- *
7
- * The env loader maps the legacy `HILBRAS_PROVIDER_*` variables to the
8
- * canonical `ProviderConfig` shape (introduced in v0.10.0) and runs every
9
- * `baseUrl` through `validateBaseUrl` so an env-var-based SSRF bypass is
10
- * not possible. The API key is captured for redacted error messages; it
11
- * is *not* stored as a plain string on the loaded config — the loader
12
- * forces it into the `authentication` field which is the public contract.
4
+ * New code should use `resolveConfig()` and explicit configuration sources.
5
+ * These functions remain as the v3.2-compatible API surface.
13
6
  */
14
- import { DEFAULT_CONFIG } from "./schema.js";
15
- import { validateBaseUrl } from "../security/url-guard.js";
16
7
  import { readFileSync } from "node:fs";
17
- /** Environment variable prefix for SDK config */
18
- const ENV_PREFIX = "HILBRAS_";
19
- /**
20
- * Heuristic adapter detection from a baseUrl. Used when the env loader
21
- * builds a provider from `HILBRAS_PROVIDER_URL`/`HILBRAS_PROVIDER_FORMAT`
22
- * and the user has not specified an adapter explicitly. Matches the
23
- * simplest substrings; if no match, defaults to `openai`.
24
- */
25
- function inferAdapter(baseUrl) {
26
- const lower = baseUrl.toLowerCase();
27
- if (lower.includes("anthropic"))
28
- return "anthropic";
29
- if (lower.includes("googleapis") || lower.includes("generativelanguage"))
30
- return "google-genai";
31
- if (lower.includes("azure"))
32
- return "azure";
33
- if (lower.includes("groq"))
34
- return "groq";
35
- if (lower.includes("localhost") || lower.includes("127.0.0.1") || lower.includes("[::1]"))
36
- return "ollama";
37
- return "openai";
38
- }
39
- /** Parse environment variables into SDKConfig fields */
40
- function loadFromEnv() {
41
- const env = process.env;
42
- const config = {};
43
- if (env[`${ENV_PREFIX}DEFAULT_PROVIDER`])
44
- config.defaultProvider = env[`${ENV_PREFIX}DEFAULT_PROVIDER`];
45
- if (env[`${ENV_PREFIX}DEFAULT_MODEL`])
46
- config.defaultModel = env[`${ENV_PREFIX}DEFAULT_MODEL`];
47
- if (env[`${ENV_PREFIX}TEMPERATURE`])
48
- config.temperature = parseFloat(env[`${ENV_PREFIX}TEMPERATURE`] ?? "");
49
- if (env[`${ENV_PREFIX}MAX_TOKENS`])
50
- config.maxTokens = parseInt(env[`${ENV_PREFIX}MAX_TOKENS`] ?? "", 10);
51
- if (env[`${ENV_PREFIX}STREAM`])
52
- config.stream = env[`${ENV_PREFIX}STREAM`] === "true";
53
- if (env[`${ENV_PREFIX}LOG_LEVEL`])
54
- config.logLevel = env[`${ENV_PREFIX}LOG_LEVEL`];
55
- if (env[`${ENV_PREFIX}TIMEOUT`])
56
- config.requestTimeoutMs = parseInt(env[`${ENV_PREFIX}TIMEOUT`] ?? "", 10);
57
- if (env[`${ENV_PREFIX}MAX_RETRIES`])
58
- config.maxRetries = parseInt(env[`${ENV_PREFIX}MAX_RETRIES`] ?? "", 10);
59
- if (env[`${ENV_PREFIX}PROMPT_CACHING`])
60
- config.promptCaching = env[`${ENV_PREFIX}PROMPT_CACHING`] === "true";
61
- // Provider config from env. v0.10.0: the loader now produces the canonical
62
- // `ProviderConfig` shape. We also redact the API key for any log that
63
- // would surface it.
64
- const providerUrl = env[`${ENV_PREFIX}PROVIDER_URL`];
65
- const providerKey = env[`${ENV_PREFIX}PROVIDER_KEY`];
66
- const providerName = env[`${ENV_PREFIX}PROVIDER_NAME`];
67
- if (providerUrl && providerKey) {
68
- // Validate the URL through the v0.9.3 SSRF guard. We deliberately
69
- // allow insecure here because the env loader is the documented
70
- // way to point at a local Ollama (`http://localhost:11434`).
71
- // Loopback/private-range access is gated by the global
72
- // `allowInsecureUrls` / `allowPrivateNetwork` flags on HilbrasClient,
73
- // not on the loader.
74
- const guard = validateBaseUrl(providerUrl, { allowInsecure: true });
75
- if (!guard.ok) {
76
- throw new Error(`HILBRAS_PROVIDER_URL rejected by SSRF guard: ${guard.reason}`);
77
- }
78
- const inferredAdapter = inferAdapter(providerUrl);
79
- config.providers = [{
80
- name: providerName || "default",
81
- baseUrl: providerUrl,
82
- authentication: { type: "bearer", apiKey: providerKey },
83
- models: [],
84
- adapter: inferredAdapter,
85
- allowInsecure: providerUrl.startsWith("http://"),
86
- }];
87
- config.defaultProvider = providerName || "default";
88
- }
89
- return config;
90
- }
91
- /** Parse a simple JSON config file */
92
- function loadFromFile(filePath) {
93
- try {
94
- const content = readFileSync(filePath, "utf-8");
95
- return JSON.parse(content);
96
- }
97
- catch {
98
- return {};
99
- }
100
- }
101
- /** Deep merge two config objects (second overrides first) */
102
- function deepMerge(base, override) {
103
- const result = { ...base };
104
- for (const [key, value] of Object.entries(override)) {
105
- if (value === undefined)
106
- continue;
107
- const existing = result[key];
108
- if (typeof existing === "object" && existing !== null && !Array.isArray(existing) && typeof value === "object" && value !== null && !Array.isArray(value)) {
109
- result[key] = deepMerge(existing, value);
110
- }
111
- else {
112
- result[key] = value;
113
- }
114
- }
115
- return result;
116
- }
8
+ import { resolveConfig } from "./config-resolver.js";
9
+ import { createEnvironmentSource } from "./sources/environment.js";
10
+ import { createFileSource } from "./sources/file.js";
11
+ import { validateBaseUrl } from "../security/url-guard.js";
117
12
  /**
118
- * Load configuration with layered precedence:
119
- * 1. Defaults
120
- * 2. File config (if provided)
121
- * 3. Environment variables
122
- * 4. Runtime overrides
13
+ * Load configuration with the legacy precedence and permissive file behavior:
14
+ * defaults < file < environment < runtime overrides.
123
15
  */
124
16
  export function loadConfig(options) {
125
- let config = { ...DEFAULT_CONFIG };
126
- // Layer 2: File config
17
+ const sources = [];
127
18
  if (options?.configPath) {
128
- const fileConfig = loadFromFile(options.configPath);
129
- config = deepMerge(config, fileConfig);
19
+ sources.push(createFileSource({
20
+ path: options.configPath,
21
+ readFile: (path) => readFileSync(path, "utf-8"),
22
+ }));
130
23
  }
131
- // Layer 3: Environment variables
132
- const envConfig = loadFromEnv();
133
- config = deepMerge(config, envConfig);
134
- // Layer 4: Runtime overrides
135
- if (options?.overrides) {
136
- config = deepMerge(config, options.overrides);
24
+ sources.push(createEnvironmentSource(typeof process !== "undefined" && process.env ? process.env : {}));
25
+ const resolved = resolveConfig({
26
+ sources,
27
+ overrides: options?.overrides,
28
+ strict: false,
29
+ });
30
+ const unsafeUrl = resolved.diagnostics.find((diagnostic) => diagnostic.code === "CONFIG_UNSAFE_PROVIDER_URL");
31
+ if (unsafeUrl) {
32
+ throw new Error(`HILBRAS_PROVIDER_URL rejected by SSRF guard: ${unsafeUrl.message}`);
137
33
  }
138
- return config;
34
+ return resolved.values;
139
35
  }
140
- /** Create a fresh config with overrides (no env or file loading) */
36
+ /** Create a fresh config with overrides (no environment or file loading). */
141
37
  export function createConfig(overrides) {
142
- return deepMerge({ ...DEFAULT_CONFIG }, overrides ?? {});
38
+ return resolveConfig({
39
+ sources: [],
40
+ overrides: overrides ?? {},
41
+ strict: false,
42
+ }).values;
143
43
  }
144
- /** Validate a config (returns null if valid, error message if invalid) */
44
+ /**
45
+ * Validate a config using the legacy string-or-null contract.
46
+ * New code should inspect `resolveConfig().diagnostics` instead.
47
+ */
145
48
  export function validateConfig(config) {
146
49
  if (config.temperature < 0 || config.temperature > 2) {
147
50
  return `Temperature must be between 0 and 2, got ${config.temperature}`;
@@ -158,11 +61,10 @@ export function validateConfig(config) {
158
61
  if (!["none", "error", "info", "debug"].includes(config.logLevel)) {
159
62
  return `Invalid logLevel: ${config.logLevel}`;
160
63
  }
161
- // v0.10.0: also validate every provider's baseUrl.
162
- for (const p of config.providers) {
163
- const guard = validateBaseUrl(p.baseUrl, { allowInsecure: !!p.allowInsecure });
64
+ for (const provider of config.providers) {
65
+ const guard = validateBaseUrl(provider.baseUrl, { allowInsecure: !!provider.allowInsecure });
164
66
  if (!guard.ok)
165
- return `Provider ${p.name}: ${guard.reason}`;
67
+ return `Provider ${provider.name}: ${guard.reason}`;
166
68
  }
167
69
  return null;
168
70
  }
@@ -0,0 +1,11 @@
1
+ export { DEFAULT_CONFIG } from "./schema.js";
2
+ export type { SDKConfig } from "./schema.js";
3
+ export { resolveConfig } from "./config-resolver.js";
4
+ export { createDefaultsSource } from "./sources/defaults.js";
5
+ export { createEnvironmentSource } from "./sources/environment.js";
6
+ export { createFileSource } from "./sources/file.js";
7
+ export { createRuntimeSource } from "./sources/runtime.js";
8
+ export type { ConfigDiagnostic, ConfigResolutionOptions, ConfigSource, ConfigSourceKind, ConfigSourceResult, SafeProviderConfig, SafeSDKConfig, } from "./config-schema.js";
9
+ export type { ResolvedSDKConfig } from "./resolved-config.js";
10
+ export { budgetFromConfig, policyFromConfig } from "./resolved-config.js";
11
+ export { createConfig, loadConfig, validateConfig } from "./config.js";
@@ -0,0 +1,8 @@
1
+ export { DEFAULT_CONFIG } from "./schema.js";
2
+ export { resolveConfig } from "./config-resolver.js";
3
+ export { createDefaultsSource } from "./sources/defaults.js";
4
+ export { createEnvironmentSource } from "./sources/environment.js";
5
+ export { createFileSource } from "./sources/file.js";
6
+ export { createRuntimeSource } from "./sources/runtime.js";
7
+ export { budgetFromConfig, policyFromConfig } from "./resolved-config.js";
8
+ export { createConfig, loadConfig, validateConfig } from "./config.js";
@@ -0,0 +1,15 @@
1
+ import type { SDKConfig } from "./schema.js";
2
+ import type { ExecutionPolicy } from "../types/policy.js";
3
+ import type { BudgetConfig } from "../cost/types.js";
4
+ import { type ConfigDiagnostic, type ConfigSourceKind, type SafeSDKConfig } from "./config-schema.js";
5
+ export interface ResolvedSDKConfig {
6
+ values: SDKConfig;
7
+ sources: ConfigSourceKind[];
8
+ diagnostics: ConfigDiagnostic[];
9
+ fieldSources: Partial<Record<keyof SDKConfig, ConfigSourceKind>>;
10
+ safeSnapshot(): SafeSDKConfig;
11
+ }
12
+ export declare function policyFromConfig(config: SDKConfig): ExecutionPolicy;
13
+ export declare function budgetFromConfig(config: SDKConfig): BudgetConfig;
14
+ export declare function createSafeSnapshot(values: SDKConfig): SafeSDKConfig;
15
+ export declare function createResolvedConfig(values: SDKConfig, sources: ConfigSourceKind[], diagnostics: ConfigDiagnostic[], fieldSources: Partial<Record<keyof SDKConfig, ConfigSourceKind>>): ResolvedSDKConfig;
@@ -0,0 +1,60 @@
1
+ import { cloneConfigValue, } from "./config-schema.js";
2
+ const SECRET_KEY = /(secret|token|password|apikey|api_key|authorization|webhook|credential)/i;
3
+ function redactValue(key, value) {
4
+ if (SECRET_KEY.test(key))
5
+ return "[REDACTED]";
6
+ if (Array.isArray(value))
7
+ return value.map((item) => redactValue(key, item));
8
+ if (value && typeof value === "object") {
9
+ const result = {};
10
+ for (const [childKey, childValue] of Object.entries(value)) {
11
+ result[childKey] = redactValue(childKey, childValue);
12
+ }
13
+ return result;
14
+ }
15
+ return value;
16
+ }
17
+ export function policyFromConfig(config) {
18
+ return {
19
+ retry: { maxRetries: config.maxRetries },
20
+ timeout: { requestTimeoutMs: config.requestTimeoutMs },
21
+ circuitBreaker: {
22
+ enabled: config.circuitBreakerEnabled,
23
+ failureThreshold: config.circuitBreakerThreshold,
24
+ timeoutMs: config.circuitBreakerResetMs,
25
+ },
26
+ };
27
+ }
28
+ export function budgetFromConfig(config) {
29
+ const budget = {};
30
+ if (config.sessionBudget !== undefined)
31
+ budget.sessionBudget = config.sessionBudget;
32
+ if (config.perRequestBudget !== undefined)
33
+ budget.perRequestBudget = config.perRequestBudget;
34
+ return budget;
35
+ }
36
+ export function createSafeSnapshot(values) {
37
+ const copied = cloneConfigValue(values);
38
+ const safe = redactValue("config", copied);
39
+ return {
40
+ ...safe,
41
+ providers: safe.providers.map((provider) => ({
42
+ ...provider,
43
+ authentication: { type: provider.authentication.type },
44
+ extraHeaders: provider.extraHeaders
45
+ ? Object.fromEntries(Object.keys(provider.extraHeaders).map((key) => [key, "[REDACTED]"]))
46
+ : undefined,
47
+ })),
48
+ };
49
+ }
50
+ export function createResolvedConfig(values, sources, diagnostics, fieldSources) {
51
+ const stableValues = cloneConfigValue(values);
52
+ const stableDiagnostics = diagnostics.map((diagnostic) => ({ ...diagnostic }));
53
+ return {
54
+ values: stableValues,
55
+ sources: [...sources],
56
+ diagnostics: stableDiagnostics,
57
+ fieldSources: { ...fieldSources },
58
+ safeSnapshot: () => createSafeSnapshot(stableValues),
59
+ };
60
+ }
@@ -1,62 +1,8 @@
1
1
  /**
2
- * @hilbras/sdk — Configuration Schema
2
+ * @hilbras/sdk — Configuration schema compatibility exports
3
3
  *
4
- * Type-safe configuration with defaults, validation, and layered overrides.
5
- * Supports global defaults → file config → environment variables → runtime overrides.
6
- *
7
- * `ProviderConfig` is the canonical type, defined in `./provider-config.ts`
8
- * and re-exported from this module for convenience. The legacy
9
- * `format`/`apiKey` fields are gone; callers should use the structured
10
- * `authentication` and `adapter` fields.
4
+ * The canonical schema now lives in `config-schema.ts`; this module preserves
5
+ * the historical `@hilbras/sdk` and internal import paths.
11
6
  */
12
- import type { ProviderConfig } from "./provider-config.js";
13
- export type { ProviderConfig } from "./provider-config.js";
14
- export interface SDKConfig {
15
- /** Default provider name */
16
- defaultProvider: string;
17
- /** Default model ID */
18
- defaultModel: string;
19
- /** Default temperature (0-2) */
20
- temperature: number;
21
- /** Default max tokens */
22
- maxTokens: number;
23
- /** Enable streaming by default */
24
- stream: boolean;
25
- /** Enable tool calling by default */
26
- toolsEnabled: boolean;
27
- /** Enable reasoning/thinking by default */
28
- reasoningEnabled: boolean;
29
- /** Log level: none | error | info | debug */
30
- logLevel: "none" | "error" | "info" | "debug";
31
- /** Timeout for HTTP requests (ms) */
32
- requestTimeoutMs: number;
33
- /** Max retry attempts */
34
- maxRetries: number;
35
- /** Enable circuit breaker */
36
- circuitBreakerEnabled: boolean;
37
- /** Circuit breaker failure threshold */
38
- circuitBreakerThreshold: number;
39
- /** Circuit breaker reset timeout (ms) */
40
- circuitBreakerResetMs: number;
41
- /** Enable prompt caching when supported */
42
- promptCaching: boolean;
43
- /** Working directory for file tools */
44
- workspaceDir: string;
45
- /** Custom provider configurations */
46
- providers: ProviderConfig[];
47
- /** Allowed tools (empty = all) */
48
- allowedTools: string[];
49
- /** Denied tools */
50
- deniedTools: string[];
51
- /** Maximum total cost for the session (null = unlimited) */
52
- sessionBudget?: number;
53
- /** Maximum cost per individual request (null = unlimited) */
54
- perRequestBudget?: number;
55
- /** Role-based access control configuration */
56
- rbac?: import("../security/rbac.js").RBACConfig;
57
- /** Cost alert thresholds and channels */
58
- costAlerts?: import("../cost/alerts.js").CostAlertConfig;
59
- /** SLA monitoring definitions */
60
- sla?: Array<import("../telemetry/sla.js").SLADefinition>;
61
- }
62
- export declare const DEFAULT_CONFIG: SDKConfig;
7
+ export type { SDKConfig } from "./config-schema.js";
8
+ export { DEFAULT_CONFIG } from "./config-schema.js";
@@ -1,31 +1,7 @@
1
1
  /**
2
- * @hilbras/sdk — Configuration Schema
2
+ * @hilbras/sdk — Configuration schema compatibility exports
3
3
  *
4
- * Type-safe configuration with defaults, validation, and layered overrides.
5
- * Supports global defaults → file config → environment variables → runtime overrides.
6
- *
7
- * `ProviderConfig` is the canonical type, defined in `./provider-config.ts`
8
- * and re-exported from this module for convenience. The legacy
9
- * `format`/`apiKey` fields are gone; callers should use the structured
10
- * `authentication` and `adapter` fields.
4
+ * The canonical schema now lives in `config-schema.ts`; this module preserves
5
+ * the historical `@hilbras/sdk` and internal import paths.
11
6
  */
12
- export const DEFAULT_CONFIG = {
13
- defaultProvider: "",
14
- defaultModel: "gpt-4o",
15
- temperature: 0.7,
16
- maxTokens: 4096,
17
- stream: true,
18
- toolsEnabled: true,
19
- reasoningEnabled: false,
20
- logLevel: "none",
21
- requestTimeoutMs: 120_000,
22
- maxRetries: 3,
23
- circuitBreakerEnabled: true,
24
- circuitBreakerThreshold: 5,
25
- circuitBreakerResetMs: 60_000,
26
- promptCaching: true,
27
- workspaceDir: typeof process !== "undefined" && typeof process.cwd === "function" ? process.cwd() : "/",
28
- providers: [],
29
- allowedTools: [],
30
- deniedTools: [],
31
- };
7
+ export { DEFAULT_CONFIG } from "./config-schema.js";
@@ -0,0 +1,2 @@
1
+ import { type ConfigSource } from "../config-schema.js";
2
+ export declare function createDefaultsSource(): ConfigSource;
@@ -0,0 +1,10 @@
1
+ import { DEFAULT_CONFIG } from "../schema.js";
2
+ import { cloneConfigValue } from "../config-schema.js";
3
+ export function createDefaultsSource() {
4
+ return {
5
+ kind: "defaults",
6
+ load: () => ({
7
+ values: cloneConfigValue(DEFAULT_CONFIG),
8
+ }),
9
+ };
10
+ }
@@ -0,0 +1,4 @@
1
+ import type { ConfigSource } from "../config-schema.js";
2
+ type Env = Record<string, string | undefined>;
3
+ export declare function createEnvironmentSource(env?: Env): ConfigSource;
4
+ export {};
@@ -0,0 +1,114 @@
1
+ import { validateBaseUrl } from "../../security/url-guard.js";
2
+ const ENV_PREFIX = "HILBRAS_";
3
+ const LOG_LEVELS = new Set(["none", "error", "info", "debug"]);
4
+ function defaultEnv() {
5
+ return typeof process !== "undefined" && process.env ? process.env : {};
6
+ }
7
+ function diagnostic(source, code, path, message) {
8
+ return { code, path, message, severity: "error", source };
9
+ }
10
+ function parseNumber(env, name, diagnostics) {
11
+ const raw = env[`${ENV_PREFIX}${name}`];
12
+ if (raw === undefined || raw === "")
13
+ return undefined;
14
+ const value = Number(raw);
15
+ if (!Number.isFinite(value)) {
16
+ diagnostics.push(diagnostic("environment", "CONFIG_INVALID_NUMBER", name, `${name} must be a finite number`));
17
+ return undefined;
18
+ }
19
+ return value;
20
+ }
21
+ function parseBoolean(env, name, diagnostics) {
22
+ const raw = env[`${ENV_PREFIX}${name}`]?.toLowerCase();
23
+ if (raw === undefined || raw === "")
24
+ return undefined;
25
+ if (raw === "true" || raw === "1")
26
+ return true;
27
+ if (raw === "false" || raw === "0")
28
+ return false;
29
+ diagnostics.push(diagnostic("environment", "CONFIG_INVALID_BOOLEAN", name, `${name} must be true, false, 1, or 0`));
30
+ return undefined;
31
+ }
32
+ function inferAdapter(baseUrl) {
33
+ const lower = baseUrl.toLowerCase();
34
+ if (lower.includes("anthropic"))
35
+ return "anthropic";
36
+ if (lower.includes("googleapis") || lower.includes("generativelanguage"))
37
+ return "google-genai";
38
+ if (lower.includes("azure"))
39
+ return "azure";
40
+ if (lower.includes("groq"))
41
+ return "groq";
42
+ if (lower.includes("localhost") || lower.includes("127.0.0.1") || lower.includes("[::1]"))
43
+ return "ollama";
44
+ return "openai";
45
+ }
46
+ export function createEnvironmentSource(env = defaultEnv()) {
47
+ return {
48
+ kind: "environment",
49
+ load: () => {
50
+ const values = {};
51
+ const diagnostics = [];
52
+ const stringValue = (name) => {
53
+ const value = env[`${ENV_PREFIX}${name}`];
54
+ return value === undefined || value === "" ? undefined : value;
55
+ };
56
+ const defaultProvider = stringValue("DEFAULT_PROVIDER");
57
+ const defaultModel = stringValue("DEFAULT_MODEL");
58
+ const logLevel = stringValue("LOG_LEVEL");
59
+ if (defaultProvider !== undefined)
60
+ values.defaultProvider = defaultProvider;
61
+ if (defaultModel !== undefined)
62
+ values.defaultModel = defaultModel;
63
+ if (logLevel !== undefined) {
64
+ if (!LOG_LEVELS.has(logLevel)) {
65
+ diagnostics.push(diagnostic("environment", "CONFIG_INVALID_ENUM", "logLevel", "logLevel must be none, error, info, or debug"));
66
+ }
67
+ else {
68
+ values.logLevel = logLevel;
69
+ }
70
+ }
71
+ const numericFields = [
72
+ ["TEMPERATURE", "temperature"],
73
+ ["MAX_TOKENS", "maxTokens"],
74
+ ["TIMEOUT", "requestTimeoutMs"],
75
+ ["MAX_RETRIES", "maxRetries"],
76
+ ];
77
+ for (const [envName, configName] of numericFields) {
78
+ const value = parseNumber(env, envName, diagnostics);
79
+ if (value !== undefined)
80
+ values[configName] = value;
81
+ }
82
+ const stream = parseBoolean(env, "STREAM", diagnostics);
83
+ const promptCaching = parseBoolean(env, "PROMPT_CACHING", diagnostics);
84
+ if (stream !== undefined)
85
+ values.stream = stream;
86
+ if (promptCaching !== undefined)
87
+ values.promptCaching = promptCaching;
88
+ const providerUrl = env[`${ENV_PREFIX}PROVIDER_URL`];
89
+ const providerKey = env[`${ENV_PREFIX}PROVIDER_KEY`];
90
+ const providerName = env[`${ENV_PREFIX}PROVIDER_NAME`];
91
+ if ((providerUrl && !providerKey) || (!providerUrl && providerKey)) {
92
+ diagnostics.push(diagnostic("environment", "CONFIG_INCOMPLETE_PROVIDER", "providers", "HILBRAS_PROVIDER_URL and HILBRAS_PROVIDER_KEY must be provided together"));
93
+ }
94
+ else if (providerUrl && providerKey) {
95
+ const guard = validateBaseUrl(providerUrl, { allowInsecure: true });
96
+ if (!guard.ok) {
97
+ diagnostics.push(diagnostic("environment", "CONFIG_UNSAFE_PROVIDER_URL", "providers[0].baseUrl", `provider URL rejected by security policy: ${guard.reason}`));
98
+ }
99
+ else {
100
+ values.providers = [{
101
+ name: providerName || "default",
102
+ baseUrl: providerUrl,
103
+ authentication: { type: "bearer", apiKey: providerKey },
104
+ models: [],
105
+ adapter: inferAdapter(providerUrl),
106
+ allowInsecure: providerUrl.startsWith("http://"),
107
+ }];
108
+ values.defaultProvider = providerName || "default";
109
+ }
110
+ }
111
+ return { values, diagnostics };
112
+ },
113
+ };
114
+ }
@@ -0,0 +1,6 @@
1
+ import type { ConfigSource } from "../config-schema.js";
2
+ export interface FileSourceOptions {
3
+ path: string;
4
+ readFile(path: string): string;
5
+ }
6
+ export declare function createFileSource(options: FileSourceOptions): ConfigSource;
@@ -0,0 +1,33 @@
1
+ export function createFileSource(options) {
2
+ return {
3
+ kind: "file",
4
+ load: () => {
5
+ const diagnostics = [];
6
+ let parsed;
7
+ try {
8
+ parsed = JSON.parse(options.readFile(options.path));
9
+ }
10
+ catch {
11
+ diagnostics.push({
12
+ code: "CONFIG_FILE_INVALID_JSON",
13
+ message: "configuration file is not valid JSON",
14
+ path: "$",
15
+ severity: "error",
16
+ source: "file",
17
+ });
18
+ return { values: {}, diagnostics };
19
+ }
20
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
21
+ diagnostics.push({
22
+ code: "CONFIG_FILE_INVALID_SHAPE",
23
+ message: "configuration file must contain a JSON object",
24
+ path: "$",
25
+ severity: "error",
26
+ source: "file",
27
+ });
28
+ return { values: {}, diagnostics };
29
+ }
30
+ return { values: parsed, diagnostics };
31
+ },
32
+ };
33
+ }
@@ -0,0 +1,3 @@
1
+ import { type ConfigSource } from "../config-schema.js";
2
+ import type { SDKConfig } from "../schema.js";
3
+ export declare function createRuntimeSource(overrides?: Partial<SDKConfig>): ConfigSource;
@@ -0,0 +1,7 @@
1
+ import { cloneConfigValue } from "../config-schema.js";
2
+ export function createRuntimeSource(overrides = {}) {
3
+ return {
4
+ kind: "runtime",
5
+ load: () => ({ values: cloneConfigValue(overrides) }),
6
+ };
7
+ }
package/dist/index.d.ts CHANGED
@@ -69,6 +69,14 @@ export { cacheSystemMessage, cacheLastN, cacheAtIndex, autoCache, supportsCacheC
69
69
  export type { TokenEstimate, Tokenizer } from "./tokens/counter.js";
70
70
  export type { CacheControl, CacheableMessage } from "./tokens/prompt-cache.js";
71
71
  export { loadConfig, createConfig, validateConfig } from "./config/config.js";
72
+ export { resolveConfig } from "./config/config-resolver.js";
73
+ export { createDefaultsSource } from "./config/sources/defaults.js";
74
+ export { createEnvironmentSource } from "./config/sources/environment.js";
75
+ export { createFileSource } from "./config/sources/file.js";
76
+ export { createRuntimeSource } from "./config/sources/runtime.js";
77
+ export type { ConfigDiagnostic, ConfigResolutionOptions, ConfigSource, ConfigSourceKind, ConfigSourceResult, SafeProviderConfig, SafeSDKConfig, } from "./config/config-schema.js";
78
+ export type { ResolvedSDKConfig } from "./config/resolved-config.js";
79
+ export { budgetFromConfig, policyFromConfig } from "./config/resolved-config.js";
72
80
  export type { SDKConfig } from "./config/schema.js";
73
81
  export { DEFAULT_CONFIG } from "./config/schema.js";
74
82
  export { buildPrompt, buildToolSection, buildEnvironmentSection, buildCodingAgentPrompt } from "./config/prompts.js";
package/dist/index.js CHANGED
@@ -50,6 +50,12 @@ export { estimateTokens, estimateMessageTokens, estimateToolTokens, estimateCost
50
50
  export { cacheSystemMessage, cacheLastN, cacheAtIndex, autoCache, supportsCacheControl } from "./tokens/prompt-cache.js";
51
51
  // ─── Config ───────────────────────────────────────────────────────────────
52
52
  export { loadConfig, createConfig, validateConfig } from "./config/config.js";
53
+ export { resolveConfig } from "./config/config-resolver.js";
54
+ export { createDefaultsSource } from "./config/sources/defaults.js";
55
+ export { createEnvironmentSource } from "./config/sources/environment.js";
56
+ export { createFileSource } from "./config/sources/file.js";
57
+ export { createRuntimeSource } from "./config/sources/runtime.js";
58
+ export { budgetFromConfig, policyFromConfig } from "./config/resolved-config.js";
53
59
  export { DEFAULT_CONFIG } from "./config/schema.js";
54
60
  export { buildPrompt, buildToolSection, buildEnvironmentSection, buildCodingAgentPrompt } from "./config/prompts.js";
55
61
  // ─── Credentials ────────────────────────────────────────────────────────────
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hilbras/sdk",
3
- "version": "3.2.0",
3
+ "version": "3.3.0",
4
4
  "description": "Provider-agnostic LLM client SDK — streaming, tool calling, embeddings, image generation, speech synthesis, transcription, reranking, circuit breaker, retry, reasoning normalization, cost enforcement, structured output with schema validation, type-safe tool builder, and SSRF-safe provider registration. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -136,8 +136,8 @@
136
136
  "import": "./dist/tokens/counter.js"
137
137
  },
138
138
  "./config": {
139
- "types": "./dist/config/config.d.ts",
140
- "import": "./dist/config/config.js"
139
+ "types": "./dist/config/index.d.ts",
140
+ "import": "./dist/config/index.js"
141
141
  },
142
142
  "./transport": {
143
143
  "types": "./dist/transport/transport.d.ts",