@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.
- package/README.md +15 -7
- 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 +37 -2
- 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 +44 -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/output/structured.js +12 -3
- 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/tokens/counter.d.ts +6 -0
- package/dist/tokens/counter.js +43 -35
- package/dist/transport/fetch.js +47 -5
- 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 -11
- package/dist/mcp/index.d.ts +0 -63
- package/dist/mcp/index.js +0 -77
|
@@ -38,9 +38,7 @@ export class RequestExecutor {
|
|
|
38
38
|
}
|
|
39
39
|
}
|
|
40
40
|
const timeoutMs = resolved.timeout.requestTimeoutMs || input.providerTimeoutMs || 0;
|
|
41
|
-
|
|
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
|
-
|
|
54
|
-
|
|
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
|
|
65
|
-
if (
|
|
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
|
|
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
|
|
93
|
-
const
|
|
94
|
-
|
|
95
|
-
|
|
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:
|
|
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:
|
|
263
|
+
latencyMs: this.ports.now() - input.startTime,
|
|
252
264
|
});
|
|
253
265
|
}
|
|
254
266
|
if (chunk.type === "usage") {
|
|
@@ -331,12 +343,10 @@ export class RequestPipeline {
|
|
|
331
343
|
}
|
|
332
344
|
throw error;
|
|
333
345
|
}
|
|
334
|
-
const
|
|
335
|
-
const
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
const canRetry = (isNetworkError && shouldRetryNetworkError(attempt, prepared.retryConfig))
|
|
339
|
-
|| (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;
|
|
340
350
|
if (!canRetry) {
|
|
341
351
|
if (prepared.context.policy.allowFallback) {
|
|
342
352
|
releaseMainBudget();
|
|
@@ -366,13 +376,14 @@ export class RequestPipeline {
|
|
|
366
376
|
let fallbackInputTokens;
|
|
367
377
|
let fallbackOutputTokens;
|
|
368
378
|
let fallbackReservationActive = true;
|
|
379
|
+
let fallbackFirstChunk = false;
|
|
369
380
|
try {
|
|
370
381
|
fallbackPrepared = this.prepare({
|
|
371
382
|
...input,
|
|
372
383
|
provider: fallback.provider,
|
|
373
384
|
model: fallback.model,
|
|
374
385
|
params: { ...input.params, model: fallback.model },
|
|
375
|
-
callerSignal:
|
|
386
|
+
callerSignal: input.callerSignal,
|
|
376
387
|
providerTimeoutMs: 0,
|
|
377
388
|
}, "stream");
|
|
378
389
|
for await (const chunk of this.ports.executor.executeStream(fallbackPrepared, { ...input.params, model: fallback.model }, { recordCircuitFailure: false })) {
|
|
@@ -389,6 +400,15 @@ export class RequestPipeline {
|
|
|
389
400
|
fallbackReservationActive = false;
|
|
390
401
|
}
|
|
391
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
|
+
}
|
|
392
412
|
yield chunk;
|
|
393
413
|
}
|
|
394
414
|
if (fallbackReservationActive) {
|
|
@@ -625,11 +645,10 @@ export class RequestPipeline {
|
|
|
625
645
|
primaryError = result.error;
|
|
626
646
|
if (input.callerSignal?.aborted)
|
|
627
647
|
break;
|
|
628
|
-
const
|
|
629
|
-
const
|
|
630
|
-
|
|
631
|
-
const canRetry =
|
|
632
|
-
|| (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;
|
|
633
652
|
if (canRetry) {
|
|
634
653
|
const delay = calculateBackoff(attempt, prepared.context.policy.backoff);
|
|
635
654
|
this.ports.emit({
|
|
@@ -652,7 +671,10 @@ export class RequestPipeline {
|
|
|
652
671
|
continue;
|
|
653
672
|
}
|
|
654
673
|
if (prepared.context.policy.allowFallback) {
|
|
655
|
-
|
|
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();
|
|
656
678
|
const attemptedModels = [input.model];
|
|
657
679
|
const fallbacks = input.fallbackCandidates(attemptedModels);
|
|
658
680
|
for (const fallback of fallbacks) {
|
|
@@ -673,7 +695,7 @@ export class RequestPipeline {
|
|
|
673
695
|
provider: fallback.provider,
|
|
674
696
|
model: fallback.model,
|
|
675
697
|
params: { ...input.params, model: fallback.model },
|
|
676
|
-
callerSignal:
|
|
698
|
+
callerSignal: input.callerSignal,
|
|
677
699
|
providerTimeoutMs: 0,
|
|
678
700
|
});
|
|
679
701
|
const fallbackResult = await this.ports.executor.executeComplete(fallbackPrepared, {
|
package/dist/cost/alerts.d.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
}
|
package/dist/cost/alerts.js
CHANGED
|
@@ -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
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
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
|
-
|
|
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
|
|
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, (
|
|
117
|
+
return Math.max(0, Math.min(100, (committed / budget) * 100));
|
|
114
118
|
}
|
|
115
119
|
_fireThresholds(report, type) {
|
|
116
|
-
const currentPercent = this.
|
|
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
|
-
|
|
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
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
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
|
-
|
|
159
|
-
|
|
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
|
|
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
|
-
|
|
114
|
-
|
|
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;
|
|
@@ -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,
|