@hilbras/sdk 2.4.0 → 3.0.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 +151 -5
- package/dist/client/client.d.ts +59 -0
- package/dist/client/client.d.ts.map +1 -1
- package/dist/client/client.js +75 -3
- package/dist/client/client.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 +106 -0
- package/dist/cost/alerts.d.ts.map +1 -0
- package/dist/cost/alerts.js +150 -0
- package/dist/cost/alerts.js.map +1 -0
- 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/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -1
- package/dist/logging/logger.d.ts +9 -0
- package/dist/logging/logger.d.ts.map +1 -1
- package/dist/logging/logger.js +9 -0
- package/dist/logging/logger.js.map +1 -1
- package/dist/plugin/index.d.ts +9 -0
- package/dist/plugin/index.d.ts.map +1 -0
- package/dist/plugin/index.js +8 -0
- package/dist/plugin/index.js.map +1 -0
- package/dist/plugin/registry.d.ts +50 -0
- package/dist/plugin/registry.d.ts.map +1 -0
- package/dist/plugin/registry.js +109 -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/security/index.d.ts +2 -0
- package/dist/security/index.d.ts.map +1 -1
- package/dist/security/index.js +2 -0
- package/dist/security/index.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/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/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/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/package.json +3 -2
package/README.md
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
<p align="center">
|
|
2
|
-
<img src="https://img.shields.io/badge/version-
|
|
2
|
+
<img src="https://img.shields.io/badge/version-3.0.0-blue" alt="version">
|
|
3
3
|
<img src="https://img.shields.io/badge/license-MIT-green" alt="license">
|
|
4
4
|
<img src="https://img.shields.io/badge/node-%3E%3D18-brightgreen" alt="node">
|
|
5
5
|
<img src="https://img.shields.io/badge/types-strict-blueviolet" alt="types">
|
|
6
|
-
<img src="https://img.shields.io/badge/tests-
|
|
6
|
+
<img src="https://img.shields.io/badge/tests-1586%20passing-brightgreen" alt="tests">
|
|
7
7
|
<img src="https://img.shields.io/badge/runtime%20deps-zero-brightgreen" alt="zero deps">
|
|
8
8
|
</p>
|
|
9
9
|
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
|
|
12
12
|
<p align="center">
|
|
13
13
|
<strong>Provider-agnostic AI execution engine for TypeScript.</strong><br>
|
|
14
|
-
Streaming, tool calling, structured output, circuit breaker, retry, reasoning normalization, cost enforcement, and SSRF-safe provider registration — for OpenAI, Anthropic, Gemini, Azure, Groq, Ollama, Bedrock, Vertex AI, HuggingFace, Deepgram, ElevenLabs, Voyage AI, and Cohere Rerank. Zero runtime dependencies.
|
|
14
|
+
Streaming, tool calling, structured output, circuit breaker, retry, reasoning normalization, cost enforcement, plugin system, RBAC, SLA monitoring, A/B testing, and SSRF-safe provider registration — for OpenAI, Anthropic, Gemini, Azure, Groq, Ollama, Bedrock, Vertex AI, HuggingFace, Deepgram, ElevenLabs, Voyage AI, and Cohere Rerank. Zero runtime dependencies.
|
|
15
15
|
</p>
|
|
16
16
|
|
|
17
17
|
---
|
|
@@ -37,6 +37,9 @@ Application
|
|
|
37
37
|
│ Token Counting Cost Enforcement │
|
|
38
38
|
│ Prompt Caching Auto-Repair Output │
|
|
39
39
|
│ Middleware Pipeline Typed Errors │
|
|
40
|
+
│ Plugin System RBAC Access Control │
|
|
41
|
+
│ SLA Monitoring A/B Prompt Testing │
|
|
42
|
+
│ Cost Alerts Audit Logging │
|
|
40
43
|
└──────────────────────┬────────────────────────┘
|
|
41
44
|
│
|
|
42
45
|
┌────────────┼────────────┐
|
|
@@ -95,6 +98,74 @@ const reply = await client.complete({
|
|
|
95
98
|
|
|
96
99
|
---
|
|
97
100
|
|
|
101
|
+
## Configuration
|
|
102
|
+
|
|
103
|
+
### Per-client tokenizer
|
|
104
|
+
|
|
105
|
+
By default, token counting uses a heuristic word-based estimator. Pass a
|
|
106
|
+
custom tokenizer to scope it to a single client instance:
|
|
107
|
+
|
|
108
|
+
```typescript
|
|
109
|
+
import { HilbrasClient } from "@hilbras/sdk";
|
|
110
|
+
|
|
111
|
+
// Your BPE / tiktoken / ollama tokenizer
|
|
112
|
+
const tokenizer = {
|
|
113
|
+
count(text: string): number {
|
|
114
|
+
return yourTokenizer.encode(text).length;
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
const client = new HilbrasClient({ tokenizer });
|
|
119
|
+
|
|
120
|
+
// Every request on this client uses your tokenizer
|
|
121
|
+
const reply = await client.complete({
|
|
122
|
+
provider: "openai",
|
|
123
|
+
model: "gpt-4o",
|
|
124
|
+
messages: [{ role: "user", content: "Hello!" }],
|
|
125
|
+
});
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
> **v2.5.0+:** The global `setTokenizer()` / `getTokenizer()` singletons are
|
|
129
|
+
> deprecated. Use the per-client `tokenizer` config instead to avoid cross-client
|
|
130
|
+
> interference.
|
|
131
|
+
|
|
132
|
+
### Middleware
|
|
133
|
+
|
|
134
|
+
Wrap the transport with middleware for auth, logging, or custom transforms.
|
|
135
|
+
Middleware runs on **every** request (including retries) for the client:
|
|
136
|
+
|
|
137
|
+
```typescript
|
|
138
|
+
import { HilbrasClient } from "@hilbras/sdk";
|
|
139
|
+
import { authMiddleware, loggingMiddleware, composeMiddlewares } from "@hilbras/sdk";
|
|
140
|
+
|
|
141
|
+
const client = new HilbrasClient({
|
|
142
|
+
middleware: composeMiddlewares(
|
|
143
|
+
authMiddleware(() => process.env.API_KEY!),
|
|
144
|
+
loggingMiddleware(console),
|
|
145
|
+
),
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
// All requests go through both middleware layers
|
|
149
|
+
const reply = await client.complete({
|
|
150
|
+
provider: "openai",
|
|
151
|
+
model: "gpt-4o",
|
|
152
|
+
messages: [{ role: "user", content: "Hello!" }],
|
|
153
|
+
});
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
You can also use `MiddlewareTransport` directly to wrap any transport:
|
|
157
|
+
|
|
158
|
+
```typescript
|
|
159
|
+
import { MiddlewareTransport, FetchTransport } from "@hilbras/sdk";
|
|
160
|
+
|
|
161
|
+
const transport = new MiddlewareTransport(
|
|
162
|
+
new FetchTransport(),
|
|
163
|
+
composeMiddlewares(authMiddleware(() => "my-key")),
|
|
164
|
+
);
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
---
|
|
168
|
+
|
|
98
169
|
## Features at a glance
|
|
99
170
|
|
|
100
171
|
| Feature | Summary | Docs |
|
|
@@ -107,17 +178,24 @@ const reply = await client.complete({
|
|
|
107
178
|
| **Circuit breaker** | Per-provider failure isolation with half-open recovery | [API Reference](docs/api-reference.md#reliability) |
|
|
108
179
|
| **Retry & backoff** | Exponential backoff with jitter for 429/5xx/network errors | [API Reference](docs/api-reference.md#reliability) |
|
|
109
180
|
| **Cost enforcement** | Atomic reservations, per-request and session budgets, streaming included | [Cost & Budget](docs/cost-and-budget.md) |
|
|
181
|
+
| **Plugin system** | Lifecycle hooks (onRequest/onResponse/onError) for extensibility | [API Reference](docs/api-reference.md) |
|
|
182
|
+
| **RBAC** | Role-based access control with provider/model restrictions and per-role rate limiting | [Security](docs/security.md) |
|
|
183
|
+
| **SLA monitoring** | Latency, error rate, and availability tracking with breach alerts | [Observability](docs/observability.md) |
|
|
184
|
+
| **Cost alerts** | Configurable threshold alerts via webhook or callback | [Cost & Budget](docs/cost-and-budget.md) |
|
|
185
|
+
| **A/B prompt testing** | Compare prompt variants against datasets with built-in metrics | [Eval](docs/eval.md) |
|
|
110
186
|
| **Observability** | Typed lifecycle events for OpenTelemetry/Datadog/etc. | [Observability](docs/observability.md) |
|
|
111
187
|
| **SSRF safety** | Default-reject `http://`, block AWS metadata, opt-in for local Ollama | [Security](docs/security.md) |
|
|
112
188
|
| **Error redaction** | API keys auto-redacted from provider error bodies | [Security](docs/security.md#error-redaction-in-provider-responses) |
|
|
113
189
|
| **Reasoning normalization** | Detect & normalize `<thinking>` / `<reasoning>` tags and native fields | [API Reference](docs/api-reference.md) |
|
|
190
|
+
| **Per-client tokenizer** | Scoped BPE tokenizer per client instance — no global singletons | [API Reference](docs/api-reference.md) |
|
|
191
|
+
| **Middleware pipeline** | Transport-level middleware: auth headers, logging, custom request/response transforms | [API Reference](docs/api-reference.md) |
|
|
114
192
|
| **Agent framework** | ToolLoopAgent, ReActAgent, PlanAndExecuteAgent with approval, budget, cost tracking | [Agent](docs/agent.md) |
|
|
115
193
|
| **Evaluation** | LLM output evaluation with built-in metrics (exact_match, similarity, toxicity) | [Eval](docs/eval.md) |
|
|
116
194
|
| **React hooks** | `useChat`, `useCompletion`, `useCost` with streaming, abort, retry | [React](#react-hooks) |
|
|
117
195
|
| **Framework hooks** | Vue, Svelte, Solid, Qwik, Angular, Next.js, Astro, Remix | [Frameworks](docs/frameworks.md) |
|
|
118
196
|
| **RAG primitives** | VectorStore, Retriever, RAGPipeline, chunking | [RAG](docs/rag.md) |
|
|
119
197
|
| **Provider catalog** | Runtime provider/model discovery with search | [Catalog](docs/catalog.md) |
|
|
120
|
-
| **CLI** | `hilbras` CLI
|
|
198
|
+
| **CLI** | `hilbras` CLI — chat REPL, provider benchmarking, cost reports, dashboard | [CLI](docs/cli.md) |
|
|
121
199
|
| **Migration** | Guide from Vercel AI SDK | [Migration](docs/migration-from-vercel-ai-sdk.md) |
|
|
122
200
|
| **Fine-tuning** | Export training data in 6 formats, data splitting, quality validation | [Fine-tune](docs/fine-tune.md) |
|
|
123
201
|
| **Scaffolding** | `npx create-hilbras-app` project scaffolding | [CLI](docs/cli.md) |
|
|
@@ -125,6 +203,66 @@ const reply = await client.complete({
|
|
|
125
203
|
|
|
126
204
|
---
|
|
127
205
|
|
|
206
|
+
## What's New in v3.0.0
|
|
207
|
+
|
|
208
|
+
**Plugin System** — Extend the client with lifecycle hooks:
|
|
209
|
+
```typescript
|
|
210
|
+
client.use({
|
|
211
|
+
name: "logger",
|
|
212
|
+
onRequest(ctx) { console.log(`→ ${ctx.provider}/${ctx.model}`); },
|
|
213
|
+
onResponse(ctx) { console.log(`✓ ${ctx.durationMs}ms`); },
|
|
214
|
+
onError(ctx) { console.error(`✗ ${ctx.error.message}`); },
|
|
215
|
+
});
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
**RBAC** — Role-based access control with per-role provider/model restrictions:
|
|
219
|
+
```typescript
|
|
220
|
+
const client = new HilbrasClient({
|
|
221
|
+
middleware: createRBACMiddleware({
|
|
222
|
+
roles: {
|
|
223
|
+
viewer: { name: "viewer", allowedProviders: ["openai"], maxTokensPerRequest: 4096 },
|
|
224
|
+
admin: { name: "admin" },
|
|
225
|
+
},
|
|
226
|
+
defaultRole: "viewer",
|
|
227
|
+
}, (ctx) => extractUserId(ctx)),
|
|
228
|
+
});
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
**SLA Monitoring** — Track latency, error rate, and availability:
|
|
232
|
+
```typescript
|
|
233
|
+
const monitor = new SLAMonitor(client, [
|
|
234
|
+
{ name: "p95 latency", metric: "latency_p95", threshold: 2000, windowMs: 60_000 },
|
|
235
|
+
{ name: "availability", metric: "availability", threshold: 0.99, windowMs: 300_000 },
|
|
236
|
+
]);
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
**Cost Alerts** — Get notified when spending crosses thresholds:
|
|
240
|
+
```typescript
|
|
241
|
+
const { budget, monitor } = createCostAlertBudget({
|
|
242
|
+
sessionBudget: 10.00,
|
|
243
|
+
thresholds: [
|
|
244
|
+
{ percent: 50, channel: { type: "callback", callback: (a) => console.log("50%!") } },
|
|
245
|
+
{ percent: 75, channel: { type: "webhook", url: "https://hooks.slack.com/..." } },
|
|
246
|
+
],
|
|
247
|
+
});
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
**A/B Prompt Testing** — Compare prompt variants against datasets:
|
|
251
|
+
```typescript
|
|
252
|
+
const result = await runABTest(client, {
|
|
253
|
+
variants: [
|
|
254
|
+
{ name: "concise", systemPrompt: "Answer concisely." },
|
|
255
|
+
{ name: "detailed", systemPrompt: "Answer in detail with examples." },
|
|
256
|
+
],
|
|
257
|
+
dataset: [{ id: "1", input: "What is 2+2?", expected: "4" }],
|
|
258
|
+
});
|
|
259
|
+
console.log(`Winner: ${result.winner.name}`);
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
**CLI** — New commands: `hilbras chat`, `hilbras bench`, `hilbras costs`, `hilbras dashboard`
|
|
263
|
+
|
|
264
|
+
---
|
|
265
|
+
|
|
128
266
|
## React Hooks
|
|
129
267
|
|
|
130
268
|
First-class React integration via `@hilbras/react`. Zero runtime dependencies beyond React itself.
|
|
@@ -238,8 +376,16 @@ import type { AIProvider } from "@hilbras/sdk/adapter"; // Provider cont
|
|
|
238
376
|
import { estimateTokens } from "@hilbras/sdk/tokens"; // Token utilities
|
|
239
377
|
import { loadConfig } from "@hilbras/sdk/config"; // Config
|
|
240
378
|
import { FetchTransport } from "@hilbras/sdk/transport/fetch"; // Transport
|
|
379
|
+
import { MiddlewareTransport } from "@hilbras/sdk"; // Middleware wrapper
|
|
241
380
|
import { validateBaseUrl } from "@hilbras/sdk"; // SSRF guard
|
|
242
381
|
|
|
382
|
+
// v3.0.0: Plugin system, RBAC, SLA, cost alerts, A/B testing
|
|
383
|
+
import type { Plugin } from "@hilbras/sdk"; // Plugin interface
|
|
384
|
+
import { createRBACMiddleware } from "@hilbras/sdk"; // RBAC
|
|
385
|
+
import { SLAMonitor } from "@hilbras/sdk"; // SLA monitoring
|
|
386
|
+
import { CostAlertMonitor } from "@hilbras/sdk"; // Cost alerts
|
|
387
|
+
import { runABTest } from "@hilbras/sdk"; // A/B testing
|
|
388
|
+
|
|
243
389
|
// Packages
|
|
244
390
|
import { useChat, useCompletion, useCost, HilbrasProvider } from "@hilbras/react"; // React hooks
|
|
245
391
|
import { useChat } from "@hilbras/vue"; // Vue composables
|
|
@@ -261,7 +407,7 @@ import { exportTrainingData } from "@hilbras/fine-tune"; // Fine-tuning
|
|
|
261
407
|
```bash
|
|
262
408
|
npm install
|
|
263
409
|
npm run build # Compile TypeScript
|
|
264
|
-
npm test # Run
|
|
410
|
+
npm test # Run 1586 tests
|
|
265
411
|
npm run test:watch # Watch mode
|
|
266
412
|
npm run lint # Lint with oxlint
|
|
267
413
|
```
|
package/dist/client/client.d.ts
CHANGED
|
@@ -25,9 +25,27 @@ import type { OpenTelemetryExporter } from "../telemetry/opentelemetry.js";
|
|
|
25
25
|
import type { HookEvent, HookEventType, HookListener } from "../types/observability.js";
|
|
26
26
|
import { BudgetTracker } from "../cost/tracker.js";
|
|
27
27
|
import type { BudgetConfig, CostReport } from "../cost/types.js";
|
|
28
|
+
import { type Tokenizer } from "../tokens/counter.js";
|
|
29
|
+
import type { Plugin } from "../plugin/types.js";
|
|
28
30
|
export interface HilbrasClientConfig {
|
|
29
31
|
/** Custom transport (default: FetchTransport) */
|
|
30
32
|
transport?: Transport;
|
|
33
|
+
/**
|
|
34
|
+
* v2.5.0: Middleware pipeline applied to all transport requests.
|
|
35
|
+
* When provided, the transport is automatically wrapped with a
|
|
36
|
+
* `MiddlewareTransport` that applies the middleware chain.
|
|
37
|
+
*
|
|
38
|
+
* This is a convenience shortcut — if you already have a custom
|
|
39
|
+
* `transport` that wraps middleware, you don't need this.
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* ```ts
|
|
43
|
+
* const client = new HilbrasClient({
|
|
44
|
+
* middleware: composeMiddlewares(authMiddleware(getToken), loggingMiddleware()),
|
|
45
|
+
* });
|
|
46
|
+
* ```
|
|
47
|
+
*/
|
|
48
|
+
middleware?: import("../middleware/middleware.js").Middleware;
|
|
31
49
|
/** Custom adapter registry (default: built-in registry with openai, anthropic, etc.) */
|
|
32
50
|
adapterRegistry?: AdapterRegistry;
|
|
33
51
|
/** Default execution policy for all requests (can be overridden per-request) */
|
|
@@ -67,6 +85,22 @@ export interface HilbrasClientConfig {
|
|
|
67
85
|
/** OpenTelemetry exporter for traces and metrics */
|
|
68
86
|
openTelemetry?: OpenTelemetryExporter;
|
|
69
87
|
};
|
|
88
|
+
/**
|
|
89
|
+
* v2.5.0 BUG-04: Optional per-client tokenizer for accurate token counting.
|
|
90
|
+
* When provided, this tokenizer is used instead of the global `setTokenizer()`
|
|
91
|
+
* singleton, allowing multiple clients to use different tokenizers without
|
|
92
|
+
* interfering with each other.
|
|
93
|
+
*
|
|
94
|
+
* @example
|
|
95
|
+
* ```ts
|
|
96
|
+
* import { createTokenizer } from "tiktoken";
|
|
97
|
+
* const enc = await createTokenizer("cl100k_base");
|
|
98
|
+
* const client = new HilbrasClient({
|
|
99
|
+
* tokenizer: { count: (text) => enc.encode(text).length },
|
|
100
|
+
* });
|
|
101
|
+
* ```
|
|
102
|
+
*/
|
|
103
|
+
tokenizer?: Tokenizer;
|
|
70
104
|
}
|
|
71
105
|
export declare class HilbrasClient implements AsyncDisposable {
|
|
72
106
|
private _registry;
|
|
@@ -80,6 +114,8 @@ export declare class HilbrasClient implements AsyncDisposable {
|
|
|
80
114
|
private _budgetTracker;
|
|
81
115
|
private _allowInsecureUrls;
|
|
82
116
|
private _allowPrivateNetwork;
|
|
117
|
+
private _tokenizer;
|
|
118
|
+
private _plugins;
|
|
83
119
|
constructor(config?: HilbrasClientConfig);
|
|
84
120
|
/**
|
|
85
121
|
* Map the legacy SDKConfig fields (maxRetries, requestTimeoutMs,
|
|
@@ -96,7 +132,30 @@ export declare class HilbrasClient implements AsyncDisposable {
|
|
|
96
132
|
off(event: HookEventType, listener: HookListener): void;
|
|
97
133
|
/** Remove all listeners */
|
|
98
134
|
removeAllListeners(event?: HookEventType): void;
|
|
135
|
+
/**
|
|
136
|
+
* Register one or more plugins with the client. Plugins receive lifecycle
|
|
137
|
+
* hooks that fire around every LLM request.
|
|
138
|
+
*
|
|
139
|
+
* @example
|
|
140
|
+
* ```ts
|
|
141
|
+
* client.use({
|
|
142
|
+
* name: "logger",
|
|
143
|
+
* onRequest(ctx) { console.log(`[${ctx.requestId}] → ${ctx.provider}/${ctx.model}`); },
|
|
144
|
+
* onResponse(ctx) { console.log(`[${ctx.requestId}] ✓ ${ctx.durationMs}ms`); },
|
|
145
|
+
* onError(ctx) { console.error(`[${ctx.requestId}] ✗ ${ctx.error.message}`); },
|
|
146
|
+
* });
|
|
147
|
+
* ```
|
|
148
|
+
*/
|
|
149
|
+
use(...plugins: Plugin[]): Promise<void>;
|
|
99
150
|
private _nextRequestId;
|
|
151
|
+
/**
|
|
152
|
+
* Client-scoped token estimation. Uses the per-client tokenizer when set,
|
|
153
|
+
* otherwise falls back to the global `estimateTokens()`.
|
|
154
|
+
*
|
|
155
|
+
* BUG-04 fix: This prevents multiple clients from fighting over the global
|
|
156
|
+
* `setTokenizer()` singleton.
|
|
157
|
+
*/
|
|
158
|
+
private _estimateTokens;
|
|
100
159
|
private _emit;
|
|
101
160
|
addProvider(config: ProviderConfig): void;
|
|
102
161
|
removeProvider(name: string): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/client/client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAE5D,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAC1D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAC1D,OAAO,KAAK,EAAE,sBAAsB,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACvG,OAAO,KAAK,EACV,eAAe,EACf,WAAW,EACX,YAAY,EACZ,mBAAmB,EACnB,YAAY,EACb,MAAM,yBAAyB,CAAC;
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/client/client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAE5D,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO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AG,cAAc,CAAC,WAAW,CAAC,CAwG9B;IAID;;;;;;;;;;;;;;;;OAgBG;IACI,YAAY,CAAC,CAAC,EACnB,MAAM,EAAE,mBAAmB,CAAC,CAAC,CAAC,GAAG;QAC/B,QAAQ,EAAE,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,CAAC;QACnD,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,eAAe,CAAC,CAAC,CAAC,CAAC;KACtD,GACA,cAAc,CAAC;QAAE,IAAI,EAAE,cAAc,CAAC;QAAC,aAAa,EAAE,OAAO,CAAC,CAAC,CAAC,CAAA;KAAE,GAAG,WAAW,CAAC,CA0GnF;IAIK,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAY7B;IAEK,CAAC,MAAM,CAAC,YAAY,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAE3C;CACF"}
|
package/dist/client/client.js
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
*/
|
|
12
12
|
import { ProviderRegistry } from "../providers/registry.js";
|
|
13
13
|
import { FetchTransport } from "../transport/fetch.js";
|
|
14
|
+
import { MiddlewareTransport } from "../transport/middleware-transport.js";
|
|
14
15
|
import { getCircuitBreakerRegistry } from "../reliability/circuit-breaker.js";
|
|
15
16
|
import { createRetryConfig, shouldRetry, shouldRetryNetworkError } from "../reliability/retry.js";
|
|
16
17
|
import { calculateBackoff, sleep } from "../reliability/backoff.js";
|
|
@@ -26,6 +27,7 @@ import { ClientHooks } from "./hooks.js";
|
|
|
26
27
|
import { BudgetTracker } from "../cost/tracker.js";
|
|
27
28
|
import { estimateTokens } from "../tokens/counter.js";
|
|
28
29
|
import { getProviderCatalog, getModelsForProvider } from "../catalog/index.js";
|
|
30
|
+
import { PluginRegistry } from "../plugin/registry.js";
|
|
29
31
|
export class HilbrasClient {
|
|
30
32
|
_registry = new ProviderRegistry();
|
|
31
33
|
_transport;
|
|
@@ -38,12 +40,19 @@ export class HilbrasClient {
|
|
|
38
40
|
_budgetTracker;
|
|
39
41
|
_allowInsecureUrls;
|
|
40
42
|
_allowPrivateNetwork;
|
|
43
|
+
_tokenizer;
|
|
44
|
+
_plugins = new PluginRegistry();
|
|
41
45
|
constructor(config) {
|
|
42
46
|
this._transport = config?.transport ?? new FetchTransport();
|
|
47
|
+
// v2.5.0: Wrap transport with middleware pipeline when provided
|
|
48
|
+
if (config?.middleware) {
|
|
49
|
+
this._transport = new MiddlewareTransport(this._transport, config.middleware);
|
|
50
|
+
}
|
|
43
51
|
this._adapterRegistry = config?.adapterRegistry ?? getDefaultAdapterRegistry();
|
|
44
52
|
this._router = new ModelRouter();
|
|
45
53
|
this._allowInsecureUrls = config?.allowInsecureUrls ?? false;
|
|
46
54
|
this._allowPrivateNetwork = config?.allowPrivateNetwork ?? false;
|
|
55
|
+
this._tokenizer = config?.tokenizer ?? null;
|
|
47
56
|
// v0.10.0 PR-5: derive policy + budget from sdkConfig when not
|
|
48
57
|
// explicitly provided. Precedence: explicit > sdkConfig > defaults.
|
|
49
58
|
const sdk = config?.sdkConfig;
|
|
@@ -110,9 +119,40 @@ export class HilbrasClient {
|
|
|
110
119
|
removeAllListeners(event) {
|
|
111
120
|
this._hooks.removeAll(event);
|
|
112
121
|
}
|
|
122
|
+
// ─── Plugin System ──────────────────────────────────────────────────────
|
|
123
|
+
/**
|
|
124
|
+
* Register one or more plugins with the client. Plugins receive lifecycle
|
|
125
|
+
* hooks that fire around every LLM request.
|
|
126
|
+
*
|
|
127
|
+
* @example
|
|
128
|
+
* ```ts
|
|
129
|
+
* client.use({
|
|
130
|
+
* name: "logger",
|
|
131
|
+
* onRequest(ctx) { console.log(`[${ctx.requestId}] → ${ctx.provider}/${ctx.model}`); },
|
|
132
|
+
* onResponse(ctx) { console.log(`[${ctx.requestId}] ✓ ${ctx.durationMs}ms`); },
|
|
133
|
+
* onError(ctx) { console.error(`[${ctx.requestId}] ✗ ${ctx.error.message}`); },
|
|
134
|
+
* });
|
|
135
|
+
* ```
|
|
136
|
+
*/
|
|
137
|
+
async use(...plugins) {
|
|
138
|
+
await this._plugins.add(...plugins);
|
|
139
|
+
await this._plugins.setupAll(this);
|
|
140
|
+
}
|
|
113
141
|
_nextRequestId() {
|
|
114
142
|
return `req_${++this._requestCounter}`;
|
|
115
143
|
}
|
|
144
|
+
/**
|
|
145
|
+
* Client-scoped token estimation. Uses the per-client tokenizer when set,
|
|
146
|
+
* otherwise falls back to the global `estimateTokens()`.
|
|
147
|
+
*
|
|
148
|
+
* BUG-04 fix: This prevents multiple clients from fighting over the global
|
|
149
|
+
* `setTokenizer()` singleton.
|
|
150
|
+
*/
|
|
151
|
+
_estimateTokens(text) {
|
|
152
|
+
if (this._tokenizer)
|
|
153
|
+
return this._tokenizer.count(text);
|
|
154
|
+
return estimateTokens(text);
|
|
155
|
+
}
|
|
116
156
|
_emit(event) {
|
|
117
157
|
this._hooks.emit(event);
|
|
118
158
|
}
|
|
@@ -358,10 +398,20 @@ export class HilbrasClient {
|
|
|
358
398
|
// setup into _prepareRequest so stream() and complete() share it.
|
|
359
399
|
const { resolved, circuitBreaker, retryConfig, signal } = this._prepareRequest(requestId, providerName, providerConfig, params.policy, params.signal);
|
|
360
400
|
const messages = this._normalizeMessages(params.messages);
|
|
401
|
+
// v3.0.0: Plugin onRequest hook
|
|
402
|
+
await this._plugins.fireRequest({
|
|
403
|
+
requestId,
|
|
404
|
+
provider: providerName,
|
|
405
|
+
model: modelId,
|
|
406
|
+
messages,
|
|
407
|
+
extra: params.extra,
|
|
408
|
+
signal: params.signal,
|
|
409
|
+
timestamp: startTime,
|
|
410
|
+
});
|
|
361
411
|
// Atomic budget reservation before any provider call. Reserves the
|
|
362
412
|
// estimated cost for the entire retry+fallback chain; the reservation is
|
|
363
413
|
// converted to actual on the first usage chunk, or released on failure.
|
|
364
|
-
estimatedCost = this._budgetTracker.estimate(modelId, providerName,
|
|
414
|
+
estimatedCost = this._budgetTracker.estimate(modelId, providerName, this._estimateTokens(messages.map((m) => m.content ?? "").join("")), 0);
|
|
365
415
|
const initialReservation = this._budgetTracker.reserve(requestId, estimatedCost);
|
|
366
416
|
if (!initialReservation) {
|
|
367
417
|
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,6 +458,8 @@ export class HilbrasClient {
|
|
|
408
458
|
reservationActive = false;
|
|
409
459
|
}
|
|
410
460
|
this._emit({ type: "request.completed", requestId, timestamp: performance.now(), provider: providerName, model: modelId, durationMs: performance.now() - startTime, attempts: attempt + 1, inputTokens, outputTokens, structuredOutput: false });
|
|
461
|
+
// v3.0.0: Plugin onResponse hook
|
|
462
|
+
await this._plugins.fireResponse({ requestId, provider: providerName, model: modelId, durationMs: performance.now() - startTime, inputTokens, outputTokens, streaming: true });
|
|
411
463
|
return;
|
|
412
464
|
}
|
|
413
465
|
catch (err) {
|
|
@@ -438,7 +490,7 @@ export class HilbrasClient {
|
|
|
438
490
|
reservationActive = false;
|
|
439
491
|
}
|
|
440
492
|
const fbReservationId = `${requestId}_fb_${fb.model}`;
|
|
441
|
-
const fbEstimatedCost = this._budgetTracker.estimate(fb.model, fb.provider,
|
|
493
|
+
const fbEstimatedCost = this._budgetTracker.estimate(fb.model, fb.provider, this._estimateTokens(messages.map((m) => m.content ?? "").join("")), 0);
|
|
442
494
|
const fbReservation = this._budgetTracker.reserve(fbReservationId, fbEstimatedCost);
|
|
443
495
|
if (!fbReservation)
|
|
444
496
|
continue; // budget exceeded for this fallback
|
|
@@ -480,6 +532,8 @@ export class HilbrasClient {
|
|
|
480
532
|
}
|
|
481
533
|
circuitBreaker?.recordFailure(err instanceof Error ? err : undefined);
|
|
482
534
|
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) });
|
|
535
|
+
// v3.0.0: Plugin onError hook
|
|
536
|
+
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
537
|
throw err;
|
|
484
538
|
}
|
|
485
539
|
}
|
|
@@ -513,6 +567,16 @@ export class HilbrasClient {
|
|
|
513
567
|
// setup into _prepareRequest so stream() and complete() share it.
|
|
514
568
|
const { resolved, circuitBreaker, retryConfig, signal } = this._prepareRequest(requestId, providerName, providerConfig, params.policy, params.signal);
|
|
515
569
|
const messages = this._normalizeMessages(params.messages);
|
|
570
|
+
// v3.0.0: Plugin onRequest hook
|
|
571
|
+
await this._plugins.fireRequest({
|
|
572
|
+
requestId,
|
|
573
|
+
provider: providerName,
|
|
574
|
+
model: modelId,
|
|
575
|
+
messages,
|
|
576
|
+
extra: params.extra,
|
|
577
|
+
signal: params.signal,
|
|
578
|
+
timestamp: startTime,
|
|
579
|
+
});
|
|
516
580
|
// Structured output setup
|
|
517
581
|
const outputConfig = params.output;
|
|
518
582
|
let structuredMessages = [...messages];
|
|
@@ -529,7 +593,7 @@ export class HilbrasClient {
|
|
|
529
593
|
}
|
|
530
594
|
const maxRepairAttempts = outputConfig?.maxRepairAttempts ?? 2;
|
|
531
595
|
// Budget: atomic reserve before execution
|
|
532
|
-
const estimatedCost = this._budgetTracker.estimate(modelId, providerName,
|
|
596
|
+
const estimatedCost = this._budgetTracker.estimate(modelId, providerName, this._estimateTokens(messages.map((m) => m.content ?? "").join("")), 0);
|
|
533
597
|
const reservation = this._budgetTracker.reserve(requestId, estimatedCost);
|
|
534
598
|
if (!reservation) {
|
|
535
599
|
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`);
|
|
@@ -550,6 +614,8 @@ export class HilbrasClient {
|
|
|
550
614
|
if (!outputConfig) {
|
|
551
615
|
this._budgetTracker.settle(requestId, estimatedCost, { provider: providerName, model: modelId, phase: "execute" });
|
|
552
616
|
this._emit({ type: "request.completed", requestId, timestamp: performance.now(), provider: providerName, model: modelId, durationMs: performance.now() - startTime, attempts: attempt + 1, structuredOutput: false });
|
|
617
|
+
// v3.0.0: Plugin onResponse hook
|
|
618
|
+
await this._plugins.fireResponse({ requestId, provider: providerName, model: modelId, durationMs: performance.now() - startTime, streaming: false });
|
|
553
619
|
return result;
|
|
554
620
|
}
|
|
555
621
|
// Validate structured output
|
|
@@ -560,6 +626,8 @@ export class HilbrasClient {
|
|
|
560
626
|
this._budgetTracker.settle(requestId, estimatedCost, { provider: providerName, model: modelId, phase: "execute" });
|
|
561
627
|
this._emit({ type: "structured.validate.pass", requestId, timestamp: performance.now() });
|
|
562
628
|
this._emit({ type: "request.completed", requestId, timestamp: performance.now(), provider: providerName, model: modelId, durationMs: performance.now() - startTime, attempts: attempt + 1, structuredOutput: true });
|
|
629
|
+
// v3.0.0: Plugin onResponse hook
|
|
630
|
+
await this._plugins.fireResponse({ requestId, provider: providerName, model: modelId, durationMs: performance.now() - startTime, streaming: false });
|
|
563
631
|
return validation.data;
|
|
564
632
|
}
|
|
565
633
|
// Validation failed — attempt repair
|
|
@@ -634,6 +702,8 @@ export class HilbrasClient {
|
|
|
634
702
|
this._budgetTracker.release(requestId);
|
|
635
703
|
circuitBreaker?.recordFailure(err instanceof Error ? err : undefined);
|
|
636
704
|
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) });
|
|
705
|
+
// v3.0.0: Plugin onError hook
|
|
706
|
+
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 });
|
|
637
707
|
throw err;
|
|
638
708
|
}
|
|
639
709
|
}
|
|
@@ -972,6 +1042,8 @@ export class HilbrasClient {
|
|
|
972
1042
|
}
|
|
973
1043
|
// ─── Cleanup ────────────────────────────────────────────────────────────
|
|
974
1044
|
async dispose() {
|
|
1045
|
+
// v3.0.0: Destroy all plugins before transport cleanup
|
|
1046
|
+
await this._plugins.destroyAll();
|
|
975
1047
|
// v2.4.0: Call destroy() when available to clear timers and pooled
|
|
976
1048
|
// connections; fall back to abort() for basic transports.
|
|
977
1049
|
if (typeof this._transport.destroy === "function") {
|