@tungoai/sdk 0.0.0-stage → 0.2.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 +40 -0
- package/LICENSE +21 -0
- package/README.kk.md +327 -0
- package/README.md +346 -2
- package/README.ru.md +327 -0
- package/dist/cjs/chat.d.ts +85 -0
- package/dist/cjs/chat.js +151 -0
- package/dist/cjs/client.d.ts +116 -0
- package/dist/cjs/client.js +223 -0
- package/dist/cjs/core.d.ts +210 -0
- package/dist/cjs/core.js +605 -0
- package/dist/cjs/errors.d.ts +212 -0
- package/dist/cjs/errors.js +410 -0
- package/dist/cjs/generated/resources.d.ts +1059 -0
- package/dist/cjs/generated/resources.js +1064 -0
- package/dist/cjs/generated/types.d.ts +4927 -0
- package/dist/cjs/generated/types.js +11 -0
- package/dist/cjs/index.d.ts +12 -0
- package/dist/cjs/index.js +80 -0
- package/dist/cjs/json.d.ts +10 -0
- package/dist/cjs/json.js +120 -0
- package/dist/cjs/money.d.ts +32 -0
- package/dist/cjs/money.js +141 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/pagination.d.ts +47 -0
- package/dist/cjs/pagination.js +113 -0
- package/dist/cjs/streaming.d.ts +74 -0
- package/dist/cjs/streaming.js +253 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +6 -0
- package/dist/cjs/webhooks.d.ts +74 -0
- package/dist/cjs/webhooks.js +248 -0
- package/dist/esm/chat.d.ts +85 -0
- package/dist/esm/chat.js +143 -0
- package/dist/esm/client.d.ts +116 -0
- package/dist/esm/client.js +219 -0
- package/dist/esm/core.d.ts +210 -0
- package/dist/esm/core.js +589 -0
- package/dist/esm/errors.d.ts +212 -0
- package/dist/esm/errors.js +381 -0
- package/dist/esm/generated/resources.d.ts +1059 -0
- package/dist/esm/generated/resources.js +1048 -0
- package/dist/esm/generated/types.d.ts +4927 -0
- package/dist/esm/generated/types.js +10 -0
- package/dist/esm/index.d.ts +12 -0
- package/dist/esm/index.js +11 -0
- package/dist/esm/json.d.ts +10 -0
- package/dist/esm/json.js +116 -0
- package/dist/esm/money.d.ts +32 -0
- package/dist/esm/money.js +137 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/pagination.d.ts +47 -0
- package/dist/esm/pagination.js +107 -0
- package/dist/esm/streaming.d.ts +74 -0
- package/dist/esm/streaming.js +247 -0
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +3 -0
- package/dist/esm/webhooks.d.ts +74 -0
- package/dist/esm/webhooks.js +239 -0
- package/package.json +67 -4
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { type APIPromise, type ClientOptions, type RequestOptions, type RequestSpec } from './core.js';
|
|
2
|
+
import { type ChatStreamCallbacks, type ChatStreamPromise, type ChatStreamResult } from './chat.js';
|
|
3
|
+
import { type HeadersLike, type HookPayload, type SendHookOptions, type VerifyWebhookOptions } from './webhooks.js';
|
|
4
|
+
import * as R from './generated/resources.js';
|
|
5
|
+
import type * as T from './generated/types.js';
|
|
6
|
+
/** Options of the wait helpers. */
|
|
7
|
+
export interface WaitOptions {
|
|
8
|
+
/**
|
|
9
|
+
* Overall deadline in milliseconds; a TimeoutError is thrown when it passes, also in the middle
|
|
10
|
+
* of a poll request or of its retries. Default: 600 000. `Infinity` waits without a deadline.
|
|
11
|
+
*/
|
|
12
|
+
timeout?: number | undefined;
|
|
13
|
+
/** First pause between polls in milliseconds; it grows by half each time. Default: 1000. */
|
|
14
|
+
pollInterval?: number | undefined;
|
|
15
|
+
/** Longest pause between polls in milliseconds. Default: 5000. */
|
|
16
|
+
maxPollInterval?: number | undefined;
|
|
17
|
+
/** Cancels the wait. */
|
|
18
|
+
signal?: AbortSignal | undefined;
|
|
19
|
+
}
|
|
20
|
+
/** A chat message: plain text, or the full request without the `stream` flag. */
|
|
21
|
+
export type ChatInput = string | Omit<T.ChatMessageRequest, 'stream'>;
|
|
22
|
+
/**
|
|
23
|
+
* The Tungo Platform API client.
|
|
24
|
+
*
|
|
25
|
+
* Create one instance and share it: it is immutable and safe to use concurrently. Resources
|
|
26
|
+
* (`client.companies`, `client.chat`, ...) mirror the API one to one; the methods on the client
|
|
27
|
+
* itself are shortcuts for common tasks.
|
|
28
|
+
*/
|
|
29
|
+
export declare class Tungo {
|
|
30
|
+
#private;
|
|
31
|
+
/** Организации (workspace), доступные ключу API */
|
|
32
|
+
readonly workspaces: R.WorkspacesResource;
|
|
33
|
+
/** Компании организации и их карточки */
|
|
34
|
+
readonly companies: R.CompaniesResource;
|
|
35
|
+
/** Баланс платформы, книга движений, отчёты о расходе, лимиты, аудит и тарифы моделей */
|
|
36
|
+
readonly platform: R.PlatformResource;
|
|
37
|
+
/** Сведения о текущем ключе API и статистика его расхода */
|
|
38
|
+
readonly apiKeys: R.ApiKeysResource;
|
|
39
|
+
/** Исходящие вебхуки организации (Svix): адреса, каталог событий, доставки и проверка подписи */
|
|
40
|
+
readonly webhooks: R.WebhooksResource;
|
|
41
|
+
/** Диалоги с ИИ-бухгалтером: вопросы, потоковый чат (SSE), подсчёт токенов и история */
|
|
42
|
+
readonly chat: R.ChatResource;
|
|
43
|
+
/** Предложения документов ИИ-бухгалтера: просмотр, одобрение записи в 1С и отклонение */
|
|
44
|
+
readonly proposals: R.ProposalsResource;
|
|
45
|
+
/** Лента событий и предложений компании (страницы и живой поток SSE) */
|
|
46
|
+
readonly feed: R.FeedResource;
|
|
47
|
+
/** Пачки обработки банковских выписок, входящих ЭСФ и DirectBank */
|
|
48
|
+
readonly batches: R.BatchesResource;
|
|
49
|
+
/** Входящие и исходящие электронные счета-фактуры (ИС ЭСФ) */
|
|
50
|
+
readonly esf: R.EsfResource;
|
|
51
|
+
/** Налоговые формы (ФНО 100.00 и др.): сборка, проверка ИСНА и разрывы данных */
|
|
52
|
+
readonly forms: R.FormsResource;
|
|
53
|
+
/** Состояние подключения компании к базе 1С */
|
|
54
|
+
readonly onec: R.OnecResource;
|
|
55
|
+
/** Автоматизации компании: входящие хуки, сценарии, цепочки шагов, запуски и уровень автономности ИИ */
|
|
56
|
+
readonly automations: R.AutomationsResource;
|
|
57
|
+
constructor(options?: ClientOptions);
|
|
58
|
+
/** Base URL the client talks to. */
|
|
59
|
+
get baseUrl(): string;
|
|
60
|
+
/**
|
|
61
|
+
* Performs an arbitrary API call with the client's authentication, retries, timeouts and error
|
|
62
|
+
* handling. Use it for endpoints this SDK version does not cover yet.
|
|
63
|
+
*/
|
|
64
|
+
request<Result = unknown>(spec: RequestSpec): APIPromise<Result>;
|
|
65
|
+
/**
|
|
66
|
+
* Asks the assistant one question and waits for the complete answer (no streaming).
|
|
67
|
+
* If the turn reports an error, the matching typed APIError is thrown; its `partialResult`
|
|
68
|
+
* holds the turn as returned.
|
|
69
|
+
*/
|
|
70
|
+
ask(companyId: string, message: ChatInput, options?: RequestOptions): Promise<T.ChatTurnResult>;
|
|
71
|
+
/** Asks the assistant and streams the events of the turn as they are produced. */
|
|
72
|
+
streamChat(companyId: string, message: ChatInput, options?: RequestOptions): ChatStreamPromise;
|
|
73
|
+
/**
|
|
74
|
+
* Streams a chat turn, calling the callbacks as events arrive, and returns the assembled turn.
|
|
75
|
+
* A mid-stream `error` event is thrown as the matching typed APIError.
|
|
76
|
+
*/
|
|
77
|
+
streamChatWithResult(companyId: string, message: ChatInput, callbacks?: ChatStreamCallbacks, options?: RequestOptions): Promise<ChatStreamResult>;
|
|
78
|
+
/** Answers a clarifying question of the assistant (a `choice` event) and waits for the rest of the turn. */
|
|
79
|
+
answerQuestion(companyId: string, dialogId: string, choiceId: string, answers: T.ChatChoiceAnswer[], options?: RequestOptions): APIPromise<T.ChatTurnResult>;
|
|
80
|
+
/**
|
|
81
|
+
* Uploads a bank statement for processing into proposals. `content` is the file bytes, or a
|
|
82
|
+
* string: base64 of the file by default, or the statement text itself with `{ text: true }`.
|
|
83
|
+
*/
|
|
84
|
+
uploadBankStatement(companyId: string, fileName: string, content: string | Uint8Array | ArrayBuffer, options?: RequestOptions & {
|
|
85
|
+
text?: boolean | undefined;
|
|
86
|
+
limit?: number | undefined;
|
|
87
|
+
}): APIPromise<T.BatchJob>;
|
|
88
|
+
/**
|
|
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. The API key is not sent.
|
|
91
|
+
* Same as `client.automations.postHook`.
|
|
92
|
+
*/
|
|
93
|
+
sendHook(token: string, payload: HookPayload, options?: SendHookOptions): APIPromise<T.AutomationHookAccepted>;
|
|
94
|
+
/**
|
|
95
|
+
* Verifies an outgoing webhook and returns the typed event. Uses `options.secret`, else the
|
|
96
|
+
* client's webhook secret. Throws a WebhookVerificationError when the webhook is not authentic.
|
|
97
|
+
*/
|
|
98
|
+
verifyWebhook(body: string | Uint8Array | ArrayBuffer, headers: HeadersLike, options?: VerifyWebhookOptions & {
|
|
99
|
+
secret?: string | undefined;
|
|
100
|
+
}): Promise<T.WebhookEvent>;
|
|
101
|
+
/** Starts a scenario run and waits until it finishes (see {@link Tungo.waitForRun}). */
|
|
102
|
+
runScenarioAndWait(companyId: string, scenarioId: string, body?: T.AutomationScenarioRunInput, options?: WaitOptions): Promise<T.AutomationRunDetail>;
|
|
103
|
+
/**
|
|
104
|
+
* Polls an automation run until it reaches a final state (done, error, skipped, cancelled). A state this
|
|
105
|
+
* SDK version does not know is treated as "still running". Throws a TimeoutError at the deadline.
|
|
106
|
+
*/
|
|
107
|
+
waitForRun(companyId: string, runId: string, options?: WaitOptions): Promise<T.AutomationRunDetail>;
|
|
108
|
+
/** Polls a batch job until it stops running. Throws a TimeoutError at the deadline. */
|
|
109
|
+
waitForBatch(companyId: string, batchId: string, options?: WaitOptions): Promise<T.BatchJob>;
|
|
110
|
+
/** A description without secrets (the API key is never included). */
|
|
111
|
+
toJSON(): {
|
|
112
|
+
baseUrl: string;
|
|
113
|
+
timeout: number;
|
|
114
|
+
maxRetries: number;
|
|
115
|
+
};
|
|
116
|
+
}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Tungo = void 0;
|
|
4
|
+
// Code generated by tungo-sdkgen. DO NOT EDIT.
|
|
5
|
+
const core_js_1 = require("./core.js");
|
|
6
|
+
const chat_js_1 = require("./chat.js");
|
|
7
|
+
const errors_js_1 = require("./errors.js");
|
|
8
|
+
const webhooks_js_1 = require("./webhooks.js");
|
|
9
|
+
const R = require("./generated/resources.js");
|
|
10
|
+
const RUN_FINAL_STATES = ['done', 'error', 'skipped', 'cancelled'];
|
|
11
|
+
function chatBody(message) {
|
|
12
|
+
return typeof message === 'string' ? { message } : message;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The Tungo Platform API client.
|
|
16
|
+
*
|
|
17
|
+
* Create one instance and share it: it is immutable and safe to use concurrently. Resources
|
|
18
|
+
* (`client.companies`, `client.chat`, ...) mirror the API one to one; the methods on the client
|
|
19
|
+
* itself are shortcuts for common tasks.
|
|
20
|
+
*/
|
|
21
|
+
class Tungo {
|
|
22
|
+
/** Организации (workspace), доступные ключу API */
|
|
23
|
+
workspaces;
|
|
24
|
+
/** Компании организации и их карточки */
|
|
25
|
+
companies;
|
|
26
|
+
/** Баланс платформы, книга движений, отчёты о расходе, лимиты, аудит и тарифы моделей */
|
|
27
|
+
platform;
|
|
28
|
+
/** Сведения о текущем ключе API и статистика его расхода */
|
|
29
|
+
apiKeys;
|
|
30
|
+
/** Исходящие вебхуки организации (Svix): адреса, каталог событий, доставки и проверка подписи */
|
|
31
|
+
webhooks;
|
|
32
|
+
/** Диалоги с ИИ-бухгалтером: вопросы, потоковый чат (SSE), подсчёт токенов и история */
|
|
33
|
+
chat;
|
|
34
|
+
/** Предложения документов ИИ-бухгалтера: просмотр, одобрение записи в 1С и отклонение */
|
|
35
|
+
proposals;
|
|
36
|
+
/** Лента событий и предложений компании (страницы и живой поток SSE) */
|
|
37
|
+
feed;
|
|
38
|
+
/** Пачки обработки банковских выписок, входящих ЭСФ и DirectBank */
|
|
39
|
+
batches;
|
|
40
|
+
/** Входящие и исходящие электронные счета-фактуры (ИС ЭСФ) */
|
|
41
|
+
esf;
|
|
42
|
+
/** Налоговые формы (ФНО 100.00 и др.): сборка, проверка ИСНА и разрывы данных */
|
|
43
|
+
forms;
|
|
44
|
+
/** Состояние подключения компании к базе 1С */
|
|
45
|
+
onec;
|
|
46
|
+
/** Автоматизации компании: входящие хуки, сценарии, цепочки шагов, запуски и уровень автономности ИИ */
|
|
47
|
+
automations;
|
|
48
|
+
#client;
|
|
49
|
+
constructor(options = {}) {
|
|
50
|
+
const client = new core_js_1.APIClient(options);
|
|
51
|
+
this.#client = client;
|
|
52
|
+
this.workspaces = new R.WorkspacesResource(client);
|
|
53
|
+
this.companies = new R.CompaniesResource(client);
|
|
54
|
+
this.platform = new R.PlatformResource(client);
|
|
55
|
+
this.apiKeys = new R.ApiKeysResource(client);
|
|
56
|
+
this.webhooks = new R.WebhooksResource(client);
|
|
57
|
+
this.chat = new R.ChatResource(client);
|
|
58
|
+
this.proposals = new R.ProposalsResource(client);
|
|
59
|
+
this.feed = new R.FeedResource(client);
|
|
60
|
+
this.batches = new R.BatchesResource(client);
|
|
61
|
+
this.esf = new R.EsfResource(client);
|
|
62
|
+
this.forms = new R.FormsResource(client);
|
|
63
|
+
this.onec = new R.OnecResource(client);
|
|
64
|
+
this.automations = new R.AutomationsResource(client);
|
|
65
|
+
}
|
|
66
|
+
/** Base URL the client talks to. */
|
|
67
|
+
get baseUrl() {
|
|
68
|
+
return this.#client.baseUrl;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Performs an arbitrary API call with the client's authentication, retries, timeouts and error
|
|
72
|
+
* handling. Use it for endpoints this SDK version does not cover yet.
|
|
73
|
+
*/
|
|
74
|
+
request(spec) {
|
|
75
|
+
return this.#client.request(spec);
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Asks the assistant one question and waits for the complete answer (no streaming).
|
|
79
|
+
* If the turn reports an error, the matching typed APIError is thrown; its `partialResult`
|
|
80
|
+
* holds the turn as returned.
|
|
81
|
+
*/
|
|
82
|
+
async ask(companyId, message, options) {
|
|
83
|
+
const { data, response } = await this.chat.create(companyId, chatBody(message), options).withResponse();
|
|
84
|
+
const first = Array.isArray(data.errors) ? data.errors[0] : undefined;
|
|
85
|
+
if (first !== undefined) {
|
|
86
|
+
const failure = (0, chat_js_1.chatTurnError)(first, null, response);
|
|
87
|
+
failure.partialResult = data;
|
|
88
|
+
throw failure;
|
|
89
|
+
}
|
|
90
|
+
return data;
|
|
91
|
+
}
|
|
92
|
+
/** Asks the assistant and streams the events of the turn as they are produced. */
|
|
93
|
+
streamChat(companyId, message, options) {
|
|
94
|
+
return this.chat.stream(companyId, chatBody(message), options);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Streams a chat turn, calling the callbacks as events arrive, and returns the assembled turn.
|
|
98
|
+
* A mid-stream `error` event is thrown as the matching typed APIError.
|
|
99
|
+
*/
|
|
100
|
+
streamChatWithResult(companyId, message, callbacks, options) {
|
|
101
|
+
return this.chat.stream(companyId, chatBody(message), options).finalResult(callbacks);
|
|
102
|
+
}
|
|
103
|
+
/** Answers a clarifying question of the assistant (a `choice` event) and waits for the rest of the turn. */
|
|
104
|
+
answerQuestion(companyId, dialogId, choiceId, answers, options) {
|
|
105
|
+
return this.chat.answer(companyId, dialogId, { choice_id: choiceId, answers }, options);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Uploads a bank statement for processing into proposals. `content` is the file bytes, or a
|
|
109
|
+
* string: base64 of the file by default, or the statement text itself with `{ text: true }`.
|
|
110
|
+
*/
|
|
111
|
+
uploadBankStatement(companyId, fileName, content, options = {}) {
|
|
112
|
+
const { text, limit, ...requestOptions } = options;
|
|
113
|
+
const body = { file_name: fileName };
|
|
114
|
+
if (typeof content === 'string') {
|
|
115
|
+
if (text === true)
|
|
116
|
+
body.text = content;
|
|
117
|
+
else
|
|
118
|
+
body.file = content;
|
|
119
|
+
}
|
|
120
|
+
else {
|
|
121
|
+
body.file = (0, webhooks_js_1.bytesToBase64)(content instanceof ArrayBuffer ? new Uint8Array(content) : content);
|
|
122
|
+
}
|
|
123
|
+
if (limit !== undefined)
|
|
124
|
+
body.limit = limit;
|
|
125
|
+
return this.batches.createBankStatement(companyId, body, requestOptions);
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Sends an event to an incoming automation hook (`/hooks/{token}`). With `secret`, the exact
|
|
129
|
+
* bytes sent are signed in the `X-Signature: sha256=<hex>` header. The API key is not sent.
|
|
130
|
+
* Same as `client.automations.postHook`.
|
|
131
|
+
*/
|
|
132
|
+
sendHook(token, payload, options) {
|
|
133
|
+
return this.automations.postHook(token, payload, options);
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Verifies an outgoing webhook and returns the typed event. Uses `options.secret`, else the
|
|
137
|
+
* client's webhook secret. Throws a WebhookVerificationError when the webhook is not authentic.
|
|
138
|
+
*/
|
|
139
|
+
async verifyWebhook(body, headers, options = {}) {
|
|
140
|
+
const { secret, ...rest } = options;
|
|
141
|
+
return (0, webhooks_js_1.verifyWebhook)(body, headers, this.#client.webhookSecret(secret), rest);
|
|
142
|
+
}
|
|
143
|
+
/** Starts a scenario run and waits until it finishes (see {@link Tungo.waitForRun}). */
|
|
144
|
+
async runScenarioAndWait(companyId, scenarioId, body, options = {}) {
|
|
145
|
+
const requestOptions = { signal: options.signal };
|
|
146
|
+
const started = await this.automations.runScenario(companyId, scenarioId, body, requestOptions);
|
|
147
|
+
return this.waitForRun(companyId, started.id, options);
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Polls an automation run until it reaches a final state (done, error, skipped, cancelled). A state this
|
|
151
|
+
* SDK version does not know is treated as "still running". Throws a TimeoutError at the deadline.
|
|
152
|
+
*/
|
|
153
|
+
waitForRun(companyId, runId, options = {}) {
|
|
154
|
+
return this.#poll('the automation run to finish', (requestOptions) => this.automations.getRun(companyId, runId, requestOptions).withResponse(), (run, response) => {
|
|
155
|
+
const state = run?.state;
|
|
156
|
+
if (typeof state !== 'string') {
|
|
157
|
+
throw new errors_js_1.DecodeError('The automation run has no "state"', { status: response.status, requestId: response.requestId, body: JSON.stringify(run) ?? '' });
|
|
158
|
+
}
|
|
159
|
+
return RUN_FINAL_STATES.includes(state);
|
|
160
|
+
}, options);
|
|
161
|
+
}
|
|
162
|
+
/** Polls a batch job until it stops running. Throws a TimeoutError at the deadline. */
|
|
163
|
+
waitForBatch(companyId, batchId, options = {}) {
|
|
164
|
+
return this.#poll('the batch job to finish', (requestOptions) => this.batches.get(companyId, batchId, requestOptions).withResponse(), (job, response) => {
|
|
165
|
+
const running = job?.running;
|
|
166
|
+
if (typeof running !== 'boolean') {
|
|
167
|
+
throw new errors_js_1.DecodeError('The batch job has no "running" flag', { status: response.status, requestId: response.requestId, body: JSON.stringify(job) ?? '' });
|
|
168
|
+
}
|
|
169
|
+
return !running;
|
|
170
|
+
}, options);
|
|
171
|
+
}
|
|
172
|
+
async #poll(what, load, finished, options) {
|
|
173
|
+
const timeout = options.timeout ?? 600_000;
|
|
174
|
+
const outer = options.signal ?? undefined;
|
|
175
|
+
if (outer !== undefined && outer.aborted)
|
|
176
|
+
throw new errors_js_1.AbortError('The wait was aborted', { cause: outer.reason });
|
|
177
|
+
const deadline = Date.now() + timeout;
|
|
178
|
+
let pause = options.pollInterval ?? 1000;
|
|
179
|
+
const longest = Math.max(pause, options.maxPollInterval ?? 5000);
|
|
180
|
+
// One signal ends everything the wait does (a poll request, its retries, the pause between
|
|
181
|
+
// polls) at the deadline, so the wait cannot outlive it by a request timeout or by retries.
|
|
182
|
+
const controller = new AbortController();
|
|
183
|
+
let expired = false;
|
|
184
|
+
const timer = (0, core_js_1.startTimer)(() => {
|
|
185
|
+
expired = true;
|
|
186
|
+
controller.abort();
|
|
187
|
+
}, timeout);
|
|
188
|
+
const onAbort = () => {
|
|
189
|
+
controller.abort(outer?.reason);
|
|
190
|
+
};
|
|
191
|
+
if (outer !== undefined)
|
|
192
|
+
outer.addEventListener('abort', onAbort, { once: true });
|
|
193
|
+
const late = (cause) => new errors_js_1.TimeoutError('Timed out after ' + timeout + ' ms waiting for ' + what, timeout, { cause });
|
|
194
|
+
try {
|
|
195
|
+
for (;;) {
|
|
196
|
+
const { data, response } = await load({ signal: controller.signal });
|
|
197
|
+
if (finished(data, response))
|
|
198
|
+
return data;
|
|
199
|
+
const left = deadline - Date.now();
|
|
200
|
+
if (left <= 0)
|
|
201
|
+
throw late();
|
|
202
|
+
await (0, core_js_1.sleep)(Math.min(pause, left), controller.signal);
|
|
203
|
+
pause = Math.min(pause * 1.5, longest);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
catch (cause) {
|
|
207
|
+
// The deadline aborted whatever was pending: report the deadline, not the abort.
|
|
208
|
+
if (expired && cause instanceof errors_js_1.AbortError && !(outer !== undefined && outer.aborted))
|
|
209
|
+
throw late(cause);
|
|
210
|
+
throw cause;
|
|
211
|
+
}
|
|
212
|
+
finally {
|
|
213
|
+
clearTimeout(timer);
|
|
214
|
+
if (outer !== undefined)
|
|
215
|
+
outer.removeEventListener('abort', onAbort);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
/** A description without secrets (the API key is never included). */
|
|
219
|
+
toJSON() {
|
|
220
|
+
return { baseUrl: this.#client.baseUrl, timeout: this.#client.timeout, maxRetries: this.#client.maxRetries };
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
exports.Tungo = Tungo;
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import { TungoError } from './errors.js';
|
|
2
|
+
import type { ResponseInfo, StreamInit, Stream } from './streaming.js';
|
|
3
|
+
/** The production API host. */
|
|
4
|
+
export declare const DEFAULT_BASE_URL = "https://api.tungo.kz";
|
|
5
|
+
/** Default timeout of an ordinary request, in milliseconds. */
|
|
6
|
+
export declare const DEFAULT_TIMEOUT = 60000;
|
|
7
|
+
/** Default timeout of a non-streaming chat turn, in milliseconds. */
|
|
8
|
+
export declare const DEFAULT_LONG_RUNNING_TIMEOUT = 600000;
|
|
9
|
+
/** Default number of retries (so 3 attempts in total). */
|
|
10
|
+
export declare const DEFAULT_MAX_RETRIES = 2;
|
|
11
|
+
/** Default idle timeout of a stream, in milliseconds. */
|
|
12
|
+
export declare const DEFAULT_STREAM_IDLE_TIMEOUT = 120000;
|
|
13
|
+
/** A server-requested delay above this many seconds is not slept: the error is raised instead. */
|
|
14
|
+
export declare const MAX_RETRY_AFTER_SECONDS = 60;
|
|
15
|
+
/**
|
|
16
|
+
* The longest delay a platform timer supports, in milliseconds (2^31 - 1, about 24.8 days).
|
|
17
|
+
* A timeout above it, `Infinity` included, means "no time limit": no timer is started.
|
|
18
|
+
*/
|
|
19
|
+
export declare const MAX_TIMER_MS = 2147483647;
|
|
20
|
+
/** The `fetch` function the client uses; pass your own to add a proxy, tracing or a mock. */
|
|
21
|
+
export type Fetch = (input: string, init: RequestInit) => Promise<Response>;
|
|
22
|
+
/** What the optional `logger` receives. It never contains credentials, header values or hook tokens. */
|
|
23
|
+
export interface LogEvent {
|
|
24
|
+
kind: 'request' | 'response' | 'retry' | 'error';
|
|
25
|
+
method: string;
|
|
26
|
+
/** The path template, e.g. `/v1/companies/{co}`; parameter values are not included. */
|
|
27
|
+
route: string;
|
|
28
|
+
/** 1 for the first attempt. */
|
|
29
|
+
attempt: number;
|
|
30
|
+
status?: number;
|
|
31
|
+
durationMs?: number;
|
|
32
|
+
requestId?: string | null;
|
|
33
|
+
/** For `retry`: how long the client waits before the next attempt. */
|
|
34
|
+
delayMs?: number;
|
|
35
|
+
error?: TungoError;
|
|
36
|
+
}
|
|
37
|
+
/** Client configuration. Every field is optional. */
|
|
38
|
+
export interface ClientOptions {
|
|
39
|
+
/** API key (`tg_...`). Default: the `TUNGO_API_KEY` environment variable. */
|
|
40
|
+
apiKey?: string | undefined;
|
|
41
|
+
/** Base URL of the API. Default: `TUNGO_BASE_URL`, else `https://api.tungo.kz`. */
|
|
42
|
+
baseUrl?: string | undefined;
|
|
43
|
+
/** Webhook signing secret (`whsec_...`) used by `verifyWebhook`. Default: `TUNGO_WEBHOOK_SECRET`. */
|
|
44
|
+
webhookSecret?: string | undefined;
|
|
45
|
+
/**
|
|
46
|
+
* Timeout of one request in milliseconds, including reading the body. Default: 60 000.
|
|
47
|
+
* It must be greater than zero (0 is rejected, it does not mean "no timeout"); `Infinity`, or
|
|
48
|
+
* any value above {@link MAX_TIMER_MS}, disables the time limit. It does not apply to
|
|
49
|
+
* non-streaming chat turns, which have their own `longRunningTimeout`.
|
|
50
|
+
*/
|
|
51
|
+
timeout?: number | undefined;
|
|
52
|
+
/** Timeout of a non-streaming chat turn in milliseconds, with the same rules as `timeout`. Default: 600 000. */
|
|
53
|
+
longRunningTimeout?: number | undefined;
|
|
54
|
+
/** How many times a failed request is retried when repeating it is safe. Default: 2. */
|
|
55
|
+
maxRetries?: number | undefined;
|
|
56
|
+
/**
|
|
57
|
+
* Milliseconds a stream may stay silent before it fails with a TimeoutError. Default: 120 000.
|
|
58
|
+
* 0, `Infinity` or a value above {@link MAX_TIMER_MS} disables the check.
|
|
59
|
+
*/
|
|
60
|
+
streamIdleTimeout?: number | undefined;
|
|
61
|
+
/** Headers added to every request. */
|
|
62
|
+
defaultHeaders?: Record<string, string> | undefined;
|
|
63
|
+
/** Custom `fetch` implementation. Default: the global `fetch`. */
|
|
64
|
+
fetch?: Fetch | undefined;
|
|
65
|
+
/** How the API key is sent: the `x-api-key` header (default) or `Authorization: Bearer`. */
|
|
66
|
+
authScheme?: 'x-api-key' | 'bearer' | undefined;
|
|
67
|
+
/** Receives one event per request, response, retry and failure. */
|
|
68
|
+
logger?: ((event: LogEvent) => void) | undefined;
|
|
69
|
+
}
|
|
70
|
+
/** Options accepted by every method as its last argument. */
|
|
71
|
+
export interface RequestOptions {
|
|
72
|
+
/**
|
|
73
|
+
* Timeout of this request in milliseconds (for a stream: the time allowed to connect). It wins
|
|
74
|
+
* over both client timeouts. Greater than zero; `Infinity` disables the time limit.
|
|
75
|
+
*/
|
|
76
|
+
timeout?: number | undefined;
|
|
77
|
+
/** Retries for this request. */
|
|
78
|
+
maxRetries?: number | undefined;
|
|
79
|
+
/** Extra headers; a null value removes a default header. */
|
|
80
|
+
headers?: Record<string, string | null | undefined> | undefined;
|
|
81
|
+
/** Your own `Idempotency-Key`. Without it the SDK generates one for operations that declare the header. */
|
|
82
|
+
idempotencyKey?: string | undefined;
|
|
83
|
+
/** Cancels the request (and its retries and waits). It is combined with the timeout. */
|
|
84
|
+
signal?: AbortSignal | undefined;
|
|
85
|
+
/** For streams: milliseconds without data before the stream fails. */
|
|
86
|
+
streamIdleTimeout?: number | undefined;
|
|
87
|
+
}
|
|
88
|
+
/** Description of one HTTP call. The generated resource methods build these. */
|
|
89
|
+
export interface RequestSpec {
|
|
90
|
+
method: string;
|
|
91
|
+
/** Path template such as `/v1/companies/{co}`. */
|
|
92
|
+
path: string;
|
|
93
|
+
/** Values of the path parameters; each is validated and percent-encoded as one segment. */
|
|
94
|
+
pathParams?: Record<string, string> | undefined;
|
|
95
|
+
/** Query parameters; null and undefined values are omitted, arrays repeat the key. */
|
|
96
|
+
query?: object | undefined;
|
|
97
|
+
/** JSON body. */
|
|
98
|
+
body?: unknown;
|
|
99
|
+
/** Exact bytes to send instead of a JSON body. */
|
|
100
|
+
rawBody?: Uint8Array | string | undefined;
|
|
101
|
+
/** Content type of `rawBody`. */
|
|
102
|
+
contentType?: string | undefined;
|
|
103
|
+
/** Operation-specific headers. */
|
|
104
|
+
headers?: Record<string, string | undefined> | undefined;
|
|
105
|
+
/** `key`: send the API key. `public` and `hook`: never send credentials. Default: `key`. */
|
|
106
|
+
auth?: 'key' | 'public' | 'hook' | undefined;
|
|
107
|
+
/** Wire name of the idempotency header when the operation declares one. */
|
|
108
|
+
idempotencyHeader?: string | undefined;
|
|
109
|
+
/** Use the long-running timeout by default. */
|
|
110
|
+
longRunning?: boolean | undefined;
|
|
111
|
+
/** The success response has no body. */
|
|
112
|
+
emptyResult?: boolean | undefined;
|
|
113
|
+
options?: RequestOptions | undefined;
|
|
114
|
+
}
|
|
115
|
+
/** A decoded response together with its status and headers. */
|
|
116
|
+
export interface WithResponse<T> {
|
|
117
|
+
data: T;
|
|
118
|
+
response: ResponseInfo;
|
|
119
|
+
}
|
|
120
|
+
/** Reads an environment variable on Node.js, Bun and Deno; undefined elsewhere or when empty. */
|
|
121
|
+
export declare function readEnv(name: string): string | undefined;
|
|
122
|
+
/** A random RFC 4122 version 4 UUID from the platform CSPRNG. */
|
|
123
|
+
export declare function uuid4(): string;
|
|
124
|
+
/**
|
|
125
|
+
* Percent-encodes a value as ONE path segment (`/`, `?`, `#`, spaces, CR/LF and non-ASCII are all
|
|
126
|
+
* encoded). An empty value, `.` and `..` are rejected because they would change the path.
|
|
127
|
+
*/
|
|
128
|
+
export declare function encodePathSegment(value: unknown, name?: string): string;
|
|
129
|
+
/** Fills a path template (`/v1/companies/{co}`) with encoded parameter values. */
|
|
130
|
+
export declare function buildPath(template: string, params: Record<string, string> | undefined): string;
|
|
131
|
+
/**
|
|
132
|
+
* Builds a query string (without the leading `?`): booleans as `true`/`false`, dates as RFC 3339,
|
|
133
|
+
* arrays as repeated keys, null and undefined omitted, `+` encoded as `%2B`.
|
|
134
|
+
*/
|
|
135
|
+
export declare function buildQuery(query: object | undefined): string;
|
|
136
|
+
/** Delay before retry number `attempt` (0-based), in milliseconds: min(0.5 s * 2^attempt, 8 s) * [0.75, 1]. */
|
|
137
|
+
export declare function backoffDelay(attempt: number, random?: () => number): number;
|
|
138
|
+
/** Statuses after which a request may be repeated. */
|
|
139
|
+
export declare function isRetryableStatus(status: number): boolean;
|
|
140
|
+
/**
|
|
141
|
+
* The retry rule: the failure must be transient (a retryable status, a connection error or a
|
|
142
|
+
* timeout) AND repeating the request must be safe (GET, HEAD, PUT, DELETE, or any request that
|
|
143
|
+
* carries an idempotency key).
|
|
144
|
+
*/
|
|
145
|
+
export declare function shouldRetry(method: string, hasIdempotencyKey: boolean, cause: number | 'connection_error' | 'timeout'): boolean;
|
|
146
|
+
/**
|
|
147
|
+
* Starts a timer, or none (undefined) when the delay is infinite or longer than the platform can
|
|
148
|
+
* count: `setTimeout` would fire such a timer at once instead of never.
|
|
149
|
+
*/
|
|
150
|
+
export declare function startTimer(callback: () => void, ms: number): ReturnType<typeof setTimeout> | undefined;
|
|
151
|
+
/**
|
|
152
|
+
* Waits `ms` milliseconds; rejects with an AbortError as soon as the signal aborts. A delay above
|
|
153
|
+
* {@link MAX_TIMER_MS} waits until the signal aborts.
|
|
154
|
+
*/
|
|
155
|
+
export declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
|
|
156
|
+
/**
|
|
157
|
+
* A promise of a decoded response that also gives access to the raw response:
|
|
158
|
+
* `await client.companies.get(id)` yields the data, `.withResponse()` adds status, headers,
|
|
159
|
+
* request id and rate-limit information of that very response.
|
|
160
|
+
*/
|
|
161
|
+
export declare class APIPromise<T> extends Promise<T> {
|
|
162
|
+
#private;
|
|
163
|
+
constructor(result: Promise<WithResponse<T>>);
|
|
164
|
+
/** The decoded data together with the status, headers, request id and rate limit of the response. */
|
|
165
|
+
withResponse(): Promise<WithResponse<T>>;
|
|
166
|
+
/** Only the status, headers, request id and rate limit of the response. */
|
|
167
|
+
asResponse(): Promise<ResponseInfo>;
|
|
168
|
+
then<A = T, B = never>(onfulfilled?: ((value: T) => A | PromiseLike<A>) | null, onrejected?: ((reason: unknown) => B | PromiseLike<B>) | null): Promise<A | B>;
|
|
169
|
+
catch<B = never>(onrejected?: ((reason: unknown) => B | PromiseLike<B>) | null): Promise<T | B>;
|
|
170
|
+
finally(onfinally?: (() => void) | null): Promise<T>;
|
|
171
|
+
static get [Symbol.species](): PromiseConstructor;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* A promise of an open stream that can also be iterated directly:
|
|
175
|
+
* `for await (const event of client.feed.listEvents(co))`. Awaiting it gives the stream object
|
|
176
|
+
* (with `response`, `close()` and, for chat streams, `dialogId` and `turnNo`).
|
|
177
|
+
*/
|
|
178
|
+
export declare class StreamPromise<T, S extends Stream<T> = Stream<T>> extends Promise<S> implements AsyncIterable<T> {
|
|
179
|
+
#private;
|
|
180
|
+
constructor(stream: Promise<S>);
|
|
181
|
+
then<A = S, B = never>(onfulfilled?: ((value: S) => A | PromiseLike<A>) | null, onrejected?: ((reason: unknown) => B | PromiseLike<B>) | null): Promise<A | B>;
|
|
182
|
+
catch<B = never>(onrejected?: ((reason: unknown) => B | PromiseLike<B>) | null): Promise<S | B>;
|
|
183
|
+
finally(onfinally?: (() => void) | null): Promise<S>;
|
|
184
|
+
[Symbol.asyncIterator](): AsyncGenerator<T, void, undefined>;
|
|
185
|
+
static get [Symbol.species](): PromiseConstructor;
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* The HTTP engine shared by all resources: configuration, authentication, retries, timeouts,
|
|
189
|
+
* cancellation and decoding. It is immutable after construction and safe to share.
|
|
190
|
+
*/
|
|
191
|
+
export declare class APIClient {
|
|
192
|
+
#private;
|
|
193
|
+
/** Base URL without a trailing slash. */
|
|
194
|
+
readonly baseUrl: string;
|
|
195
|
+
/** Default request timeout in milliseconds. */
|
|
196
|
+
readonly timeout: number;
|
|
197
|
+
/** Default timeout of non-streaming chat turns in milliseconds. */
|
|
198
|
+
readonly longRunningTimeout: number;
|
|
199
|
+
/** Default number of retries. */
|
|
200
|
+
readonly maxRetries: number;
|
|
201
|
+
/** Default idle timeout of streams in milliseconds. */
|
|
202
|
+
readonly streamIdleTimeout: number;
|
|
203
|
+
constructor(options?: ClientOptions);
|
|
204
|
+
/** The webhook secret to use: the explicit one, else the client's; a ConfigError when there is none. */
|
|
205
|
+
webhookSecret(explicit?: string): string;
|
|
206
|
+
/** Performs a request and decodes the JSON response. */
|
|
207
|
+
request<T>(spec: RequestSpec): APIPromise<T>;
|
|
208
|
+
/** Opens a server-sent event stream; `make` wraps the connection into the stream object. */
|
|
209
|
+
openStream<S>(spec: RequestSpec, make: (init: StreamInit) => S): Promise<S>;
|
|
210
|
+
}
|