@tungoai/sdk 0.2.0 → 1.0.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 +90 -1
- package/README.kk.md +7 -5
- package/README.md +9 -7
- package/README.ru.md +7 -5
- package/dist/cjs/chat.js +3 -2
- package/dist/cjs/client.d.ts +6 -1
- package/dist/cjs/client.js +11 -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 +191 -2
- package/dist/cjs/generated/resources.js +197 -2
- package/dist/cjs/generated/types.d.ts +957 -428
- 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 +6 -1
- package/dist/esm/client.js +11 -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 +191 -2
- package/dist/esm/generated/resources.js +194 -1
- package/dist/esm/generated/types.d.ts +957 -428
- 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/core.js
CHANGED
|
@@ -34,6 +34,87 @@ exports.MAX_RETRY_AFTER_SECONDS = 60;
|
|
|
34
34
|
exports.MAX_TIMER_MS = 2_147_483_647;
|
|
35
35
|
const USER_AGENT = 'tungo-sdk-typescript/' + version_js_1.VERSION;
|
|
36
36
|
/** Reads an environment variable on Node.js, Bun and Deno; undefined elsewhere or when empty. */
|
|
37
|
+
/** Whether a stream call was answered with a stored result replayed by Idempotency-Key. */
|
|
38
|
+
function isReplayedJSON(headers) {
|
|
39
|
+
const mediaType = (headers.get('content-type') ?? '').split(';')[0] ?? '';
|
|
40
|
+
return mediaType.trim().toLowerCase() === 'application/json' && (headers.get('idempotent-replayed') ?? '').trim().toLowerCase() === 'true';
|
|
41
|
+
}
|
|
42
|
+
function isObject(value) {
|
|
43
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Turns a replayed ChatTurnResult into the event stream of the turn it stands for: text (the
|
|
47
|
+
* answer), proposal, question, citation, error, choice and next events, then done. The dialog id and
|
|
48
|
+
* the turn number, which a replay carries only in the body, become the X-Dialog-Id and X-Turn-No
|
|
49
|
+
* headers when they are missing: `headers` are those of the response with them, the other headers
|
|
50
|
+
* (Idempotent-Replayed among them) unchanged. Returns null when the body is not a chat turn result.
|
|
51
|
+
*/
|
|
52
|
+
function replayAsEventStream(response, text, requestId) {
|
|
53
|
+
let result;
|
|
54
|
+
try {
|
|
55
|
+
result = (0, json_js_1.parseJSON)(text);
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
if (!isObject(result))
|
|
61
|
+
return null;
|
|
62
|
+
const dialogId = result['dialog_id'];
|
|
63
|
+
if (typeof dialogId !== 'string')
|
|
64
|
+
return null;
|
|
65
|
+
const headers = new Headers(response.headers);
|
|
66
|
+
if ((headers.get('x-dialog-id') ?? '') === '')
|
|
67
|
+
headers.set('x-dialog-id', dialogId);
|
|
68
|
+
const turnNo = result['turn_no'];
|
|
69
|
+
if ((headers.get('x-turn-no') ?? '') === '' && (typeof turnNo === 'number' || typeof turnNo === 'bigint'))
|
|
70
|
+
headers.set('x-turn-no', String(turnNo));
|
|
71
|
+
const entries = (key) => {
|
|
72
|
+
const list = result[key];
|
|
73
|
+
return Array.isArray(list) ? list.filter(isObject) : [];
|
|
74
|
+
};
|
|
75
|
+
let body = '';
|
|
76
|
+
const emit = (type, event) => {
|
|
77
|
+
body += 'event: ' + type + '\ndata: ' + (0, json_js_1.stringifyJSON)({ ...event, type }) + '\n\n';
|
|
78
|
+
};
|
|
79
|
+
const answerValue = result['answer'];
|
|
80
|
+
const answer = typeof answerValue === 'string' ? answerValue : '';
|
|
81
|
+
if (answer !== '')
|
|
82
|
+
emit('text', { delta: answer });
|
|
83
|
+
for (const { id, ...rest } of entries('proposals'))
|
|
84
|
+
emit('proposal', { ...rest, proposal_id: id });
|
|
85
|
+
for (const question of entries('questions'))
|
|
86
|
+
emit('question', question);
|
|
87
|
+
for (const citation of entries('citations'))
|
|
88
|
+
emit('citation', citation);
|
|
89
|
+
for (const error of entries('errors'))
|
|
90
|
+
emit('error', { error, request_id: requestId });
|
|
91
|
+
const done = { answer };
|
|
92
|
+
const stopReason = result['stop_reason'];
|
|
93
|
+
if (typeof stopReason === 'string')
|
|
94
|
+
done['stop_reason'] = stopReason;
|
|
95
|
+
const usageValue = result['usage'];
|
|
96
|
+
if (isObject(usageValue)) {
|
|
97
|
+
const { cost_tiyn: cost, ...usage } = usageValue;
|
|
98
|
+
done['usage'] = usage;
|
|
99
|
+
if (cost !== undefined)
|
|
100
|
+
done['cost_tiyn'] = cost;
|
|
101
|
+
}
|
|
102
|
+
const pending = result['pending_question'];
|
|
103
|
+
if (isObject(pending)) {
|
|
104
|
+
emit('choice', pending);
|
|
105
|
+
done['choice_id'] = pending['choice_id'];
|
|
106
|
+
}
|
|
107
|
+
// A live turn ends its finished answer with next right before done; the stored result keeps it
|
|
108
|
+
// as followups and next_action.
|
|
109
|
+
const followups = Array.isArray(result['followups']) ? result['followups'] : [];
|
|
110
|
+
const action = result['next_action'];
|
|
111
|
+
if (followups.length > 0 || isObject(action))
|
|
112
|
+
emit('next', { followups, action: isObject(action) ? action : null });
|
|
113
|
+
emit('done', done);
|
|
114
|
+
const streamHeaders = new Headers(headers);
|
|
115
|
+
streamHeaders.set('content-type', 'text/event-stream');
|
|
116
|
+
return { response: new Response(body, { status: response.status, headers: streamHeaders }), headers };
|
|
117
|
+
}
|
|
37
118
|
function readEnv(name) {
|
|
38
119
|
try {
|
|
39
120
|
const scope = globalThis;
|
|
@@ -49,6 +130,21 @@ function readEnv(name) {
|
|
|
49
130
|
}
|
|
50
131
|
return undefined;
|
|
51
132
|
}
|
|
133
|
+
/**
|
|
134
|
+
* The `idempotency_key` field of a JSON object body (approving a proposal documents it as the same
|
|
135
|
+
* as the header), trimmed like the API trims it. The API prefers the header over the field, so a
|
|
136
|
+
* generated header would make the caller's own key useless. A key that cannot travel in a header
|
|
137
|
+
* (outside printable ASCII) is ignored here.
|
|
138
|
+
*/
|
|
139
|
+
function bodyIdempotencyKey(body) {
|
|
140
|
+
if (typeof body !== 'object' || body === null || Array.isArray(body))
|
|
141
|
+
return undefined;
|
|
142
|
+
const value = body['idempotency_key'];
|
|
143
|
+
if (typeof value !== 'string')
|
|
144
|
+
return undefined;
|
|
145
|
+
const key = value.trim();
|
|
146
|
+
return key !== '' && /^[\x20-\x7e]+$/.test(key) ? key : undefined;
|
|
147
|
+
}
|
|
52
148
|
/** A random RFC 4122 version 4 UUID from the platform CSPRNG. */
|
|
53
149
|
function uuid4() {
|
|
54
150
|
const bytes = new Uint8Array(16);
|
|
@@ -201,6 +297,29 @@ function causeText(cause) {
|
|
|
201
297
|
}
|
|
202
298
|
return cause.message;
|
|
203
299
|
}
|
|
300
|
+
/**
|
|
301
|
+
* The text of a transport failure without the request URL: a custom fetch (node-fetch, a proxy
|
|
302
|
+
* or tracing wrapper) may put the full URL into its message, and the path can carry a hook token
|
|
303
|
+
* and the query search text. The URL and the concrete path become the route template, and any
|
|
304
|
+
* other absolute URL and every path parameter value are cut out.
|
|
305
|
+
*/
|
|
306
|
+
function redactedCauseText(cause, baseUrl, url, spec) {
|
|
307
|
+
let text = causeText(cause);
|
|
308
|
+
const path = buildPath(spec.path, spec.pathParams);
|
|
309
|
+
const pathAndQuery = url.slice(baseUrl.length);
|
|
310
|
+
for (const concrete of [url, url.split('?')[0] ?? url, pathAndQuery, path]) {
|
|
311
|
+
if (concrete !== '' && concrete !== '/')
|
|
312
|
+
text = text.split(concrete).join(spec.path);
|
|
313
|
+
}
|
|
314
|
+
text = text.replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s"'<>]*/gi, '[url]');
|
|
315
|
+
for (const value of Object.values(spec.pathParams ?? {})) {
|
|
316
|
+
if (typeof value !== 'string' || value === '')
|
|
317
|
+
continue;
|
|
318
|
+
for (const form of new Set([value, encodeURIComponent(value)]))
|
|
319
|
+
text = text.split(form).join('[redacted]');
|
|
320
|
+
}
|
|
321
|
+
return text;
|
|
322
|
+
}
|
|
204
323
|
function positive(value, fallback, name, zeroAllowed) {
|
|
205
324
|
if (value === undefined)
|
|
206
325
|
return fallback;
|
|
@@ -217,10 +336,23 @@ function retries(value, fallback) {
|
|
|
217
336
|
}
|
|
218
337
|
return value;
|
|
219
338
|
}
|
|
339
|
+
/**
|
|
340
|
+
* Whether a header value can be sent at all: fetch refuses CR, LF and NUL, and a character above
|
|
341
|
+
* U+00FF (a Cyrillic look-alike pasted into a key) is not a byte, so fetch would throw a
|
|
342
|
+
* TypeError that looks like a network failure.
|
|
343
|
+
*/
|
|
344
|
+
function sendableHeaderValue(value) {
|
|
345
|
+
for (let i = 0; i < value.length; i++) {
|
|
346
|
+
const code = value.charCodeAt(i);
|
|
347
|
+
if (code === 0 || code === 10 || code === 13 || code > 0xff)
|
|
348
|
+
return false;
|
|
349
|
+
}
|
|
350
|
+
return true;
|
|
351
|
+
}
|
|
220
352
|
class HeaderBag {
|
|
221
353
|
#map = new Map();
|
|
222
354
|
set(name, value) {
|
|
223
|
-
if (
|
|
355
|
+
if (!sendableHeaderValue(value) || !/^[!#$%&'*+.^_|~0-9A-Za-z-]+$/.test(name)) {
|
|
224
356
|
throw new errors_js_1.ValidationError('The header "' + name.replace(/[^ -~]/g, '?') + '" has an invalid name or value');
|
|
225
357
|
}
|
|
226
358
|
this.#map.set(name.toLowerCase(), [name, value]);
|
|
@@ -375,16 +507,29 @@ class APIClient {
|
|
|
375
507
|
return new APIPromise(this.#requestJSON(spec));
|
|
376
508
|
}
|
|
377
509
|
/** Opens a server-sent event stream; `make` wraps the connection into the stream object. */
|
|
378
|
-
openStream(spec, make) {
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
510
|
+
async openStream(spec, make) {
|
|
511
|
+
// Checked before anything is sent: once the turn is posted it runs (and is billed) on the
|
|
512
|
+
// server, so a bad option found afterwards would cost a turn and leave the connection open.
|
|
513
|
+
const idleTimeout = positive(spec.options?.streamIdleTimeout, this.streamIdleTimeout, 'streamIdleTimeout', true);
|
|
514
|
+
const x = await this.#exchange(spec, true);
|
|
515
|
+
try {
|
|
516
|
+
return make({
|
|
517
|
+
response: x.info,
|
|
518
|
+
body: x.response.body,
|
|
519
|
+
controller: x.controller,
|
|
520
|
+
signal: spec.options?.signal ?? undefined,
|
|
521
|
+
detach: x.detach,
|
|
522
|
+
idleTimeout,
|
|
523
|
+
route: spec.method.toUpperCase() + ' ' + spec.path,
|
|
524
|
+
});
|
|
525
|
+
}
|
|
526
|
+
catch (error) {
|
|
527
|
+
// The stream object never came to be: nobody else can close the connection.
|
|
528
|
+
x.detach();
|
|
529
|
+
x.controller.abort();
|
|
530
|
+
x.response.body?.cancel().catch(() => undefined);
|
|
531
|
+
throw error;
|
|
532
|
+
}
|
|
388
533
|
}
|
|
389
534
|
async #requestJSON(spec) {
|
|
390
535
|
const x = await this.#exchange(spec, false);
|
|
@@ -443,19 +588,30 @@ class APIClient {
|
|
|
443
588
|
if (key === undefined) {
|
|
444
589
|
throw new errors_js_1.ConfigError('No API key: pass "apiKey" to the client or set the TUNGO_API_KEY environment variable');
|
|
445
590
|
}
|
|
591
|
+
if (!sendableHeaderValue(key)) {
|
|
592
|
+
// Never the key itself: only what is wrong with it.
|
|
593
|
+
throw new errors_js_1.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');
|
|
594
|
+
}
|
|
446
595
|
if (this.#bearer)
|
|
447
596
|
bag.set('Authorization', 'Bearer ' + key);
|
|
448
597
|
else
|
|
449
598
|
bag.set('x-api-key', key);
|
|
450
599
|
}
|
|
451
|
-
|
|
600
|
+
if (options.idempotencyKey === '')
|
|
601
|
+
throw new errors_js_1.ValidationError('The idempotency key must not be empty');
|
|
602
|
+
const headerName = spec.idempotencyHeader;
|
|
603
|
+
if (headerName === undefined) {
|
|
604
|
+
// The API ignores a key on an operation that declares none: sending one would make a retry
|
|
605
|
+
// look safe when it repeats the action.
|
|
606
|
+
bag.delete('Idempotency-Key');
|
|
607
|
+
return { headers: bag.toRecord(), hasIdempotencyKey: false };
|
|
608
|
+
}
|
|
452
609
|
if (options.idempotencyKey !== undefined) {
|
|
453
|
-
if (options.idempotencyKey === '')
|
|
454
|
-
throw new errors_js_1.ValidationError('The idempotency key must not be empty');
|
|
455
610
|
bag.set(headerName, options.idempotencyKey);
|
|
456
611
|
}
|
|
457
|
-
else if (
|
|
458
|
-
|
|
612
|
+
else if (!bag.has(headerName)) {
|
|
613
|
+
const fallback = spec.defaultIdempotencyKey !== undefined && spec.defaultIdempotencyKey !== '' ? spec.defaultIdempotencyKey : bodyIdempotencyKey(spec.body);
|
|
614
|
+
bag.set(headerName, fallback ?? uuid4());
|
|
459
615
|
}
|
|
460
616
|
return { headers: bag.toRecord(), hasIdempotencyKey: bag.has(headerName) };
|
|
461
617
|
}
|
|
@@ -537,6 +693,24 @@ class APIClient {
|
|
|
537
693
|
attempts: attempt + 1,
|
|
538
694
|
};
|
|
539
695
|
if (response.status >= 200 && response.status < 300) {
|
|
696
|
+
if (stream && isReplayedJSON(response.headers)) {
|
|
697
|
+
// A chat turn repeated with the same Idempotency-Key after it finished: the server
|
|
698
|
+
// answers the stored ChatTurnResult instead of a stream. The caller gets its events.
|
|
699
|
+
const replayed = await response.text();
|
|
700
|
+
const synthesized = replayAsEventStream(response, replayed, info.requestId);
|
|
701
|
+
if (synthesized === null) {
|
|
702
|
+
throw new errors_js_1.DecodeError('The response of ' + route + ' (status ' + response.status + ') replays a result that is not a chat turn', {
|
|
703
|
+
status: response.status,
|
|
704
|
+
requestId: info.requestId,
|
|
705
|
+
body: replayed,
|
|
706
|
+
});
|
|
707
|
+
}
|
|
708
|
+
info.headers = synthesized.headers;
|
|
709
|
+
keepOpen = true;
|
|
710
|
+
clearTimeout(timer);
|
|
711
|
+
this.#log({ kind: 'response', method, route: spec.path, attempt: attempt + 1, status: info.status, durationMs: Date.now() - started, requestId: info.requestId });
|
|
712
|
+
return { info, text: '', response: synthesized.response, controller, detach };
|
|
713
|
+
}
|
|
540
714
|
if (stream) {
|
|
541
715
|
const contentType = (response.headers.get('content-type') ?? '').trim().toLowerCase();
|
|
542
716
|
if (!contentType.startsWith('text/event-stream')) {
|
|
@@ -576,7 +750,7 @@ class APIClient {
|
|
|
576
750
|
cause = 'timeout';
|
|
577
751
|
}
|
|
578
752
|
else {
|
|
579
|
-
failure = new errors_js_1.ConnectionError('Could not reach the API for ' + route + ': ' +
|
|
753
|
+
failure = new errors_js_1.ConnectionError('Could not reach the API for ' + route + ': ' + redactedCauseText(reason, this.baseUrl, url, spec), { cause: reason });
|
|
580
754
|
cause = 'connection_error';
|
|
581
755
|
}
|
|
582
756
|
}
|
package/dist/cjs/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. */
|
package/dist/cjs/errors.js
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
// Code generated by tungo-sdkgen. DO NOT EDIT.
|
|
3
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
-
exports.UnavailableError = exports.InternalServerError = exports.LimitError = exports.GoneError = exports.ConflictError = exports.NotFoundError = exports.PermissionError = exports.PaymentRequiredError = exports.AuthenticationError = exports.InvalidRequestError = exports.APIError = exports.MoneyError = exports.WebhookVerificationError = exports.DecodeError = exports.AbortError = exports.TimeoutError = exports.ConnectionError = exports.ValidationError = exports.ConfigError = exports.TungoError = void 0;
|
|
3
|
+
exports.UnavailableError = exports.InternalServerError = exports.LimitError = exports.GoneError = exports.ConflictError = exports.NotFoundError = exports.PermissionError = exports.PaymentRequiredError = exports.AuthenticationError = exports.InvalidRequestError = exports.APIError = exports.MoneyError = exports.WebhookVerificationError = exports.StreamError = exports.DecodeError = exports.AbortError = exports.TimeoutError = exports.ConnectionError = exports.ValidationError = exports.ConfigError = exports.TungoError = void 0;
|
|
5
4
|
exports.parseRetryAfter = parseRetryAfter;
|
|
6
5
|
exports.parseRateLimit = parseRateLimit;
|
|
7
6
|
exports.errorTypeForStatus = errorTypeForStatus;
|
|
8
7
|
exports.parseErrorDetail = parseErrorDetail;
|
|
9
8
|
exports.makeAPIError = makeAPIError;
|
|
10
9
|
exports.apiErrorFromResponse = apiErrorFromResponse;
|
|
10
|
+
// Code generated by tungo-sdkgen. DO NOT EDIT.
|
|
11
|
+
const json_js_1 = require("./json.js");
|
|
11
12
|
/** Base class of every error thrown by the SDK. */
|
|
12
13
|
class TungoError extends Error {
|
|
13
14
|
constructor(message, options) {
|
|
@@ -85,6 +86,40 @@ class DecodeError extends TungoError {
|
|
|
85
86
|
}
|
|
86
87
|
}
|
|
87
88
|
exports.DecodeError = DecodeError;
|
|
89
|
+
/**
|
|
90
|
+
* A stream of items (not chat events; for example `feed.listEvents`) carried an `error` event: the
|
|
91
|
+
* server could not go on and ended the stream. It is thrown by the `for await` loop after the
|
|
92
|
+
* items that came before it. The stream did not finish: reconnect (from the cursor of the last
|
|
93
|
+
* item) to resume it.
|
|
94
|
+
*/
|
|
95
|
+
class StreamError extends TungoError {
|
|
96
|
+
/** The machine-readable reason, for example `feed_failed`; null when the event had none. */
|
|
97
|
+
code;
|
|
98
|
+
/** The text for people. */
|
|
99
|
+
detail;
|
|
100
|
+
/** Request id: `request_id` of the event, else the `x-request-id` header. Quote it to support. */
|
|
101
|
+
requestId;
|
|
102
|
+
/** Every other property of the event data. */
|
|
103
|
+
extra;
|
|
104
|
+
/** The data of the event as received (possibly truncated to 2000 characters). */
|
|
105
|
+
body;
|
|
106
|
+
constructor(init) {
|
|
107
|
+
let text = 'Tungo stream error';
|
|
108
|
+
if (init.code !== null)
|
|
109
|
+
text += ' (' + init.code + ')';
|
|
110
|
+
text += ': ' + init.detail;
|
|
111
|
+
if (init.requestId !== null)
|
|
112
|
+
text += ' [request id ' + init.requestId + ']';
|
|
113
|
+
super(text);
|
|
114
|
+
this.name = 'StreamError';
|
|
115
|
+
this.code = init.code;
|
|
116
|
+
this.detail = init.detail;
|
|
117
|
+
this.requestId = init.requestId;
|
|
118
|
+
this.extra = init.extra;
|
|
119
|
+
this.body = init.body.length > 2000 ? init.body.slice(0, 2000) : init.body;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
exports.StreamError = StreamError;
|
|
88
123
|
/** A webhook failed verification. Never trust the payload when this is thrown. */
|
|
89
124
|
class WebhookVerificationError extends TungoError {
|
|
90
125
|
reason;
|
|
@@ -387,7 +422,8 @@ function apiErrorFromResponse(status, headers, body, nowMs = Date.now()) {
|
|
|
387
422
|
};
|
|
388
423
|
let parsed;
|
|
389
424
|
try {
|
|
390
|
-
|
|
425
|
+
// parseJSON keeps an integer beyond 2^53 (a 64-bit amount in `extra`) exact, as a bigint.
|
|
426
|
+
parsed = (0, json_js_1.parseJSON)(body);
|
|
391
427
|
}
|
|
392
428
|
catch {
|
|
393
429
|
parsed = undefined;
|
|
@@ -117,6 +117,38 @@ export interface ChatListParams {
|
|
|
117
117
|
/** Сколько на странице: 1–100, по умолчанию 50 */
|
|
118
118
|
limit?: number | undefined;
|
|
119
119
|
}
|
|
120
|
+
/** Query parameters of `chat.listFiles`. */
|
|
121
|
+
export interface ChatListFilesParams {
|
|
122
|
+
/** next_cursor прошлой страницы; без него — самые новые файлы. Фильтры — те же, что у первой страницы */
|
|
123
|
+
cursor?: string | undefined;
|
|
124
|
+
/** Только из этого разговора */
|
|
125
|
+
dialog_id?: string | undefined;
|
|
126
|
+
/** Только этого формата: xlsx, docx, pdf или csv */
|
|
127
|
+
format?: T.ListCompanyChatFilesFormat | undefined;
|
|
128
|
+
/** Сколько на странице: 1–200, по умолчанию 50 */
|
|
129
|
+
limit?: number | undefined;
|
|
130
|
+
/** Подстрока имени файла, без учёта регистра */
|
|
131
|
+
q?: string | undefined;
|
|
132
|
+
}
|
|
133
|
+
/** Query parameters of `chat.listMentions`. */
|
|
134
|
+
export interface ChatListMentionsParams {
|
|
135
|
+
/** Сколько на каждый вид: 1–20, по умолчанию 8 */
|
|
136
|
+
limit?: number | undefined;
|
|
137
|
+
/** Что ищем: часть номера, названия, имени; у контрагента — от 2 знаков (или БИН цифрами). Пусто — свежие предложения и задания */
|
|
138
|
+
q?: string | undefined;
|
|
139
|
+
/** Виды через запятую; по умолчанию все. `proposal` — предложение (документ для 1С), id — его номер P-000123; `counterparty` — контрагент из 1С компании, id — его ссылка из поиска; `batch` — задание пачки (разбор выписки, в… */
|
|
140
|
+
types?: string | undefined;
|
|
141
|
+
}
|
|
142
|
+
/** Query parameters of `chat.getRatingOptions`. */
|
|
143
|
+
export interface ChatGetRatingOptionsParams {
|
|
144
|
+
/** Язык названий причин; по умолчанию ru */
|
|
145
|
+
lang?: T.ListCompanyChatRatingOptionsLang | undefined;
|
|
146
|
+
}
|
|
147
|
+
/** Query parameters of `chat.listSuggestions`. */
|
|
148
|
+
export interface ChatListSuggestionsParams {
|
|
149
|
+
/** Язык текстов — язык интерфейса кабинета. Не передан — язык ответов ИИ из профиля (`kk` — по-казахски, иначе по-русски) */
|
|
150
|
+
lang?: T.ListCompanyChatSuggestionsLang | undefined;
|
|
151
|
+
}
|
|
120
152
|
/** Query parameters of `chat.listEvents`. */
|
|
121
153
|
export interface ChatListEventsParams {
|
|
122
154
|
/** Номер хода (X-Turn-No), к которому переподключиться; без него — к текущему */
|
|
@@ -124,6 +156,10 @@ export interface ChatListEventsParams {
|
|
|
124
156
|
}
|
|
125
157
|
/** Query parameters of `proposals.list`. */
|
|
126
158
|
export interface ProposalsListParams {
|
|
159
|
+
/** true — только отправленные на одобрение и ещё не решённые; false — только остальные */
|
|
160
|
+
approval_requested?: T.ListCompanyProposalsApprovalRequested | undefined;
|
|
161
|
+
/** Только документы одного задания пачки (bat_…) — тот же состав, что в сводке задания и у «Одобрить и отправить в 1С». Не id задания — 400; задания нет — пустой список */
|
|
162
|
+
batch_id?: string | undefined;
|
|
127
163
|
/** next_cursor из ответа прошлой страницы; без него — первая (самая свежая) страница. Остальные фильтры — те же, что у первой страницы. */
|
|
128
164
|
cursor?: string | undefined;
|
|
129
165
|
/** Созданные не раньше этого дня (ГГГГ-ММ-ДД, день по Алматы) */
|
|
@@ -134,8 +170,10 @@ export interface ProposalsListParams {
|
|
|
134
170
|
kind?: string | undefined;
|
|
135
171
|
/** Сколько на странице: 1–100, по умолчанию 20 */
|
|
136
172
|
limit?: number | undefined;
|
|
137
|
-
/** Поиск без учёта регистра: номер предложения (P-…), номер документа 1С, контрагент (имя из превью),
|
|
173
|
+
/** Поиск без учёта регистра: номер предложения (P-…), номер документа 1С, контрагент (имя из превью), БИН/ИИН, сумма (как пишут: «150 000,50» или 150000.5) и другие реквизиты документа */
|
|
138
174
|
q?: string | undefined;
|
|
175
|
+
/** Только из этих источников (origin.source): один или несколько через запятую (chat, statement, esf, automation). Неизвестный — 400 */
|
|
176
|
+
source?: string | undefined;
|
|
139
177
|
/** Только в этих статусах: один или несколько через запятую (previewed, approved, rejected, committed, posted, verified, mismatch, failed); без него — все. Неизвестный — 400 */
|
|
140
178
|
status?: string | undefined;
|
|
141
179
|
}
|
|
@@ -536,6 +574,68 @@ export declare class ChatResource {
|
|
|
536
574
|
* Required permission: `chat.use`.
|
|
537
575
|
*/
|
|
538
576
|
countTokens(co: string, body: T.ChatTokenCountRequest, options?: RequestOptions): APIPromise<T.ChatTokenCount>;
|
|
577
|
+
/**
|
|
578
|
+
* Файлы от ИИ в своих разговорах, новые сверху
|
|
579
|
+
*
|
|
580
|
+
* Returns one page; iterate the result with `for await` to walk every item of every page.
|
|
581
|
+
*
|
|
582
|
+
* `GET /v1/companies/{co}/chat/files`
|
|
583
|
+
*
|
|
584
|
+
* Required permission: `chat.use`.
|
|
585
|
+
*/
|
|
586
|
+
listFiles(co: string, query?: ChatListFilesParams, options?: RequestOptions): PagePromise<T.ChatFileItem, T.ChatFileList>;
|
|
587
|
+
/**
|
|
588
|
+
* Every item of `listFiles`, across all pages. Pages are fetched lazily; leaving the loop stops fetching.
|
|
589
|
+
*/
|
|
590
|
+
listFilesAll(co: string, query?: ChatListFilesParams, options?: RequestOptions): AsyncGenerator<T.ChatFileItem, void, undefined>;
|
|
591
|
+
/**
|
|
592
|
+
* Что можно упомянуть через «@»
|
|
593
|
+
*
|
|
594
|
+
* `GET /v1/companies/{co}/chat/mentions`
|
|
595
|
+
*
|
|
596
|
+
* Required permission: `chat.use`.
|
|
597
|
+
*/
|
|
598
|
+
listMentions(co: string, query?: ChatListMentionsParams, options?: RequestOptions): APIPromise<T.ChatMentionSearch>;
|
|
599
|
+
/**
|
|
600
|
+
* Что нужно форме оценки: причины «вниз» и предел комментария
|
|
601
|
+
*
|
|
602
|
+
* `GET /v1/companies/{co}/chat/rating-options`
|
|
603
|
+
*
|
|
604
|
+
* Required permission: `chat.use`.
|
|
605
|
+
*/
|
|
606
|
+
getRatingOptions(co: string, query?: ChatGetRatingOptionsParams, options?: RequestOptions): APIPromise<T.ChatRatingOptions>;
|
|
607
|
+
/**
|
|
608
|
+
* Подсказки пустого чата
|
|
609
|
+
*
|
|
610
|
+
* `GET /v1/companies/{co}/chat/suggestions`
|
|
611
|
+
*
|
|
612
|
+
* Required permission: `chat.use`.
|
|
613
|
+
*/
|
|
614
|
+
listSuggestions(co: string, query?: ChatListSuggestionsParams, options?: RequestOptions): APIPromise<T.ChatSuggestions>;
|
|
615
|
+
/**
|
|
616
|
+
* Начать загрузку архива к сообщению
|
|
617
|
+
*
|
|
618
|
+
* `POST /v1/companies/{co}/chat/uploads`
|
|
619
|
+
*
|
|
620
|
+
* Required permission: `chat.use`.
|
|
621
|
+
*/
|
|
622
|
+
createUpload(co: string, body: T.ChatUploadCreate, options?: RequestOptions): APIPromise<T.ChatUpload>;
|
|
623
|
+
/**
|
|
624
|
+
* Отменить загрузку архива
|
|
625
|
+
*
|
|
626
|
+
* `DELETE /v1/companies/{co}/chat/uploads/{upload}`
|
|
627
|
+
*
|
|
628
|
+
* Required permission: `chat.use`.
|
|
629
|
+
*/
|
|
630
|
+
deleteUpload(co: string, upload: string, options?: RequestOptions): APIPromise<void>;
|
|
631
|
+
/**
|
|
632
|
+
* Часть архива
|
|
633
|
+
*
|
|
634
|
+
* `PUT /v1/companies/{co}/chat/uploads/{upload}/parts/{n}`
|
|
635
|
+
*
|
|
636
|
+
* Required permission: `chat.use`.
|
|
637
|
+
*/
|
|
638
|
+
putUploadPart(co: string, upload: string, n: string, options?: RequestOptions): APIPromise<T.ChatUploadPart>;
|
|
539
639
|
/**
|
|
540
640
|
* Разговор целиком
|
|
541
641
|
*
|
|
@@ -590,6 +690,38 @@ export declare class ChatResource {
|
|
|
590
690
|
* Required permission: `chat.use`.
|
|
591
691
|
*/
|
|
592
692
|
listEvents(co: string, id: string, query?: ChatListEventsParams, options?: RequestOptions): ChatStreamPromise;
|
|
693
|
+
/**
|
|
694
|
+
* Оценить ответ ИИ: палец вверх или вниз
|
|
695
|
+
*
|
|
696
|
+
* `PUT /v1/companies/{co}/chat/{id}/messages/{turn}/rating`
|
|
697
|
+
*
|
|
698
|
+
* Required permission: `chat.use`.
|
|
699
|
+
*/
|
|
700
|
+
rateMessage(co: string, id: string, turn: string, body: T.ChatMessageRatingBody, options?: RequestOptions): APIPromise<T.ChatMessageRated>;
|
|
701
|
+
/**
|
|
702
|
+
* Снять свою оценку ответа
|
|
703
|
+
*
|
|
704
|
+
* `DELETE /v1/companies/{co}/chat/{id}/messages/{turn}/rating`
|
|
705
|
+
*
|
|
706
|
+
* Required permission: `chat.use`.
|
|
707
|
+
*/
|
|
708
|
+
deleteMessageRating(co: string, id: string, turn: string, options?: RequestOptions): APIPromise<T.ChatMessageRated>;
|
|
709
|
+
/**
|
|
710
|
+
* Оценить разговор целиком: от 1 до 5
|
|
711
|
+
*
|
|
712
|
+
* `PUT /v1/companies/{co}/chat/{id}/rating`
|
|
713
|
+
*
|
|
714
|
+
* Required permission: `chat.use`.
|
|
715
|
+
*/
|
|
716
|
+
rate(co: string, id: string, body: T.ChatDialogRatingBody, options?: RequestOptions): APIPromise<T.ChatDialogRated>;
|
|
717
|
+
/**
|
|
718
|
+
* Не сейчас: закрыть предложение оценить разговор
|
|
719
|
+
*
|
|
720
|
+
* `POST /v1/companies/{co}/chat/{id}/rating/dismiss`
|
|
721
|
+
*
|
|
722
|
+
* Required permission: `chat.use`.
|
|
723
|
+
*/
|
|
724
|
+
dismissRating(co: string, id: string, options?: RequestOptions): APIPromise<T.ChatRatingDismissed>;
|
|
593
725
|
/**
|
|
594
726
|
* Остановить ход или закрыть открытый вопрос
|
|
595
727
|
*
|
|
@@ -598,6 +730,14 @@ export declare class ChatResource {
|
|
|
598
730
|
* Required permission: `chat.use`.
|
|
599
731
|
*/
|
|
600
732
|
stop(co: string, id: string, options?: RequestOptions): APIPromise<T.ChatStopResult>;
|
|
733
|
+
/**
|
|
734
|
+
* Перевести размышление на русский
|
|
735
|
+
*
|
|
736
|
+
* `POST /v1/companies/{co}/chat/{id}/thinking/{tid}/translate`
|
|
737
|
+
*
|
|
738
|
+
* Required permission: `chat.use`.
|
|
739
|
+
*/
|
|
740
|
+
translateThinking(co: string, id: string, tid: string, options?: RequestOptions): APIPromise<T.ChatThinkingTranslation>;
|
|
601
741
|
}
|
|
602
742
|
/** Предложения документов ИИ-бухгалтера: просмотр, одобрение записи в 1С и отклонение */
|
|
603
743
|
export declare class ProposalsResource {
|
|
@@ -649,6 +789,14 @@ export declare class ProposalsResource {
|
|
|
649
789
|
* Required permission: `proposals.approve`.
|
|
650
790
|
*/
|
|
651
791
|
reject(co: string, id: string, body: T.RejectRequest, options?: RequestOptions): APIPromise<T.ProposalDecision>;
|
|
792
|
+
/**
|
|
793
|
+
* Отправить на одобрение
|
|
794
|
+
*
|
|
795
|
+
* `POST /v1/companies/{co}/proposals/{id}/request-approval`
|
|
796
|
+
*
|
|
797
|
+
* Required permission: `proposals.create`.
|
|
798
|
+
*/
|
|
799
|
+
requestApproval(co: string, id: string, body?: T.ProposalApprovalRequestBody, options?: RequestOptions): APIPromise<T.ProposalApprovalRequestResult>;
|
|
652
800
|
}
|
|
653
801
|
/** Лента событий и предложений компании (страницы и живой поток SSE) */
|
|
654
802
|
export declare class FeedResource {
|
|
@@ -869,7 +1017,8 @@ export declare class AutomationsResource {
|
|
|
869
1017
|
* Принять событие по адресу хука
|
|
870
1018
|
*
|
|
871
1019
|
* The body is sent as it is (text or bytes) or serialised as JSON. With `options.secret` the exact bytes
|
|
872
|
-
* are signed in the `X-Signature: sha256=<hex>` header
|
|
1020
|
+
* are signed in the `X-Signature: sha256=<hex>` header, or in `options.signatureHeader` for a hook created with
|
|
1021
|
+
* its own `signature_header`. The API key is never sent to this endpoint.
|
|
873
1022
|
*
|
|
874
1023
|
* `POST /hooks/{token}`
|
|
875
1024
|
*/
|
|
@@ -1057,3 +1206,43 @@ export declare class AutomationsResource {
|
|
|
1057
1206
|
*/
|
|
1058
1207
|
putAutonomy(co: string, body: T.CompanyAutonomyInput, options?: RequestOptions): APIPromise<T.CompanyAutonomy>;
|
|
1059
1208
|
}
|
|
1209
|
+
/** Публичная проверка электронной подписи документов Tungo: по коду, по файлу, по блоку QR и ключи подписи (без ключа API) */
|
|
1210
|
+
export declare class VerificationResource {
|
|
1211
|
+
#private;
|
|
1212
|
+
constructor(client: APIClient);
|
|
1213
|
+
/**
|
|
1214
|
+
* Ключи подписи QR (JWKS)
|
|
1215
|
+
*
|
|
1216
|
+
* `GET /v1/public/verify-keys`
|
|
1217
|
+
*/
|
|
1218
|
+
listKeys(options?: RequestOptions): APIPromise<T.VerifyKeys>;
|
|
1219
|
+
/**
|
|
1220
|
+
* Проверить подписанный блок QR
|
|
1221
|
+
*
|
|
1222
|
+
* `POST /v1/public/verify/qr`
|
|
1223
|
+
*/
|
|
1224
|
+
verifyQr(body: T.VerifyQrInput, options?: RequestOptions): APIPromise<T.VerifyQrResult>;
|
|
1225
|
+
/**
|
|
1226
|
+
* Проверка подписи документа по коду
|
|
1227
|
+
*
|
|
1228
|
+
* `GET /v1/public/verify/{code}`
|
|
1229
|
+
*/
|
|
1230
|
+
get(code: string, options?: RequestOptions): APIPromise<T.PublicVerification>;
|
|
1231
|
+
/**
|
|
1232
|
+
* Сверить файл с подписанным
|
|
1233
|
+
*
|
|
1234
|
+
* `POST /v1/public/verify/{code}/check`
|
|
1235
|
+
*/
|
|
1236
|
+
check(code: string, body: T.VerifyCheckInput, options?: RequestOptions): APIPromise<T.VerifyCheck>;
|
|
1237
|
+
}
|
|
1238
|
+
/** Публичный список загрузок: расширение 1С и Tungo Connector (без ключа API) */
|
|
1239
|
+
export declare class ReleasesResource {
|
|
1240
|
+
#private;
|
|
1241
|
+
constructor(client: APIClient);
|
|
1242
|
+
/**
|
|
1243
|
+
* Что скачать
|
|
1244
|
+
*
|
|
1245
|
+
* `GET /v1/public/downloads`
|
|
1246
|
+
*/
|
|
1247
|
+
list(options?: RequestOptions): APIPromise<T.Downloads>;
|
|
1248
|
+
}
|