@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
package/dist/adapters/groq.js
CHANGED
|
@@ -8,16 +8,16 @@
|
|
|
8
8
|
* - Uses Authorization: Bearer (like OpenAI)
|
|
9
9
|
* - Has its own model names (llama-3.3-70b-versatile, mixtral-8x7b, etc.)
|
|
10
10
|
* - Stricter rate limits
|
|
11
|
-
* -
|
|
11
|
+
* - Native tool calling via the OpenAI `tools` field
|
|
12
12
|
*/
|
|
13
13
|
import { ProviderRequestError } from "../errors/index.js";
|
|
14
14
|
import { ReasoningNormalizer } from "../reasoning/normalizer.js";
|
|
15
|
+
import { splitSseFrames } from "../utils/sse.js";
|
|
15
16
|
import { mergeExtraParams } from "./extra.js";
|
|
16
17
|
/**
|
|
17
18
|
* GroqAdapter — OpenAI-compatible adapter for Groq's fast inference.
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
* text-tool-call-parser handles automatically.
|
|
19
|
+
* Tool calling is native: `tools` goes out in the OpenAI shape and the model
|
|
20
|
+
* replies with `tool_calls`.
|
|
21
21
|
*/
|
|
22
22
|
export class GroqAdapter {
|
|
23
23
|
id = "groq";
|
|
@@ -59,6 +59,19 @@ export class GroqAdapter {
|
|
|
59
59
|
if (params.stream) {
|
|
60
60
|
body.stream_options = { include_usage: true };
|
|
61
61
|
}
|
|
62
|
+
// Groq speaks the OpenAI wire format and supports native tool calling, but
|
|
63
|
+
// the field was never sent — so `tools` reached the model not at all, while
|
|
64
|
+
// the stream loop's native `tool_calls` branch sat unreachable.
|
|
65
|
+
if (params.tools?.length) {
|
|
66
|
+
body.tools = params.tools.map((t) => ({
|
|
67
|
+
type: "function",
|
|
68
|
+
function: {
|
|
69
|
+
name: t.function.name,
|
|
70
|
+
description: t.function.description,
|
|
71
|
+
parameters: t.function.parameters,
|
|
72
|
+
},
|
|
73
|
+
}));
|
|
74
|
+
}
|
|
62
75
|
if (params.extra) {
|
|
63
76
|
mergeExtraParams(body, params.extra);
|
|
64
77
|
}
|
|
@@ -98,16 +111,10 @@ export class GroqAdapter {
|
|
|
98
111
|
const { done, value } = await reader.read();
|
|
99
112
|
if (done)
|
|
100
113
|
break;
|
|
101
|
-
buffer
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
const lines = part.split("\n");
|
|
106
|
-
let rawData = "";
|
|
107
|
-
for (const line of lines) {
|
|
108
|
-
if (line.startsWith("data: "))
|
|
109
|
-
rawData = line.slice(6).trim();
|
|
110
|
-
}
|
|
114
|
+
const decoded = splitSseFrames(buffer, decoder.decode(value, { stream: true }));
|
|
115
|
+
buffer = decoded.buffer;
|
|
116
|
+
for (const frame of decoded.frames) {
|
|
117
|
+
const rawData = frame.data.trim();
|
|
111
118
|
if (!rawData || rawData === "[DONE]")
|
|
112
119
|
continue;
|
|
113
120
|
let data;
|
|
@@ -130,20 +137,25 @@ export class GroqAdapter {
|
|
|
130
137
|
if (!choices?.length)
|
|
131
138
|
continue;
|
|
132
139
|
const choice = choices[0];
|
|
140
|
+
const finishReason = choice.finish_reason;
|
|
141
|
+
if (finishReason) {
|
|
142
|
+
yield { type: "finish", reason: finishReason };
|
|
143
|
+
}
|
|
133
144
|
const delta = choice.delta;
|
|
134
145
|
if (!delta)
|
|
135
146
|
continue;
|
|
136
147
|
const content = delta.content;
|
|
137
148
|
if (content) {
|
|
138
|
-
const
|
|
139
|
-
if (
|
|
140
|
-
|
|
149
|
+
const reasoningParts = reasoningNormalizer.feedText(content);
|
|
150
|
+
if (reasoningParts.length > 0) {
|
|
151
|
+
for (const part of reasoningParts)
|
|
152
|
+
yield part;
|
|
153
|
+
}
|
|
141
154
|
else if (!ReasoningNormalizer.looksLikeReasoningTag(content)) {
|
|
142
155
|
yield { type: "text", text: content };
|
|
143
156
|
}
|
|
144
157
|
continue;
|
|
145
158
|
}
|
|
146
|
-
// Groq may support tool calls in the future
|
|
147
159
|
const toolCalls = delta.tool_calls;
|
|
148
160
|
if (toolCalls) {
|
|
149
161
|
for (const tc of toolCalls) {
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
*/
|
|
14
14
|
import { ProviderRequestError } from "../errors/index.js";
|
|
15
15
|
import { ReasoningNormalizer } from "../reasoning/normalizer.js";
|
|
16
|
+
import { splitSseFrames } from "../utils/sse.js";
|
|
16
17
|
export class HuggingFaceAdapter {
|
|
17
18
|
id = "huggingface";
|
|
18
19
|
_provider;
|
|
@@ -109,16 +110,10 @@ export class HuggingFaceAdapter {
|
|
|
109
110
|
const { done, value } = await reader.read();
|
|
110
111
|
if (done)
|
|
111
112
|
break;
|
|
112
|
-
buffer
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
const lines = part.split("\n");
|
|
117
|
-
let rawData = "";
|
|
118
|
-
for (const line of lines) {
|
|
119
|
-
if (line.startsWith("data: "))
|
|
120
|
-
rawData = line.slice(6).trim();
|
|
121
|
-
}
|
|
113
|
+
const decoded = splitSseFrames(buffer, decoder.decode(value, { stream: true }));
|
|
114
|
+
buffer = decoded.buffer;
|
|
115
|
+
for (const frame of decoded.frames) {
|
|
116
|
+
const rawData = frame.data.trim();
|
|
122
117
|
if (!rawData || rawData === "[DONE]")
|
|
123
118
|
continue;
|
|
124
119
|
let data;
|
|
@@ -151,9 +146,11 @@ export class HuggingFaceAdapter {
|
|
|
151
146
|
}
|
|
152
147
|
const content = delta.content;
|
|
153
148
|
if (content) {
|
|
154
|
-
const
|
|
155
|
-
if (
|
|
156
|
-
|
|
149
|
+
const reasoningParts = reasoningNormalizer.feedText(content);
|
|
150
|
+
if (reasoningParts.length > 0) {
|
|
151
|
+
for (const part of reasoningParts)
|
|
152
|
+
yield part;
|
|
153
|
+
}
|
|
157
154
|
else if (!ReasoningNormalizer.looksLikeReasoningTag(content)) {
|
|
158
155
|
yield { type: "text", text: content };
|
|
159
156
|
}
|
|
@@ -18,7 +18,8 @@ import type { EmbeddingParams, EmbeddingResult } from "../types/multi-modal.js";
|
|
|
18
18
|
export type OllamaAdapterConfig = AdapterConfig;
|
|
19
19
|
/**
|
|
20
20
|
* OllamaAdapter — OpenAI-compatible adapter for Ollama local models.
|
|
21
|
-
* No API key needed.
|
|
21
|
+
* No API key needed. Tool calling is native: `tools` goes out in the OpenAI
|
|
22
|
+
* shape and tool-capable models reply with `tool_calls`.
|
|
22
23
|
*/
|
|
23
24
|
export declare class OllamaAdapter implements AIProvider {
|
|
24
25
|
readonly id = "ollama";
|
package/dist/adapters/ollama.js
CHANGED
|
@@ -12,10 +12,12 @@
|
|
|
12
12
|
*/
|
|
13
13
|
import { ProviderRequestError } from "../errors/index.js";
|
|
14
14
|
import { ReasoningNormalizer } from "../reasoning/normalizer.js";
|
|
15
|
+
import { splitSseFrames } from "../utils/sse.js";
|
|
15
16
|
import { mergeExtraParams } from "./extra.js";
|
|
16
17
|
/**
|
|
17
18
|
* OllamaAdapter — OpenAI-compatible adapter for Ollama local models.
|
|
18
|
-
* No API key needed.
|
|
19
|
+
* No API key needed. Tool calling is native: `tools` goes out in the OpenAI
|
|
20
|
+
* shape and tool-capable models reply with `tool_calls`.
|
|
19
21
|
*/
|
|
20
22
|
export class OllamaAdapter {
|
|
21
23
|
id = "ollama";
|
|
@@ -39,8 +41,24 @@ export class OllamaAdapter {
|
|
|
39
41
|
};
|
|
40
42
|
if (params.temperature !== undefined)
|
|
41
43
|
body.temperature = params.temperature;
|
|
44
|
+
// The adapter calls `/v1/chat/completions`, so the limit belongs in the
|
|
45
|
+
// OpenAI-shaped `max_tokens`. `options.num_predict` is a native-API field
|
|
46
|
+
// and was ignored on this endpoint, leaving maxTokens with no effect.
|
|
42
47
|
if (params.maxTokens != null && params.maxTokens > 0)
|
|
43
|
-
body.
|
|
48
|
+
body.max_tokens = params.maxTokens;
|
|
49
|
+
// Ollama's OpenAI-compatible endpoint accepts `tools` for tool-capable
|
|
50
|
+
// models. It was never sent, so the stream loop's native `tool_calls`
|
|
51
|
+
// branch was unreachable.
|
|
52
|
+
if (params.tools?.length) {
|
|
53
|
+
body.tools = params.tools.map((t) => ({
|
|
54
|
+
type: "function",
|
|
55
|
+
function: {
|
|
56
|
+
name: t.function.name,
|
|
57
|
+
description: t.function.description,
|
|
58
|
+
parameters: t.function.parameters,
|
|
59
|
+
},
|
|
60
|
+
}));
|
|
61
|
+
}
|
|
44
62
|
if (params.extra) {
|
|
45
63
|
mergeExtraParams(body, params.extra);
|
|
46
64
|
}
|
|
@@ -54,6 +72,7 @@ export class OllamaAdapter {
|
|
|
54
72
|
messages: params.messages,
|
|
55
73
|
temperature: params.temperature ?? 0.7,
|
|
56
74
|
maxTokens: params.maxTokens,
|
|
75
|
+
tools: params.tools,
|
|
57
76
|
stream: true,
|
|
58
77
|
extra: params.extra,
|
|
59
78
|
});
|
|
@@ -78,16 +97,10 @@ export class OllamaAdapter {
|
|
|
78
97
|
const { done, value } = await reader.read();
|
|
79
98
|
if (done)
|
|
80
99
|
break;
|
|
81
|
-
buffer
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
const lines = part.split("\n");
|
|
86
|
-
let rawData = "";
|
|
87
|
-
for (const line of lines) {
|
|
88
|
-
if (line.startsWith("data: "))
|
|
89
|
-
rawData = line.slice(6).trim();
|
|
90
|
-
}
|
|
100
|
+
const decoded = splitSseFrames(buffer, decoder.decode(value, { stream: true }));
|
|
101
|
+
buffer = decoded.buffer;
|
|
102
|
+
for (const frame of decoded.frames) {
|
|
103
|
+
const rawData = frame.data.trim();
|
|
91
104
|
if (!rawData || rawData === "[DONE]")
|
|
92
105
|
continue;
|
|
93
106
|
let data;
|
|
@@ -97,24 +110,38 @@ export class OllamaAdapter {
|
|
|
97
110
|
catch {
|
|
98
111
|
continue;
|
|
99
112
|
}
|
|
113
|
+
if (data.usage) {
|
|
114
|
+
const usage = data.usage;
|
|
115
|
+
yield {
|
|
116
|
+
type: "usage",
|
|
117
|
+
inputTokens: usage.prompt_tokens ?? 0,
|
|
118
|
+
outputTokens: usage.completion_tokens ?? 0,
|
|
119
|
+
totalTokens: usage.total_tokens ?? 0,
|
|
120
|
+
};
|
|
121
|
+
}
|
|
100
122
|
const choices = data.choices;
|
|
101
123
|
if (!choices?.length)
|
|
102
124
|
continue;
|
|
103
125
|
const choice = choices[0];
|
|
126
|
+
const finishReason = choice.finish_reason;
|
|
127
|
+
if (finishReason) {
|
|
128
|
+
yield { type: "finish", reason: finishReason };
|
|
129
|
+
}
|
|
104
130
|
const delta = choice.delta;
|
|
105
131
|
if (!delta)
|
|
106
132
|
continue;
|
|
107
133
|
const content = delta.content;
|
|
108
134
|
if (content) {
|
|
109
|
-
const
|
|
110
|
-
if (
|
|
111
|
-
|
|
135
|
+
const reasoningParts = reasoningNormalizer.feedText(content);
|
|
136
|
+
if (reasoningParts.length > 0) {
|
|
137
|
+
for (const part of reasoningParts)
|
|
138
|
+
yield part;
|
|
139
|
+
}
|
|
112
140
|
else if (!ReasoningNormalizer.looksLikeReasoningTag(content)) {
|
|
113
141
|
yield { type: "text", text: content };
|
|
114
142
|
}
|
|
115
143
|
continue;
|
|
116
144
|
}
|
|
117
|
-
// Ollama may support tool calls in the future
|
|
118
145
|
const toolCalls = delta.tool_calls;
|
|
119
146
|
if (toolCalls) {
|
|
120
147
|
for (const tc of toolCalls) {
|
|
@@ -152,6 +179,7 @@ export class OllamaAdapter {
|
|
|
152
179
|
messages: params.messages,
|
|
153
180
|
temperature: params.temperature ?? 0.7,
|
|
154
181
|
maxTokens: params.maxTokens,
|
|
182
|
+
tools: params.tools,
|
|
155
183
|
stream: false,
|
|
156
184
|
extra: params.extra,
|
|
157
185
|
});
|
|
@@ -174,7 +202,11 @@ export class OllamaAdapter {
|
|
|
174
202
|
}
|
|
175
203
|
// ─── Multi-Modal: Embeddings ────────────────────────────────────────────
|
|
176
204
|
async embed(params) {
|
|
177
|
-
|
|
205
|
+
// The native endpoint sits at the Ollama root, but the configured baseUrl
|
|
206
|
+
// carries the OpenAI-compatible `/v1` suffix. Appending the native path
|
|
207
|
+
// without stripping it produced `<host>/v1/api/embeddings` — a 404.
|
|
208
|
+
const root = this._provider.baseUrl.replace(/\/v1\/?$/, "");
|
|
209
|
+
const url = `${root}/api/embeddings`;
|
|
178
210
|
const body = {
|
|
179
211
|
model: params.model,
|
|
180
212
|
prompt: Array.isArray(params.input) ? params.input.join("\n") : params.input,
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
*/
|
|
12
12
|
import { ProviderRequestError } from "../errors/index.js";
|
|
13
13
|
import { ReasoningNormalizer } from "../reasoning/normalizer.js";
|
|
14
|
+
import { splitSseFrames } from "../utils/sse.js";
|
|
14
15
|
import { TextToolCallParser } from "./text-tool-call-parser.js";
|
|
15
16
|
import { assertExtraFieldAllowed } from "./extra.js";
|
|
16
17
|
/**
|
|
@@ -161,16 +162,10 @@ export class GenericOpenAIAdapter {
|
|
|
161
162
|
const { done, value } = await reader.read();
|
|
162
163
|
if (done)
|
|
163
164
|
break;
|
|
164
|
-
buffer
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
const lines = part.split("\n");
|
|
169
|
-
let rawData = "";
|
|
170
|
-
for (const line of lines) {
|
|
171
|
-
if (line.startsWith("data: "))
|
|
172
|
-
rawData = line.slice(6).trim();
|
|
173
|
-
}
|
|
165
|
+
const decoded = splitSseFrames(buffer, decoder.decode(value, { stream: true }));
|
|
166
|
+
buffer = decoded.buffer;
|
|
167
|
+
for (const frame of decoded.frames) {
|
|
168
|
+
const rawData = frame.data.trim();
|
|
174
169
|
if (!rawData || rawData === "[DONE]")
|
|
175
170
|
continue;
|
|
176
171
|
let data;
|
|
@@ -207,9 +202,10 @@ export class GenericOpenAIAdapter {
|
|
|
207
202
|
}
|
|
208
203
|
const content = delta.content;
|
|
209
204
|
if (content) {
|
|
210
|
-
const
|
|
211
|
-
if (
|
|
212
|
-
|
|
205
|
+
const reasoningParts = reasoningNormalizer.feedText(content);
|
|
206
|
+
if (reasoningParts.length > 0) {
|
|
207
|
+
for (const part of reasoningParts)
|
|
208
|
+
yield part;
|
|
213
209
|
}
|
|
214
210
|
else if (!ReasoningNormalizer.looksLikeReasoningTag(content)) {
|
|
215
211
|
if (this._supportsNativeTools) {
|
package/dist/adapters/openai.js
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
*/
|
|
11
11
|
import { ProviderRequestError } from "../errors/index.js";
|
|
12
12
|
import { ReasoningNormalizer } from "../reasoning/normalizer.js";
|
|
13
|
+
import { splitSseFrames } from "../utils/sse.js";
|
|
13
14
|
import { TextToolCallParser } from "./text-tool-call-parser.js";
|
|
14
15
|
import { messageToDict } from "../types/messages.js";
|
|
15
16
|
import { assertExtraFieldAllowed } from "./extra.js";
|
|
@@ -146,16 +147,10 @@ export class OpenAIAdapter {
|
|
|
146
147
|
const { done, value } = await reader.read();
|
|
147
148
|
if (done)
|
|
148
149
|
break;
|
|
149
|
-
buffer
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
const lines = part.split("\n");
|
|
154
|
-
let rawData = "";
|
|
155
|
-
for (const line of lines) {
|
|
156
|
-
if (line.startsWith("data: "))
|
|
157
|
-
rawData = line.slice(6).trim();
|
|
158
|
-
}
|
|
150
|
+
const decoded = splitSseFrames(buffer, decoder.decode(value, { stream: true }));
|
|
151
|
+
buffer = decoded.buffer;
|
|
152
|
+
for (const frame of decoded.frames) {
|
|
153
|
+
const rawData = frame.data.trim();
|
|
159
154
|
if (!rawData || rawData === "[DONE]")
|
|
160
155
|
continue;
|
|
161
156
|
let data;
|
|
@@ -198,9 +193,10 @@ export class OpenAIAdapter {
|
|
|
198
193
|
// Text content — check for reasoning tags
|
|
199
194
|
const content = delta.content;
|
|
200
195
|
if (content) {
|
|
201
|
-
const
|
|
202
|
-
if (
|
|
203
|
-
|
|
196
|
+
const reasoningParts = reasoningNormalizer.feedText(content);
|
|
197
|
+
if (reasoningParts.length > 0) {
|
|
198
|
+
for (const part of reasoningParts)
|
|
199
|
+
yield part;
|
|
204
200
|
}
|
|
205
201
|
else if (!ReasoningNormalizer.looksLikeReasoningTag(content)) {
|
|
206
202
|
yield* emitTextToolCallItems(textToolCalls.feed(content));
|
package/dist/catalog/models.d.ts
CHANGED
|
@@ -14,6 +14,16 @@ export interface ModelEntry {
|
|
|
14
14
|
capabilities: ModelCapabilities;
|
|
15
15
|
aliases?: string[];
|
|
16
16
|
}
|
|
17
|
+
/**
|
|
18
|
+
* The models the router enforces limits from.
|
|
19
|
+
*
|
|
20
|
+
* `provider-catalog.ts` is generated from upstream model metadata and is the
|
|
21
|
+
* data source; the array above is hand-written code. Both are published, and
|
|
22
|
+
* they had drifted — the catalog said 1050000/128000 where this table said
|
|
23
|
+
* 1048576/131072 — so a caller reading `getProviderCatalog()` could be told a
|
|
24
|
+
* different context window from the one the router applies. The generated
|
|
25
|
+
* figures win for every id it knows about; local-only entries keep their own.
|
|
26
|
+
*/
|
|
17
27
|
export declare const BUILTIN_MODELS: ModelEntry[];
|
|
18
28
|
export declare function findModel(query: string): ModelEntry | undefined;
|
|
19
29
|
export declare function modelsForProvider(provider: string): ModelEntry[];
|
package/dist/catalog/models.js
CHANGED
|
@@ -4,6 +4,23 @@
|
|
|
4
4
|
* Pre-configured model definitions for common providers.
|
|
5
5
|
* Users can extend this with their own models via addProvider().
|
|
6
6
|
*/
|
|
7
|
+
import catalog from "./provider-catalog.js";
|
|
8
|
+
/**
|
|
9
|
+
* Context window and output limit published in the generated catalog, by model
|
|
10
|
+
* id. See `BUILTIN_MODELS` for why this table is consulted.
|
|
11
|
+
*/
|
|
12
|
+
const PUBLISHED_LIMITS = (() => {
|
|
13
|
+
const limits = new Map();
|
|
14
|
+
const providers = catalog.providers;
|
|
15
|
+
for (const provider of Object.values(providers)) {
|
|
16
|
+
for (const model of provider.models ?? []) {
|
|
17
|
+
if (typeof model.contextWindow === "number" && typeof model.maxOutput === "number") {
|
|
18
|
+
limits.set(model.id, { contextWindow: model.contextWindow, maxOutput: model.maxOutput });
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return limits;
|
|
23
|
+
})();
|
|
7
24
|
const ALL_FALSE_CAPS = {
|
|
8
25
|
streaming: false, tools: false, vision: false, reasoning: false,
|
|
9
26
|
structuredOutput: false, parallelTools: false, systemPrompts: false,
|
|
@@ -20,7 +37,7 @@ const IMAGE_GEN_CAPS = { ...ALL_FALSE_CAPS, imageGeneration: true };
|
|
|
20
37
|
const SPEECH_CAPS = { ...ALL_FALSE_CAPS, speech: true };
|
|
21
38
|
const TRANSCRIPTION_CAPS = { ...ALL_FALSE_CAPS, transcription: true };
|
|
22
39
|
const RERANK_CAPS = { ...ALL_FALSE_CAPS, reranking: true };
|
|
23
|
-
|
|
40
|
+
const MODEL_DEFINITIONS = [
|
|
24
41
|
// ─── OpenAI ───────────────────────────────────────────────────────
|
|
25
42
|
{ id: "gpt-5.6-sol", name: "GPT-5.6 Sol", provider: "openai", contextWindow: 1_048_576, maxOutput: 131_072, capabilities: FULL_CAPS, aliases: ["5.6-sol", "gpt5.6"] },
|
|
26
43
|
{ id: "gpt-5.6-terra", name: "GPT-5.6 Terra", provider: "openai", contextWindow: 1_048_576, maxOutput: 131_072, capabilities: FULL_CAPS, aliases: ["5.6-terra", "terra"] },
|
|
@@ -160,6 +177,20 @@ export const BUILTIN_MODELS = [
|
|
|
160
177
|
{ id: "rerank-english-v3.0", name: "Cohere Rerank v3", provider: "cohere", contextWindow: 512, maxOutput: 0, capabilities: RERANK_CAPS, aliases: ["cohere-rerank"] },
|
|
161
178
|
{ id: "rerank-multilingual-v3.0", name: "Cohere Rerank Multilingual v3", provider: "cohere", contextWindow: 512, maxOutput: 0, capabilities: RERANK_CAPS, aliases: ["cohere-rerank-ml"] },
|
|
162
179
|
];
|
|
180
|
+
/**
|
|
181
|
+
* The models the router enforces limits from.
|
|
182
|
+
*
|
|
183
|
+
* `provider-catalog.ts` is generated from upstream model metadata and is the
|
|
184
|
+
* data source; the array above is hand-written code. Both are published, and
|
|
185
|
+
* they had drifted — the catalog said 1050000/128000 where this table said
|
|
186
|
+
* 1048576/131072 — so a caller reading `getProviderCatalog()` could be told a
|
|
187
|
+
* different context window from the one the router applies. The generated
|
|
188
|
+
* figures win for every id it knows about; local-only entries keep their own.
|
|
189
|
+
*/
|
|
190
|
+
export const BUILTIN_MODELS = MODEL_DEFINITIONS.map((entry) => {
|
|
191
|
+
const published = PUBLISHED_LIMITS.get(entry.id);
|
|
192
|
+
return published ? { ...entry, ...published } : entry;
|
|
193
|
+
});
|
|
163
194
|
export function findModel(query) {
|
|
164
195
|
const q = query.toLowerCase();
|
|
165
196
|
return BUILTIN_MODELS.find((m) => m.id === q || m.name.toLowerCase() === q || m.aliases?.includes(q));
|
package/dist/client/client.js
CHANGED
|
@@ -35,6 +35,26 @@ import { BudgetTracker } from "../cost/tracker.js";
|
|
|
35
35
|
import { estimateTokens } from "../tokens/counter.js";
|
|
36
36
|
import { getProviderCatalog, getModelsForProvider, listProviders } from "../catalog/index.js";
|
|
37
37
|
import { PluginRegistry } from "../plugin/registry.js";
|
|
38
|
+
import { registerKnownSecret } from "../security/known-secrets.js";
|
|
39
|
+
/**
|
|
40
|
+
* Credential material a provider config carries, so it can be registered for
|
|
41
|
+
* value-based redaction. Covers bearer keys, header auth values, and any extra
|
|
42
|
+
* header whose name looks credential-ish — Bedrock passes its access key id
|
|
43
|
+
* that way.
|
|
44
|
+
*/
|
|
45
|
+
function credentialsOf(provider) {
|
|
46
|
+
const credentials = [];
|
|
47
|
+
const authentication = provider.authentication;
|
|
48
|
+
if (authentication.type === "bearer")
|
|
49
|
+
credentials.push(authentication.apiKey);
|
|
50
|
+
if (authentication.type === "header")
|
|
51
|
+
credentials.push(authentication.value);
|
|
52
|
+
for (const [name, value] of Object.entries(provider.extraHeaders ?? {})) {
|
|
53
|
+
if (/key|token|secret|auth/i.test(name))
|
|
54
|
+
credentials.push(value);
|
|
55
|
+
}
|
|
56
|
+
return credentials;
|
|
57
|
+
}
|
|
38
58
|
/**
|
|
39
59
|
* Maximum number of authorization diagnostics retained per client. Older
|
|
40
60
|
* entries are dropped so a long-lived client cannot grow without bound.
|
|
@@ -216,6 +236,11 @@ export class HilbrasClient {
|
|
|
216
236
|
// ─── Provider Management ────────────────────────────────────────────────
|
|
217
237
|
addProvider(config) {
|
|
218
238
|
const ownedConfig = cloneProviderConfig(config);
|
|
239
|
+
// Remember the credentials so they can be scrubbed by exact value from any
|
|
240
|
+
// error or log line. Pattern matching alone misses short keys: `sk-` needs
|
|
241
|
+
// 20 characters after the prefix.
|
|
242
|
+
for (const secret of credentialsOf(ownedConfig))
|
|
243
|
+
registerKnownSecret(secret);
|
|
219
244
|
// v0.9.3: SSRF guard. Per-provider `allowInsecure` overrides client-wide
|
|
220
245
|
// `allowInsecureUrls`; local targets require explicit opt-in.
|
|
221
246
|
const guard = validateBaseUrl(ownedConfig.baseUrl, {
|
|
@@ -435,7 +460,12 @@ export class HilbrasClient {
|
|
|
435
460
|
_resolveProviderModel(params) {
|
|
436
461
|
// If explicit provider + model, use them directly
|
|
437
462
|
if (params.provider && params.model) {
|
|
438
|
-
return {
|
|
463
|
+
return {
|
|
464
|
+
providerName: params.provider,
|
|
465
|
+
modelId: params.model,
|
|
466
|
+
score: 0,
|
|
467
|
+
reasons: ["Explicit provider/model"],
|
|
468
|
+
};
|
|
439
469
|
}
|
|
440
470
|
// Auto-connect: structured output requirement → router capability filter
|
|
441
471
|
const needsStructured = params.needsStructuredOutput ?? params.hasOutput ?? false;
|
|
@@ -455,7 +485,12 @@ export class HilbrasClient {
|
|
|
455
485
|
throw new Error("No model found matching the given requirements. " +
|
|
456
486
|
"Try relaxing constraints or registering more providers.");
|
|
457
487
|
}
|
|
458
|
-
return {
|
|
488
|
+
return {
|
|
489
|
+
providerName: result.provider,
|
|
490
|
+
modelId: result.model,
|
|
491
|
+
score: result.score,
|
|
492
|
+
reasons: result.reasons,
|
|
493
|
+
};
|
|
459
494
|
}
|
|
460
495
|
// ─── Message Normalization ──────────────────────────────────────────────
|
|
461
496
|
_normalizeMessages(raw) {
|
|
@@ -472,12 +507,12 @@ export class HilbrasClient {
|
|
|
472
507
|
const startTime = performance.now();
|
|
473
508
|
this._emit({ type: "request.start", requestId, timestamp: startTime, provider: params.provider, model: params.model, task: params.task });
|
|
474
509
|
// Resolve provider + model — either explicit or via router
|
|
475
|
-
const { providerName, modelId } = this._resolveProviderModel(params);
|
|
510
|
+
const { providerName, modelId, score, reasons } = this._resolveProviderModel(params);
|
|
476
511
|
const providerConfig = this._registry.getOrThrow(providerName);
|
|
477
512
|
const model = providerConfig.models.find((m) => m.id === modelId);
|
|
478
513
|
if (!model)
|
|
479
514
|
throw new ModelNotFoundError(modelId, providerName, providerConfig.models.map((m) => m.id));
|
|
480
|
-
this._emit({ type: "routing.resolved", requestId, timestamp: performance.now(), provider: providerName, model: modelId, score
|
|
515
|
+
this._emit({ type: "routing.resolved", requestId, timestamp: performance.now(), provider: providerName, model: modelId, score, reasons });
|
|
481
516
|
const messages = this._normalizeMessages(params.messages);
|
|
482
517
|
const estimatedCost = this._budgetTracker.estimate(modelId, providerName, this._estimateTokens(messages.map((m) => m.content ?? "").join("")), 0);
|
|
483
518
|
yield* this._requestPipeline.runStream({
|
|
@@ -521,7 +556,7 @@ export class HilbrasClient {
|
|
|
521
556
|
}
|
|
522
557
|
const providerName = resolved_.providerName;
|
|
523
558
|
const modelId = resolved_.modelId;
|
|
524
|
-
this._emit({ type: "routing.resolved", requestId, timestamp: performance.now(), provider: providerName, model: modelId, score:
|
|
559
|
+
this._emit({ type: "routing.resolved", requestId, timestamp: performance.now(), provider: providerName, model: modelId, score: resolved_.score, reasons: resolved_.reasons });
|
|
525
560
|
if (!params.output) {
|
|
526
561
|
const messages = this._normalizeMessages(params.messages);
|
|
527
562
|
const estimatedCost = this._budgetTracker.estimate(modelId, providerName, this._estimateTokens(messages.map((m) => m.content ?? "").join("")), 0);
|
|
@@ -607,13 +642,23 @@ export class HilbrasClient {
|
|
|
607
642
|
}
|
|
608
643
|
catch (err) {
|
|
609
644
|
lastError = err instanceof Error ? err : new Error(String(err));
|
|
645
|
+
// Caller cancellation is not a provider failure: do not retry it, and
|
|
646
|
+
// do not count it against the circuit breaker.
|
|
647
|
+
if (userSignal?.aborted) {
|
|
648
|
+
this._emit({ type: "request.failed", requestId, timestamp: performance.now(), provider: providerName, model: modelId, durationMs: performance.now() - startTime, attempts: attempt + 1, error: lastError.message });
|
|
649
|
+
throw lastError;
|
|
650
|
+
}
|
|
610
651
|
const status = err.status ?? 0;
|
|
611
|
-
|
|
652
|
+
// Gate on status when there is one. The network classifier ignores the
|
|
653
|
+
// status and defaults on, so `A || B` retried 401/403/404 as well.
|
|
654
|
+
const retryable = status > 0
|
|
655
|
+
? shouldRetry(status, attempt, retryConfig)
|
|
656
|
+
: shouldRetryNetworkError(attempt, retryConfig);
|
|
612
657
|
circuitBreaker?.recordFailure(lastError);
|
|
613
658
|
if (retryable && attempt < maxAttempts - 1) {
|
|
614
659
|
const delay = calculateBackoff(attempt, resolved.backoff);
|
|
615
660
|
this._emit({ type: "request.retrying", requestId, timestamp: performance.now(), provider: providerName, attempt, delayMs: delay, reason: lastError.message });
|
|
616
|
-
await sleep(delay);
|
|
661
|
+
await sleep(delay, userSignal);
|
|
617
662
|
continue;
|
|
618
663
|
}
|
|
619
664
|
this._emit({ type: "request.failed", requestId, timestamp: performance.now(), provider: providerName, model: modelId, durationMs: performance.now() - startTime, attempts: attempt + 1, error: lastError.message });
|
|
@@ -102,7 +102,10 @@ function validateValues(values, source) {
|
|
|
102
102
|
else {
|
|
103
103
|
const guard = validateBaseUrl(provider.baseUrl, { allowInsecure: !!provider.allowInsecure });
|
|
104
104
|
if (!guard.ok) {
|
|
105
|
-
|
|
105
|
+
// The guard echoes the URL it rejected, and a URL can carry a key in
|
|
106
|
+
// its query string. Strip the literal before it reaches diagnostics.
|
|
107
|
+
const reason = guard.reason.split(provider.baseUrl).join("[URL]");
|
|
108
|
+
diagnostics.push(errorDiagnostic(source, "CONFIG_UNSAFE_PROVIDER_URL", `${path}.baseUrl`, `provider URL rejected by security policy: ${reason}`));
|
|
106
109
|
}
|
|
107
110
|
}
|
|
108
111
|
const auth = provider.authentication;
|
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { cloneConfigValue, } from "./config-schema.js";
|
|
2
2
|
const SECRET_KEY = /(secret|token|password|apikey|api_key|authorization|webhook|credential)/i;
|
|
3
|
+
// Anchored so it matches a bare `url`/`uri` key without also catching
|
|
4
|
+
// `baseUrl`, which is useful in a snapshot for diagnosing a bad endpoint.
|
|
5
|
+
const SECRET_EXACT_KEY = /^(url|uri)$/i;
|
|
3
6
|
function redactValue(key, value) {
|
|
4
|
-
if (SECRET_KEY.test(key))
|
|
7
|
+
if (SECRET_KEY.test(key) || SECRET_EXACT_KEY.test(key))
|
|
5
8
|
return "[REDACTED]";
|
|
6
9
|
if (Array.isArray(value))
|
|
7
10
|
return value.map((item) => redactValue(key, item));
|
|
@@ -36,12 +39,16 @@ export function budgetFromConfig(config) {
|
|
|
36
39
|
export function createSafeSnapshot(values) {
|
|
37
40
|
const copied = cloneConfigValue(values);
|
|
38
41
|
const safe = redactValue("config", copied);
|
|
42
|
+
// A malformed config can carry a non-array `providers` (e.g. loaded from
|
|
43
|
+
// JSON). Coerce rather than throw: the snapshot is the diagnostic path, and
|
|
44
|
+
// crashing it hides the very problem it exists to report.
|
|
45
|
+
const providers = Array.isArray(safe.providers) ? safe.providers : [];
|
|
39
46
|
return {
|
|
40
47
|
...safe,
|
|
41
|
-
providers:
|
|
48
|
+
providers: providers.map((provider) => ({
|
|
42
49
|
...provider,
|
|
43
|
-
authentication: { type: provider
|
|
44
|
-
extraHeaders: provider
|
|
50
|
+
authentication: { type: provider?.authentication?.type },
|
|
51
|
+
extraHeaders: provider?.extraHeaders
|
|
45
52
|
? Object.fromEntries(Object.keys(provider.extraHeaders).map((key) => [key, "[REDACTED]"]))
|
|
46
53
|
: undefined,
|
|
47
54
|
})),
|
|
@@ -94,7 +94,8 @@ export function createEnvironmentSource(env = defaultEnv()) {
|
|
|
94
94
|
else if (providerUrl && providerKey) {
|
|
95
95
|
const guard = validateBaseUrl(providerUrl, { allowInsecure: true });
|
|
96
96
|
if (!guard.ok) {
|
|
97
|
-
|
|
97
|
+
const reason = guard.reason.split(providerUrl).join("[URL]");
|
|
98
|
+
diagnostics.push(diagnostic("environment", "CONFIG_UNSAFE_PROVIDER_URL", "providers[0].baseUrl", `provider URL rejected by security policy: ${reason}`));
|
|
98
99
|
}
|
|
99
100
|
else {
|
|
100
101
|
values.providers = [{
|
|
@@ -41,14 +41,9 @@ export interface BudgetPort {
|
|
|
41
41
|
remainingBudget: number | null;
|
|
42
42
|
};
|
|
43
43
|
}
|
|
44
|
-
export interface ClockPort {
|
|
45
|
-
now(): number;
|
|
46
|
-
sleep(ms: number, signal?: AbortSignal): Promise<void>;
|
|
47
|
-
}
|
|
48
44
|
export interface ExecutionPorts {
|
|
49
45
|
policy: PolicyPort;
|
|
50
46
|
circuitBreakers: CircuitBreakerRegistryPort;
|
|
51
47
|
adapters: AdapterRegistryPort;
|
|
52
48
|
budget?: BudgetPort;
|
|
53
|
-
clock?: ClockPort;
|
|
54
49
|
}
|
|
@@ -49,15 +49,3 @@ export interface RequestContext {
|
|
|
49
49
|
}
|
|
50
50
|
/** Create the initial context for a resolved provider/model pair. */
|
|
51
51
|
export declare function createRequestContext(init: RequestContextInit): RequestContext;
|
|
52
|
-
/** Derive an attempt context without mutating the logical request context. */
|
|
53
|
-
export declare function deriveRequestContext(context: RequestContext, changes: Partial<Pick<RequestContext, "provider" | "model" | "executionSignal" | "routing" | "attempt" | "phase" | "metadata">>): RequestContext;
|
|
54
|
-
/** Minimal, non-sensitive projection suitable for telemetry adapters. */
|
|
55
|
-
export interface TelemetryRequestContext {
|
|
56
|
-
requestId: string;
|
|
57
|
-
operation: RequestOperation;
|
|
58
|
-
provider: string;
|
|
59
|
-
model: string;
|
|
60
|
-
attempt: number;
|
|
61
|
-
phase: RequestPhase;
|
|
62
|
-
}
|
|
63
|
-
export declare function toTelemetryContext(context: RequestContext): TelemetryRequestContext;
|