@hilbras/sdk 3.4.2 → 3.4.4

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 CHANGED
@@ -1,9 +1,9 @@
1
1
  <p align="center">
2
- <img src="https://img.shields.io/badge/version-3.4.2-blue" alt="version">
2
+ <img src="https://img.shields.io/badge/version-3.4.4-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">
6
- <img src="https://img.shields.io/badge/tests-1806%20passing-brightgreen" alt="tests">
6
+ <img src="https://img.shields.io/badge/tests-1836%20passing-brightgreen" alt="tests">
7
7
  <img src="https://img.shields.io/badge/runtime%20deps-zero-brightgreen" alt="zero deps">
8
8
  </p>
9
9
 
@@ -71,6 +71,18 @@ export declare class CircuitBreakerOpenError extends HilbrasSdkError {
71
71
  retryAfterMs?: number;
72
72
  });
73
73
  }
74
+ /**
75
+ * A request could not be accepted as written: malformed JSON, a missing or
76
+ * wrongly typed field, or a body that exceeds the configured limits.
77
+ *
78
+ * This is a caller error, so the default `status` is 400. Framework handlers
79
+ * map it to that status instead of surfacing a 200 with a failure buried in a
80
+ * stream.
81
+ */
82
+ export declare class RequestValidationError extends HilbrasSdkError {
83
+ readonly status: number;
84
+ constructor(message: string, hint?: string, status?: number);
85
+ }
74
86
  export declare class ValidationError extends HilbrasSdkError {
75
87
  readonly attempts: number;
76
88
  readonly lastError: unknown;
@@ -168,6 +168,22 @@ export class CircuitBreakerOpenError extends HilbrasSdkError {
168
168
  this.name = "CircuitBreakerOpenError";
169
169
  }
170
170
  }
171
+ /**
172
+ * A request could not be accepted as written: malformed JSON, a missing or
173
+ * wrongly typed field, or a body that exceeds the configured limits.
174
+ *
175
+ * This is a caller error, so the default `status` is 400. Framework handlers
176
+ * map it to that status instead of surfacing a 200 with a failure buried in a
177
+ * stream.
178
+ */
179
+ export class RequestValidationError extends HilbrasSdkError {
180
+ status;
181
+ constructor(message, hint, status = 400) {
182
+ super(message, { hint });
183
+ this.name = "RequestValidationError";
184
+ this.status = status;
185
+ }
186
+ }
171
187
  export class ValidationError extends HilbrasSdkError {
172
188
  attempts;
173
189
  lastError;
@@ -5,14 +5,12 @@
5
5
  * Uses the HilbrasClient to generate streaming responses with full protocol support.
6
6
  */
7
7
  import type { Tool } from "../../types/tools.js";
8
+ import { type FrameworkHandlerBaseOptions } from "../shared/handler-core.js";
8
9
  export interface ChatMessage {
9
10
  role: "user" | "assistant" | "system";
10
11
  content: string;
11
12
  }
12
- export interface EndpointOptions {
13
- provider: string;
14
- model: string;
15
- systemPrompt?: string;
13
+ export interface EndpointOptions extends FrameworkHandlerBaseOptions {
16
14
  tools?: Tool[];
17
15
  maxSteps?: number;
18
16
  }
@@ -22,10 +20,10 @@ export interface EndpointOptions {
22
20
  * @example
23
21
  * ```ts
24
22
  * // src/pages/api/chat.ts
25
- * import { createChatEndpoint } from "@hilbras/astro";
23
+ * import { createChatEndpoint } from "@hilbras/sdk/astro";
26
24
  *
27
25
  * export const { POST } = createChatEndpoint({
28
- * provider: "OpenAI",
26
+ * provider: "openai",
29
27
  * model: "gpt-4o",
30
28
  * });
31
29
  * ```
@@ -34,6 +32,7 @@ export declare function createChatEndpoint(options: EndpointOptions): {
34
32
  POST: ({ request }: {
35
33
  request: Request;
36
34
  }) => Promise<Response>;
35
+ dispose: () => Promise<void>;
37
36
  };
38
37
  /**
39
38
  * Create a non-streaming completion endpoint for Astro.
@@ -42,4 +41,5 @@ export declare function createCompletionEndpoint(options: EndpointOptions): {
42
41
  POST: ({ request }: {
43
42
  request: Request;
44
43
  }) => Promise<Response>;
44
+ dispose: () => Promise<void>;
45
45
  };
@@ -4,74 +4,103 @@
4
4
  * Create API endpoints for streaming chat/completion in Astro.
5
5
  * Uses the HilbrasClient to generate streaming responses with full protocol support.
6
6
  */
7
- import { HilbrasClient } from "../../client/client.js";
8
7
  import { createSSEResponse } from "../../utils/sse-writer.js";
8
+ import { createFrameworkClientPool, errorResponse, readJsonBody, requireArray, requireString, } from "../shared/handler-core.js";
9
9
  /**
10
10
  * Create a streaming chat endpoint for Astro.
11
11
  *
12
12
  * @example
13
13
  * ```ts
14
14
  * // src/pages/api/chat.ts
15
- * import { createChatEndpoint } from "@hilbras/astro";
15
+ * import { createChatEndpoint } from "@hilbras/sdk/astro";
16
16
  *
17
17
  * export const { POST } = createChatEndpoint({
18
- * provider: "OpenAI",
18
+ * provider: "openai",
19
19
  * model: "gpt-4o",
20
20
  * });
21
21
  * ```
22
22
  */
23
23
  export function createChatEndpoint(options) {
24
+ const pool = createFrameworkClientPool({
25
+ provider: options.provider,
26
+ model: options.model,
27
+ apiKey: options.apiKey,
28
+ });
24
29
  async function POST({ request }) {
25
- const body = await request.json();
26
- const { messages, stream } = body;
27
- const client = new HilbrasClient();
28
- client.addProviderFromCatalog(options.provider, options.model, process.env.AI_API_KEY ?? "");
29
- const allMessages = options.systemPrompt
30
- ? [{ role: "system", content: options.systemPrompt }, ...messages]
31
- : messages;
32
- if (stream === false) {
33
- const result = await client.complete({
34
- provider: options.provider,
30
+ try {
31
+ const body = await readJsonBody(request);
32
+ const messages = requireArray(body, "messages");
33
+ const client = pool.get(options.model);
34
+ const providerName = pool.providerName;
35
+ const allMessages = options.systemPrompt
36
+ ? [{ role: "system", content: options.systemPrompt }, ...messages]
37
+ : messages;
38
+ if (body.stream === false) {
39
+ const result = await client.complete({
40
+ provider: providerName,
41
+ model: options.model,
42
+ messages: allMessages,
43
+ signal: request.signal,
44
+ });
45
+ return new Response(JSON.stringify({
46
+ id: `cmpl-${Date.now()}`,
47
+ choices: [{ message: { role: "assistant", content: result }, finishReason: "stop" }],
48
+ }), {
49
+ headers: { "Content-Type": "application/json" },
50
+ });
51
+ }
52
+ const chunks = client.streamText({
53
+ provider: providerName,
35
54
  model: options.model,
36
55
  messages: allMessages,
56
+ tools: options.tools,
57
+ maxSteps: options.maxSteps,
58
+ signal: request.signal,
37
59
  });
38
- return new Response(JSON.stringify({
39
- id: `cmpl-${Date.now()}`,
40
- choices: [{ message: { role: "assistant", content: result }, finishReason: "stop" }],
41
- }), {
42
- headers: { "Content-Type": "application/json" },
43
- });
60
+ return createSSEResponse(chunks);
61
+ }
62
+ catch (error) {
63
+ return errorResponse(error);
44
64
  }
45
- const chunks = client.streamText({
46
- provider: options.provider,
47
- model: options.model,
48
- messages: allMessages,
49
- tools: options.tools,
50
- maxSteps: options.maxSteps,
51
- });
52
- return createSSEResponse(chunks);
53
65
  }
54
- return { POST };
66
+ async function dispose() {
67
+ await pool.dispose();
68
+ }
69
+ return { POST, dispose };
55
70
  }
56
71
  /**
57
72
  * Create a non-streaming completion endpoint for Astro.
58
73
  */
59
74
  export function createCompletionEndpoint(options) {
75
+ const pool = createFrameworkClientPool({
76
+ provider: options.provider,
77
+ model: options.model,
78
+ apiKey: options.apiKey,
79
+ });
60
80
  async function POST({ request }) {
61
- const body = await request.json();
62
- const client = new HilbrasClient();
63
- client.addProviderFromCatalog(options.provider, options.model, process.env.AI_API_KEY ?? "");
64
- const result = await client.complete({
65
- provider: options.provider,
66
- model: options.model,
67
- messages: [{ role: "user", content: body.prompt ?? "" }],
68
- });
69
- return new Response(JSON.stringify({
70
- id: `cmpl-${Date.now()}`,
71
- choices: [{ message: { role: "assistant", content: result }, finishReason: "stop" }],
72
- }), {
73
- headers: { "Content-Type": "application/json" },
74
- });
81
+ try {
82
+ const body = await readJsonBody(request);
83
+ const prompt = requireString(body, "prompt");
84
+ const client = pool.get(options.model);
85
+ const result = await client.complete({
86
+ provider: pool.providerName,
87
+ model: options.model,
88
+ messages: [{ role: "user", content: prompt }],
89
+ signal: request.signal,
90
+ });
91
+ return new Response(JSON.stringify({
92
+ id: `cmpl-${Date.now()}`,
93
+ choices: [{ message: { role: "assistant", content: result }, finishReason: "stop" }],
94
+ }), {
95
+ headers: { "Content-Type": "application/json" },
96
+ });
97
+ }
98
+ catch (error) {
99
+ return errorResponse(error);
100
+ }
101
+ }
102
+ async function dispose() {
103
+ await pool.dispose();
75
104
  }
76
- return { POST };
105
+ return { POST, dispose };
77
106
  }
@@ -1,24 +1,29 @@
1
1
  /**
2
- * @hilbras/nextjs — Route Handler Helpers
2
+ * @hilbras/nextjs — Next.js Route Handlers
3
3
  *
4
- * Helpers for Next.js App Router route handlers.
4
+ * Create streaming chat/completion endpoints for the Next.js App Router.
5
5
  * Uses the HilbrasClient to generate streaming responses with full protocol support.
6
6
  */
7
7
  import type { Tool } from "../../types/tools.js";
8
+ import { type FrameworkHandlerBaseOptions } from "../shared/handler-core.js";
9
+ export interface ChatMessage {
10
+ role: "user" | "assistant" | "system";
11
+ content: string;
12
+ }
8
13
  export interface ChatRequest {
9
- messages: Array<{
10
- role: string;
11
- content: string;
12
- }>;
14
+ messages: ChatMessage[];
13
15
  model?: string;
14
16
  provider?: string;
15
- systemPrompt?: string;
16
17
  temperature?: number;
17
18
  maxTokens?: number;
18
19
  tools?: Tool[];
19
20
  maxSteps?: number;
20
21
  stream?: boolean;
21
22
  }
23
+ export interface ChatHandlerOptions extends FrameworkHandlerBaseOptions {
24
+ tools?: Tool[];
25
+ maxSteps?: number;
26
+ }
22
27
  export interface ChatResponse {
23
28
  id: string;
24
29
  choices: Array<{
@@ -35,34 +40,36 @@ export interface ChatResponse {
35
40
  };
36
41
  }
37
42
  /**
38
- * Create a streaming chat endpoint handler.
43
+ * Create a streaming chat endpoint for Next.js.
39
44
  *
40
45
  * @example
41
46
  * ```ts
42
47
  * // app/api/chat/route.ts
43
- * import { createChatHandler } from "@hilbras/nextjs";
48
+ * import { createChatHandler } from "@hilbras/sdk/nextjs";
44
49
  *
45
50
  * export const { POST } = createChatHandler({
46
- * provider: "OpenAI",
51
+ * provider: "openai",
47
52
  * model: "gpt-4o",
48
53
  * });
49
54
  * ```
50
55
  */
51
- export declare function createChatHandler(options: {
52
- provider: string;
53
- model: string;
54
- systemPrompt?: string;
55
- tools?: Tool[];
56
- maxSteps?: number;
57
- }): {
56
+ export declare function createChatHandler(options: ChatHandlerOptions): {
58
57
  POST: (req: Request) => Promise<Response>;
58
+ dispose: () => Promise<void>;
59
59
  };
60
+ export interface CompletionRequest {
61
+ prompt: string;
62
+ model?: string;
63
+ temperature?: number;
64
+ maxTokens?: number;
65
+ stream?: boolean;
66
+ }
67
+ export interface CompletionHandlerOptions extends FrameworkHandlerBaseOptions {
68
+ }
60
69
  /**
61
- * Create a non-streaming completion endpoint handler.
70
+ * Create a non-streaming completion endpoint for Next.js.
62
71
  */
63
- export declare function createCompletionHandler(options: {
64
- provider: string;
65
- model: string;
66
- }): {
72
+ export declare function createCompletionHandler(options: CompletionHandlerOptions): {
67
73
  POST: (req: Request) => Promise<Response>;
74
+ dispose: () => Promise<void>;
68
75
  };
@@ -1,80 +1,119 @@
1
1
  /**
2
- * @hilbras/nextjs — Route Handler Helpers
2
+ * @hilbras/nextjs — Next.js Route Handlers
3
3
  *
4
- * Helpers for Next.js App Router route handlers.
4
+ * Create streaming chat/completion endpoints for the Next.js App Router.
5
5
  * Uses the HilbrasClient to generate streaming responses with full protocol support.
6
6
  */
7
- import { HilbrasClient } from "../../client/client.js";
8
7
  import { createSSEResponse } from "../../utils/sse-writer.js";
8
+ import { createFrameworkClientPool, errorResponse, readJsonBody, requireArray, requireString, } from "../shared/handler-core.js";
9
9
  /**
10
- * Create a streaming chat endpoint handler.
10
+ * Create a streaming chat endpoint for Next.js.
11
11
  *
12
12
  * @example
13
13
  * ```ts
14
14
  * // app/api/chat/route.ts
15
- * import { createChatHandler } from "@hilbras/nextjs";
15
+ * import { createChatHandler } from "@hilbras/sdk/nextjs";
16
16
  *
17
17
  * export const { POST } = createChatHandler({
18
- * provider: "OpenAI",
18
+ * provider: "openai",
19
19
  * model: "gpt-4o",
20
20
  * });
21
21
  * ```
22
22
  */
23
23
  export function createChatHandler(options) {
24
+ const pool = createFrameworkClientPool({
25
+ provider: options.provider,
26
+ model: options.model,
27
+ apiKey: options.apiKey,
28
+ });
24
29
  async function POST(req) {
25
- const body = await req.json();
26
- const client = new HilbrasClient();
27
- client.addProviderFromCatalog(options.provider, body.model ?? options.model, process.env.AI_API_KEY ?? "");
28
- const messages = [
29
- ...(options.systemPrompt ? [{ role: "system", content: options.systemPrompt }] : []),
30
- ...body.messages,
31
- ];
32
- if (body.stream === false) {
33
- const result = await client.complete({
34
- provider: options.provider,
35
- model: body.model ?? options.model,
36
- messages,
37
- temperature: body.temperature,
38
- maxTokens: body.maxTokens,
39
- });
40
- return Response.json({
41
- id: `cmpl-${Date.now()}`,
42
- choices: [{ message: { role: "assistant", content: result }, finishReason: "stop" }],
30
+ try {
31
+ const body = await readJsonBody(req);
32
+ const messages = requireArray(body, "messages");
33
+ const model = typeof body.model === "string" && body.model.length > 0
34
+ ? body.model
35
+ : options.model;
36
+ // Resolving the client before responding means a bad provider or model
37
+ // produces a real error status instead of an HTTP 200 whose body carries
38
+ // the failure.
39
+ const client = pool.get(model);
40
+ const providerName = pool.providerName;
41
+ const allMessages = [
42
+ ...(options.systemPrompt ? [{ role: "system", content: options.systemPrompt }] : []),
43
+ ...messages,
44
+ ];
45
+ if (body.stream === false) {
46
+ const result = await client.complete({
47
+ provider: providerName,
48
+ model,
49
+ messages: allMessages,
50
+ temperature: typeof body.temperature === "number" ? body.temperature : undefined,
51
+ maxTokens: typeof body.maxTokens === "number" ? body.maxTokens : undefined,
52
+ signal: req.signal,
53
+ });
54
+ return Response.json({
55
+ id: `cmpl-${Date.now()}`,
56
+ choices: [{ message: { role: "assistant", content: result }, finishReason: "stop" }],
57
+ });
58
+ }
59
+ const chunks = client.streamText({
60
+ provider: providerName,
61
+ model,
62
+ messages: allMessages,
63
+ temperature: typeof body.temperature === "number" ? body.temperature : undefined,
64
+ maxTokens: typeof body.maxTokens === "number" ? body.maxTokens : undefined,
65
+ tools: body.tools ?? options.tools,
66
+ maxSteps: typeof body.maxSteps === "number" ? body.maxSteps : options.maxSteps,
67
+ signal: req.signal,
43
68
  });
69
+ return createSSEResponse(chunks);
70
+ }
71
+ catch (error) {
72
+ return errorResponse(error);
44
73
  }
45
- const chunks = client.streamText({
46
- provider: options.provider,
47
- model: body.model ?? options.model,
48
- messages,
49
- temperature: body.temperature,
50
- maxTokens: body.maxTokens,
51
- tools: body.tools ?? options.tools,
52
- maxSteps: body.maxSteps ?? options.maxSteps,
53
- });
54
- return createSSEResponse(chunks);
55
74
  }
56
- return { POST };
75
+ /** Release the cached clients. Call this on server shutdown. */
76
+ async function dispose() {
77
+ await pool.dispose();
78
+ }
79
+ return { POST, dispose };
57
80
  }
58
81
  /**
59
- * Create a non-streaming completion endpoint handler.
82
+ * Create a non-streaming completion endpoint for Next.js.
60
83
  */
61
84
  export function createCompletionHandler(options) {
85
+ const pool = createFrameworkClientPool({
86
+ provider: options.provider,
87
+ model: options.model,
88
+ apiKey: options.apiKey,
89
+ });
62
90
  async function POST(req) {
63
- const body = await req.json();
64
- const client = new HilbrasClient();
65
- client.addProviderFromCatalog(options.provider, body.model ?? options.model, process.env.AI_API_KEY ?? "");
66
- const result = await client.complete({
67
- provider: options.provider,
68
- model: options.model,
69
- messages: [{ role: "user", content: body.prompt ?? "" }],
70
- });
71
- return Response.json({
72
- id: `cmpl-${Date.now()}`,
73
- choices: [{
74
- message: { role: "assistant", content: result },
75
- finishReason: "stop",
76
- }],
77
- });
91
+ try {
92
+ const body = await readJsonBody(req);
93
+ const prompt = requireString(body, "prompt");
94
+ const model = typeof body.model === "string" && body.model.length > 0
95
+ ? body.model
96
+ : options.model;
97
+ const client = pool.get(model);
98
+ const result = await client.complete({
99
+ provider: pool.providerName,
100
+ model,
101
+ messages: [{ role: "user", content: prompt }],
102
+ temperature: typeof body.temperature === "number" ? body.temperature : undefined,
103
+ maxTokens: typeof body.maxTokens === "number" ? body.maxTokens : undefined,
104
+ signal: req.signal,
105
+ });
106
+ return Response.json({
107
+ id: `cmpl-${Date.now()}`,
108
+ choices: [{ message: { role: "assistant", content: result }, finishReason: "stop" }],
109
+ });
110
+ }
111
+ catch (error) {
112
+ return errorResponse(error);
113
+ }
114
+ }
115
+ async function dispose() {
116
+ await pool.dispose();
78
117
  }
79
- return { POST };
118
+ return { POST, dispose };
80
119
  }
@@ -5,14 +5,12 @@
5
5
  * Uses the HilbrasClient to generate streaming responses with full protocol support.
6
6
  */
7
7
  import type { Tool } from "../../types/tools.js";
8
+ import { type FrameworkHandlerBaseOptions } from "../shared/handler-core.js";
8
9
  export interface ChatMessage {
9
10
  role: "user" | "assistant" | "system";
10
11
  content: string;
11
12
  }
12
- export interface ActionOptions {
13
- provider: string;
14
- model: string;
15
- systemPrompt?: string;
13
+ export interface ActionOptions extends FrameworkHandlerBaseOptions {
16
14
  tools?: Tool[];
17
15
  maxSteps?: number;
18
16
  }
@@ -22,20 +20,24 @@ export interface ActionOptions {
22
20
  * @example
23
21
  * ```ts
24
22
  * // app/routes/api.chat.ts
25
- * import { createChatAction } from "@hilbras/remix";
23
+ * import { createChatAction } from "@hilbras/sdk/remix";
26
24
  *
27
25
  * export const action = createChatAction({
28
- * provider: "OpenAI",
26
+ * provider: "openai",
29
27
  * model: "gpt-4o",
30
28
  * });
31
29
  * ```
32
30
  */
33
- export declare function createChatAction(options: ActionOptions): ({ request }: {
31
+ export declare function createChatAction(options: ActionOptions): (({ request }: {
34
32
  request: Request;
35
- }) => Promise<Response>;
33
+ }) => Promise<Response>) & {
34
+ dispose: () => Promise<void>;
35
+ };
36
36
  /**
37
37
  * Create a non-streaming completion action for Remix.
38
38
  */
39
- export declare function createCompletionAction(options: ActionOptions): ({ request }: {
39
+ export declare function createCompletionAction(options: ActionOptions): (({ request }: {
40
40
  request: Request;
41
- }) => Promise<Response>;
41
+ }) => Promise<Response>) & {
42
+ dispose: () => Promise<void>;
43
+ };
@@ -4,72 +4,103 @@
4
4
  * Remix action helpers for streaming chat/completion.
5
5
  * Uses the HilbrasClient to generate streaming responses with full protocol support.
6
6
  */
7
- import { HilbrasClient } from "../../client/client.js";
8
7
  import { createSSEResponse } from "../../utils/sse-writer.js";
8
+ import { createFrameworkClientPool, errorResponse, readJsonBody, requireArray, requireString, } from "../shared/handler-core.js";
9
9
  /**
10
10
  * Create a streaming chat action for Remix.
11
11
  *
12
12
  * @example
13
13
  * ```ts
14
14
  * // app/routes/api.chat.ts
15
- * import { createChatAction } from "@hilbras/remix";
15
+ * import { createChatAction } from "@hilbras/sdk/remix";
16
16
  *
17
17
  * export const action = createChatAction({
18
- * provider: "OpenAI",
18
+ * provider: "openai",
19
19
  * model: "gpt-4o",
20
20
  * });
21
21
  * ```
22
22
  */
23
23
  export function createChatAction(options) {
24
- return async ({ request }) => {
25
- const body = await request.json();
26
- const { messages, stream } = body;
27
- const client = new HilbrasClient();
28
- client.addProviderFromCatalog(options.provider, options.model, process.env.AI_API_KEY ?? "");
29
- const allMessages = options.systemPrompt
30
- ? [{ role: "system", content: options.systemPrompt }, ...messages]
31
- : messages;
32
- if (stream === false) {
33
- const result = await client.complete({
34
- provider: options.provider,
24
+ const pool = createFrameworkClientPool({
25
+ provider: options.provider,
26
+ model: options.model,
27
+ apiKey: options.apiKey,
28
+ });
29
+ const action = async ({ request }) => {
30
+ try {
31
+ const body = await readJsonBody(request);
32
+ const messages = requireArray(body, "messages");
33
+ const client = pool.get(options.model);
34
+ const providerName = pool.providerName;
35
+ const allMessages = options.systemPrompt
36
+ ? [{ role: "system", content: options.systemPrompt }, ...messages]
37
+ : messages;
38
+ if (body.stream === false) {
39
+ const result = await client.complete({
40
+ provider: providerName,
41
+ model: options.model,
42
+ messages: allMessages,
43
+ signal: request.signal,
44
+ });
45
+ return new Response(JSON.stringify({
46
+ id: `cmpl-${Date.now()}`,
47
+ choices: [{ message: { role: "assistant", content: result }, finishReason: "stop" }],
48
+ }), {
49
+ headers: { "Content-Type": "application/json" },
50
+ });
51
+ }
52
+ const chunks = client.streamText({
53
+ provider: providerName,
35
54
  model: options.model,
36
55
  messages: allMessages,
56
+ tools: options.tools,
57
+ maxSteps: options.maxSteps,
58
+ signal: request.signal,
37
59
  });
38
- return new Response(JSON.stringify({
39
- id: `cmpl-${Date.now()}`,
40
- choices: [{ message: { role: "assistant", content: result }, finishReason: "stop" }],
41
- }), {
42
- headers: { "Content-Type": "application/json" },
43
- });
60
+ return createSSEResponse(chunks);
61
+ }
62
+ catch (error) {
63
+ return errorResponse(error);
44
64
  }
45
- const chunks = client.streamText({
46
- provider: options.provider,
47
- model: options.model,
48
- messages: allMessages,
49
- tools: options.tools,
50
- maxSteps: options.maxSteps,
51
- });
52
- return createSSEResponse(chunks);
53
65
  };
66
+ async function dispose() {
67
+ await pool.dispose();
68
+ }
69
+ return Object.assign(action, { dispose });
54
70
  }
55
71
  /**
56
72
  * Create a non-streaming completion action for Remix.
57
73
  */
58
74
  export function createCompletionAction(options) {
59
- return async ({ request }) => {
60
- const body = await request.json();
61
- const client = new HilbrasClient();
62
- client.addProviderFromCatalog(options.provider, options.model, process.env.AI_API_KEY ?? "");
63
- const result = await client.complete({
64
- provider: options.provider,
65
- model: options.model,
66
- messages: [{ role: "user", content: body.prompt ?? "" }],
67
- });
68
- return new Response(JSON.stringify({
69
- id: `cmpl-${Date.now()}`,
70
- choices: [{ message: { role: "assistant", content: result }, finishReason: "stop" }],
71
- }), {
72
- headers: { "Content-Type": "application/json" },
73
- });
75
+ const pool = createFrameworkClientPool({
76
+ provider: options.provider,
77
+ model: options.model,
78
+ apiKey: options.apiKey,
79
+ });
80
+ const action = async ({ request }) => {
81
+ try {
82
+ const body = await readJsonBody(request);
83
+ const prompt = requireString(body, "prompt");
84
+ const client = pool.get(options.model);
85
+ const result = await client.complete({
86
+ provider: pool.providerName,
87
+ model: options.model,
88
+ messages: [{ role: "user", content: prompt }],
89
+ signal: request.signal,
90
+ });
91
+ return new Response(JSON.stringify({
92
+ id: `cmpl-${Date.now()}`,
93
+ choices: [{ message: { role: "assistant", content: result }, finishReason: "stop" }],
94
+ }), {
95
+ headers: { "Content-Type": "application/json" },
96
+ });
97
+ }
98
+ catch (error) {
99
+ return errorResponse(error);
100
+ }
74
101
  };
102
+ async function dispose() {
103
+ await pool.dispose();
104
+ }
105
+ return Object.assign(action, { dispose });
75
106
  }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * @hilbras/sdk — Shared framework handler core
3
+ *
4
+ * Every framework adapter (Next.js route handlers, Astro endpoints, Remix
5
+ * actions) previously re-implemented the same request handling. `actions.ts`
6
+ * was byte-for-byte identical to `endpoints.ts` across 33 lines, and all three
7
+ * shared the same defects: they discarded the canonical provider name returned
8
+ * by `addProviderFromCatalog` and then called with the caller's spelling, they
9
+ * built a fresh client per request and never disposed it, they read a hardcoded
10
+ * environment variable, and they reported configuration failures as an HTTP 200
11
+ * with the error buried in the stream body.
12
+ *
13
+ * This module owns the parts that must behave identically everywhere. Framework
14
+ * files keep only what is genuinely framework-specific: how to read the request
15
+ * and how to build a `Response`.
16
+ */
17
+ import { HilbrasClient } from "../../client/client.js";
18
+ /** Options common to every framework handler factory. */
19
+ export interface FrameworkHandlerBaseOptions {
20
+ /** Catalog provider id or display name, e.g. `"openai"` or `"OpenAI"`. */
21
+ provider: string;
22
+ /** Model id used when the request does not select one. */
23
+ model: string;
24
+ /** Prepended to the conversation as a system message. */
25
+ systemPrompt?: string;
26
+ /**
27
+ * API key. When omitted, `AI_API_KEY` is tried, then the provider's own
28
+ * catalog `envKey` (for example `OPENAI_API_KEY`).
29
+ */
30
+ apiKey?: string;
31
+ }
32
+ /** Resolve a provider spelling to its canonical catalog id. */
33
+ export declare function resolveCatalogProviderId(provider: string): string;
34
+ /**
35
+ * Resolve the API key for a provider.
36
+ *
37
+ * Precedence: an explicit `apiKey`, then the shared `AI_API_KEY`, then the
38
+ * provider's catalog `envKey`. The previous hardcoded `process.env.AI_API_KEY`
39
+ * only meant an operator using the documented `OPENAI_API_KEY` naming got an
40
+ * empty key.
41
+ */
42
+ export declare function resolveApiKey(provider: string, explicit?: string): string;
43
+ /**
44
+ * A lazily-built, cached `HilbrasClient` per `provider::model` pair.
45
+ *
46
+ * Reusing a client preserves its connection pool and its adapter registry.
47
+ * Building one per request discarded both, and left a live cleanup interval
48
+ * behind for every request served.
49
+ */
50
+ export interface FrameworkClientPool {
51
+ /** Get a client with the requested provider and model registered. */
52
+ get(model: string): HilbrasClient;
53
+ /** The canonical registered provider name, for provider-scoped calls. */
54
+ readonly providerName: string;
55
+ /** Release every cached client. */
56
+ dispose(): Promise<void>;
57
+ }
58
+ export declare function createFrameworkClientPool(options: {
59
+ provider: string;
60
+ model: string;
61
+ apiKey?: string;
62
+ client?: HilbrasClient;
63
+ }): FrameworkClientPool;
64
+ /**
65
+ * Read and parse a JSON request body.
66
+ *
67
+ * Malformed JSON previously threw a bare `SyntaxError` out of the handler, so
68
+ * the response depended entirely on the host framework's error handling.
69
+ */
70
+ export declare function readJsonBody(request: Request): Promise<Record<string, unknown>>;
71
+ /** Read a required non-empty string field from a parsed body. */
72
+ export declare function requireString(body: Record<string, unknown>, field: string): string;
73
+ /** Read a required array field from a parsed body. */
74
+ export declare function requireArray(body: Record<string, unknown>, field: string): unknown[];
75
+ /**
76
+ * Map a thrown error to an HTTP response.
77
+ *
78
+ * Two classes of error are reported with their message:
79
+ *
80
+ * - `RequestValidationError`, a caller error, whose message names the offending
81
+ * field and nothing else.
82
+ * - `ConfigurationError`, an operator-config error. Its text is built from the
83
+ * handler's own options, so it is safe to return and it is what makes a typo
84
+ * in `createChatHandler({ provider })` debuggable at all.
85
+ *
86
+ * Everything else — including any provider-side failure — becomes a generic 500
87
+ * with no detail, so an internal message, provider response body, or key cannot
88
+ * leak through a public route. Route the detail to a server-side log or an
89
+ * `onError` hook instead.
90
+ */
91
+ export declare function errorResponse(error: unknown): Response;
@@ -0,0 +1,166 @@
1
+ /**
2
+ * @hilbras/sdk — Shared framework handler core
3
+ *
4
+ * Every framework adapter (Next.js route handlers, Astro endpoints, Remix
5
+ * actions) previously re-implemented the same request handling. `actions.ts`
6
+ * was byte-for-byte identical to `endpoints.ts` across 33 lines, and all three
7
+ * shared the same defects: they discarded the canonical provider name returned
8
+ * by `addProviderFromCatalog` and then called with the caller's spelling, they
9
+ * built a fresh client per request and never disposed it, they read a hardcoded
10
+ * environment variable, and they reported configuration failures as an HTTP 200
11
+ * with the error buried in the stream body.
12
+ *
13
+ * This module owns the parts that must behave identically everywhere. Framework
14
+ * files keep only what is genuinely framework-specific: how to read the request
15
+ * and how to build a `Response`.
16
+ */
17
+ import { HilbrasClient } from "../../client/client.js";
18
+ import { getProviderCatalog, listProviders } from "../../catalog/index.js";
19
+ import { ConfigurationError, RequestValidationError } from "../../errors/index.js";
20
+ /** Resolve a provider spelling to its canonical catalog id. */
21
+ export function resolveCatalogProviderId(provider) {
22
+ return (listProviders().find((id) => id.toLowerCase() === provider.toLowerCase()) ?? provider);
23
+ }
24
+ /**
25
+ * Resolve the API key for a provider.
26
+ *
27
+ * Precedence: an explicit `apiKey`, then the shared `AI_API_KEY`, then the
28
+ * provider's catalog `envKey`. The previous hardcoded `process.env.AI_API_KEY`
29
+ * only meant an operator using the documented `OPENAI_API_KEY` naming got an
30
+ * empty key.
31
+ */
32
+ export function resolveApiKey(provider, explicit) {
33
+ if (explicit)
34
+ return explicit;
35
+ const shared = typeof process !== "undefined" ? process.env?.AI_API_KEY : undefined;
36
+ if (shared)
37
+ return shared;
38
+ const catalog = getProviderCatalog(resolveCatalogProviderId(provider));
39
+ if (catalog?.envKey && typeof process !== "undefined") {
40
+ return process.env?.[catalog.envKey] ?? "";
41
+ }
42
+ return "";
43
+ }
44
+ export function createFrameworkClientPool(options) {
45
+ const apiKey = resolveApiKey(options.provider, options.apiKey);
46
+ const owned = new Set();
47
+ const cache = new Map();
48
+ // `providerName` is only known once a client has been built, because
49
+ // `addProviderFromCatalog` returns the canonical display name and registers
50
+ // under it. Reading the caller's spelling back is what broke the handlers.
51
+ let providerName = options.provider;
52
+ const pool = {
53
+ get(model) {
54
+ const key = model;
55
+ const cached = cache.get(key);
56
+ if (cached)
57
+ return cached;
58
+ const client = options.client ?? new HilbrasClient();
59
+ if (!options.client)
60
+ owned.add(client);
61
+ // Use the returned canonical name. Registering under the catalog display
62
+ // name and then calling with the caller's id was the root cause of
63
+ // `ProviderNotFoundError` in every shipped framework handler.
64
+ providerName = client.addProviderFromCatalog(options.provider, model, apiKey);
65
+ cache.set(key, client);
66
+ return client;
67
+ },
68
+ get providerName() {
69
+ return providerName;
70
+ },
71
+ async dispose() {
72
+ cache.clear();
73
+ for (const client of owned)
74
+ await client.dispose();
75
+ owned.clear();
76
+ },
77
+ };
78
+ return pool;
79
+ }
80
+ /**
81
+ * Read and parse a JSON request body.
82
+ *
83
+ * Malformed JSON previously threw a bare `SyntaxError` out of the handler, so
84
+ * the response depended entirely on the host framework's error handling.
85
+ */
86
+ export async function readJsonBody(request) {
87
+ let raw;
88
+ try {
89
+ raw = await request.text();
90
+ }
91
+ catch {
92
+ throw new RequestValidationError("Request body could not be read");
93
+ }
94
+ if (raw.trim().length === 0) {
95
+ throw new RequestValidationError("Request body is empty", "Send a JSON object.");
96
+ }
97
+ try {
98
+ const parsed = JSON.parse(raw);
99
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
100
+ throw new RequestValidationError("Request body must be a JSON object");
101
+ }
102
+ return parsed;
103
+ }
104
+ catch (error) {
105
+ if (error instanceof RequestValidationError)
106
+ throw error;
107
+ throw new RequestValidationError("Request body is not valid JSON");
108
+ }
109
+ }
110
+ /** Read a required non-empty string field from a parsed body. */
111
+ export function requireString(body, field) {
112
+ const value = body[field];
113
+ if (typeof value !== "string" || value.length === 0) {
114
+ throw new RequestValidationError(`"${field}" is required and must be a non-empty string`);
115
+ }
116
+ return value;
117
+ }
118
+ /** Read a required array field from a parsed body. */
119
+ export function requireArray(body, field) {
120
+ const value = body[field];
121
+ if (!Array.isArray(value)) {
122
+ throw new RequestValidationError(`"${field}" is required and must be an array`);
123
+ }
124
+ return value;
125
+ }
126
+ /**
127
+ * Map a thrown error to an HTTP response.
128
+ *
129
+ * Two classes of error are reported with their message:
130
+ *
131
+ * - `RequestValidationError`, a caller error, whose message names the offending
132
+ * field and nothing else.
133
+ * - `ConfigurationError`, an operator-config error. Its text is built from the
134
+ * handler's own options, so it is safe to return and it is what makes a typo
135
+ * in `createChatHandler({ provider })` debuggable at all.
136
+ *
137
+ * Everything else — including any provider-side failure — becomes a generic 500
138
+ * with no detail, so an internal message, provider response body, or key cannot
139
+ * leak through a public route. Route the detail to a server-side log or an
140
+ * `onError` hook instead.
141
+ */
142
+ export function errorResponse(error) {
143
+ const status = error?.status;
144
+ if (error instanceof RequestValidationError) {
145
+ return new Response(JSON.stringify({ error: error.message }), {
146
+ status: typeof status === "number" ? status : 400,
147
+ headers: { "Content-Type": "application/json" },
148
+ });
149
+ }
150
+ if (error instanceof ConfigurationError) {
151
+ return new Response(JSON.stringify({ error: error.message }), {
152
+ status: typeof status === "number" ? status : 500,
153
+ headers: { "Content-Type": "application/json" },
154
+ });
155
+ }
156
+ if (typeof status === "number" && status >= 400 && status < 600) {
157
+ return new Response(JSON.stringify({ error: "Request failed" }), {
158
+ status,
159
+ headers: { "Content-Type": "application/json" },
160
+ });
161
+ }
162
+ return new Response(JSON.stringify({ error: "Request failed" }), {
163
+ status: 500,
164
+ headers: { "Content-Type": "application/json" },
165
+ });
166
+ }
package/dist/index.d.ts CHANGED
@@ -17,7 +17,7 @@ export type { Model, ModelCapabilities } from "./types/models.js";
17
17
  export { DEFAULT_CAPABILITIES } from "./types/models.js";
18
18
  export type { EmbeddingParams, EmbeddingResult, ImageParams, ImageResult, SpeechParams, SpeechResult, TranscriptionParams, TranscriptionResult, RerankParams, RerankResult, ImageSize, ImageQuality, ImageStyle, SpeechVoice, SpeechFormat, TranscriptLanguage, TranscriptFormat, } from "./types/multi-modal.js";
19
19
  export { redact } from "./logging/logger.js";
20
- export { HilbrasSdkError, ProviderNotFoundError, ModelNotFoundError, ProviderRequestError, StreamError, InvalidFormatError, ConfigurationError, CircuitBreakerOpenError, ValidationError, } from "./errors/index.js";
20
+ export { HilbrasSdkError, ProviderNotFoundError, ModelNotFoundError, ProviderRequestError, StreamError, InvalidFormatError, ConfigurationError, CircuitBreakerOpenError, RequestValidationError, ValidationError, } from "./errors/index.js";
21
21
  export { ProviderRegistry } from "./providers/registry.js";
22
22
  export { AdapterRegistry, getDefaultAdapterRegistry } from "./providers/adapter-registry.js";
23
23
  export type { AdapterFactory } from "./providers/adapter-registry.js";
package/dist/index.js CHANGED
@@ -12,7 +12,7 @@ export { DEFAULT_CAPABILITIES } from "./types/models.js";
12
12
  // ─── Logging ────────────────────────────────────────────────────────────────
13
13
  export { redact } from "./logging/logger.js";
14
14
  // ─── Errors ─────────────────────────────────────────────────────────────────
15
- export { HilbrasSdkError, ProviderNotFoundError, ModelNotFoundError, ProviderRequestError, StreamError, InvalidFormatError, ConfigurationError, CircuitBreakerOpenError, ValidationError, } from "./errors/index.js";
15
+ export { HilbrasSdkError, ProviderNotFoundError, ModelNotFoundError, ProviderRequestError, StreamError, InvalidFormatError, ConfigurationError, CircuitBreakerOpenError, RequestValidationError, ValidationError, } from "./errors/index.js";
16
16
  // ─── Providers ──────────────────────────────────────────────────────────────
17
17
  export { ProviderRegistry } from "./providers/registry.js";
18
18
  export { AdapterRegistry, getDefaultAdapterRegistry } from "./providers/adapter-registry.js";
@@ -26,6 +26,15 @@ export declare class FetchTransport implements Transport {
26
26
  private _coalesce;
27
27
  private _cleanupTimer;
28
28
  constructor(options?: FetchTransportOptions);
29
+ /**
30
+ * Start the idle-connection cleanup timer on first use.
31
+ *
32
+ * The timer is deliberately lazy. A client that never issues a request —
33
+ * including one whose constructor throws before the caller can dispose it —
34
+ * then holds no interval, so a failed construction cannot leave a repeating
35
+ * timer that pins the Node event loop open.
36
+ */
37
+ private _ensureCleanupTimer;
29
38
  private _getOrigin;
30
39
  private _acquire;
31
40
  private _release;
@@ -20,10 +20,21 @@ export class FetchTransport {
20
20
  this._maxConnections = options.maxConnectionsPerOrigin ?? 6;
21
21
  this._idleTimeout = options.idleTimeout ?? 30000;
22
22
  this._coalesce = options.coalesceRequests ?? false;
23
- // Clean up idle connections periodically
24
- if (typeof setInterval !== "undefined") {
25
- this._cleanupTimer = setInterval(() => this._cleanupPools(), this._idleTimeout);
26
- }
23
+ }
24
+ /**
25
+ * Start the idle-connection cleanup timer on first use.
26
+ *
27
+ * The timer is deliberately lazy. A client that never issues a request —
28
+ * including one whose constructor throws before the caller can dispose it —
29
+ * then holds no interval, so a failed construction cannot leave a repeating
30
+ * timer that pins the Node event loop open.
31
+ */
32
+ _ensureCleanupTimer() {
33
+ if (this._cleanupTimer !== null || typeof setInterval === "undefined")
34
+ return;
35
+ this._cleanupTimer = setInterval(() => this._cleanupPools(), this._idleTimeout);
36
+ // Never keep a process alive just to age out an idle connection pool.
37
+ this._cleanupTimer.unref?.();
27
38
  }
28
39
  _getOrigin(url) {
29
40
  try {
@@ -76,6 +87,7 @@ export class FetchTransport {
76
87
  return JSON.stringify([init.method || "GET", url, init.body ?? "", headers]);
77
88
  }
78
89
  async request(url, init) {
90
+ this._ensureCleanupTimer();
79
91
  const origin = this._getOrigin(url);
80
92
  const externalSignal = init.signal;
81
93
  if (externalSignal?.aborted) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hilbras/sdk",
3
- "version": "3.4.2",
3
+ "version": "3.4.4",
4
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",