@hilbras/sdk 3.6.1 → 3.8.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 +16 -8
- package/dist/adapters/anthropic.js +39 -25
- package/dist/adapters/azure.js +10 -13
- package/dist/adapters/bedrock.js +41 -26
- package/dist/adapters/cohere.js +28 -43
- package/dist/adapters/google-genai.js +25 -14
- package/dist/adapters/google-vertex.js +25 -14
- package/dist/adapters/groq.d.ts +3 -4
- package/dist/adapters/groq.js +30 -18
- package/dist/adapters/huggingface.js +10 -13
- package/dist/adapters/ollama.d.ts +2 -1
- package/dist/adapters/ollama.js +49 -17
- package/dist/adapters/openai-compatible.js +9 -13
- package/dist/adapters/openai.js +9 -13
- package/dist/catalog/models.d.ts +10 -0
- package/dist/catalog/models.js +32 -1
- package/dist/client/client.js +52 -7
- package/dist/config/config-resolver.js +4 -1
- package/dist/config/resolved-config.js +11 -4
- package/dist/config/sources/environment.js +2 -1
- package/dist/core/execution/ports.d.ts +0 -5
- package/dist/core/execution/request-context.d.ts +0 -12
- package/dist/core/execution/request-context.js +0 -20
- package/dist/core/execution/request-executor.d.ts +13 -3
- package/dist/core/execution/request-executor.js +16 -8
- package/dist/core/execution/request-pipeline.js +47 -22
- package/dist/cost/alerts.d.ts +18 -1
- package/dist/cost/alerts.js +67 -31
- package/dist/frameworks/astro/endpoints.js +8 -5
- package/dist/frameworks/nextjs/route-handlers.js +18 -6
- package/dist/frameworks/nextjs/use-chat.js +8 -0
- package/dist/frameworks/react/use-chat.js +8 -1
- package/dist/frameworks/react-client/use-chat.d.ts +17 -0
- package/dist/frameworks/react-client/use-chat.js +49 -21
- package/dist/frameworks/remix/actions.js +8 -5
- package/dist/frameworks/shared/handler-core.js +9 -4
- package/dist/frameworks/svelte/use-chat.d.ts +1 -0
- package/dist/frameworks/svelte/use-chat.js +14 -0
- package/dist/frameworks/vue/use-chat.js +8 -1
- package/dist/index.d.ts +0 -2
- package/dist/index.js +4 -1
- package/dist/logging/logger.js +4 -1
- package/dist/output/schema-helpers.js +4 -1
- package/dist/reasoning/normalizer.d.ts +15 -5
- package/dist/reasoning/normalizer.js +44 -36
- package/dist/reliability/backoff.js +3 -1
- package/dist/reliability/circuit-breaker.d.ts +2 -0
- package/dist/reliability/circuit-breaker.js +17 -0
- package/dist/reliability/degradation.js +5 -4
- package/dist/reliability/presets.js +2 -2
- package/dist/reliability/retry.js +8 -1
- package/dist/reliability/timeout.d.ts +7 -3
- package/dist/reliability/timeout.js +11 -2
- package/dist/router/model-router.js +30 -5
- package/dist/security/audit-logger.js +50 -6
- package/dist/security/authorization.d.ts +2 -2
- package/dist/security/known-secrets.d.ts +19 -0
- package/dist/security/known-secrets.js +39 -0
- package/dist/security/prompt-injection-guard.js +28 -16
- package/dist/security/rbac.d.ts +6 -2
- package/dist/security/rbac.js +8 -5
- package/dist/telemetry/opentelemetry.d.ts +6 -1
- package/dist/telemetry/opentelemetry.js +41 -0
- package/dist/tokens/counter.d.ts +6 -0
- package/dist/tokens/counter.js +43 -35
- package/dist/transport/fetch.js +47 -5
- package/dist/types/observability.d.ts +2 -0
- package/dist/types/router.d.ts +3 -0
- package/dist/utils/base64.d.ts +13 -0
- package/dist/utils/base64.js +20 -0
- package/dist/utils/sse-writer.d.ts +9 -0
- package/dist/utils/sse-writer.js +5 -2
- package/dist/utils/sse.d.ts +20 -0
- package/dist/utils/sse.js +52 -10
- package/package.json +10 -10
- package/dist/mcp/index.d.ts +0 -63
- package/dist/mcp/index.js +0 -77
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
* console.log(result[0].reasons); // ["Supports required tools", "Within budget", ...]
|
|
16
16
|
*/
|
|
17
17
|
import { BUILTIN_MODELS } from "../catalog/models.js";
|
|
18
|
-
import { estimateCost } from "../tokens/counter.js";
|
|
18
|
+
import { estimateCost, hasPricing } from "../tokens/counter.js";
|
|
19
19
|
/** Task-specific scoring weights — defines what matters for each task type */
|
|
20
20
|
const TASK_WEIGHTS = {
|
|
21
21
|
coding: { reasoning: 25, tools: 25, speed: 15, cost: 20, structured: 15 },
|
|
@@ -73,6 +73,8 @@ export class ModelRouter {
|
|
|
73
73
|
provider: s.entry.provider,
|
|
74
74
|
model: s.entry.id,
|
|
75
75
|
score: s.score,
|
|
76
|
+
estimatedCost: this._estimateCost(s.entry),
|
|
77
|
+
rejectionReason: s.reasons[0],
|
|
76
78
|
}));
|
|
77
79
|
return scored.map((s, i) => ({
|
|
78
80
|
provider: s.entry.provider,
|
|
@@ -116,7 +118,13 @@ export class ModelRouter {
|
|
|
116
118
|
const fallbacks = (primary.fallbacks ?? []);
|
|
117
119
|
const allCandidates = [
|
|
118
120
|
{ provider: primary.provider, model: primary.model, score: primary.score, estimatedCost: primary.estimatedCost, reasons: primary.reasons },
|
|
119
|
-
...fallbacks.map((f) => ({
|
|
121
|
+
...fallbacks.map((f) => ({
|
|
122
|
+
provider: f.provider,
|
|
123
|
+
model: f.model,
|
|
124
|
+
score: f.score,
|
|
125
|
+
estimatedCost: f.estimatedCost ?? 0,
|
|
126
|
+
reasons: [f.rejectionReason ?? "Fallback candidate"],
|
|
127
|
+
})),
|
|
120
128
|
];
|
|
121
129
|
// Estimate total cost: primary + retries + repairs + possible fallback
|
|
122
130
|
const retryCostPerAttempt = primary.estimatedCost * 0.8; // Assume retries are slightly cheaper (backoff reduces load)
|
|
@@ -233,9 +241,12 @@ export class ModelRouter {
|
|
|
233
241
|
const taskFit = this._computeTaskFit(entry, req);
|
|
234
242
|
// Context fit score (0-100)
|
|
235
243
|
const contextFit = this._computeContextFit(entry, req);
|
|
236
|
-
// Cost score (0-100) — lower cost = higher score
|
|
244
|
+
// Cost score (0-100) — lower cost = higher score. An unpriced model is not
|
|
245
|
+
// free: `estimateCost` returns 0 for an unknown model, and treating that as
|
|
246
|
+
// perfect cost efficiency made the router prefer models with no known price.
|
|
237
247
|
const cost = this._estimateCost(entry);
|
|
238
|
-
const
|
|
248
|
+
const priced = hasPricing(entry.provider, entry.id);
|
|
249
|
+
const costEfficiency = !priced ? 0 : cost === 0 ? 100 : Math.max(0, 100 - (cost * 2000));
|
|
239
250
|
if (req.maxCost && cost <= req.maxCost)
|
|
240
251
|
reasons.push(`Within budget ($${cost.toFixed(4)} of $${req.maxCost})`);
|
|
241
252
|
else if (req.budget)
|
|
@@ -262,7 +273,8 @@ export class ModelRouter {
|
|
|
262
273
|
reasons.push(`Context window sufficient (${entry.contextWindow.toLocaleString()} tokens)`);
|
|
263
274
|
}
|
|
264
275
|
// Weighted combination
|
|
265
|
-
const
|
|
276
|
+
const capabilityWeight = (weights.reasoning + weights.tools + weights.structured) / 100;
|
|
277
|
+
const rawScore = (capabilityFit * capabilityWeight)
|
|
266
278
|
+ (taskFit * 10 / 100)
|
|
267
279
|
+ (contextFit * 10 / 100)
|
|
268
280
|
+ (costEfficiency * weights.cost / 100)
|
|
@@ -271,6 +283,19 @@ export class ModelRouter {
|
|
|
271
283
|
+ providerPreference
|
|
272
284
|
+ structuredOutputFit
|
|
273
285
|
+ toolFit;
|
|
286
|
+
// Normalise against the maximum this task's weights can reach. The weighted
|
|
287
|
+
// sum alone runs to ~155, and clamping it at 100 made most models tie and
|
|
288
|
+
// dropped the ranking back to catalog order.
|
|
289
|
+
const maxScore = (100 * capabilityWeight)
|
|
290
|
+
+ 10
|
|
291
|
+
+ 10
|
|
292
|
+
+ (100 * weights.cost / 100)
|
|
293
|
+
+ (100 * weights.speed / 100)
|
|
294
|
+
+ 10
|
|
295
|
+
+ 5
|
|
296
|
+
+ 10
|
|
297
|
+
+ 10;
|
|
298
|
+
const finalScore = maxScore > 0 ? (rawScore / maxScore) * 100 : 0;
|
|
274
299
|
const breakdown = {
|
|
275
300
|
capabilityFit: Math.round(capabilityFit),
|
|
276
301
|
taskFit: Math.round(taskFit),
|
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
* audit.logConfigChange({ action: "add_provider", provider: "openai", userId: "admin" });
|
|
19
19
|
*/
|
|
20
20
|
import { redactPii } from "./pii-guard.js";
|
|
21
|
+
import { redact } from "../logging/logger.js";
|
|
21
22
|
/** Monotonic counter for unique event IDs */
|
|
22
23
|
let _eventCounter = 0;
|
|
23
24
|
function generateEventId() {
|
|
@@ -30,8 +31,12 @@ function cloneValue(value, seen = new WeakSet()) {
|
|
|
30
31
|
if (Array.isArray(value))
|
|
31
32
|
return value.map((item) => cloneValue(item, seen));
|
|
32
33
|
if (value && typeof value === "object") {
|
|
34
|
+
// Non-plain objects (Date, Map, Set, Error, class instances) are returned
|
|
35
|
+
// as-is: walking them with Object.entries silently turned a Date into {}.
|
|
36
|
+
if (Object.getPrototypeOf(value) !== Object.prototype)
|
|
37
|
+
return value;
|
|
33
38
|
if (seen.has(value))
|
|
34
|
-
return
|
|
39
|
+
return undefined; // circular reference — drop the branch
|
|
35
40
|
seen.add(value);
|
|
36
41
|
const result = {};
|
|
37
42
|
for (const [key, item] of Object.entries(value))
|
|
@@ -40,6 +45,40 @@ function cloneValue(value, seen = new WeakSet()) {
|
|
|
40
45
|
}
|
|
41
46
|
return value;
|
|
42
47
|
}
|
|
48
|
+
/**
|
|
49
|
+
* Redact PII and credentials from every string in a value, nested objects and
|
|
50
|
+
* arrays included. The logger previously redacted only `description`, so a
|
|
51
|
+
* `meta` / `previousValue` / `newValue` / `error` field carrying a credential
|
|
52
|
+
* was written verbatim to the log sink.
|
|
53
|
+
*
|
|
54
|
+
* Three passes, because no single one covers everything:
|
|
55
|
+
* - a value under a credential-shaped key (`apiKey`, `token`, `password`, ...)
|
|
56
|
+
* is replaced outright — `ghp_...` and other opaque tokens carry no prefix a
|
|
57
|
+
* pattern can recognise;
|
|
58
|
+
* - `redact` strips recognisable credential formats (`sk-`, `AKIA`, `AIza`, ...);
|
|
59
|
+
* - `redactPii` strips emails, phone numbers, card numbers and so on.
|
|
60
|
+
*/
|
|
61
|
+
const SENSITIVE_KEY = /(secret|token|password|passwd|api[_-]?key|apikey|credential|authorization|private[_-]?key|session[_-]?id)/i;
|
|
62
|
+
function redactDeep(value, keyHint = "") {
|
|
63
|
+
if (typeof value === "string") {
|
|
64
|
+
if (keyHint && SENSITIVE_KEY.test(keyHint))
|
|
65
|
+
return "[REDACTED]";
|
|
66
|
+
return redact(redactPii(value));
|
|
67
|
+
}
|
|
68
|
+
if (Array.isArray(value))
|
|
69
|
+
return value.map((item) => redactDeep(item, keyHint));
|
|
70
|
+
if (value && typeof value === "object") {
|
|
71
|
+
// Non-plain objects (Date, Map, Error, ...) are not walked: it would
|
|
72
|
+
// destroy them the same way `cloneValue` used to.
|
|
73
|
+
if (Object.getPrototypeOf(value) !== Object.prototype)
|
|
74
|
+
return value;
|
|
75
|
+
const result = {};
|
|
76
|
+
for (const [key, item] of Object.entries(value))
|
|
77
|
+
result[key] = redactDeep(item, key);
|
|
78
|
+
return result;
|
|
79
|
+
}
|
|
80
|
+
return value;
|
|
81
|
+
}
|
|
43
82
|
function cloneEntry(entry) {
|
|
44
83
|
return cloneValue(entry);
|
|
45
84
|
}
|
|
@@ -140,7 +179,13 @@ export class AuditLogger {
|
|
|
140
179
|
}
|
|
141
180
|
/** Count entries by category */
|
|
142
181
|
countByCategory() {
|
|
143
|
-
const counts = {
|
|
182
|
+
const counts = {
|
|
183
|
+
auth: 0,
|
|
184
|
+
data_access: 0,
|
|
185
|
+
config_change: 0,
|
|
186
|
+
security: 0,
|
|
187
|
+
error: 0,
|
|
188
|
+
};
|
|
144
189
|
for (const entry of this._entries) {
|
|
145
190
|
counts[entry.category] = (counts[entry.category] ?? 0) + 1;
|
|
146
191
|
}
|
|
@@ -172,14 +217,13 @@ export class AuditLogger {
|
|
|
172
217
|
userId: event.userId,
|
|
173
218
|
sourceIp: this._config.includeSourceIp ? event.sourceIp : undefined,
|
|
174
219
|
requestId: event.requestId,
|
|
175
|
-
description:
|
|
176
|
-
? redactPii(event.description)
|
|
177
|
-
: event.description,
|
|
220
|
+
description: event.description,
|
|
178
221
|
meta: { ...this._config.defaultFields, ...event.meta },
|
|
179
222
|
};
|
|
180
223
|
}
|
|
181
224
|
_emit(entry) {
|
|
182
|
-
const
|
|
225
|
+
const cloned = cloneEntry(entry);
|
|
226
|
+
const stored = this._config.redactPii ? redactDeep(cloned) : cloned;
|
|
183
227
|
this._entries.push(stored);
|
|
184
228
|
if (this._entries.length > this._maxEntries) {
|
|
185
229
|
this._entries = this._entries.slice(-this._maxEntries);
|
|
@@ -126,9 +126,9 @@ export interface AuthorizationDiagnostic {
|
|
|
126
126
|
/** Result of evaluating a single request against a single role. */
|
|
127
127
|
export interface AuthorizationVerdict {
|
|
128
128
|
allow: boolean;
|
|
129
|
-
|
|
129
|
+
/** 403 only: a rate-limit rejection answers directly and never becomes a verdict. */
|
|
130
|
+
status?: 403;
|
|
130
131
|
reason?: string;
|
|
131
|
-
retryAfterMs?: number;
|
|
132
132
|
role?: string;
|
|
133
133
|
/**
|
|
134
134
|
* True when the verdict came from a context the middleware could not fully
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hilbras/sdk — Known credential registry
|
|
3
|
+
*
|
|
4
|
+
* Pattern matching has a floor. `redact()` scrubs `\bsk-[A-Za-z0-9\-_]{20,}`,
|
|
5
|
+
* so a short key such as `sk-local-gateway` sails through untouched and lands in
|
|
6
|
+
* error messages and logs.
|
|
7
|
+
*
|
|
8
|
+
* The SDK knows the credentials it was configured with, so it does not have to
|
|
9
|
+
* guess: registering a key lets it be scrubbed by exact value at any length,
|
|
10
|
+
* with no pattern and therefore no false positives.
|
|
11
|
+
*/
|
|
12
|
+
/** Register a credential so it is scrubbed from any text the SDK emits. */
|
|
13
|
+
export declare function registerKnownSecret(value: string | undefined | null): void;
|
|
14
|
+
/** Replace every registered credential in `text` with `[REDACTED]`. */
|
|
15
|
+
export declare function redactKnownSecrets(text: string): string;
|
|
16
|
+
/** How many credentials are registered. Test seam. */
|
|
17
|
+
export declare function knownSecretCount(): number;
|
|
18
|
+
/** Forget every registered credential. Test seam. */
|
|
19
|
+
export declare function clearKnownSecrets(): void;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hilbras/sdk — Known credential registry
|
|
3
|
+
*
|
|
4
|
+
* Pattern matching has a floor. `redact()` scrubs `\bsk-[A-Za-z0-9\-_]{20,}`,
|
|
5
|
+
* so a short key such as `sk-local-gateway` sails through untouched and lands in
|
|
6
|
+
* error messages and logs.
|
|
7
|
+
*
|
|
8
|
+
* The SDK knows the credentials it was configured with, so it does not have to
|
|
9
|
+
* guess: registering a key lets it be scrubbed by exact value at any length,
|
|
10
|
+
* with no pattern and therefore no false positives.
|
|
11
|
+
*/
|
|
12
|
+
/** Below this length a "secret" is as likely to be an ordinary word. */
|
|
13
|
+
const MIN_SECRET_LENGTH = 8;
|
|
14
|
+
const knownSecrets = new Set();
|
|
15
|
+
/** Register a credential so it is scrubbed from any text the SDK emits. */
|
|
16
|
+
export function registerKnownSecret(value) {
|
|
17
|
+
if (typeof value === "string" && value.length >= MIN_SECRET_LENGTH) {
|
|
18
|
+
knownSecrets.add(value);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/** Replace every registered credential in `text` with `[REDACTED]`. */
|
|
22
|
+
export function redactKnownSecrets(text) {
|
|
23
|
+
if (!text || knownSecrets.size === 0)
|
|
24
|
+
return text;
|
|
25
|
+
let result = text;
|
|
26
|
+
for (const secret of knownSecrets) {
|
|
27
|
+
if (result.includes(secret))
|
|
28
|
+
result = result.split(secret).join("[REDACTED]");
|
|
29
|
+
}
|
|
30
|
+
return result;
|
|
31
|
+
}
|
|
32
|
+
/** How many credentials are registered. Test seam. */
|
|
33
|
+
export function knownSecretCount() {
|
|
34
|
+
return knownSecrets.size;
|
|
35
|
+
}
|
|
36
|
+
/** Forget every registered credential. Test seam. */
|
|
37
|
+
export function clearKnownSecrets() {
|
|
38
|
+
knownSecrets.clear();
|
|
39
|
+
}
|
|
@@ -299,27 +299,39 @@ function stripInjections(messages, config) {
|
|
|
299
299
|
return messages.map((msg) => {
|
|
300
300
|
if (!roles.includes(msg.role))
|
|
301
301
|
return msg;
|
|
302
|
+
// Multimodal content: strip only the text parts and keep the rest. The
|
|
303
|
+
// previous version rebuilt `content` as a string, silently deleting images.
|
|
304
|
+
if (Array.isArray(msg.content)) {
|
|
305
|
+
const content = msg.content.map((part) => {
|
|
306
|
+
if (part.type !== "text")
|
|
307
|
+
return part;
|
|
308
|
+
const stripped = stripInjectionText(part.text, config);
|
|
309
|
+
return stripped === part.text ? part : { ...part, text: stripped };
|
|
310
|
+
});
|
|
311
|
+
return { ...msg, content };
|
|
312
|
+
}
|
|
302
313
|
const text = extractText(msg.content);
|
|
303
314
|
if (!text)
|
|
304
315
|
return msg;
|
|
305
|
-
const
|
|
306
|
-
|
|
307
|
-
return msg;
|
|
308
|
-
let sanitized = text;
|
|
309
|
-
// Strip in reverse order of position to preserve indices
|
|
310
|
-
const sorted = [...detection.detections].sort((a, b) => text.indexOf(b.matchedText) - text.indexOf(a.matchedText));
|
|
311
|
-
for (const match of sorted) {
|
|
312
|
-
const idx = sanitized.indexOf(match.matchedText);
|
|
313
|
-
if (idx !== -1) {
|
|
314
|
-
sanitized =
|
|
315
|
-
sanitized.slice(0, idx) +
|
|
316
|
-
`[INJECTION BLOCKED: ${match.category}]` +
|
|
317
|
-
sanitized.slice(idx + match.matchedText.length);
|
|
318
|
-
}
|
|
319
|
-
}
|
|
320
|
-
return { ...msg, content: sanitized };
|
|
316
|
+
const sanitized = stripInjectionText(text, config);
|
|
317
|
+
return sanitized === text ? msg : { ...msg, content: sanitized };
|
|
321
318
|
});
|
|
322
319
|
}
|
|
320
|
+
/**
|
|
321
|
+
* Replace every detected injection in `text`. Replacing a single occurrence —
|
|
322
|
+
* which is what the previous index-based loop did — let a payload survive
|
|
323
|
+
* simply by repeating itself.
|
|
324
|
+
*/
|
|
325
|
+
function stripInjectionText(text, config) {
|
|
326
|
+
const detection = detectInjection(text, config);
|
|
327
|
+
if (detection.safe)
|
|
328
|
+
return text;
|
|
329
|
+
let sanitized = text;
|
|
330
|
+
for (const match of detection.detections) {
|
|
331
|
+
sanitized = sanitized.split(match.matchedText).join(`[INJECTION BLOCKED: ${match.category}]`);
|
|
332
|
+
}
|
|
333
|
+
return sanitized;
|
|
334
|
+
}
|
|
323
335
|
/**
|
|
324
336
|
* Create an injection guard middleware function that processes message arrays.
|
|
325
337
|
*
|
package/dist/security/rbac.d.ts
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* construction.
|
|
12
12
|
*/
|
|
13
13
|
import type { Middleware, MiddlewareContext } from "../middleware/middleware.js";
|
|
14
|
-
import { type AuthorizationOptions, type RBACConfig, type RBACRole } from "./authorization.js";
|
|
14
|
+
import { type AuthorizationEnforcement, type AuthorizationOptions, type RBACConfig, type RBACRole } from "./authorization.js";
|
|
15
15
|
export type { RBACRole, RBACConfig } from "./authorization.js";
|
|
16
16
|
export type { AuthorizationBudgetView, AuthorizationDiagnostic, AuthorizationEnforcement, AuthorizationOptions, AuthorizationVerdict, RBACRequestContext, } from "./authorization.js";
|
|
17
17
|
export { evaluateAuthorization, evaluateRoleRequest, resolveRequestFromContext, validateRbacConfig, } from "./authorization.js";
|
|
@@ -32,8 +32,12 @@ export interface PermissionCheck {
|
|
|
32
32
|
* A role that declares no restrictions allows everything. A role whose policy
|
|
33
33
|
* is malformed denies, because an invalid policy must never be treated as an
|
|
34
34
|
* absent one.
|
|
35
|
+
*
|
|
36
|
+
* `enforcement` defaults to `"strict"`: a role that restricts providers cannot
|
|
37
|
+
* have that restriction evaluated when the caller names no provider, and an
|
|
38
|
+
* unevaluable restriction must not answer "allowed".
|
|
35
39
|
*/
|
|
36
|
-
export declare function checkPermission(role: RBACRole, provider: string, model: string, tokenCount?: number): PermissionCheck;
|
|
40
|
+
export declare function checkPermission(role: RBACRole, provider: string, model: string, tokenCount?: number, enforcement?: AuthorizationEnforcement): PermissionCheck;
|
|
37
41
|
/**
|
|
38
42
|
* Create RBAC middleware that enforces role-based access control.
|
|
39
43
|
*
|
package/dist/security/rbac.js
CHANGED
|
@@ -19,13 +19,17 @@ export { evaluateAuthorization, evaluateRoleRequest, resolveRequestFromContext,
|
|
|
19
19
|
* A role that declares no restrictions allows everything. A role whose policy
|
|
20
20
|
* is malformed denies, because an invalid policy must never be treated as an
|
|
21
21
|
* absent one.
|
|
22
|
+
*
|
|
23
|
+
* `enforcement` defaults to `"strict"`: a role that restricts providers cannot
|
|
24
|
+
* have that restriction evaluated when the caller names no provider, and an
|
|
25
|
+
* unevaluable restriction must not answer "allowed".
|
|
22
26
|
*/
|
|
23
|
-
export function checkPermission(role, provider, model, tokenCount) {
|
|
27
|
+
export function checkPermission(role, provider, model, tokenCount, enforcement = "strict") {
|
|
24
28
|
const verdict = evaluateAuthorization({
|
|
25
29
|
role,
|
|
26
30
|
roleName: role.name,
|
|
27
31
|
request: { provider, model, tokenCount },
|
|
28
|
-
enforcement
|
|
32
|
+
enforcement,
|
|
29
33
|
userId: null,
|
|
30
34
|
report: () => { },
|
|
31
35
|
});
|
|
@@ -212,9 +216,8 @@ export function createRBACMiddleware(config, getUserId, options) {
|
|
|
212
216
|
severity: "warning",
|
|
213
217
|
meta: { role: verdict.role, unresolved: verdict.unresolved },
|
|
214
218
|
});
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
}
|
|
219
|
+
// No 429 branch: a verdict is only ever 403 or an allow. Rate limiting
|
|
220
|
+
// answers before evaluation and never reaches here.
|
|
218
221
|
return jsonResponse(403, { error: verdict.reason ?? "Access denied" });
|
|
219
222
|
};
|
|
220
223
|
}
|
|
@@ -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 */
|
package/dist/tokens/counter.d.ts
CHANGED
|
@@ -62,6 +62,12 @@ export declare function estimateToolTokens(tools: Array<{
|
|
|
62
62
|
parameters: Record<string, unknown>;
|
|
63
63
|
};
|
|
64
64
|
}>): TokenEstimate;
|
|
65
|
+
/**
|
|
66
|
+
* Whether a model has a known price. `estimateCost` reports 0 for an unknown
|
|
67
|
+
* model, which is indistinguishable from a genuinely free one — so callers
|
|
68
|
+
* that rank or filter by cost must check this first.
|
|
69
|
+
*/
|
|
70
|
+
export declare function hasPricing(provider: string, model: string): boolean;
|
|
65
71
|
/** Calculate cost estimate based on provider and token counts */
|
|
66
72
|
export declare function estimateCost(inputTokens: number, outputTokens: number, provider: string, model: string): {
|
|
67
73
|
inputCost: number;
|
package/dist/tokens/counter.js
CHANGED
|
@@ -136,43 +136,51 @@ export function estimateToolTokens(tools) {
|
|
|
136
136
|
}
|
|
137
137
|
return { text: "", tokens: total, chars };
|
|
138
138
|
}
|
|
139
|
+
/** Approximate pricing per 1M tokens (USD), keyed by model id or `provider/model` */
|
|
140
|
+
const PRICING = {
|
|
141
|
+
"gpt-5.6-sol": { input: 4.00, output: 20.00 },
|
|
142
|
+
"gpt-5.6-terra": { input: 2.00, output: 12.00 },
|
|
143
|
+
"gpt-5.6-luna": { input: 0.20, output: 1.20 },
|
|
144
|
+
"o3": { input: 10.00, output: 40.00 },
|
|
145
|
+
"o3-mini": { input: 1.10, output: 4.40 },
|
|
146
|
+
"o4-mini": { input: 1.10, output: 4.40 },
|
|
147
|
+
"claude-fable-5": { input: 10.00, output: 50.00 },
|
|
148
|
+
"claude-opus-5": { input: 5.00, output: 25.00 },
|
|
149
|
+
"claude-sonnet-5": { input: 2.00, output: 10.00 },
|
|
150
|
+
"claude-haiku-4-5": { input: 1.00, output: 5.00 },
|
|
151
|
+
"gemini-3.7-flash": { input: 0.75, output: 3.75 },
|
|
152
|
+
"gemini-3.6-flash": { input: 0.75, output: 3.75 },
|
|
153
|
+
"gemini-3.5-flash": { input: 1.50, output: 9.00 },
|
|
154
|
+
"gemini-3.5-flash-lite": { input: 0.30, output: 2.50 },
|
|
155
|
+
"gemini-3.1-pro-preview": { input: 2.00, output: 12.00 },
|
|
156
|
+
"gemini-3.1-flash-lite": { input: 0.25, output: 1.50 },
|
|
157
|
+
"gemini-3-flash-preview": { input: 0.50, output: 3.00 },
|
|
158
|
+
"gemini-2.5-pro": { input: 1.25, output: 10.00 },
|
|
159
|
+
"gemini-2.5-flash": { input: 0.30, output: 2.50 },
|
|
160
|
+
// Mistral
|
|
161
|
+
"mistral-large-latest": { input: 2.00, output: 6.00 },
|
|
162
|
+
"mistral-small-latest": { input: 0.10, output: 0.30 },
|
|
163
|
+
"codestral-latest": { input: 0.30, output: 0.90 },
|
|
164
|
+
// DeepSeek
|
|
165
|
+
"deepseek-chat": { input: 0.27, output: 1.10 },
|
|
166
|
+
"deepseek-reasoner": { input: 0.55, output: 2.19 },
|
|
167
|
+
// xAI
|
|
168
|
+
"grok-3": { input: 3.00, output: 15.00 },
|
|
169
|
+
"grok-3-mini": { input: 0.30, output: 0.50 },
|
|
170
|
+
// Cohere
|
|
171
|
+
"command-r-plus-08-2024": { input: 2.50, output: 10.00 },
|
|
172
|
+
"command-r-08-2024": { input: 0.15, output: 0.60 },
|
|
173
|
+
};
|
|
174
|
+
/**
|
|
175
|
+
* Whether a model has a known price. `estimateCost` reports 0 for an unknown
|
|
176
|
+
* model, which is indistinguishable from a genuinely free one — so callers
|
|
177
|
+
* that rank or filter by cost must check this first.
|
|
178
|
+
*/
|
|
179
|
+
export function hasPricing(provider, model) {
|
|
180
|
+
return PRICING[model] !== undefined || PRICING[`${provider}/${model}`] !== undefined;
|
|
181
|
+
}
|
|
139
182
|
/** Calculate cost estimate based on provider and token counts */
|
|
140
183
|
export function estimateCost(inputTokens, outputTokens, provider, model) {
|
|
141
|
-
// Approximate pricing per 1M tokens (USD)
|
|
142
|
-
const PRICING = {
|
|
143
|
-
"gpt-5.6-sol": { input: 4.00, output: 20.00 },
|
|
144
|
-
"gpt-5.6-terra": { input: 2.00, output: 12.00 },
|
|
145
|
-
"gpt-5.6-luna": { input: 0.20, output: 1.20 },
|
|
146
|
-
"o3": { input: 10.00, output: 40.00 },
|
|
147
|
-
"o3-mini": { input: 1.10, output: 4.40 },
|
|
148
|
-
"o4-mini": { input: 1.10, output: 4.40 },
|
|
149
|
-
"claude-fable-5": { input: 10.00, output: 50.00 },
|
|
150
|
-
"claude-opus-5": { input: 5.00, output: 25.00 },
|
|
151
|
-
"claude-sonnet-5": { input: 2.00, output: 10.00 },
|
|
152
|
-
"claude-haiku-4-5": { input: 1.00, output: 5.00 },
|
|
153
|
-
"gemini-3.7-flash": { input: 0.75, output: 3.75 },
|
|
154
|
-
"gemini-3.6-flash": { input: 0.75, output: 3.75 },
|
|
155
|
-
"gemini-3.5-flash": { input: 1.50, output: 9.00 },
|
|
156
|
-
"gemini-3.5-flash-lite": { input: 0.30, output: 2.50 },
|
|
157
|
-
"gemini-3.1-pro-preview": { input: 2.00, output: 12.00 },
|
|
158
|
-
"gemini-3.1-flash-lite": { input: 0.25, output: 1.50 },
|
|
159
|
-
"gemini-3-flash-preview": { input: 0.50, output: 3.00 },
|
|
160
|
-
"gemini-2.5-pro": { input: 1.25, output: 10.00 },
|
|
161
|
-
"gemini-2.5-flash": { input: 0.30, output: 2.50 },
|
|
162
|
-
// Mistral
|
|
163
|
-
"mistral-large-latest": { input: 2.00, output: 6.00 },
|
|
164
|
-
"mistral-small-latest": { input: 0.10, output: 0.30 },
|
|
165
|
-
"codestral-latest": { input: 0.30, output: 0.90 },
|
|
166
|
-
// DeepSeek
|
|
167
|
-
"deepseek-chat": { input: 0.27, output: 1.10 },
|
|
168
|
-
"deepseek-reasoner": { input: 0.55, output: 2.19 },
|
|
169
|
-
// xAI
|
|
170
|
-
"grok-3": { input: 3.00, output: 15.00 },
|
|
171
|
-
"grok-3-mini": { input: 0.30, output: 0.50 },
|
|
172
|
-
// Cohere
|
|
173
|
-
"command-r-plus-08-2024": { input: 2.50, output: 10.00 },
|
|
174
|
-
"command-r-08-2024": { input: 0.15, output: 0.60 },
|
|
175
|
-
};
|
|
176
184
|
const pricing = PRICING[model] ?? PRICING[`${provider}/${model}`] ?? { input: 0, output: 0 };
|
|
177
185
|
const inputCost = Math.max(0, (inputTokens / 1_000_000) * pricing.input);
|
|
178
186
|
const outputCost = Math.max(0, (outputTokens / 1_000_000) * pricing.output);
|
package/dist/transport/fetch.js
CHANGED
|
@@ -127,12 +127,22 @@ export class FetchTransport {
|
|
|
127
127
|
onExternalAbort();
|
|
128
128
|
}
|
|
129
129
|
this._controllers.add(controller);
|
|
130
|
+
// The connection slot and the controller registration are held until the
|
|
131
|
+
// response BODY finishes, not until the headers arrive. Releasing at headers
|
|
132
|
+
// made `maxConnectionsPerOrigin` cosmetic for streams, and let
|
|
133
|
+
// destroy()/abort() forget a body that was still being read.
|
|
134
|
+
const settle = () => {
|
|
135
|
+
externalSignal?.removeEventListener("abort", onExternalAbort);
|
|
136
|
+
this._controllers.delete(controller);
|
|
137
|
+
this._release(origin);
|
|
138
|
+
};
|
|
130
139
|
const requestFn = async () => {
|
|
140
|
+
let response;
|
|
131
141
|
try {
|
|
132
142
|
const headers = init.headers
|
|
133
143
|
? Object.fromEntries(Object.entries(init.headers).filter(([, v]) => v !== undefined))
|
|
134
144
|
: undefined;
|
|
135
|
-
|
|
145
|
+
response = await fetch(url, {
|
|
136
146
|
method: init.method,
|
|
137
147
|
headers,
|
|
138
148
|
body: init.body,
|
|
@@ -140,11 +150,43 @@ export class FetchTransport {
|
|
|
140
150
|
redirect: "error",
|
|
141
151
|
});
|
|
142
152
|
}
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
153
|
+
catch (error) {
|
|
154
|
+
// No response arrived, so no body will complete to release the slot.
|
|
155
|
+
settle();
|
|
156
|
+
throw error;
|
|
157
|
+
}
|
|
158
|
+
// 204/205/304 and similar carry no body to wait for.
|
|
159
|
+
if (!response.body) {
|
|
160
|
+
settle();
|
|
161
|
+
return response;
|
|
147
162
|
}
|
|
163
|
+
const reader = response.body.getReader();
|
|
164
|
+
const body = new ReadableStream({
|
|
165
|
+
async pull(out) {
|
|
166
|
+
try {
|
|
167
|
+
const { done, value } = await reader.read();
|
|
168
|
+
if (done) {
|
|
169
|
+
settle();
|
|
170
|
+
out.close();
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
out.enqueue(value);
|
|
174
|
+
}
|
|
175
|
+
catch (error) {
|
|
176
|
+
settle();
|
|
177
|
+
out.error(error);
|
|
178
|
+
}
|
|
179
|
+
},
|
|
180
|
+
cancel(reason) {
|
|
181
|
+
settle();
|
|
182
|
+
return reader.cancel(reason);
|
|
183
|
+
},
|
|
184
|
+
});
|
|
185
|
+
return new Response(body, {
|
|
186
|
+
status: response.status,
|
|
187
|
+
statusText: response.statusText,
|
|
188
|
+
headers: response.headers,
|
|
189
|
+
});
|
|
148
190
|
};
|
|
149
191
|
const promise = requestFn();
|
|
150
192
|
if (requestKey) {
|
|
@@ -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/types/router.d.ts
CHANGED
|
@@ -39,7 +39,10 @@ export interface RejectedCandidate {
|
|
|
39
39
|
provider: string;
|
|
40
40
|
model: string;
|
|
41
41
|
score: number;
|
|
42
|
+
/** Why this candidate was not selected, or why it is a viable fallback */
|
|
42
43
|
rejectionReason?: string;
|
|
44
|
+
/** Estimated cost per request in USD */
|
|
45
|
+
estimatedCost?: number;
|
|
43
46
|
}
|
|
44
47
|
/** A routing decision — explainable, with full audit trail */
|
|
45
48
|
export interface RoutingResult {
|