@tungoai/sdk 0.2.0 → 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.
- package/CHANGELOG.md +54 -1
- package/README.kk.md +5 -5
- package/README.md +7 -7
- package/README.ru.md +5 -5
- package/dist/cjs/chat.js +3 -2
- package/dist/cjs/client.d.ts +2 -1
- package/dist/cjs/client.js +5 -3
- package/dist/cjs/core.d.ts +9 -2
- package/dist/cjs/core.js +191 -17
- package/dist/cjs/errors.d.ts +25 -0
- package/dist/cjs/errors.js +39 -3
- package/dist/cjs/generated/resources.d.ts +92 -2
- package/dist/cjs/generated/resources.js +82 -1
- package/dist/cjs/generated/types.d.ts +562 -54
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/index.js +3 -2
- package/dist/cjs/json.d.ts +6 -0
- package/dist/cjs/json.js +17 -0
- package/dist/cjs/pagination.js +2 -1
- package/dist/cjs/streaming.d.ts +4 -2
- package/dist/cjs/streaming.js +40 -2
- package/dist/cjs/version.d.ts +1 -1
- package/dist/cjs/version.js +1 -1
- package/dist/cjs/webhooks.d.ts +5 -0
- package/dist/cjs/webhooks.js +17 -3
- package/dist/esm/chat.js +3 -2
- package/dist/esm/client.d.ts +2 -1
- package/dist/esm/client.js +5 -3
- package/dist/esm/core.d.ts +9 -2
- package/dist/esm/core.js +191 -17
- package/dist/esm/errors.d.ts +25 -0
- package/dist/esm/errors.js +36 -1
- package/dist/esm/generated/resources.d.ts +92 -2
- package/dist/esm/generated/resources.js +82 -1
- package/dist/esm/generated/types.d.ts +562 -54
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/json.d.ts +6 -0
- package/dist/esm/json.js +16 -0
- package/dist/esm/pagination.js +2 -1
- package/dist/esm/streaming.d.ts +4 -2
- package/dist/esm/streaming.js +41 -3
- package/dist/esm/version.d.ts +1 -1
- package/dist/esm/version.js +1 -1
- package/dist/esm/webhooks.d.ts +5 -0
- package/dist/esm/webhooks.js +17 -3
- package/package.json +1 -1
package/dist/cjs/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ export type * from './generated/types.js';
|
|
|
2
2
|
export * from './generated/resources.js';
|
|
3
3
|
export { Tungo, Tungo as TungoClient, type ChatInput, type WaitOptions } from './client.js';
|
|
4
4
|
export { APIClient, APIPromise, StreamPromise, DEFAULT_BASE_URL, DEFAULT_LONG_RUNNING_TIMEOUT, DEFAULT_MAX_RETRIES, DEFAULT_STREAM_IDLE_TIMEOUT, DEFAULT_TIMEOUT, type ClientOptions, type Fetch, type LogEvent, type RequestOptions, type RequestSpec, type WithResponse, } from './core.js';
|
|
5
|
-
export { APIError, AbortError, AuthenticationError, ConfigError, ConflictError, ConnectionError, DecodeError, GoneError, InternalServerError, InvalidRequestError, LimitError, MoneyError, NotFoundError, PaymentRequiredError, PermissionError, TimeoutError, TungoError, UnavailableError, ValidationError, WebhookVerificationError, type APIErrorType, type APIFieldError, type RateLimit, type WebhookVerificationReason, } from './errors.js';
|
|
5
|
+
export { APIError, AbortError, AuthenticationError, ConfigError, ConflictError, ConnectionError, DecodeError, GoneError, InternalServerError, InvalidRequestError, LimitError, MoneyError, NotFoundError, PaymentRequiredError, PermissionError, StreamError, TimeoutError, TungoError, UnavailableError, ValidationError, WebhookVerificationError, type APIErrorType, type APIFieldError, type RateLimit, type WebhookVerificationReason, } from './errors.js';
|
|
6
6
|
export { SSEDecoder, Stream, type ResponseInfo, type ServerSentEvent } from './streaming.js';
|
|
7
7
|
export { Page, PagePromise, type CursorPageBody } from './pagination.js';
|
|
8
8
|
export { ChatAccumulator, ChatStream, ChatStreamPromise, accumulateChatStream, chatTurnError, type ChatStreamCallbacks, type ChatStreamResult, } from './chat.js';
|
package/dist/cjs/index.js
CHANGED
|
@@ -14,8 +14,8 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
exports.
|
|
18
|
-
exports.VERSION = void 0;
|
|
17
|
+
exports.parseJSON = exports.isValidBinIin = exports.TungoMoney = exports.TungoKazakhstan = exports.verifyWebhook = exports.verifyHookSignature = exports.signHookPayload = exports.TungoWebhooks = exports.TungoHooks = exports.DEFAULT_WEBHOOK_TOLERANCE_SECONDS = exports.chatTurnError = exports.accumulateChatStream = exports.ChatStreamPromise = exports.ChatStream = exports.ChatAccumulator = exports.PagePromise = exports.Page = exports.Stream = exports.SSEDecoder = exports.WebhookVerificationError = exports.ValidationError = exports.UnavailableError = exports.TungoError = exports.TimeoutError = exports.StreamError = exports.PermissionError = exports.PaymentRequiredError = exports.NotFoundError = exports.MoneyError = exports.LimitError = exports.InvalidRequestError = exports.InternalServerError = exports.GoneError = exports.DecodeError = exports.ConnectionError = exports.ConflictError = exports.ConfigError = exports.AuthenticationError = exports.AbortError = exports.APIError = exports.DEFAULT_TIMEOUT = exports.DEFAULT_STREAM_IDLE_TIMEOUT = exports.DEFAULT_MAX_RETRIES = exports.DEFAULT_LONG_RUNNING_TIMEOUT = exports.DEFAULT_BASE_URL = exports.StreamPromise = exports.APIPromise = exports.APIClient = exports.TungoClient = exports.Tungo = void 0;
|
|
18
|
+
exports.VERSION = exports.stringifyJSON = void 0;
|
|
19
19
|
__exportStar(require("./generated/resources.js"), exports);
|
|
20
20
|
var client_js_1 = require("./client.js");
|
|
21
21
|
Object.defineProperty(exports, "Tungo", { enumerable: true, get: function () { return client_js_1.Tungo; } });
|
|
@@ -45,6 +45,7 @@ Object.defineProperty(exports, "MoneyError", { enumerable: true, get: function (
|
|
|
45
45
|
Object.defineProperty(exports, "NotFoundError", { enumerable: true, get: function () { return errors_js_1.NotFoundError; } });
|
|
46
46
|
Object.defineProperty(exports, "PaymentRequiredError", { enumerable: true, get: function () { return errors_js_1.PaymentRequiredError; } });
|
|
47
47
|
Object.defineProperty(exports, "PermissionError", { enumerable: true, get: function () { return errors_js_1.PermissionError; } });
|
|
48
|
+
Object.defineProperty(exports, "StreamError", { enumerable: true, get: function () { return errors_js_1.StreamError; } });
|
|
48
49
|
Object.defineProperty(exports, "TimeoutError", { enumerable: true, get: function () { return errors_js_1.TimeoutError; } });
|
|
49
50
|
Object.defineProperty(exports, "TungoError", { enumerable: true, get: function () { return errors_js_1.TungoError; } });
|
|
50
51
|
Object.defineProperty(exports, "UnavailableError", { enumerable: true, get: function () { return errors_js_1.UnavailableError; } });
|
package/dist/cjs/json.d.ts
CHANGED
|
@@ -8,3 +8,9 @@ export declare function parseJSON(text: string): unknown;
|
|
|
8
8
|
* NaN and Infinity (which JSON cannot express) and unserialisable values raise a ValidationError.
|
|
9
9
|
*/
|
|
10
10
|
export declare function stringifyJSON(value: unknown): string;
|
|
11
|
+
/**
|
|
12
|
+
* The JSON text of a decoded value for an error message or the `body` of an error: like
|
|
13
|
+
* stringifyJSON (a bigint keeps every digit), but it never throws: `undefined` and a value JSON
|
|
14
|
+
* cannot express give ''.
|
|
15
|
+
*/
|
|
16
|
+
export declare function debugJSON(value: unknown): string;
|
package/dist/cjs/json.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.parseJSON = parseJSON;
|
|
4
4
|
exports.stringifyJSON = stringifyJSON;
|
|
5
|
+
exports.debugJSON = debugJSON;
|
|
5
6
|
// Code generated by tungo-sdkgen. DO NOT EDIT.
|
|
6
7
|
const errors_js_1 = require("./errors.js");
|
|
7
8
|
// JSON numbers are IEEE doubles in JavaScript, so an integer beyond 2^53 would silently lose its
|
|
@@ -118,3 +119,19 @@ function stringifyJSON(value) {
|
|
|
118
119
|
return text;
|
|
119
120
|
return text.replace(new RegExp('"\\\\u0000' + prefix + '(-?[0-9]+)"', 'g'), '$1');
|
|
120
121
|
}
|
|
122
|
+
/**
|
|
123
|
+
* The JSON text of a decoded value for an error message or the `body` of an error: like
|
|
124
|
+
* stringifyJSON (a bigint keeps every digit), but it never throws: `undefined` and a value JSON
|
|
125
|
+
* cannot express give ''.
|
|
126
|
+
*/
|
|
127
|
+
function debugJSON(value) {
|
|
128
|
+
if (value === undefined)
|
|
129
|
+
return '';
|
|
130
|
+
try {
|
|
131
|
+
return stringifyJSON(value);
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
// NaN or Infinity inside, a cycle: the error is still raised, only without its body.
|
|
135
|
+
return '';
|
|
136
|
+
}
|
|
137
|
+
}
|
package/dist/cjs/pagination.js
CHANGED
|
@@ -5,6 +5,7 @@ exports.requestPage = requestPage;
|
|
|
5
5
|
// Code generated by tungo-sdkgen. DO NOT EDIT.
|
|
6
6
|
const core_js_1 = require("./core.js");
|
|
7
7
|
const errors_js_1 = require("./errors.js");
|
|
8
|
+
const json_js_1 = require("./json.js");
|
|
8
9
|
/**
|
|
9
10
|
* One page of a cursor-paginated list. `data` holds the items of this page, `body` the complete
|
|
10
11
|
* typed response (totals and other fields next to `data`). Iterating the page with `for await`
|
|
@@ -30,7 +31,7 @@ class Page {
|
|
|
30
31
|
throw new errors_js_1.DecodeError('The response of ' + spec.method + ' ' + spec.path + ' is not a page: "data" is not an array', {
|
|
31
32
|
status: result.response.status,
|
|
32
33
|
requestId: result.response.requestId,
|
|
33
|
-
body:
|
|
34
|
+
body: (0, json_js_1.debugJSON)(body),
|
|
34
35
|
});
|
|
35
36
|
}
|
|
36
37
|
const next = body.next_cursor;
|
package/dist/cjs/streaming.d.ts
CHANGED
|
@@ -69,6 +69,8 @@ export declare class Stream<T> implements AsyncIterable<T> {
|
|
|
69
69
|
}
|
|
70
70
|
/**
|
|
71
71
|
* Decodes the `data` of an event as JSON. Heart-beats (`ping`, or an event with empty data) are
|
|
72
|
-
* skipped; data that is not valid JSON raises a DecodeError.
|
|
72
|
+
* skipped; data that is not valid JSON raises a DecodeError. Unless `errorIsEvent` (chat events,
|
|
73
|
+
* where `error` is a variant of the union), an `error` event is a failure of the stream and raises
|
|
74
|
+
* a StreamError, so a broken stream never looks like one that ended normally.
|
|
73
75
|
*/
|
|
74
|
-
export declare function decodeJSONEvent<T>(event: ServerSentEvent, response: ResponseInfo): T | undefined;
|
|
76
|
+
export declare function decodeJSONEvent<T>(event: ServerSentEvent, response: ResponseInfo, errorIsEvent?: boolean): T | undefined;
|
package/dist/cjs/streaming.js
CHANGED
|
@@ -234,11 +234,15 @@ class Stream {
|
|
|
234
234
|
exports.Stream = Stream;
|
|
235
235
|
/**
|
|
236
236
|
* Decodes the `data` of an event as JSON. Heart-beats (`ping`, or an event with empty data) are
|
|
237
|
-
* skipped; data that is not valid JSON raises a DecodeError.
|
|
237
|
+
* skipped; data that is not valid JSON raises a DecodeError. Unless `errorIsEvent` (chat events,
|
|
238
|
+
* where `error` is a variant of the union), an `error` event is a failure of the stream and raises
|
|
239
|
+
* a StreamError, so a broken stream never looks like one that ended normally.
|
|
238
240
|
*/
|
|
239
|
-
function decodeJSONEvent(event, response) {
|
|
241
|
+
function decodeJSONEvent(event, response, errorIsEvent = false) {
|
|
240
242
|
if (event.event === 'ping' || event.data === '')
|
|
241
243
|
return undefined;
|
|
244
|
+
if (event.event === 'error' && !errorIsEvent)
|
|
245
|
+
throw streamError(event.data, response);
|
|
242
246
|
try {
|
|
243
247
|
return (0, json_js_1.parseJSON)(event.data);
|
|
244
248
|
}
|
|
@@ -251,3 +255,37 @@ function decodeJSONEvent(event, response) {
|
|
|
251
255
|
});
|
|
252
256
|
}
|
|
253
257
|
}
|
|
258
|
+
/**
|
|
259
|
+
* Reads the data of an `error` event: `{"error": "code", "message": ...}` as the contract sends it,
|
|
260
|
+
* or the API error envelope `{"error": {"code", "message", ...}}`. Other data still gives a StreamError.
|
|
261
|
+
*/
|
|
262
|
+
function streamError(data, response) {
|
|
263
|
+
let root;
|
|
264
|
+
try {
|
|
265
|
+
root = (0, json_js_1.parseJSON)(data);
|
|
266
|
+
}
|
|
267
|
+
catch {
|
|
268
|
+
root = undefined;
|
|
269
|
+
}
|
|
270
|
+
const text = (value) => (typeof value === 'string' && value !== '' ? value : null);
|
|
271
|
+
const props = isRecord(root) ? root : {};
|
|
272
|
+
const inner = isRecord(props['error']) ? props['error'] : {};
|
|
273
|
+
const extra = {};
|
|
274
|
+
for (const [key, value] of Object.entries(inner))
|
|
275
|
+
if (key !== 'code' && key !== 'message')
|
|
276
|
+
extra[key] = value;
|
|
277
|
+
for (const [key, value] of Object.entries(props)) {
|
|
278
|
+
if (key !== 'error' && key !== 'code' && key !== 'message' && key !== 'request_id')
|
|
279
|
+
extra[key] = value;
|
|
280
|
+
}
|
|
281
|
+
return new errors_js_1.StreamError({
|
|
282
|
+
code: text(props['code']) ?? text(props['error']) ?? text(inner['code']),
|
|
283
|
+
detail: text(props['message']) ?? text(inner['message']) ?? 'The stream reported an error',
|
|
284
|
+
requestId: text(props['request_id']) ?? response.requestId,
|
|
285
|
+
extra,
|
|
286
|
+
body: data,
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
function isRecord(value) {
|
|
290
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
291
|
+
}
|
package/dist/cjs/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** Version of this SDK; sent in the User-Agent header. */
|
|
2
|
-
export declare const VERSION = "0.
|
|
2
|
+
export declare const VERSION = "0.3.0";
|
package/dist/cjs/version.js
CHANGED
package/dist/cjs/webhooks.d.ts
CHANGED
|
@@ -65,6 +65,11 @@ export interface HookOperation {
|
|
|
65
65
|
export interface SendHookOptions extends RequestOptions {
|
|
66
66
|
/** The hook's signing secret. When given, the exact bytes sent are signed in the signature header. */
|
|
67
67
|
secret?: string | undefined;
|
|
68
|
+
/**
|
|
69
|
+
* The header the hook reads its signature from: the `signature_header` it was created with.
|
|
70
|
+
* Default `X-Signature`.
|
|
71
|
+
*/
|
|
72
|
+
signatureHeader?: string | undefined;
|
|
68
73
|
/** Your id of the event, for de-duplication on the server. */
|
|
69
74
|
eventId?: string | undefined;
|
|
70
75
|
/** Content type of the body. Default: `application/json` for text and JSON values, `application/octet-stream` for bytes. */
|
package/dist/cjs/webhooks.js
CHANGED
|
@@ -222,14 +222,24 @@ function encodeHookPayload(payload) {
|
|
|
222
222
|
}
|
|
223
223
|
return { bytes: encoder.encode((0, json_js_1.stringifyJSON)(payload)), contentType: 'application/json' };
|
|
224
224
|
}
|
|
225
|
+
const HOOK_SIGNATURE_HEADER = /^[A-Za-z0-9-]{1,64}$/;
|
|
225
226
|
/** Posts an event to an incoming hook. No API key is sent: the token in the path authenticates. */
|
|
226
227
|
function sendHook(client, operation, token, payload, options = {}) {
|
|
227
228
|
const run = async () => {
|
|
228
|
-
const { secret, eventId, contentType, ...requestOptions } = options;
|
|
229
|
+
const { secret, eventId, contentType, signatureHeader, ...requestOptions } = options;
|
|
230
|
+
const target = signatureHeader ?? operation.signatureHeader;
|
|
231
|
+
if (typeof target !== 'string' || !HOOK_SIGNATURE_HEADER.test(target)) {
|
|
232
|
+
throw new errors_js_1.ValidationError("signatureHeader must be 1 to 64 Latin letters, digits or hyphens, like the hook's signature_header.");
|
|
233
|
+
}
|
|
229
234
|
const encoded = encodeHookPayload(payload);
|
|
230
235
|
const headers = {};
|
|
231
|
-
if (secret !== undefined)
|
|
232
|
-
|
|
236
|
+
if (secret !== undefined) {
|
|
237
|
+
const lower = target.toLowerCase();
|
|
238
|
+
if (Object.entries(requestOptions.headers ?? {}).some(([name, value]) => name.toLowerCase() === lower && value != null)) {
|
|
239
|
+
throw new errors_js_1.ValidationError(`Pass either secret or the ${target} header, not both.`);
|
|
240
|
+
}
|
|
241
|
+
headers[target] = 'sha256=' + (await signHookPayload(encoded.bytes, secret));
|
|
242
|
+
}
|
|
233
243
|
if (eventId !== undefined && operation.eventIdHeader !== undefined)
|
|
234
244
|
headers[operation.eventIdHeader] = eventId;
|
|
235
245
|
return {
|
|
@@ -241,6 +251,10 @@ function sendHook(client, operation, token, payload, options = {}) {
|
|
|
241
251
|
headers,
|
|
242
252
|
auth: 'hook',
|
|
243
253
|
idempotencyHeader: operation.idempotencyHeader,
|
|
254
|
+
// The backend takes the id of a hook event from Idempotency-Key before X-Event-Id, so a random
|
|
255
|
+
// key would override the caller's event id: the event id is the default key. A key the caller
|
|
256
|
+
// gives (`idempotencyKey`, or the header per request or in the client's default headers) wins.
|
|
257
|
+
defaultIdempotencyKey: eventId,
|
|
244
258
|
options: requestOptions,
|
|
245
259
|
};
|
|
246
260
|
};
|
package/dist/esm/chat.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// Code generated by tungo-sdkgen. DO NOT EDIT.
|
|
2
2
|
import { StreamPromise } from './core.js';
|
|
3
|
+
import { debugJSON } from './json.js';
|
|
3
4
|
import { DecodeError, makeAPIError, parseErrorDetail } from './errors.js';
|
|
4
5
|
import { Stream, decodeJSONEvent } from './streaming.js';
|
|
5
6
|
/** Folds the events of one chat turn into a {@link ChatStreamResult}. */
|
|
@@ -82,7 +83,7 @@ export function chatTurnError(error, requestId, response) {
|
|
|
82
83
|
retryAfter: null,
|
|
83
84
|
rateLimit: response?.rateLimit ?? null,
|
|
84
85
|
headers: response?.headers ?? new Headers(),
|
|
85
|
-
body:
|
|
86
|
+
body: debugJSON(error),
|
|
86
87
|
extra: detail?.extra ?? {},
|
|
87
88
|
envelope: detail !== null,
|
|
88
89
|
});
|
|
@@ -123,7 +124,7 @@ export class ChatStream extends Stream {
|
|
|
123
124
|
/** Turn number from the `X-Turn-No` response header; null when absent. */
|
|
124
125
|
turnNo;
|
|
125
126
|
constructor(init) {
|
|
126
|
-
super(init, (event, response) => decodeJSONEvent(event, response));
|
|
127
|
+
super(init, (event, response) => decodeJSONEvent(event, response, true));
|
|
127
128
|
const dialogId = init.response.headers.get('x-dialog-id');
|
|
128
129
|
this.dialogId = dialogId === null || dialogId === '' ? null : dialogId;
|
|
129
130
|
const turnNo = init.response.headers.get('x-turn-no');
|
package/dist/esm/client.d.ts
CHANGED
|
@@ -87,7 +87,8 @@ export declare class Tungo {
|
|
|
87
87
|
}): APIPromise<T.BatchJob>;
|
|
88
88
|
/**
|
|
89
89
|
* Sends an event to an incoming automation hook (`/hooks/{token}`). With `secret`, the exact
|
|
90
|
-
* bytes sent are signed in the `X-Signature: sha256=<hex>` header
|
|
90
|
+
* bytes sent are signed in the `X-Signature: sha256=<hex>` header, or in `signatureHeader` for a
|
|
91
|
+
* hook created with its own `signature_header`. The API key is not sent.
|
|
91
92
|
* Same as `client.automations.postHook`.
|
|
92
93
|
*/
|
|
93
94
|
sendHook(token: string, payload: HookPayload, options?: SendHookOptions): APIPromise<T.AutomationHookAccepted>;
|
package/dist/esm/client.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import { APIClient, sleep, startTimer } from './core.js';
|
|
3
3
|
import { chatTurnError } from './chat.js';
|
|
4
4
|
import { AbortError, DecodeError, TimeoutError } from './errors.js';
|
|
5
|
+
import { debugJSON } from './json.js';
|
|
5
6
|
import { bytesToBase64, verifyWebhook } from './webhooks.js';
|
|
6
7
|
import * as R from './generated/resources.js';
|
|
7
8
|
const RUN_FINAL_STATES = ['done', 'error', 'skipped', 'cancelled'];
|
|
@@ -123,7 +124,8 @@ export class Tungo {
|
|
|
123
124
|
}
|
|
124
125
|
/**
|
|
125
126
|
* Sends an event to an incoming automation hook (`/hooks/{token}`). With `secret`, the exact
|
|
126
|
-
* bytes sent are signed in the `X-Signature: sha256=<hex>` header
|
|
127
|
+
* bytes sent are signed in the `X-Signature: sha256=<hex>` header, or in `signatureHeader` for a
|
|
128
|
+
* hook created with its own `signature_header`. The API key is not sent.
|
|
127
129
|
* Same as `client.automations.postHook`.
|
|
128
130
|
*/
|
|
129
131
|
sendHook(token, payload, options) {
|
|
@@ -151,7 +153,7 @@ export class Tungo {
|
|
|
151
153
|
return this.#poll('the automation run to finish', (requestOptions) => this.automations.getRun(companyId, runId, requestOptions).withResponse(), (run, response) => {
|
|
152
154
|
const state = run?.state;
|
|
153
155
|
if (typeof state !== 'string') {
|
|
154
|
-
throw new DecodeError('The automation run has no "state"', { status: response.status, requestId: response.requestId, body:
|
|
156
|
+
throw new DecodeError('The automation run has no "state"', { status: response.status, requestId: response.requestId, body: debugJSON(run) });
|
|
155
157
|
}
|
|
156
158
|
return RUN_FINAL_STATES.includes(state);
|
|
157
159
|
}, options);
|
|
@@ -161,7 +163,7 @@ export class Tungo {
|
|
|
161
163
|
return this.#poll('the batch job to finish', (requestOptions) => this.batches.get(companyId, batchId, requestOptions).withResponse(), (job, response) => {
|
|
162
164
|
const running = job?.running;
|
|
163
165
|
if (typeof running !== 'boolean') {
|
|
164
|
-
throw new DecodeError('The batch job has no "running" flag', { status: response.status, requestId: response.requestId, body:
|
|
166
|
+
throw new DecodeError('The batch job has no "running" flag', { status: response.status, requestId: response.requestId, body: debugJSON(job) });
|
|
165
167
|
}
|
|
166
168
|
return !running;
|
|
167
169
|
}, options);
|
package/dist/esm/core.d.ts
CHANGED
|
@@ -78,7 +78,10 @@ export interface RequestOptions {
|
|
|
78
78
|
maxRetries?: number | undefined;
|
|
79
79
|
/** Extra headers; a null value removes a default header. */
|
|
80
80
|
headers?: Record<string, string | null | undefined> | undefined;
|
|
81
|
-
/**
|
|
81
|
+
/**
|
|
82
|
+
* Your own `Idempotency-Key` for an operation that declares the header (without it the SDK
|
|
83
|
+
* generates one). Other operations do not send it and are not retried because of it.
|
|
84
|
+
*/
|
|
82
85
|
idempotencyKey?: string | undefined;
|
|
83
86
|
/** Cancels the request (and its retries and waits). It is combined with the timeout. */
|
|
84
87
|
signal?: AbortSignal | undefined;
|
|
@@ -106,6 +109,11 @@ export interface RequestSpec {
|
|
|
106
109
|
auth?: 'key' | 'public' | 'hook' | undefined;
|
|
107
110
|
/** Wire name of the idempotency header when the operation declares one. */
|
|
108
111
|
idempotencyHeader?: string | undefined;
|
|
112
|
+
/**
|
|
113
|
+
* Key sent in the idempotency header when the caller gives none (neither `idempotencyKey` nor the
|
|
114
|
+
* header itself, per request or in the client's default headers). Default: a random UUID.
|
|
115
|
+
*/
|
|
116
|
+
defaultIdempotencyKey?: string | undefined;
|
|
109
117
|
/** Use the long-running timeout by default. */
|
|
110
118
|
longRunning?: boolean | undefined;
|
|
111
119
|
/** The success response has no body. */
|
|
@@ -117,7 +125,6 @@ export interface WithResponse<T> {
|
|
|
117
125
|
data: T;
|
|
118
126
|
response: ResponseInfo;
|
|
119
127
|
}
|
|
120
|
-
/** Reads an environment variable on Node.js, Bun and Deno; undefined elsewhere or when empty. */
|
|
121
128
|
export declare function readEnv(name: string): string | undefined;
|
|
122
129
|
/** A random RFC 4122 version 4 UUID from the platform CSPRNG. */
|
|
123
130
|
export declare function uuid4(): string;
|
package/dist/esm/core.js
CHANGED
|
@@ -21,6 +21,87 @@ export const MAX_RETRY_AFTER_SECONDS = 60;
|
|
|
21
21
|
export const MAX_TIMER_MS = 2_147_483_647;
|
|
22
22
|
const USER_AGENT = 'tungo-sdk-typescript/' + VERSION;
|
|
23
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
|
+
}
|
|
24
105
|
export function readEnv(name) {
|
|
25
106
|
try {
|
|
26
107
|
const scope = globalThis;
|
|
@@ -36,6 +117,21 @@ export function readEnv(name) {
|
|
|
36
117
|
}
|
|
37
118
|
return undefined;
|
|
38
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
|
+
}
|
|
39
135
|
/** A random RFC 4122 version 4 UUID from the platform CSPRNG. */
|
|
40
136
|
export function uuid4() {
|
|
41
137
|
const bytes = new Uint8Array(16);
|
|
@@ -188,6 +284,29 @@ function causeText(cause) {
|
|
|
188
284
|
}
|
|
189
285
|
return cause.message;
|
|
190
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
|
+
}
|
|
191
310
|
function positive(value, fallback, name, zeroAllowed) {
|
|
192
311
|
if (value === undefined)
|
|
193
312
|
return fallback;
|
|
@@ -204,10 +323,23 @@ function retries(value, fallback) {
|
|
|
204
323
|
}
|
|
205
324
|
return value;
|
|
206
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
|
+
}
|
|
207
339
|
class HeaderBag {
|
|
208
340
|
#map = new Map();
|
|
209
341
|
set(name, value) {
|
|
210
|
-
if (
|
|
342
|
+
if (!sendableHeaderValue(value) || !/^[!#$%&'*+.^_|~0-9A-Za-z-]+$/.test(name)) {
|
|
211
343
|
throw new ValidationError('The header "' + name.replace(/[^ -~]/g, '?') + '" has an invalid name or value');
|
|
212
344
|
}
|
|
213
345
|
this.#map.set(name.toLowerCase(), [name, value]);
|
|
@@ -360,16 +492,29 @@ export class APIClient {
|
|
|
360
492
|
return new APIPromise(this.#requestJSON(spec));
|
|
361
493
|
}
|
|
362
494
|
/** Opens a server-sent event stream; `make` wraps the connection into the stream object. */
|
|
363
|
-
openStream(spec, make) {
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
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
|
+
}
|
|
373
518
|
}
|
|
374
519
|
async #requestJSON(spec) {
|
|
375
520
|
const x = await this.#exchange(spec, false);
|
|
@@ -428,19 +573,30 @@ export class APIClient {
|
|
|
428
573
|
if (key === undefined) {
|
|
429
574
|
throw new ConfigError('No API key: pass "apiKey" to the client or set the TUNGO_API_KEY environment variable');
|
|
430
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
|
+
}
|
|
431
580
|
if (this.#bearer)
|
|
432
581
|
bag.set('Authorization', 'Bearer ' + key);
|
|
433
582
|
else
|
|
434
583
|
bag.set('x-api-key', key);
|
|
435
584
|
}
|
|
436
|
-
|
|
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
|
+
}
|
|
437
594
|
if (options.idempotencyKey !== undefined) {
|
|
438
|
-
if (options.idempotencyKey === '')
|
|
439
|
-
throw new ValidationError('The idempotency key must not be empty');
|
|
440
595
|
bag.set(headerName, options.idempotencyKey);
|
|
441
596
|
}
|
|
442
|
-
else if (
|
|
443
|
-
|
|
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());
|
|
444
600
|
}
|
|
445
601
|
return { headers: bag.toRecord(), hasIdempotencyKey: bag.has(headerName) };
|
|
446
602
|
}
|
|
@@ -522,6 +678,24 @@ export class APIClient {
|
|
|
522
678
|
attempts: attempt + 1,
|
|
523
679
|
};
|
|
524
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
|
+
}
|
|
525
699
|
if (stream) {
|
|
526
700
|
const contentType = (response.headers.get('content-type') ?? '').trim().toLowerCase();
|
|
527
701
|
if (!contentType.startsWith('text/event-stream')) {
|
|
@@ -561,7 +735,7 @@ export class APIClient {
|
|
|
561
735
|
cause = 'timeout';
|
|
562
736
|
}
|
|
563
737
|
else {
|
|
564
|
-
failure = new ConnectionError('Could not reach the API for ' + route + ': ' +
|
|
738
|
+
failure = new ConnectionError('Could not reach the API for ' + route + ': ' + redactedCauseText(reason, this.baseUrl, url, spec), { cause: reason });
|
|
565
739
|
cause = 'connection_error';
|
|
566
740
|
}
|
|
567
741
|
}
|
package/dist/esm/errors.d.ts
CHANGED
|
@@ -79,6 +79,31 @@ export declare class DecodeError extends TungoError {
|
|
|
79
79
|
cause?: unknown;
|
|
80
80
|
});
|
|
81
81
|
}
|
|
82
|
+
/**
|
|
83
|
+
* A stream of items (not chat events; for example `feed.listEvents`) carried an `error` event: the
|
|
84
|
+
* server could not go on and ended the stream. It is thrown by the `for await` loop after the
|
|
85
|
+
* items that came before it. The stream did not finish: reconnect (from the cursor of the last
|
|
86
|
+
* item) to resume it.
|
|
87
|
+
*/
|
|
88
|
+
export declare class StreamError extends TungoError {
|
|
89
|
+
/** The machine-readable reason, for example `feed_failed`; null when the event had none. */
|
|
90
|
+
readonly code: string | null;
|
|
91
|
+
/** The text for people. */
|
|
92
|
+
readonly detail: string;
|
|
93
|
+
/** Request id: `request_id` of the event, else the `x-request-id` header. Quote it to support. */
|
|
94
|
+
readonly requestId: string | null;
|
|
95
|
+
/** Every other property of the event data. */
|
|
96
|
+
readonly extra: Record<string, unknown>;
|
|
97
|
+
/** The data of the event as received (possibly truncated to 2000 characters). */
|
|
98
|
+
readonly body: string;
|
|
99
|
+
constructor(init: {
|
|
100
|
+
code: string | null;
|
|
101
|
+
detail: string;
|
|
102
|
+
requestId: string | null;
|
|
103
|
+
extra: Record<string, unknown>;
|
|
104
|
+
body: string;
|
|
105
|
+
});
|
|
106
|
+
}
|
|
82
107
|
/** Why a webhook was rejected. */
|
|
83
108
|
export type WebhookVerificationReason = 'invalid_tolerance' | 'invalid_secret' | 'missing_header' | 'malformed_timestamp' | 'timestamp_too_old' | 'timestamp_too_new' | 'signature_mismatch' | 'invalid_payload';
|
|
84
109
|
/** A webhook failed verification. Never trust the payload when this is thrown. */
|