@hilbras/sdk 3.6.0 → 3.6.1
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/core/execution/request-pipeline.js +138 -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/utils/sse-writer.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
<p align="center">
|
|
2
|
-
<img src="https://img.shields.io/badge/version-3.6.
|
|
2
|
+
<img src="https://img.shields.io/badge/version-3.6.1-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">
|
|
@@ -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,
|
|
@@ -255,10 +302,7 @@ export class RequestPipeline {
|
|
|
255
302
|
const callerAborted = input.callerSignal?.aborted === true;
|
|
256
303
|
const internalTimeout = prepared.signal?.aborted === true;
|
|
257
304
|
if (callerAborted || firstChunkEmitted || internalTimeout) {
|
|
258
|
-
|
|
259
|
-
this.ports.budget.release(input.requestId);
|
|
260
|
-
reservationActive = false;
|
|
261
|
-
}
|
|
305
|
+
releaseMainBudget();
|
|
262
306
|
const terminalError = error instanceof Error ? error : new Error(String(error));
|
|
263
307
|
this.recordTerminalFailure(prepared, terminalError);
|
|
264
308
|
this.ports.emit({
|
|
@@ -271,25 +315,30 @@ export class RequestPipeline {
|
|
|
271
315
|
attempts: attempt + 1,
|
|
272
316
|
error: terminalError.message,
|
|
273
317
|
});
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
318
|
+
try {
|
|
319
|
+
await this.ports.plugins.fireError({
|
|
320
|
+
requestId: input.requestId,
|
|
321
|
+
provider: input.provider,
|
|
322
|
+
model: input.model,
|
|
323
|
+
error: terminalError,
|
|
324
|
+
durationMs: this.ports.now() - input.startTime,
|
|
325
|
+
attempts: attempt + 1,
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
catch {
|
|
329
|
+
// Swallow plugin hook failures so the original stream error is still surfaced.
|
|
330
|
+
}
|
|
282
331
|
throw error;
|
|
283
332
|
}
|
|
284
333
|
const status = error.status;
|
|
285
334
|
const isNetworkError = error instanceof TypeError
|
|
286
|
-
|| (error instanceof Error && error.name === "AbortError")
|
|
335
|
+
|| (error instanceof Error && error.name === "AbortError")
|
|
336
|
+
|| isNetworkFailure(error);
|
|
287
337
|
const canRetry = (isNetworkError && shouldRetryNetworkError(attempt, prepared.retryConfig))
|
|
288
338
|
|| (typeof status === "number" && shouldRetry(status, attempt, prepared.retryConfig));
|
|
289
339
|
if (!canRetry) {
|
|
290
340
|
if (prepared.context.policy.allowFallback) {
|
|
291
|
-
|
|
292
|
-
reservationActive = false;
|
|
341
|
+
releaseMainBudget();
|
|
293
342
|
const attemptedModels = [input.model];
|
|
294
343
|
const fallbacks = input.fallbackCandidates(attemptedModels);
|
|
295
344
|
for (const fallback of fallbacks) {
|
|
@@ -313,7 +362,6 @@ export class RequestPipeline {
|
|
|
313
362
|
if (!fallbackReservation)
|
|
314
363
|
continue;
|
|
315
364
|
let fallbackPrepared;
|
|
316
|
-
let fallbackVisible = false;
|
|
317
365
|
let fallbackInputTokens;
|
|
318
366
|
let fallbackOutputTokens;
|
|
319
367
|
let fallbackReservationActive = true;
|
|
@@ -327,7 +375,6 @@ export class RequestPipeline {
|
|
|
327
375
|
providerTimeoutMs: 0,
|
|
328
376
|
}, "stream");
|
|
329
377
|
for await (const chunk of this.ports.executor.executeStream(fallbackPrepared, { ...input.params, model: fallback.model }, { recordCircuitFailure: false })) {
|
|
330
|
-
fallbackVisible = true;
|
|
331
378
|
if (chunk.type === "usage") {
|
|
332
379
|
fallbackInputTokens = chunk.inputTokens;
|
|
333
380
|
fallbackOutputTokens = chunk.outputTokens;
|
|
@@ -375,10 +422,7 @@ export class RequestPipeline {
|
|
|
375
422
|
return;
|
|
376
423
|
}
|
|
377
424
|
catch (fallbackError) {
|
|
378
|
-
|
|
379
|
-
primaryError = fallbackError;
|
|
380
|
-
break;
|
|
381
|
-
}
|
|
425
|
+
primaryError = fallbackError;
|
|
382
426
|
}
|
|
383
427
|
finally {
|
|
384
428
|
fallbackPrepared?.dispose();
|
|
@@ -391,10 +435,7 @@ export class RequestPipeline {
|
|
|
391
435
|
}
|
|
392
436
|
}
|
|
393
437
|
if (!canRetry) {
|
|
394
|
-
|
|
395
|
-
this.ports.budget.release(input.requestId);
|
|
396
|
-
reservationActive = false;
|
|
397
|
-
}
|
|
438
|
+
releaseMainBudget();
|
|
398
439
|
const terminalError = primaryError instanceof Error ? primaryError : new Error(String(primaryError));
|
|
399
440
|
this.recordTerminalFailure(prepared, terminalError);
|
|
400
441
|
this.ports.emit({
|
|
@@ -407,14 +448,19 @@ export class RequestPipeline {
|
|
|
407
448
|
attempts: attempt + 1,
|
|
408
449
|
error: terminalError.message,
|
|
409
450
|
});
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
451
|
+
try {
|
|
452
|
+
await this.ports.plugins.fireError({
|
|
453
|
+
requestId: input.requestId,
|
|
454
|
+
provider: input.provider,
|
|
455
|
+
model: input.model,
|
|
456
|
+
error: terminalError,
|
|
457
|
+
durationMs: this.ports.now() - input.startTime,
|
|
458
|
+
attempts: attempt + 1,
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
catch {
|
|
462
|
+
// Swallow plugin hook failures so the original stream error is still surfaced.
|
|
463
|
+
}
|
|
418
464
|
throw primaryError;
|
|
419
465
|
}
|
|
420
466
|
const delay = calculateBackoff(attempt, prepared.context.policy.backoff);
|
|
@@ -431,10 +477,7 @@ export class RequestPipeline {
|
|
|
431
477
|
await this.ports.sleep(delay, input.callerSignal);
|
|
432
478
|
}
|
|
433
479
|
catch (sleepError) {
|
|
434
|
-
|
|
435
|
-
this.ports.budget.release(input.requestId);
|
|
436
|
-
reservationActive = false;
|
|
437
|
-
}
|
|
480
|
+
releaseMainBudget();
|
|
438
481
|
const terminalError = sleepError instanceof Error ? sleepError : new Error(String(sleepError));
|
|
439
482
|
this.recordTerminalFailure(prepared, terminalError);
|
|
440
483
|
this.ports.emit({
|
|
@@ -447,14 +490,19 @@ export class RequestPipeline {
|
|
|
447
490
|
attempts: attempt + 1,
|
|
448
491
|
error: terminalError.message,
|
|
449
492
|
});
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
493
|
+
try {
|
|
494
|
+
await this.ports.plugins.fireError({
|
|
495
|
+
requestId: input.requestId,
|
|
496
|
+
provider: input.provider,
|
|
497
|
+
model: input.model,
|
|
498
|
+
error: terminalError,
|
|
499
|
+
durationMs: this.ports.now() - input.startTime,
|
|
500
|
+
attempts: attempt + 1,
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
catch {
|
|
504
|
+
// Swallow plugin hook failures so the original stream error is still surfaced.
|
|
505
|
+
}
|
|
458
506
|
throw sleepError;
|
|
459
507
|
}
|
|
460
508
|
attempt++;
|
|
@@ -462,8 +510,7 @@ export class RequestPipeline {
|
|
|
462
510
|
}
|
|
463
511
|
}
|
|
464
512
|
finally {
|
|
465
|
-
|
|
466
|
-
this.ports.budget.release(input.requestId);
|
|
513
|
+
releaseMainBudget();
|
|
467
514
|
prepared.dispose();
|
|
468
515
|
}
|
|
469
516
|
}
|
|
@@ -495,6 +542,13 @@ export class RequestPipeline {
|
|
|
495
542
|
};
|
|
496
543
|
let attempt = 0;
|
|
497
544
|
let primaryError;
|
|
545
|
+
let budgetReleased = false;
|
|
546
|
+
const releaseBudget = () => {
|
|
547
|
+
if (!budgetReleased) {
|
|
548
|
+
this.ports.budget.release(input.requestId);
|
|
549
|
+
budgetReleased = true;
|
|
550
|
+
}
|
|
551
|
+
};
|
|
498
552
|
for (;;) {
|
|
499
553
|
const result = await this.ports.executor.executeComplete(prepared, { ...input.params, messages: structuredMessages, extra: structuredExtra }, { dispose: false, recordCircuitFailure: false });
|
|
500
554
|
if (result.ok) {
|
|
@@ -545,7 +599,7 @@ export class RequestPipeline {
|
|
|
545
599
|
continue;
|
|
546
600
|
}
|
|
547
601
|
const validationError = new ValidationError(maxRepairAttempts + 1, validation.error, result.value, { requestId: input.requestId, model: input.model });
|
|
548
|
-
|
|
602
|
+
releaseBudget();
|
|
549
603
|
this.ports.emit({
|
|
550
604
|
type: "request.failed",
|
|
551
605
|
requestId: input.requestId,
|
|
@@ -630,7 +684,14 @@ export class RequestPipeline {
|
|
|
630
684
|
primaryError = fallbackResult.error;
|
|
631
685
|
}
|
|
632
686
|
if (fallbackResult.ok) {
|
|
633
|
-
|
|
687
|
+
let parsed;
|
|
688
|
+
try {
|
|
689
|
+
parsed = JSON.parse(extractJson(fallbackResult.value));
|
|
690
|
+
}
|
|
691
|
+
catch (error) {
|
|
692
|
+
primaryError = error;
|
|
693
|
+
break;
|
|
694
|
+
}
|
|
634
695
|
const validation = input.output.schema.safeParse(parsed);
|
|
635
696
|
if (validation.success) {
|
|
636
697
|
this.ports.budget.settle(fallbackId, fallbackCost, {
|
|
@@ -651,8 +712,7 @@ export class RequestPipeline {
|
|
|
651
712
|
}
|
|
652
713
|
}
|
|
653
714
|
catch (error) {
|
|
654
|
-
|
|
655
|
-
primaryError = error;
|
|
715
|
+
primaryError = error;
|
|
656
716
|
}
|
|
657
717
|
finally {
|
|
658
718
|
fallbackPrepared?.dispose();
|
|
@@ -665,7 +725,7 @@ export class RequestPipeline {
|
|
|
665
725
|
break;
|
|
666
726
|
}
|
|
667
727
|
this.recordTerminalFailure(prepared, primaryError);
|
|
668
|
-
|
|
728
|
+
releaseBudget();
|
|
669
729
|
const error = primaryError instanceof Error ? primaryError : new Error(String(primaryError));
|
|
670
730
|
this.ports.emit({
|
|
671
731
|
type: "request.failed",
|
|
@@ -677,14 +737,19 @@ export class RequestPipeline {
|
|
|
677
737
|
attempts: attempt + 1,
|
|
678
738
|
error: error.message,
|
|
679
739
|
});
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
740
|
+
try {
|
|
741
|
+
await this.ports.plugins.fireError({
|
|
742
|
+
requestId: input.requestId,
|
|
743
|
+
provider: input.provider,
|
|
744
|
+
model: input.model,
|
|
745
|
+
error,
|
|
746
|
+
durationMs: this.ports.now() - input.startTime,
|
|
747
|
+
attempts: attempt + 1,
|
|
748
|
+
});
|
|
749
|
+
}
|
|
750
|
+
catch {
|
|
751
|
+
// Swallow plugin hook failures so the original request error is still surfaced.
|
|
752
|
+
}
|
|
688
753
|
throw primaryError;
|
|
689
754
|
}
|
|
690
755
|
finally {
|
|
@@ -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.
|
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.6.
|
|
3
|
+
"version": "3.6.1",
|
|
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",
|