@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
@@ -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 client = pool.get(fields.model);
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
  },
@@ -49,5 +49,6 @@ export declare function useChat(options: UseChatToolOptions): {
49
49
  setMessages: (newMessages: UIMessage[]) => void;
50
50
  stop: () => void;
51
51
  clear: () => void;
52
+ dispose: () => void;
52
53
  subscribe: (fn: () => void) => () => void;
53
54
  };
@@ -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
- export { MCPClient, createMCPToolExecution } from "./mcp/index.js";
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 ───────────────────────────────────────────────────────────────
@@ -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
- let result = text;
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 && type !== "array" && type !== "object" && type !== typeof data) {
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;
@@ -52,9 +52,18 @@ export function extractJson(raw) {
52
52
  return text;
53
53
  }
54
54
  // Strip markdown code fences: ```json ... ``` or ``` ... ```
55
- const fenceMatch = text.match(/^```(?:json)?\s*\n?([\s\S]*?)\n?\s*```$/);
56
- if (fenceMatch) {
57
- return fenceMatch[1].trim();
55
+ //
56
+ // String operations rather than a regex. The equivalent pattern
57
+ // (`^```(?:json)?\s*\n?([\s\S]*?)\n?\s*```$`) partitions the leading
58
+ // whitespace ambiguously, so a response that opens a fence and then runs on
59
+ // in spaces without ever closing it makes the engine backtrack
60
+ // quadratically — tens of thousands of spaces is enough to hang the process.
61
+ // `extractJson` runs on model output, so an upstream response could trigger
62
+ // it.
63
+ if (text.length >= 6 && text.startsWith("```") && text.endsWith("```")) {
64
+ // Drop the opening fence and its optional language token (```json).
65
+ const body = text.slice(3, -3).replace(/^(?:json)?[ \t]*\r?\n?/, "");
66
+ return body.trim();
58
67
  }
59
68
  // Try to find a JSON object or array in the text by bracket matching
60
69
  const objStart = text.indexOf("{");
@@ -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. Returns a ReasoningChunk if the
18
- * content is confirmed as reasoning, null if it should be treated as text.
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): ReasoningChunk | null;
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
- const TAG_PATTERNS = [
12
- /^<(?:thinking|reasoning|reason)>\s*/i,
13
- /<\/(?:thinking|reasoning|reason)>\s*$/i,
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. Returns a ReasoningChunk if the
21
- * content is confirmed as reasoning, null if it should be treated as text.
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
- // Check if we just entered a reasoning tag
35
+ const parts = [];
26
36
  if (!this._inTag) {
27
- for (const pat of TAG_PATTERNS) {
28
- if (pat.test(this._buffer)) {
29
- this._inTag = true;
30
- // Strip the opening tag
31
- this._buffer = this._buffer.replace(TAG_PATTERNS[0], "");
32
- this._lastReturnedIndex = this._buffer.length;
33
- return this._buffer.length > 0
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
- // Not a reasoning tag — return null (caller should yield as text).
39
- // v2.4.0 BUG-02: keep only a small tail for cross-chunk tag detection
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
- // We're inside a tag — check for closing
48
- if (/<\/(?:thinking|reasoning|reason)>/i.test(this._buffer)) {
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
- this._lastReturnedIndex = 0;
54
- return newText ? { type: "reasoning", text: newText } : null;
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
- // Still accumulating inside tag — return only new content
57
- const newText = this._buffer.slice(this._lastReturnedIndex);
58
- this._lastReturnedIndex = this._buffer.length;
59
- return { type: "reasoning", text: newText };
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
- return Math.max(0, capped + jitter);
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
- // If the response is not ok but not a degradation-recoverable error, throw
83
- if (response.status !== 413 && response.status !== 400) {
84
- lastError = new Error(`HTTP ${response.status}`);
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, 408, 429]), retryableNetworkErrors: true },
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, 408, 413, 429, 507]), retryableNetworkErrors: true },
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
- return { ...DEFAULT_RETRY, ...overrides };
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
  }
@@ -15,7 +15,7 @@
15
15
  * console.log(result[0].reasons); // ["Supports required tools", "Within budget", ...]
16
16
  */
17
17
  import { BUILTIN_MODELS } from "../catalog/models.js";
18
- import { estimateCost } from "../tokens/counter.js";
18
+ import { estimateCost, hasPricing } from "../tokens/counter.js";
19
19
  /** Task-specific scoring weights — defines what matters for each task type */
20
20
  const TASK_WEIGHTS = {
21
21
  coding: { reasoning: 25, tools: 25, speed: 15, cost: 20, structured: 15 },
@@ -73,6 +73,8 @@ export class ModelRouter {
73
73
  provider: s.entry.provider,
74
74
  model: s.entry.id,
75
75
  score: s.score,
76
+ estimatedCost: this._estimateCost(s.entry),
77
+ rejectionReason: s.reasons[0],
76
78
  }));
77
79
  return scored.map((s, i) => ({
78
80
  provider: s.entry.provider,
@@ -116,7 +118,13 @@ export class ModelRouter {
116
118
  const fallbacks = (primary.fallbacks ?? []);
117
119
  const allCandidates = [
118
120
  { provider: primary.provider, model: primary.model, score: primary.score, estimatedCost: primary.estimatedCost, reasons: primary.reasons },
119
- ...fallbacks.map((f) => ({ provider: f.provider, model: f.model, score: f.score, estimatedCost: 0, reasons: [f.rejectionReason ?? ""] })),
121
+ ...fallbacks.map((f) => ({
122
+ provider: f.provider,
123
+ model: f.model,
124
+ score: f.score,
125
+ estimatedCost: f.estimatedCost ?? 0,
126
+ reasons: [f.rejectionReason ?? "Fallback candidate"],
127
+ })),
120
128
  ];
121
129
  // Estimate total cost: primary + retries + repairs + possible fallback
122
130
  const retryCostPerAttempt = primary.estimatedCost * 0.8; // Assume retries are slightly cheaper (backoff reduces load)
@@ -233,9 +241,12 @@ export class ModelRouter {
233
241
  const taskFit = this._computeTaskFit(entry, req);
234
242
  // Context fit score (0-100)
235
243
  const contextFit = this._computeContextFit(entry, req);
236
- // Cost score (0-100) — lower cost = higher score
244
+ // Cost score (0-100) — lower cost = higher score. An unpriced model is not
245
+ // free: `estimateCost` returns 0 for an unknown model, and treating that as
246
+ // perfect cost efficiency made the router prefer models with no known price.
237
247
  const cost = this._estimateCost(entry);
238
- const costEfficiency = cost === 0 ? 100 : Math.max(0, 100 - (cost * 2000));
248
+ const priced = hasPricing(entry.provider, entry.id);
249
+ const costEfficiency = !priced ? 0 : cost === 0 ? 100 : Math.max(0, 100 - (cost * 2000));
239
250
  if (req.maxCost && cost <= req.maxCost)
240
251
  reasons.push(`Within budget ($${cost.toFixed(4)} of $${req.maxCost})`);
241
252
  else if (req.budget)
@@ -262,7 +273,8 @@ export class ModelRouter {
262
273
  reasons.push(`Context window sufficient (${entry.contextWindow.toLocaleString()} tokens)`);
263
274
  }
264
275
  // Weighted combination
265
- const finalScore = (capabilityFit * (weights.reasoning + weights.tools + weights.structured) / 100)
276
+ const capabilityWeight = (weights.reasoning + weights.tools + weights.structured) / 100;
277
+ const rawScore = (capabilityFit * capabilityWeight)
266
278
  + (taskFit * 10 / 100)
267
279
  + (contextFit * 10 / 100)
268
280
  + (costEfficiency * weights.cost / 100)
@@ -271,6 +283,19 @@ export class ModelRouter {
271
283
  + providerPreference
272
284
  + structuredOutputFit
273
285
  + toolFit;
286
+ // Normalise against the maximum this task's weights can reach. The weighted
287
+ // sum alone runs to ~155, and clamping it at 100 made most models tie and
288
+ // dropped the ranking back to catalog order.
289
+ const maxScore = (100 * capabilityWeight)
290
+ + 10
291
+ + 10
292
+ + (100 * weights.cost / 100)
293
+ + (100 * weights.speed / 100)
294
+ + 10
295
+ + 5
296
+ + 10
297
+ + 10;
298
+ const finalScore = maxScore > 0 ? (rawScore / maxScore) * 100 : 0;
274
299
  const breakdown = {
275
300
  capabilityFit: Math.round(capabilityFit),
276
301
  taskFit: Math.round(taskFit),