@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
package/dist/esm/chat.js
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// Code generated by tungo-sdkgen. DO NOT EDIT.
|
|
2
|
+
import { StreamPromise } from './core.js';
|
|
3
|
+
import { DecodeError, makeAPIError, parseErrorDetail } from './errors.js';
|
|
4
|
+
import { Stream, decodeJSONEvent } from './streaming.js';
|
|
5
|
+
/** Folds the events of one chat turn into a {@link ChatStreamResult}. */
|
|
6
|
+
export class ChatAccumulator {
|
|
7
|
+
#segments = [];
|
|
8
|
+
#events = [];
|
|
9
|
+
#done = null;
|
|
10
|
+
#error = null;
|
|
11
|
+
/** Adds one event. Unknown event types are kept in `events` and otherwise ignored. */
|
|
12
|
+
push(event, callbacks = {}) {
|
|
13
|
+
this.#events.push(event);
|
|
14
|
+
callbacks.onEvent?.(event);
|
|
15
|
+
switch (event.type) {
|
|
16
|
+
case 'text':
|
|
17
|
+
this.#segments.push({ step: event.step, delta: event.delta });
|
|
18
|
+
callbacks.onTextDelta?.(event.delta, event);
|
|
19
|
+
break;
|
|
20
|
+
case 'progress':
|
|
21
|
+
this.#segments = this.#segments.filter((s) => s.step === undefined || event.step === undefined || s.step !== event.step);
|
|
22
|
+
callbacks.onProgress?.(event);
|
|
23
|
+
break;
|
|
24
|
+
case 'thinking':
|
|
25
|
+
callbacks.onThinkingDelta?.(event.delta, event);
|
|
26
|
+
break;
|
|
27
|
+
case 'tool':
|
|
28
|
+
callbacks.onTool?.(event);
|
|
29
|
+
break;
|
|
30
|
+
case 'error':
|
|
31
|
+
if (this.#error === null)
|
|
32
|
+
this.#error = event;
|
|
33
|
+
break;
|
|
34
|
+
case 'done':
|
|
35
|
+
this.#done = event;
|
|
36
|
+
break;
|
|
37
|
+
default:
|
|
38
|
+
break;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** True once the `done` event has arrived: the server finished the turn. */
|
|
42
|
+
get completed() {
|
|
43
|
+
return this.#done !== null;
|
|
44
|
+
}
|
|
45
|
+
/** The turn as accumulated so far. */
|
|
46
|
+
result(meta = {}) {
|
|
47
|
+
const done = this.#done;
|
|
48
|
+
let text = '';
|
|
49
|
+
for (const s of this.#segments)
|
|
50
|
+
text += s.delta;
|
|
51
|
+
if (done !== null && typeof done.answer === 'string')
|
|
52
|
+
text = done.answer;
|
|
53
|
+
return {
|
|
54
|
+
text,
|
|
55
|
+
dialogId: meta.dialogId ?? null,
|
|
56
|
+
turnNo: meta.turnNo ?? null,
|
|
57
|
+
stopReason: done !== null && typeof done.stop_reason === 'string' ? done.stop_reason : null,
|
|
58
|
+
costTiyn: done !== null && done.cost_tiyn !== undefined && done.cost_tiyn !== null ? done.cost_tiyn : null,
|
|
59
|
+
usage: done !== null && done.usage !== undefined && done.usage !== null ? done.usage : null,
|
|
60
|
+
choiceId: done !== null && typeof done.choice_id === 'string' ? done.choice_id : null,
|
|
61
|
+
events: this.#events.slice(),
|
|
62
|
+
error: this.#error,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Converts a chat `error` object (`{ type, code, message, ... }`, from a stream event or from
|
|
68
|
+
* `ChatTurnResult.errors`) into the typed error of the class an HTTP error response with the same
|
|
69
|
+
* `error.type` produces. Its `status` is undefined: the HTTP response that carried the turn was
|
|
70
|
+
* successful, so there is no error status to report. `response` supplies the headers, the request
|
|
71
|
+
* id and the rate limit.
|
|
72
|
+
*/
|
|
73
|
+
export function chatTurnError(error, requestId, response) {
|
|
74
|
+
const detail = parseErrorDetail(error);
|
|
75
|
+
return makeAPIError({
|
|
76
|
+
status: undefined,
|
|
77
|
+
type: detail?.type ?? 'api_error',
|
|
78
|
+
code: detail?.code ?? null,
|
|
79
|
+
detail: detail?.detail ?? 'The chat turn failed',
|
|
80
|
+
requestId: requestId ?? response?.requestId ?? null,
|
|
81
|
+
fields: detail?.fields ?? [],
|
|
82
|
+
retryAfter: null,
|
|
83
|
+
rateLimit: response?.rateLimit ?? null,
|
|
84
|
+
headers: response?.headers ?? new Headers(),
|
|
85
|
+
body: JSON.stringify(error) ?? '',
|
|
86
|
+
extra: detail?.extra ?? {},
|
|
87
|
+
envelope: detail !== null,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Consumes a chat event stream to its end and returns the assembled turn. A mid-stream `error`
|
|
92
|
+
* event makes it throw the matching typed {@link APIError}, and a stream that ends without its
|
|
93
|
+
* `done` event (a dropped connection, a proxy that cut it) a {@link DecodeError}: a partial text
|
|
94
|
+
* is never returned as a finished turn. Both errors carry what was accumulated in `partialResult`.
|
|
95
|
+
* When `events` is a {@link ChatStream}, `dialogId` and `turnNo` are filled from the response headers.
|
|
96
|
+
*/
|
|
97
|
+
export async function accumulateChatStream(events, callbacks = {}) {
|
|
98
|
+
const accumulator = new ChatAccumulator();
|
|
99
|
+
for await (const event of events)
|
|
100
|
+
accumulator.push(event, callbacks);
|
|
101
|
+
const source = events instanceof ChatStream ? events : undefined;
|
|
102
|
+
const result = accumulator.result(source === undefined ? {} : { dialogId: source.dialogId, turnNo: source.turnNo });
|
|
103
|
+
if (result.error !== null) {
|
|
104
|
+
const failure = chatTurnError(result.error.error, result.error.request_id ?? null, source?.response);
|
|
105
|
+
failure.partialResult = result;
|
|
106
|
+
throw failure;
|
|
107
|
+
}
|
|
108
|
+
if (!accumulator.completed) {
|
|
109
|
+
const failure = new DecodeError('The chat stream ended before completion: no "done" event was received', {
|
|
110
|
+
status: source?.response.status,
|
|
111
|
+
requestId: source?.response.requestId ?? null,
|
|
112
|
+
body: '',
|
|
113
|
+
});
|
|
114
|
+
failure.partialResult = result;
|
|
115
|
+
throw failure;
|
|
116
|
+
}
|
|
117
|
+
return result;
|
|
118
|
+
}
|
|
119
|
+
/** The event stream of one chat turn (or of a batch job, which reports with the same events). */
|
|
120
|
+
export class ChatStream extends Stream {
|
|
121
|
+
/** Dialog id from the `X-Dialog-Id` response header; null when the operation does not send it. */
|
|
122
|
+
dialogId;
|
|
123
|
+
/** Turn number from the `X-Turn-No` response header; null when absent. */
|
|
124
|
+
turnNo;
|
|
125
|
+
constructor(init) {
|
|
126
|
+
super(init, (event, response) => decodeJSONEvent(event, response));
|
|
127
|
+
const dialogId = init.response.headers.get('x-dialog-id');
|
|
128
|
+
this.dialogId = dialogId === null || dialogId === '' ? null : dialogId;
|
|
129
|
+
const turnNo = init.response.headers.get('x-turn-no');
|
|
130
|
+
this.turnNo = turnNo !== null && /^[0-9]+$/.test(turnNo) ? Number(turnNo) : null;
|
|
131
|
+
}
|
|
132
|
+
/** Reads the stream to its end and returns the assembled turn; throws on a mid-stream `error` event and when the stream ends without `done`. */
|
|
133
|
+
finalResult(callbacks = {}) {
|
|
134
|
+
return accumulateChatStream(this, callbacks);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/** A promise of a {@link ChatStream} that can be iterated directly or reduced with `finalResult()`. */
|
|
138
|
+
export class ChatStreamPromise extends StreamPromise {
|
|
139
|
+
/** Opens the stream, reads it to its end and returns the assembled turn. */
|
|
140
|
+
finalResult(callbacks = {}) {
|
|
141
|
+
return this.then((stream) => stream.finalResult(callbacks));
|
|
142
|
+
}
|
|
143
|
+
}
|
|
@@ -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,219 @@
|
|
|
1
|
+
// Code generated by tungo-sdkgen. DO NOT EDIT.
|
|
2
|
+
import { APIClient, sleep, startTimer } from './core.js';
|
|
3
|
+
import { chatTurnError } from './chat.js';
|
|
4
|
+
import { AbortError, DecodeError, TimeoutError } from './errors.js';
|
|
5
|
+
import { bytesToBase64, verifyWebhook } from './webhooks.js';
|
|
6
|
+
import * as R from './generated/resources.js';
|
|
7
|
+
const RUN_FINAL_STATES = ['done', 'error', 'skipped', 'cancelled'];
|
|
8
|
+
function chatBody(message) {
|
|
9
|
+
return typeof message === 'string' ? { message } : message;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* The Tungo Platform API client.
|
|
13
|
+
*
|
|
14
|
+
* Create one instance and share it: it is immutable and safe to use concurrently. Resources
|
|
15
|
+
* (`client.companies`, `client.chat`, ...) mirror the API one to one; the methods on the client
|
|
16
|
+
* itself are shortcuts for common tasks.
|
|
17
|
+
*/
|
|
18
|
+
export class Tungo {
|
|
19
|
+
/** Организации (workspace), доступные ключу API */
|
|
20
|
+
workspaces;
|
|
21
|
+
/** Компании организации и их карточки */
|
|
22
|
+
companies;
|
|
23
|
+
/** Баланс платформы, книга движений, отчёты о расходе, лимиты, аудит и тарифы моделей */
|
|
24
|
+
platform;
|
|
25
|
+
/** Сведения о текущем ключе API и статистика его расхода */
|
|
26
|
+
apiKeys;
|
|
27
|
+
/** Исходящие вебхуки организации (Svix): адреса, каталог событий, доставки и проверка подписи */
|
|
28
|
+
webhooks;
|
|
29
|
+
/** Диалоги с ИИ-бухгалтером: вопросы, потоковый чат (SSE), подсчёт токенов и история */
|
|
30
|
+
chat;
|
|
31
|
+
/** Предложения документов ИИ-бухгалтера: просмотр, одобрение записи в 1С и отклонение */
|
|
32
|
+
proposals;
|
|
33
|
+
/** Лента событий и предложений компании (страницы и живой поток SSE) */
|
|
34
|
+
feed;
|
|
35
|
+
/** Пачки обработки банковских выписок, входящих ЭСФ и DirectBank */
|
|
36
|
+
batches;
|
|
37
|
+
/** Входящие и исходящие электронные счета-фактуры (ИС ЭСФ) */
|
|
38
|
+
esf;
|
|
39
|
+
/** Налоговые формы (ФНО 100.00 и др.): сборка, проверка ИСНА и разрывы данных */
|
|
40
|
+
forms;
|
|
41
|
+
/** Состояние подключения компании к базе 1С */
|
|
42
|
+
onec;
|
|
43
|
+
/** Автоматизации компании: входящие хуки, сценарии, цепочки шагов, запуски и уровень автономности ИИ */
|
|
44
|
+
automations;
|
|
45
|
+
#client;
|
|
46
|
+
constructor(options = {}) {
|
|
47
|
+
const client = new APIClient(options);
|
|
48
|
+
this.#client = client;
|
|
49
|
+
this.workspaces = new R.WorkspacesResource(client);
|
|
50
|
+
this.companies = new R.CompaniesResource(client);
|
|
51
|
+
this.platform = new R.PlatformResource(client);
|
|
52
|
+
this.apiKeys = new R.ApiKeysResource(client);
|
|
53
|
+
this.webhooks = new R.WebhooksResource(client);
|
|
54
|
+
this.chat = new R.ChatResource(client);
|
|
55
|
+
this.proposals = new R.ProposalsResource(client);
|
|
56
|
+
this.feed = new R.FeedResource(client);
|
|
57
|
+
this.batches = new R.BatchesResource(client);
|
|
58
|
+
this.esf = new R.EsfResource(client);
|
|
59
|
+
this.forms = new R.FormsResource(client);
|
|
60
|
+
this.onec = new R.OnecResource(client);
|
|
61
|
+
this.automations = new R.AutomationsResource(client);
|
|
62
|
+
}
|
|
63
|
+
/** Base URL the client talks to. */
|
|
64
|
+
get baseUrl() {
|
|
65
|
+
return this.#client.baseUrl;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Performs an arbitrary API call with the client's authentication, retries, timeouts and error
|
|
69
|
+
* handling. Use it for endpoints this SDK version does not cover yet.
|
|
70
|
+
*/
|
|
71
|
+
request(spec) {
|
|
72
|
+
return this.#client.request(spec);
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Asks the assistant one question and waits for the complete answer (no streaming).
|
|
76
|
+
* If the turn reports an error, the matching typed APIError is thrown; its `partialResult`
|
|
77
|
+
* holds the turn as returned.
|
|
78
|
+
*/
|
|
79
|
+
async ask(companyId, message, options) {
|
|
80
|
+
const { data, response } = await this.chat.create(companyId, chatBody(message), options).withResponse();
|
|
81
|
+
const first = Array.isArray(data.errors) ? data.errors[0] : undefined;
|
|
82
|
+
if (first !== undefined) {
|
|
83
|
+
const failure = chatTurnError(first, null, response);
|
|
84
|
+
failure.partialResult = data;
|
|
85
|
+
throw failure;
|
|
86
|
+
}
|
|
87
|
+
return data;
|
|
88
|
+
}
|
|
89
|
+
/** Asks the assistant and streams the events of the turn as they are produced. */
|
|
90
|
+
streamChat(companyId, message, options) {
|
|
91
|
+
return this.chat.stream(companyId, chatBody(message), options);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Streams a chat turn, calling the callbacks as events arrive, and returns the assembled turn.
|
|
95
|
+
* A mid-stream `error` event is thrown as the matching typed APIError.
|
|
96
|
+
*/
|
|
97
|
+
streamChatWithResult(companyId, message, callbacks, options) {
|
|
98
|
+
return this.chat.stream(companyId, chatBody(message), options).finalResult(callbacks);
|
|
99
|
+
}
|
|
100
|
+
/** Answers a clarifying question of the assistant (a `choice` event) and waits for the rest of the turn. */
|
|
101
|
+
answerQuestion(companyId, dialogId, choiceId, answers, options) {
|
|
102
|
+
return this.chat.answer(companyId, dialogId, { choice_id: choiceId, answers }, options);
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Uploads a bank statement for processing into proposals. `content` is the file bytes, or a
|
|
106
|
+
* string: base64 of the file by default, or the statement text itself with `{ text: true }`.
|
|
107
|
+
*/
|
|
108
|
+
uploadBankStatement(companyId, fileName, content, options = {}) {
|
|
109
|
+
const { text, limit, ...requestOptions } = options;
|
|
110
|
+
const body = { file_name: fileName };
|
|
111
|
+
if (typeof content === 'string') {
|
|
112
|
+
if (text === true)
|
|
113
|
+
body.text = content;
|
|
114
|
+
else
|
|
115
|
+
body.file = content;
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
body.file = bytesToBase64(content instanceof ArrayBuffer ? new Uint8Array(content) : content);
|
|
119
|
+
}
|
|
120
|
+
if (limit !== undefined)
|
|
121
|
+
body.limit = limit;
|
|
122
|
+
return this.batches.createBankStatement(companyId, body, requestOptions);
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* 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. The API key is not sent.
|
|
127
|
+
* Same as `client.automations.postHook`.
|
|
128
|
+
*/
|
|
129
|
+
sendHook(token, payload, options) {
|
|
130
|
+
return this.automations.postHook(token, payload, options);
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Verifies an outgoing webhook and returns the typed event. Uses `options.secret`, else the
|
|
134
|
+
* client's webhook secret. Throws a WebhookVerificationError when the webhook is not authentic.
|
|
135
|
+
*/
|
|
136
|
+
async verifyWebhook(body, headers, options = {}) {
|
|
137
|
+
const { secret, ...rest } = options;
|
|
138
|
+
return verifyWebhook(body, headers, this.#client.webhookSecret(secret), rest);
|
|
139
|
+
}
|
|
140
|
+
/** Starts a scenario run and waits until it finishes (see {@link Tungo.waitForRun}). */
|
|
141
|
+
async runScenarioAndWait(companyId, scenarioId, body, options = {}) {
|
|
142
|
+
const requestOptions = { signal: options.signal };
|
|
143
|
+
const started = await this.automations.runScenario(companyId, scenarioId, body, requestOptions);
|
|
144
|
+
return this.waitForRun(companyId, started.id, options);
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Polls an automation run until it reaches a final state (done, error, skipped, cancelled). A state this
|
|
148
|
+
* SDK version does not know is treated as "still running". Throws a TimeoutError at the deadline.
|
|
149
|
+
*/
|
|
150
|
+
waitForRun(companyId, runId, options = {}) {
|
|
151
|
+
return this.#poll('the automation run to finish', (requestOptions) => this.automations.getRun(companyId, runId, requestOptions).withResponse(), (run, response) => {
|
|
152
|
+
const state = run?.state;
|
|
153
|
+
if (typeof state !== 'string') {
|
|
154
|
+
throw new DecodeError('The automation run has no "state"', { status: response.status, requestId: response.requestId, body: JSON.stringify(run) ?? '' });
|
|
155
|
+
}
|
|
156
|
+
return RUN_FINAL_STATES.includes(state);
|
|
157
|
+
}, options);
|
|
158
|
+
}
|
|
159
|
+
/** Polls a batch job until it stops running. Throws a TimeoutError at the deadline. */
|
|
160
|
+
waitForBatch(companyId, batchId, options = {}) {
|
|
161
|
+
return this.#poll('the batch job to finish', (requestOptions) => this.batches.get(companyId, batchId, requestOptions).withResponse(), (job, response) => {
|
|
162
|
+
const running = job?.running;
|
|
163
|
+
if (typeof running !== 'boolean') {
|
|
164
|
+
throw new DecodeError('The batch job has no "running" flag', { status: response.status, requestId: response.requestId, body: JSON.stringify(job) ?? '' });
|
|
165
|
+
}
|
|
166
|
+
return !running;
|
|
167
|
+
}, options);
|
|
168
|
+
}
|
|
169
|
+
async #poll(what, load, finished, options) {
|
|
170
|
+
const timeout = options.timeout ?? 600_000;
|
|
171
|
+
const outer = options.signal ?? undefined;
|
|
172
|
+
if (outer !== undefined && outer.aborted)
|
|
173
|
+
throw new AbortError('The wait was aborted', { cause: outer.reason });
|
|
174
|
+
const deadline = Date.now() + timeout;
|
|
175
|
+
let pause = options.pollInterval ?? 1000;
|
|
176
|
+
const longest = Math.max(pause, options.maxPollInterval ?? 5000);
|
|
177
|
+
// One signal ends everything the wait does (a poll request, its retries, the pause between
|
|
178
|
+
// polls) at the deadline, so the wait cannot outlive it by a request timeout or by retries.
|
|
179
|
+
const controller = new AbortController();
|
|
180
|
+
let expired = false;
|
|
181
|
+
const timer = startTimer(() => {
|
|
182
|
+
expired = true;
|
|
183
|
+
controller.abort();
|
|
184
|
+
}, timeout);
|
|
185
|
+
const onAbort = () => {
|
|
186
|
+
controller.abort(outer?.reason);
|
|
187
|
+
};
|
|
188
|
+
if (outer !== undefined)
|
|
189
|
+
outer.addEventListener('abort', onAbort, { once: true });
|
|
190
|
+
const late = (cause) => new TimeoutError('Timed out after ' + timeout + ' ms waiting for ' + what, timeout, { cause });
|
|
191
|
+
try {
|
|
192
|
+
for (;;) {
|
|
193
|
+
const { data, response } = await load({ signal: controller.signal });
|
|
194
|
+
if (finished(data, response))
|
|
195
|
+
return data;
|
|
196
|
+
const left = deadline - Date.now();
|
|
197
|
+
if (left <= 0)
|
|
198
|
+
throw late();
|
|
199
|
+
await sleep(Math.min(pause, left), controller.signal);
|
|
200
|
+
pause = Math.min(pause * 1.5, longest);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
catch (cause) {
|
|
204
|
+
// The deadline aborted whatever was pending: report the deadline, not the abort.
|
|
205
|
+
if (expired && cause instanceof AbortError && !(outer !== undefined && outer.aborted))
|
|
206
|
+
throw late(cause);
|
|
207
|
+
throw cause;
|
|
208
|
+
}
|
|
209
|
+
finally {
|
|
210
|
+
clearTimeout(timer);
|
|
211
|
+
if (outer !== undefined)
|
|
212
|
+
outer.removeEventListener('abort', onAbort);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
/** A description without secrets (the API key is never included). */
|
|
216
|
+
toJSON() {
|
|
217
|
+
return { baseUrl: this.#client.baseUrl, timeout: this.#client.timeout, maxRetries: this.#client.maxRetries };
|
|
218
|
+
}
|
|
219
|
+
}
|