@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.
Files changed (77) hide show
  1. package/README.md +16 -8
  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 +52 -7
  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 +47 -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/telemetry/opentelemetry.d.ts +6 -1
  63. package/dist/telemetry/opentelemetry.js +41 -0
  64. package/dist/tokens/counter.d.ts +6 -0
  65. package/dist/tokens/counter.js +43 -35
  66. package/dist/transport/fetch.js +47 -5
  67. package/dist/types/observability.d.ts +2 -0
  68. package/dist/types/router.d.ts +3 -0
  69. package/dist/utils/base64.d.ts +13 -0
  70. package/dist/utils/base64.js +20 -0
  71. package/dist/utils/sse-writer.d.ts +9 -0
  72. package/dist/utils/sse-writer.js +5 -2
  73. package/dist/utils/sse.d.ts +20 -0
  74. package/dist/utils/sse.js +52 -10
  75. package/package.json +10 -10
  76. package/dist/mcp/index.d.ts +0 -63
  77. package/dist/mcp/index.js +0 -77
@@ -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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hilbras/sdk",
3
- "version": "3.6.1",
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.",
3
+ "version": "3.8.0",
4
+ "description": "Provider-agnostic LLM client SDK — 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",
7
7
  "types": "dist/index.d.ts",
@@ -151,10 +151,6 @@
151
151
  "types": "./dist/reliability/*.d.ts",
152
152
  "import": "./dist/reliability/*.js"
153
153
  },
154
- "./mcp": {
155
- "types": "./dist/mcp/index.d.ts",
156
- "import": "./dist/mcp/index.js"
157
- },
158
154
  "./realtime": {
159
155
  "types": "./dist/realtime/index.d.ts",
160
156
  "import": "./dist/realtime/index.js"
@@ -244,6 +240,7 @@
244
240
  "dev": "tsc --watch",
245
241
  "pretest": "npx tsc --noEmit",
246
242
  "typecheck:examples": "tsc -p tsconfig.examples-check.json",
243
+ "typecheck:tests": "tsc -p tsconfig.tests.json",
247
244
  "test": "npm run test:root",
248
245
  "test:watch": "vitest",
249
246
  "test:coverage": "vitest run --coverage",
@@ -315,14 +312,17 @@
315
312
  }
316
313
  },
317
314
  "devDependencies": {
318
- "@types/node": "^26.2.0",
315
+ "@types/node": "^26.6.5",
319
316
  "@types/react": "^19.3.0",
317
+ "@types/react-dom": "^19.3.0",
320
318
  "@vitest/coverage-v8": "^4.1.11",
321
- "oxlint": "^1.79.0",
322
- "react": "^19.3.0",
319
+ "jsdom": "^31.0.0",
320
+ "oxlint": "^1.88.0",
321
+ "react": "^19.3.1",
322
+ "react-dom": "^19.3.1",
323
323
  "typescript": "^7.0.2",
324
324
  "vitest": "^4.1.11",
325
- "vue": "^3.5.43"
325
+ "vue": "^3.5.44"
326
326
  },
327
327
  "packageManager": "npm@11.19.0",
328
328
  "workspaces": [
@@ -1,63 +0,0 @@
1
- /**
2
- * @hilbras/sdk — MCP (Model Context Protocol) Client
3
- *
4
- * Connect to MCP servers to discover and use external tools,
5
- * resources, and prompts in your Hilbras SDK applications.
6
- */
7
- export interface MCPServerConfig {
8
- name: string;
9
- transport: "stdio" | "sse";
10
- command?: string;
11
- args?: string[];
12
- env?: Record<string, string>;
13
- url?: string;
14
- timeout?: number;
15
- }
16
- export interface MCPTool {
17
- name: string;
18
- description: string;
19
- inputSchema: Record<string, unknown>;
20
- }
21
- export interface MCPResource {
22
- uri: string;
23
- name: string;
24
- description?: string;
25
- mimeType?: string;
26
- }
27
- export interface MCPPrompt {
28
- name: string;
29
- description?: string;
30
- arguments?: Array<{
31
- name: string;
32
- description?: string;
33
- required?: boolean;
34
- }>;
35
- }
36
- export interface MCPConnection {
37
- server: MCPServerConfig;
38
- tools: MCPTool[];
39
- resources: MCPResource[];
40
- prompts: MCPPrompt[];
41
- connected: boolean;
42
- }
43
- /** Tool in Hilbras SDK format (loose typing for MCP conversion) */
44
- export interface MCPHilbrasTool {
45
- type: "function";
46
- function: {
47
- name: string;
48
- description: string;
49
- parameters: Record<string, unknown>;
50
- };
51
- }
52
- export declare class MCPClient {
53
- private _connections;
54
- connect(config: MCPServerConfig): Promise<MCPConnection>;
55
- registerTools(serverName: string, tools: MCPTool[]): void;
56
- callTool(serverName: string, toolName: string, _args: Record<string, unknown>): Promise<unknown>;
57
- readResource(serverName: string, uri: string): Promise<unknown>;
58
- getToolsAsHilbras(): MCPHilbrasTool[];
59
- disconnect(serverName: string): Promise<void>;
60
- disconnectAll(): Promise<void>;
61
- getConnections(): MCPConnection[];
62
- }
63
- export declare function createMCPToolExecution(mcpClient: MCPClient): (toolName: string, args: Record<string, unknown>) => Promise<unknown>;
package/dist/mcp/index.js DELETED
@@ -1,77 +0,0 @@
1
- /**
2
- * @hilbras/sdk — MCP (Model Context Protocol) Client
3
- *
4
- * Connect to MCP servers to discover and use external tools,
5
- * resources, and prompts in your Hilbras SDK applications.
6
- */
7
- // ─── MCP Client ─────────────────────────────────────────────────────────────
8
- export class MCPClient {
9
- _connections = new Map();
10
- async connect(config) {
11
- const connection = {
12
- server: config,
13
- tools: [],
14
- resources: [],
15
- prompts: [],
16
- connected: true,
17
- };
18
- this._connections.set(config.name, connection);
19
- return connection;
20
- }
21
- registerTools(serverName, tools) {
22
- const conn = this._connections.get(serverName);
23
- if (conn)
24
- conn.tools = tools;
25
- }
26
- async callTool(serverName, toolName, _args) {
27
- const connection = this._connections.get(serverName);
28
- if (!connection?.connected)
29
- throw new Error(`MCP server "${serverName}" not connected`);
30
- return { result: `Called ${toolName} on ${serverName}` };
31
- }
32
- async readResource(serverName, uri) {
33
- const connection = this._connections.get(serverName);
34
- if (!connection?.connected)
35
- throw new Error(`MCP server "${serverName}" not connected`);
36
- return { contents: [{ uri, text: "" }] };
37
- }
38
- getToolsAsHilbras() {
39
- const tools = [];
40
- for (const [, conn] of this._connections) {
41
- if (!conn.connected)
42
- continue;
43
- for (const mcpTool of conn.tools) {
44
- tools.push({
45
- type: "function",
46
- function: {
47
- name: `${conn.server.name}_${mcpTool.name}`,
48
- description: mcpTool.description,
49
- parameters: mcpTool.inputSchema,
50
- },
51
- });
52
- }
53
- }
54
- return tools;
55
- }
56
- async disconnect(serverName) {
57
- this._connections.delete(serverName);
58
- }
59
- async disconnectAll() {
60
- this._connections.clear();
61
- }
62
- getConnections() {
63
- return Array.from(this._connections.values());
64
- }
65
- }
66
- export function createMCPToolExecution(mcpClient) {
67
- return async (toolName, args) => {
68
- for (const conn of mcpClient.getConnections()) {
69
- const prefix = `${conn.server.name}_`;
70
- if (toolName.startsWith(prefix)) {
71
- const mcpToolName = toolName.slice(prefix.length);
72
- return mcpClient.callTool(conn.server.name, mcpToolName, args);
73
- }
74
- }
75
- throw new Error(`No MCP server has tool "${toolName}"`);
76
- };
77
- }