@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.
- package/README.md +201 -34
- package/dist/adapters/anthropic.d.ts +0 -1
- package/dist/adapters/anthropic.d.ts.map +1 -1
- package/dist/adapters/anthropic.js +4 -3
- package/dist/adapters/anthropic.js.map +1 -1
- package/dist/adapters/azure.d.ts +0 -1
- package/dist/adapters/azure.d.ts.map +1 -1
- package/dist/adapters/azure.js +4 -2
- package/dist/adapters/azure.js.map +1 -1
- package/dist/adapters/bedrock.d.ts +0 -1
- package/dist/adapters/bedrock.d.ts.map +1 -1
- package/dist/adapters/bedrock.js +4 -4
- package/dist/adapters/bedrock.js.map +1 -1
- package/dist/adapters/cohere.d.ts.map +1 -1
- package/dist/adapters/cohere.js +2 -1
- package/dist/adapters/cohere.js.map +1 -1
- package/dist/adapters/deepgram.js +4 -4
- package/dist/adapters/deepgram.js.map +1 -1
- package/dist/adapters/extra.d.ts +3 -0
- package/dist/adapters/extra.d.ts.map +1 -0
- package/dist/adapters/extra.js +35 -0
- package/dist/adapters/extra.js.map +1 -0
- package/dist/adapters/google-genai.d.ts +0 -1
- package/dist/adapters/google-genai.d.ts.map +1 -1
- package/dist/adapters/google-genai.js +2 -2
- package/dist/adapters/google-genai.js.map +1 -1
- package/dist/adapters/google-vertex.d.ts +0 -1
- package/dist/adapters/google-vertex.d.ts.map +1 -1
- package/dist/adapters/google-vertex.js +2 -2
- package/dist/adapters/google-vertex.js.map +1 -1
- package/dist/adapters/groq.d.ts +0 -1
- package/dist/adapters/groq.d.ts.map +1 -1
- package/dist/adapters/groq.js +4 -3
- package/dist/adapters/groq.js.map +1 -1
- package/dist/adapters/huggingface.d.ts +0 -1
- package/dist/adapters/huggingface.d.ts.map +1 -1
- package/dist/adapters/huggingface.js +2 -2
- package/dist/adapters/huggingface.js.map +1 -1
- package/dist/adapters/ollama.d.ts +0 -1
- package/dist/adapters/ollama.d.ts.map +1 -1
- package/dist/adapters/ollama.js +4 -3
- package/dist/adapters/ollama.js.map +1 -1
- package/dist/adapters/openai-compatible.d.ts +0 -2
- package/dist/adapters/openai-compatible.d.ts.map +1 -1
- package/dist/adapters/openai-compatible.js +4 -2
- package/dist/adapters/openai-compatible.js.map +1 -1
- package/dist/adapters/openai.d.ts +0 -1
- package/dist/adapters/openai.d.ts.map +1 -1
- package/dist/adapters/openai.js +4 -2
- package/dist/adapters/openai.js.map +1 -1
- package/dist/catalog/index.js +1 -1
- package/dist/catalog/index.js.map +1 -1
- package/dist/catalog/models.d.ts.map +1 -1
- package/dist/catalog/models.js +11 -8
- package/dist/catalog/models.js.map +1 -1
- package/dist/catalog/provider-catalog.d.ts +229 -0
- package/dist/catalog/provider-catalog.d.ts.map +1 -0
- package/dist/catalog/provider-catalog.js +1494 -0
- package/dist/catalog/provider-catalog.js.map +1 -0
- package/dist/client/client.d.ts +60 -1
- package/dist/client/client.d.ts.map +1 -1
- package/dist/client/client.js +260 -128
- package/dist/client/client.js.map +1 -1
- package/dist/config/config.d.ts.map +1 -1
- package/dist/config/config.js.map +1 -1
- package/dist/config/provider-config.d.ts +2 -0
- package/dist/config/provider-config.d.ts.map +1 -1
- package/dist/config/provider-config.js +12 -1
- package/dist/config/provider-config.js.map +1 -1
- package/dist/config/schema.d.ts +6 -0
- package/dist/config/schema.d.ts.map +1 -1
- package/dist/config/schema.js.map +1 -1
- package/dist/cost/alerts.d.ts +107 -0
- package/dist/cost/alerts.d.ts.map +1 -0
- package/dist/cost/alerts.js +163 -0
- package/dist/cost/alerts.js.map +1 -0
- package/dist/cost/tracker.d.ts.map +1 -1
- package/dist/cost/tracker.js +8 -8
- package/dist/cost/tracker.js.map +1 -1
- package/dist/features/eval/ab-test.d.ts +80 -0
- package/dist/features/eval/ab-test.d.ts.map +1 -0
- package/dist/features/eval/ab-test.js +102 -0
- package/dist/features/eval/ab-test.js.map +1 -0
- package/dist/features/rag/chunker.d.ts.map +1 -1
- package/dist/features/rag/chunker.js +6 -0
- package/dist/features/rag/chunker.js.map +1 -1
- package/dist/features/rag/in-memory-store.d.ts.map +1 -1
- package/dist/features/rag/in-memory-store.js +2 -0
- package/dist/features/rag/in-memory-store.js.map +1 -1
- package/dist/features/rag/pipeline.d.ts.map +1 -1
- package/dist/features/rag/pipeline.js +3 -6
- package/dist/features/rag/pipeline.js.map +1 -1
- package/dist/features/rag/retriever.d.ts +5 -0
- package/dist/features/rag/retriever.d.ts.map +1 -1
- package/dist/features/rag/retriever.js +22 -25
- package/dist/features/rag/retriever.js.map +1 -1
- package/dist/index.d.ts +13 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +13 -0
- package/dist/index.js.map +1 -1
- package/dist/logging/logger.d.ts +4 -37
- package/dist/logging/logger.d.ts.map +1 -1
- package/dist/logging/logger.js +9 -54
- package/dist/logging/logger.js.map +1 -1
- package/dist/middleware/middleware.d.ts +1 -1
- package/dist/middleware/middleware.d.ts.map +1 -1
- package/dist/middleware/middleware.js +28 -10
- package/dist/middleware/middleware.js.map +1 -1
- package/dist/plugin/registry.d.ts +53 -0
- package/dist/plugin/registry.d.ts.map +1 -0
- package/dist/plugin/registry.js +111 -0
- package/dist/plugin/registry.js.map +1 -0
- package/dist/plugin/types.d.ts +120 -0
- package/dist/plugin/types.d.ts.map +1 -0
- package/dist/plugin/types.js +9 -0
- package/dist/plugin/types.js.map +1 -0
- package/dist/providers/registry.d.ts.map +1 -1
- package/dist/providers/registry.js +9 -7
- package/dist/providers/registry.js.map +1 -1
- package/dist/reliability/circuit-breaker.d.ts.map +1 -1
- package/dist/reliability/circuit-breaker.js +5 -1
- package/dist/reliability/circuit-breaker.js.map +1 -1
- package/dist/security/audit-logger.d.ts +2 -0
- package/dist/security/audit-logger.d.ts.map +1 -1
- package/dist/security/audit-logger.js +39 -23
- package/dist/security/audit-logger.js.map +1 -1
- package/dist/security/pii-guard.d.ts.map +1 -1
- package/dist/security/pii-guard.js +21 -5
- package/dist/security/pii-guard.js.map +1 -1
- package/dist/security/prompt-injection-guard.d.ts.map +1 -1
- package/dist/security/prompt-injection-guard.js +22 -4
- package/dist/security/prompt-injection-guard.js.map +1 -1
- package/dist/security/rbac.d.ts +81 -0
- package/dist/security/rbac.d.ts.map +1 -0
- package/dist/security/rbac.js +139 -0
- package/dist/security/rbac.js.map +1 -0
- package/dist/security/url-guard.d.ts.map +1 -1
- package/dist/security/url-guard.js +110 -27
- package/dist/security/url-guard.js.map +1 -1
- package/dist/telemetry/body-logger.d.ts.map +1 -1
- package/dist/telemetry/body-logger.js +18 -9
- package/dist/telemetry/body-logger.js.map +1 -1
- package/dist/telemetry/sla.d.ts +100 -0
- package/dist/telemetry/sla.d.ts.map +1 -0
- package/dist/telemetry/sla.js +178 -0
- package/dist/telemetry/sla.js.map +1 -0
- package/dist/telemetry/structured-logger.d.ts.map +1 -1
- package/dist/telemetry/structured-logger.js +20 -7
- package/dist/telemetry/structured-logger.js.map +1 -1
- package/dist/tokens/counter.d.ts +12 -2
- package/dist/tokens/counter.d.ts.map +1 -1
- package/dist/tokens/counter.js +12 -2
- package/dist/tokens/counter.js.map +1 -1
- package/dist/transport/fetch.d.ts.map +1 -1
- package/dist/transport/fetch.js +48 -16
- package/dist/transport/fetch.js.map +1 -1
- package/dist/transport/middleware-transport.d.ts +31 -0
- package/dist/transport/middleware-transport.d.ts.map +1 -0
- package/dist/transport/middleware-transport.js +57 -0
- package/dist/transport/middleware-transport.js.map +1 -0
- package/dist/types/streams.d.ts +10 -0
- package/dist/types/streams.d.ts.map +1 -1
- package/dist/types/streams.js +10 -0
- package/dist/types/streams.js.map +1 -1
- package/dist/types/tool-builder.d.ts +3 -1
- package/dist/types/tool-builder.d.ts.map +1 -1
- package/dist/types/tool-builder.js +3 -1
- package/dist/types/tool-builder.js.map +1 -1
- package/dist/types/tools.d.ts +0 -2
- package/dist/types/tools.d.ts.map +1 -1
- package/dist/types/tools.js +1 -11
- package/dist/types/tools.js.map +1 -1
- package/package.json +125 -108
- package/dist/catalog/provider-catalog.json +0 -246
- package/dist/client/pipeline.d.ts +0 -134
- package/dist/client/pipeline.d.ts.map +0 -1
- package/dist/client/pipeline.js +0 -222
- package/dist/client/pipeline.js.map +0 -1
- package/dist/features/memory/index.d.ts +0 -3
- package/dist/features/memory/index.d.ts.map +0 -1
- package/dist/features/memory/index.js +0 -2
- package/dist/features/memory/index.js.map +0 -1
- package/dist/features/memory/memory.d.ts +0 -46
- package/dist/features/memory/memory.d.ts.map +0 -1
- package/dist/features/memory/memory.js +0 -152
- package/dist/features/memory/memory.js.map +0 -1
- package/dist/security/index.d.ts +0 -16
- package/dist/security/index.d.ts.map +0 -1
- package/dist/security/index.js +0 -10
- package/dist/security/index.js.map +0 -1
- package/dist/telemetry/index.d.ts +0 -15
- package/dist/telemetry/index.d.ts.map +0 -1
- package/dist/telemetry/index.js +0 -11
- package/dist/telemetry/index.js.map +0 -1
package/dist/client/client.js
CHANGED
|
@@ -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
|
|
123
|
-
const guard = validateBaseUrl(
|
|
124
|
-
allowInsecure:
|
|
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 '${
|
|
171
|
+
throw new ConfigurationError(`Refused to register provider '${ownedConfig.name}': ${guard.reason}`);
|
|
129
172
|
}
|
|
130
|
-
this.
|
|
131
|
-
|
|
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
|
|
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(
|
|
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,
|
|
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,
|
|
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,
|
|
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,
|
|
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
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
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
|
-
|
|
578
|
-
|
|
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
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
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
|
-
|
|
629
|
-
|
|
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
|
-
|
|
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
|
-
|
|
790
|
-
|
|
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
|
-
|
|
793
|
-
|
|
794
|
-
|
|
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
|
-
|
|
797
|
-
stepToolCalls[stepToolCalls.length - 1].result = result;
|
|
912
|
+
toolCall.result = await params.toolExecution(pending.name, parsedArgs);
|
|
798
913
|
}
|
|
799
914
|
catch (err) {
|
|
800
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
823
|
-
if (params.toolExecution) {
|
|
954
|
+
else if (params.toolExecution) {
|
|
824
955
|
try {
|
|
825
|
-
|
|
826
|
-
stepToolCalls[stepToolCalls.length - 1].result = result;
|
|
956
|
+
toolCall.result = await params.toolExecution(tc.name, parsedArgs);
|
|
827
957
|
}
|
|
828
958
|
catch (err) {
|
|
829
|
-
|
|
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") {
|