@hilbras/sdk 3.7.0 → 3.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +15 -7
  2. package/dist/adapters/anthropic.js +39 -25
  3. package/dist/adapters/azure.js +10 -13
  4. package/dist/adapters/bedrock.js +41 -26
  5. package/dist/adapters/cohere.js +28 -43
  6. package/dist/adapters/google-genai.js +25 -14
  7. package/dist/adapters/google-vertex.js +25 -14
  8. package/dist/adapters/groq.d.ts +3 -4
  9. package/dist/adapters/groq.js +30 -18
  10. package/dist/adapters/huggingface.js +10 -13
  11. package/dist/adapters/ollama.d.ts +2 -1
  12. package/dist/adapters/ollama.js +49 -17
  13. package/dist/adapters/openai-compatible.js +9 -13
  14. package/dist/adapters/openai.js +9 -13
  15. package/dist/catalog/models.d.ts +10 -0
  16. package/dist/catalog/models.js +32 -1
  17. package/dist/client/client.js +37 -2
  18. package/dist/config/config-resolver.js +4 -1
  19. package/dist/config/resolved-config.js +11 -4
  20. package/dist/config/sources/environment.js +2 -1
  21. package/dist/core/execution/ports.d.ts +0 -5
  22. package/dist/core/execution/request-context.d.ts +0 -12
  23. package/dist/core/execution/request-context.js +0 -20
  24. package/dist/core/execution/request-executor.d.ts +13 -3
  25. package/dist/core/execution/request-executor.js +16 -8
  26. package/dist/core/execution/request-pipeline.js +44 -22
  27. package/dist/cost/alerts.d.ts +18 -1
  28. package/dist/cost/alerts.js +67 -31
  29. package/dist/frameworks/astro/endpoints.js +8 -5
  30. package/dist/frameworks/nextjs/route-handlers.js +18 -6
  31. package/dist/frameworks/nextjs/use-chat.js +8 -0
  32. package/dist/frameworks/react/use-chat.js +8 -1
  33. package/dist/frameworks/react-client/use-chat.d.ts +17 -0
  34. package/dist/frameworks/react-client/use-chat.js +49 -21
  35. package/dist/frameworks/remix/actions.js +8 -5
  36. package/dist/frameworks/shared/handler-core.js +9 -4
  37. package/dist/frameworks/svelte/use-chat.d.ts +1 -0
  38. package/dist/frameworks/svelte/use-chat.js +14 -0
  39. package/dist/frameworks/vue/use-chat.js +8 -1
  40. package/dist/index.d.ts +0 -2
  41. package/dist/index.js +4 -1
  42. package/dist/logging/logger.js +4 -1
  43. package/dist/output/schema-helpers.js +4 -1
  44. package/dist/reasoning/normalizer.d.ts +15 -5
  45. package/dist/reasoning/normalizer.js +44 -36
  46. package/dist/reliability/backoff.js +3 -1
  47. package/dist/reliability/circuit-breaker.d.ts +2 -0
  48. package/dist/reliability/circuit-breaker.js +17 -0
  49. package/dist/reliability/degradation.js +5 -4
  50. package/dist/reliability/presets.js +2 -2
  51. package/dist/reliability/retry.js +8 -1
  52. package/dist/reliability/timeout.d.ts +7 -3
  53. package/dist/reliability/timeout.js +11 -2
  54. package/dist/router/model-router.js +30 -5
  55. package/dist/security/audit-logger.js +50 -6
  56. package/dist/security/authorization.d.ts +2 -2
  57. package/dist/security/known-secrets.d.ts +19 -0
  58. package/dist/security/known-secrets.js +39 -0
  59. package/dist/security/prompt-injection-guard.js +28 -16
  60. package/dist/security/rbac.d.ts +6 -2
  61. package/dist/security/rbac.js +8 -5
  62. package/dist/tokens/counter.d.ts +6 -0
  63. package/dist/tokens/counter.js +43 -35
  64. package/dist/transport/fetch.js +47 -5
  65. package/dist/types/router.d.ts +3 -0
  66. package/dist/utils/base64.d.ts +13 -0
  67. package/dist/utils/base64.js +20 -0
  68. package/dist/utils/sse-writer.d.ts +9 -0
  69. package/dist/utils/sse-writer.js +5 -2
  70. package/dist/utils/sse.d.ts +20 -0
  71. package/dist/utils/sse.js +52 -10
  72. package/package.json +5 -6
  73. package/dist/mcp/index.d.ts +0 -63
  74. package/dist/mcp/index.js +0 -77
package/README.md CHANGED
@@ -3,7 +3,7 @@
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-1939%20passing-brightgreen" alt="tests">
6
+ <img src="https://img.shields.io/badge/tests-2070%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
 
@@ -49,7 +49,14 @@ Application
49
49
  Groq Ollama Azure
50
50
  ```
51
51
 
52
- **Zero runtime dependencies.** Runs everywhere: Node 18+, Bun, Deno, browsers, VS Code extensions, CLIs, edge runtimes.
52
+ **Zero runtime dependencies.** Runs on Node 18+, Bun, Deno, VS Code extensions, and CLIs.
53
+
54
+ The root entry re-exports config loading and request signing, which import
55
+ `node:fs` and `node:crypto`, so `import "@hilbras/sdk"` does not load in a
56
+ browser bundle or an edge runtime without shimming those built-ins. Import the
57
+ subpath entries (for example `@hilbras/sdk/adapters/openai`) where the root
58
+ entry is too broad. Making the root entry portable is tracked as item 8 in
59
+ [`ROADMAP-v4.0.0.md`](./ROADMAP-v4.0.0.md).
53
60
 
54
61
  ---
55
62
 
@@ -528,11 +535,12 @@ import { exportTrainingData } from "@hilbras/sdk/fine-tune";
528
535
 
529
536
  ```bash
530
537
  npm install
531
- npm run build # Compile TypeScript
532
- npm test # Run the root test suite (1611 tests)
533
- npm run test:packages # Build and test companion packages
534
- npm run test:watch # Watch mode
535
- npm run lint # Lint with oxlint
538
+ npm run build # Compile TypeScript
539
+ npm test # Run the root test suite (2077 tests)
540
+ npm run typecheck:tests # Typecheck the tests (`tsc --noEmit` covers src only)
541
+ npm run test:packages # Build and test companion packages
542
+ npm run test:watch # Watch mode
543
+ npm run lint # Lint with oxlint
536
544
  ```
537
545
 
538
546
  ## License
@@ -12,6 +12,7 @@
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
  export class AnthropicAdapter {
17
18
  id = "anthropic";
@@ -109,25 +110,19 @@ export class AnthropicAdapter {
109
110
  const reader = res.body.getReader();
110
111
  const decoder = new TextDecoder();
111
112
  let buffer = "";
113
+ let inputTokens = 0;
114
+ let finishReason;
112
115
  const toolCalls = new Map();
113
116
  try {
114
117
  while (true) {
115
118
  const { done, value } = await reader.read();
116
119
  if (done)
117
120
  break;
118
- buffer += decoder.decode(value, { stream: true });
119
- const parts = buffer.split("\n\n");
120
- buffer = parts.pop() ?? "";
121
- for (const part of parts) {
122
- const lines = part.split("\n");
123
- let eventType = "";
124
- let rawData = "";
125
- for (const line of lines) {
126
- if (line.startsWith("event: "))
127
- eventType = line.slice(7).trim();
128
- if (line.startsWith("data: "))
129
- rawData = line.slice(6).trim();
130
- }
121
+ const decoded = splitSseFrames(buffer, decoder.decode(value, { stream: true }));
122
+ buffer = decoded.buffer;
123
+ for (const frame of decoded.frames) {
124
+ const eventType = frame.event;
125
+ const rawData = frame.data.trim();
131
126
  if (!rawData || rawData === "[DONE]")
132
127
  continue;
133
128
  let data;
@@ -143,9 +138,11 @@ export class AnthropicAdapter {
143
138
  if (!delta)
144
139
  continue;
145
140
  if (delta.type === "text_delta" && typeof delta.text === "string") {
146
- const reasoning = reasoningNormalizer.feedText(delta.text);
147
- if (reasoning)
148
- yield reasoning;
141
+ const reasoningParts = reasoningNormalizer.feedText(delta.text);
142
+ if (reasoningParts.length > 0) {
143
+ for (const part of reasoningParts)
144
+ yield part;
145
+ }
149
146
  else if (!ReasoningNormalizer.looksLikeReasoningTag(delta.text)) {
150
147
  yield { type: "text", text: delta.text };
151
148
  }
@@ -185,15 +182,32 @@ export class AnthropicAdapter {
185
182
  toolCalls.delete(idx);
186
183
  }
187
184
  }
188
- // Usage
189
- if (data.type === "message_delta" && data.usage) {
190
- const usage = data.usage;
191
- yield {
192
- type: "usage",
193
- inputTokens: usage.input_tokens ?? 0,
194
- outputTokens: usage.output_tokens ?? 0,
195
- totalTokens: (usage.input_tokens ?? 0) + (usage.output_tokens ?? 0),
196
- };
185
+ // Prompt tokens arrive on message_start; message_delta carries only
186
+ // output_tokens, so reading input_tokens there always yielded 0.
187
+ if (data.type === "message_start") {
188
+ const message = data.message;
189
+ const usage = message?.usage;
190
+ if (usage?.input_tokens)
191
+ inputTokens = usage.input_tokens;
192
+ }
193
+ if (data.type === "message_delta") {
194
+ const delta = data.delta;
195
+ if (typeof delta?.stop_reason === "string")
196
+ finishReason = delta.stop_reason;
197
+ if (data.usage) {
198
+ const usage = data.usage;
199
+ const outputTokens = usage.output_tokens ?? 0;
200
+ yield {
201
+ type: "usage",
202
+ inputTokens,
203
+ outputTokens,
204
+ totalTokens: inputTokens + outputTokens,
205
+ };
206
+ }
207
+ }
208
+ // End of message
209
+ if (eventType === "message_stop" || data.type === "message_stop") {
210
+ yield { type: "finish", reason: finishReason ?? "stop" };
197
211
  }
198
212
  }
199
213
  }
@@ -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 { assertExtraFieldAllowed } from "./extra.js";
15
16
  export class AzureAdapter {
16
17
  id = "azure";
@@ -115,16 +116,10 @@ export class AzureAdapter {
115
116
  const { done, value } = await reader.read();
116
117
  if (done)
117
118
  break;
118
- buffer += decoder.decode(value, { stream: true });
119
- const parts = buffer.split("\n\n");
120
- buffer = parts.pop() ?? "";
121
- for (const part of parts) {
122
- const lines = part.split("\n");
123
- let rawData = "";
124
- for (const line of lines) {
125
- if (line.startsWith("data: "))
126
- rawData = line.slice(6).trim();
127
- }
119
+ const decoded = splitSseFrames(buffer, decoder.decode(value, { stream: true }));
120
+ buffer = decoded.buffer;
121
+ for (const frame of decoded.frames) {
122
+ const rawData = frame.data.trim();
128
123
  if (!rawData || rawData === "[DONE]")
129
124
  continue;
130
125
  let data;
@@ -157,9 +152,11 @@ export class AzureAdapter {
157
152
  }
158
153
  const content = delta.content;
159
154
  if (content) {
160
- const reasoning = reasoningNormalizer.feedText(content);
161
- if (reasoning)
162
- yield reasoning;
155
+ const reasoningParts = reasoningNormalizer.feedText(content);
156
+ if (reasoningParts.length > 0) {
157
+ for (const part of reasoningParts)
158
+ yield part;
159
+ }
163
160
  else if (!ReasoningNormalizer.looksLikeReasoningTag(content)) {
164
161
  yield { type: "text", text: content };
165
162
  }
@@ -18,6 +18,7 @@
18
18
  import { createHash, createHmac } from "node:crypto";
19
19
  import { ProviderRequestError } from "../errors/index.js";
20
20
  import { ReasoningNormalizer } from "../reasoning/normalizer.js";
21
+ import { splitSseFrames } from "../utils/sse.js";
21
22
  /** AWS SigV4 signing helper */
22
23
  class AwsSigV4 {
23
24
  _accessKeyId;
@@ -261,21 +262,19 @@ export class BedrockAdapter {
261
262
  const reader = res.body.getReader();
262
263
  const decoder = new TextDecoder();
263
264
  let buffer = "";
265
+ // Tool-use blocks, keyed by content block index. Only the start event
266
+ // carries the real toolUseId and name; the delta and stop events must look
267
+ // them up rather than synthesise `call_<index>` with an empty name.
268
+ const toolBlocks = new Map();
264
269
  try {
265
270
  while (true) {
266
271
  const { done, value } = await reader.read();
267
272
  if (done)
268
273
  break;
269
- buffer += decoder.decode(value, { stream: true });
270
- const parts = buffer.split("\n\n");
271
- buffer = parts.pop() ?? "";
272
- for (const part of parts) {
273
- const lines = part.split("\n");
274
- let rawData = "";
275
- for (const line of lines) {
276
- if (line.startsWith("data: "))
277
- rawData = line.slice(6).trim();
278
- }
274
+ const decoded = splitSseFrames(buffer, decoder.decode(value, { stream: true }));
275
+ buffer = decoded.buffer;
276
+ for (const frame of decoded.frames) {
277
+ const rawData = frame.data.trim();
279
278
  if (!rawData || rawData === "[DONE]")
280
279
  continue;
281
280
  let data;
@@ -292,10 +291,13 @@ export class BedrockAdapter {
292
291
  const start = data.start;
293
292
  if (start?.toolUse) {
294
293
  const toolUse = start.toolUse;
294
+ const id = toolUse.toolUseId ?? `call_${contentBlock}`;
295
+ const name = toolUse.name ?? "";
296
+ toolBlocks.set(contentBlock, { id, name });
295
297
  yield {
296
298
  type: "tool_call",
297
- id: toolUse.toolUseId ?? `call_${contentBlock}`,
298
- name: toolUse.name ?? "",
299
+ id,
300
+ name,
299
301
  argumentsDelta: "",
300
302
  index: contentBlock,
301
303
  done: false,
@@ -308,9 +310,11 @@ export class BedrockAdapter {
308
310
  continue;
309
311
  if (delta.text) {
310
312
  const text = delta.text;
311
- const reasoning = reasoningNormalizer.feedText(text);
312
- if (reasoning)
313
- yield reasoning;
313
+ const reasoningParts = reasoningNormalizer.feedText(text);
314
+ if (reasoningParts.length > 0) {
315
+ for (const part of reasoningParts)
316
+ yield part;
317
+ }
314
318
  else if (!ReasoningNormalizer.looksLikeReasoningTag(text)) {
315
319
  yield { type: "text", text };
316
320
  }
@@ -323,11 +327,16 @@ export class BedrockAdapter {
323
327
  else if (delta.toolUse) {
324
328
  const toolUse = delta.toolUse;
325
329
  const contentBlock = data.contentBlockIndex;
330
+ const block = toolBlocks.get(contentBlock);
331
+ // `input` arrives as a partial-JSON string fragment and must be
332
+ // passed through as-is: re-stringifying it produced doubly-quoted
333
+ // fragments that concatenated into invalid JSON.
334
+ const fragment = toolUse.input;
326
335
  yield {
327
336
  type: "tool_call",
328
- id: `call_${contentBlock}`,
329
- name: "",
330
- argumentsDelta: JSON.stringify(toolUse.input ?? {}),
337
+ id: block?.id ?? `call_${contentBlock}`,
338
+ name: block?.name ?? "",
339
+ argumentsDelta: typeof fragment === "string" ? fragment : JSON.stringify(fragment ?? {}),
331
340
  index: contentBlock,
332
341
  done: false,
333
342
  };
@@ -335,14 +344,20 @@ export class BedrockAdapter {
335
344
  }
336
345
  else if (eventType === "contentBlockStop") {
337
346
  const contentBlock = data.contentBlockIndex;
338
- yield {
339
- type: "tool_call",
340
- id: `call_${contentBlock}`,
341
- name: "",
342
- argumentsDelta: "",
343
- index: contentBlock,
344
- done: true,
345
- };
347
+ const block = toolBlocks.get(contentBlock);
348
+ // Only tool-use blocks produce a call. Emitting unconditionally made
349
+ // every plain text reply end with a phantom tool call named "".
350
+ if (block) {
351
+ toolBlocks.delete(contentBlock);
352
+ yield {
353
+ type: "tool_call",
354
+ id: block.id,
355
+ name: block.name,
356
+ argumentsDelta: "",
357
+ index: contentBlock,
358
+ done: true,
359
+ };
360
+ }
346
361
  }
347
362
  else if (eventType === "messageStop") {
348
363
  yield { type: "finish", reason: "end_turn" };
@@ -9,6 +9,7 @@
9
9
  * - Streaming uses SSE with different event types
10
10
  */
11
11
  import { extractText } from "../types/messages.js";
12
+ import { splitSseFrames } from "../utils/sse.js";
12
13
  import { ProviderRequestError } from "../errors/index.js";
13
14
  import { mergeExtraParams } from "./extra.js";
14
15
  export class CohereAdapter {
@@ -34,29 +35,28 @@ export class CohereAdapter {
34
35
  return headers;
35
36
  }
36
37
  _buildBody(params) {
37
- let preamble = "";
38
- const chatHistory = [];
39
- for (const m of params.messages) {
40
- if (m.role === "system") {
41
- preamble += (preamble ? "\n\n" : "") + extractText(m.content);
42
- }
43
- else if (m.role === "user") {
44
- chatHistory.push({ role: "USER", message: extractText(m.content) });
45
- }
46
- else if (m.role === "assistant") {
47
- chatHistory.push({ role: "CHATBOT", message: extractText(m.content) });
48
- }
49
- }
50
- const lastUserMsg = params.messages.filter((m) => m.role === "user").pop();
51
- const message = lastUserMsg?.content ?? "";
38
+ // Cohere's `/v2/chat` takes one chronological `messages` array covering the
39
+ // user, assistant, tool and system roles, and OpenAI-style tools. The
40
+ // previous body was the v1 shape — a `chat_history` of USER/CHATBOT turns
41
+ // plus a separate top-level `message` — sent to a v2 endpoint, which meant
42
+ // the last user turn was sent twice, `role: "tool"` results were dropped
43
+ // entirely, and the v1 `parameter_definitions` tool schema was used.
44
+ const messages = params.messages.map((m) => {
45
+ const entry = {
46
+ role: m.role,
47
+ content: extractText(m.content),
48
+ };
49
+ if (m.role === "tool" && m.tool_call_id)
50
+ entry.tool_call_id = m.tool_call_id;
51
+ if (m.tool_calls?.length)
52
+ entry.tool_calls = m.tool_calls;
53
+ return entry;
54
+ });
52
55
  const body = {
53
56
  model: params.model,
54
- messages: chatHistory,
55
- message,
57
+ messages,
56
58
  stream: params.stream,
57
59
  };
58
- if (preamble)
59
- body.preamble = preamble;
60
60
  if (params.temperature != null)
61
61
  body.temperature = params.temperature;
62
62
  if (params.maxTokens != null && params.maxTokens > 0)
@@ -67,16 +67,7 @@ export class CohereAdapter {
67
67
  function: {
68
68
  name: t.function.name,
69
69
  description: t.function.description,
70
- parameter_definitions: t.function.parameters.properties
71
- ? Object.fromEntries(Object.entries(t.function.parameters.properties).map(([k, v]) => {
72
- const param = v;
73
- return [k, {
74
- description: param.description ?? "",
75
- type: param.type ?? "string",
76
- required: (t.function.parameters.required ?? []).includes(k),
77
- }];
78
- }))
79
- : {},
70
+ parameters: t.function.parameters,
80
71
  },
81
72
  }));
82
73
  }
@@ -117,19 +108,11 @@ export class CohereAdapter {
117
108
  const { done, value } = await reader.read();
118
109
  if (done)
119
110
  break;
120
- buffer += decoder.decode(value, { stream: true });
121
- const parts = buffer.split("\n\n");
122
- buffer = parts.pop() ?? "";
123
- for (const part of parts) {
124
- const lines = part.split("\n");
125
- let eventType = "";
126
- let rawData = "";
127
- for (const line of lines) {
128
- if (line.startsWith("event: "))
129
- eventType = line.slice(7).trim();
130
- if (line.startsWith("data: "))
131
- rawData = line.slice(6).trim();
132
- }
111
+ const decoded = splitSseFrames(buffer, decoder.decode(value, { stream: true }));
112
+ buffer = decoded.buffer;
113
+ for (const frame of decoded.frames) {
114
+ const eventType = frame.event;
115
+ const rawData = frame.data.trim();
133
116
  if (!rawData || rawData === "[DONE]")
134
117
  continue;
135
118
  let data;
@@ -234,8 +217,10 @@ export class CohereAdapter {
234
217
  texts,
235
218
  input_type: "search_document",
236
219
  };
220
+ // `output_dimension` is the Cohere v3 embed field; `embedding_types`
221
+ // selects the encoding format and silently ignored the requested width.
237
222
  if (params.dimensions)
238
- body.embedding_types = ["float"];
223
+ body.output_dimension = params.dimensions;
239
224
  const res = await this._transport.request(url, {
240
225
  method: "POST",
241
226
  headers: this._headers(),
@@ -13,6 +13,8 @@
13
13
  import { extractText } from "../types/messages.js";
14
14
  import { ProviderRequestError } from "../errors/index.js";
15
15
  import { ReasoningNormalizer } from "../reasoning/normalizer.js";
16
+ import { splitSseFrames } from "../utils/sse.js";
17
+ import { toBase64 } from "../utils/base64.js";
16
18
  export class GoogleGenAIAdapter {
17
19
  id = "google-genai";
18
20
  _provider;
@@ -108,16 +110,10 @@ export class GoogleGenAIAdapter {
108
110
  const { done, value } = await reader.read();
109
111
  if (done)
110
112
  break;
111
- buffer += decoder.decode(value, { stream: true });
112
- const parts = buffer.split("\n\n");
113
- buffer = parts.pop() ?? "";
114
- for (const part of parts) {
115
- const lines = part.split("\n");
116
- let rawData = "";
117
- for (const line of lines) {
118
- if (line.startsWith("data: "))
119
- rawData = line.slice(6).trim();
120
- }
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();
121
117
  if (!rawData || rawData === "[DONE]")
122
118
  continue;
123
119
  let data;
@@ -127,10 +123,23 @@ export class GoogleGenAIAdapter {
127
123
  catch {
128
124
  continue;
129
125
  }
126
+ if (data.usageMetadata) {
127
+ const usage = data.usageMetadata;
128
+ yield {
129
+ type: "usage",
130
+ inputTokens: usage.promptTokenCount ?? 0,
131
+ outputTokens: usage.candidatesTokenCount ?? 0,
132
+ totalTokens: usage.totalTokenCount ?? 0,
133
+ };
134
+ }
130
135
  const candidates = data.candidates;
131
136
  if (!candidates?.length)
132
137
  continue;
133
138
  const candidate = candidates[0];
139
+ const finishReason = candidate.finishReason;
140
+ if (finishReason) {
141
+ yield { type: "finish", reason: finishReason };
142
+ }
134
143
  const content = candidate.content;
135
144
  const parts = content?.parts;
136
145
  if (!parts?.length)
@@ -138,9 +147,11 @@ export class GoogleGenAIAdapter {
138
147
  for (const p of parts) {
139
148
  // Text content
140
149
  if (typeof p.text === "string" && p.text) {
141
- const reasoning = reasoningNormalizer.feedText(p.text);
142
- if (reasoning)
143
- yield reasoning;
150
+ const reasoningParts = reasoningNormalizer.feedText(p.text);
151
+ if (reasoningParts.length > 0) {
152
+ for (const part of reasoningParts)
153
+ yield part;
154
+ }
144
155
  else if (!ReasoningNormalizer.looksLikeReasoningTag(p.text)) {
145
156
  yield { type: "text", text: p.text };
146
157
  }
@@ -295,7 +306,7 @@ export class GoogleGenAIAdapter {
295
306
  languageCode: params.language ?? "en-US",
296
307
  enableAutomaticPunctuation: true,
297
308
  },
298
- audio: { content: btoa(String.fromCharCode(...fileBytes)) },
309
+ audio: { content: toBase64(fileBytes) },
299
310
  };
300
311
  const res = await this._transport.request(url, {
301
312
  method: "POST",
@@ -18,6 +18,8 @@
18
18
  import { extractText } from "../types/messages.js";
19
19
  import { ProviderRequestError } from "../errors/index.js";
20
20
  import { ReasoningNormalizer } from "../reasoning/normalizer.js";
21
+ import { splitSseFrames } from "../utils/sse.js";
22
+ import { toBase64 } from "../utils/base64.js";
21
23
  export class VertexAIAdapter {
22
24
  id = "google-vertex";
23
25
  _provider;
@@ -138,16 +140,10 @@ export class VertexAIAdapter {
138
140
  const { done, value } = await reader.read();
139
141
  if (done)
140
142
  break;
141
- buffer += decoder.decode(value, { stream: true });
142
- const parts = buffer.split("\n\n");
143
- buffer = parts.pop() ?? "";
144
- for (const part of parts) {
145
- const lines = part.split("\n");
146
- let rawData = "";
147
- for (const line of lines) {
148
- if (line.startsWith("data: "))
149
- rawData = line.slice(6).trim();
150
- }
143
+ const decoded = splitSseFrames(buffer, decoder.decode(value, { stream: true }));
144
+ buffer = decoded.buffer;
145
+ for (const frame of decoded.frames) {
146
+ const rawData = frame.data.trim();
151
147
  if (!rawData || rawData === "[DONE]")
152
148
  continue;
153
149
  let data;
@@ -157,10 +153,23 @@ export class VertexAIAdapter {
157
153
  catch {
158
154
  continue;
159
155
  }
156
+ if (data.usageMetadata) {
157
+ const usage = data.usageMetadata;
158
+ yield {
159
+ type: "usage",
160
+ inputTokens: usage.promptTokenCount ?? 0,
161
+ outputTokens: usage.candidatesTokenCount ?? 0,
162
+ totalTokens: usage.totalTokenCount ?? 0,
163
+ };
164
+ }
160
165
  const candidates = data.candidates;
161
166
  if (!candidates?.length)
162
167
  continue;
163
168
  const candidate = candidates[0];
169
+ const finishReason = candidate.finishReason;
170
+ if (finishReason) {
171
+ yield { type: "finish", reason: finishReason };
172
+ }
164
173
  const content = candidate.content;
165
174
  const contentParts = content?.parts;
166
175
  if (!contentParts?.length)
@@ -168,9 +177,11 @@ export class VertexAIAdapter {
168
177
  for (const p of contentParts) {
169
178
  // Text content
170
179
  if (typeof p.text === "string" && p.text) {
171
- const reasoning = reasoningNormalizer.feedText(p.text);
172
- if (reasoning)
173
- yield reasoning;
180
+ const reasoningParts = reasoningNormalizer.feedText(p.text);
181
+ if (reasoningParts.length > 0) {
182
+ for (const part of reasoningParts)
183
+ yield part;
184
+ }
174
185
  else if (!ReasoningNormalizer.looksLikeReasoningTag(p.text)) {
175
186
  yield { type: "text", text: p.text };
176
187
  }
@@ -321,7 +332,7 @@ export class VertexAIAdapter {
321
332
  languageCode: params.language ?? "en-US",
322
333
  enableAutomaticPunctuation: true,
323
334
  },
324
- audio: { content: btoa(String.fromCharCode(...fileBytes)) },
335
+ audio: { content: toBase64(fileBytes) },
325
336
  };
326
337
  const res = await this._transport.request(url, {
327
338
  method: "POST",
@@ -8,7 +8,7 @@
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 type { Message } from "../types/messages.js";
14
14
  import type { Tool } from "../types/tools.js";
@@ -18,9 +18,8 @@ import type { TranscriptionParams, TranscriptionResult } from "../types/multi-mo
18
18
  export type GroqAdapterConfig = AdapterConfig;
19
19
  /**
20
20
  * GroqAdapter — OpenAI-compatible adapter for Groq's fast inference.
21
- * Since Groq doesn't support native tool calling, models will use
22
- * text-embedded tool calls (e.g., <tool_call>), which the SDK's
23
- * text-tool-call-parser handles automatically.
21
+ * Tool calling is native: `tools` goes out in the OpenAI shape and the model
22
+ * replies with `tool_calls`.
24
23
  */
25
24
  export declare class GroqAdapter implements AIProvider {
26
25
  readonly id = "groq";