reliable-requests 0.2.1 → 0.3.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/src/local-chat.js CHANGED
@@ -1,343 +1,409 @@
1
- import { reliableRequest, HttpError, RequestTimeoutError } from './index.js';
2
- import { createLineParser, createSseParser } from './sse.js';
3
- import { parseEndpoint, isLoopback } from './endpoint.js';
4
- import { parseEvent, openaiChoice, ollamaMessage, InvalidStreamEventError } from './stream-events.js';
5
- import {
6
- isRetryableStatus,
7
- defaultShouldRetryError,
8
- retryDelayMs,
9
- pause,
10
- abortError,
11
- discardResponse,
12
- } from './retry.js';
13
-
14
- export { InvalidStreamEventError } from './stream-events.js';
15
- export { StreamLineTooLongError, StreamEventTooLongError } from './sse.js';
16
-
17
- export class StreamInterruptedError extends Error {
18
- constructor(message = 'The model stream ended before completion') {
19
- super(message);
20
- this.name = 'StreamInterruptedError';
21
- this.code = 'STREAM_INTERRUPTED';
22
- }
23
- }
24
-
25
- export class ModelRedirectError extends Error {
26
- constructor() {
27
- super('Model endpoint redirects are not supported');
28
- this.name = 'ModelRedirectError';
29
- this.code = 'MODEL_REDIRECT';
30
- }
31
- }
32
-
33
- export class UnsupportedModelOutputError extends Error {
34
- constructor() {
35
- super('Tool calls are not supported by this text-only API');
36
- this.name = 'UnsupportedModelOutputError';
37
- this.code = 'UNSUPPORTED_MODEL_OUTPUT';
38
- }
39
- }
40
-
41
- const DEFAULT_MAX_LINE_CHARS = 262_144;
42
- const HARD_MAX_LINE_CHARS = 4_194_304;
43
- const MAX_DECODE_CHUNK_BYTES = 16 * 1024;
44
-
45
- const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
46
- const TOOL_FINISH_REASONS = new Set(['tool_calls', 'function_call']);
47
-
48
- function isRedirect(response) {
49
- return response.redirected ||
50
- response.type === 'opaqueredirect' ||
51
- REDIRECT_STATUSES.has(response.status);
52
- }
53
-
54
- function readOpenAIEvent(text) {
55
- if (text === '[DONE]') return { done: true };
56
-
57
- const choice = openaiChoice(parseEvent(text, 'openai'));
58
- const delta = choice?.delta;
59
- if (delta?.tool_calls?.length || delta?.function_call ||
60
- TOOL_FINISH_REASONS.has(choice?.finish_reason)) {
61
- throw new UnsupportedModelOutputError();
62
- }
63
-
64
- return { content: delta?.content, finishReason: choice?.finish_reason };
65
- }
66
-
67
- function readOllamaEvent(text) {
68
- const event = parseEvent(text, 'ollama');
69
- const message = ollamaMessage(event);
70
- if (message?.tool_calls?.length) throw new UnsupportedModelOutputError();
71
-
72
- return {
73
- content: message?.content,
74
- finishReason: event.done_reason,
75
- done: event.done === true,
76
- };
77
- }
78
-
79
- async function readStream(response, {
80
- protocol,
81
- signal,
82
- onText,
83
- maxLineChars,
84
- maxEventChars,
85
- markNetworkError,
86
- checkDeadline,
87
- }) {
88
- if (!response.body) throw new StreamInterruptedError('The response has no stream');
89
-
90
- const reader = response.body.getReader();
91
- const cancelReader = () => { reader.cancel().catch(() => {}); };
92
- signal.addEventListener('abort', cancelReader, { once: true });
93
-
94
- const decoder = new TextDecoder('utf-8', { fatal: true });
95
- const decode = (bytes, options) => {
96
- try {
97
- return decoder.decode(bytes, options);
98
- } catch {
99
- throw new InvalidStreamEventError(protocol, 'UTF-8');
100
- }
101
- };
102
- const readEvent = protocol === 'openai' ? readOpenAIEvent : readOllamaEvent;
103
- let complete = false;
104
- let finishReason = null;
105
-
106
- function onLine(raw) {
107
- checkDeadline();
108
- const text = raw.trim();
109
- if (!text) return;
110
-
111
- const event = readEvent(text);
112
- if (typeof event.finishReason === 'string') finishReason = event.finishReason;
113
- if (typeof event.content === 'string' && event.content) onText(event.content);
114
- if (event.done) {
115
- complete = true;
116
- return false;
117
- }
118
- }
119
-
120
- const parser = protocol === 'openai'
121
- ? createSseParser({ maxLineChars, maxEventChars, onData: onLine })
122
- : createLineParser({ maxLineChars, onLine });
123
-
124
- try {
125
- while (!complete) {
126
- let chunk;
127
- try {
128
- chunk = await reader.read();
129
- } catch (error) {
130
- markNetworkError('read');
131
- throw error;
132
- }
133
-
134
- checkDeadline();
135
- if (signal.aborted) throw abortError();
136
- const { value, done } = chunk;
137
-
138
- if (done) {
139
- let trailing;
140
- try {
141
- trailing = decoder.decode();
142
- } catch {
143
- throw new StreamInterruptedError('The model stream ended in an incomplete UTF-8 character');
144
- }
145
- parser.push(trailing);
146
- parser.finish(protocol === 'ollama');
147
- break;
148
- }
149
-
150
- for (let offset = 0; offset < value.byteLength && !complete; offset += MAX_DECODE_CHUNK_BYTES) {
151
- checkDeadline();
152
- const bytes = value.subarray(offset, offset + MAX_DECODE_CHUNK_BYTES);
153
- parser.push(decode(bytes, { stream: true }));
154
- }
155
- }
156
-
157
- checkDeadline();
158
- if (!complete) throw new StreamInterruptedError();
159
- return finishReason;
160
- } finally {
161
- signal.removeEventListener('abort', cancelReader);
162
- cancelReader();
163
- try { reader.releaseLock(); } catch {}
164
- }
165
- }
166
-
167
- function shouldRetryStream(error, attempt, networkPhase, shouldRetryError) {
168
- if (error instanceof HttpError) return isRetryableStatus(error.status);
169
- if (error instanceof StreamInterruptedError) return true;
170
- if (networkPhase === null) return false;
171
-
172
- return shouldRetryError(error, {
173
- attempt,
174
- method: 'POST',
175
- phase: networkPhase,
176
- }) === true;
177
- }
178
-
179
- /**
180
- * Retry a text-only local model generation, including a partially delivered stream.
181
- * onEvent receives attempt, delta, reset, retry, and done events.
182
- */
183
- export async function streamLocalChat({
184
- endpoint,
185
- protocol = 'openai',
186
- model,
187
- messages,
188
- timeoutMs = 120_000,
189
- retries = 2,
190
- signal,
191
- onEvent,
192
- headers,
193
- fetchImpl = globalThis.fetch,
194
- shouldRetryError = defaultShouldRetryError,
195
- allowRemoteRetries = false,
196
- maxLineChars = DEFAULT_MAX_LINE_CHARS,
197
- maxEventChars = maxLineChars,
198
- } = {}) {
199
- if (protocol !== 'openai' && protocol !== 'ollama') throw new TypeError('protocol must be openai or ollama');
200
- if (!model || typeof model !== 'string') throw new TypeError('model is required');
201
- if (!Array.isArray(messages) || !messages.every(m => typeof m?.role === 'string' && typeof m?.content === 'string')) {
202
- throw new TypeError('messages must contain text-only role/content pairs');
203
- }
204
- if (typeof onEvent !== 'function') throw new TypeError('onEvent is required');
205
- if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647) throw new RangeError('invalid timeoutMs');
206
- if (!Number.isSafeInteger(retries) || retries < 0) throw new RangeError('invalid retries');
207
- if (!Number.isSafeInteger(maxLineChars) || maxLineChars < 1 || maxLineChars > HARD_MAX_LINE_CHARS) {
208
- throw new RangeError('maxLineChars must be an integer between 1 and 4194304');
209
- }
210
- if (!Number.isSafeInteger(maxEventChars) || maxEventChars < 1 || maxEventChars > HARD_MAX_LINE_CHARS) {
211
- throw new RangeError('maxEventChars must be an integer between 1 and 4194304');
212
- }
213
- if (typeof fetchImpl !== 'function') throw new TypeError('fetchImpl must be a function');
214
- if (typeof shouldRetryError !== 'function') throw new TypeError('shouldRetryError must be a function');
215
- const base = parseEndpoint(endpoint);
216
- if (retries > 0 && !isLoopback(base) && !allowRemoteRetries) {
217
- throw new Error('Retries for remote servers require allowRemoteRetries: true');
218
- }
219
- const url = base;
220
- const path = url.pathname.replace(/\/+$/, '');
221
- if (protocol === 'ollama') {
222
- url.pathname = path + '/api/chat';
223
- } else {
224
- const versionPath = path.endsWith('/v1') ? path : path + '/v1';
225
- url.pathname = versionPath + '/chat/completions';
226
- }
227
- url.search = '';
228
- url.hash = '';
229
- const requestHeaders = new Headers(headers);
230
- requestHeaders.set('content-type', 'application/json');
231
- const payload = { model, messages, stream: true };
232
- if (protocol === 'openai') payload.n = 1;
233
- const body = JSON.stringify(payload);
234
- const controller = new AbortController();
235
- let expired = false;
236
- const callerAbort = () => controller.abort();
237
- if (signal?.aborted) throw abortError();
238
- signal?.addEventListener('abort', callerAbort, { once: true });
239
- const started = performance.now();
240
- const timer = setTimeout(() => {
241
- expired = true;
242
- controller.abort();
243
- }, timeoutMs);
244
- const remainingMs = () => timeoutMs - (performance.now() - started);
245
- const checkDeadline = () => {
246
- if (expired || remainingMs() <= 0) {
247
- expired = true;
248
- controller.abort();
249
- throw new RequestTimeoutError(timeoutMs);
250
- }
251
- if (controller.signal.aborted) throw abortError();
252
- };
253
- let callbackFailed = false;
254
- const emit = event => {
255
- checkDeadline();
256
- try {
257
- onEvent(event);
258
- } catch (error) {
259
- callbackFailed = true;
260
- throw error;
261
- }
262
- };
263
- try {
264
- for (let attempt = 1; attempt <= retries + 1; attempt++) {
265
- checkDeadline();
266
- let partial = false;
267
- let networkPhase = null;
268
- emit({ type: 'attempt', attempt });
269
- try {
270
- checkDeadline();
271
- const remaining = Math.max(1, Math.ceil(remainingMs()));
272
- const finishReason = await reliableRequest(url, {
273
- method: 'POST',
274
- body,
275
- headers: requestHeaders,
276
- retries: 0,
277
- redirect: 'manual',
278
- timeoutMs: remaining,
279
- signal: controller.signal,
280
- fetchImpl: async (...args) => {
281
- let response;
282
- try {
283
- response = await fetchImpl(...args);
284
- } catch (error) {
285
- networkPhase = 'fetch';
286
- throw error;
287
- }
288
- if (isRedirect(response)) {
289
- discardResponse(response);
290
- throw new ModelRedirectError();
291
- }
292
- return response;
293
- },
294
- consume: (response, readSignal) => readStream(response, {
295
- protocol,
296
- signal: readSignal,
297
- maxLineChars,
298
- maxEventChars,
299
- checkDeadline,
300
- markNetworkError: phase => { networkPhase = phase; },
301
- onText(text) {
302
- partial = true;
303
- emit({ type: 'delta', attempt, text });
304
- },
305
- }),
306
- });
307
- checkDeadline();
308
- const completion = finishReason === null ? {} : { finishReason };
309
- emit({ type: 'done', attempt, ...completion });
310
- return { attempts: attempt, ...completion };
311
- } catch (error) {
312
- if (callbackFailed) throw error;
313
- if (expired || error instanceof RequestTimeoutError) throw new RequestTimeoutError(timeoutMs);
314
- if (controller.signal.aborted) throw abortError();
315
- checkDeadline();
316
- if (attempt > retries || error?.name === 'AbortError') throw error;
317
- if (!shouldRetryStream(error, attempt, networkPhase, shouldRetryError)) throw error;
318
-
319
- const response = error instanceof HttpError ? error.response : undefined;
320
- if (response) discardResponse(response);
321
- const delayMs = retryDelayMs({ attempt, response, remainingMs: remainingMs() });
322
- if (delayMs === null) {
323
- throw new RequestTimeoutError(timeoutMs, 'Retry delay cannot fit within the ' + timeoutMs + ' ms total timeout');
324
- }
325
- emit({ type: 'retry', attempt, error, partial, delayMs });
326
- checkDeadline();
327
- try {
328
- await pause(delayMs, controller.signal);
329
- } catch (waitError) {
330
- if (expired) throw new RequestTimeoutError(timeoutMs);
331
- throw waitError;
332
- }
333
- checkDeadline();
334
- if (partial) emit({ type: 'reset', attempt: attempt + 1 });
335
- }
336
- }
337
- } finally {
338
- clearTimeout(timer);
339
- signal?.removeEventListener('abort', callerAbort);
340
- controller.abort();
341
- }
342
- }
343
-
1
+ import { reliableRequest, HttpError, RequestTimeoutError } from './index.js';
2
+ import { createLineParser, createSseParser, StreamLineTooLongError, StreamEventTooLongError } from './sse.js';
3
+ import { parseEndpoint, isLoopback } from './endpoint.js';
4
+ import { parseEvent, openaiChoice, ollamaMessage, InvalidStreamEventError } from './stream-events.js';
5
+ import {
6
+ isRetryableStatus,
7
+ defaultShouldRetryError,
8
+ retryDelayMs,
9
+ pause,
10
+ abortError,
11
+ discardResponse,
12
+ } from './retry.js';
13
+
14
+ export { InvalidStreamEventError } from './stream-events.js';
15
+ export { StreamLineTooLongError, StreamEventTooLongError } from './sse.js';
16
+
17
+ export class StreamTimeoutError extends Error {
18
+ constructor(phase, timeoutMs) {
19
+ super(phase === 'first-text'
20
+ ? 'No model text arrived within ' + timeoutMs + ' ms'
21
+ : 'No further model text arrived within ' + timeoutMs + ' ms');
22
+ this.name = 'StreamTimeoutError';
23
+ this.code = 'STREAM_TIMEOUT';
24
+ this.phase = phase;
25
+ this.timeoutMs = timeoutMs;
26
+ }
27
+ }
28
+
29
+ export class StreamInterruptedError extends Error {
30
+ constructor(message = 'The model stream ended before completion') {
31
+ super(message);
32
+ this.name = 'StreamInterruptedError';
33
+ this.code = 'STREAM_INTERRUPTED';
34
+ }
35
+ }
36
+
37
+ export class ModelRedirectError extends Error {
38
+ constructor() {
39
+ super('Model endpoint redirects are not supported');
40
+ this.name = 'ModelRedirectError';
41
+ this.code = 'MODEL_REDIRECT';
42
+ }
43
+ }
44
+
45
+ export class UnsupportedModelOutputError extends Error {
46
+ constructor() {
47
+ super('Tool calls are not supported by this text-only API');
48
+ this.name = 'UnsupportedModelOutputError';
49
+ this.code = 'UNSUPPORTED_MODEL_OUTPUT';
50
+ }
51
+ }
52
+
53
+ const DEFAULT_MAX_LINE_CHARS = 262_144;
54
+ const HARD_MAX_LINE_CHARS = 4_194_304;
55
+ const MAX_DECODE_CHUNK_BYTES = 16 * 1024;
56
+
57
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
58
+ const TOOL_FINISH_REASONS = new Set(['tool_calls', 'function_call']);
59
+
60
+ function isRedirect(response) {
61
+ return response.redirected ||
62
+ response.type === 'opaqueredirect' ||
63
+ REDIRECT_STATUSES.has(response.status);
64
+ }
65
+
66
+ function readOpenAIEvent(text) {
67
+ if (text === '[DONE]') return { done: true };
68
+
69
+ const choice = openaiChoice(parseEvent(text, 'openai'));
70
+ const delta = choice?.delta;
71
+ if (delta?.tool_calls?.length || delta?.function_call ||
72
+ TOOL_FINISH_REASONS.has(choice?.finish_reason)) {
73
+ throw new UnsupportedModelOutputError();
74
+ }
75
+
76
+ return { content: delta?.content, finishReason: choice?.finish_reason };
77
+ }
78
+
79
+ function readOllamaEvent(text) {
80
+ const event = parseEvent(text, 'ollama');
81
+ const message = ollamaMessage(event);
82
+ if (message?.tool_calls?.length) throw new UnsupportedModelOutputError();
83
+
84
+ return {
85
+ content: message?.content,
86
+ finishReason: event.done_reason,
87
+ done: event.done === true,
88
+ };
89
+ }
90
+
91
+ async function readStream(response, {
92
+ protocol,
93
+ signal,
94
+ onText,
95
+ maxLineChars,
96
+ maxEventChars,
97
+ markNetworkError,
98
+ checkDeadline,
99
+ }) {
100
+ if (!response.body) throw new StreamInterruptedError('The response has no stream');
101
+
102
+ const reader = response.body.getReader();
103
+ const cancelReader = () => { reader.cancel().catch(() => {}); };
104
+ signal.addEventListener('abort', cancelReader, { once: true });
105
+
106
+ const decoder = new TextDecoder('utf-8', { fatal: true });
107
+ const decode = (bytes, options) => {
108
+ try {
109
+ return decoder.decode(bytes, options);
110
+ } catch {
111
+ throw new InvalidStreamEventError(protocol, 'UTF-8');
112
+ }
113
+ };
114
+ const readEvent = protocol === 'openai' ? readOpenAIEvent : readOllamaEvent;
115
+ let complete = false;
116
+ let finishReason = null;
117
+
118
+ function onLine(raw) {
119
+ checkDeadline();
120
+ const text = raw.trim();
121
+ if (!text) return;
122
+
123
+ const event = readEvent(text);
124
+ if (typeof event.finishReason === 'string') finishReason = event.finishReason;
125
+ if (typeof event.content === 'string' && event.content) onText(event.content);
126
+ if (event.done) {
127
+ complete = true;
128
+ return false;
129
+ }
130
+ }
131
+
132
+ const parser = protocol === 'openai'
133
+ ? createSseParser({ maxLineChars, maxEventChars, onData: onLine })
134
+ : createLineParser({ maxLineChars, onLine });
135
+
136
+ try {
137
+ while (!complete) {
138
+ let chunk;
139
+ try {
140
+ chunk = await reader.read();
141
+ } catch (error) {
142
+ markNetworkError('read');
143
+ throw error;
144
+ }
145
+
146
+ checkDeadline();
147
+ if (signal.aborted) throw abortError();
148
+ const { value, done } = chunk;
149
+
150
+ if (done) {
151
+ let trailing;
152
+ try {
153
+ trailing = decoder.decode();
154
+ } catch {
155
+ throw new StreamInterruptedError('The model stream ended in an incomplete UTF-8 character');
156
+ }
157
+ parser.push(trailing);
158
+ parser.finish(protocol === 'ollama');
159
+ break;
160
+ }
161
+
162
+ for (let offset = 0; offset < value.byteLength && !complete; offset += MAX_DECODE_CHUNK_BYTES) {
163
+ checkDeadline();
164
+ const bytes = value.subarray(offset, offset + MAX_DECODE_CHUNK_BYTES);
165
+ parser.push(decode(bytes, { stream: true }));
166
+ }
167
+ }
168
+
169
+ checkDeadline();
170
+ if (!complete) throw new StreamInterruptedError();
171
+ return finishReason;
172
+ } finally {
173
+ signal.removeEventListener('abort', cancelReader);
174
+ cancelReader();
175
+ try { reader.releaseLock(); } catch {}
176
+ }
177
+ }
178
+
179
+ function shouldRetryStream(error, attempt, networkPhase, shouldRetryError) {
180
+ if (error instanceof StreamTimeoutError ||
181
+ error instanceof ModelRedirectError ||
182
+ error instanceof UnsupportedModelOutputError ||
183
+ error instanceof InvalidStreamEventError ||
184
+ error instanceof StreamLineTooLongError ||
185
+ error instanceof StreamEventTooLongError) return false;
186
+ if (error instanceof HttpError) return isRetryableStatus(error.status);
187
+ if (error instanceof StreamInterruptedError) return true;
188
+ if (networkPhase === null) return false;
189
+
190
+ return shouldRetryError(error, {
191
+ attempt,
192
+ method: 'POST',
193
+ phase: networkPhase,
194
+ }) === true;
195
+ }
196
+
197
+ /**
198
+ * Retry a text-only local model generation, including a partially delivered stream.
199
+ * onEvent receives attempt, delta, reset, retry, and done events.
200
+ */
201
+ export async function streamLocalChat({
202
+ endpoint,
203
+ protocol = 'openai',
204
+ model,
205
+ messages,
206
+ timeoutMs = 120_000,
207
+ firstTextTimeoutMs,
208
+ idleTimeoutMs,
209
+ retries = 2,
210
+ signal,
211
+ onEvent,
212
+ headers,
213
+ fetchImpl = globalThis.fetch,
214
+ shouldRetryError = defaultShouldRetryError,
215
+ allowRemoteRetries = false,
216
+ maxLineChars = DEFAULT_MAX_LINE_CHARS,
217
+ maxEventChars = maxLineChars,
218
+ } = {}) {
219
+ if (protocol !== 'openai' && protocol !== 'ollama') throw new TypeError('protocol must be openai or ollama');
220
+ if (!model || typeof model !== 'string') throw new TypeError('model is required');
221
+ if (!Array.isArray(messages) || !messages.every(m => typeof m?.role === 'string' && typeof m?.content === 'string')) {
222
+ throw new TypeError('messages must contain text-only role/content pairs');
223
+ }
224
+ if (typeof onEvent !== 'function') throw new TypeError('onEvent is required');
225
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647) throw new RangeError('invalid timeoutMs');
226
+ for (const [name, value] of Object.entries({ firstTextTimeoutMs, idleTimeoutMs })) {
227
+ if (value !== undefined && (!Number.isSafeInteger(value) || value <= 0 || value > 2_147_483_647)) {
228
+ throw new RangeError(name + ' must be a positive integer no greater than 2147483647');
229
+ }
230
+ }
231
+ if (!Number.isSafeInteger(retries) || retries < 0) throw new RangeError('invalid retries');
232
+ if (!Number.isSafeInteger(maxLineChars) || maxLineChars < 1 || maxLineChars > HARD_MAX_LINE_CHARS) {
233
+ throw new RangeError('maxLineChars must be an integer between 1 and 4194304');
234
+ }
235
+ if (!Number.isSafeInteger(maxEventChars) || maxEventChars < 1 || maxEventChars > HARD_MAX_LINE_CHARS) {
236
+ throw new RangeError('maxEventChars must be an integer between 1 and 4194304');
237
+ }
238
+ if (typeof fetchImpl !== 'function') throw new TypeError('fetchImpl must be a function');
239
+ if (typeof shouldRetryError !== 'function') throw new TypeError('shouldRetryError must be a function');
240
+ const base = parseEndpoint(endpoint);
241
+ if (retries > 0 && !isLoopback(base) && !allowRemoteRetries) {
242
+ throw new Error('Retries for remote servers require allowRemoteRetries: true');
243
+ }
244
+ const url = base;
245
+ const path = url.pathname.replace(/\/+$/, '');
246
+ if (protocol === 'ollama') {
247
+ url.pathname = path + '/api/chat';
248
+ } else {
249
+ const versionPath = path.endsWith('/v1') ? path : path + '/v1';
250
+ url.pathname = versionPath + '/chat/completions';
251
+ }
252
+ url.search = '';
253
+ url.hash = '';
254
+ const requestHeaders = new Headers(headers);
255
+ requestHeaders.set('content-type', 'application/json');
256
+ const payload = { model, messages, stream: true };
257
+ if (protocol === 'openai') payload.n = 1;
258
+ const body = JSON.stringify(payload);
259
+ const controller = new AbortController();
260
+ let expired = false;
261
+ const callerAbort = () => controller.abort();
262
+ if (signal?.aborted) throw abortError();
263
+ signal?.addEventListener('abort', callerAbort, { once: true });
264
+ const started = performance.now();
265
+ const timer = setTimeout(() => {
266
+ expired = true;
267
+ controller.abort();
268
+ }, timeoutMs);
269
+ const remainingMs = () => timeoutMs - (performance.now() - started);
270
+ let phaseTimer;
271
+ let phaseDeadline = null;
272
+ let phaseFailure;
273
+ let phase;
274
+ let phaseLimit;
275
+ const clearPhase = () => {
276
+ clearTimeout(phaseTimer);
277
+ phaseDeadline = null;
278
+ };
279
+ const expirePhase = () => {
280
+ if (controller.signal.aborted || phaseDeadline === null) return;
281
+ const remaining = phaseDeadline - performance.now();
282
+ if (remaining > 0) {
283
+ phaseTimer = setTimeout(expirePhase, Math.ceil(remaining));
284
+ return;
285
+ }
286
+ phaseFailure = new StreamTimeoutError(phase, phaseLimit);
287
+ clearPhase();
288
+ controller.abort();
289
+ };
290
+ const armPhase = (name, limit) => {
291
+ clearPhase();
292
+ if (limit === undefined) return;
293
+ phase = name;
294
+ phaseLimit = limit;
295
+ phaseDeadline = performance.now() + limit;
296
+ phaseTimer = setTimeout(expirePhase, limit);
297
+ };
298
+ const checkDeadline = () => {
299
+ if (expired || remainingMs() <= 0) {
300
+ expired = true;
301
+ controller.abort();
302
+ throw new RequestTimeoutError(timeoutMs);
303
+ }
304
+ if (phaseFailure) throw phaseFailure;
305
+ if (controller.signal.aborted) throw abortError();
306
+ if (phaseDeadline !== null && performance.now() >= phaseDeadline) {
307
+ expirePhase();
308
+ if (phaseFailure) throw phaseFailure;
309
+ }
310
+ };
311
+ let callbackFailed = false;
312
+ const emit = event => {
313
+ checkDeadline();
314
+ try {
315
+ onEvent(event);
316
+ } catch (error) {
317
+ callbackFailed = true;
318
+ throw error;
319
+ }
320
+ };
321
+ try {
322
+ for (let attempt = 1; attempt <= retries + 1; attempt++) {
323
+ checkDeadline();
324
+ let partial = false;
325
+ let networkPhase = null;
326
+ emit({ type: 'attempt', attempt });
327
+ try {
328
+ checkDeadline();
329
+ armPhase('first-text', firstTextTimeoutMs);
330
+ const remaining = Math.max(1, Math.ceil(remainingMs()));
331
+ const finishReason = await reliableRequest(url, {
332
+ method: 'POST',
333
+ body,
334
+ headers: requestHeaders,
335
+ retries: 0,
336
+ redirect: 'manual',
337
+ timeoutMs: remaining,
338
+ signal: controller.signal,
339
+ fetchImpl: async (...args) => {
340
+ let response;
341
+ try {
342
+ response = await fetchImpl(...args);
343
+ } catch (error) {
344
+ networkPhase = 'fetch';
345
+ throw error;
346
+ }
347
+ if (isRedirect(response)) {
348
+ discardResponse(response);
349
+ throw new ModelRedirectError();
350
+ }
351
+ return response;
352
+ },
353
+ consume: (response, readSignal) => readStream(response, {
354
+ protocol,
355
+ signal: readSignal,
356
+ maxLineChars,
357
+ maxEventChars,
358
+ checkDeadline,
359
+ markNetworkError: phase => { networkPhase = phase; },
360
+ onText(text) {
361
+ checkDeadline();
362
+ armPhase('idle', idleTimeoutMs);
363
+ partial = true;
364
+ emit({ type: 'delta', attempt, text });
365
+ },
366
+ }),
367
+ });
368
+ checkDeadline();
369
+ clearPhase();
370
+ const completion = finishReason === null ? {} : { finishReason };
371
+ emit({ type: 'done', attempt, ...completion });
372
+ return { attempts: attempt, ...completion };
373
+ } catch (error) {
374
+ try {
375
+ if (callbackFailed) throw error;
376
+ if (expired || error instanceof RequestTimeoutError) throw new RequestTimeoutError(timeoutMs);
377
+ checkDeadline();
378
+ } finally {
379
+ clearPhase();
380
+ }
381
+ if (attempt > retries || error?.name === 'AbortError') throw error;
382
+ if (!shouldRetryStream(error, attempt, networkPhase, shouldRetryError)) throw error;
383
+
384
+ const response = error instanceof HttpError ? error.response : undefined;
385
+ if (response) discardResponse(response);
386
+ const delayMs = retryDelayMs({ attempt, response, remainingMs: remainingMs() });
387
+ if (delayMs === null) {
388
+ throw new RequestTimeoutError(timeoutMs, 'Retry delay cannot fit within the ' + timeoutMs + ' ms total timeout');
389
+ }
390
+ emit({ type: 'retry', attempt, error, partial, delayMs });
391
+ checkDeadline();
392
+ try {
393
+ await pause(delayMs, controller.signal);
394
+ } catch (waitError) {
395
+ if (expired) throw new RequestTimeoutError(timeoutMs);
396
+ throw waitError;
397
+ }
398
+ checkDeadline();
399
+ if (partial) emit({ type: 'reset', attempt: attempt + 1 });
400
+ }
401
+ }
402
+ } finally {
403
+ clearPhase();
404
+ clearTimeout(timer);
405
+ signal?.removeEventListener('abort', callerAbort);
406
+ controller.abort();
407
+ }
408
+ }
409
+