@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.
Files changed (45) hide show
  1. package/README.md +83 -2
  2. package/dist/client/client.d.ts +39 -9
  3. package/dist/client/client.js +101 -44
  4. package/dist/config/config-resolver.d.ts +3 -0
  5. package/dist/config/config-resolver.js +187 -0
  6. package/dist/config/config-schema.d.ts +69 -0
  7. package/dist/config/config-schema.js +56 -0
  8. package/dist/config/config.d.ts +10 -17
  9. package/dist/config/config.js +37 -135
  10. package/dist/config/index.d.ts +11 -0
  11. package/dist/config/index.js +8 -0
  12. package/dist/config/resolved-config.d.ts +15 -0
  13. package/dist/config/resolved-config.js +60 -0
  14. package/dist/config/schema.d.ts +5 -59
  15. package/dist/config/schema.js +4 -28
  16. package/dist/config/sources/defaults.d.ts +2 -0
  17. package/dist/config/sources/defaults.js +10 -0
  18. package/dist/config/sources/environment.d.ts +4 -0
  19. package/dist/config/sources/environment.js +114 -0
  20. package/dist/config/sources/file.d.ts +6 -0
  21. package/dist/config/sources/file.js +33 -0
  22. package/dist/config/sources/runtime.d.ts +3 -0
  23. package/dist/config/sources/runtime.js +7 -0
  24. package/dist/features/agent/tool-loop.d.ts +9 -0
  25. package/dist/features/agent/tool-loop.js +25 -0
  26. package/dist/index.d.ts +15 -1
  27. package/dist/index.js +10 -0
  28. package/dist/middleware/middleware.d.ts +10 -0
  29. package/dist/middleware/middleware.js +15 -6
  30. package/dist/providers/registry.d.ts +9 -0
  31. package/dist/providers/registry.js +37 -0
  32. package/dist/security/authorization.d.ts +180 -0
  33. package/dist/security/authorization.js +355 -0
  34. package/dist/security/rate-limiter.d.ts +11 -0
  35. package/dist/security/rate-limiter.js +14 -0
  36. package/dist/security/rbac.d.ts +29 -41
  37. package/dist/security/rbac.js +172 -90
  38. package/dist/security/replay-guard.d.ts +51 -0
  39. package/dist/security/replay-guard.js +86 -0
  40. package/dist/security/request-signer.d.ts +88 -22
  41. package/dist/security/request-signer.js +185 -76
  42. package/dist/security/tool-policy.d.ts +53 -0
  43. package/dist/security/tool-policy.js +97 -0
  44. package/dist/transport/middleware-transport.js +9 -0
  45. package/package.json +4 -3
@@ -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;