@hilbras/sdk 3.7.0 → 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.
Files changed (74) hide show
  1. package/README.md +15 -7
  2. package/dist/adapters/anthropic.js +39 -25
  3. package/dist/adapters/azure.js +10 -13
  4. package/dist/adapters/bedrock.js +41 -26
  5. package/dist/adapters/cohere.js +28 -43
  6. package/dist/adapters/google-genai.js +25 -14
  7. package/dist/adapters/google-vertex.js +25 -14
  8. package/dist/adapters/groq.d.ts +3 -4
  9. package/dist/adapters/groq.js +30 -18
  10. package/dist/adapters/huggingface.js +10 -13
  11. package/dist/adapters/ollama.d.ts +2 -1
  12. package/dist/adapters/ollama.js +49 -17
  13. package/dist/adapters/openai-compatible.js +9 -13
  14. package/dist/adapters/openai.js +9 -13
  15. package/dist/catalog/models.d.ts +10 -0
  16. package/dist/catalog/models.js +32 -1
  17. package/dist/client/client.js +37 -2
  18. package/dist/config/config-resolver.js +4 -1
  19. package/dist/config/resolved-config.js +11 -4
  20. package/dist/config/sources/environment.js +2 -1
  21. package/dist/core/execution/ports.d.ts +0 -5
  22. package/dist/core/execution/request-context.d.ts +0 -12
  23. package/dist/core/execution/request-context.js +0 -20
  24. package/dist/core/execution/request-executor.d.ts +13 -3
  25. package/dist/core/execution/request-executor.js +16 -8
  26. package/dist/core/execution/request-pipeline.js +44 -22
  27. package/dist/cost/alerts.d.ts +18 -1
  28. package/dist/cost/alerts.js +67 -31
  29. package/dist/frameworks/astro/endpoints.js +8 -5
  30. package/dist/frameworks/nextjs/route-handlers.js +18 -6
  31. package/dist/frameworks/nextjs/use-chat.js +8 -0
  32. package/dist/frameworks/react/use-chat.js +8 -1
  33. package/dist/frameworks/react-client/use-chat.d.ts +17 -0
  34. package/dist/frameworks/react-client/use-chat.js +49 -21
  35. package/dist/frameworks/remix/actions.js +8 -5
  36. package/dist/frameworks/shared/handler-core.js +9 -4
  37. package/dist/frameworks/svelte/use-chat.d.ts +1 -0
  38. package/dist/frameworks/svelte/use-chat.js +14 -0
  39. package/dist/frameworks/vue/use-chat.js +8 -1
  40. package/dist/index.d.ts +0 -2
  41. package/dist/index.js +4 -1
  42. package/dist/logging/logger.js +4 -1
  43. package/dist/output/schema-helpers.js +4 -1
  44. package/dist/reasoning/normalizer.d.ts +15 -5
  45. package/dist/reasoning/normalizer.js +44 -36
  46. package/dist/reliability/backoff.js +3 -1
  47. package/dist/reliability/circuit-breaker.d.ts +2 -0
  48. package/dist/reliability/circuit-breaker.js +17 -0
  49. package/dist/reliability/degradation.js +5 -4
  50. package/dist/reliability/presets.js +2 -2
  51. package/dist/reliability/retry.js +8 -1
  52. package/dist/reliability/timeout.d.ts +7 -3
  53. package/dist/reliability/timeout.js +11 -2
  54. package/dist/router/model-router.js +30 -5
  55. package/dist/security/audit-logger.js +50 -6
  56. package/dist/security/authorization.d.ts +2 -2
  57. package/dist/security/known-secrets.d.ts +19 -0
  58. package/dist/security/known-secrets.js +39 -0
  59. package/dist/security/prompt-injection-guard.js +28 -16
  60. package/dist/security/rbac.d.ts +6 -2
  61. package/dist/security/rbac.js +8 -5
  62. package/dist/tokens/counter.d.ts +6 -0
  63. package/dist/tokens/counter.js +43 -35
  64. package/dist/transport/fetch.js +47 -5
  65. package/dist/types/router.d.ts +3 -0
  66. package/dist/utils/base64.d.ts +13 -0
  67. package/dist/utils/base64.js +20 -0
  68. package/dist/utils/sse-writer.d.ts +9 -0
  69. package/dist/utils/sse-writer.js +5 -2
  70. package/dist/utils/sse.d.ts +20 -0
  71. package/dist/utils/sse.js +52 -10
  72. package/package.json +5 -6
  73. package/dist/mcp/index.d.ts +0 -63
  74. package/dist/mcp/index.js +0 -77
@@ -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 value; // circular reference — stop recursing
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: this._config.redactPii && event.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 stored = cloneEntry(entry);
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
- status?: 403 | 429;
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 detection = detectInjection(text, config);
306
- if (detection.safe)
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
  *
@@ -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
  *
@@ -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: "permissive",
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
- if (verdict.status === 429) {
216
- return jsonResponse(429, { error: verdict.reason, retryAfterMs: verdict.retryAfterMs });
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
  }
@@ -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;
@@ -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);
@@ -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
- return await fetch(url, {
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
- finally {
144
- externalSignal?.removeEventListener("abort", onExternalAbort);
145
- this._controllers.delete(controller);
146
- this._release(origin);
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) {
@@ -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 {
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @hilbras/sdk — Base64 encoding
3
+ */
4
+ /**
5
+ * Base64-encode bytes.
6
+ *
7
+ * `btoa(String.fromCharCode(...bytes))` — the obvious form, and the one the
8
+ * Google adapters used — spreads every element into one call, which exceeds the
9
+ * engine's argument limit at roughly 100 kB. Audio clips and images cross that
10
+ * easily, so the encoding throws `RangeError: Maximum call stack size exceeded`.
11
+ * Chunking keeps each call small.
12
+ */
13
+ export declare function toBase64(bytes: Uint8Array): string;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * @hilbras/sdk — Base64 encoding
3
+ */
4
+ /**
5
+ * Base64-encode bytes.
6
+ *
7
+ * `btoa(String.fromCharCode(...bytes))` — the obvious form, and the one the
8
+ * Google adapters used — spreads every element into one call, which exceeds the
9
+ * engine's argument limit at roughly 100 kB. Audio clips and images cross that
10
+ * easily, so the encoding throws `RangeError: Maximum call stack size exceeded`.
11
+ * Chunking keeps each call small.
12
+ */
13
+ export function toBase64(bytes) {
14
+ const CHUNK = 0x8000;
15
+ let binary = "";
16
+ for (let offset = 0; offset < bytes.length; offset += CHUNK) {
17
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + CHUNK));
18
+ }
19
+ return btoa(binary);
20
+ }
@@ -22,6 +22,15 @@ export interface SSEWriterOptions {
22
22
  includeData?: boolean;
23
23
  /** Whether to include annotation events in the stream (default: true) */
24
24
  includeAnnotations?: boolean;
25
+ /**
26
+ * Called when the stream fails after the response headers were already sent.
27
+ *
28
+ * A streaming provider call runs lazily *through* this iterable, so its
29
+ * failure surfaces here rather than at the route handler. The client gets a
30
+ * fixed message — a provider error body must not reach it — so this is the
31
+ * only place the real error can be reported.
32
+ */
33
+ onError?: (error: unknown) => void;
25
34
  }
26
35
  /**
27
36
  * Create a ReadableStream that yields SSE-encoded Uint8Array chunks
@@ -113,11 +113,14 @@ export function createSSEStream(chunks, options) {
113
113
  controller.close();
114
114
  }
115
115
  catch (err) {
116
- // Write error event if stream is still writable
116
+ options?.onError?.(err);
117
+ // Write error event if stream is still writable. The client message is
118
+ // deliberately fixed: the raw error can carry provider response text
119
+ // (a 401 body, an upstream trace), which must not reach the browser.
117
120
  try {
118
121
  writeEvent(controller, encoder, {
119
122
  type: "error",
120
- error: err instanceof Error ? err.message : String(err),
123
+ error: "The model stream failed. Check the server logs for details.",
121
124
  });
122
125
  controller.enqueue(encoder.encode("data: [DONE]\n\n"));
123
126
  }
@@ -42,6 +42,26 @@ export interface SSEEvent {
42
42
  * }
43
43
  */
44
44
  export declare function parseSSEStream(stream: ReadableStream<Uint8Array>): AsyncGenerator<SSEEvent>;
45
+ /** One complete SSE event, in the shape the adapters consume. */
46
+ export interface SseFrame {
47
+ /** Concatenated `data:` payload, with the `data:` prefix removed. */
48
+ data: string;
49
+ /** `event:` field value, or "" when the event carried none. */
50
+ event: string;
51
+ }
52
+ /**
53
+ * Append a decoded chunk to `buffer` and return the SSE events it completes,
54
+ * advancing `buffer` past them.
55
+ *
56
+ * Shared by the adapters, which each hand-rolled this loop. Their copies shared
57
+ * three defects: CRLF framing never matched (a CRLF upstream produced nothing
58
+ * and grew the buffer for the whole response), `data:` without a space was
59
+ * rejected, and a `data:` payload split over several lines kept only the last.
60
+ */
61
+ export declare function splitSseFrames(buffer: string, chunk: string): {
62
+ buffer: string;
63
+ frames: SseFrame[];
64
+ };
45
65
  /**
46
66
  * Parse SSE stream and auto-parse JSON data.
47
67
  * Yields parsed JSON objects for each event with JSON data.
package/dist/utils/sse.js CHANGED
@@ -40,7 +40,10 @@ export async function* parseSSEStream(stream) {
40
40
  if (done)
41
41
  break;
42
42
  buffer += decoder.decode(value, { stream: true });
43
- const parts = buffer.split("\n\n");
43
+ // Accept CRLF framing as well as LF: `split("\n\n")` never matches a
44
+ // `\r\n\r\n` boundary, so a CRLF upstream yielded no events at all while
45
+ // the buffer grew for the whole response.
46
+ const parts = buffer.split(/\r?\n\r?\n/);
44
47
  buffer = parts.pop() ?? "";
45
48
  for (const part of parts) {
46
49
  if (!part.trim())
@@ -70,19 +73,23 @@ function parseSSEBlock(block) {
70
73
  let data = "";
71
74
  let id;
72
75
  let retry;
73
- for (const line of lines) {
74
- if (line.startsWith("data: ")) {
75
- const value = line.slice(6);
76
+ for (const rawLine of lines) {
77
+ // Strip a trailing CR so CRLF streams parse the same as LF.
78
+ const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
79
+ const field = line.split(":", 1)[0];
80
+ // The spec makes the space after the colon optional.
81
+ const value = line.slice(field.length + 1).replace(/^ /, "");
82
+ if (field === "data") {
76
83
  data += (data ? "\n" : "") + value;
77
84
  }
78
- else if (line.startsWith("event: ")) {
79
- event = line.slice(7).trim();
85
+ else if (field === "event") {
86
+ event = value.trim();
80
87
  }
81
- else if (line.startsWith("id: ")) {
82
- id = line.slice(4).trim();
88
+ else if (field === "id") {
89
+ id = value.trim();
83
90
  }
84
- else if (line.startsWith("retry: ")) {
85
- const n = parseInt(line.slice(7).trim(), 10);
91
+ else if (field === "retry") {
92
+ const n = parseInt(value.trim(), 10);
86
93
  if (!isNaN(n))
87
94
  retry = n;
88
95
  }
@@ -92,6 +99,41 @@ function parseSSEBlock(block) {
92
99
  return null;
93
100
  return { event, data, id, retry };
94
101
  }
102
+ function splitFrame(block) {
103
+ let data = "";
104
+ let event = "";
105
+ for (const rawLine of block.split("\n")) {
106
+ const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
107
+ if (line.startsWith("data:")) {
108
+ const value = line.slice(5).replace(/^ /, "");
109
+ data += (data ? "\n" : "") + value;
110
+ }
111
+ else if (line.startsWith("event:")) {
112
+ event = line.slice(6).trim();
113
+ }
114
+ }
115
+ return { data, event };
116
+ }
117
+ /**
118
+ * Append a decoded chunk to `buffer` and return the SSE events it completes,
119
+ * advancing `buffer` past them.
120
+ *
121
+ * Shared by the adapters, which each hand-rolled this loop. Their copies shared
122
+ * three defects: CRLF framing never matched (a CRLF upstream produced nothing
123
+ * and grew the buffer for the whole response), `data:` without a space was
124
+ * rejected, and a `data:` payload split over several lines kept only the last.
125
+ */
126
+ export function splitSseFrames(buffer, chunk) {
127
+ const parts = (buffer + chunk).split(/\r?\n\r?\n/);
128
+ const rest = parts.pop() ?? "";
129
+ const frames = [];
130
+ for (const part of parts) {
131
+ if (!part.trim())
132
+ continue;
133
+ frames.push(splitFrame(part));
134
+ }
135
+ return { buffer: rest, frames };
136
+ }
95
137
  /**
96
138
  * Parse SSE stream and auto-parse JSON data.
97
139
  * Yields parsed JSON objects for each event with JSON data.