@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
|
@@ -26,6 +26,26 @@ function nextId() {
|
|
|
26
26
|
* }
|
|
27
27
|
* ```
|
|
28
28
|
*/
|
|
29
|
+
/**
|
|
30
|
+
* Build the provider payload for one turn.
|
|
31
|
+
*
|
|
32
|
+
* Extracted so the retry path is testable without a renderer: `retry` must not
|
|
33
|
+
* append the user turn a second time, and must not re-send the failed
|
|
34
|
+
* assistant turn.
|
|
35
|
+
*/
|
|
36
|
+
export function buildChatApiMessages(params) {
|
|
37
|
+
const apiMessages = [];
|
|
38
|
+
if (params.systemPrompt) {
|
|
39
|
+
apiMessages.push({ role: "system", content: params.systemPrompt });
|
|
40
|
+
}
|
|
41
|
+
for (const msg of params.transcript.slice(-params.maxContextMessages)) {
|
|
42
|
+
apiMessages.push({ role: msg.role, content: msg.content });
|
|
43
|
+
}
|
|
44
|
+
if (params.appendUserMessage) {
|
|
45
|
+
apiMessages.push({ role: "user", content: params.userContent });
|
|
46
|
+
}
|
|
47
|
+
return apiMessages;
|
|
48
|
+
}
|
|
29
49
|
export function useChat(options) {
|
|
30
50
|
const { provider, model, systemPrompt, initialMessages, maxContextMessages = 50, onChunk, onComplete, onError } = options;
|
|
31
51
|
const client = useHilbrasClient();
|
|
@@ -57,7 +77,7 @@ export function useChat(options) {
|
|
|
57
77
|
setTotalTokens(0);
|
|
58
78
|
setTotalCost(0);
|
|
59
79
|
}, [stop]);
|
|
60
|
-
const sendMessage = useCallback(async (content) => {
|
|
80
|
+
const sendMessage = useCallback(async (content, options) => {
|
|
61
81
|
if (!content.trim() || isLoading)
|
|
62
82
|
return;
|
|
63
83
|
const userMessage = {
|
|
@@ -67,14 +87,18 @@ export function useChat(options) {
|
|
|
67
87
|
timestamp: Date.now(),
|
|
68
88
|
};
|
|
69
89
|
lastUserMessageRef.current = content.trim();
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
90
|
+
// On a retry the user turn is already in the transcript. Appending it again
|
|
91
|
+
// sent the question to the provider twice and duplicated it in the UI.
|
|
92
|
+
if (!options?.retry) {
|
|
93
|
+
setMessages((prev) => {
|
|
94
|
+
const updated = [...prev, userMessage];
|
|
95
|
+
// Trim context window
|
|
96
|
+
if (updated.length > maxContextMessages + 1) {
|
|
97
|
+
return updated.slice(-maxContextMessages);
|
|
98
|
+
}
|
|
99
|
+
return updated;
|
|
100
|
+
});
|
|
101
|
+
}
|
|
78
102
|
setInput("");
|
|
79
103
|
setIsLoading(true);
|
|
80
104
|
setIsStreaming(true);
|
|
@@ -82,17 +106,20 @@ export function useChat(options) {
|
|
|
82
106
|
const controller = new AbortController();
|
|
83
107
|
abortRef.current = controller;
|
|
84
108
|
try {
|
|
85
|
-
//
|
|
86
|
-
|
|
87
|
-
if
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
109
|
+
// On a retry the transcript may or may not still carry the failed
|
|
110
|
+
// assistant turn, depending on whether `retry`'s removal has rendered
|
|
111
|
+
// yet, so drop a trailing assistant message if there is one rather than
|
|
112
|
+
// assuming which state this closure captured.
|
|
113
|
+
const transcript = options?.retry && messages[messages.length - 1]?.role === "assistant"
|
|
114
|
+
? messages.slice(0, -1)
|
|
115
|
+
: messages;
|
|
116
|
+
const apiMessages = buildChatApiMessages({
|
|
117
|
+
transcript,
|
|
118
|
+
userContent: userMessage.content,
|
|
119
|
+
systemPrompt,
|
|
120
|
+
maxContextMessages,
|
|
121
|
+
appendUserMessage: !options?.retry,
|
|
122
|
+
});
|
|
96
123
|
let assistantContent = "";
|
|
97
124
|
let inputTokens = 0;
|
|
98
125
|
let outputTokens = 0;
|
|
@@ -182,7 +209,8 @@ export function useChat(options) {
|
|
|
182
209
|
}
|
|
183
210
|
return prev;
|
|
184
211
|
});
|
|
185
|
-
|
|
212
|
+
// The user turn stays in the transcript, so ask sendMessage not to append it.
|
|
213
|
+
await sendMessage(lastUserMessageRef.current, { retry: true });
|
|
186
214
|
}, [isLoading, sendMessage]);
|
|
187
215
|
return {
|
|
188
216
|
messages,
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* Uses the HilbrasClient to generate streaming responses with full protocol support.
|
|
6
6
|
*/
|
|
7
7
|
import { createSSEResponse } from "../../utils/sse-writer.js";
|
|
8
|
-
import { createFrameworkClientPool, errorResponse, isRequestPhaseError, readJsonBody, resolveChatFields, resolveCompletionFields, resolveLimits, } from "../shared/handler-core.js";
|
|
8
|
+
import { createFrameworkClientPool, errorResponse, isRequestPhaseError, readJsonBody, resolveCatalogProviderId, resolveChatFields, resolveCompletionFields, resolveLimits, } from "../shared/handler-core.js";
|
|
9
9
|
/**
|
|
10
10
|
* Create a streaming chat action for Remix.
|
|
11
11
|
*
|
|
@@ -41,10 +41,13 @@ export function createChatAction(options) {
|
|
|
41
41
|
trustClientFields,
|
|
42
42
|
limits,
|
|
43
43
|
});
|
|
44
|
+
// The hook decides before a client is built: `pool.get()` constructs one,
|
|
45
|
+
// so an unauthenticated caller could otherwise force that work on every
|
|
46
|
+
// request even when the hook was about to reject them.
|
|
47
|
+
const effective = { ...fields, provider: resolveCatalogProviderId(options.provider) };
|
|
48
|
+
await options.onRequest?.({ request, body, effective });
|
|
44
49
|
const client = pool.get(fields.model);
|
|
45
50
|
const providerName = pool.providerName;
|
|
46
|
-
const effective = { ...fields, provider: providerName };
|
|
47
|
-
await options.onRequest?.({ request, body, effective });
|
|
48
51
|
const allMessages = options.systemPrompt
|
|
49
52
|
? [{ role: "system", content: options.systemPrompt }, ...fields.messages]
|
|
50
53
|
: fields.messages;
|
|
@@ -113,9 +116,9 @@ export function createCompletionAction(options) {
|
|
|
113
116
|
trustClientFields,
|
|
114
117
|
limits,
|
|
115
118
|
});
|
|
116
|
-
const
|
|
117
|
-
const effective = { ...fields, provider: pool.providerName };
|
|
119
|
+
const effective = { ...fields, provider: resolveCatalogProviderId(options.provider) };
|
|
118
120
|
await options.onRequest?.({ request, body, effective });
|
|
121
|
+
const client = pool.get(fields.model);
|
|
119
122
|
const result = await client.complete({
|
|
120
123
|
provider: pool.providerName,
|
|
121
124
|
model: fields.model,
|
|
@@ -64,12 +64,17 @@ export function createFrameworkClientPool(options) {
|
|
|
64
64
|
if (cached)
|
|
65
65
|
return cached;
|
|
66
66
|
const client = options.client ?? new HilbrasClient();
|
|
67
|
+
// Register before retaining. `addProviderFromCatalog` throws for a model
|
|
68
|
+
// that is not in the catalog, and `owned` is drained only by dispose() —
|
|
69
|
+
// so retaining first left one unreachable client per failed request, an
|
|
70
|
+
// unbounded set any caller could grow.
|
|
71
|
+
//
|
|
72
|
+
// The returned canonical name is used because registering under the
|
|
73
|
+
// catalog display name and then calling with the caller's id was the root
|
|
74
|
+
// cause of `ProviderNotFoundError` in every shipped framework handler.
|
|
75
|
+
providerName = client.addProviderFromCatalog(options.provider, model, apiKey);
|
|
67
76
|
if (!options.client)
|
|
68
77
|
owned.add(client);
|
|
69
|
-
// Use the returned canonical name. Registering under the catalog display
|
|
70
|
-
// name and then calling with the caller's id was the root cause of
|
|
71
|
-
// `ProviderNotFoundError` in every shipped framework handler.
|
|
72
|
-
providerName = client.addProviderFromCatalog(options.provider, model, apiKey);
|
|
73
78
|
cache.set(key, client);
|
|
74
79
|
return client;
|
|
75
80
|
},
|
|
@@ -258,6 +258,19 @@ export function useChat(options) {
|
|
|
258
258
|
state.error = null;
|
|
259
259
|
notify();
|
|
260
260
|
}
|
|
261
|
+
/**
|
|
262
|
+
* Abort an in-flight stream. Call this from `onDestroy`.
|
|
263
|
+
*
|
|
264
|
+
* This hook deliberately imports nothing from `svelte` so the module stays
|
|
265
|
+
* loadable without the peer dependency, which means the destroy lifecycle
|
|
266
|
+
* cannot be registered from inside it.
|
|
267
|
+
*/
|
|
268
|
+
function dispose() {
|
|
269
|
+
abortController?.abort();
|
|
270
|
+
abortController = null;
|
|
271
|
+
state.isLoading = false;
|
|
272
|
+
notify();
|
|
273
|
+
}
|
|
261
274
|
return {
|
|
262
275
|
get messages() { return state.messages; },
|
|
263
276
|
get input() { return state.input; },
|
|
@@ -270,6 +283,7 @@ export function useChat(options) {
|
|
|
270
283
|
setMessages,
|
|
271
284
|
stop,
|
|
272
285
|
clear,
|
|
286
|
+
dispose,
|
|
273
287
|
subscribe,
|
|
274
288
|
};
|
|
275
289
|
}
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* Manages a streaming chat conversation with an LLM backend.
|
|
5
5
|
* Returns Vue reactive refs for state and functions for actions.
|
|
6
6
|
*/
|
|
7
|
-
import { ref, readonly } from "vue";
|
|
7
|
+
import { ref, readonly, onUnmounted } from "vue";
|
|
8
8
|
import { parseUIStream } from "./stream-parser.js";
|
|
9
9
|
let _idCounter = 0;
|
|
10
10
|
function generateId() {
|
|
@@ -22,6 +22,13 @@ export function useChat(options) {
|
|
|
22
22
|
abortController = null;
|
|
23
23
|
isLoading.value = false;
|
|
24
24
|
}
|
|
25
|
+
// Abort an in-flight stream when the component unmounts; otherwise the reader
|
|
26
|
+
// keeps writing into reactive state that no one is rendering any more.
|
|
27
|
+
// `react-client` already did this; the other hooks did not.
|
|
28
|
+
onUnmounted(() => {
|
|
29
|
+
abortController?.abort();
|
|
30
|
+
abortController = null;
|
|
31
|
+
});
|
|
25
32
|
function updateAssistantMessage(id, updater) {
|
|
26
33
|
messages.value = messages.value.map((m) => m.id === id ? updater(m) : m);
|
|
27
34
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -133,8 +133,6 @@ export type { ElevenLabsAdapterConfig } from "./adapters/elevenlabs.js";
|
|
|
133
133
|
export { VoyageAIAdapter } from "./adapters/voyageai.js";
|
|
134
134
|
export { CohereRerankAdapter } from "./adapters/cohere-rerank.js";
|
|
135
135
|
export type { CohereRerankAdapterConfig } from "./adapters/cohere-rerank.js";
|
|
136
|
-
export { MCPClient, createMCPToolExecution } from "./mcp/index.js";
|
|
137
|
-
export type { MCPServerConfig, MCPTool, MCPResource, MCPPrompt, MCPConnection } from "./mcp/index.js";
|
|
138
136
|
export { RealtimeSession } from "./realtime/index.js";
|
|
139
137
|
export type { RealtimeSessionConfig, RealtimeEvent, RealtimeEventHandler } from "./realtime/index.js";
|
|
140
138
|
export { DevTools, DevToolsDashboard } from "./devtools/index.js";
|
package/dist/index.js
CHANGED
|
@@ -101,7 +101,10 @@ export { ElevenLabsAdapter } from "./adapters/elevenlabs.js";
|
|
|
101
101
|
export { VoyageAIAdapter } from "./adapters/voyageai.js";
|
|
102
102
|
export { CohereRerankAdapter } from "./adapters/cohere-rerank.js";
|
|
103
103
|
// ─── MCP ────────────────────────────────────────────────────────────────────
|
|
104
|
-
|
|
104
|
+
// MCP removed in 3.8.0: the client was a stub returning fabricated tool
|
|
105
|
+
// results (`callTool` replied `{result: "Called X on Y"}` without opening a
|
|
106
|
+
// transport). Shipping nothing is better than shipping fake output; the
|
|
107
|
+
// `./mcp` subpath went with it.
|
|
105
108
|
// ─── Realtime ───────────────────────────────────────────────────────────────
|
|
106
109
|
export { RealtimeSession } from "./realtime/index.js";
|
|
107
110
|
// ─── DevTools ───────────────────────────────────────────────────────────────
|
package/dist/logging/logger.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* Redacts common credential formats from text before it reaches errors,
|
|
5
5
|
* telemetry, or logs.
|
|
6
6
|
*/
|
|
7
|
+
import { redactKnownSecrets } from "../security/known-secrets.js";
|
|
7
8
|
const SENSITIVE_PATTERNS = [
|
|
8
9
|
/api[_-]?key\s*[=:]\s*["']?[A-Za-z0-9\-_]{20,}["']?/gi,
|
|
9
10
|
/bearer\s+[A-Za-z0-9\-_.]{20,}/gi,
|
|
@@ -19,7 +20,9 @@ const SENSITIVE_PATTERNS = [
|
|
|
19
20
|
export function redact(text) {
|
|
20
21
|
if (!text)
|
|
21
22
|
return text;
|
|
22
|
-
|
|
23
|
+
// Registered credentials first: exact-value matching has no length floor, so
|
|
24
|
+
// it catches the keys the patterns below are too specific to see.
|
|
25
|
+
let result = redactKnownSecrets(text);
|
|
23
26
|
for (const pattern of SENSITIVE_PATTERNS) {
|
|
24
27
|
result = result.replace(pattern, (match) => {
|
|
25
28
|
if (match.startsWith('"')) {
|
|
@@ -123,7 +123,10 @@ function validateJsonSchema(data, schema) {
|
|
|
123
123
|
}
|
|
124
124
|
}
|
|
125
125
|
}
|
|
126
|
-
else if (type
|
|
126
|
+
else if (type === "object") {
|
|
127
|
+
errors.push(`Expected type "object", got "${Array.isArray(data) ? "array" : data === null ? "null" : typeof data}"`);
|
|
128
|
+
}
|
|
129
|
+
else if (type && type !== typeof data) {
|
|
127
130
|
errors.push(`Expected type "${schema.type}", got "${typeof data}"`);
|
|
128
131
|
}
|
|
129
132
|
return errors;
|
|
@@ -8,16 +8,26 @@
|
|
|
8
8
|
* - Native reasoning fields (Anthropic thinking blocks, Responses reasoning)
|
|
9
9
|
* - Text-based reasoning tags (<thinking>, <reasoning>, <reason>)
|
|
10
10
|
*/
|
|
11
|
-
import type { ReasoningChunk } from "../types/streams.js";
|
|
11
|
+
import type { ReasoningChunk, TextChunk } from "../types/streams.js";
|
|
12
|
+
/** What one delta contributes, in order. */
|
|
13
|
+
export type ReasoningPart = ReasoningChunk | TextChunk;
|
|
12
14
|
export declare class ReasoningNormalizer {
|
|
13
15
|
private _buffer;
|
|
14
16
|
private _inTag;
|
|
15
|
-
private _lastReturnedIndex;
|
|
16
17
|
/**
|
|
17
|
-
* Feed text that might be reasoning
|
|
18
|
-
*
|
|
18
|
+
* Feed text that might be reasoning and return the parts it contributes, in
|
|
19
|
+
* order.
|
|
20
|
+
*
|
|
21
|
+
* A single delta can carry a complete reasoning block *and* the reply that
|
|
22
|
+
* follows it — e.g. `<thinking>2+2=4</thinking>The answer is 4`. The previous
|
|
23
|
+
* single-chunk return value could not express that: it emitted everything
|
|
24
|
+
* after the opening tag as reasoning, so the answer was swallowed and the
|
|
25
|
+
* closing tag leaked into the reasoning text.
|
|
26
|
+
*
|
|
27
|
+
* An empty array means "nothing of its own" — the caller should fall back to
|
|
28
|
+
* treating the delta as plain text.
|
|
19
29
|
*/
|
|
20
|
-
feedText(text: string):
|
|
30
|
+
feedText(text: string): ReasoningPart[];
|
|
21
31
|
/** Explicitly yield a reasoning chunk (for adapters with native reasoning fields) */
|
|
22
32
|
static native(text: string): ReasoningChunk;
|
|
23
33
|
/** Check if text looks like a reasoning opening or closing tag */
|
|
@@ -8,55 +8,64 @@
|
|
|
8
8
|
* - Native reasoning fields (Anthropic thinking blocks, Responses reasoning)
|
|
9
9
|
* - Text-based reasoning tags (<thinking>, <reasoning>, <reason>)
|
|
10
10
|
*/
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
11
|
+
/** Matched only at the start of the buffer, as before. */
|
|
12
|
+
const OPEN_TAG = /^<(?:thinking|reasoning|reason)>\s*/i;
|
|
13
|
+
/** Matched anywhere: the closing tag can sit mid-buffer when a provider batches. */
|
|
14
|
+
const CLOSE_TAG = /<\/(?:thinking|reasoning|reason)>/i;
|
|
15
|
+
/** "<reasoning>" is the longest opening tag — the tail kept for cross-chunk detection. */
|
|
16
|
+
const MAX_TAG_PREFIX = 11;
|
|
15
17
|
export class ReasoningNormalizer {
|
|
16
18
|
_buffer = "";
|
|
17
19
|
_inTag = false;
|
|
18
|
-
_lastReturnedIndex = 0;
|
|
19
20
|
/**
|
|
20
|
-
* Feed text that might be reasoning
|
|
21
|
-
*
|
|
21
|
+
* Feed text that might be reasoning and return the parts it contributes, in
|
|
22
|
+
* order.
|
|
23
|
+
*
|
|
24
|
+
* A single delta can carry a complete reasoning block *and* the reply that
|
|
25
|
+
* follows it — e.g. `<thinking>2+2=4</thinking>The answer is 4`. The previous
|
|
26
|
+
* single-chunk return value could not express that: it emitted everything
|
|
27
|
+
* after the opening tag as reasoning, so the answer was swallowed and the
|
|
28
|
+
* closing tag leaked into the reasoning text.
|
|
29
|
+
*
|
|
30
|
+
* An empty array means "nothing of its own" — the caller should fall back to
|
|
31
|
+
* treating the delta as plain text.
|
|
22
32
|
*/
|
|
23
33
|
feedText(text) {
|
|
24
34
|
this._buffer += text;
|
|
25
|
-
|
|
35
|
+
const parts = [];
|
|
26
36
|
if (!this._inTag) {
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
? { type: "reasoning", text: this._buffer }
|
|
35
|
-
: null;
|
|
37
|
+
const open = OPEN_TAG.exec(this._buffer);
|
|
38
|
+
if (!open) {
|
|
39
|
+
// Not a reasoning tag. Keep only a small tail so a tag split across
|
|
40
|
+
// deltas ("<think" + "ing>") is still detected, without unbounded
|
|
41
|
+
// buffer growth.
|
|
42
|
+
if (this._buffer.length > MAX_TAG_PREFIX) {
|
|
43
|
+
this._buffer = this._buffer.slice(-MAX_TAG_PREFIX);
|
|
36
44
|
}
|
|
45
|
+
return parts;
|
|
37
46
|
}
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
// (e.g. chunk ends with "<think") to prevent unbounded buffer growth.
|
|
41
|
-
const MAX_TAG_PREFIX = 11; // "<reasoning>" is the longest opening tag
|
|
42
|
-
if (this._buffer.length > MAX_TAG_PREFIX) {
|
|
43
|
-
this._buffer = this._buffer.slice(-MAX_TAG_PREFIX);
|
|
44
|
-
}
|
|
45
|
-
return null;
|
|
47
|
+
this._buffer = this._buffer.slice(open[0].length);
|
|
48
|
+
this._inTag = true;
|
|
46
49
|
}
|
|
47
|
-
//
|
|
48
|
-
|
|
50
|
+
// Inside a reasoning block. The closing tag may already be present in this
|
|
51
|
+
// same delta, so check before treating the whole buffer as reasoning.
|
|
52
|
+
const close = CLOSE_TAG.exec(this._buffer);
|
|
53
|
+
if (close) {
|
|
54
|
+
const reasoning = this._buffer.slice(0, close.index).trim();
|
|
55
|
+
const trailing = this._buffer.slice(close.index + close[0].length).trim();
|
|
49
56
|
this._inTag = false;
|
|
50
|
-
const cleaned = this._buffer.replace(TAG_PATTERNS[1], "").trim();
|
|
51
|
-
const newText = cleaned.slice(this._lastReturnedIndex).trim();
|
|
52
57
|
this._buffer = "";
|
|
53
|
-
|
|
54
|
-
|
|
58
|
+
if (reasoning)
|
|
59
|
+
parts.push({ type: "reasoning", text: reasoning });
|
|
60
|
+
if (trailing)
|
|
61
|
+
parts.push({ type: "text", text: trailing });
|
|
62
|
+
return parts;
|
|
55
63
|
}
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
64
|
+
const reasoning = this._buffer;
|
|
65
|
+
this._buffer = "";
|
|
66
|
+
if (reasoning)
|
|
67
|
+
parts.push({ type: "reasoning", text: reasoning });
|
|
68
|
+
return parts;
|
|
60
69
|
}
|
|
61
70
|
/** Explicitly yield a reasoning chunk (for adapters with native reasoning fields) */
|
|
62
71
|
static native(text) {
|
|
@@ -69,6 +78,5 @@ export class ReasoningNormalizer {
|
|
|
69
78
|
reset() {
|
|
70
79
|
this._buffer = "";
|
|
71
80
|
this._inTag = false;
|
|
72
|
-
this._lastReturnedIndex = 0;
|
|
73
81
|
}
|
|
74
82
|
}
|
|
@@ -14,7 +14,9 @@ export function calculateBackoff(attempt, config) {
|
|
|
14
14
|
const capped = Math.min(exponential, cfg.maxDelayMs);
|
|
15
15
|
const jitterRange = capped * cfg.jitter;
|
|
16
16
|
const jitter = (Math.random() * 2 - 1) * jitterRange;
|
|
17
|
-
|
|
17
|
+
// Clamp after jitter: capping first let the positive jitter push the delay
|
|
18
|
+
// above `maxDelayMs`, which callers treat as a hard ceiling.
|
|
19
|
+
return Math.min(cfg.maxDelayMs, Math.max(0, capped + jitter));
|
|
18
20
|
}
|
|
19
21
|
export async function sleep(ms, signal) {
|
|
20
22
|
if (signal?.aborted) {
|
|
@@ -33,6 +33,8 @@ export declare class CircuitBreaker {
|
|
|
33
33
|
private _totalFailures;
|
|
34
34
|
private _totalSuccesses;
|
|
35
35
|
private _halfOpenCalls;
|
|
36
|
+
/** When the current half-open probe round started (for the stuck-round escape). */
|
|
37
|
+
private _halfOpenSince;
|
|
36
38
|
constructor(name: string, config?: CircuitBreakerConfig);
|
|
37
39
|
get state(): CircuitState;
|
|
38
40
|
get stats(): CircuitBreakerStats;
|
|
@@ -24,6 +24,8 @@ export class CircuitBreaker {
|
|
|
24
24
|
_totalFailures = 0;
|
|
25
25
|
_totalSuccesses = 0;
|
|
26
26
|
_halfOpenCalls = 0;
|
|
27
|
+
/** When the current half-open probe round started (for the stuck-round escape). */
|
|
28
|
+
_halfOpenSince = null;
|
|
27
29
|
constructor(name, config = DEFAULT_CB_CONFIG) {
|
|
28
30
|
this.name = name;
|
|
29
31
|
this.config = config;
|
|
@@ -47,6 +49,7 @@ export class CircuitBreaker {
|
|
|
47
49
|
if (this._state === "open") {
|
|
48
50
|
if (this._lastFailureTime && Date.now() - this._lastFailureTime >= this.config.timeoutMs) {
|
|
49
51
|
this._transitionTo("half_open");
|
|
52
|
+
this._halfOpenCalls++;
|
|
50
53
|
return true;
|
|
51
54
|
}
|
|
52
55
|
return false;
|
|
@@ -56,6 +59,18 @@ export class CircuitBreaker {
|
|
|
56
59
|
this._halfOpenCalls++;
|
|
57
60
|
return true;
|
|
58
61
|
}
|
|
62
|
+
// Every probe slot is taken, but slots are released only by recordSuccess /
|
|
63
|
+
// recordFailure. A probe that is admitted and never reported back — an
|
|
64
|
+
// aborted request, or a provider that turns out not to be registered —
|
|
65
|
+
// used to refuse every later request for the rest of the process lifetime.
|
|
66
|
+
// If this probe round has been stuck for a full timeout window, start a
|
|
67
|
+
// fresh one.
|
|
68
|
+
const since = this._halfOpenSince ?? this._lastFailureTime ?? 0;
|
|
69
|
+
if (Date.now() - since >= this.config.timeoutMs) {
|
|
70
|
+
this._halfOpenSince = Date.now();
|
|
71
|
+
this._halfOpenCalls = 1;
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
59
74
|
return false;
|
|
60
75
|
}
|
|
61
76
|
recordSuccess() {
|
|
@@ -98,10 +113,12 @@ export class CircuitBreaker {
|
|
|
98
113
|
this._failureCount = 0;
|
|
99
114
|
this._successCount = 0;
|
|
100
115
|
this._halfOpenCalls = 0;
|
|
116
|
+
this._halfOpenSince = null;
|
|
101
117
|
}
|
|
102
118
|
else if (state === "half_open") {
|
|
103
119
|
this._successCount = 0;
|
|
104
120
|
this._halfOpenCalls = 0;
|
|
121
|
+
this._halfOpenSince = Date.now();
|
|
105
122
|
}
|
|
106
123
|
}
|
|
107
124
|
}
|
|
@@ -79,11 +79,12 @@ export async function withDegradation(transport, url, messages, buildRequest, le
|
|
|
79
79
|
if (response.ok) {
|
|
80
80
|
return { response, level: level.name };
|
|
81
81
|
}
|
|
82
|
-
//
|
|
83
|
-
|
|
84
|
-
|
|
82
|
+
// Remember the status either way. A degradation-recoverable status
|
|
83
|
+
// (413/400) still means this level failed, and when every level fails the
|
|
84
|
+
// caller needs the real cause instead of a generic message.
|
|
85
|
+
lastError = new Error(`HTTP ${response.status}`);
|
|
86
|
+
if (response.status !== 413 && response.status !== 400)
|
|
85
87
|
break;
|
|
86
|
-
}
|
|
87
88
|
}
|
|
88
89
|
catch (err) {
|
|
89
90
|
lastError = err instanceof Error ? err : new Error(String(err));
|
|
@@ -49,7 +49,7 @@ const PRESETS = {
|
|
|
49
49
|
cheap: {
|
|
50
50
|
allowFallback: true,
|
|
51
51
|
maxFallbackCost: null,
|
|
52
|
-
retry: { maxRetries: 10, retryableStatuses: new Set([429, 500, 502, 503, 504
|
|
52
|
+
retry: { maxRetries: 10, retryableStatuses: new Set([408, 429, 500, 502, 503, 504]), retryableNetworkErrors: true },
|
|
53
53
|
backoff: { baseDelayMs: 2_000, maxDelayMs: 120_000, jitter: 0.5 },
|
|
54
54
|
timeout: { requestTimeoutMs: 300_000 },
|
|
55
55
|
circuitBreaker: { enabled: false, failureThreshold: 10, successThreshold: 2, timeoutMs: 60_000, halfOpenMaxCalls: 5 },
|
|
@@ -61,7 +61,7 @@ const PRESETS = {
|
|
|
61
61
|
maximum: {
|
|
62
62
|
allowFallback: true,
|
|
63
63
|
maxFallbackCost: null,
|
|
64
|
-
retry: { maxRetries: 10, retryableStatuses: new Set([429, 500, 502, 503, 504,
|
|
64
|
+
retry: { maxRetries: 10, retryableStatuses: new Set([408, 413, 429, 500, 502, 503, 504, 507]), retryableNetworkErrors: true },
|
|
65
65
|
backoff: { baseDelayMs: 1_000, maxDelayMs: 60_000, jitter: 0.3 },
|
|
66
66
|
timeout: { requestTimeoutMs: 300_000 },
|
|
67
67
|
circuitBreaker: { enabled: true, failureThreshold: 10, successThreshold: 3, timeoutMs: 120_000, halfOpenMaxCalls: 5 },
|
|
@@ -12,7 +12,14 @@ const DEFAULT_RETRY = {
|
|
|
12
12
|
retryableNetworkErrors: true,
|
|
13
13
|
};
|
|
14
14
|
export function createRetryConfig(overrides) {
|
|
15
|
-
|
|
15
|
+
// Copy the status Set. Spreading DEFAULT_RETRY alone shares the reference, so
|
|
16
|
+
// `createRetryConfig().retryableStatuses.add(...)` mutated the module default
|
|
17
|
+
// and every other client with it.
|
|
18
|
+
return {
|
|
19
|
+
...DEFAULT_RETRY,
|
|
20
|
+
...overrides,
|
|
21
|
+
retryableStatuses: new Set(overrides?.retryableStatuses ?? DEFAULT_RETRY.retryableStatuses),
|
|
22
|
+
};
|
|
16
23
|
}
|
|
17
24
|
export function shouldRetry(status, attempt, config) {
|
|
18
25
|
const cfg = config ?? DEFAULT_RETRY;
|
|
@@ -6,8 +6,6 @@
|
|
|
6
6
|
export interface TimeoutConfig {
|
|
7
7
|
/** Request timeout in ms (default: 60_000) */
|
|
8
8
|
requestTimeoutMs: number;
|
|
9
|
-
/** Stream idle timeout in ms — max time without new chunks (default: 120_000) */
|
|
10
|
-
streamIdleTimeoutMs: number;
|
|
11
9
|
}
|
|
12
10
|
export interface ScopedTimeout {
|
|
13
11
|
readonly signal: AbortSignal;
|
|
@@ -20,5 +18,11 @@ export interface ScopedTimeout {
|
|
|
20
18
|
* from caller cancellation and can be cleaned up when an attempt completes.
|
|
21
19
|
*/
|
|
22
20
|
export declare function createScopedTimeout(config?: Partial<TimeoutConfig>, parentSignal?: AbortSignal): ScopedTimeout;
|
|
23
|
-
/** Backwards-compatible signal-only timeout API.
|
|
21
|
+
/** Backwards-compatible signal-only timeout API.
|
|
22
|
+
*
|
|
23
|
+
* @deprecated The returned signal carries no way to cancel, so the timer and
|
|
24
|
+
* the parent `abort` listener live until the timeout fires. Use
|
|
25
|
+
* {@link createScopedTimeout} and call its `cancel()` when the attempt
|
|
26
|
+
* completes.
|
|
27
|
+
*/
|
|
24
28
|
export declare function createTimeoutSignal(config?: Partial<TimeoutConfig>, parentSignal?: AbortSignal): AbortSignal;
|
|
@@ -5,7 +5,6 @@
|
|
|
5
5
|
*/
|
|
6
6
|
const DEFAULT_TIMEOUT = {
|
|
7
7
|
requestTimeoutMs: 60_000,
|
|
8
|
-
streamIdleTimeoutMs: 120_000,
|
|
9
8
|
};
|
|
10
9
|
/**
|
|
11
10
|
* Create an internal timeout scope that can distinguish an internal timeout
|
|
@@ -51,6 +50,10 @@ export function createScopedTimeout(config, parentSignal) {
|
|
|
51
50
|
}
|
|
52
51
|
cleanup();
|
|
53
52
|
}, cfg.requestTimeoutMs);
|
|
53
|
+
// Do not hold the process open for the timeout window: a caller that
|
|
54
|
+
// abandons the scope without calling cancel() would otherwise leave a
|
|
55
|
+
// live timer behind. unref() is Node-only and a no-op elsewhere.
|
|
56
|
+
timer.unref?.();
|
|
54
57
|
}
|
|
55
58
|
}
|
|
56
59
|
return {
|
|
@@ -61,7 +64,13 @@ export function createScopedTimeout(config, parentSignal) {
|
|
|
61
64
|
cancel: cleanup,
|
|
62
65
|
};
|
|
63
66
|
}
|
|
64
|
-
/** Backwards-compatible signal-only timeout API.
|
|
67
|
+
/** Backwards-compatible signal-only timeout API.
|
|
68
|
+
*
|
|
69
|
+
* @deprecated The returned signal carries no way to cancel, so the timer and
|
|
70
|
+
* the parent `abort` listener live until the timeout fires. Use
|
|
71
|
+
* {@link createScopedTimeout} and call its `cancel()` when the attempt
|
|
72
|
+
* completes.
|
|
73
|
+
*/
|
|
65
74
|
export function createTimeoutSignal(config, parentSignal) {
|
|
66
75
|
return createScopedTimeout(config, parentSignal).signal;
|
|
67
76
|
}
|