@tungoai/sdk 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/LICENSE +21 -0
  3. package/README.kk.md +327 -0
  4. package/README.md +346 -2
  5. package/README.ru.md +327 -0
  6. package/dist/cjs/chat.d.ts +85 -0
  7. package/dist/cjs/chat.js +152 -0
  8. package/dist/cjs/client.d.ts +117 -0
  9. package/dist/cjs/client.js +225 -0
  10. package/dist/cjs/core.d.ts +217 -0
  11. package/dist/cjs/core.js +779 -0
  12. package/dist/cjs/errors.d.ts +237 -0
  13. package/dist/cjs/errors.js +446 -0
  14. package/dist/cjs/generated/resources.d.ts +1149 -0
  15. package/dist/cjs/generated/resources.js +1145 -0
  16. package/dist/cjs/generated/types.d.ts +5435 -0
  17. package/dist/cjs/generated/types.js +11 -0
  18. package/dist/cjs/index.d.ts +12 -0
  19. package/dist/cjs/index.js +81 -0
  20. package/dist/cjs/json.d.ts +16 -0
  21. package/dist/cjs/json.js +137 -0
  22. package/dist/cjs/money.d.ts +32 -0
  23. package/dist/cjs/money.js +141 -0
  24. package/dist/cjs/package.json +1 -0
  25. package/dist/cjs/pagination.d.ts +47 -0
  26. package/dist/cjs/pagination.js +114 -0
  27. package/dist/cjs/streaming.d.ts +76 -0
  28. package/dist/cjs/streaming.js +291 -0
  29. package/dist/cjs/version.d.ts +2 -0
  30. package/dist/cjs/version.js +6 -0
  31. package/dist/cjs/webhooks.d.ts +79 -0
  32. package/dist/cjs/webhooks.js +262 -0
  33. package/dist/esm/chat.d.ts +85 -0
  34. package/dist/esm/chat.js +144 -0
  35. package/dist/esm/client.d.ts +117 -0
  36. package/dist/esm/client.js +221 -0
  37. package/dist/esm/core.d.ts +217 -0
  38. package/dist/esm/core.js +763 -0
  39. package/dist/esm/errors.d.ts +237 -0
  40. package/dist/esm/errors.js +416 -0
  41. package/dist/esm/generated/resources.d.ts +1149 -0
  42. package/dist/esm/generated/resources.js +1129 -0
  43. package/dist/esm/generated/types.d.ts +5435 -0
  44. package/dist/esm/generated/types.js +10 -0
  45. package/dist/esm/index.d.ts +12 -0
  46. package/dist/esm/index.js +11 -0
  47. package/dist/esm/json.d.ts +16 -0
  48. package/dist/esm/json.js +132 -0
  49. package/dist/esm/money.d.ts +32 -0
  50. package/dist/esm/money.js +137 -0
  51. package/dist/esm/package.json +1 -0
  52. package/dist/esm/pagination.d.ts +47 -0
  53. package/dist/esm/pagination.js +108 -0
  54. package/dist/esm/streaming.d.ts +76 -0
  55. package/dist/esm/streaming.js +285 -0
  56. package/dist/esm/version.d.ts +2 -0
  57. package/dist/esm/version.js +3 -0
  58. package/dist/esm/webhooks.d.ts +79 -0
  59. package/dist/esm/webhooks.js +253 -0
  60. package/package.json +67 -4
@@ -0,0 +1,262 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TungoWebhooks = exports.TungoHooks = exports.DEFAULT_WEBHOOK_TOLERANCE_SECONDS = void 0;
4
+ exports.verifyWebhook = verifyWebhook;
5
+ exports.signHookPayload = signHookPayload;
6
+ exports.verifyHookSignature = verifyHookSignature;
7
+ exports.bytesToBase64 = bytesToBase64;
8
+ exports.encodeHookPayload = encodeHookPayload;
9
+ exports.sendHook = sendHook;
10
+ // Code generated by tungo-sdkgen. DO NOT EDIT.
11
+ const errors_js_1 = require("./errors.js");
12
+ const core_js_1 = require("./core.js");
13
+ const json_js_1 = require("./json.js");
14
+ /** Default tolerance for the webhook timestamp, in seconds (both directions). */
15
+ exports.DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
16
+ const encoder = new TextEncoder();
17
+ function toBytes(body) {
18
+ if (typeof body === 'string')
19
+ return encoder.encode(body);
20
+ if (body instanceof ArrayBuffer)
21
+ return new Uint8Array(body);
22
+ if (ArrayBuffer.isView(body)) {
23
+ const copy = new Uint8Array(body.byteLength);
24
+ copy.set(new Uint8Array(body.buffer, body.byteOffset, body.byteLength));
25
+ return copy;
26
+ }
27
+ throw new errors_js_1.ValidationError('The body must be a string, a Uint8Array or an ArrayBuffer (the raw bytes as received)');
28
+ }
29
+ function concat(a, b) {
30
+ const out = new Uint8Array(a.length + b.length);
31
+ out.set(a, 0);
32
+ out.set(b, a.length);
33
+ return out;
34
+ }
35
+ function decodeBase64(text) {
36
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(text))
37
+ return null;
38
+ let binary;
39
+ try {
40
+ binary = atob(text);
41
+ }
42
+ catch {
43
+ return null;
44
+ }
45
+ const out = new Uint8Array(binary.length);
46
+ for (let i = 0; i < binary.length; i++)
47
+ out[i] = binary.charCodeAt(i);
48
+ return out;
49
+ }
50
+ function decodeHex(text) {
51
+ if (text.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(text))
52
+ return null;
53
+ const out = new Uint8Array(text.length / 2);
54
+ for (let i = 0; i < out.length; i++)
55
+ out[i] = Number.parseInt(text.slice(i * 2, i * 2 + 2), 16);
56
+ return out;
57
+ }
58
+ function encodeHex(bytes) {
59
+ let out = '';
60
+ for (const b of bytes)
61
+ out += b.toString(16).padStart(2, '0');
62
+ return out;
63
+ }
64
+ function hmacKey(key, usage) {
65
+ return crypto.subtle.importKey('raw', key, { name: 'HMAC', hash: 'SHA-256' }, false, [usage]);
66
+ }
67
+ function findHeader(headers, name) {
68
+ const wanted = name.toLowerCase();
69
+ const iterable = headers;
70
+ if (typeof iterable[Symbol.iterator] === 'function') {
71
+ for (const pair of headers) {
72
+ if (Array.isArray(pair) && typeof pair[0] === 'string' && pair[0].toLowerCase() === wanted && typeof pair[1] === 'string') {
73
+ return pair[1];
74
+ }
75
+ }
76
+ return undefined;
77
+ }
78
+ for (const [key, value] of Object.entries(headers)) {
79
+ if (key.toLowerCase() !== wanted)
80
+ continue;
81
+ if (typeof value === 'string')
82
+ return value;
83
+ if (Array.isArray(value) && typeof value[0] === 'string')
84
+ return value[0];
85
+ }
86
+ return undefined;
87
+ }
88
+ function clock(now) {
89
+ if (now === undefined)
90
+ return Math.floor(Date.now() / 1000);
91
+ if (typeof now === 'number')
92
+ return now;
93
+ if (now instanceof Date)
94
+ return Math.floor(now.getTime() / 1000);
95
+ return now();
96
+ }
97
+ /**
98
+ * Verifies an outgoing Tungo webhook (Standard Webhooks / Svix) and returns the typed event.
99
+ *
100
+ * Pass the RAW request body (the exact bytes, before any JSON parsing), the request headers
101
+ * (`webhook-*` or `svix-*`) and the endpoint's signing secret (`whsec_...`). The signature is
102
+ * checked in constant time and the timestamp must be within the tolerance of the clock.
103
+ * Every problem is reported as a {@link WebhookVerificationError}.
104
+ */
105
+ async function verifyWebhook(body, headers, secret, options = {}) {
106
+ const tolerance = options.toleranceSeconds ?? exports.DEFAULT_WEBHOOK_TOLERANCE_SECONDS;
107
+ if (typeof tolerance !== 'number' || !(tolerance > 0) || !Number.isFinite(tolerance)) {
108
+ throw new errors_js_1.WebhookVerificationError('invalid_tolerance', 'The webhook tolerance must be a positive number of seconds');
109
+ }
110
+ if (typeof secret !== 'string') {
111
+ throw new errors_js_1.WebhookVerificationError('invalid_secret', 'The webhook secret must be a string');
112
+ }
113
+ const encoded = secret.startsWith('whsec_') ? secret.slice(6) : secret;
114
+ const key = encoded === '' ? null : decodeBase64(encoded);
115
+ if (key === null || key.length === 0) {
116
+ throw new errors_js_1.WebhookVerificationError('invalid_secret', 'The webhook secret is empty or is not base64 (expected "whsec_" followed by base64)');
117
+ }
118
+ if (headers === null || typeof headers !== 'object') {
119
+ throw new errors_js_1.WebhookVerificationError('missing_header', 'The webhook headers are missing');
120
+ }
121
+ const get = (suffix) => findHeader(headers, 'svix-' + suffix) ?? findHeader(headers, 'webhook-' + suffix);
122
+ const id = get('id');
123
+ const timestamp = get('timestamp');
124
+ const signature = get('signature');
125
+ if (id === undefined || timestamp === undefined || signature === undefined) {
126
+ throw new errors_js_1.WebhookVerificationError('missing_header', 'A webhook header is missing (webhook-id, webhook-timestamp and webhook-signature are required)');
127
+ }
128
+ if (!/^[0-9]+$/.test(timestamp) || !Number.isSafeInteger(Number(timestamp))) {
129
+ throw new errors_js_1.WebhookVerificationError('malformed_timestamp', 'The webhook timestamp is not a whole number of seconds');
130
+ }
131
+ const sent = Number(timestamp);
132
+ const now = clock(options.now);
133
+ if (now - sent > tolerance) {
134
+ throw new errors_js_1.WebhookVerificationError('timestamp_too_old', 'The webhook timestamp is older than the tolerance of ' + tolerance + ' s');
135
+ }
136
+ if (sent - now > tolerance) {
137
+ throw new errors_js_1.WebhookVerificationError('timestamp_too_new', 'The webhook timestamp is further in the future than the tolerance of ' + tolerance + ' s');
138
+ }
139
+ let bytes;
140
+ try {
141
+ bytes = toBytes(body);
142
+ }
143
+ catch (cause) {
144
+ throw new errors_js_1.WebhookVerificationError('invalid_payload', 'The webhook body must be the raw request body (string or bytes)', { cause });
145
+ }
146
+ const signed = concat(encoder.encode(id + '.' + timestamp + '.'), bytes);
147
+ let matched = false;
148
+ try {
149
+ const cryptoKey = await hmacKey(key, 'verify');
150
+ for (const part of signature.split(/[ \t\r\n\f\v]+/)) {
151
+ const comma = part.indexOf(',');
152
+ if (comma === -1 || part.slice(0, comma) !== 'v1')
153
+ continue;
154
+ const candidate = decodeBase64(part.slice(comma + 1));
155
+ if (candidate === null)
156
+ continue;
157
+ // SubtleCrypto.verify compares the MAC in constant time.
158
+ if (await crypto.subtle.verify('HMAC', cryptoKey, candidate, signed))
159
+ matched = true;
160
+ }
161
+ }
162
+ catch (cause) {
163
+ throw new errors_js_1.WebhookVerificationError('signature_mismatch', 'The webhook signature could not be checked', { cause });
164
+ }
165
+ if (!matched) {
166
+ throw new errors_js_1.WebhookVerificationError('signature_mismatch', 'No webhook signature matches the body: check the secret and pass the raw body');
167
+ }
168
+ let event;
169
+ try {
170
+ event = (0, json_js_1.parseJSON)(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
171
+ }
172
+ catch (cause) {
173
+ throw new errors_js_1.WebhookVerificationError('invalid_payload', 'The webhook signature is valid but the body is not JSON', { cause });
174
+ }
175
+ if (typeof event !== 'object' || event === null || typeof event.type !== 'string') {
176
+ throw new errors_js_1.WebhookVerificationError('invalid_payload', 'The webhook signature is valid but the body is not an event object');
177
+ }
178
+ return event;
179
+ }
180
+ /**
181
+ * Computes the signature of an incoming-hook body: lower-case hex of HMAC-SHA256(secret, body).
182
+ * Send it as `X-Signature: sha256=<hex>`. An empty secret is rejected.
183
+ */
184
+ async function signHookPayload(body, secret) {
185
+ if (typeof secret !== 'string' || secret === '')
186
+ throw new errors_js_1.ValidationError('The hook secret must not be empty');
187
+ const key = await hmacKey(encoder.encode(secret), 'sign');
188
+ return encodeHex(new Uint8Array(await crypto.subtle.sign('HMAC', key, toBytes(body))));
189
+ }
190
+ /**
191
+ * Checks a hook signature (hex in any case, with or without the `sha256=` prefix) in constant
192
+ * time. Returns false for an empty secret or a malformed signature; it never throws for those.
193
+ */
194
+ async function verifyHookSignature(body, signature, secret) {
195
+ if (typeof secret !== 'string' || secret === '' || typeof signature !== 'string')
196
+ return false;
197
+ const hex = signature.slice(0, 7).toLowerCase() === 'sha256=' ? signature.slice(7) : signature;
198
+ const given = decodeHex(hex);
199
+ if (given === null || given.length !== 32)
200
+ return false;
201
+ const key = await hmacKey(encoder.encode(secret), 'verify');
202
+ return crypto.subtle.verify('HMAC', key, given, toBytes(body));
203
+ }
204
+ /** Encodes bytes as base64 without relying on Node.js APIs. */
205
+ function bytesToBase64(bytes) {
206
+ let binary = '';
207
+ for (let i = 0; i < bytes.length; i += 0x8000) {
208
+ binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
209
+ }
210
+ return btoa(binary);
211
+ }
212
+ /** Helpers for incoming automation hooks (`/hooks/{token}`). */
213
+ exports.TungoHooks = { sign: signHookPayload, verify: verifyHookSignature };
214
+ /** Helpers for outgoing webhooks. */
215
+ exports.TungoWebhooks = { verify: verifyWebhook };
216
+ /** Turns a hook payload into the exact bytes to send and their default content type. */
217
+ function encodeHookPayload(payload) {
218
+ if (typeof payload === 'string')
219
+ return { bytes: encoder.encode(payload), contentType: 'application/json' };
220
+ if (payload instanceof ArrayBuffer || ArrayBuffer.isView(payload)) {
221
+ return { bytes: toBytes(payload), contentType: 'application/octet-stream' };
222
+ }
223
+ return { bytes: encoder.encode((0, json_js_1.stringifyJSON)(payload)), contentType: 'application/json' };
224
+ }
225
+ const HOOK_SIGNATURE_HEADER = /^[A-Za-z0-9-]{1,64}$/;
226
+ /** Posts an event to an incoming hook. No API key is sent: the token in the path authenticates. */
227
+ function sendHook(client, operation, token, payload, options = {}) {
228
+ const run = async () => {
229
+ const { secret, eventId, contentType, signatureHeader, ...requestOptions } = options;
230
+ const target = signatureHeader ?? operation.signatureHeader;
231
+ if (typeof target !== 'string' || !HOOK_SIGNATURE_HEADER.test(target)) {
232
+ throw new errors_js_1.ValidationError("signatureHeader must be 1 to 64 Latin letters, digits or hyphens, like the hook's signature_header.");
233
+ }
234
+ const encoded = encodeHookPayload(payload);
235
+ const headers = {};
236
+ if (secret !== undefined) {
237
+ const lower = target.toLowerCase();
238
+ if (Object.entries(requestOptions.headers ?? {}).some(([name, value]) => name.toLowerCase() === lower && value != null)) {
239
+ throw new errors_js_1.ValidationError(`Pass either secret or the ${target} header, not both.`);
240
+ }
241
+ headers[target] = 'sha256=' + (await signHookPayload(encoded.bytes, secret));
242
+ }
243
+ if (eventId !== undefined && operation.eventIdHeader !== undefined)
244
+ headers[operation.eventIdHeader] = eventId;
245
+ return {
246
+ method: operation.method,
247
+ path: operation.path,
248
+ pathParams: { [operation.tokenParam]: token },
249
+ rawBody: encoded.bytes,
250
+ contentType: contentType ?? encoded.contentType,
251
+ headers,
252
+ auth: 'hook',
253
+ idempotencyHeader: operation.idempotencyHeader,
254
+ // The backend takes the id of a hook event from Idempotency-Key before X-Event-Id, so a random
255
+ // key would override the caller's event id: the event id is the default key. A key the caller
256
+ // gives (`idempotencyKey`, or the header per request or in the client's default headers) wins.
257
+ defaultIdempotencyKey: eventId,
258
+ options: requestOptions,
259
+ };
260
+ };
261
+ return new core_js_1.APIPromise(run().then((spec) => client.request(spec).withResponse()));
262
+ }
@@ -0,0 +1,85 @@
1
+ import { StreamPromise } from './core.js';
2
+ import { type APIError } from './errors.js';
3
+ import { Stream, type ResponseInfo, type StreamInit } from './streaming.js';
4
+ import type * as T from './generated/types.js';
5
+ /** Callbacks invoked while a chat stream is being accumulated. */
6
+ export interface ChatStreamCallbacks {
7
+ /** Every event, in order. */
8
+ onEvent?: ((event: T.ChatEvent) => void) | undefined;
9
+ /** A piece of the answer text. */
10
+ onTextDelta?: ((delta: string, event: T.ChatEventText) => void) | undefined;
11
+ /** A piece of the model's reasoning. */
12
+ onThinkingDelta?: ((delta: string, event: T.ChatEventThinking) => void) | undefined;
13
+ /** A tool call started, finished or failed. */
14
+ onTool?: ((event: T.ChatEventTool) => void) | undefined;
15
+ /** The text of a step turned out to be an intermediate remark, not part of the answer. */
16
+ onProgress?: ((event: T.ChatEventProgress) => void) | undefined;
17
+ }
18
+ /** A chat turn assembled from its stream. */
19
+ export interface ChatStreamResult {
20
+ /**
21
+ * The final answer: `done.answer` when the server sent it, otherwise the text deltas joined,
22
+ * without the deltas of steps that a later `progress` event marked as intermediate.
23
+ */
24
+ text: string;
25
+ /** Dialog id from the `X-Dialog-Id` response header. */
26
+ dialogId: string | null;
27
+ /** Turn number from the `X-Turn-No` response header. */
28
+ turnNo: number | null;
29
+ /** `done.stop_reason`; null when absent (and in the partial result of a stream that ended without `done`). */
30
+ stopReason: string | null;
31
+ /** `done.cost_tiyn`; null when absent. A `bigint` beyond 2^53, like every 64-bit integer of the API. */
32
+ costTiyn: number | bigint | null;
33
+ /** `done.usage`; null when absent. */
34
+ usage: T.ChatUsage | null;
35
+ /** `done.choice_id`: the question to answer with `chat.answer`; null when absent. */
36
+ choiceId: string | null;
37
+ /** Every event received, heart-beats excluded. */
38
+ events: T.ChatEvent[];
39
+ /** The first `error` event of the turn, or null. */
40
+ error: T.ChatEventError | null;
41
+ }
42
+ /** Folds the events of one chat turn into a {@link ChatStreamResult}. */
43
+ export declare class ChatAccumulator {
44
+ #private;
45
+ /** Adds one event. Unknown event types are kept in `events` and otherwise ignored. */
46
+ push(event: T.ChatEvent, callbacks?: ChatStreamCallbacks): void;
47
+ /** True once the `done` event has arrived: the server finished the turn. */
48
+ get completed(): boolean;
49
+ /** The turn as accumulated so far. */
50
+ result(meta?: {
51
+ dialogId?: string | null;
52
+ turnNo?: number | null;
53
+ }): ChatStreamResult;
54
+ }
55
+ /**
56
+ * Converts a chat `error` object (`{ type, code, message, ... }`, from a stream event or from
57
+ * `ChatTurnResult.errors`) into the typed error of the class an HTTP error response with the same
58
+ * `error.type` produces. Its `status` is undefined: the HTTP response that carried the turn was
59
+ * successful, so there is no error status to report. `response` supplies the headers, the request
60
+ * id and the rate limit.
61
+ */
62
+ export declare function chatTurnError(error: unknown, requestId: string | null, response?: ResponseInfo): APIError;
63
+ /**
64
+ * Consumes a chat event stream to its end and returns the assembled turn. A mid-stream `error`
65
+ * event makes it throw the matching typed {@link APIError}, and a stream that ends without its
66
+ * `done` event (a dropped connection, a proxy that cut it) a {@link DecodeError}: a partial text
67
+ * is never returned as a finished turn. Both errors carry what was accumulated in `partialResult`.
68
+ * When `events` is a {@link ChatStream}, `dialogId` and `turnNo` are filled from the response headers.
69
+ */
70
+ export declare function accumulateChatStream(events: AsyncIterable<T.ChatEvent> | Iterable<T.ChatEvent>, callbacks?: ChatStreamCallbacks): Promise<ChatStreamResult>;
71
+ /** The event stream of one chat turn (or of a batch job, which reports with the same events). */
72
+ export declare class ChatStream extends Stream<T.ChatEvent> {
73
+ /** Dialog id from the `X-Dialog-Id` response header; null when the operation does not send it. */
74
+ readonly dialogId: string | null;
75
+ /** Turn number from the `X-Turn-No` response header; null when absent. */
76
+ readonly turnNo: number | null;
77
+ constructor(init: StreamInit);
78
+ /** 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`. */
79
+ finalResult(callbacks?: ChatStreamCallbacks): Promise<ChatStreamResult>;
80
+ }
81
+ /** A promise of a {@link ChatStream} that can be iterated directly or reduced with `finalResult()`. */
82
+ export declare class ChatStreamPromise extends StreamPromise<T.ChatEvent, ChatStream> {
83
+ /** Opens the stream, reads it to its end and returns the assembled turn. */
84
+ finalResult(callbacks?: ChatStreamCallbacks): Promise<ChatStreamResult>;
85
+ }
@@ -0,0 +1,144 @@
1
+ // Code generated by tungo-sdkgen. DO NOT EDIT.
2
+ import { StreamPromise } from './core.js';
3
+ import { debugJSON } from './json.js';
4
+ import { DecodeError, makeAPIError, parseErrorDetail } from './errors.js';
5
+ import { Stream, decodeJSONEvent } from './streaming.js';
6
+ /** Folds the events of one chat turn into a {@link ChatStreamResult}. */
7
+ export class ChatAccumulator {
8
+ #segments = [];
9
+ #events = [];
10
+ #done = null;
11
+ #error = null;
12
+ /** Adds one event. Unknown event types are kept in `events` and otherwise ignored. */
13
+ push(event, callbacks = {}) {
14
+ this.#events.push(event);
15
+ callbacks.onEvent?.(event);
16
+ switch (event.type) {
17
+ case 'text':
18
+ this.#segments.push({ step: event.step, delta: event.delta });
19
+ callbacks.onTextDelta?.(event.delta, event);
20
+ break;
21
+ case 'progress':
22
+ this.#segments = this.#segments.filter((s) => s.step === undefined || event.step === undefined || s.step !== event.step);
23
+ callbacks.onProgress?.(event);
24
+ break;
25
+ case 'thinking':
26
+ callbacks.onThinkingDelta?.(event.delta, event);
27
+ break;
28
+ case 'tool':
29
+ callbacks.onTool?.(event);
30
+ break;
31
+ case 'error':
32
+ if (this.#error === null)
33
+ this.#error = event;
34
+ break;
35
+ case 'done':
36
+ this.#done = event;
37
+ break;
38
+ default:
39
+ break;
40
+ }
41
+ }
42
+ /** True once the `done` event has arrived: the server finished the turn. */
43
+ get completed() {
44
+ return this.#done !== null;
45
+ }
46
+ /** The turn as accumulated so far. */
47
+ result(meta = {}) {
48
+ const done = this.#done;
49
+ let text = '';
50
+ for (const s of this.#segments)
51
+ text += s.delta;
52
+ if (done !== null && typeof done.answer === 'string')
53
+ text = done.answer;
54
+ return {
55
+ text,
56
+ dialogId: meta.dialogId ?? null,
57
+ turnNo: meta.turnNo ?? null,
58
+ stopReason: done !== null && typeof done.stop_reason === 'string' ? done.stop_reason : null,
59
+ costTiyn: done !== null && done.cost_tiyn !== undefined && done.cost_tiyn !== null ? done.cost_tiyn : null,
60
+ usage: done !== null && done.usage !== undefined && done.usage !== null ? done.usage : null,
61
+ choiceId: done !== null && typeof done.choice_id === 'string' ? done.choice_id : null,
62
+ events: this.#events.slice(),
63
+ error: this.#error,
64
+ };
65
+ }
66
+ }
67
+ /**
68
+ * Converts a chat `error` object (`{ type, code, message, ... }`, from a stream event or from
69
+ * `ChatTurnResult.errors`) into the typed error of the class an HTTP error response with the same
70
+ * `error.type` produces. Its `status` is undefined: the HTTP response that carried the turn was
71
+ * successful, so there is no error status to report. `response` supplies the headers, the request
72
+ * id and the rate limit.
73
+ */
74
+ export function chatTurnError(error, requestId, response) {
75
+ const detail = parseErrorDetail(error);
76
+ return makeAPIError({
77
+ status: undefined,
78
+ type: detail?.type ?? 'api_error',
79
+ code: detail?.code ?? null,
80
+ detail: detail?.detail ?? 'The chat turn failed',
81
+ requestId: requestId ?? response?.requestId ?? null,
82
+ fields: detail?.fields ?? [],
83
+ retryAfter: null,
84
+ rateLimit: response?.rateLimit ?? null,
85
+ headers: response?.headers ?? new Headers(),
86
+ body: debugJSON(error),
87
+ extra: detail?.extra ?? {},
88
+ envelope: detail !== null,
89
+ });
90
+ }
91
+ /**
92
+ * Consumes a chat event stream to its end and returns the assembled turn. A mid-stream `error`
93
+ * event makes it throw the matching typed {@link APIError}, and a stream that ends without its
94
+ * `done` event (a dropped connection, a proxy that cut it) a {@link DecodeError}: a partial text
95
+ * is never returned as a finished turn. Both errors carry what was accumulated in `partialResult`.
96
+ * When `events` is a {@link ChatStream}, `dialogId` and `turnNo` are filled from the response headers.
97
+ */
98
+ export async function accumulateChatStream(events, callbacks = {}) {
99
+ const accumulator = new ChatAccumulator();
100
+ for await (const event of events)
101
+ accumulator.push(event, callbacks);
102
+ const source = events instanceof ChatStream ? events : undefined;
103
+ const result = accumulator.result(source === undefined ? {} : { dialogId: source.dialogId, turnNo: source.turnNo });
104
+ if (result.error !== null) {
105
+ const failure = chatTurnError(result.error.error, result.error.request_id ?? null, source?.response);
106
+ failure.partialResult = result;
107
+ throw failure;
108
+ }
109
+ if (!accumulator.completed) {
110
+ const failure = new DecodeError('The chat stream ended before completion: no "done" event was received', {
111
+ status: source?.response.status,
112
+ requestId: source?.response.requestId ?? null,
113
+ body: '',
114
+ });
115
+ failure.partialResult = result;
116
+ throw failure;
117
+ }
118
+ return result;
119
+ }
120
+ /** The event stream of one chat turn (or of a batch job, which reports with the same events). */
121
+ export class ChatStream extends Stream {
122
+ /** Dialog id from the `X-Dialog-Id` response header; null when the operation does not send it. */
123
+ dialogId;
124
+ /** Turn number from the `X-Turn-No` response header; null when absent. */
125
+ turnNo;
126
+ constructor(init) {
127
+ super(init, (event, response) => decodeJSONEvent(event, response, true));
128
+ const dialogId = init.response.headers.get('x-dialog-id');
129
+ this.dialogId = dialogId === null || dialogId === '' ? null : dialogId;
130
+ const turnNo = init.response.headers.get('x-turn-no');
131
+ this.turnNo = turnNo !== null && /^[0-9]+$/.test(turnNo) ? Number(turnNo) : null;
132
+ }
133
+ /** 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`. */
134
+ finalResult(callbacks = {}) {
135
+ return accumulateChatStream(this, callbacks);
136
+ }
137
+ }
138
+ /** A promise of a {@link ChatStream} that can be iterated directly or reduced with `finalResult()`. */
139
+ export class ChatStreamPromise extends StreamPromise {
140
+ /** Opens the stream, reads it to its end and returns the assembled turn. */
141
+ finalResult(callbacks = {}) {
142
+ return this.then((stream) => stream.finalResult(callbacks));
143
+ }
144
+ }
@@ -0,0 +1,117 @@
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, or in `signatureHeader` for a
91
+ * hook created with its own `signature_header`. The API key is not sent.
92
+ * Same as `client.automations.postHook`.
93
+ */
94
+ sendHook(token: string, payload: HookPayload, options?: SendHookOptions): APIPromise<T.AutomationHookAccepted>;
95
+ /**
96
+ * Verifies an outgoing webhook and returns the typed event. Uses `options.secret`, else the
97
+ * client's webhook secret. Throws a WebhookVerificationError when the webhook is not authentic.
98
+ */
99
+ verifyWebhook(body: string | Uint8Array | ArrayBuffer, headers: HeadersLike, options?: VerifyWebhookOptions & {
100
+ secret?: string | undefined;
101
+ }): Promise<T.WebhookEvent>;
102
+ /** Starts a scenario run and waits until it finishes (see {@link Tungo.waitForRun}). */
103
+ runScenarioAndWait(companyId: string, scenarioId: string, body?: T.AutomationScenarioRunInput, options?: WaitOptions): Promise<T.AutomationRunDetail>;
104
+ /**
105
+ * Polls an automation run until it reaches a final state (done, error, skipped, cancelled). A state this
106
+ * SDK version does not know is treated as "still running". Throws a TimeoutError at the deadline.
107
+ */
108
+ waitForRun(companyId: string, runId: string, options?: WaitOptions): Promise<T.AutomationRunDetail>;
109
+ /** Polls a batch job until it stops running. Throws a TimeoutError at the deadline. */
110
+ waitForBatch(companyId: string, batchId: string, options?: WaitOptions): Promise<T.BatchJob>;
111
+ /** A description without secrets (the API key is never included). */
112
+ toJSON(): {
113
+ baseUrl: string;
114
+ timeout: number;
115
+ maxRetries: number;
116
+ };
117
+ }