@hilbras/sdk 2.4.0 → 3.1.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 (194) hide show
  1. package/README.md +201 -34
  2. package/dist/adapters/anthropic.d.ts +0 -1
  3. package/dist/adapters/anthropic.d.ts.map +1 -1
  4. package/dist/adapters/anthropic.js +4 -3
  5. package/dist/adapters/anthropic.js.map +1 -1
  6. package/dist/adapters/azure.d.ts +0 -1
  7. package/dist/adapters/azure.d.ts.map +1 -1
  8. package/dist/adapters/azure.js +4 -2
  9. package/dist/adapters/azure.js.map +1 -1
  10. package/dist/adapters/bedrock.d.ts +0 -1
  11. package/dist/adapters/bedrock.d.ts.map +1 -1
  12. package/dist/adapters/bedrock.js +4 -4
  13. package/dist/adapters/bedrock.js.map +1 -1
  14. package/dist/adapters/cohere.d.ts.map +1 -1
  15. package/dist/adapters/cohere.js +2 -1
  16. package/dist/adapters/cohere.js.map +1 -1
  17. package/dist/adapters/deepgram.js +4 -4
  18. package/dist/adapters/deepgram.js.map +1 -1
  19. package/dist/adapters/extra.d.ts +3 -0
  20. package/dist/adapters/extra.d.ts.map +1 -0
  21. package/dist/adapters/extra.js +35 -0
  22. package/dist/adapters/extra.js.map +1 -0
  23. package/dist/adapters/google-genai.d.ts +0 -1
  24. package/dist/adapters/google-genai.d.ts.map +1 -1
  25. package/dist/adapters/google-genai.js +2 -2
  26. package/dist/adapters/google-genai.js.map +1 -1
  27. package/dist/adapters/google-vertex.d.ts +0 -1
  28. package/dist/adapters/google-vertex.d.ts.map +1 -1
  29. package/dist/adapters/google-vertex.js +2 -2
  30. package/dist/adapters/google-vertex.js.map +1 -1
  31. package/dist/adapters/groq.d.ts +0 -1
  32. package/dist/adapters/groq.d.ts.map +1 -1
  33. package/dist/adapters/groq.js +4 -3
  34. package/dist/adapters/groq.js.map +1 -1
  35. package/dist/adapters/huggingface.d.ts +0 -1
  36. package/dist/adapters/huggingface.d.ts.map +1 -1
  37. package/dist/adapters/huggingface.js +2 -2
  38. package/dist/adapters/huggingface.js.map +1 -1
  39. package/dist/adapters/ollama.d.ts +0 -1
  40. package/dist/adapters/ollama.d.ts.map +1 -1
  41. package/dist/adapters/ollama.js +4 -3
  42. package/dist/adapters/ollama.js.map +1 -1
  43. package/dist/adapters/openai-compatible.d.ts +0 -2
  44. package/dist/adapters/openai-compatible.d.ts.map +1 -1
  45. package/dist/adapters/openai-compatible.js +4 -2
  46. package/dist/adapters/openai-compatible.js.map +1 -1
  47. package/dist/adapters/openai.d.ts +0 -1
  48. package/dist/adapters/openai.d.ts.map +1 -1
  49. package/dist/adapters/openai.js +4 -2
  50. package/dist/adapters/openai.js.map +1 -1
  51. package/dist/catalog/index.js +1 -1
  52. package/dist/catalog/index.js.map +1 -1
  53. package/dist/catalog/models.d.ts.map +1 -1
  54. package/dist/catalog/models.js +11 -8
  55. package/dist/catalog/models.js.map +1 -1
  56. package/dist/catalog/provider-catalog.d.ts +229 -0
  57. package/dist/catalog/provider-catalog.d.ts.map +1 -0
  58. package/dist/catalog/provider-catalog.js +1494 -0
  59. package/dist/catalog/provider-catalog.js.map +1 -0
  60. package/dist/client/client.d.ts +60 -1
  61. package/dist/client/client.d.ts.map +1 -1
  62. package/dist/client/client.js +260 -128
  63. package/dist/client/client.js.map +1 -1
  64. package/dist/config/config.d.ts.map +1 -1
  65. package/dist/config/config.js.map +1 -1
  66. package/dist/config/provider-config.d.ts +2 -0
  67. package/dist/config/provider-config.d.ts.map +1 -1
  68. package/dist/config/provider-config.js +12 -1
  69. package/dist/config/provider-config.js.map +1 -1
  70. package/dist/config/schema.d.ts +6 -0
  71. package/dist/config/schema.d.ts.map +1 -1
  72. package/dist/config/schema.js.map +1 -1
  73. package/dist/cost/alerts.d.ts +107 -0
  74. package/dist/cost/alerts.d.ts.map +1 -0
  75. package/dist/cost/alerts.js +163 -0
  76. package/dist/cost/alerts.js.map +1 -0
  77. package/dist/cost/tracker.d.ts.map +1 -1
  78. package/dist/cost/tracker.js +8 -8
  79. package/dist/cost/tracker.js.map +1 -1
  80. package/dist/features/eval/ab-test.d.ts +80 -0
  81. package/dist/features/eval/ab-test.d.ts.map +1 -0
  82. package/dist/features/eval/ab-test.js +102 -0
  83. package/dist/features/eval/ab-test.js.map +1 -0
  84. package/dist/features/rag/chunker.d.ts.map +1 -1
  85. package/dist/features/rag/chunker.js +6 -0
  86. package/dist/features/rag/chunker.js.map +1 -1
  87. package/dist/features/rag/in-memory-store.d.ts.map +1 -1
  88. package/dist/features/rag/in-memory-store.js +2 -0
  89. package/dist/features/rag/in-memory-store.js.map +1 -1
  90. package/dist/features/rag/pipeline.d.ts.map +1 -1
  91. package/dist/features/rag/pipeline.js +3 -6
  92. package/dist/features/rag/pipeline.js.map +1 -1
  93. package/dist/features/rag/retriever.d.ts +5 -0
  94. package/dist/features/rag/retriever.d.ts.map +1 -1
  95. package/dist/features/rag/retriever.js +22 -25
  96. package/dist/features/rag/retriever.js.map +1 -1
  97. package/dist/index.d.ts +13 -0
  98. package/dist/index.d.ts.map +1 -1
  99. package/dist/index.js +13 -0
  100. package/dist/index.js.map +1 -1
  101. package/dist/logging/logger.d.ts +4 -37
  102. package/dist/logging/logger.d.ts.map +1 -1
  103. package/dist/logging/logger.js +9 -54
  104. package/dist/logging/logger.js.map +1 -1
  105. package/dist/middleware/middleware.d.ts +1 -1
  106. package/dist/middleware/middleware.d.ts.map +1 -1
  107. package/dist/middleware/middleware.js +28 -10
  108. package/dist/middleware/middleware.js.map +1 -1
  109. package/dist/plugin/registry.d.ts +53 -0
  110. package/dist/plugin/registry.d.ts.map +1 -0
  111. package/dist/plugin/registry.js +111 -0
  112. package/dist/plugin/registry.js.map +1 -0
  113. package/dist/plugin/types.d.ts +120 -0
  114. package/dist/plugin/types.d.ts.map +1 -0
  115. package/dist/plugin/types.js +9 -0
  116. package/dist/plugin/types.js.map +1 -0
  117. package/dist/providers/registry.d.ts.map +1 -1
  118. package/dist/providers/registry.js +9 -7
  119. package/dist/providers/registry.js.map +1 -1
  120. package/dist/reliability/circuit-breaker.d.ts.map +1 -1
  121. package/dist/reliability/circuit-breaker.js +5 -1
  122. package/dist/reliability/circuit-breaker.js.map +1 -1
  123. package/dist/security/audit-logger.d.ts +2 -0
  124. package/dist/security/audit-logger.d.ts.map +1 -1
  125. package/dist/security/audit-logger.js +39 -23
  126. package/dist/security/audit-logger.js.map +1 -1
  127. package/dist/security/pii-guard.d.ts.map +1 -1
  128. package/dist/security/pii-guard.js +21 -5
  129. package/dist/security/pii-guard.js.map +1 -1
  130. package/dist/security/prompt-injection-guard.d.ts.map +1 -1
  131. package/dist/security/prompt-injection-guard.js +22 -4
  132. package/dist/security/prompt-injection-guard.js.map +1 -1
  133. package/dist/security/rbac.d.ts +81 -0
  134. package/dist/security/rbac.d.ts.map +1 -0
  135. package/dist/security/rbac.js +139 -0
  136. package/dist/security/rbac.js.map +1 -0
  137. package/dist/security/url-guard.d.ts.map +1 -1
  138. package/dist/security/url-guard.js +110 -27
  139. package/dist/security/url-guard.js.map +1 -1
  140. package/dist/telemetry/body-logger.d.ts.map +1 -1
  141. package/dist/telemetry/body-logger.js +18 -9
  142. package/dist/telemetry/body-logger.js.map +1 -1
  143. package/dist/telemetry/sla.d.ts +100 -0
  144. package/dist/telemetry/sla.d.ts.map +1 -0
  145. package/dist/telemetry/sla.js +178 -0
  146. package/dist/telemetry/sla.js.map +1 -0
  147. package/dist/telemetry/structured-logger.d.ts.map +1 -1
  148. package/dist/telemetry/structured-logger.js +20 -7
  149. package/dist/telemetry/structured-logger.js.map +1 -1
  150. package/dist/tokens/counter.d.ts +12 -2
  151. package/dist/tokens/counter.d.ts.map +1 -1
  152. package/dist/tokens/counter.js +12 -2
  153. package/dist/tokens/counter.js.map +1 -1
  154. package/dist/transport/fetch.d.ts.map +1 -1
  155. package/dist/transport/fetch.js +48 -16
  156. package/dist/transport/fetch.js.map +1 -1
  157. package/dist/transport/middleware-transport.d.ts +31 -0
  158. package/dist/transport/middleware-transport.d.ts.map +1 -0
  159. package/dist/transport/middleware-transport.js +57 -0
  160. package/dist/transport/middleware-transport.js.map +1 -0
  161. package/dist/types/streams.d.ts +10 -0
  162. package/dist/types/streams.d.ts.map +1 -1
  163. package/dist/types/streams.js +10 -0
  164. package/dist/types/streams.js.map +1 -1
  165. package/dist/types/tool-builder.d.ts +3 -1
  166. package/dist/types/tool-builder.d.ts.map +1 -1
  167. package/dist/types/tool-builder.js +3 -1
  168. package/dist/types/tool-builder.js.map +1 -1
  169. package/dist/types/tools.d.ts +0 -2
  170. package/dist/types/tools.d.ts.map +1 -1
  171. package/dist/types/tools.js +1 -11
  172. package/dist/types/tools.js.map +1 -1
  173. package/package.json +125 -108
  174. package/dist/catalog/provider-catalog.json +0 -246
  175. package/dist/client/pipeline.d.ts +0 -134
  176. package/dist/client/pipeline.d.ts.map +0 -1
  177. package/dist/client/pipeline.js +0 -222
  178. package/dist/client/pipeline.js.map +0 -1
  179. package/dist/features/memory/index.d.ts +0 -3
  180. package/dist/features/memory/index.d.ts.map +0 -1
  181. package/dist/features/memory/index.js +0 -2
  182. package/dist/features/memory/index.js.map +0 -1
  183. package/dist/features/memory/memory.d.ts +0 -46
  184. package/dist/features/memory/memory.d.ts.map +0 -1
  185. package/dist/features/memory/memory.js +0 -152
  186. package/dist/features/memory/memory.js.map +0 -1
  187. package/dist/security/index.d.ts +0 -16
  188. package/dist/security/index.d.ts.map +0 -1
  189. package/dist/security/index.js +0 -10
  190. package/dist/security/index.js.map +0 -1
  191. package/dist/telemetry/index.d.ts +0 -15
  192. package/dist/telemetry/index.d.ts.map +0 -1
  193. package/dist/telemetry/index.js +0 -11
  194. package/dist/telemetry/index.js.map +0 -1
@@ -10,7 +10,9 @@
10
10
  * for await (const chunk of client.stream({ provider: "OpenAI", model: "gpt-4", messages })) { ... }
11
11
  */
12
12
  import { ProviderRegistry } from "../providers/registry.js";
13
+ import { cloneProviderConfig } from "../config/provider-config.js";
13
14
  import { FetchTransport } from "../transport/fetch.js";
15
+ import { MiddlewareTransport } from "../transport/middleware-transport.js";
14
16
  import { getCircuitBreakerRegistry } from "../reliability/circuit-breaker.js";
15
17
  import { createRetryConfig, shouldRetry, shouldRetryNetworkError } from "../reliability/retry.js";
16
18
  import { calculateBackoff, sleep } from "../reliability/backoff.js";
@@ -25,7 +27,8 @@ import { buildJsonSystemInstruction, buildRepairPrompt, extractJson, buildJsonMo
25
27
  import { ClientHooks } from "./hooks.js";
26
28
  import { BudgetTracker } from "../cost/tracker.js";
27
29
  import { estimateTokens } from "../tokens/counter.js";
28
- import { getProviderCatalog, getModelsForProvider } from "../catalog/index.js";
30
+ import { getProviderCatalog, getModelsForProvider, listProviders } from "../catalog/index.js";
31
+ import { PluginRegistry } from "../plugin/registry.js";
29
32
  export class HilbrasClient {
30
33
  _registry = new ProviderRegistry();
31
34
  _transport;
@@ -38,12 +41,19 @@ export class HilbrasClient {
38
41
  _budgetTracker;
39
42
  _allowInsecureUrls;
40
43
  _allowPrivateNetwork;
44
+ _tokenizer;
45
+ _plugins = new PluginRegistry();
41
46
  constructor(config) {
42
47
  this._transport = config?.transport ?? new FetchTransport();
48
+ // v2.5.0: Wrap transport with middleware pipeline when provided
49
+ if (config?.middleware) {
50
+ this._transport = new MiddlewareTransport(this._transport, config.middleware);
51
+ }
43
52
  this._adapterRegistry = config?.adapterRegistry ?? getDefaultAdapterRegistry();
44
53
  this._router = new ModelRouter();
45
54
  this._allowInsecureUrls = config?.allowInsecureUrls ?? false;
46
55
  this._allowPrivateNetwork = config?.allowPrivateNetwork ?? false;
56
+ this._tokenizer = config?.tokenizer ?? null;
47
57
  // v0.10.0 PR-5: derive policy + budget from sdkConfig when not
48
58
  // explicitly provided. Precedence: explicit > sdkConfig > defaults.
49
59
  const sdk = config?.sdkConfig;
@@ -110,28 +120,62 @@ export class HilbrasClient {
110
120
  removeAllListeners(event) {
111
121
  this._hooks.removeAll(event);
112
122
  }
123
+ // ─── Plugin System ──────────────────────────────────────────────────────
124
+ /**
125
+ * Register one or more plugins with the client. Plugins receive lifecycle
126
+ * hooks that fire around every LLM request.
127
+ *
128
+ * @example
129
+ * ```ts
130
+ * client.use({
131
+ * name: "logger",
132
+ * onRequest(ctx) { console.log(`[${ctx.requestId}] → ${ctx.provider}/${ctx.model}`); },
133
+ * onResponse(ctx) { console.log(`[${ctx.requestId}] ✓ ${ctx.durationMs}ms`); },
134
+ * onError(ctx) { console.error(`[${ctx.requestId}] ✗ ${ctx.error.message}`); },
135
+ * });
136
+ * ```
137
+ */
138
+ async use(...plugins) {
139
+ await this._plugins.add(...plugins);
140
+ for (const plugin of plugins)
141
+ await this._plugins.setup(plugin, this);
142
+ }
113
143
  _nextRequestId() {
114
144
  return `req_${++this._requestCounter}`;
115
145
  }
146
+ /**
147
+ * Client-scoped token estimation. Uses the per-client tokenizer when set,
148
+ * otherwise falls back to the global `estimateTokens()`.
149
+ *
150
+ * BUG-04 fix: This prevents multiple clients from fighting over the global
151
+ * `setTokenizer()` singleton.
152
+ */
153
+ _estimateTokens(text) {
154
+ if (this._tokenizer)
155
+ return this._tokenizer.count(text);
156
+ return estimateTokens(text);
157
+ }
116
158
  _emit(event) {
117
159
  this._hooks.emit(event);
118
160
  }
119
161
  // ─── Provider Management ────────────────────────────────────────────────
120
162
  addProvider(config) {
163
+ const ownedConfig = cloneProviderConfig(config);
121
164
  // v0.9.3: SSRF guard. Per-provider `allowInsecure` overrides client-wide
122
- // `allowInsecureUrls`. Loopback is always allowed when either is on.
123
- const guard = validateBaseUrl(config.baseUrl, {
124
- allowInsecure: config.allowInsecure ?? this._allowInsecureUrls,
165
+ // `allowInsecureUrls`; local targets require explicit opt-in.
166
+ const guard = validateBaseUrl(ownedConfig.baseUrl, {
167
+ allowInsecure: ownedConfig.allowInsecure ?? this._allowInsecureUrls,
125
168
  allowPrivateNetwork: this._allowPrivateNetwork,
126
169
  });
127
170
  if (!guard.ok) {
128
- throw new ConfigurationError(`Refused to register provider '${config.name}': ${guard.reason}`);
171
+ throw new ConfigurationError(`Refused to register provider '${ownedConfig.name}': ${guard.reason}`);
129
172
  }
130
- this._registry.add(config);
131
- this._adapters.set(config.name, this._adapterRegistry.create(config.adapter, {
132
- provider: config,
173
+ const adapter = this._adapterRegistry.create(ownedConfig.adapter, {
174
+ provider: ownedConfig,
133
175
  transport: this._transport,
134
- }));
176
+ });
177
+ this._registry.add(ownedConfig);
178
+ this._adapters.set(ownedConfig.name, adapter);
135
179
  this._router.updateProviders(this._registry.list().map((p) => p.name));
136
180
  }
137
181
  removeProvider(name) {
@@ -154,10 +198,11 @@ export class HilbrasClient {
154
198
  * ```
155
199
  */
156
200
  addProviderFromCatalog(providerId, modelId, apiKey) {
157
- const provider = getProviderCatalog(providerId);
201
+ const catalogProviderId = listProviders().find((id) => id.toLowerCase() === providerId.toLowerCase()) ?? providerId;
202
+ const provider = getProviderCatalog(catalogProviderId);
158
203
  if (!provider)
159
204
  throw new ConfigurationError(`Unknown provider: ${providerId}`, `Available catalog providers: openai, anthropic, google-vertex, google-genai, groq, mistral, deepseek, cohere, huggingface, ollama, bedrock, azure, elevenlabs, voyageai`);
160
- const models = getModelsForProvider(providerId);
205
+ const models = getModelsForProvider(catalogProviderId);
161
206
  const model = models.find((m) => m.id === modelId);
162
207
  if (!model)
163
208
  throw new ConfigurationError(`Model ${modelId} not found for provider ${providerId}`, `Available models for ${providerId}: ${models.map((m) => m.id).join(", ")}`);
@@ -172,10 +217,11 @@ export class HilbrasClient {
172
217
  id: model.id,
173
218
  contextWindow: model.contextWindow,
174
219
  maxOutputTokens: model.maxOutput,
175
- capabilities: this._parseCapabilities(model.capabilities, providerId),
220
+ capabilities: this._parseCapabilities(model.capabilities, catalogProviderId),
176
221
  },
177
222
  ],
178
223
  });
224
+ return provider.name;
179
225
  }
180
226
  /** Access the adapter registry for plugins */
181
227
  get adapterRegistry() {
@@ -358,10 +404,20 @@ export class HilbrasClient {
358
404
  // setup into _prepareRequest so stream() and complete() share it.
359
405
  const { resolved, circuitBreaker, retryConfig, signal } = this._prepareRequest(requestId, providerName, providerConfig, params.policy, params.signal);
360
406
  const messages = this._normalizeMessages(params.messages);
407
+ // v3.0.0: Plugin onRequest hook
408
+ await this._plugins.fireRequest({
409
+ requestId,
410
+ provider: providerName,
411
+ model: modelId,
412
+ messages,
413
+ extra: params.extra,
414
+ signal: params.signal,
415
+ timestamp: startTime,
416
+ });
361
417
  // Atomic budget reservation before any provider call. Reserves the
362
418
  // estimated cost for the entire retry+fallback chain; the reservation is
363
419
  // converted to actual on the first usage chunk, or released on failure.
364
- estimatedCost = this._budgetTracker.estimate(modelId, providerName, estimateTokens(messages.map((m) => m.content ?? "").join("")), 0);
420
+ estimatedCost = this._budgetTracker.estimate(modelId, providerName, this._estimateTokens(messages.map((m) => m.content ?? "").join("")), 0);
365
421
  const initialReservation = this._budgetTracker.reserve(requestId, estimatedCost);
366
422
  if (!initialReservation) {
367
423
  throw new ConfigurationError(`Budget reservation rejected — estimated cost $${estimatedCost.toFixed(4)} would exceed budget`, `Remaining budget: $${this._budgetTracker.report().remainingBudget?.toFixed(4) ?? "unknown"}. Options: (1) increase sessionBudget, (2) use a cheaper model, (3) reduce input token count`);
@@ -408,9 +464,21 @@ export class HilbrasClient {
408
464
  reservationActive = false;
409
465
  }
410
466
  this._emit({ type: "request.completed", requestId, timestamp: performance.now(), provider: providerName, model: modelId, durationMs: performance.now() - startTime, attempts: attempt + 1, inputTokens, outputTokens, structuredOutput: false });
467
+ // v3.0.0: Plugin onResponse hook
468
+ await this._plugins.fireResponse({ requestId, provider: providerName, model: modelId, durationMs: performance.now() - startTime, inputTokens, outputTokens, streaming: true });
411
469
  return;
412
470
  }
413
471
  catch (err) {
472
+ // Once a chunk has escaped to the caller, retrying would duplicate
473
+ // output and potentially repeat tool side effects. Caller cancellation
474
+ // is terminal as well.
475
+ const callerAborted = params.signal?.aborted === true;
476
+ if (callerAborted || firstChunkEmitted) {
477
+ circuitBreaker?.recordFailure(err instanceof Error ? err : undefined);
478
+ this._emit({ type: "request.failed", requestId, timestamp: performance.now(), provider: providerName, model: modelId, durationMs: performance.now() - startTime, attempts: attempt + 1, error: err instanceof Error ? err.message : String(err) });
479
+ await this._plugins.fireError({ requestId, provider: providerName, model: modelId, error: err instanceof Error ? err : new Error(String(err)), durationMs: performance.now() - startTime, attempts: attempt + 1 });
480
+ throw err;
481
+ }
414
482
  // Check if we should retry
415
483
  const isNetworkError = err instanceof TypeError || (err instanceof Error && err.name === "AbortError");
416
484
  const status = err.status;
@@ -438,7 +506,7 @@ export class HilbrasClient {
438
506
  reservationActive = false;
439
507
  }
440
508
  const fbReservationId = `${requestId}_fb_${fb.model}`;
441
- const fbEstimatedCost = this._budgetTracker.estimate(fb.model, fb.provider, estimateTokens(messages.map((m) => m.content ?? "").join("")), 0);
509
+ const fbEstimatedCost = this._budgetTracker.estimate(fb.model, fb.provider, this._estimateTokens(messages.map((m) => m.content ?? "").join("")), 0);
442
510
  const fbReservation = this._budgetTracker.reserve(fbReservationId, fbEstimatedCost);
443
511
  if (!fbReservation)
444
512
  continue; // budget exceeded for this fallback
@@ -480,6 +548,8 @@ export class HilbrasClient {
480
548
  }
481
549
  circuitBreaker?.recordFailure(err instanceof Error ? err : undefined);
482
550
  this._emit({ type: "request.failed", requestId, timestamp: performance.now(), provider: providerName, model: modelId, durationMs: performance.now() - startTime, attempts: attempt + 1, error: err instanceof Error ? err.message : String(err) });
551
+ // v3.0.0: Plugin onError hook
552
+ await this._plugins.fireError({ requestId, provider: providerName, model: modelId, error: err instanceof Error ? err : new Error(String(err)), durationMs: performance.now() - startTime, attempts: attempt + 1 });
483
553
  throw err;
484
554
  }
485
555
  }
@@ -503,8 +573,9 @@ export class HilbrasClient {
503
573
  const resolved_ = this._resolveProviderModel({ ...params, hasOutput: !!params.output });
504
574
  const providerConfig = this._registry.getOrThrow(resolved_.providerName);
505
575
  const model = providerConfig.models.find((m) => m.id === resolved_.modelId);
506
- if (!model)
576
+ if (!model && providerConfig.models.length > 0) {
507
577
  throw new ModelNotFoundError(resolved_.modelId, resolved_.providerName, providerConfig.models.map((m) => m.id));
578
+ }
508
579
  const providerName = resolved_.providerName;
509
580
  const modelId = resolved_.modelId;
510
581
  this._emit({ type: "routing.resolved", requestId, timestamp: performance.now(), provider: providerName, model: modelId, score: 0, reasons: params.provider ? ["Explicit provider/model"] : ["Router selected"] });
@@ -513,6 +584,16 @@ export class HilbrasClient {
513
584
  // setup into _prepareRequest so stream() and complete() share it.
514
585
  const { resolved, circuitBreaker, retryConfig, signal } = this._prepareRequest(requestId, providerName, providerConfig, params.policy, params.signal);
515
586
  const messages = this._normalizeMessages(params.messages);
587
+ // v3.0.0: Plugin onRequest hook
588
+ await this._plugins.fireRequest({
589
+ requestId,
590
+ provider: providerName,
591
+ model: modelId,
592
+ messages,
593
+ extra: params.extra,
594
+ signal: params.signal,
595
+ timestamp: startTime,
596
+ });
516
597
  // Structured output setup
517
598
  const outputConfig = params.output;
518
599
  let structuredMessages = [...messages];
@@ -529,114 +610,133 @@ export class HilbrasClient {
529
610
  }
530
611
  const maxRepairAttempts = outputConfig?.maxRepairAttempts ?? 2;
531
612
  // Budget: atomic reserve before execution
532
- const estimatedCost = this._budgetTracker.estimate(modelId, providerName, estimateTokens(messages.map((m) => m.content ?? "").join("")), 0);
613
+ const estimatedCost = this._budgetTracker.estimate(modelId, providerName, this._estimateTokens(messages.map((m) => m.content ?? "").join("")), 0);
533
614
  const reservation = this._budgetTracker.reserve(requestId, estimatedCost);
534
615
  if (!reservation) {
535
616
  throw new ConfigurationError(`Budget reservation rejected — estimated cost $${estimatedCost.toFixed(4)} would exceed budget`, `Remaining budget: $${this._budgetTracker.report().remainingBudget?.toFixed(4) ?? "unknown"}. Options: (1) increase sessionBudget, (2) use a cheaper model, (3) reduce input token count`);
536
617
  }
537
- for (let attempt = 0;; attempt++) {
538
- try {
539
- const result = await adapter.complete({
540
- model: modelId,
541
- messages: structuredMessages,
542
- temperature: params.temperature,
543
- maxTokens: params.maxTokens,
544
- tools: params.tools,
545
- extra: structuredExtra,
546
- signal,
547
- });
548
- circuitBreaker?.recordSuccess();
549
- // If no structured output, settle and return
550
- if (!outputConfig) {
551
- this._budgetTracker.settle(requestId, estimatedCost, { provider: providerName, model: modelId, phase: "execute" });
552
- this._emit({ type: "request.completed", requestId, timestamp: performance.now(), provider: providerName, model: modelId, durationMs: performance.now() - startTime, attempts: attempt + 1, structuredOutput: false });
553
- return result;
554
- }
555
- // Validate structured output
556
- const json = extractJson(result);
557
- const parsed = JSON.parse(json);
558
- const validation = outputConfig.schema.safeParse(parsed);
559
- if (validation.success) {
560
- this._budgetTracker.settle(requestId, estimatedCost, { provider: providerName, model: modelId, phase: "execute" });
561
- this._emit({ type: "structured.validate.pass", requestId, timestamp: performance.now() });
562
- this._emit({ type: "request.completed", requestId, timestamp: performance.now(), provider: providerName, model: modelId, durationMs: performance.now() - startTime, attempts: attempt + 1, structuredOutput: true });
563
- return validation.data;
564
- }
565
- // Validation failed — attempt repair
566
- this._emit({ type: "structured.validate.fail", requestId, timestamp: performance.now(), attempt, error: validation.error instanceof Error ? validation.error.message : String(validation.error) });
567
- if (attempt < maxRepairAttempts) {
568
- const repairPrompt = buildRepairPrompt(validation.error, result, buildJsonSystemInstruction(outputConfig.schema), outputConfig.repairInstructions);
569
- // Replace last user message with repair prompt
570
- const lastUserIdx = structuredMessages.map((m) => m.role).lastIndexOf("user");
571
- if (lastUserIdx >= 0) {
572
- structuredMessages = [
573
- ...structuredMessages.slice(0, lastUserIdx),
574
- { role: "user", content: repairPrompt },
575
- ];
618
+ try {
619
+ for (let attempt = 0;; attempt++) {
620
+ try {
621
+ const result = await adapter.complete({
622
+ model: modelId,
623
+ messages: structuredMessages,
624
+ temperature: params.temperature,
625
+ maxTokens: params.maxTokens,
626
+ tools: params.tools,
627
+ extra: structuredExtra,
628
+ signal,
629
+ });
630
+ circuitBreaker?.recordSuccess();
631
+ // If no structured output, settle and return
632
+ if (!outputConfig) {
633
+ this._budgetTracker.settle(requestId, estimatedCost, { provider: providerName, model: modelId, phase: "execute" });
634
+ this._emit({ type: "request.completed", requestId, timestamp: performance.now(), provider: providerName, model: modelId, durationMs: performance.now() - startTime, attempts: attempt + 1, structuredOutput: false });
635
+ // v3.0.0: Plugin onResponse hook
636
+ await this._plugins.fireResponse({ requestId, provider: providerName, model: modelId, durationMs: performance.now() - startTime, streaming: false });
637
+ return result;
576
638
  }
577
- else {
578
- structuredMessages = [...structuredMessages, { role: "user", content: repairPrompt }];
639
+ // Validate structured output
640
+ const json = extractJson(result);
641
+ const parsed = JSON.parse(json);
642
+ const validation = outputConfig.schema.safeParse(parsed);
643
+ if (validation.success) {
644
+ this._budgetTracker.settle(requestId, estimatedCost, { provider: providerName, model: modelId, phase: "execute" });
645
+ this._emit({ type: "structured.validate.pass", requestId, timestamp: performance.now() });
646
+ this._emit({ type: "request.completed", requestId, timestamp: performance.now(), provider: providerName, model: modelId, durationMs: performance.now() - startTime, attempts: attempt + 1, structuredOutput: true });
647
+ // v3.0.0: Plugin onResponse hook
648
+ await this._plugins.fireResponse({ requestId, provider: providerName, model: modelId, durationMs: performance.now() - startTime, streaming: false });
649
+ return validation.data;
579
650
  }
580
- continue;
581
- }
582
- // Exhausted repair attempts
583
- this._emit({ type: "request.failed", requestId, timestamp: performance.now(), provider: providerName, model: modelId, durationMs: performance.now() - startTime, attempts: attempt + 1, error: "Validation failed after repair attempts" });
584
- throw new ValidationError(maxRepairAttempts + 1, validation.error, result, { requestId, model: modelId });
585
- }
586
- catch (err) {
587
- // Don't retry validation errors through the retry loop
588
- if (err instanceof ValidationError) {
589
- throw err;
590
- }
591
- const isNetworkError = err instanceof TypeError || (err instanceof Error && err.name === "AbortError");
592
- const status = err.status;
593
- if (isNetworkError && shouldRetryNetworkError(attempt, retryConfig)) {
594
- const delay = calculateBackoff(attempt, resolved.backoff);
595
- this._emit({ type: "request.retrying", requestId, timestamp: performance.now(), provider: providerName, attempt, delayMs: delay, reason: "network error" });
596
- await sleep(delay);
597
- continue;
598
- }
599
- if (typeof status === "number" && shouldRetry(status, attempt, retryConfig)) {
600
- const delay = calculateBackoff(attempt, resolved.backoff);
601
- this._emit({ type: "request.retrying", requestId, timestamp: performance.now(), provider: providerName, attempt, delayMs: delay, reason: `HTTP ${status}` });
602
- await sleep(delay);
603
- continue;
604
- }
605
- // Try fallback if allowed and retries exhausted
606
- if (resolved.allowFallback && attempt >= retryConfig.maxRetries && !(err instanceof ValidationError)) {
607
- this._budgetTracker.release(requestId); // Release original reservation
608
- const fallbacks = this._getFallbacks([modelId], params);
609
- for (const fb of fallbacks) {
610
- const fbEstimatedCost = this._budgetTracker.estimate(fb.model, fb.provider, 0, 0);
611
- const fbReservation = this._budgetTracker.reserve(`${requestId}_fb_${fb.model}`, fbEstimatedCost);
612
- if (!fbReservation)
613
- continue; // Budget exceeded — skip this fallback
614
- try {
615
- const fbAdapter = this._getAdapter(fb.provider);
616
- const result = await fbAdapter.complete({ model: fb.model, messages: structuredMessages, temperature: params.temperature, maxTokens: params.maxTokens, tools: params.tools, extra: structuredExtra, signal });
617
- this._budgetTracker.settle(`${requestId}_fb_${fb.model}`, fbEstimatedCost, { provider: fb.provider, model: fb.model, phase: "fallback" });
618
- this._emit({ type: "request.completed", requestId, timestamp: performance.now(), provider: fb.provider, model: fb.model, durationMs: performance.now() - startTime, attempts: attempt + 2, structuredOutput: !!outputConfig });
619
- if (!outputConfig)
620
- return result;
621
- const json = extractJson(result);
622
- const parsed = JSON.parse(json);
623
- const validation = outputConfig.schema.safeParse(parsed);
624
- if (validation.success)
625
- return validation.data;
626
- throw new ValidationError(maxRepairAttempts + 1, validation.error, result, { requestId, model: fb.model });
651
+ // Validation failed — attempt repair
652
+ this._emit({ type: "structured.validate.fail", requestId, timestamp: performance.now(), attempt, error: validation.error instanceof Error ? validation.error.message : String(validation.error) });
653
+ if (attempt < maxRepairAttempts) {
654
+ const repairPrompt = buildRepairPrompt(validation.error, result, buildJsonSystemInstruction(outputConfig.schema), outputConfig.repairInstructions);
655
+ // Replace last user message with repair prompt
656
+ const lastUserIdx = structuredMessages.map((m) => m.role).lastIndexOf("user");
657
+ if (lastUserIdx >= 0) {
658
+ structuredMessages = [
659
+ ...structuredMessages.slice(0, lastUserIdx),
660
+ { role: "user", content: repairPrompt },
661
+ ];
627
662
  }
628
- catch {
629
- this._budgetTracker.release(`${requestId}_fb_${fb.model}`);
663
+ else {
664
+ structuredMessages = [...structuredMessages, { role: "user", content: repairPrompt }];
630
665
  }
666
+ continue;
631
667
  }
668
+ // Exhausted repair attempts
669
+ this._emit({ type: "request.failed", requestId, timestamp: performance.now(), provider: providerName, model: modelId, durationMs: performance.now() - startTime, attempts: attempt + 1, error: "Validation failed after repair attempts" });
670
+ throw new ValidationError(maxRepairAttempts + 1, validation.error, result, { requestId, model: modelId });
671
+ }
672
+ catch (err) {
673
+ // Don't retry validation errors through the retry loop
674
+ if (err instanceof ValidationError) {
675
+ throw err;
676
+ }
677
+ if (params.signal?.aborted) {
678
+ circuitBreaker?.recordFailure(err instanceof Error ? err : undefined);
679
+ this._emit({ type: "request.failed", requestId, timestamp: performance.now(), provider: providerName, model: modelId, durationMs: performance.now() - startTime, attempts: attempt + 1, error: err instanceof Error ? err.message : String(err) });
680
+ await this._plugins.fireError({ requestId, provider: providerName, model: modelId, error: err instanceof Error ? err : new Error(String(err)), durationMs: performance.now() - startTime, attempts: attempt + 1 });
681
+ throw err;
682
+ }
683
+ const isNetworkError = err instanceof TypeError || (err instanceof Error && err.name === "AbortError");
684
+ const status = err.status;
685
+ if (isNetworkError && shouldRetryNetworkError(attempt, retryConfig)) {
686
+ const delay = calculateBackoff(attempt, resolved.backoff);
687
+ this._emit({ type: "request.retrying", requestId, timestamp: performance.now(), provider: providerName, attempt, delayMs: delay, reason: "network error" });
688
+ await sleep(delay);
689
+ continue;
690
+ }
691
+ if (typeof status === "number" && shouldRetry(status, attempt, retryConfig)) {
692
+ const delay = calculateBackoff(attempt, resolved.backoff);
693
+ this._emit({ type: "request.retrying", requestId, timestamp: performance.now(), provider: providerName, attempt, delayMs: delay, reason: `HTTP ${status}` });
694
+ await sleep(delay);
695
+ continue;
696
+ }
697
+ // Try fallback if allowed and retries exhausted
698
+ if (resolved.allowFallback && attempt >= retryConfig.maxRetries && !(err instanceof ValidationError)) {
699
+ this._budgetTracker.release(requestId); // Release original reservation
700
+ const fallbacks = this._getFallbacks([modelId], params);
701
+ for (const fb of fallbacks) {
702
+ const fbEstimatedCost = this._budgetTracker.estimate(fb.model, fb.provider, this._estimateTokens(messages.map((m) => m.content ?? "").join("")), 0);
703
+ const fbReservation = this._budgetTracker.reserve(`${requestId}_fb_${fb.model}`, fbEstimatedCost);
704
+ if (!fbReservation)
705
+ continue; // Budget exceeded — skip this fallback
706
+ try {
707
+ const fbAdapter = this._getAdapter(fb.provider);
708
+ const result = await fbAdapter.complete({ model: fb.model, messages: structuredMessages, temperature: params.temperature, maxTokens: params.maxTokens, tools: params.tools, extra: structuredExtra, signal });
709
+ this._budgetTracker.settle(`${requestId}_fb_${fb.model}`, fbEstimatedCost, { provider: fb.provider, model: fb.model, phase: "fallback" });
710
+ this._emit({ type: "request.completed", requestId, timestamp: performance.now(), provider: fb.provider, model: fb.model, durationMs: performance.now() - startTime, attempts: attempt + 2, structuredOutput: !!outputConfig });
711
+ if (!outputConfig)
712
+ return result;
713
+ const json = extractJson(result);
714
+ const parsed = JSON.parse(json);
715
+ const validation = outputConfig.schema.safeParse(parsed);
716
+ if (validation.success)
717
+ return validation.data;
718
+ throw new ValidationError(maxRepairAttempts + 1, validation.error, result, { requestId, model: fb.model });
719
+ }
720
+ catch {
721
+ this._budgetTracker.release(`${requestId}_fb_${fb.model}`);
722
+ }
723
+ }
724
+ }
725
+ // Release reservation on final failure
726
+ this._budgetTracker.release(requestId);
727
+ circuitBreaker?.recordFailure(err instanceof Error ? err : undefined);
728
+ this._emit({ type: "request.failed", requestId, timestamp: performance.now(), provider: providerName, model: modelId, durationMs: performance.now() - startTime, attempts: attempt + 1, error: err instanceof Error ? err.message : String(err) });
729
+ // v3.0.0: Plugin onError hook
730
+ await this._plugins.fireError({ requestId, provider: providerName, model: modelId, error: err instanceof Error ? err : new Error(String(err)), durationMs: performance.now() - startTime, attempts: attempt + 1 });
731
+ throw err;
632
732
  }
633
- // Release reservation on final failure
634
- this._budgetTracker.release(requestId);
635
- circuitBreaker?.recordFailure(err instanceof Error ? err : undefined);
636
- this._emit({ type: "request.failed", requestId, timestamp: performance.now(), provider: providerName, model: modelId, durationMs: performance.now() - startTime, attempts: attempt + 1, error: err instanceof Error ? err.message : String(err) });
637
- throw err;
638
733
  }
639
734
  }
735
+ finally {
736
+ // Validation failures and every other terminal path must not strand an
737
+ // active reservation. Settled reservations are unaffected.
738
+ this._budgetTracker.release(requestId);
739
+ }
640
740
  }
641
741
  // ─── Multi-Modal Reliability Pipeline ──────────────────────────────────
642
742
  /**
@@ -750,6 +850,7 @@ export class HilbrasClient {
750
850
  async *streamText(params) {
751
851
  const maxSteps = params.maxSteps ?? 1;
752
852
  const messages = this._normalizeMessages(params.messages);
853
+ const allowedToolNames = new Set((params.tools ?? []).map((tool) => tool.function.name));
753
854
  let currentMessages = [...messages];
754
855
  for (let step = 0; step < maxSteps; step++) {
755
856
  let stepText = "";
@@ -783,21 +884,35 @@ export class HilbrasClient {
783
884
  // Only finalize when done=true, or if done field is absent (backwards compat: treat as complete)
784
885
  if (chunk.done === true || chunk.done === undefined) {
785
886
  let parsedArgs;
887
+ let argumentError;
786
888
  try {
787
- parsedArgs = JSON.parse(pending.arguments || "{}");
889
+ const parsed = JSON.parse(pending.arguments || "{}");
890
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
891
+ throw new Error("Tool arguments must be an object");
892
+ }
893
+ parsedArgs = parsed;
894
+ }
895
+ catch (err) {
896
+ argumentError = err instanceof Error ? err.message : String(err);
897
+ parsedArgs = {};
788
898
  }
789
- catch {
790
- parsedArgs = { raw: pending.arguments };
899
+ const toolCall = { name: pending.name, args: parsedArgs, result: undefined };
900
+ stepToolCalls.push(toolCall);
901
+ if (argumentError) {
902
+ toolCall.result = { error: argumentError };
903
+ yield { type: "error", message: `Invalid arguments for tool ${pending.name}: ${argumentError}`, retryable: false };
791
904
  }
792
- stepToolCalls.push({ name: pending.name, args: parsedArgs, result: undefined });
793
- // Execute tool if handler provided
794
- if (params.toolExecution) {
905
+ else if (!allowedToolNames.has(pending.name)) {
906
+ const message = `Tool ${pending.name} is not in the configured allowlist`;
907
+ toolCall.result = { error: message };
908
+ yield { type: "error", message, retryable: false };
909
+ }
910
+ else if (params.toolExecution) {
795
911
  try {
796
- const result = await params.toolExecution(pending.name, parsedArgs);
797
- stepToolCalls[stepToolCalls.length - 1].result = result;
912
+ toolCall.result = await params.toolExecution(pending.name, parsedArgs);
798
913
  }
799
914
  catch (err) {
800
- stepToolCalls[stepToolCalls.length - 1].result = { error: err.message };
915
+ toolCall.result = { error: err.message };
801
916
  }
802
917
  }
803
918
  pendingToolCalls.delete(idx);
@@ -813,20 +928,35 @@ export class HilbrasClient {
813
928
  // Flush any remaining pending tool calls (stream ended without done=true)
814
929
  for (const [, tc] of pendingToolCalls) {
815
930
  let parsedArgs;
931
+ let argumentError;
816
932
  try {
817
- parsedArgs = JSON.parse(tc.arguments || "{}");
933
+ const parsed = JSON.parse(tc.arguments || "{}");
934
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
935
+ throw new Error("Tool arguments must be an object");
936
+ }
937
+ parsedArgs = parsed;
818
938
  }
819
- catch {
820
- parsedArgs = { raw: tc.arguments };
939
+ catch (err) {
940
+ argumentError = err instanceof Error ? err.message : String(err);
941
+ parsedArgs = {};
942
+ }
943
+ const toolCall = { name: tc.name, args: parsedArgs, result: undefined };
944
+ stepToolCalls.push(toolCall);
945
+ if (argumentError) {
946
+ toolCall.result = { error: argumentError };
947
+ yield { type: "error", message: `Invalid arguments for tool ${tc.name}: ${argumentError}`, retryable: false };
948
+ }
949
+ else if (!allowedToolNames.has(tc.name)) {
950
+ const message = `Tool ${tc.name} is not in the configured allowlist`;
951
+ toolCall.result = { error: message };
952
+ yield { type: "error", message, retryable: false };
821
953
  }
822
- stepToolCalls.push({ name: tc.name, args: parsedArgs, result: undefined });
823
- if (params.toolExecution) {
954
+ else if (params.toolExecution) {
824
955
  try {
825
- const result = await params.toolExecution(tc.name, parsedArgs);
826
- stepToolCalls[stepToolCalls.length - 1].result = result;
956
+ toolCall.result = await params.toolExecution(tc.name, parsedArgs);
827
957
  }
828
958
  catch (err) {
829
- stepToolCalls[stepToolCalls.length - 1].result = { error: err.message };
959
+ toolCall.result = { error: err.message };
830
960
  }
831
961
  }
832
962
  }
@@ -972,6 +1102,8 @@ export class HilbrasClient {
972
1102
  }
973
1103
  // ─── Cleanup ────────────────────────────────────────────────────────────
974
1104
  async dispose() {
1105
+ // v3.0.0: Destroy all plugins before transport cleanup
1106
+ await this._plugins.destroyAll();
975
1107
  // v2.4.0: Call destroy() when available to clear timers and pooled
976
1108
  // connections; fall back to abort() for basic transports.
977
1109
  if (typeof this._transport.destroy === "function") {