@tungoai/sdk 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/LICENSE +21 -0
  3. package/README.kk.md +327 -0
  4. package/README.md +346 -2
  5. package/README.ru.md +327 -0
  6. package/dist/cjs/chat.d.ts +85 -0
  7. package/dist/cjs/chat.js +152 -0
  8. package/dist/cjs/client.d.ts +117 -0
  9. package/dist/cjs/client.js +225 -0
  10. package/dist/cjs/core.d.ts +217 -0
  11. package/dist/cjs/core.js +779 -0
  12. package/dist/cjs/errors.d.ts +237 -0
  13. package/dist/cjs/errors.js +446 -0
  14. package/dist/cjs/generated/resources.d.ts +1149 -0
  15. package/dist/cjs/generated/resources.js +1145 -0
  16. package/dist/cjs/generated/types.d.ts +5435 -0
  17. package/dist/cjs/generated/types.js +11 -0
  18. package/dist/cjs/index.d.ts +12 -0
  19. package/dist/cjs/index.js +81 -0
  20. package/dist/cjs/json.d.ts +16 -0
  21. package/dist/cjs/json.js +137 -0
  22. package/dist/cjs/money.d.ts +32 -0
  23. package/dist/cjs/money.js +141 -0
  24. package/dist/cjs/package.json +1 -0
  25. package/dist/cjs/pagination.d.ts +47 -0
  26. package/dist/cjs/pagination.js +114 -0
  27. package/dist/cjs/streaming.d.ts +76 -0
  28. package/dist/cjs/streaming.js +291 -0
  29. package/dist/cjs/version.d.ts +2 -0
  30. package/dist/cjs/version.js +6 -0
  31. package/dist/cjs/webhooks.d.ts +79 -0
  32. package/dist/cjs/webhooks.js +262 -0
  33. package/dist/esm/chat.d.ts +85 -0
  34. package/dist/esm/chat.js +144 -0
  35. package/dist/esm/client.d.ts +117 -0
  36. package/dist/esm/client.js +221 -0
  37. package/dist/esm/core.d.ts +217 -0
  38. package/dist/esm/core.js +763 -0
  39. package/dist/esm/errors.d.ts +237 -0
  40. package/dist/esm/errors.js +416 -0
  41. package/dist/esm/generated/resources.d.ts +1149 -0
  42. package/dist/esm/generated/resources.js +1129 -0
  43. package/dist/esm/generated/types.d.ts +5435 -0
  44. package/dist/esm/generated/types.js +10 -0
  45. package/dist/esm/index.d.ts +12 -0
  46. package/dist/esm/index.js +11 -0
  47. package/dist/esm/json.d.ts +16 -0
  48. package/dist/esm/json.js +132 -0
  49. package/dist/esm/money.d.ts +32 -0
  50. package/dist/esm/money.js +137 -0
  51. package/dist/esm/package.json +1 -0
  52. package/dist/esm/pagination.d.ts +47 -0
  53. package/dist/esm/pagination.js +108 -0
  54. package/dist/esm/streaming.d.ts +76 -0
  55. package/dist/esm/streaming.js +285 -0
  56. package/dist/esm/version.d.ts +2 -0
  57. package/dist/esm/version.js +3 -0
  58. package/dist/esm/webhooks.d.ts +79 -0
  59. package/dist/esm/webhooks.js +253 -0
  60. package/package.json +67 -4
@@ -0,0 +1,763 @@
1
+ // Code generated by tungo-sdkgen. DO NOT EDIT.
2
+ import { AbortError, APIError, ConfigError, ConnectionError, DecodeError, TimeoutError, TungoError, ValidationError, apiErrorFromResponse, parseRateLimit, } from './errors.js';
3
+ import { parseJSON, stringifyJSON } from './json.js';
4
+ import { VERSION } from './version.js';
5
+ /** The production API host. */
6
+ export const DEFAULT_BASE_URL = 'https://api.tungo.kz';
7
+ /** Default timeout of an ordinary request, in milliseconds. */
8
+ export const DEFAULT_TIMEOUT = 60_000;
9
+ /** Default timeout of a non-streaming chat turn, in milliseconds. */
10
+ export const DEFAULT_LONG_RUNNING_TIMEOUT = 600_000;
11
+ /** Default number of retries (so 3 attempts in total). */
12
+ export const DEFAULT_MAX_RETRIES = 2;
13
+ /** Default idle timeout of a stream, in milliseconds. */
14
+ export const DEFAULT_STREAM_IDLE_TIMEOUT = 120_000;
15
+ /** A server-requested delay above this many seconds is not slept: the error is raised instead. */
16
+ export const MAX_RETRY_AFTER_SECONDS = 60;
17
+ /**
18
+ * The longest delay a platform timer supports, in milliseconds (2^31 - 1, about 24.8 days).
19
+ * A timeout above it, `Infinity` included, means "no time limit": no timer is started.
20
+ */
21
+ export const MAX_TIMER_MS = 2_147_483_647;
22
+ const USER_AGENT = 'tungo-sdk-typescript/' + VERSION;
23
+ /** Reads an environment variable on Node.js, Bun and Deno; undefined elsewhere or when empty. */
24
+ /** Whether a stream call was answered with a stored result replayed by Idempotency-Key. */
25
+ function isReplayedJSON(headers) {
26
+ const mediaType = (headers.get('content-type') ?? '').split(';')[0] ?? '';
27
+ return mediaType.trim().toLowerCase() === 'application/json' && (headers.get('idempotent-replayed') ?? '').trim().toLowerCase() === 'true';
28
+ }
29
+ function isObject(value) {
30
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
31
+ }
32
+ /**
33
+ * Turns a replayed ChatTurnResult into the event stream of the turn it stands for: text (the
34
+ * answer), proposal, question, citation, error, choice and next events, then done. The dialog id and
35
+ * the turn number, which a replay carries only in the body, become the X-Dialog-Id and X-Turn-No
36
+ * headers when they are missing: `headers` are those of the response with them, the other headers
37
+ * (Idempotent-Replayed among them) unchanged. Returns null when the body is not a chat turn result.
38
+ */
39
+ function replayAsEventStream(response, text, requestId) {
40
+ let result;
41
+ try {
42
+ result = parseJSON(text);
43
+ }
44
+ catch {
45
+ return null;
46
+ }
47
+ if (!isObject(result))
48
+ return null;
49
+ const dialogId = result['dialog_id'];
50
+ if (typeof dialogId !== 'string')
51
+ return null;
52
+ const headers = new Headers(response.headers);
53
+ if ((headers.get('x-dialog-id') ?? '') === '')
54
+ headers.set('x-dialog-id', dialogId);
55
+ const turnNo = result['turn_no'];
56
+ if ((headers.get('x-turn-no') ?? '') === '' && (typeof turnNo === 'number' || typeof turnNo === 'bigint'))
57
+ headers.set('x-turn-no', String(turnNo));
58
+ const entries = (key) => {
59
+ const list = result[key];
60
+ return Array.isArray(list) ? list.filter(isObject) : [];
61
+ };
62
+ let body = '';
63
+ const emit = (type, event) => {
64
+ body += 'event: ' + type + '\ndata: ' + stringifyJSON({ ...event, type }) + '\n\n';
65
+ };
66
+ const answerValue = result['answer'];
67
+ const answer = typeof answerValue === 'string' ? answerValue : '';
68
+ if (answer !== '')
69
+ emit('text', { delta: answer });
70
+ for (const { id, ...rest } of entries('proposals'))
71
+ emit('proposal', { ...rest, proposal_id: id });
72
+ for (const question of entries('questions'))
73
+ emit('question', question);
74
+ for (const citation of entries('citations'))
75
+ emit('citation', citation);
76
+ for (const error of entries('errors'))
77
+ emit('error', { error, request_id: requestId });
78
+ const done = { answer };
79
+ const stopReason = result['stop_reason'];
80
+ if (typeof stopReason === 'string')
81
+ done['stop_reason'] = stopReason;
82
+ const usageValue = result['usage'];
83
+ if (isObject(usageValue)) {
84
+ const { cost_tiyn: cost, ...usage } = usageValue;
85
+ done['usage'] = usage;
86
+ if (cost !== undefined)
87
+ done['cost_tiyn'] = cost;
88
+ }
89
+ const pending = result['pending_question'];
90
+ if (isObject(pending)) {
91
+ emit('choice', pending);
92
+ done['choice_id'] = pending['choice_id'];
93
+ }
94
+ // A live turn ends its finished answer with next right before done; the stored result keeps it
95
+ // as followups and next_action.
96
+ const followups = Array.isArray(result['followups']) ? result['followups'] : [];
97
+ const action = result['next_action'];
98
+ if (followups.length > 0 || isObject(action))
99
+ emit('next', { followups, action: isObject(action) ? action : null });
100
+ emit('done', done);
101
+ const streamHeaders = new Headers(headers);
102
+ streamHeaders.set('content-type', 'text/event-stream');
103
+ return { response: new Response(body, { status: response.status, headers: streamHeaders }), headers };
104
+ }
105
+ export function readEnv(name) {
106
+ try {
107
+ const scope = globalThis;
108
+ const fromProcess = scope.process?.env?.[name];
109
+ if (typeof fromProcess === 'string' && fromProcess !== '')
110
+ return fromProcess;
111
+ const fromDeno = scope.Deno?.env?.get?.(name);
112
+ if (typeof fromDeno === 'string' && fromDeno !== '')
113
+ return fromDeno;
114
+ }
115
+ catch {
116
+ // No permission to read the environment.
117
+ }
118
+ return undefined;
119
+ }
120
+ /**
121
+ * The `idempotency_key` field of a JSON object body (approving a proposal documents it as the same
122
+ * as the header), trimmed like the API trims it. The API prefers the header over the field, so a
123
+ * generated header would make the caller's own key useless. A key that cannot travel in a header
124
+ * (outside printable ASCII) is ignored here.
125
+ */
126
+ function bodyIdempotencyKey(body) {
127
+ if (typeof body !== 'object' || body === null || Array.isArray(body))
128
+ return undefined;
129
+ const value = body['idempotency_key'];
130
+ if (typeof value !== 'string')
131
+ return undefined;
132
+ const key = value.trim();
133
+ return key !== '' && /^[\x20-\x7e]+$/.test(key) ? key : undefined;
134
+ }
135
+ /** A random RFC 4122 version 4 UUID from the platform CSPRNG. */
136
+ export function uuid4() {
137
+ const bytes = new Uint8Array(16);
138
+ crypto.getRandomValues(bytes);
139
+ bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;
140
+ bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
141
+ let hex = '';
142
+ for (const b of bytes)
143
+ hex += b.toString(16).padStart(2, '0');
144
+ return hex.slice(0, 8) + '-' + hex.slice(8, 12) + '-' + hex.slice(12, 16) + '-' + hex.slice(16, 20) + '-' + hex.slice(20);
145
+ }
146
+ /**
147
+ * Percent-encodes a value as ONE path segment (`/`, `?`, `#`, spaces, CR/LF and non-ASCII are all
148
+ * encoded). An empty value, `.` and `..` are rejected because they would change the path.
149
+ */
150
+ export function encodePathSegment(value, name = 'value') {
151
+ if (typeof value !== 'string') {
152
+ throw new ValidationError('The path parameter "' + name + '" must be a string');
153
+ }
154
+ if (value === '' || value === '.' || value === '..') {
155
+ throw new ValidationError('The path parameter "' + name + '" must not be empty, "." or ".."');
156
+ }
157
+ try {
158
+ return encodeURIComponent(value).replace(/[!'()*]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase());
159
+ }
160
+ catch (cause) {
161
+ throw new ValidationError('The path parameter "' + name + '" is not valid Unicode text', { cause });
162
+ }
163
+ }
164
+ /** Fills a path template (`/v1/companies/{co}`) with encoded parameter values. */
165
+ export function buildPath(template, params) {
166
+ return template.replace(/\{([^{}]+)\}/g, (_match, name) => {
167
+ const value = params === undefined ? undefined : params[name];
168
+ return encodePathSegment(value, name);
169
+ });
170
+ }
171
+ function queryText(name, value) {
172
+ switch (typeof value) {
173
+ case 'string':
174
+ return value;
175
+ case 'boolean':
176
+ return value ? 'true' : 'false';
177
+ case 'bigint':
178
+ return value.toString();
179
+ case 'number':
180
+ if (!Number.isFinite(value))
181
+ break;
182
+ return String(value);
183
+ case 'object':
184
+ if (value instanceof Date && !Number.isNaN(value.getTime()))
185
+ return value.toISOString();
186
+ break;
187
+ default:
188
+ break;
189
+ }
190
+ throw new ValidationError('The query parameter "' + name + '" has a value that cannot be sent');
191
+ }
192
+ /**
193
+ * Builds a query string (without the leading `?`): booleans as `true`/`false`, dates as RFC 3339,
194
+ * arrays as repeated keys, null and undefined omitted, `+` encoded as `%2B`.
195
+ */
196
+ export function buildQuery(query) {
197
+ if (query === undefined)
198
+ return '';
199
+ const parts = [];
200
+ const add = (name, value) => {
201
+ try {
202
+ parts.push(encodeURIComponent(name) + '=' + encodeURIComponent(queryText(name, value)));
203
+ }
204
+ catch (cause) {
205
+ if (cause instanceof TungoError)
206
+ throw cause;
207
+ throw new ValidationError('The query parameter "' + name + '" is not valid Unicode text', { cause });
208
+ }
209
+ };
210
+ for (const [name, value] of Object.entries(query)) {
211
+ if (value === undefined || value === null)
212
+ continue;
213
+ if (Array.isArray(value)) {
214
+ for (const item of value) {
215
+ if (item !== undefined && item !== null)
216
+ add(name, item);
217
+ }
218
+ }
219
+ else {
220
+ add(name, value);
221
+ }
222
+ }
223
+ return parts.join('&');
224
+ }
225
+ /** Delay before retry number `attempt` (0-based), in milliseconds: min(0.5 s * 2^attempt, 8 s) * [0.75, 1]. */
226
+ export function backoffDelay(attempt, random = Math.random) {
227
+ const base = Math.min(500 * 2 ** attempt, 8000);
228
+ return base * (0.75 + 0.25 * random());
229
+ }
230
+ /** Statuses after which a request may be repeated. */
231
+ export function isRetryableStatus(status) {
232
+ return status === 408 || status === 429 || status === 500 || status === 502 || status === 503 || status === 504;
233
+ }
234
+ /**
235
+ * The retry rule: the failure must be transient (a retryable status, a connection error or a
236
+ * timeout) AND repeating the request must be safe (GET, HEAD, PUT, DELETE, or any request that
237
+ * carries an idempotency key).
238
+ */
239
+ export function shouldRetry(method, hasIdempotencyKey, cause) {
240
+ const transient = typeof cause === 'number' ? isRetryableStatus(cause) : true;
241
+ const m = method.toUpperCase();
242
+ const repeatable = m === 'GET' || m === 'HEAD' || m === 'PUT' || m === 'DELETE' || hasIdempotencyKey;
243
+ return transient && repeatable;
244
+ }
245
+ function abortError(signal, what) {
246
+ return new AbortError(what + ' was aborted', { cause: signal.reason });
247
+ }
248
+ /**
249
+ * Starts a timer, or none (undefined) when the delay is infinite or longer than the platform can
250
+ * count: `setTimeout` would fire such a timer at once instead of never.
251
+ */
252
+ export function startTimer(callback, ms) {
253
+ return ms > MAX_TIMER_MS ? undefined : setTimeout(callback, ms);
254
+ }
255
+ /**
256
+ * Waits `ms` milliseconds; rejects with an AbortError as soon as the signal aborts. A delay above
257
+ * {@link MAX_TIMER_MS} waits until the signal aborts.
258
+ */
259
+ export function sleep(ms, signal) {
260
+ return new Promise((resolve, reject) => {
261
+ if (signal !== undefined && signal.aborted) {
262
+ reject(abortError(signal, 'The wait'));
263
+ return;
264
+ }
265
+ const onAbort = () => {
266
+ clearTimeout(timer);
267
+ reject(abortError(signal, 'The wait'));
268
+ };
269
+ const timer = startTimer(() => {
270
+ if (signal !== undefined)
271
+ signal.removeEventListener('abort', onAbort);
272
+ resolve();
273
+ }, ms);
274
+ if (signal !== undefined)
275
+ signal.addEventListener('abort', onAbort, { once: true });
276
+ });
277
+ }
278
+ function causeText(cause) {
279
+ if (!(cause instanceof Error))
280
+ return String(cause);
281
+ const inner = cause.cause;
282
+ if (inner instanceof Error && inner.message !== '' && inner.message !== cause.message) {
283
+ return cause.message + ': ' + inner.message;
284
+ }
285
+ return cause.message;
286
+ }
287
+ /**
288
+ * The text of a transport failure without the request URL: a custom fetch (node-fetch, a proxy
289
+ * or tracing wrapper) may put the full URL into its message, and the path can carry a hook token
290
+ * and the query search text. The URL and the concrete path become the route template, and any
291
+ * other absolute URL and every path parameter value are cut out.
292
+ */
293
+ function redactedCauseText(cause, baseUrl, url, spec) {
294
+ let text = causeText(cause);
295
+ const path = buildPath(spec.path, spec.pathParams);
296
+ const pathAndQuery = url.slice(baseUrl.length);
297
+ for (const concrete of [url, url.split('?')[0] ?? url, pathAndQuery, path]) {
298
+ if (concrete !== '' && concrete !== '/')
299
+ text = text.split(concrete).join(spec.path);
300
+ }
301
+ text = text.replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s"'<>]*/gi, '[url]');
302
+ for (const value of Object.values(spec.pathParams ?? {})) {
303
+ if (typeof value !== 'string' || value === '')
304
+ continue;
305
+ for (const form of new Set([value, encodeURIComponent(value)]))
306
+ text = text.split(form).join('[redacted]');
307
+ }
308
+ return text;
309
+ }
310
+ function positive(value, fallback, name, zeroAllowed) {
311
+ if (value === undefined)
312
+ return fallback;
313
+ if (typeof value !== 'number' || Number.isNaN(value) || value < 0 || (value === 0 && !zeroAllowed)) {
314
+ throw new ConfigError('The option "' + name + '" must be a ' + (zeroAllowed ? 'non-negative' : 'positive') + ' number');
315
+ }
316
+ return value;
317
+ }
318
+ function retries(value, fallback) {
319
+ if (value === undefined)
320
+ return fallback;
321
+ if (!Number.isInteger(value) || value < 0) {
322
+ throw new ConfigError('The option "maxRetries" must be a non-negative integer');
323
+ }
324
+ return value;
325
+ }
326
+ /**
327
+ * Whether a header value can be sent at all: fetch refuses CR, LF and NUL, and a character above
328
+ * U+00FF (a Cyrillic look-alike pasted into a key) is not a byte, so fetch would throw a
329
+ * TypeError that looks like a network failure.
330
+ */
331
+ function sendableHeaderValue(value) {
332
+ for (let i = 0; i < value.length; i++) {
333
+ const code = value.charCodeAt(i);
334
+ if (code === 0 || code === 10 || code === 13 || code > 0xff)
335
+ return false;
336
+ }
337
+ return true;
338
+ }
339
+ class HeaderBag {
340
+ #map = new Map();
341
+ set(name, value) {
342
+ if (!sendableHeaderValue(value) || !/^[!#$%&'*+.^_|~0-9A-Za-z-]+$/.test(name)) {
343
+ throw new ValidationError('The header "' + name.replace(/[^ -~]/g, '?') + '" has an invalid name or value');
344
+ }
345
+ this.#map.set(name.toLowerCase(), [name, value]);
346
+ }
347
+ delete(name) {
348
+ this.#map.delete(name.toLowerCase());
349
+ }
350
+ has(name) {
351
+ return this.#map.has(name.toLowerCase());
352
+ }
353
+ toRecord() {
354
+ const out = {};
355
+ for (const [name, value] of this.#map.values())
356
+ out[name] = value;
357
+ return out;
358
+ }
359
+ }
360
+ /**
361
+ * A promise of a decoded response that also gives access to the raw response:
362
+ * `await client.companies.get(id)` yields the data, `.withResponse()` adds status, headers,
363
+ * request id and rate-limit information of that very response.
364
+ */
365
+ export class APIPromise extends Promise {
366
+ #result;
367
+ constructor(result) {
368
+ super((resolve) => {
369
+ resolve(undefined);
370
+ });
371
+ this.#result = result;
372
+ }
373
+ /** The decoded data together with the status, headers, request id and rate limit of the response. */
374
+ withResponse() {
375
+ return this.#result;
376
+ }
377
+ /** Only the status, headers, request id and rate limit of the response. */
378
+ asResponse() {
379
+ return this.#result.then((r) => r.response);
380
+ }
381
+ then(onfulfilled, onrejected) {
382
+ return this.#result.then((r) => r.data).then(onfulfilled, onrejected);
383
+ }
384
+ catch(onrejected) {
385
+ return this.#result.then((r) => r.data).catch(onrejected);
386
+ }
387
+ finally(onfinally) {
388
+ return this.#result.then((r) => r.data).finally(onfinally);
389
+ }
390
+ static get [Symbol.species]() {
391
+ return Promise;
392
+ }
393
+ }
394
+ /**
395
+ * A promise of an open stream that can also be iterated directly:
396
+ * `for await (const event of client.feed.listEvents(co))`. Awaiting it gives the stream object
397
+ * (with `response`, `close()` and, for chat streams, `dialogId` and `turnNo`).
398
+ */
399
+ export class StreamPromise extends Promise {
400
+ #stream;
401
+ constructor(stream) {
402
+ super((resolve) => {
403
+ resolve(undefined);
404
+ });
405
+ this.#stream = stream;
406
+ }
407
+ then(onfulfilled, onrejected) {
408
+ return this.#stream.then(onfulfilled, onrejected);
409
+ }
410
+ catch(onrejected) {
411
+ return this.#stream.catch(onrejected);
412
+ }
413
+ finally(onfinally) {
414
+ return this.#stream.finally(onfinally);
415
+ }
416
+ async *[Symbol.asyncIterator]() {
417
+ const stream = await this.#stream;
418
+ yield* stream;
419
+ }
420
+ static get [Symbol.species]() {
421
+ return Promise;
422
+ }
423
+ }
424
+ /**
425
+ * The HTTP engine shared by all resources: configuration, authentication, retries, timeouts,
426
+ * cancellation and decoding. It is immutable after construction and safe to share.
427
+ */
428
+ export class APIClient {
429
+ /** Base URL without a trailing slash. */
430
+ baseUrl;
431
+ /** Default request timeout in milliseconds. */
432
+ timeout;
433
+ /** Default timeout of non-streaming chat turns in milliseconds. */
434
+ longRunningTimeout;
435
+ /** Default number of retries. */
436
+ maxRetries;
437
+ /** Default idle timeout of streams in milliseconds. */
438
+ streamIdleTimeout;
439
+ #apiKey;
440
+ #webhookSecret;
441
+ #fetch;
442
+ #defaultHeaders;
443
+ #bearer;
444
+ #logger;
445
+ constructor(options = {}) {
446
+ const baseUrl = (options.baseUrl ?? readEnv('TUNGO_BASE_URL') ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
447
+ let parsed;
448
+ try {
449
+ parsed = new URL(baseUrl);
450
+ }
451
+ catch (cause) {
452
+ throw new ConfigError('The base URL is not a valid absolute URL', { cause });
453
+ }
454
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
455
+ throw new ConfigError('The base URL must start with https:// or http://');
456
+ }
457
+ if (parsed.search !== '' || parsed.hash !== '' || parsed.username !== '' || parsed.password !== '') {
458
+ throw new ConfigError('The base URL must not contain credentials, a query string or a fragment');
459
+ }
460
+ this.baseUrl = baseUrl;
461
+ this.timeout = positive(options.timeout, DEFAULT_TIMEOUT, 'timeout', false);
462
+ this.longRunningTimeout = positive(options.longRunningTimeout, DEFAULT_LONG_RUNNING_TIMEOUT, 'longRunningTimeout', false);
463
+ this.streamIdleTimeout = positive(options.streamIdleTimeout, DEFAULT_STREAM_IDLE_TIMEOUT, 'streamIdleTimeout', true);
464
+ this.maxRetries = retries(options.maxRetries, DEFAULT_MAX_RETRIES);
465
+ const apiKey = options.apiKey ?? readEnv('TUNGO_API_KEY');
466
+ this.#apiKey = apiKey === '' ? undefined : apiKey;
467
+ const webhookSecret = options.webhookSecret ?? readEnv('TUNGO_WEBHOOK_SECRET');
468
+ this.#webhookSecret = webhookSecret === '' ? undefined : webhookSecret;
469
+ this.#bearer = options.authScheme === 'bearer';
470
+ this.#defaultHeaders = { ...(options.defaultHeaders ?? {}) };
471
+ this.#logger = options.logger;
472
+ if (options.fetch !== undefined) {
473
+ this.#fetch = options.fetch;
474
+ }
475
+ else if (typeof globalThis.fetch === 'function') {
476
+ this.#fetch = (input, init) => globalThis.fetch(input, init);
477
+ }
478
+ else {
479
+ throw new ConfigError('This runtime has no global fetch: pass a fetch implementation in the "fetch" option');
480
+ }
481
+ }
482
+ /** The webhook secret to use: the explicit one, else the client's; a ConfigError when there is none. */
483
+ webhookSecret(explicit) {
484
+ const secret = explicit ?? this.#webhookSecret;
485
+ if (secret === undefined || secret === '') {
486
+ throw new ConfigError('No webhook secret: pass one or set the TUNGO_WEBHOOK_SECRET environment variable');
487
+ }
488
+ return secret;
489
+ }
490
+ /** Performs a request and decodes the JSON response. */
491
+ request(spec) {
492
+ return new APIPromise(this.#requestJSON(spec));
493
+ }
494
+ /** Opens a server-sent event stream; `make` wraps the connection into the stream object. */
495
+ async openStream(spec, make) {
496
+ // Checked before anything is sent: once the turn is posted it runs (and is billed) on the
497
+ // server, so a bad option found afterwards would cost a turn and leave the connection open.
498
+ const idleTimeout = positive(spec.options?.streamIdleTimeout, this.streamIdleTimeout, 'streamIdleTimeout', true);
499
+ const x = await this.#exchange(spec, true);
500
+ try {
501
+ return make({
502
+ response: x.info,
503
+ body: x.response.body,
504
+ controller: x.controller,
505
+ signal: spec.options?.signal ?? undefined,
506
+ detach: x.detach,
507
+ idleTimeout,
508
+ route: spec.method.toUpperCase() + ' ' + spec.path,
509
+ });
510
+ }
511
+ catch (error) {
512
+ // The stream object never came to be: nobody else can close the connection.
513
+ x.detach();
514
+ x.controller.abort();
515
+ x.response.body?.cancel().catch(() => undefined);
516
+ throw error;
517
+ }
518
+ }
519
+ async #requestJSON(spec) {
520
+ const x = await this.#exchange(spec, false);
521
+ const status = x.info.status;
522
+ if (spec.emptyResult === true || status === 204 || status === 205) {
523
+ return { data: undefined, response: x.info };
524
+ }
525
+ const route = spec.method.toUpperCase() + ' ' + spec.path;
526
+ if (x.text.trim() === '') {
527
+ throw new DecodeError('The response of ' + route + ' (status ' + status + ') has an empty body where JSON was expected', {
528
+ status,
529
+ requestId: x.info.requestId,
530
+ body: x.text,
531
+ });
532
+ }
533
+ try {
534
+ return { data: parseJSON(x.text), response: x.info };
535
+ }
536
+ catch (cause) {
537
+ throw new DecodeError('The response of ' + route + ' (status ' + status + ') is not valid JSON', {
538
+ status,
539
+ requestId: x.info.requestId,
540
+ body: x.text,
541
+ cause,
542
+ });
543
+ }
544
+ }
545
+ #headers(spec, stream) {
546
+ const options = spec.options ?? {};
547
+ const bag = new HeaderBag();
548
+ bag.set('Accept', stream ? 'text/event-stream' : 'application/json');
549
+ bag.set('User-Agent', USER_AGENT);
550
+ if (spec.rawBody !== undefined) {
551
+ bag.set('Content-Type', spec.contentType ?? 'application/octet-stream');
552
+ }
553
+ else if (spec.body !== undefined) {
554
+ bag.set('Content-Type', 'application/json');
555
+ }
556
+ for (const [name, value] of Object.entries(this.#defaultHeaders))
557
+ bag.set(name, value);
558
+ for (const [name, value] of Object.entries(spec.headers ?? {})) {
559
+ if (value !== undefined)
560
+ bag.set(name, value);
561
+ }
562
+ for (const [name, value] of Object.entries(options.headers ?? {})) {
563
+ if (value === null)
564
+ bag.delete(name);
565
+ else if (value !== undefined)
566
+ bag.set(name, value);
567
+ }
568
+ // Credentials go only to operations that require the API key.
569
+ bag.delete('x-api-key');
570
+ bag.delete('authorization');
571
+ if ((spec.auth ?? 'key') === 'key') {
572
+ const key = this.#apiKey;
573
+ if (key === undefined) {
574
+ throw new ConfigError('No API key: pass "apiKey" to the client or set the TUNGO_API_KEY environment variable');
575
+ }
576
+ if (!sendableHeaderValue(key)) {
577
+ // Never the key itself: only what is wrong with it.
578
+ throw new ConfigError('The API key contains a character that cannot be sent in a header (a line break, or a letter outside Latin-1 such as a Cyrillic look-alike): check "apiKey" or TUNGO_API_KEY');
579
+ }
580
+ if (this.#bearer)
581
+ bag.set('Authorization', 'Bearer ' + key);
582
+ else
583
+ bag.set('x-api-key', key);
584
+ }
585
+ if (options.idempotencyKey === '')
586
+ throw new ValidationError('The idempotency key must not be empty');
587
+ const headerName = spec.idempotencyHeader;
588
+ if (headerName === undefined) {
589
+ // The API ignores a key on an operation that declares none: sending one would make a retry
590
+ // look safe when it repeats the action.
591
+ bag.delete('Idempotency-Key');
592
+ return { headers: bag.toRecord(), hasIdempotencyKey: false };
593
+ }
594
+ if (options.idempotencyKey !== undefined) {
595
+ bag.set(headerName, options.idempotencyKey);
596
+ }
597
+ else if (!bag.has(headerName)) {
598
+ const fallback = spec.defaultIdempotencyKey !== undefined && spec.defaultIdempotencyKey !== '' ? spec.defaultIdempotencyKey : bodyIdempotencyKey(spec.body);
599
+ bag.set(headerName, fallback ?? uuid4());
600
+ }
601
+ return { headers: bag.toRecord(), hasIdempotencyKey: bag.has(headerName) };
602
+ }
603
+ #log(event) {
604
+ const logger = this.#logger;
605
+ if (logger === undefined)
606
+ return;
607
+ try {
608
+ logger(event);
609
+ }
610
+ catch {
611
+ // A failing logger must not break the request.
612
+ }
613
+ }
614
+ /**
615
+ * Fetches without ever following a redirect: the request carries the API key in a custom
616
+ * header, which no HTTP client strips when a redirect leads to another host. A 3xx answer is
617
+ * returned as it is and becomes an APIError with that status.
618
+ */
619
+ async #fetchNoRedirect(url, init) {
620
+ const res = await this.#fetch(url, init);
621
+ if (res.type === 'opaqueredirect') {
622
+ // Browsers hide the status and the headers of a redirect fetched with redirect: 'manual'.
623
+ throw new ConnectionError('The API answered with a redirect, which is never followed');
624
+ }
625
+ return res;
626
+ }
627
+ async #exchange(spec, stream) {
628
+ const options = spec.options ?? {};
629
+ const signal = options.signal ?? undefined;
630
+ const method = spec.method.toUpperCase();
631
+ const route = method + ' ' + spec.path;
632
+ if (signal !== undefined && signal.aborted)
633
+ throw abortError(signal, 'The request ' + route);
634
+ const query = buildQuery(spec.query);
635
+ const url = this.baseUrl + buildPath(spec.path, spec.pathParams) + (query === '' ? '' : '?' + query);
636
+ const { headers, hasIdempotencyKey } = this.#headers(spec, stream);
637
+ let body;
638
+ if (spec.rawBody !== undefined)
639
+ body = spec.rawBody;
640
+ else if (spec.body !== undefined)
641
+ body = stringifyJSON(spec.body);
642
+ const maxRetries = retries(options.maxRetries, this.maxRetries);
643
+ const timeout = positive(options.timeout, spec.longRunning === true ? this.longRunningTimeout : this.timeout, 'timeout', false);
644
+ for (let attempt = 0;; attempt++) {
645
+ const controller = new AbortController();
646
+ let timedOut = false;
647
+ // No timer at all for an unlimited timeout (see MAX_TIMER_MS).
648
+ const timer = startTimer(() => {
649
+ timedOut = true;
650
+ controller.abort();
651
+ }, timeout);
652
+ const onAbort = () => {
653
+ controller.abort();
654
+ };
655
+ const detach = () => {
656
+ if (signal !== undefined)
657
+ signal.removeEventListener('abort', onAbort);
658
+ };
659
+ if (signal !== undefined)
660
+ signal.addEventListener('abort', onAbort, { once: true });
661
+ const started = Date.now();
662
+ let keepOpen = false;
663
+ let failure;
664
+ let cause;
665
+ let retryAfter = null;
666
+ this.#log({ kind: 'request', method, route: spec.path, attempt: attempt + 1 });
667
+ try {
668
+ const init = { method, headers, signal: controller.signal, redirect: 'manual' };
669
+ if (body !== undefined)
670
+ init.body = body;
671
+ const response = await this.#fetchNoRedirect(url, init);
672
+ const requestId = response.headers.get('x-request-id');
673
+ const info = {
674
+ status: response.status,
675
+ headers: response.headers,
676
+ requestId: requestId === '' ? null : requestId,
677
+ rateLimit: parseRateLimit(response.headers),
678
+ attempts: attempt + 1,
679
+ };
680
+ if (response.status >= 200 && response.status < 300) {
681
+ if (stream && isReplayedJSON(response.headers)) {
682
+ // A chat turn repeated with the same Idempotency-Key after it finished: the server
683
+ // answers the stored ChatTurnResult instead of a stream. The caller gets its events.
684
+ const replayed = await response.text();
685
+ const synthesized = replayAsEventStream(response, replayed, info.requestId);
686
+ if (synthesized === null) {
687
+ throw new DecodeError('The response of ' + route + ' (status ' + response.status + ') replays a result that is not a chat turn', {
688
+ status: response.status,
689
+ requestId: info.requestId,
690
+ body: replayed,
691
+ });
692
+ }
693
+ info.headers = synthesized.headers;
694
+ keepOpen = true;
695
+ clearTimeout(timer);
696
+ this.#log({ kind: 'response', method, route: spec.path, attempt: attempt + 1, status: info.status, durationMs: Date.now() - started, requestId: info.requestId });
697
+ return { info, text: '', response: synthesized.response, controller, detach };
698
+ }
699
+ if (stream) {
700
+ const contentType = (response.headers.get('content-type') ?? '').trim().toLowerCase();
701
+ if (!contentType.startsWith('text/event-stream')) {
702
+ // Not an event stream (a proxy page, a JSON body): reading it as one would yield
703
+ // zero events and look like a turn that produced nothing.
704
+ const unexpected = await response.text();
705
+ const shown = contentType === '' ? 'missing' : '"' + contentType.replace(/[^ -~]/g, '?').slice(0, 100) + '"';
706
+ throw new DecodeError('The response of ' + route + ' (status ' + response.status + ') is not an event stream: its content type is ' + shown, {
707
+ status: response.status,
708
+ requestId: info.requestId,
709
+ body: unexpected,
710
+ });
711
+ }
712
+ keepOpen = true;
713
+ clearTimeout(timer);
714
+ this.#log({ kind: 'response', method, route: spec.path, attempt: attempt + 1, status: info.status, durationMs: Date.now() - started, requestId: info.requestId });
715
+ return { info, text: '', response, controller, detach };
716
+ }
717
+ const text = await response.text();
718
+ this.#log({ kind: 'response', method, route: spec.path, attempt: attempt + 1, status: info.status, durationMs: Date.now() - started, requestId: info.requestId });
719
+ return { info, text, response, controller, detach };
720
+ }
721
+ const text = await response.text();
722
+ this.#log({ kind: 'response', method, route: spec.path, attempt: attempt + 1, status: info.status, durationMs: Date.now() - started, requestId: info.requestId });
723
+ const apiError = apiErrorFromResponse(response.status, response.headers, text);
724
+ failure = apiError;
725
+ cause = response.status;
726
+ retryAfter = apiError.retryAfter;
727
+ }
728
+ catch (reason) {
729
+ if (signal !== undefined && signal.aborted)
730
+ throw abortError(signal, 'The request ' + route);
731
+ if (reason instanceof TungoError)
732
+ throw reason;
733
+ if (timedOut) {
734
+ failure = new TimeoutError('The request ' + route + ' timed out after ' + timeout + ' ms', timeout, { cause: reason });
735
+ cause = 'timeout';
736
+ }
737
+ else {
738
+ failure = new ConnectionError('Could not reach the API for ' + route + ': ' + redactedCauseText(reason, this.baseUrl, url, spec), { cause: reason });
739
+ cause = 'connection_error';
740
+ }
741
+ }
742
+ finally {
743
+ if (!keepOpen) {
744
+ clearTimeout(timer);
745
+ detach();
746
+ }
747
+ }
748
+ const retry = attempt < maxRetries && shouldRetry(method, hasIdempotencyKey, cause) && (retryAfter === null || retryAfter <= MAX_RETRY_AFTER_SECONDS);
749
+ if (!retry) {
750
+ this.#log({ kind: 'error', method, route: spec.path, attempt: attempt + 1, error: failure });
751
+ throw failure;
752
+ }
753
+ // A delay of zero (also an HTTP-date that has already passed) is not an order to hammer the
754
+ // server at once: the computed backoff applies.
755
+ const delayMs = retryAfter !== null && retryAfter > 0 ? Math.ceil(retryAfter * 1000) : Math.round(backoffDelay(attempt));
756
+ const event = { kind: 'retry', method, route: spec.path, attempt: attempt + 1, delayMs, error: failure };
757
+ if (failure instanceof APIError && failure.status !== undefined)
758
+ event.status = failure.status;
759
+ this.#log(event);
760
+ await sleep(delayMs, signal);
761
+ }
762
+ }
763
+ }