@hilbras/sdk 3.7.0 → 3.8.1

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 (75) hide show
  1. package/README.md +15 -7
  2. package/dist/adapters/anthropic.js +39 -25
  3. package/dist/adapters/azure.js +10 -13
  4. package/dist/adapters/bedrock.js +41 -26
  5. package/dist/adapters/cohere.js +28 -43
  6. package/dist/adapters/google-genai.js +25 -14
  7. package/dist/adapters/google-vertex.js +25 -14
  8. package/dist/adapters/groq.d.ts +3 -4
  9. package/dist/adapters/groq.js +30 -18
  10. package/dist/adapters/huggingface.js +10 -13
  11. package/dist/adapters/ollama.d.ts +2 -1
  12. package/dist/adapters/ollama.js +49 -17
  13. package/dist/adapters/openai-compatible.js +9 -13
  14. package/dist/adapters/openai.js +9 -13
  15. package/dist/catalog/models.d.ts +10 -0
  16. package/dist/catalog/models.js +32 -1
  17. package/dist/client/client.js +37 -2
  18. package/dist/config/config-resolver.js +4 -1
  19. package/dist/config/resolved-config.js +11 -4
  20. package/dist/config/sources/environment.js +2 -1
  21. package/dist/core/execution/ports.d.ts +0 -5
  22. package/dist/core/execution/request-context.d.ts +0 -12
  23. package/dist/core/execution/request-context.js +0 -20
  24. package/dist/core/execution/request-executor.d.ts +13 -3
  25. package/dist/core/execution/request-executor.js +16 -8
  26. package/dist/core/execution/request-pipeline.js +44 -22
  27. package/dist/cost/alerts.d.ts +18 -1
  28. package/dist/cost/alerts.js +67 -31
  29. package/dist/frameworks/astro/endpoints.js +8 -5
  30. package/dist/frameworks/nextjs/route-handlers.js +18 -6
  31. package/dist/frameworks/nextjs/use-chat.js +8 -0
  32. package/dist/frameworks/react/use-chat.js +8 -1
  33. package/dist/frameworks/react-client/use-chat.d.ts +17 -0
  34. package/dist/frameworks/react-client/use-chat.js +49 -21
  35. package/dist/frameworks/remix/actions.js +8 -5
  36. package/dist/frameworks/shared/handler-core.js +9 -4
  37. package/dist/frameworks/svelte/use-chat.d.ts +1 -0
  38. package/dist/frameworks/svelte/use-chat.js +14 -0
  39. package/dist/frameworks/vue/use-chat.js +8 -1
  40. package/dist/index.d.ts +0 -2
  41. package/dist/index.js +4 -1
  42. package/dist/logging/logger.js +4 -1
  43. package/dist/output/schema-helpers.js +4 -1
  44. package/dist/output/structured.js +12 -3
  45. package/dist/reasoning/normalizer.d.ts +15 -5
  46. package/dist/reasoning/normalizer.js +44 -36
  47. package/dist/reliability/backoff.js +3 -1
  48. package/dist/reliability/circuit-breaker.d.ts +2 -0
  49. package/dist/reliability/circuit-breaker.js +17 -0
  50. package/dist/reliability/degradation.js +5 -4
  51. package/dist/reliability/presets.js +2 -2
  52. package/dist/reliability/retry.js +8 -1
  53. package/dist/reliability/timeout.d.ts +7 -3
  54. package/dist/reliability/timeout.js +11 -2
  55. package/dist/router/model-router.js +30 -5
  56. package/dist/security/audit-logger.js +50 -6
  57. package/dist/security/authorization.d.ts +2 -2
  58. package/dist/security/known-secrets.d.ts +19 -0
  59. package/dist/security/known-secrets.js +39 -0
  60. package/dist/security/prompt-injection-guard.js +28 -16
  61. package/dist/security/rbac.d.ts +6 -2
  62. package/dist/security/rbac.js +8 -5
  63. package/dist/tokens/counter.d.ts +6 -0
  64. package/dist/tokens/counter.js +43 -35
  65. package/dist/transport/fetch.js +47 -5
  66. package/dist/types/router.d.ts +3 -0
  67. package/dist/utils/base64.d.ts +13 -0
  68. package/dist/utils/base64.js +20 -0
  69. package/dist/utils/sse-writer.d.ts +9 -0
  70. package/dist/utils/sse-writer.js +5 -2
  71. package/dist/utils/sse.d.ts +20 -0
  72. package/dist/utils/sse.js +52 -10
  73. package/package.json +10 -11
  74. package/dist/mcp/index.d.ts +0 -63
  75. package/dist/mcp/index.js +0 -77
@@ -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
- * - No native tool calling support (text-embedded only)
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
- * Since Groq doesn't support native tool calling, models will use
19
- * text-embedded tool calls (e.g., <tool_call>), which the SDK's
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 += decoder.decode(value, { stream: true });
102
- const parts = buffer.split("\n\n");
103
- buffer = parts.pop() ?? "";
104
- for (const part of parts) {
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 reasoning = reasoningNormalizer.feedText(content);
139
- if (reasoning)
140
- yield reasoning;
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 += decoder.decode(value, { stream: true });
113
- const parts = buffer.split("\n\n");
114
- buffer = parts.pop() ?? "";
115
- for (const part of parts) {
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 reasoning = reasoningNormalizer.feedText(content);
155
- if (reasoning)
156
- yield reasoning;
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. Supports text-embedded tool calls via the SDK's parser.
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";
@@ -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. Supports text-embedded tool calls via the SDK's parser.
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.options = { num_predict: params.maxTokens };
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 += decoder.decode(value, { stream: true });
82
- const parts = buffer.split("\n\n");
83
- buffer = parts.pop() ?? "";
84
- for (const part of parts) {
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 reasoning = reasoningNormalizer.feedText(content);
110
- if (reasoning)
111
- yield reasoning;
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
- const url = `${this._provider.baseUrl}/api/embeddings`;
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 += decoder.decode(value, { stream: true });
165
- const parts = buffer.split("\n\n");
166
- buffer = parts.pop() ?? "";
167
- for (const part of parts) {
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 reasoning = reasoningNormalizer.feedText(content);
211
- if (reasoning) {
212
- yield reasoning;
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) {
@@ -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 += decoder.decode(value, { stream: true });
150
- const parts = buffer.split("\n\n");
151
- buffer = parts.pop() ?? "";
152
- for (const part of parts) {
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 reasoning = reasoningNormalizer.feedText(content);
202
- if (reasoning) {
203
- yield reasoning;
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));
@@ -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[];
@@ -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
- export const BUILTIN_MODELS = [
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));
@@ -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, {
@@ -617,13 +642,23 @@ export class HilbrasClient {
617
642
  }
618
643
  catch (err) {
619
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
+ }
620
651
  const status = err.status ?? 0;
621
- const retryable = (status > 0 && shouldRetry(status, attempt, retryConfig)) || shouldRetryNetworkError(attempt, retryConfig);
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);
622
657
  circuitBreaker?.recordFailure(lastError);
623
658
  if (retryable && attempt < maxAttempts - 1) {
624
659
  const delay = calculateBackoff(attempt, resolved.backoff);
625
660
  this._emit({ type: "request.retrying", requestId, timestamp: performance.now(), provider: providerName, attempt, delayMs: delay, reason: lastError.message });
626
- await sleep(delay);
661
+ await sleep(delay, userSignal);
627
662
  continue;
628
663
  }
629
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
- diagnostics.push(errorDiagnostic(source, "CONFIG_UNSAFE_PROVIDER_URL", `${path}.baseUrl`, `provider URL rejected by security policy: ${guard.reason}`));
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: safe.providers.map((provider) => ({
48
+ providers: providers.map((provider) => ({
42
49
  ...provider,
43
- authentication: { type: provider.authentication.type },
44
- extraHeaders: provider.extraHeaders
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
- diagnostics.push(diagnostic("environment", "CONFIG_UNSAFE_PROVIDER_URL", "providers[0].baseUrl", `provider URL rejected by security policy: ${guard.reason}`));
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;
@@ -26,23 +26,3 @@ export function createRequestContext(init) {
26
26
  startedAt: init.startedAt ?? Date.now(),
27
27
  };
28
28
  }
29
- /** Derive an attempt context without mutating the logical request context. */
30
- export function deriveRequestContext(context, changes) {
31
- return {
32
- ...context,
33
- ...changes,
34
- metadata: changes.metadata
35
- ? { ...context.metadata, ...changes.metadata }
36
- : context.metadata,
37
- };
38
- }
39
- export function toTelemetryContext(context) {
40
- return {
41
- requestId: context.requestId,
42
- operation: context.operation,
43
- provider: context.provider,
44
- model: context.model,
45
- attempt: context.attempt,
46
- phase: context.phase,
47
- };
48
- }
@@ -5,7 +5,6 @@
5
5
  * to RequestPipeline. This class owns preparation and one provider attempt.
6
6
  */
7
7
  import { type RetryConfig } from "../../reliability/retry.js";
8
- import { type ScopedTimeout } from "../../reliability/timeout.js";
9
8
  import type { ExecutionPolicy } from "../../types/policy.js";
10
9
  import type { RoutingResult } from "../../types/router.js";
11
10
  import type { GenerateParams } from "../../types/adapter.js";
@@ -30,8 +29,19 @@ export interface PreparedRequest {
30
29
  context: RequestContext;
31
30
  retryConfig: RetryConfig;
32
31
  circuitBreaker?: CircuitBreakerPort;
33
- signal?: AbortSignal;
34
- timeout?: ScopedTimeout;
32
+ /**
33
+ * Signal for the current attempt: the internal timeout signal when a timeout
34
+ * is configured, otherwise the caller signal. Replaced by `beginAttempt()`.
35
+ */
36
+ readonly signal?: AbortSignal;
37
+ /**
38
+ * Start a fresh timeout window for one attempt and return its signal.
39
+ *
40
+ * The timeout must not be created once per logical request: it aborts once
41
+ * and never resets, so after a primary timeout every retry and every fallback
42
+ * would abort instantly on arrival.
43
+ */
44
+ beginAttempt(): AbortSignal | undefined;
35
45
  dispose(): void;
36
46
  }
37
47
  export declare class RequestExecutor {