@hilbras/sdk 3.6.0 → 3.7.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 +1 -1
- package/dist/client/client.js +15 -5
- package/dist/core/execution/request-pipeline.js +141 -73
- package/dist/features/agent/plan-and-execute.js +1 -1
- package/dist/features/agent/react.js +1 -1
- package/dist/features/agent/tool-loop.js +1 -1
- package/dist/frameworks/angular/angular-shim.d.ts +1 -1
- package/dist/frameworks/angular/angular-shim.js +1 -1
- package/dist/frameworks/angular/chat.service.js +1 -1
- package/dist/frameworks/angular/completion.service.js +1 -1
- package/dist/frameworks/angular/object.service.js +1 -1
- package/dist/frameworks/nextjs/server.js +1 -1
- package/dist/frameworks/svelte/use-chat.js +1 -1
- package/dist/frameworks/vue/use-chat.js +1 -1
- package/dist/security/audit-logger.d.ts +7 -1
- package/dist/security/audit-logger.js +7 -5
- package/dist/security/pii-guard.js +21 -1
- package/dist/security/prompt-injection-guard.js +1 -1
- package/dist/security/rate-limiter.d.ts +2 -0
- package/dist/security/rate-limiter.js +8 -1
- package/dist/security/rbac.js +2 -2
- package/dist/security/request-signer.d.ts +2 -0
- package/dist/security/request-signer.js +3 -1
- package/dist/security/url-guard.d.ts +1 -1
- package/dist/security/url-guard.js +4 -3
- package/dist/telemetry/opentelemetry.d.ts +6 -1
- package/dist/telemetry/opentelemetry.js +41 -0
- package/dist/types/observability.d.ts +2 -0
- package/dist/utils/sse-writer.js +1 -1
- package/package.json +6 -5
package/README.md
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
<p align="center">
|
|
2
|
-
<img src="https://img.shields.io/badge/version-3.
|
|
2
|
+
<img src="https://img.shields.io/badge/version-3.7.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">
|
package/dist/client/client.js
CHANGED
|
@@ -435,7 +435,12 @@ export class HilbrasClient {
|
|
|
435
435
|
_resolveProviderModel(params) {
|
|
436
436
|
// If explicit provider + model, use them directly
|
|
437
437
|
if (params.provider && params.model) {
|
|
438
|
-
return {
|
|
438
|
+
return {
|
|
439
|
+
providerName: params.provider,
|
|
440
|
+
modelId: params.model,
|
|
441
|
+
score: 0,
|
|
442
|
+
reasons: ["Explicit provider/model"],
|
|
443
|
+
};
|
|
439
444
|
}
|
|
440
445
|
// Auto-connect: structured output requirement → router capability filter
|
|
441
446
|
const needsStructured = params.needsStructuredOutput ?? params.hasOutput ?? false;
|
|
@@ -455,7 +460,12 @@ export class HilbrasClient {
|
|
|
455
460
|
throw new Error("No model found matching the given requirements. " +
|
|
456
461
|
"Try relaxing constraints or registering more providers.");
|
|
457
462
|
}
|
|
458
|
-
return {
|
|
463
|
+
return {
|
|
464
|
+
providerName: result.provider,
|
|
465
|
+
modelId: result.model,
|
|
466
|
+
score: result.score,
|
|
467
|
+
reasons: result.reasons,
|
|
468
|
+
};
|
|
459
469
|
}
|
|
460
470
|
// ─── Message Normalization ──────────────────────────────────────────────
|
|
461
471
|
_normalizeMessages(raw) {
|
|
@@ -472,12 +482,12 @@ export class HilbrasClient {
|
|
|
472
482
|
const startTime = performance.now();
|
|
473
483
|
this._emit({ type: "request.start", requestId, timestamp: startTime, provider: params.provider, model: params.model, task: params.task });
|
|
474
484
|
// Resolve provider + model — either explicit or via router
|
|
475
|
-
const { providerName, modelId } = this._resolveProviderModel(params);
|
|
485
|
+
const { providerName, modelId, score, reasons } = this._resolveProviderModel(params);
|
|
476
486
|
const providerConfig = this._registry.getOrThrow(providerName);
|
|
477
487
|
const model = providerConfig.models.find((m) => m.id === modelId);
|
|
478
488
|
if (!model)
|
|
479
489
|
throw new ModelNotFoundError(modelId, providerName, providerConfig.models.map((m) => m.id));
|
|
480
|
-
this._emit({ type: "routing.resolved", requestId, timestamp: performance.now(), provider: providerName, model: modelId, score
|
|
490
|
+
this._emit({ type: "routing.resolved", requestId, timestamp: performance.now(), provider: providerName, model: modelId, score, reasons });
|
|
481
491
|
const messages = this._normalizeMessages(params.messages);
|
|
482
492
|
const estimatedCost = this._budgetTracker.estimate(modelId, providerName, this._estimateTokens(messages.map((m) => m.content ?? "").join("")), 0);
|
|
483
493
|
yield* this._requestPipeline.runStream({
|
|
@@ -521,7 +531,7 @@ export class HilbrasClient {
|
|
|
521
531
|
}
|
|
522
532
|
const providerName = resolved_.providerName;
|
|
523
533
|
const modelId = resolved_.modelId;
|
|
524
|
-
this._emit({ type: "routing.resolved", requestId, timestamp: performance.now(), provider: providerName, model: modelId, score:
|
|
534
|
+
this._emit({ type: "routing.resolved", requestId, timestamp: performance.now(), provider: providerName, model: modelId, score: resolved_.score, reasons: resolved_.reasons });
|
|
525
535
|
if (!params.output) {
|
|
526
536
|
const messages = this._normalizeMessages(params.messages);
|
|
527
537
|
const estimatedCost = this._budgetTracker.estimate(modelId, providerName, this._estimateTokens(messages.map((m) => m.content ?? "").join("")), 0);
|
|
@@ -9,6 +9,33 @@ import { CircuitBreakerOpenError, ConfigurationError, ValidationError } from "..
|
|
|
9
9
|
import { calculateBackoff } from "../../reliability/backoff.js";
|
|
10
10
|
import { buildJsonSystemInstruction, buildRepairPrompt, extractJson } from "../../output/structured.js";
|
|
11
11
|
import { shouldRetry, shouldRetryNetworkError } from "../../reliability/retry.js";
|
|
12
|
+
const NETWORK_ERROR_CODES = new Set([
|
|
13
|
+
"ECONNREFUSED",
|
|
14
|
+
"ECONNRESET",
|
|
15
|
+
"ENOTFOUND",
|
|
16
|
+
"ENETUNREACH",
|
|
17
|
+
"ETIMEDOUT",
|
|
18
|
+
"EAI_AGAIN",
|
|
19
|
+
"EAI_FAIL",
|
|
20
|
+
"EAI_NONAME",
|
|
21
|
+
"EAI_SERVICE",
|
|
22
|
+
"ESOCKETTIMEDOUT",
|
|
23
|
+
]);
|
|
24
|
+
/**
|
|
25
|
+
* Best-effort detection of transport-level failures (DNS, connection,
|
|
26
|
+
* timeout, socket errors) so they are retried like network errors even
|
|
27
|
+
* when they surface as generic Errors rather than TypeErrors.
|
|
28
|
+
*/
|
|
29
|
+
function isNetworkFailure(error) {
|
|
30
|
+
if (error instanceof Error) {
|
|
31
|
+
const code = error.code;
|
|
32
|
+
if (typeof code === "string" && NETWORK_ERROR_CODES.has(code))
|
|
33
|
+
return true;
|
|
34
|
+
if (/network|unreachable|connection|reset|refused|timed out|dns|resolve|socket/i.test(error.message))
|
|
35
|
+
return true;
|
|
36
|
+
}
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
12
39
|
export class RequestPipeline {
|
|
13
40
|
ports;
|
|
14
41
|
constructor(ports) {
|
|
@@ -33,6 +60,13 @@ export class RequestPipeline {
|
|
|
33
60
|
}
|
|
34
61
|
let attempt = 0;
|
|
35
62
|
let primaryError;
|
|
63
|
+
let budgetReleased = false;
|
|
64
|
+
const releaseBudget = () => {
|
|
65
|
+
if (!budgetReleased) {
|
|
66
|
+
this.ports.budget.release(input.requestId);
|
|
67
|
+
budgetReleased = true;
|
|
68
|
+
}
|
|
69
|
+
};
|
|
36
70
|
for (;;) {
|
|
37
71
|
const result = await this.ports.executor.executeComplete(prepared, input.params, { dispose: false, recordCircuitFailure: false });
|
|
38
72
|
if (result.ok) {
|
|
@@ -57,7 +91,8 @@ export class RequestPipeline {
|
|
|
57
91
|
}
|
|
58
92
|
const status = primaryError.status;
|
|
59
93
|
const isNetworkError = primaryError instanceof TypeError
|
|
60
|
-
|| (primaryError instanceof Error && primaryError.name === "AbortError")
|
|
94
|
+
|| (primaryError instanceof Error && primaryError.name === "AbortError")
|
|
95
|
+
|| isNetworkFailure(primaryError);
|
|
61
96
|
const canRetry = (isNetworkError && shouldRetryNetworkError(attempt, prepared.retryConfig))
|
|
62
97
|
|| (typeof status === "number" && shouldRetry(status, attempt, prepared.retryConfig));
|
|
63
98
|
if (canRetry) {
|
|
@@ -82,7 +117,7 @@ export class RequestPipeline {
|
|
|
82
117
|
continue;
|
|
83
118
|
}
|
|
84
119
|
if (prepared.context.policy.allowFallback) {
|
|
85
|
-
|
|
120
|
+
releaseBudget();
|
|
86
121
|
const attemptedModels = [input.model];
|
|
87
122
|
const fallbacks = input.fallbackCandidates(attemptedModels);
|
|
88
123
|
for (const fallback of fallbacks) {
|
|
@@ -128,8 +163,7 @@ export class RequestPipeline {
|
|
|
128
163
|
}
|
|
129
164
|
}
|
|
130
165
|
catch (error) {
|
|
131
|
-
|
|
132
|
-
primaryError = error;
|
|
166
|
+
primaryError = error;
|
|
133
167
|
}
|
|
134
168
|
finally {
|
|
135
169
|
fallbackPrepared?.dispose();
|
|
@@ -142,7 +176,7 @@ export class RequestPipeline {
|
|
|
142
176
|
break;
|
|
143
177
|
}
|
|
144
178
|
this.recordTerminalFailure(prepared, primaryError);
|
|
145
|
-
|
|
179
|
+
releaseBudget();
|
|
146
180
|
const error = primaryError instanceof Error ? primaryError : new Error(String(primaryError));
|
|
147
181
|
this.ports.emit({
|
|
148
182
|
type: "request.failed",
|
|
@@ -154,14 +188,19 @@ export class RequestPipeline {
|
|
|
154
188
|
attempts: attempt + 1,
|
|
155
189
|
error: error.message,
|
|
156
190
|
});
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
191
|
+
try {
|
|
192
|
+
await this.ports.plugins.fireError({
|
|
193
|
+
requestId: input.requestId,
|
|
194
|
+
provider: input.provider,
|
|
195
|
+
model: input.model,
|
|
196
|
+
error,
|
|
197
|
+
durationMs: this.ports.now() - input.startTime,
|
|
198
|
+
attempts: attempt + 1,
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
// Swallow plugin hook failures so the original request error is still surfaced.
|
|
203
|
+
}
|
|
165
204
|
throw primaryError;
|
|
166
205
|
}
|
|
167
206
|
finally {
|
|
@@ -176,6 +215,14 @@ export class RequestPipeline {
|
|
|
176
215
|
let firstChunkEmitted = false;
|
|
177
216
|
let attempt = 0;
|
|
178
217
|
let primaryError;
|
|
218
|
+
let budgetReleased = false;
|
|
219
|
+
const releaseMainBudget = () => {
|
|
220
|
+
if (!budgetReleased) {
|
|
221
|
+
this.ports.budget.release(input.requestId);
|
|
222
|
+
budgetReleased = true;
|
|
223
|
+
}
|
|
224
|
+
reservationActive = false;
|
|
225
|
+
};
|
|
179
226
|
try {
|
|
180
227
|
await this.ports.plugins.fireRequest({
|
|
181
228
|
requestId: input.requestId,
|
|
@@ -237,6 +284,7 @@ export class RequestPipeline {
|
|
|
237
284
|
attempts: attempt + 1,
|
|
238
285
|
inputTokens,
|
|
239
286
|
outputTokens,
|
|
287
|
+
estimatedCost: input.estimatedCost,
|
|
240
288
|
structuredOutput: false,
|
|
241
289
|
});
|
|
242
290
|
await this.ports.plugins.fireResponse({
|
|
@@ -255,10 +303,7 @@ export class RequestPipeline {
|
|
|
255
303
|
const callerAborted = input.callerSignal?.aborted === true;
|
|
256
304
|
const internalTimeout = prepared.signal?.aborted === true;
|
|
257
305
|
if (callerAborted || firstChunkEmitted || internalTimeout) {
|
|
258
|
-
|
|
259
|
-
this.ports.budget.release(input.requestId);
|
|
260
|
-
reservationActive = false;
|
|
261
|
-
}
|
|
306
|
+
releaseMainBudget();
|
|
262
307
|
const terminalError = error instanceof Error ? error : new Error(String(error));
|
|
263
308
|
this.recordTerminalFailure(prepared, terminalError);
|
|
264
309
|
this.ports.emit({
|
|
@@ -271,25 +316,30 @@ export class RequestPipeline {
|
|
|
271
316
|
attempts: attempt + 1,
|
|
272
317
|
error: terminalError.message,
|
|
273
318
|
});
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
319
|
+
try {
|
|
320
|
+
await this.ports.plugins.fireError({
|
|
321
|
+
requestId: input.requestId,
|
|
322
|
+
provider: input.provider,
|
|
323
|
+
model: input.model,
|
|
324
|
+
error: terminalError,
|
|
325
|
+
durationMs: this.ports.now() - input.startTime,
|
|
326
|
+
attempts: attempt + 1,
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
catch {
|
|
330
|
+
// Swallow plugin hook failures so the original stream error is still surfaced.
|
|
331
|
+
}
|
|
282
332
|
throw error;
|
|
283
333
|
}
|
|
284
334
|
const status = error.status;
|
|
285
335
|
const isNetworkError = error instanceof TypeError
|
|
286
|
-
|| (error instanceof Error && error.name === "AbortError")
|
|
336
|
+
|| (error instanceof Error && error.name === "AbortError")
|
|
337
|
+
|| isNetworkFailure(error);
|
|
287
338
|
const canRetry = (isNetworkError && shouldRetryNetworkError(attempt, prepared.retryConfig))
|
|
288
339
|
|| (typeof status === "number" && shouldRetry(status, attempt, prepared.retryConfig));
|
|
289
340
|
if (!canRetry) {
|
|
290
341
|
if (prepared.context.policy.allowFallback) {
|
|
291
|
-
|
|
292
|
-
reservationActive = false;
|
|
342
|
+
releaseMainBudget();
|
|
293
343
|
const attemptedModels = [input.model];
|
|
294
344
|
const fallbacks = input.fallbackCandidates(attemptedModels);
|
|
295
345
|
for (const fallback of fallbacks) {
|
|
@@ -313,7 +363,6 @@ export class RequestPipeline {
|
|
|
313
363
|
if (!fallbackReservation)
|
|
314
364
|
continue;
|
|
315
365
|
let fallbackPrepared;
|
|
316
|
-
let fallbackVisible = false;
|
|
317
366
|
let fallbackInputTokens;
|
|
318
367
|
let fallbackOutputTokens;
|
|
319
368
|
let fallbackReservationActive = true;
|
|
@@ -327,7 +376,6 @@ export class RequestPipeline {
|
|
|
327
376
|
providerTimeoutMs: 0,
|
|
328
377
|
}, "stream");
|
|
329
378
|
for await (const chunk of this.ports.executor.executeStream(fallbackPrepared, { ...input.params, model: fallback.model }, { recordCircuitFailure: false })) {
|
|
330
|
-
fallbackVisible = true;
|
|
331
379
|
if (chunk.type === "usage") {
|
|
332
380
|
fallbackInputTokens = chunk.inputTokens;
|
|
333
381
|
fallbackOutputTokens = chunk.outputTokens;
|
|
@@ -361,6 +409,7 @@ export class RequestPipeline {
|
|
|
361
409
|
attempts: attempt + 2,
|
|
362
410
|
inputTokens: fallbackInputTokens,
|
|
363
411
|
outputTokens: fallbackOutputTokens,
|
|
412
|
+
estimatedCost: input.estimatedCost,
|
|
364
413
|
structuredOutput: false,
|
|
365
414
|
});
|
|
366
415
|
await this.ports.plugins.fireResponse({
|
|
@@ -375,10 +424,7 @@ export class RequestPipeline {
|
|
|
375
424
|
return;
|
|
376
425
|
}
|
|
377
426
|
catch (fallbackError) {
|
|
378
|
-
|
|
379
|
-
primaryError = fallbackError;
|
|
380
|
-
break;
|
|
381
|
-
}
|
|
427
|
+
primaryError = fallbackError;
|
|
382
428
|
}
|
|
383
429
|
finally {
|
|
384
430
|
fallbackPrepared?.dispose();
|
|
@@ -391,10 +437,7 @@ export class RequestPipeline {
|
|
|
391
437
|
}
|
|
392
438
|
}
|
|
393
439
|
if (!canRetry) {
|
|
394
|
-
|
|
395
|
-
this.ports.budget.release(input.requestId);
|
|
396
|
-
reservationActive = false;
|
|
397
|
-
}
|
|
440
|
+
releaseMainBudget();
|
|
398
441
|
const terminalError = primaryError instanceof Error ? primaryError : new Error(String(primaryError));
|
|
399
442
|
this.recordTerminalFailure(prepared, terminalError);
|
|
400
443
|
this.ports.emit({
|
|
@@ -407,14 +450,19 @@ export class RequestPipeline {
|
|
|
407
450
|
attempts: attempt + 1,
|
|
408
451
|
error: terminalError.message,
|
|
409
452
|
});
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
453
|
+
try {
|
|
454
|
+
await this.ports.plugins.fireError({
|
|
455
|
+
requestId: input.requestId,
|
|
456
|
+
provider: input.provider,
|
|
457
|
+
model: input.model,
|
|
458
|
+
error: terminalError,
|
|
459
|
+
durationMs: this.ports.now() - input.startTime,
|
|
460
|
+
attempts: attempt + 1,
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
catch {
|
|
464
|
+
// Swallow plugin hook failures so the original stream error is still surfaced.
|
|
465
|
+
}
|
|
418
466
|
throw primaryError;
|
|
419
467
|
}
|
|
420
468
|
const delay = calculateBackoff(attempt, prepared.context.policy.backoff);
|
|
@@ -431,10 +479,7 @@ export class RequestPipeline {
|
|
|
431
479
|
await this.ports.sleep(delay, input.callerSignal);
|
|
432
480
|
}
|
|
433
481
|
catch (sleepError) {
|
|
434
|
-
|
|
435
|
-
this.ports.budget.release(input.requestId);
|
|
436
|
-
reservationActive = false;
|
|
437
|
-
}
|
|
482
|
+
releaseMainBudget();
|
|
438
483
|
const terminalError = sleepError instanceof Error ? sleepError : new Error(String(sleepError));
|
|
439
484
|
this.recordTerminalFailure(prepared, terminalError);
|
|
440
485
|
this.ports.emit({
|
|
@@ -447,14 +492,19 @@ export class RequestPipeline {
|
|
|
447
492
|
attempts: attempt + 1,
|
|
448
493
|
error: terminalError.message,
|
|
449
494
|
});
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
495
|
+
try {
|
|
496
|
+
await this.ports.plugins.fireError({
|
|
497
|
+
requestId: input.requestId,
|
|
498
|
+
provider: input.provider,
|
|
499
|
+
model: input.model,
|
|
500
|
+
error: terminalError,
|
|
501
|
+
durationMs: this.ports.now() - input.startTime,
|
|
502
|
+
attempts: attempt + 1,
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
catch {
|
|
506
|
+
// Swallow plugin hook failures so the original stream error is still surfaced.
|
|
507
|
+
}
|
|
458
508
|
throw sleepError;
|
|
459
509
|
}
|
|
460
510
|
attempt++;
|
|
@@ -462,8 +512,7 @@ export class RequestPipeline {
|
|
|
462
512
|
}
|
|
463
513
|
}
|
|
464
514
|
finally {
|
|
465
|
-
|
|
466
|
-
this.ports.budget.release(input.requestId);
|
|
515
|
+
releaseMainBudget();
|
|
467
516
|
prepared.dispose();
|
|
468
517
|
}
|
|
469
518
|
}
|
|
@@ -495,6 +544,13 @@ export class RequestPipeline {
|
|
|
495
544
|
};
|
|
496
545
|
let attempt = 0;
|
|
497
546
|
let primaryError;
|
|
547
|
+
let budgetReleased = false;
|
|
548
|
+
const releaseBudget = () => {
|
|
549
|
+
if (!budgetReleased) {
|
|
550
|
+
this.ports.budget.release(input.requestId);
|
|
551
|
+
budgetReleased = true;
|
|
552
|
+
}
|
|
553
|
+
};
|
|
498
554
|
for (;;) {
|
|
499
555
|
const result = await this.ports.executor.executeComplete(prepared, { ...input.params, messages: structuredMessages, extra: structuredExtra }, { dispose: false, recordCircuitFailure: false });
|
|
500
556
|
if (result.ok) {
|
|
@@ -545,7 +601,7 @@ export class RequestPipeline {
|
|
|
545
601
|
continue;
|
|
546
602
|
}
|
|
547
603
|
const validationError = new ValidationError(maxRepairAttempts + 1, validation.error, result.value, { requestId: input.requestId, model: input.model });
|
|
548
|
-
|
|
604
|
+
releaseBudget();
|
|
549
605
|
this.ports.emit({
|
|
550
606
|
type: "request.failed",
|
|
551
607
|
requestId: input.requestId,
|
|
@@ -630,7 +686,14 @@ export class RequestPipeline {
|
|
|
630
686
|
primaryError = fallbackResult.error;
|
|
631
687
|
}
|
|
632
688
|
if (fallbackResult.ok) {
|
|
633
|
-
|
|
689
|
+
let parsed;
|
|
690
|
+
try {
|
|
691
|
+
parsed = JSON.parse(extractJson(fallbackResult.value));
|
|
692
|
+
}
|
|
693
|
+
catch (error) {
|
|
694
|
+
primaryError = error;
|
|
695
|
+
break;
|
|
696
|
+
}
|
|
634
697
|
const validation = input.output.schema.safeParse(parsed);
|
|
635
698
|
if (validation.success) {
|
|
636
699
|
this.ports.budget.settle(fallbackId, fallbackCost, {
|
|
@@ -651,8 +714,7 @@ export class RequestPipeline {
|
|
|
651
714
|
}
|
|
652
715
|
}
|
|
653
716
|
catch (error) {
|
|
654
|
-
|
|
655
|
-
primaryError = error;
|
|
717
|
+
primaryError = error;
|
|
656
718
|
}
|
|
657
719
|
finally {
|
|
658
720
|
fallbackPrepared?.dispose();
|
|
@@ -665,7 +727,7 @@ export class RequestPipeline {
|
|
|
665
727
|
break;
|
|
666
728
|
}
|
|
667
729
|
this.recordTerminalFailure(prepared, primaryError);
|
|
668
|
-
|
|
730
|
+
releaseBudget();
|
|
669
731
|
const error = primaryError instanceof Error ? primaryError : new Error(String(primaryError));
|
|
670
732
|
this.ports.emit({
|
|
671
733
|
type: "request.failed",
|
|
@@ -677,14 +739,19 @@ export class RequestPipeline {
|
|
|
677
739
|
attempts: attempt + 1,
|
|
678
740
|
error: error.message,
|
|
679
741
|
});
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
742
|
+
try {
|
|
743
|
+
await this.ports.plugins.fireError({
|
|
744
|
+
requestId: input.requestId,
|
|
745
|
+
provider: input.provider,
|
|
746
|
+
model: input.model,
|
|
747
|
+
error,
|
|
748
|
+
durationMs: this.ports.now() - input.startTime,
|
|
749
|
+
attempts: attempt + 1,
|
|
750
|
+
});
|
|
751
|
+
}
|
|
752
|
+
catch {
|
|
753
|
+
// Swallow plugin hook failures so the original request error is still surfaced.
|
|
754
|
+
}
|
|
688
755
|
throw primaryError;
|
|
689
756
|
}
|
|
690
757
|
finally {
|
|
@@ -724,6 +791,7 @@ export class RequestPipeline {
|
|
|
724
791
|
model,
|
|
725
792
|
durationMs: this.ports.now() - input.startTime,
|
|
726
793
|
attempts,
|
|
794
|
+
estimatedCost: input.estimatedCost,
|
|
727
795
|
structuredOutput,
|
|
728
796
|
});
|
|
729
797
|
}
|
|
@@ -33,7 +33,7 @@ export class PlanAndExecuteAgent {
|
|
|
33
33
|
* Run the plan-and-execute agent.
|
|
34
34
|
*/
|
|
35
35
|
async run(initialPrompt) {
|
|
36
|
-
const { tools, maxSteps = 10, budget = null, systemPrompt = PLAN_SYSTEM_PROMPT,
|
|
36
|
+
const { tools, maxSteps = 10, budget = null, systemPrompt = PLAN_SYSTEM_PROMPT, signal, llm, costEstimator, onApproval, onEvent, replanOnFailure = true, } = this._config;
|
|
37
37
|
const effectiveLLM = llm ?? (() => { throw new Error("No LLM function provided. Pass llm() in PlanAndExecuteAgentConfig."); });
|
|
38
38
|
const effectiveCost = costEstimator ?? (() => 0);
|
|
39
39
|
const steps = [];
|
|
@@ -31,7 +31,7 @@ export class ReActAgent {
|
|
|
31
31
|
* Run the ReAct agent loop.
|
|
32
32
|
*/
|
|
33
33
|
async run(initialPrompt) {
|
|
34
|
-
const { tools, maxSteps = 10, budget = null, systemPrompt = REACT_SYSTEM_PROMPT,
|
|
34
|
+
const { tools, maxSteps = 10, budget = null, systemPrompt = REACT_SYSTEM_PROMPT, signal, llm, costEstimator, onApproval, onEvent, } = this._config;
|
|
35
35
|
const effectiveLLM = llm ?? (() => { throw new Error("No LLM function provided. Pass llm() in ReActAgentConfig."); });
|
|
36
36
|
const effectiveCost = costEstimator ?? (() => 0);
|
|
37
37
|
const steps = [];
|
|
@@ -23,7 +23,7 @@ function defaultCostEstimator(usage, model) {
|
|
|
23
23
|
const p = pricing[model] ?? { input: 3, output: 15 };
|
|
24
24
|
return (usage.promptTokens * p.input + usage.completionTokens * p.output) / 1_000_000;
|
|
25
25
|
}
|
|
26
|
-
function defaultLLM(
|
|
26
|
+
function defaultLLM() {
|
|
27
27
|
throw new Error("No LLM function provided. Pass llm() in ToolLoopAgentConfig.");
|
|
28
28
|
}
|
|
29
29
|
export class ToolLoopAgent {
|
|
@@ -15,4 +15,4 @@ export interface Signal<T> {
|
|
|
15
15
|
}
|
|
16
16
|
export declare function signal<T>(initialValue: T): WritableSignal<T>;
|
|
17
17
|
export declare function computed<T>(fn: () => T): Signal<T>;
|
|
18
|
-
export declare function Injectable(
|
|
18
|
+
export declare function Injectable(): ClassDecorator;
|
|
@@ -66,7 +66,7 @@ export class ServerHilbrasClient {
|
|
|
66
66
|
* response. Removed in 4.0.0 — see the module deprecation notice.
|
|
67
67
|
*/
|
|
68
68
|
async streamResponse(params) {
|
|
69
|
-
const { messages,
|
|
69
|
+
const { messages, systemPrompt } = params;
|
|
70
70
|
const allMessages = systemPrompt
|
|
71
71
|
? [{ role: "system", content: systemPrompt }, ...messages]
|
|
72
72
|
: messages;
|
|
@@ -14,7 +14,7 @@ function generateId() {
|
|
|
14
14
|
return `msg_${Date.now()}_${_idCounter++}`;
|
|
15
15
|
}
|
|
16
16
|
export function useChat(options) {
|
|
17
|
-
const { api, initialMessages = [], provider, model, onFinish, onError, headers = {}, body = {}, maxSteps = 1, onToolCall,
|
|
17
|
+
const { api, initialMessages = [], provider, model, onFinish, onError, headers = {}, body = {}, maxSteps = 1, onToolCall, } = options;
|
|
18
18
|
const state = {
|
|
19
19
|
messages: [...initialMessages],
|
|
20
20
|
input: "",
|
|
@@ -11,7 +11,7 @@ function generateId() {
|
|
|
11
11
|
return `msg_${Date.now()}_${_idCounter++}`;
|
|
12
12
|
}
|
|
13
13
|
export function useChat(options) {
|
|
14
|
-
const { api, initialMessages = [], provider, model, onFinish, onError, headers = {}, body = {}, maxSteps = 1, onToolCall,
|
|
14
|
+
const { api, initialMessages = [], provider, model, onFinish, onError, headers = {}, body = {}, maxSteps = 1, onToolCall, } = options;
|
|
15
15
|
const messages = ref([...initialMessages]);
|
|
16
16
|
const input = ref("");
|
|
17
17
|
const isLoading = ref(false);
|
|
@@ -80,8 +80,14 @@ export interface SecurityAuditEntry extends AuditBase {
|
|
|
80
80
|
/** Security event type */
|
|
81
81
|
eventType: "ssrf_blocked" | "rate_limit" | "circuit_breaker" | "invalid_input" | "pii_detected" | "custom";
|
|
82
82
|
}
|
|
83
|
+
/** Error audit entry */
|
|
84
|
+
export interface ErrorAuditEntry extends AuditBase {
|
|
85
|
+
category: "error";
|
|
86
|
+
/** The error message */
|
|
87
|
+
error: string;
|
|
88
|
+
}
|
|
83
89
|
/** Union of all audit entry types */
|
|
84
|
-
export type AuditEntry = AuthAuditEntry | DataAccessAuditEntry | ConfigChangeAuditEntry | SecurityAuditEntry;
|
|
90
|
+
export type AuditEntry = AuthAuditEntry | DataAccessAuditEntry | ConfigChangeAuditEntry | SecurityAuditEntry | ErrorAuditEntry;
|
|
85
91
|
/** Configuration for the audit logger */
|
|
86
92
|
export interface AuditLoggerConfig {
|
|
87
93
|
/** Service name included in every entry */
|
|
@@ -26,13 +26,16 @@ function generateEventId() {
|
|
|
26
26
|
const cnt = _eventCounter.toString(36).padStart(4, "0");
|
|
27
27
|
return `audit_${ts}_${cnt}`;
|
|
28
28
|
}
|
|
29
|
-
function cloneValue(value) {
|
|
29
|
+
function cloneValue(value, seen = new WeakSet()) {
|
|
30
30
|
if (Array.isArray(value))
|
|
31
|
-
return value.map((item) => cloneValue(item));
|
|
31
|
+
return value.map((item) => cloneValue(item, seen));
|
|
32
32
|
if (value && typeof value === "object") {
|
|
33
|
+
if (seen.has(value))
|
|
34
|
+
return value; // circular reference — stop recursing
|
|
35
|
+
seen.add(value);
|
|
33
36
|
const result = {};
|
|
34
37
|
for (const [key, item] of Object.entries(value))
|
|
35
|
-
result[key] = cloneValue(item);
|
|
38
|
+
result[key] = cloneValue(item, seen);
|
|
36
39
|
return result;
|
|
37
40
|
}
|
|
38
41
|
return value;
|
|
@@ -100,8 +103,7 @@ export class AuditLogger {
|
|
|
100
103
|
logError(event) {
|
|
101
104
|
const entry = {
|
|
102
105
|
...this._base("error", "critical", event.action, event),
|
|
103
|
-
|
|
104
|
-
reason: event.error,
|
|
106
|
+
error: event.error,
|
|
105
107
|
};
|
|
106
108
|
this._emit(entry);
|
|
107
109
|
}
|
|
@@ -26,9 +26,27 @@ const PII_PATTERNS = {
|
|
|
26
26
|
credit_card: /\b(?:4\d{3}|5[1-5]\d{2}|3[47]\d{2}|6(?:011|5\d{2}))[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b/g,
|
|
27
27
|
ip_address: /\b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\b/g,
|
|
28
28
|
uk_nhs: /\b\d{3}\s?\d{3}\s?\d{4}\b/g,
|
|
29
|
-
|
|
29
|
+
// Unrolled: IBANs are at most 34 chars (2+2+7*4+4). Nested quantifiers like
|
|
30
|
+
// ([\dA-Z]{4}[\s]?){1,7} followed by [\dA-Z]{1,4} are ReDoS-vulnerable, so
|
|
31
|
+
// the repeating group is written out explicitly instead.
|
|
32
|
+
eu_iban: /\b[A-Z]{2}\d{2}[\s]?[\dA-Z]{4}[\s]?[\dA-Z]{4}[\s]?[\dA-Z]{4}[\s]?[\dA-Z]{4}[\s]?[\dA-Z]{4}[\s]?[\dA-Z]{4}[\s]?[\dA-Z]{4}[\s]?[\dA-Z]{1,4}\b/g,
|
|
30
33
|
custom: /(?!.)/, // Never matches — placeholder
|
|
31
34
|
};
|
|
35
|
+
/** Validate an NHS number with the MOD 11 check-digit algorithm. */
|
|
36
|
+
function isValidUkNhs(value) {
|
|
37
|
+
const digits = value.replace(/\s/g, "");
|
|
38
|
+
if (!/^\d{10}$/.test(digits))
|
|
39
|
+
return false;
|
|
40
|
+
let sum = 0;
|
|
41
|
+
for (let i = 0; i < 9; i += 1)
|
|
42
|
+
sum += Number(digits[i]) * (10 - i);
|
|
43
|
+
const remainder = sum % 11;
|
|
44
|
+
if (remainder === 0)
|
|
45
|
+
return Number(digits[9]) === 0;
|
|
46
|
+
if (remainder === 1)
|
|
47
|
+
return false; // check digit would be 10 — invalid
|
|
48
|
+
return Number(digits[9]) === 11 - remainder;
|
|
49
|
+
}
|
|
32
50
|
/** Mask a value by keeping first and last characters */
|
|
33
51
|
function maskValue(value) {
|
|
34
52
|
if (value.length <= 4)
|
|
@@ -71,6 +89,8 @@ export function detectPii(text, config) {
|
|
|
71
89
|
re.lastIndex++;
|
|
72
90
|
continue;
|
|
73
91
|
}
|
|
92
|
+
if (type === "uk_nhs" && !isValidUkNhs(m[0]))
|
|
93
|
+
continue;
|
|
74
94
|
matches.push({
|
|
75
95
|
type,
|
|
76
96
|
value: m[0],
|
|
@@ -56,6 +56,8 @@ export declare class RateLimiter {
|
|
|
56
56
|
private _tokens;
|
|
57
57
|
private _lastRefill;
|
|
58
58
|
constructor(config?: RateLimiterConfig);
|
|
59
|
+
/** `true` when the bucket never refills (refillRate of 0 or negative). */
|
|
60
|
+
get _isStaticBucket(): boolean;
|
|
59
61
|
/** Current token count (refills on access) */
|
|
60
62
|
get tokens(): number;
|
|
61
63
|
/**
|
|
@@ -41,6 +41,10 @@ export class RateLimiter {
|
|
|
41
41
|
this._tokens = this._maxTokens;
|
|
42
42
|
this._lastRefill = Date.now();
|
|
43
43
|
}
|
|
44
|
+
/** `true` when the bucket never refills (refillRate of 0 or negative). */
|
|
45
|
+
get _isStaticBucket() {
|
|
46
|
+
return !Number.isFinite(this._refillRate) || this._refillRate <= 0;
|
|
47
|
+
}
|
|
44
48
|
/** Current token count (refills on access) */
|
|
45
49
|
get tokens() {
|
|
46
50
|
this._refill();
|
|
@@ -57,7 +61,10 @@ export class RateLimiter {
|
|
|
57
61
|
return { allowed: true, retryAfterMs: 0 };
|
|
58
62
|
}
|
|
59
63
|
const deficit = tokensNeeded - this._tokens;
|
|
60
|
-
|
|
64
|
+
// A rate of 0 (or negative) means the bucket never refills, so a request
|
|
65
|
+
// that cannot be afforded now will never become affordable. Division by
|
|
66
|
+
// zero would otherwise yield Infinity/NaN retry-after values.
|
|
67
|
+
const retryAfterMs = this._isStaticBucket ? Infinity : Math.ceil((deficit / this._refillRate) * 1000);
|
|
61
68
|
return { allowed: false, retryAfterMs };
|
|
62
69
|
}
|
|
63
70
|
/**
|
package/dist/security/rbac.js
CHANGED
|
@@ -116,7 +116,7 @@ export function createRBACMiddleware(config, getUserId, options) {
|
|
|
116
116
|
if (roleName === null)
|
|
117
117
|
roleName = config.defaultRole ?? "default";
|
|
118
118
|
const role = config.roles?.[roleName] ?? null;
|
|
119
|
-
if (
|
|
119
|
+
if (role === null) {
|
|
120
120
|
report({
|
|
121
121
|
code: "RBAC_UNRESOLVED_ROLE",
|
|
122
122
|
message: `role "${roleName}" is not defined in the configured roles`,
|
|
@@ -203,7 +203,7 @@ export function createRBACMiddleware(config, getUserId, options) {
|
|
|
203
203
|
report,
|
|
204
204
|
});
|
|
205
205
|
if (verdict.allow)
|
|
206
|
-
return ctx.next();
|
|
206
|
+
return await ctx.next();
|
|
207
207
|
auditLogger?.logSecurity({
|
|
208
208
|
eventType: "custom",
|
|
209
209
|
action: "rbac_denied",
|
|
@@ -78,6 +78,8 @@ export interface SignedRequest {
|
|
|
78
78
|
*/
|
|
79
79
|
export declare class RequestSigner {
|
|
80
80
|
private _config;
|
|
81
|
+
/** Lazily created default replay guard, so `verifyFresh` calls without a `guard` share one persistent seen-signature cache. */
|
|
82
|
+
private _defaultGuard?;
|
|
81
83
|
constructor(config: RequestSignerConfig);
|
|
82
84
|
/** The active wire-format profile. */
|
|
83
85
|
get profile(): SignatureProfile;
|
|
@@ -56,6 +56,8 @@ function isByteBody(body) {
|
|
|
56
56
|
*/
|
|
57
57
|
export class RequestSigner {
|
|
58
58
|
_config;
|
|
59
|
+
/** Lazily created default replay guard, so `verifyFresh` calls without a `guard` share one persistent seen-signature cache. */
|
|
60
|
+
_defaultGuard;
|
|
59
61
|
constructor(config) {
|
|
60
62
|
this._config = {
|
|
61
63
|
secret: config.secret,
|
|
@@ -204,7 +206,7 @@ export class RequestSigner {
|
|
|
204
206
|
const signatureOk = this.verify(url, request, receivedSignature);
|
|
205
207
|
if (!signatureOk)
|
|
206
208
|
return { valid: false, reason: "signature does not match" };
|
|
207
|
-
const freshness = (guard ?? new ReplayGuard(guardOptions)).verify(request.headers, receivedSignature);
|
|
209
|
+
const freshness = (guard ?? (this._defaultGuard ??= new ReplayGuard(guardOptions))).verify(request.headers, receivedSignature);
|
|
208
210
|
if (!freshness.valid)
|
|
209
211
|
return { valid: false, reason: freshness.reason };
|
|
210
212
|
return { valid: true };
|
|
@@ -54,7 +54,7 @@ export declare function validateBaseUrl(url: string, options?: UrlGuardOptions):
|
|
|
54
54
|
* for this string-level guard. This function covers the case where the
|
|
55
55
|
* initial resolution itself yields a private/blocked address.
|
|
56
56
|
*/
|
|
57
|
-
export declare function validateResolvedAddress(ip: string
|
|
57
|
+
export declare function validateResolvedAddress(ip: string): UrlGuardResult;
|
|
58
58
|
/**
|
|
59
59
|
* Perform all SSRF checks and return a result suitable for passing to the
|
|
60
60
|
* transport layer.
|
|
@@ -59,8 +59,9 @@ function normalizeIpLiteral(host) {
|
|
|
59
59
|
return `${(num >>> 24) & 0xff}.${(num >>> 16) & 0xff}.${(num >>> 8) & 0xff}.${num & 0xff}`;
|
|
60
60
|
}
|
|
61
61
|
}
|
|
62
|
-
// Octal: 0177.0.0.1 or 017700000001 —
|
|
63
|
-
|
|
62
|
+
// Octal: 0177.0.0.1 or 017700000001 — each octet must contain only octal digits (0-7);
|
|
63
|
+
// "08" and "09" are not valid octal and must not be misparsed as decimal.
|
|
64
|
+
if (/^(?:0[0-7]{1,3}\.){3}0?[0-7]{1,3}$/.test(host)) {
|
|
64
65
|
const parts = host.split(".");
|
|
65
66
|
const decimal = parts.map((p) => parseInt(p, 8));
|
|
66
67
|
if (decimal.every((p) => p >= 0 && p <= 255)) {
|
|
@@ -387,7 +388,7 @@ export function validateBaseUrl(url, options = {}) {
|
|
|
387
388
|
* for this string-level guard. This function covers the case where the
|
|
388
389
|
* initial resolution itself yields a private/blocked address.
|
|
389
390
|
*/
|
|
390
|
-
export function validateResolvedAddress(ip
|
|
391
|
+
export function validateResolvedAddress(ip) {
|
|
391
392
|
const normalized = normalizeIpLiteral(ip);
|
|
392
393
|
if (!normalized) {
|
|
393
394
|
// Not an IP literal — nothing to check at this level.
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
* // Or use the built-in hook adapter
|
|
16
16
|
* otel.instrumentClient(client);
|
|
17
17
|
*/
|
|
18
|
-
import type { HookEvent, RequestCompletedEvent, RequestFailedEvent, RetryEvent } from "../types/observability.js";
|
|
18
|
+
import type { CircuitBreakerOpenEvent, HookEvent, RequestCompletedEvent, RequestFailedEvent, RetryEvent, RoutingResolvedEvent } from "../types/observability.js";
|
|
19
19
|
/** Configuration for the OpenTelemetry exporter */
|
|
20
20
|
export interface OpenTelemetryConfig {
|
|
21
21
|
/** Service name for traces and metrics */
|
|
@@ -40,6 +40,7 @@ export declare class OpenTelemetryExporter {
|
|
|
40
40
|
private _requestCount?;
|
|
41
41
|
private _errorCount?;
|
|
42
42
|
private _tokenUsage?;
|
|
43
|
+
private _cost?;
|
|
43
44
|
private _activeRequests?;
|
|
44
45
|
private _retryCount?;
|
|
45
46
|
constructor(config?: OpenTelemetryConfig);
|
|
@@ -50,6 +51,10 @@ export declare class OpenTelemetryExporter {
|
|
|
50
51
|
recordError(event: RequestFailedEvent): void;
|
|
51
52
|
/** Record a retry event */
|
|
52
53
|
recordRetry(event: RetryEvent): void;
|
|
54
|
+
/** Record a routing decision */
|
|
55
|
+
recordRouting(event: RoutingResolvedEvent): void;
|
|
56
|
+
/** Record a circuit breaker opening */
|
|
57
|
+
recordCircuitBreakerOpen(event: CircuitBreakerOpenEvent): void;
|
|
53
58
|
/** Record active request count */
|
|
54
59
|
recordActiveRequests(count: number): void;
|
|
55
60
|
/**
|
|
@@ -41,6 +41,7 @@ export class OpenTelemetryExporter {
|
|
|
41
41
|
_requestCount;
|
|
42
42
|
_errorCount;
|
|
43
43
|
_tokenUsage;
|
|
44
|
+
_cost;
|
|
44
45
|
_activeRequests;
|
|
45
46
|
_retryCount;
|
|
46
47
|
constructor(config) {
|
|
@@ -76,6 +77,9 @@ export class OpenTelemetryExporter {
|
|
|
76
77
|
this._tokenUsage = this._meter.createHistogram("llm.tokens", {
|
|
77
78
|
description: "Token usage per request",
|
|
78
79
|
});
|
|
80
|
+
this._cost = this._meter.createHistogram("llm.cost", {
|
|
81
|
+
description: "Estimated cost per request in USD",
|
|
82
|
+
});
|
|
79
83
|
this._activeRequests = this._meter.createGauge("llm.requests.active", {
|
|
80
84
|
description: "Number of currently active LLM requests",
|
|
81
85
|
});
|
|
@@ -98,6 +102,9 @@ export class OpenTelemetryExporter {
|
|
|
98
102
|
if (event.outputTokens) {
|
|
99
103
|
this._tokenUsage?.record(event.outputTokens, { ...attrs, token_type: "output" });
|
|
100
104
|
}
|
|
105
|
+
if (event.estimatedCost != null) {
|
|
106
|
+
this._cost?.record(event.estimatedCost, attrs);
|
|
107
|
+
}
|
|
101
108
|
// Trace span
|
|
102
109
|
if (this._tracer) {
|
|
103
110
|
const span = this._tracer.startSpan(`llm.complete`);
|
|
@@ -108,6 +115,8 @@ export class OpenTelemetryExporter {
|
|
|
108
115
|
span.setAttribute("llm.input_tokens", event.inputTokens);
|
|
109
116
|
if (event.outputTokens)
|
|
110
117
|
span.setAttribute("llm.output_tokens", event.outputTokens);
|
|
118
|
+
if (event.estimatedCost != null)
|
|
119
|
+
span.setAttribute("llm.estimated_cost", event.estimatedCost);
|
|
111
120
|
span.setStatus({ code: 0 }); // OK
|
|
112
121
|
span.end();
|
|
113
122
|
}
|
|
@@ -137,6 +146,28 @@ export class OpenTelemetryExporter {
|
|
|
137
146
|
reason: event.reason,
|
|
138
147
|
});
|
|
139
148
|
}
|
|
149
|
+
/** Record a routing decision */
|
|
150
|
+
recordRouting(event) {
|
|
151
|
+
if (!this._tracer)
|
|
152
|
+
return;
|
|
153
|
+
const span = this._tracer.startSpan(`llm.route`);
|
|
154
|
+
span.setAttribute("llm.provider", event.provider);
|
|
155
|
+
span.setAttribute("llm.model", event.model);
|
|
156
|
+
span.setAttribute("llm.routing.score", event.score);
|
|
157
|
+
span.setAttribute("llm.routing.reasons", event.reasons.join("; "));
|
|
158
|
+
span.setStatus({ code: 0 }); // OK
|
|
159
|
+
span.end();
|
|
160
|
+
}
|
|
161
|
+
/** Record a circuit breaker opening */
|
|
162
|
+
recordCircuitBreakerOpen(event) {
|
|
163
|
+
if (!this._tracer)
|
|
164
|
+
return;
|
|
165
|
+
const span = this._tracer.startSpan(`llm.circuit_breaker`);
|
|
166
|
+
span.setAttribute("llm.provider", event.provider);
|
|
167
|
+
span.setAttribute("llm.circuit_breaker.state", "open");
|
|
168
|
+
span.setStatus({ code: 0 }); // OK
|
|
169
|
+
span.end();
|
|
170
|
+
}
|
|
140
171
|
/** Record active request count */
|
|
141
172
|
recordActiveRequests(count) {
|
|
142
173
|
this._activeRequests?.record(count);
|
|
@@ -158,10 +189,20 @@ export class OpenTelemetryExporter {
|
|
|
158
189
|
if (e.type === "request.retrying")
|
|
159
190
|
this.recordRetry(e);
|
|
160
191
|
});
|
|
192
|
+
const unsub4 = client.on("routing.resolved", (e) => {
|
|
193
|
+
if (e.type === "routing.resolved")
|
|
194
|
+
this.recordRouting(e);
|
|
195
|
+
});
|
|
196
|
+
const unsub5 = client.on("circuit_breaker.open", (e) => {
|
|
197
|
+
if (e.type === "circuit_breaker.open")
|
|
198
|
+
this.recordCircuitBreakerOpen(e);
|
|
199
|
+
});
|
|
161
200
|
return () => {
|
|
162
201
|
unsub1();
|
|
163
202
|
unsub2();
|
|
164
203
|
unsub3();
|
|
204
|
+
unsub4();
|
|
205
|
+
unsub5();
|
|
165
206
|
};
|
|
166
207
|
}
|
|
167
208
|
/** Check if OpenTelemetry is available */
|
|
@@ -48,6 +48,8 @@ export interface RequestCompletedEvent extends BaseEvent {
|
|
|
48
48
|
inputTokens?: number;
|
|
49
49
|
/** Output tokens (if available from usage chunk) */
|
|
50
50
|
outputTokens?: number;
|
|
51
|
+
/** Estimated cost of the request in USD (if cost tracking is enabled) */
|
|
52
|
+
estimatedCost?: number;
|
|
51
53
|
/** Whether structured output was used */
|
|
52
54
|
structuredOutput: boolean;
|
|
53
55
|
}
|
package/dist/utils/sse-writer.js
CHANGED
|
@@ -105,7 +105,7 @@ export function createSSEStream(chunks, options) {
|
|
|
105
105
|
}
|
|
106
106
|
}
|
|
107
107
|
// Flush any remaining pending tool calls
|
|
108
|
-
for (const [id
|
|
108
|
+
for (const [id] of pendingToolCalls) {
|
|
109
109
|
writeEvent(controller, encoder, { type: "tool_call_end", id });
|
|
110
110
|
}
|
|
111
111
|
// Write done terminator
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hilbras/sdk",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.7.0",
|
|
4
4
|
"description": "Provider-agnostic LLM client SDK \u2014 streaming, tool calling, embeddings, image generation, speech synthesis, transcription, reranking, circuit breaker, retry, reasoning normalization, cost enforcement, structured output with schema validation, type-safe tool builder, and SSRF-safe provider registration. Zero runtime dependencies.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -315,14 +315,15 @@
|
|
|
315
315
|
}
|
|
316
316
|
},
|
|
317
317
|
"devDependencies": {
|
|
318
|
-
"@types/node": "^26.
|
|
318
|
+
"@types/node": "^26.6.5",
|
|
319
319
|
"@types/react": "^19.3.0",
|
|
320
320
|
"@vitest/coverage-v8": "^4.1.11",
|
|
321
|
-
"oxlint": "^1.
|
|
322
|
-
"react": "^19.3.
|
|
321
|
+
"oxlint": "^1.88.0",
|
|
322
|
+
"react": "^19.3.1",
|
|
323
|
+
"react-dom": "^19.3.1",
|
|
323
324
|
"typescript": "^7.0.2",
|
|
324
325
|
"vitest": "^4.1.11",
|
|
325
|
-
"vue": "^3.5.
|
|
326
|
+
"vue": "^3.5.44"
|
|
326
327
|
},
|
|
327
328
|
"packageManager": "npm@11.19.0",
|
|
328
329
|
"workspaces": [
|