@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.
Files changed (77) hide show
  1. package/README.md +16 -8
  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 +52 -7
  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 +47 -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/telemetry/opentelemetry.d.ts +6 -1
  63. package/dist/telemetry/opentelemetry.js +41 -0
  64. package/dist/tokens/counter.d.ts +6 -0
  65. package/dist/tokens/counter.js +43 -35
  66. package/dist/transport/fetch.js +47 -5
  67. package/dist/types/observability.d.ts +2 -0
  68. package/dist/types/router.d.ts +3 -0
  69. package/dist/utils/base64.d.ts +13 -0
  70. package/dist/utils/base64.js +20 -0
  71. package/dist/utils/sse-writer.d.ts +9 -0
  72. package/dist/utils/sse-writer.js +5 -2
  73. package/dist/utils/sse.d.ts +20 -0
  74. package/dist/utils/sse.js +52 -10
  75. package/package.json +10 -10
  76. package/dist/mcp/index.d.ts +0 -63
  77. package/dist/mcp/index.js +0 -77
@@ -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 {
@@ -38,9 +38,7 @@ export class RequestExecutor {
38
38
  }
39
39
  }
40
40
  const timeoutMs = resolved.timeout.requestTimeoutMs || input.providerTimeoutMs || 0;
41
- const timeout = timeoutMs > 0
42
- ? createScopedTimeout({ requestTimeoutMs: timeoutMs }, input.callerSignal)
43
- : undefined;
41
+ let timeout;
44
42
  const retryConfig = createRetryConfig({
45
43
  maxRetries: resolved.retry.maxRetries,
46
44
  retryableStatuses: resolved.retry.retryableStatuses,
@@ -50,19 +48,28 @@ export class RequestExecutor {
50
48
  context,
51
49
  retryConfig,
52
50
  circuitBreaker,
53
- signal: timeout?.signal ?? input.callerSignal,
54
- timeout,
51
+ beginAttempt: () => {
52
+ timeout?.cancel();
53
+ timeout = timeoutMs > 0
54
+ ? createScopedTimeout({ requestTimeoutMs: timeoutMs }, input.callerSignal)
55
+ : undefined;
56
+ return timeout?.signal ?? input.callerSignal;
57
+ },
58
+ get signal() {
59
+ return timeout?.signal ?? input.callerSignal;
60
+ },
55
61
  dispose: () => timeout?.cancel(),
56
62
  };
57
63
  }
58
64
  async *executeStream(prepared, params, options = {}) {
65
+ const signal = prepared.beginAttempt();
59
66
  const adapter = this.ports.adapters.get(prepared.context.provider);
60
67
  if (!adapter) {
61
68
  throw new ProviderNotFoundError(prepared.context.provider);
62
69
  }
63
70
  try {
64
- for await (const chunk of adapter.stream({ ...params, signal: prepared.signal })) {
65
- if (prepared.signal?.aborted) {
71
+ for await (const chunk of adapter.stream({ ...params, signal })) {
72
+ if (signal?.aborted) {
66
73
  throw new DOMException("The operation was aborted", "AbortError");
67
74
  }
68
75
  yield chunk;
@@ -81,6 +88,7 @@ export class RequestExecutor {
81
88
  }
82
89
  }
83
90
  async executeComplete(prepared, params, options = {}) {
91
+ const signal = prepared.beginAttempt();
84
92
  if (prepared.context.callerSignal?.aborted) {
85
93
  return executionFailure(new DOMException("The operation was aborted", "AbortError"), prepared.context);
86
94
  }
@@ -89,7 +97,7 @@ export class RequestExecutor {
89
97
  return executionFailure(new ProviderNotFoundError(prepared.context.provider), prepared.context);
90
98
  }
91
99
  try {
92
- const value = await adapter.complete({ ...params, signal: prepared.signal });
100
+ const value = await adapter.complete({ ...params, signal });
93
101
  prepared.circuitBreaker?.recordSuccess();
94
102
  return executionSuccess(value, prepared.context);
95
103
  }
@@ -36,6 +36,20 @@ function isNetworkFailure(error) {
36
36
  }
37
37
  return false;
38
38
  }
39
+ /**
40
+ * One retry classifier shared by the complete, stream and structured loops.
41
+ * The structured loop omitted `isNetworkFailure`, so a socket ECONNRESET never
42
+ * retried there while the same error did on `complete()`.
43
+ */
44
+ function classifyRetryableFailure(error, attempt, retryConfig) {
45
+ const status = error.status;
46
+ const isNetworkError = error instanceof TypeError
47
+ || (error instanceof Error && error.name === "AbortError")
48
+ || isNetworkFailure(error);
49
+ const retryable = (isNetworkError && shouldRetryNetworkError(attempt, retryConfig))
50
+ || (typeof status === "number" && shouldRetry(status, attempt, retryConfig));
51
+ return { retryable, isNetworkError, status };
52
+ }
39
53
  export class RequestPipeline {
40
54
  ports;
41
55
  constructor(ports) {
@@ -89,12 +103,10 @@ export class RequestPipeline {
89
103
  if (input.callerSignal?.aborted) {
90
104
  break;
91
105
  }
92
- const status = primaryError.status;
93
- const isNetworkError = primaryError instanceof TypeError
94
- || (primaryError instanceof Error && primaryError.name === "AbortError")
95
- || isNetworkFailure(primaryError);
96
- const canRetry = (isNetworkError && shouldRetryNetworkError(attempt, prepared.retryConfig))
97
- || (typeof status === "number" && shouldRetry(status, attempt, prepared.retryConfig));
106
+ const failure = classifyRetryableFailure(primaryError, attempt, prepared.retryConfig);
107
+ const status = failure.status;
108
+ const isNetworkError = failure.isNetworkError;
109
+ const canRetry = failure.retryable;
98
110
  if (canRetry) {
99
111
  const delay = calculateBackoff(attempt, prepared.context.policy.backoff);
100
112
  this.ports.emit({
@@ -138,7 +150,7 @@ export class RequestPipeline {
138
150
  provider: fallback.provider,
139
151
  model: fallback.model,
140
152
  params: { ...input.params, model: fallback.model },
141
- callerSignal: prepared.signal,
153
+ callerSignal: input.callerSignal,
142
154
  providerTimeoutMs: 0,
143
155
  });
144
156
  const fallbackResult = await this.ports.executor.executeComplete(fallbackPrepared, { ...input.params, model: fallback.model }, { recordCircuitFailure: false });
@@ -248,7 +260,7 @@ export class RequestPipeline {
248
260
  type: "stream.first_chunk",
249
261
  requestId: input.requestId,
250
262
  timestamp: this.ports.now(),
251
- latencyMs: 0,
263
+ latencyMs: this.ports.now() - input.startTime,
252
264
  });
253
265
  }
254
266
  if (chunk.type === "usage") {
@@ -284,6 +296,7 @@ export class RequestPipeline {
284
296
  attempts: attempt + 1,
285
297
  inputTokens,
286
298
  outputTokens,
299
+ estimatedCost: input.estimatedCost,
287
300
  structuredOutput: false,
288
301
  });
289
302
  await this.ports.plugins.fireResponse({
@@ -330,12 +343,10 @@ export class RequestPipeline {
330
343
  }
331
344
  throw error;
332
345
  }
333
- const status = error.status;
334
- const isNetworkError = error instanceof TypeError
335
- || (error instanceof Error && error.name === "AbortError")
336
- || isNetworkFailure(error);
337
- const canRetry = (isNetworkError && shouldRetryNetworkError(attempt, prepared.retryConfig))
338
- || (typeof status === "number" && shouldRetry(status, attempt, prepared.retryConfig));
346
+ const failure = classifyRetryableFailure(error, attempt, prepared.retryConfig);
347
+ const status = failure.status;
348
+ const isNetworkError = failure.isNetworkError;
349
+ const canRetry = failure.retryable;
339
350
  if (!canRetry) {
340
351
  if (prepared.context.policy.allowFallback) {
341
352
  releaseMainBudget();
@@ -365,13 +376,14 @@ export class RequestPipeline {
365
376
  let fallbackInputTokens;
366
377
  let fallbackOutputTokens;
367
378
  let fallbackReservationActive = true;
379
+ let fallbackFirstChunk = false;
368
380
  try {
369
381
  fallbackPrepared = this.prepare({
370
382
  ...input,
371
383
  provider: fallback.provider,
372
384
  model: fallback.model,
373
385
  params: { ...input.params, model: fallback.model },
374
- callerSignal: prepared.signal,
386
+ callerSignal: input.callerSignal,
375
387
  providerTimeoutMs: 0,
376
388
  }, "stream");
377
389
  for await (const chunk of this.ports.executor.executeStream(fallbackPrepared, { ...input.params, model: fallback.model }, { recordCircuitFailure: false })) {
@@ -388,6 +400,15 @@ export class RequestPipeline {
388
400
  fallbackReservationActive = false;
389
401
  }
390
402
  }
403
+ if (!fallbackFirstChunk) {
404
+ fallbackFirstChunk = true;
405
+ this.ports.emit({
406
+ type: "stream.first_chunk",
407
+ requestId: input.requestId,
408
+ timestamp: this.ports.now(),
409
+ latencyMs: this.ports.now() - input.startTime,
410
+ });
411
+ }
391
412
  yield chunk;
392
413
  }
393
414
  if (fallbackReservationActive) {
@@ -408,6 +429,7 @@ export class RequestPipeline {
408
429
  attempts: attempt + 2,
409
430
  inputTokens: fallbackInputTokens,
410
431
  outputTokens: fallbackOutputTokens,
432
+ estimatedCost: input.estimatedCost,
411
433
  structuredOutput: false,
412
434
  });
413
435
  await this.ports.plugins.fireResponse({
@@ -623,11 +645,10 @@ export class RequestPipeline {
623
645
  primaryError = result.error;
624
646
  if (input.callerSignal?.aborted)
625
647
  break;
626
- const status = primaryError.status;
627
- const isNetworkError = primaryError instanceof TypeError
628
- || (primaryError instanceof Error && primaryError.name === "AbortError");
629
- const canRetry = (isNetworkError && shouldRetryNetworkError(attempt, prepared.retryConfig))
630
- || (typeof status === "number" && shouldRetry(status, attempt, prepared.retryConfig));
648
+ const failure = classifyRetryableFailure(primaryError, attempt, prepared.retryConfig);
649
+ const status = failure.status;
650
+ const isNetworkError = failure.isNetworkError;
651
+ const canRetry = failure.retryable;
631
652
  if (canRetry) {
632
653
  const delay = calculateBackoff(attempt, prepared.context.policy.backoff);
633
654
  this.ports.emit({
@@ -650,7 +671,10 @@ export class RequestPipeline {
650
671
  continue;
651
672
  }
652
673
  if (prepared.context.policy.allowFallback) {
653
- this.ports.budget.release(input.requestId);
674
+ // releaseBudget(), not a bare release: the guarded helper marks the
675
+ // reservation released so the trailing cleanup does not release the
676
+ // same id twice.
677
+ releaseBudget();
654
678
  const attemptedModels = [input.model];
655
679
  const fallbacks = input.fallbackCandidates(attemptedModels);
656
680
  for (const fallback of fallbacks) {
@@ -671,7 +695,7 @@ export class RequestPipeline {
671
695
  provider: fallback.provider,
672
696
  model: fallback.model,
673
697
  params: { ...input.params, model: fallback.model },
674
- callerSignal: prepared.signal,
698
+ callerSignal: input.callerSignal,
675
699
  providerTimeoutMs: 0,
676
700
  });
677
701
  const fallbackResult = await this.ports.executor.executeComplete(fallbackPrepared, {
@@ -789,6 +813,7 @@ export class RequestPipeline {
789
813
  model,
790
814
  durationMs: this.ports.now() - input.startTime,
791
815
  attempts,
816
+ estimatedCost: input.estimatedCost,
792
817
  structuredOutput,
793
818
  });
794
819
  }
@@ -43,6 +43,11 @@ export interface CostAlertConfig {
43
43
  thresholds?: ThresholdConfig[];
44
44
  /** Default channel for thresholds that don't specify one */
45
45
  defaultChannel?: AlertChannel;
46
+ /**
47
+ * Called when a channel fails to deliver an alert. A failed delivery does
48
+ * not mark the threshold as fired, so the next check retries it.
49
+ */
50
+ onDispatchError?: (error: unknown, alert: CostAlert) => void;
46
51
  }
47
52
  /**
48
53
  * Creates a BudgetConfig that integrates with the CostAlertMonitor.
@@ -99,8 +104,20 @@ export declare class CostAlertMonitor {
99
104
  * Reset all fired thresholds (e.g., when starting a new budget period).
100
105
  */
101
106
  reset(): void;
102
- private _currentPercent;
107
+ /**
108
+ * Percent of the session budget consumed, counted on committed cost
109
+ * (`totalActual + totalReserved`). The tracker's `remainingBudget` is
110
+ * already net of reservations, so `totalActual` is the wrong numerator:
111
+ * with $90 reserved and $0 spent it would report 0%.
112
+ */
113
+ private _percent;
103
114
  private _fireThresholds;
104
115
  private _buildAlert;
116
+ /**
117
+ * Deliver an alert. `percent` is the threshold it belongs to: the caller has
118
+ * already marked it fired, and this releases it again if delivery fails, so
119
+ * the next check retries instead of losing the alert.
120
+ */
105
121
  private _dispatch;
122
+ private _settle;
106
123
  }
@@ -79,19 +79,16 @@ export class CostAlertMonitor {
79
79
  this._firedThresholds.add(100);
80
80
  const alert = this._buildAlert(100, report, "budget_exceeded");
81
81
  alerts.push(alert);
82
- this._dispatch(alert);
82
+ this._dispatch(alert, undefined, 100);
83
83
  }
84
- if (report.remainingBudget !== undefined && report.remainingBudget !== null) {
85
- const sessionBudget = report.totalActual + report.remainingBudget;
86
- if (sessionBudget > 0) {
87
- const percent = (report.totalActual / sessionBudget) * 100;
88
- for (const threshold of this._config.thresholds ?? []) {
89
- if (percent >= threshold.percent && !this._firedThresholds.has(threshold.percent)) {
90
- this._firedThresholds.add(threshold.percent);
91
- const alert = this._buildAlert(threshold.percent, report, "threshold_reached");
92
- alerts.push(alert);
93
- this._dispatch(alert, threshold.channel);
94
- }
84
+ const percent = this._percent(report);
85
+ if (percent !== null) {
86
+ for (const threshold of this._config.thresholds ?? []) {
87
+ if (percent >= threshold.percent && !this._firedThresholds.has(threshold.percent)) {
88
+ this._firedThresholds.add(threshold.percent);
89
+ const alert = this._buildAlert(threshold.percent, report, "threshold_reached");
90
+ alerts.push(alert);
91
+ this._dispatch(alert, threshold.channel, threshold.percent);
95
92
  }
96
93
  }
97
94
  }
@@ -104,16 +101,23 @@ export class CostAlertMonitor {
104
101
  this._firedThresholds.clear();
105
102
  this._firedExceeded = false;
106
103
  }
107
- _currentPercent(report) {
104
+ /**
105
+ * Percent of the session budget consumed, counted on committed cost
106
+ * (`totalActual + totalReserved`). The tracker's `remainingBudget` is
107
+ * already net of reservations, so `totalActual` is the wrong numerator:
108
+ * with $90 reserved and $0 spent it would report 0%.
109
+ */
110
+ _percent(report) {
108
111
  if (report.remainingBudget === undefined || report.remainingBudget === null)
109
112
  return null;
110
- const budget = report.totalActual + report.remainingBudget;
113
+ const committed = report.committedCost;
114
+ const budget = committed + report.remainingBudget;
111
115
  if (budget <= 0)
112
116
  return report.budgetExceeded ? 100 : null;
113
- return Math.max(0, Math.min(100, (report.totalActual / budget) * 100));
117
+ return Math.max(0, Math.min(100, (committed / budget) * 100));
114
118
  }
115
119
  _fireThresholds(report, type) {
116
- const currentPercent = this._currentPercent(report);
120
+ const currentPercent = this._percent(report);
117
121
  if (currentPercent === null)
118
122
  return;
119
123
  const thresholds = type === "budget_exceeded"
@@ -124,7 +128,7 @@ export class CostAlertMonitor {
124
128
  continue;
125
129
  this._firedThresholds.add(threshold.percent);
126
130
  const alert = this._buildAlert(threshold.percent, report, type);
127
- this._dispatch(alert, threshold.channel);
131
+ this._dispatch(alert, threshold.channel, threshold.percent);
128
132
  }
129
133
  if (type === "budget_exceeded") {
130
134
  this._firedThresholds.add(100);
@@ -139,24 +143,56 @@ export class CostAlertMonitor {
139
143
  type,
140
144
  };
141
145
  }
142
- async _dispatch(alert, channel) {
146
+ /**
147
+ * Deliver an alert. `percent` is the threshold it belongs to: the caller has
148
+ * already marked it fired, and this releases it again if delivery fails, so
149
+ * the next check retries instead of losing the alert.
150
+ */
151
+ _dispatch(alert, channel, percent) {
143
152
  const target = channel ?? this._config.defaultChannel;
144
- if (!target)
153
+ if (!target) {
154
+ this._settle(percent, true);
145
155
  return;
146
- try {
147
- if (target.type === "webhook" && target.url) {
148
- await fetch(target.url, {
149
- method: "POST",
150
- headers: { "Content-Type": "application/json" },
151
- body: JSON.stringify(alert),
152
- });
153
- }
154
- else if (target.type === "callback" && target.callback) {
156
+ }
157
+ const settle = (ok, error) => {
158
+ this._settle(percent, ok);
159
+ if (!ok)
160
+ this._config.onDispatchError?.(error, alert);
161
+ };
162
+ if (target.type === "webhook" && target.url) {
163
+ void fetch(target.url, {
164
+ method: "POST",
165
+ headers: { "Content-Type": "application/json" },
166
+ body: JSON.stringify(alert),
167
+ })
168
+ .then((response) => {
169
+ if (response.ok) {
170
+ settle(true);
171
+ }
172
+ else {
173
+ settle(false, new Error(`alert webhook returned HTTP ${response.status}`));
174
+ }
175
+ })
176
+ .catch((error) => settle(false, error));
177
+ return;
178
+ }
179
+ if (target.type === "callback" && target.callback) {
180
+ try {
155
181
  target.callback(alert);
182
+ settle(true);
156
183
  }
184
+ catch (error) {
185
+ settle(false, error);
186
+ }
187
+ return;
157
188
  }
158
- catch {
159
- // Alert dispatch errors never break the SDK
160
- }
189
+ settle(true);
190
+ }
191
+ _settle(percent, delivered) {
192
+ if (percent === undefined || delivered)
193
+ return;
194
+ this._firedThresholds.delete(percent);
195
+ if (percent === 100)
196
+ this._firedExceeded = false;
161
197
  }
162
198
  }
@@ -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 endpoint for Astro.
11
11
  *
@@ -41,10 +41,13 @@ export function createChatEndpoint(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 createCompletionEndpoint(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,
@@ -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 endpoint for Next.js.
11
11
  *
@@ -38,13 +38,16 @@ export function createChatHandler(options) {
38
38
  trustClientFields,
39
39
  limits,
40
40
  });
41
+ // Run the request hook before building a client. `pool.get()` constructs
42
+ // one, so doing it first let any unauthenticated caller force a client
43
+ // construction even when the hook was about to reject them.
44
+ const effective = { ...fields, provider: resolveCatalogProviderId(options.provider) };
45
+ await options.onRequest?.({ request: req, body, effective });
41
46
  // Resolving the client before responding means a bad provider or model
42
47
  // produces a real error status instead of an HTTP 200 whose body carries
43
48
  // the failure.
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: req, body, effective });
48
51
  const allMessages = [
49
52
  ...(options.systemPrompt ? [{ role: "system", content: options.systemPrompt }] : []),
50
53
  ...fields.messages,
@@ -73,7 +76,14 @@ export function createChatHandler(options) {
73
76
  maxSteps: fields.maxSteps,
74
77
  signal: req.signal,
75
78
  });
76
- return createSSEResponse(chunks);
79
+ return createSSEResponse(chunks, {
80
+ onError: (streamError) => {
81
+ // The provider call happens lazily inside the stream, after this
82
+ // handler has already returned 200, so this is the only place a
83
+ // streaming failure can reach the operator.
84
+ void options.onError?.(streamError, { request: req, phase: "provider" });
85
+ },
86
+ });
77
87
  }
78
88
  catch (error) {
79
89
  if (options.onError) {
@@ -110,9 +120,11 @@ export function createCompletionHandler(options) {
110
120
  trustClientFields,
111
121
  limits,
112
122
  });
113
- const client = pool.get(fields.model);
114
- const effective = { ...fields, provider: pool.providerName };
123
+ // Same ordering as the chat handler: the hook decides before a client is
124
+ // built.
125
+ const effective = { ...fields, provider: resolveCatalogProviderId(options.provider) };
115
126
  await options.onRequest?.({ request: req, body, effective });
127
+ const client = pool.get(fields.model);
116
128
  const result = await client.complete({
117
129
  provider: pool.providerName,
118
130
  model: fields.model,
@@ -52,11 +52,19 @@ export function useChat(options = {}) {
52
52
  }
53
53
  }
54
54
  async function append(message) {
55
+ // One stream at a time. Without this, two overlapping calls each appended
56
+ // an assistant placeholder and both wrote into the last array slot, so the
57
+ // text interleaved — and `abortController` was overwritten, leaving only
58
+ // the second request abortable.
59
+ if (isLoading.value)
60
+ return;
55
61
  const newMessages = [...messages.value, message];
56
62
  messages.value = newMessages;
57
63
  await sendRequest(newMessages);
58
64
  }
59
65
  async function reload() {
66
+ if (isLoading.value)
67
+ return;
60
68
  const msgs = messages.value;
61
69
  if (msgs.length === 0)
62
70
  return;
@@ -5,7 +5,7 @@
5
5
  * Handles message state, streaming, tool calls, input, error recovery,
6
6
  * optimistic updates, reload, and step-level callbacks.
7
7
  */
8
- import { useState, useCallback, useRef } from "react";
8
+ import { useState, useCallback, useEffect, useRef } from "react";
9
9
  import { parseUIStream } from "./stream-parser.js";
10
10
  let _idCounter = 0;
11
11
  function generateId() {
@@ -23,6 +23,13 @@ export function useChat(options) {
23
23
  abortRef.current = null;
24
24
  setIsLoading(false);
25
25
  }, []);
26
+ // Abort an in-flight stream on unmount. Without this the reader keeps running
27
+ // and writing state into a component that no longer exists. `react-client`
28
+ // already did this; the other hooks did not.
29
+ useEffect(() => () => {
30
+ abortRef.current?.abort();
31
+ abortRef.current = null;
32
+ }, []);
26
33
  const sendRequest = useCallback(async (messageHistory, assistantMessage) => {
27
34
  const controller = new AbortController();
28
35
  abortRef.current = controller;
@@ -82,4 +82,21 @@ export interface UseChatReturn {
82
82
  * }
83
83
  * ```
84
84
  */
85
+ /**
86
+ * Build the provider payload for one turn.
87
+ *
88
+ * Extracted so the retry path is testable without a renderer: `retry` must not
89
+ * append the user turn a second time, and must not re-send the failed
90
+ * assistant turn.
91
+ */
92
+ export declare function buildChatApiMessages(params: {
93
+ transcript: ChatMessage[];
94
+ userContent: string;
95
+ systemPrompt?: string;
96
+ maxContextMessages: number;
97
+ appendUserMessage: boolean;
98
+ }): Array<{
99
+ role: "user" | "assistant" | "system";
100
+ content: string;
101
+ }>;
85
102
  export declare function useChat(options: UseChatOptions): UseChatReturn;