@node-agent/provider 0.0.0-stage → 0.1.5

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 (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +167 -2
  3. package/dist/i18n/en.json +105 -0
  4. package/dist/i18n/zh-CN.json +105 -0
  5. package/dist/icon.svg +6 -0
  6. package/dist/index.d.ts +20 -0
  7. package/dist/index.js +364 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/mode.d.ts +26 -0
  10. package/dist/mode.js +39 -0
  11. package/dist/mode.js.map +1 -0
  12. package/dist/persistency/history.d.ts +11 -0
  13. package/dist/persistency/history.js +50 -0
  14. package/dist/persistency/history.js.map +1 -0
  15. package/dist/persistency/index.d.ts +23 -0
  16. package/dist/persistency/index.js +33 -0
  17. package/dist/persistency/index.js.map +1 -0
  18. package/dist/persistency/local.d.ts +20 -0
  19. package/dist/persistency/local.js +50 -0
  20. package/dist/persistency/local.js.map +1 -0
  21. package/dist/providers/anthropic.d.ts +28 -0
  22. package/dist/providers/anthropic.js +538 -0
  23. package/dist/providers/anthropic.js.map +1 -0
  24. package/dist/providers/base.d.ts +262 -0
  25. package/dist/providers/base.js +871 -0
  26. package/dist/providers/base.js.map +1 -0
  27. package/dist/providers/deepseek.d.ts +18 -0
  28. package/dist/providers/deepseek.js +73 -0
  29. package/dist/providers/deepseek.js.map +1 -0
  30. package/dist/providers/index.d.ts +13 -0
  31. package/dist/providers/index.js +30 -0
  32. package/dist/providers/index.js.map +1 -0
  33. package/dist/providers/responses.d.ts +28 -0
  34. package/dist/providers/responses.js +310 -0
  35. package/dist/providers/responses.js.map +1 -0
  36. package/dist/serve.d.ts +2 -0
  37. package/dist/serve.js +28 -0
  38. package/dist/serve.js.map +1 -0
  39. package/dist/ui.html +324 -0
  40. package/package.json +190 -4
  41. package/src/icon.svg +6 -0
  42. package/src/ui.html +324 -0
@@ -0,0 +1,871 @@
1
+ // Provider-neutral chat types and the OpenAI-compatible implementation.
2
+ //
3
+ // The three protocols share these shapes. A caller sends a transcript in the neutral message shape,
4
+ // the provider translates it to its wire, and the answer comes back in the same neutral shape. The
5
+ // node, the page and an agent therefore never learn which protocol answered.
6
+ import { setTimeout as sleep } from 'node:timers/promises';
7
+ import OpenAI from 'openai';
8
+ /** How many attempts one request gets, the first one included; `NODE_AGENT_MODEL_ATTEMPTS` (8).
9
+ * 1 means "never retry". A failed request is a pause, not the end. */
10
+ export const RETRY_ATTEMPTS = Math.max(1, Number.parseInt(process.env.NODE_AGENT_MODEL_ATTEMPTS ?? '8', 10) || 8);
11
+ /** The wait before the second attempt, in seconds; `NODE_AGENT_MODEL_BACKOFF` (1). */
12
+ export const RETRY_BACKOFF = Number(process.env.NODE_AGENT_MODEL_BACKOFF ?? '1') || 1;
13
+ /** The longest one wait may grow to, in seconds; `NODE_AGENT_MODEL_MAX_DELAY` (60). */
14
+ export const RETRY_MAX_DELAY = Math.max(0, Number(process.env.NODE_AGENT_MODEL_MAX_DELAY ?? '60') || 60);
15
+ /** Statuses this deployment asked *not* to retry: `NODE_AGENT_MODEL_NO_RETRY_STATUSES=401,403`,
16
+ * `4xx`, or `400-499`.
17
+ *
18
+ * The policy is "an HTTP failure is a retry", 400 and 404 included, because a gateway in front of a
19
+ * model answers all of those for reasons a second attempt outlives. A status is skipped only when
20
+ * somebody writes it here, in the open — never because the base class quietly decided a retry is
21
+ * pointless. A 429 or an upstream limit body is retried even so: that is a wait, not a verdict. */
22
+ export const RETRY_EXCLUDED_STATUSES = parseStatuses(process.env.NODE_AGENT_MODEL_NO_RETRY_STATUSES ?? '');
23
+ /** `401,403`, `4xx` and `400-499` in one comma-separated list, as a set of statuses. */
24
+ function parseStatuses(raw) {
25
+ const statuses = new Set();
26
+ for (const part of raw.split(',')) {
27
+ const text = part.trim();
28
+ if (text === '')
29
+ continue;
30
+ const range = /^(\d{3})\s*-\s*(\d{3})$/.exec(text);
31
+ if (range !== null) {
32
+ const from = Number(range[1]);
33
+ const to = Number(range[2]);
34
+ for (let status = from; status <= to; status += 1)
35
+ statuses.add(status);
36
+ continue;
37
+ }
38
+ const wholeClass = /^([1-5])xx$/i.exec(text);
39
+ if (wholeClass !== null) {
40
+ const hundred = Number(wholeClass[1]) * 100;
41
+ for (let status = hundred; status < hundred + 100; status += 1)
42
+ statuses.add(status);
43
+ continue;
44
+ }
45
+ const single = Number(text);
46
+ if (Number.isInteger(single) && single >= 100 && single <= 599)
47
+ statuses.add(single);
48
+ }
49
+ return statuses;
50
+ }
51
+ /** The one policy the three protocols run under; the base class owns it, a provider does not. */
52
+ export const retryPolicy = {
53
+ attempts: RETRY_ATTEMPTS,
54
+ backoffSeconds: RETRY_BACKOFF,
55
+ maxDelaySeconds: RETRY_MAX_DELAY,
56
+ excludedStatuses: new Set(RETRY_EXCLUDED_STATUSES),
57
+ random: () => Math.random(),
58
+ };
59
+ /** The wait before attempt `attempt + 1`, in seconds: the base doubled per attempt, jittered, capped.
60
+ *
61
+ * Half of the wait is fixed and half random, so callers that failed together do not all come back
62
+ * at the same instant, while the wait still grows with every attempt. */
63
+ export function retryDelaySeconds(attempt, policy = retryPolicy) {
64
+ const cap = Math.max(0, policy.maxDelaySeconds);
65
+ const base = Math.min(Math.max(0, policy.backoffSeconds) * 2 ** Math.max(0, attempt - 1), cap);
66
+ if (base <= 0)
67
+ return 0;
68
+ const jitter = 0.5 + Math.min(Math.max(policy.random(), 0), 1) * 0.5;
69
+ return Math.min(base * jitter, cap);
70
+ }
71
+ /** What an OpenAI row posts to when the page leaves `base_url` blank. */
72
+ export const OPENAI_BASE_URL = 'https://api.openai.com/v1';
73
+ /** The pause between two attempts. A test replaces it, because the wait is not what it checks; a
74
+ * cancel closes it early, because a caller that stopped waiting deserves its error back at once. */
75
+ export const retryPause = {
76
+ async for(seconds, signal) {
77
+ await sleep(seconds * 1000, undefined, signal ? { signal } : {});
78
+ },
79
+ };
80
+ /** One model request's HTTP failure, carrying the status that decides whether a retry can help. */
81
+ export class HttpError extends Error {
82
+ status;
83
+ retryAfterMs;
84
+ constructor(status, message, retryAfterMs = null) {
85
+ super(message);
86
+ this.name = 'HttpError';
87
+ this.status = status;
88
+ this.retryAfterMs = retryAfterMs;
89
+ }
90
+ }
91
+ /** The errno and undici codes that mean the request never reached the endpoint. */
92
+ const REFUSED_CODES = new Set([
93
+ 'ECONNREFUSED',
94
+ 'ECONNRESET',
95
+ 'ECONNABORTED',
96
+ 'ENOTFOUND',
97
+ 'EAI_AGAIN',
98
+ 'ETIMEDOUT',
99
+ 'EHOSTUNREACH',
100
+ 'EHOSTDOWN',
101
+ 'ENETUNREACH',
102
+ 'ENETDOWN',
103
+ 'EPIPE',
104
+ 'UND_ERR_CONNECT_TIMEOUT',
105
+ 'UND_ERR_HEADERS_TIMEOUT',
106
+ 'UND_ERR_BODY_TIMEOUT',
107
+ 'UND_ERR_SOCKET',
108
+ 'UND_ERR_CLOSED',
109
+ ]);
110
+ /** The classes both SDKs name a request that never reached the endpoint. */
111
+ const CONNECTION_NAMES = new Set([
112
+ 'APIConnectionError',
113
+ 'APIConnectionTimeoutError',
114
+ 'ConnectTimeoutError',
115
+ 'TimeoutError',
116
+ ]);
117
+ /** The classes that mean somebody stopped the request: a cancel is not a connection to retry. */
118
+ const ABORT_NAMES = new Set(['AbortError', 'APIUserAbortError']);
119
+ /** Error names/codes that mean an upstream rate limiter answered, not a dead socket. */
120
+ const RATE_LIMIT_NAMES = new Set(['RateLimitError', 'RateLimitExceededError']);
121
+ const RATE_LIMIT_CODES = new Set(['rate_limit_exceeded', 'rate_limit_error', 'too_many_requests']);
122
+ /** What an upstream says when it is the concurrency that is spent, not the quota.
123
+ *
124
+ * A 429 is the polite way to say it; the gateways in front of these models also say it on a 400, a
125
+ * 403 or a 503, and the same request would work once a slot frees up. The words are matched
126
+ * case-insensitively against the whole cause chain, so a body the SDK kept in `message`, `body` or
127
+ * `response.data` is read either way. */
128
+ const UPSTREAM_LIMIT_MARKERS = [
129
+ 'concurrency',
130
+ 'concurrent request',
131
+ 'too many request',
132
+ 'too many connection',
133
+ 'rate limit',
134
+ 'rate-limit',
135
+ 'ratelimit',
136
+ 'slow down',
137
+ 'capacity',
138
+ 'overloaded',
139
+ 'resource_exhausted',
140
+ 'resource exhausted',
141
+ 'quota exceeded',
142
+ 'quota_exceeded',
143
+ 'server_busy',
144
+ 'server busy',
145
+ 'try again later',
146
+ // The gateways in front of the MIOFFICE models say it in Chinese.
147
+ '并发',
148
+ '限流',
149
+ '请求过多',
150
+ '稍后重试',
151
+ ];
152
+ /** An error's own name and its class name: the SDKs leave `name` at "Error" and rely on the class. */
153
+ function kindsOf(error) {
154
+ const shape = error;
155
+ const kinds = [];
156
+ if (typeof shape.name === 'string')
157
+ kinds.push(shape.name);
158
+ const own = shape.constructor?.name;
159
+ if (typeof own === 'string')
160
+ kinds.push(own);
161
+ return kinds;
162
+ }
163
+ /** An error and the `cause` chain under it: `fetch` hides why it failed one or two levels down. */
164
+ function chainOf(error) {
165
+ const links = [];
166
+ let current = error;
167
+ for (let depth = 0; depth < 6 && current !== null && typeof current === 'object'; depth += 1) {
168
+ links.push(current);
169
+ current = current.cause;
170
+ }
171
+ return links;
172
+ }
173
+ /** Did somebody cancel this request? Whichever layer wrapped it, the abort is in the chain. */
174
+ export function isAbortFailure(error) {
175
+ return chainOf(error).some((link) => {
176
+ if (kindsOf(link).some((kind) => ABORT_NAMES.has(kind)))
177
+ return true;
178
+ const code = link.code;
179
+ return code === 'ABORT_ERR' || code === 'ABORTED';
180
+ });
181
+ }
182
+ /** The error a cancel becomes, named the way every other abort in the chain is. */
183
+ function abortFailure(signal) {
184
+ const reason = signal.reason;
185
+ if (reason instanceof Error)
186
+ return reason;
187
+ const error = new Error('the request was aborted');
188
+ error.name = 'AbortError';
189
+ return error;
190
+ }
191
+ /** The HTTP status an SDK or a fetch error carries, if it has one. */
192
+ export function statusOf(error) {
193
+ for (const link of chainOf(error)) {
194
+ for (const key of ['status', 'statusCode']) {
195
+ const value = link[key];
196
+ if (typeof value === 'number' && Number.isFinite(value))
197
+ return value;
198
+ }
199
+ const response = link.response;
200
+ if (typeof response?.status === 'number')
201
+ return response.status;
202
+ }
203
+ return null;
204
+ }
205
+ /** The first machine-readable code in the chain (`ECONNRESET`, `rate_limit_exceeded`, …). */
206
+ export function codeOf(error) {
207
+ for (const link of chainOf(error)) {
208
+ const value = link.code;
209
+ if (typeof value === 'string' && value !== '')
210
+ return value;
211
+ }
212
+ return '';
213
+ }
214
+ /** Read one response header without assuming which SDK shape carries it. */
215
+ function headerOf(error, name) {
216
+ const headers = error.headers;
217
+ if (headers instanceof Headers)
218
+ return headers.get(name) ?? '';
219
+ if (headers !== null && typeof headers === 'object') {
220
+ const value = headers[name];
221
+ if (typeof value === 'string')
222
+ return value;
223
+ }
224
+ return '';
225
+ }
226
+ /** Parse `Retry-After` (seconds or HTTP date) into milliseconds. */
227
+ export function retryAfterMsFromHeader(raw) {
228
+ if (raw === null || raw.trim() === '')
229
+ return null;
230
+ const text = raw.trim();
231
+ const seconds = Number(text);
232
+ if (Number.isFinite(seconds) && seconds >= 0)
233
+ return Math.min(seconds * 1000, 300_000);
234
+ const at = Date.parse(text);
235
+ if (!Number.isNaN(at))
236
+ return Math.min(Math.max(at - Date.now(), 0), 300_000);
237
+ return null;
238
+ }
239
+ /** Parse `Retry-After` off an error or anything in its cause chain. */
240
+ export function retryAfterMsOf(error) {
241
+ for (const link of chainOf(error)) {
242
+ // `HttpError` keeps the parsed header in a typed field; an SDK error keeps it in `headers`.
243
+ const own = link.retryAfterMs;
244
+ if (typeof own === 'number' && Number.isFinite(own) && own >= 0) {
245
+ return Math.min(own, 300_000);
246
+ }
247
+ for (const name of ['retry-after', 'retryAfter']) {
248
+ const parsed = retryAfterMsFromHeader(headerOf(link, name));
249
+ if (parsed !== null)
250
+ return parsed;
251
+ }
252
+ }
253
+ return null;
254
+ }
255
+ /** One link's own text: the message, the code, its type, and whatever body came with it. */
256
+ function textOfValue(value) {
257
+ if (typeof value === 'string')
258
+ return value;
259
+ if (value === null || value === undefined)
260
+ return '';
261
+ if (typeof value === 'object') {
262
+ try {
263
+ return JSON.stringify(value) ?? '';
264
+ }
265
+ catch {
266
+ return '';
267
+ }
268
+ }
269
+ return String(value);
270
+ }
271
+ /** Everything this link says, so a marker is found in `message`, `code`, `body` or `response.data`.
272
+ * An SDK error keeps the endpoint's own words in one of those, and which one differs per SDK. */
273
+ function textOfLink(link) {
274
+ const parts = [];
275
+ for (const key of ['message', 'code', 'type', 'body', 'detail']) {
276
+ const text = textOfValue(link[key]);
277
+ if (text !== '')
278
+ parts.push(text);
279
+ }
280
+ const response = link.response;
281
+ if (response !== null && typeof response === 'object') {
282
+ for (const key of ['body', 'data', 'text']) {
283
+ const text = textOfValue(response[key]);
284
+ if (text !== '')
285
+ parts.push(text);
286
+ }
287
+ }
288
+ return parts.join(' ');
289
+ }
290
+ /** The whole chain as one lowercase string: markers are matched without caring about case. */
291
+ function textOfChain(error) {
292
+ return chainOf(error).map(textOfLink).join(' ').toLowerCase();
293
+ }
294
+ /** Did the endpoint answer "you have no slot right now"?
295
+ *
296
+ * A spent concurrency slot, a rate limiter, an overloaded gateway: the status is the polite part and
297
+ * the body is the truth. A 429 says it outright, and a 400, 403 or 503 carrying the words means the
298
+ * same thing — the same request works once a slot frees up. */
299
+ export function isUpstreamLimitFailure(error) {
300
+ if (statusOf(error) === 429)
301
+ return true;
302
+ if (RATE_LIMIT_CODES.has(codeOf(error)))
303
+ return true;
304
+ if (chainOf(error).some((link) => kindsOf(link).some((kind) => RATE_LIMIT_NAMES.has(kind))))
305
+ return true;
306
+ const text = textOfChain(error);
307
+ return UPSTREAM_LIMIT_MARKERS.some((marker) => text.includes(marker));
308
+ }
309
+ /** The name the callers, the logs and the kinds already use: a concurrency answer is a rate limit. */
310
+ export function isRateLimitFailure(error) {
311
+ return isUpstreamLimitFailure(error);
312
+ }
313
+ /** Did the endpoint answer, but with a server-side failure? */
314
+ export function isServerFailure(error) {
315
+ const status = statusOf(error);
316
+ return status !== null && status >= 500;
317
+ }
318
+ /** Did the request fail to reach the endpoint at all? */
319
+ export function isConnectionFailure(error) {
320
+ if (error instanceof HttpError || isAbortFailure(error))
321
+ return false;
322
+ return chainOf(error).some((link) => {
323
+ if (link instanceof HttpError)
324
+ return false;
325
+ if (kindsOf(link).some((kind) => CONNECTION_NAMES.has(kind)))
326
+ return true;
327
+ const code = link.code;
328
+ if (typeof code === 'string' && REFUSED_CODES.has(code))
329
+ return true;
330
+ if (link instanceof TypeError) {
331
+ const message = link.message.toLowerCase();
332
+ return (message.includes('fetch failed') ||
333
+ message.includes('network') ||
334
+ message.includes('connection') ||
335
+ message.includes('terminated'));
336
+ }
337
+ return false;
338
+ });
339
+ }
340
+ /** The broad class of the final failure, so callers and logs can tell a dead socket from a 429. */
341
+ export function failureKind(error) {
342
+ if (isAbortFailure(error))
343
+ return 'aborted';
344
+ if (isRateLimitFailure(error))
345
+ return 'rate_limit';
346
+ if (isServerFailure(error))
347
+ return 'server';
348
+ if (statusOf(error) !== null)
349
+ return 'http';
350
+ if (isConnectionFailure(error))
351
+ return 'connection';
352
+ return 'unknown';
353
+ }
354
+ /** Is this failure one a second attempt can fix?
355
+ *
356
+ * Every HTTP failure is: a status that is not 2xx reached this function because an attempt failed,
357
+ * and a gateway, a proxy or a queue in front of the model is free to answer 400, 401, 403, 404 or
358
+ * 409 for a reason that goes away by itself. So the answer is yes for all of them, and a caller
359
+ * that knows its endpoint better says otherwise through `excludedStatuses`
360
+ * (`NODE_AGENT_MODEL_NO_RETRY_STATUSES`) — in the open, never by the base class quietly deciding
361
+ * that a retry is pointless. Two things are never retried: a request somebody cancelled, and a
362
+ * failure with no status and no dead socket behind it (a malformed answer, which a retry would
363
+ * reproduce). A wait the endpoint asked for — a 429 or an upstream concurrency body — is always
364
+ * retried, whatever status carried it and whatever was excluded. */
365
+ export function retryable(error, policy = retryPolicy) {
366
+ if (isAbortFailure(error))
367
+ return false;
368
+ if (isUpstreamLimitFailure(error))
369
+ return true;
370
+ const status = statusOf(error);
371
+ if (status === null)
372
+ return isConnectionFailure(error);
373
+ return !policy.excludedStatuses.has(status);
374
+ }
375
+ /** The type name a person can search for, even when the SDK left `name` as "Error". */
376
+ function typeOf(error) {
377
+ if (error === null || typeof error !== 'object')
378
+ return typeof error;
379
+ const own = error.constructor
380
+ ?.name;
381
+ const named = error.name;
382
+ return typeof own === 'string' && own !== ''
383
+ ? own
384
+ : typeof named === 'string' && named !== ''
385
+ ? named
386
+ : 'Error';
387
+ }
388
+ /** A gateway sometimes answers one error body inside another: the real sentence, and its code, sit in
389
+ * `param` as JSON while `message` says only "Request Error". That buried sentence is the only part a
390
+ * person reading the failure can act on, so it is read back out and shown beside the type. */
391
+ function buriedDetail(error) {
392
+ const param = error.param;
393
+ if (typeof param !== 'string' || param.trim().startsWith('{') === false)
394
+ return '';
395
+ try {
396
+ const parsed = JSON.parse(param);
397
+ const inner = parsed?.error ?? {};
398
+ const message = typeof inner.message === 'string' ? inner.message.trim() : '';
399
+ const code = typeof inner.code === 'string' ? inner.code.trim() : '';
400
+ if (message === '')
401
+ return '';
402
+ return code === '' ? message : `${message} (${code})`;
403
+ }
404
+ catch {
405
+ return '';
406
+ }
407
+ }
408
+ /** The id the endpoint logged this request under, when the SDK kept one: what an operator needs to
409
+ * find the same request on the gateway's side. */
410
+ function requestIdOf(error) {
411
+ for (const key of ['requestID', 'request_id']) {
412
+ const value = error[key];
413
+ if (typeof value === 'string' && value !== '')
414
+ return value;
415
+ }
416
+ return '';
417
+ }
418
+ /** One link of the cause chain, with everything a caller would need to identify it. */
419
+ function describeLink(error) {
420
+ const type = typeOf(error);
421
+ const message = typeof error.message === 'string'
422
+ ? error.message.trim().replace(/\.$/, '')
423
+ : '';
424
+ const buried = buriedDetail(error);
425
+ const meta = [];
426
+ const code = error.code;
427
+ if (typeof code === 'string' && code !== '')
428
+ meta.push(`code=${code}`);
429
+ const status = error.status;
430
+ if (typeof status === 'number')
431
+ meta.push(`status=${status}`);
432
+ const requestId = requestIdOf(error);
433
+ if (requestId !== '')
434
+ meta.push(`request_id=${requestId}`);
435
+ const retryAfter = retryAfterMsOf(error);
436
+ if (retryAfter !== null)
437
+ meta.push(`retry_after_ms=${retryAfter}`);
438
+ return `${type}${message === '' ? '' : `: ${message}`}${buried === '' ? '' : ` (${buried})`}${meta.length === 0 ? '' : ` [${meta.join(', ')}]`}`;
439
+ }
440
+ /** The SDK says `Connection error.` and hides the reason in `cause`; show the whole chain, with every
441
+ * type and machine-readable field, instead of one bare sentence. */
442
+ export function failureReason(error) {
443
+ const parts = [];
444
+ for (const link of chainOf(error)) {
445
+ const text = describeLink(link);
446
+ if (text !== '' && !parts.includes(text))
447
+ parts.push(text);
448
+ }
449
+ return parts.join(' -> ') || 'no answer';
450
+ }
451
+ /** The host inside a base URL, or the wire's own when the row names none. */
452
+ export function endpointHost(baseUrl, fallback) {
453
+ const raw = (baseUrl ?? '').trim() || fallback;
454
+ try {
455
+ return new URL(raw).host;
456
+ }
457
+ catch {
458
+ const withoutScheme = raw.replace(/^[a-z][a-z0-9+.-]*:\/\//i, '');
459
+ return withoutScheme.split('/')[0] || raw;
460
+ }
461
+ }
462
+ /** What a caller reads when the attempts are spent: provider, host, attempts, final kind, and the
463
+ * complete cause chain (type, message, code, status, Retry-After). */
464
+ export function failureMessage(endpoint, attempts, cause, streamStarted = false) {
465
+ const tries = attempts === 1 ? '1 attempt' : `${attempts} attempts`;
466
+ const kind = failureKind(cause);
467
+ const verb = streamStarted
468
+ ? 'failed while streaming from'
469
+ : kind === 'connection'
470
+ ? 'cannot reach'
471
+ : 'failed at';
472
+ const status = statusOf(cause);
473
+ const meta = [`kind=${kind}`];
474
+ if (status !== null)
475
+ meta.push(`status=${status}`);
476
+ const code = codeOf(cause);
477
+ if (code !== '')
478
+ meta.push(`code=${code}`);
479
+ return `provider "${endpoint.name}" ${verb} the model endpoint ${endpoint.host} after ${tries}: ${failureReason(cause)} [${meta.join(', ')}]`;
480
+ }
481
+ /** A model request that failed after the provider's retry policy was spent. It keeps the original
482
+ * error as `cause` and exposes the fields a caller needs without parsing the sentence. */
483
+ export class ProviderCallError extends Error {
484
+ provider;
485
+ host;
486
+ attempts;
487
+ kind;
488
+ status;
489
+ code;
490
+ causeType;
491
+ streamStarted;
492
+ constructor(endpoint, attempts, cause, streamStarted = false) {
493
+ super(failureMessage(endpoint, attempts, cause, streamStarted), { cause });
494
+ this.name = 'ProviderCallError';
495
+ this.provider = endpoint.name;
496
+ this.host = endpoint.host;
497
+ this.attempts = attempts;
498
+ this.kind = failureKind(cause);
499
+ this.status = statusOf(cause);
500
+ this.code = codeOf(cause);
501
+ this.causeType = typeOf(cause);
502
+ this.streamStarted = streamStarted;
503
+ }
504
+ }
505
+ /** Kept as the connection-specific name so callers that already distinguish an unreachable host
506
+ * keep working; it now carries the same full detail as every other ProviderCallError. */
507
+ export class UnreachableError extends ProviderCallError {
508
+ constructor(endpoint, attempts, cause, streamStarted = false) {
509
+ super(endpoint, attempts, cause, streamStarted);
510
+ this.name = 'UnreachableError';
511
+ }
512
+ }
513
+ /** The error to raise once the attempts are spent. Every failure is wrapped: a 429, a 500 and a
514
+ * malformed answer all deserve the provider, host, attempt count and original type. */
515
+ export function providerFailure(error, endpoint, attempts, streamStarted = false) {
516
+ if (failureKind(error) === 'connection')
517
+ return new UnreachableError(endpoint, attempts, error, streamStarted);
518
+ return new ProviderCallError(endpoint, attempts, error, streamStarted);
519
+ }
520
+ /** Wait out the pause before the next attempt: the endpoint's `Retry-After` when it named one, the
521
+ * policy's doubled and jittered backoff otherwise. A cancel ends the wait instead of sleeping on. */
522
+ export async function waitBeforeRetrying(attempt, error, policy = retryPolicy, signal) {
523
+ const retryAfter = retryAfterMsOf(error);
524
+ const wait = retryAfter !== null ? retryAfter / 1000 : retryDelaySeconds(attempt, policy);
525
+ const basis = retryAfter !== null ? 'the endpoint asked for it' : 'backoff';
526
+ console.error(`model request failed (${failureReason(error)}); retrying in ${wait}s (${basis}; attempt ${attempt + 1} of ${policy.attempts})`);
527
+ await retryPause.for(wait, signal);
528
+ }
529
+ /** One optional string field of a provider row. */
530
+ export function optionalString(data, key) {
531
+ const value = data[key];
532
+ if (value !== undefined && value !== null && typeof value !== 'string')
533
+ throw new Error(`provider ${key} must be a string or null`);
534
+ return value === null || value === undefined ? null : value;
535
+ }
536
+ /** The row's optional thinking effort: an empty value means the endpoint's default. */
537
+ export function thinkingEffort(data) {
538
+ const value = optionalString(data, 'thinking_effort');
539
+ return value === null ? null : value.trim() || null;
540
+ }
541
+ export function timeoutOf(data, label) {
542
+ const value = data.timeout;
543
+ if (value !== undefined && value !== null && (typeof value !== 'number' || Number.isNaN(value)))
544
+ throw new Error(`${label} provider timeout must be a number or null`);
545
+ return value === undefined || value === null ? null : value;
546
+ }
547
+ export function missingProviderMessage(name, known) {
548
+ const others = [...known].sort().join(', ');
549
+ const suffix = others ? ` (configured: ${others})` : '';
550
+ return `no provider "${name}" yet — open the provider page and add one${suffix}`;
551
+ }
552
+ export function blankProviderMessage() {
553
+ return 'this provider is not filled in yet — open the provider page and add its model and API key';
554
+ }
555
+ /** Resolve with the work, or reject after `ms` rather than waiting forever on a request. */
556
+ export async function within(work, ms, what) {
557
+ let timer;
558
+ const deadline = new Promise((_resolve, reject) => {
559
+ timer = setTimeout(() => reject(new Error(`${what} did not answer within ${ms} ms`)), ms);
560
+ timer.unref?.();
561
+ });
562
+ try {
563
+ return await Promise.race([work, deadline]);
564
+ }
565
+ finally {
566
+ if (timer !== undefined)
567
+ clearTimeout(timer);
568
+ }
569
+ }
570
+ /** JSON-compatible plain data, with null object fields dropped like model_dump(exclude_none). */
571
+ export function plain(value) {
572
+ if (Array.isArray(value))
573
+ return value.map((item) => plain(item));
574
+ if (value !== null && typeof value === 'object') {
575
+ const result = {};
576
+ for (const [key, item] of Object.entries(value)) {
577
+ if (item === undefined || item === null)
578
+ continue;
579
+ result[key] = plain(item);
580
+ }
581
+ return result;
582
+ }
583
+ return value;
584
+ }
585
+ export function messageOf(value) {
586
+ const message = plain(value);
587
+ if (message === null || typeof message !== 'object' || Array.isArray(message))
588
+ throw new Error(`provider returned an invalid message: ${typeof value}`);
589
+ return message;
590
+ }
591
+ export function usageFromOpenAI(value) {
592
+ if (value === null || value === undefined)
593
+ return null;
594
+ const u = value;
595
+ return {
596
+ prompt_tokens: Number(u.prompt_tokens ?? 0),
597
+ completion_tokens: Number(u.completion_tokens ?? 0),
598
+ total_tokens: Number(u.total_tokens ?? 0),
599
+ };
600
+ }
601
+ /** POST a JSON body and return its JSON answer, raising an HttpError for a non-2xx status. */
602
+ export async function postJson(fetcher, url, headers, body, signal) {
603
+ const response = await fetcher(url, {
604
+ method: 'POST',
605
+ headers: { 'content-type': 'application/json', ...headers },
606
+ body: JSON.stringify(body),
607
+ signal,
608
+ });
609
+ if (!response.ok) {
610
+ const text = await response.text();
611
+ throw new HttpError(response.status, `HTTP ${response.status}: ${text}`, retryAfterMsFromHeader(response.headers.get('retry-after')));
612
+ }
613
+ return (await response.json());
614
+ }
615
+ /** Read a server-sent-event body and yield each JSON `data:` payload. */
616
+ export async function* sseEvents(response) {
617
+ if (!response.ok) {
618
+ const text = await response.text();
619
+ throw new HttpError(response.status, `HTTP ${response.status}: ${text}`, retryAfterMsFromHeader(response.headers.get('retry-after')));
620
+ }
621
+ if (response.body === null)
622
+ throw new Error('the model stream had no body');
623
+ const reader = response.body.getReader();
624
+ const decoder = new TextDecoder();
625
+ let buffer = '';
626
+ let data = [];
627
+ try {
628
+ for (;;) {
629
+ const { value, done } = await reader.read();
630
+ buffer += decoder.decode(value ?? new Uint8Array(), { stream: !done });
631
+ let boundary = buffer.indexOf('\n');
632
+ while (boundary >= 0) {
633
+ let line = buffer.slice(0, boundary);
634
+ buffer = buffer.slice(boundary + 1);
635
+ if (line.endsWith('\r'))
636
+ line = line.slice(0, -1);
637
+ if (line === '') {
638
+ if (data.length > 0) {
639
+ const payload = data.join('\n');
640
+ data = [];
641
+ if (payload !== '[DONE]')
642
+ yield JSON.parse(payload);
643
+ }
644
+ }
645
+ else if (line.startsWith('data:')) {
646
+ data.push(line.slice(5).trimStart());
647
+ }
648
+ boundary = buffer.indexOf('\n');
649
+ }
650
+ if (done)
651
+ break;
652
+ }
653
+ if (data.length > 0) {
654
+ const payload = data.join('\n');
655
+ if (payload !== '[DONE]')
656
+ yield JSON.parse(payload);
657
+ }
658
+ }
659
+ finally {
660
+ await reader.cancel().catch(() => { });
661
+ }
662
+ }
663
+ /** Retry one request under the policy: the one loop every protocol goes through.
664
+ *
665
+ * This and `retryStream` are the whole retry story of the package. A provider says how to make one
666
+ * attempt and nothing else — which statuses are retried, how long to wait, when to give up and how
667
+ * the failure is wrapped are decided here, once. */
668
+ export async function retryRequests(work, endpoint, options = {}) {
669
+ const policy = options.policy ?? retryPolicy;
670
+ let attempt = 0;
671
+ for (;;) {
672
+ // A cancel that landed while this request waited must not send another one.
673
+ if (options.signal?.aborted)
674
+ throw providerFailure(abortFailure(options.signal), endpoint, Math.max(attempt, 1));
675
+ attempt += 1;
676
+ try {
677
+ return await work();
678
+ }
679
+ catch (error) {
680
+ if (attempt >= policy.attempts || !retryable(error, policy))
681
+ throw providerFailure(error, endpoint, attempt);
682
+ try {
683
+ await waitBeforeRetrying(attempt, error, policy, options.signal);
684
+ }
685
+ catch (stopped) {
686
+ // The caller cancelled while this request was waiting: report the cancel, not the wait.
687
+ throw providerFailure(stopped, endpoint, attempt);
688
+ }
689
+ }
690
+ }
691
+ }
692
+ /** Retry a stream only until its first chunk; a retry after that would repeat what was read. */
693
+ export async function* retryStream(open, endpoint, options = {}) {
694
+ const policy = options.policy ?? retryPolicy;
695
+ let emitted = false;
696
+ let attempt = 0;
697
+ for (;;) {
698
+ if (options.signal?.aborted)
699
+ throw providerFailure(abortFailure(options.signal), endpoint, Math.max(attempt, 1), emitted);
700
+ attempt += 1;
701
+ try {
702
+ for await (const event of open()) {
703
+ emitted = true;
704
+ yield event;
705
+ }
706
+ return;
707
+ }
708
+ catch (error) {
709
+ if (emitted || attempt >= policy.attempts || !retryable(error, policy))
710
+ throw providerFailure(error, endpoint, attempt, emitted);
711
+ try {
712
+ await waitBeforeRetrying(attempt, error, policy, options.signal);
713
+ }
714
+ catch (stopped) {
715
+ throw providerFailure(stopped, endpoint, attempt, emitted);
716
+ }
717
+ }
718
+ }
719
+ }
720
+ /** The base every protocol extends — the `BaseProvider` the retry policy is written for.
721
+ *
722
+ * A protocol implements `chat` and `chatStream` as one attempt each and hands the attempt over
723
+ * through `attempt` / `attemptStream`. The retry itself — which failures are retried, the wait (backoff,
724
+ * jitter, `Retry-After`), the attempt ceiling, the abort, the wrapping into `ProviderCallError` —
725
+ * lives here and only here, so the three wires cannot drift apart. */
726
+ export class Provider {
727
+ /** The row this provider serves, set by whoever built it: a failure names the row, not the wire. */
728
+ name = '';
729
+ /** The retry policy this row runs under; the module's own unless a caller replaced it. */
730
+ policy = retryPolicy;
731
+ endpoint() {
732
+ return { name: this.name || String(this.dump().type ?? 'provider'), host: this.host };
733
+ }
734
+ /** Run one attempt's request under the policy, and wrap the final failure once it is spent. */
735
+ attempt(work, signal) {
736
+ return retryRequests(work, this.endpoint(), { policy: this.policy, signal });
737
+ }
738
+ /** Run one attempt's stream under the policy: retried until the first chunk, never after it. */
739
+ attemptStream(open, signal) {
740
+ return retryStream(open, this.endpoint(), { policy: this.policy, signal });
741
+ }
742
+ async close() { }
743
+ }
744
+ /** The OpenAI chat-completions provider. */
745
+ export class OpenAIProvider extends Provider {
746
+ apiKey;
747
+ organization;
748
+ modelName;
749
+ baseUrl;
750
+ timeout;
751
+ effort;
752
+ fetcher;
753
+ client;
754
+ host;
755
+ static build(data, fetcher) {
756
+ return new OpenAIProvider({
757
+ apiKey: optionalString(data, 'api_key'),
758
+ organization: optionalString(data, 'organization'),
759
+ modelName: optionalString(data, 'model_name') ?? '',
760
+ baseUrl: optionalString(data, 'base_url'),
761
+ timeout: timeoutOf(data, 'OpenAI'),
762
+ effort: thinkingEffort(data),
763
+ fetcher,
764
+ });
765
+ }
766
+ constructor(options) {
767
+ super();
768
+ this.apiKey = options.apiKey ?? null;
769
+ this.organization = options.organization ?? null;
770
+ this.modelName = options.modelName ?? '';
771
+ this.baseUrl = options.baseUrl ?? null;
772
+ this.timeout = options.timeout ?? null;
773
+ this.effort = options.effort ?? null;
774
+ this.fetcher = options.fetcher;
775
+ this.host = endpointHost(this.baseUrl, OPENAI_BASE_URL);
776
+ this.client = this.apiKey
777
+ ? new OpenAI({
778
+ apiKey: this.apiKey,
779
+ ...(this.organization ? { organization: this.organization } : {}),
780
+ ...(this.baseUrl ? { baseURL: this.baseUrl } : {}),
781
+ ...(this.timeout !== null ? { timeout: this.timeout * 1000 } : {}),
782
+ maxRetries: 0,
783
+ fetch: this.fetcher,
784
+ })
785
+ : null;
786
+ }
787
+ dump() {
788
+ return {
789
+ type: 'openai',
790
+ api_key: this.apiKey,
791
+ organization: this.organization,
792
+ model_name: this.modelName,
793
+ base_url: this.baseUrl,
794
+ timeout: this.timeout,
795
+ thinking_effort: this.effort,
796
+ };
797
+ }
798
+ /** One transcript line as the endpoint reads it. Split out so a subclass can speak a wire whose
799
+ * house rules differ from the generic one (DeepSeek, for instance, insists on a field a plain
800
+ * chat-completions endpoint never heard of). */
801
+ wireMessage(message) {
802
+ const row = { ...message };
803
+ delete row.usage;
804
+ delete row.at;
805
+ delete row.took_ms;
806
+ return row;
807
+ }
808
+ body(messages, tools, limit) {
809
+ if (this.modelName === '' || this.apiKey === null)
810
+ throw new Error(blankProviderMessage());
811
+ const body = {
812
+ model: this.modelName,
813
+ messages: messages.map((message) => this.wireMessage(message)),
814
+ };
815
+ if (tools && tools.length > 0)
816
+ body.tools = tools;
817
+ if (limit !== null && limit !== undefined)
818
+ body.max_completion_tokens = limit;
819
+ if (this.effort)
820
+ body.reasoning_effort = this.effort;
821
+ return body;
822
+ }
823
+ async chat(messages, tools, maxCompletionTokens, _previousResponseId) {
824
+ const body = this.body(messages, tools, maxCompletionTokens);
825
+ if (this.client === null)
826
+ throw new Error(blankProviderMessage());
827
+ const client = this.client;
828
+ const response = await this.attempt(() => client.chat.completions.create(body));
829
+ const payload = JSON.parse(JSON.stringify(response));
830
+ const choices = payload.choices;
831
+ const message = messageOf(choices?.[0]?.message);
832
+ return {
833
+ message,
834
+ usage: usageFromOpenAI(payload.usage),
835
+ previous_response_id: null,
836
+ };
837
+ }
838
+ async *chatStream(messages, tools, maxCompletionTokens, _previousResponseId, signal) {
839
+ const body = {
840
+ ...this.body(messages, tools, maxCompletionTokens),
841
+ stream: true,
842
+ stream_options: { include_usage: true },
843
+ };
844
+ if (this.client === null)
845
+ throw new Error(blankProviderMessage());
846
+ const client = this.client;
847
+ yield* this.attemptStream(async function* () {
848
+ const stream = await client.chat.completions.create(body, { signal });
849
+ try {
850
+ for await (const chunk of stream) {
851
+ const payload = JSON.parse(JSON.stringify(chunk));
852
+ const usage = usageFromOpenAI(payload.usage);
853
+ const choices = payload.choices;
854
+ if (!choices || choices.length === 0) {
855
+ yield { delta: {}, usage, previous_response_id: null };
856
+ continue;
857
+ }
858
+ for (const choice of choices) {
859
+ yield { delta: messageOf(choice.delta), usage, previous_response_id: null };
860
+ }
861
+ }
862
+ }
863
+ finally {
864
+ stream.controller?.abort();
865
+ }
866
+ }, signal);
867
+ }
868
+ }
869
+ /** The same class under the name the retry policy talks about. */
870
+ export { Provider as BaseProvider };
871
+ //# sourceMappingURL=base.js.map