@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,221 @@
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 { debugJSON } from './json.js';
6
+ import { bytesToBase64, verifyWebhook } from './webhooks.js';
7
+ import * as R from './generated/resources.js';
8
+ const RUN_FINAL_STATES = ['done', 'error', 'skipped', 'cancelled'];
9
+ function chatBody(message) {
10
+ return typeof message === 'string' ? { message } : message;
11
+ }
12
+ /**
13
+ * The Tungo Platform API client.
14
+ *
15
+ * Create one instance and share it: it is immutable and safe to use concurrently. Resources
16
+ * (`client.companies`, `client.chat`, ...) mirror the API one to one; the methods on the client
17
+ * itself are shortcuts for common tasks.
18
+ */
19
+ export class Tungo {
20
+ /** Организации (workspace), доступные ключу API */
21
+ workspaces;
22
+ /** Компании организации и их карточки */
23
+ companies;
24
+ /** Баланс платформы, книга движений, отчёты о расходе, лимиты, аудит и тарифы моделей */
25
+ platform;
26
+ /** Сведения о текущем ключе API и статистика его расхода */
27
+ apiKeys;
28
+ /** Исходящие вебхуки организации (Svix): адреса, каталог событий, доставки и проверка подписи */
29
+ webhooks;
30
+ /** Диалоги с ИИ-бухгалтером: вопросы, потоковый чат (SSE), подсчёт токенов и история */
31
+ chat;
32
+ /** Предложения документов ИИ-бухгалтера: просмотр, одобрение записи в 1С и отклонение */
33
+ proposals;
34
+ /** Лента событий и предложений компании (страницы и живой поток SSE) */
35
+ feed;
36
+ /** Пачки обработки банковских выписок, входящих ЭСФ и DirectBank */
37
+ batches;
38
+ /** Входящие и исходящие электронные счета-фактуры (ИС ЭСФ) */
39
+ esf;
40
+ /** Налоговые формы (ФНО 100.00 и др.): сборка, проверка ИСНА и разрывы данных */
41
+ forms;
42
+ /** Состояние подключения компании к базе 1С */
43
+ onec;
44
+ /** Автоматизации компании: входящие хуки, сценарии, цепочки шагов, запуски и уровень автономности ИИ */
45
+ automations;
46
+ #client;
47
+ constructor(options = {}) {
48
+ const client = new APIClient(options);
49
+ this.#client = client;
50
+ this.workspaces = new R.WorkspacesResource(client);
51
+ this.companies = new R.CompaniesResource(client);
52
+ this.platform = new R.PlatformResource(client);
53
+ this.apiKeys = new R.ApiKeysResource(client);
54
+ this.webhooks = new R.WebhooksResource(client);
55
+ this.chat = new R.ChatResource(client);
56
+ this.proposals = new R.ProposalsResource(client);
57
+ this.feed = new R.FeedResource(client);
58
+ this.batches = new R.BatchesResource(client);
59
+ this.esf = new R.EsfResource(client);
60
+ this.forms = new R.FormsResource(client);
61
+ this.onec = new R.OnecResource(client);
62
+ this.automations = new R.AutomationsResource(client);
63
+ }
64
+ /** Base URL the client talks to. */
65
+ get baseUrl() {
66
+ return this.#client.baseUrl;
67
+ }
68
+ /**
69
+ * Performs an arbitrary API call with the client's authentication, retries, timeouts and error
70
+ * handling. Use it for endpoints this SDK version does not cover yet.
71
+ */
72
+ request(spec) {
73
+ return this.#client.request(spec);
74
+ }
75
+ /**
76
+ * Asks the assistant one question and waits for the complete answer (no streaming).
77
+ * If the turn reports an error, the matching typed APIError is thrown; its `partialResult`
78
+ * holds the turn as returned.
79
+ */
80
+ async ask(companyId, message, options) {
81
+ const { data, response } = await this.chat.create(companyId, chatBody(message), options).withResponse();
82
+ const first = Array.isArray(data.errors) ? data.errors[0] : undefined;
83
+ if (first !== undefined) {
84
+ const failure = chatTurnError(first, null, response);
85
+ failure.partialResult = data;
86
+ throw failure;
87
+ }
88
+ return data;
89
+ }
90
+ /** Asks the assistant and streams the events of the turn as they are produced. */
91
+ streamChat(companyId, message, options) {
92
+ return this.chat.stream(companyId, chatBody(message), options);
93
+ }
94
+ /**
95
+ * Streams a chat turn, calling the callbacks as events arrive, and returns the assembled turn.
96
+ * A mid-stream `error` event is thrown as the matching typed APIError.
97
+ */
98
+ streamChatWithResult(companyId, message, callbacks, options) {
99
+ return this.chat.stream(companyId, chatBody(message), options).finalResult(callbacks);
100
+ }
101
+ /** Answers a clarifying question of the assistant (a `choice` event) and waits for the rest of the turn. */
102
+ answerQuestion(companyId, dialogId, choiceId, answers, options) {
103
+ return this.chat.answer(companyId, dialogId, { choice_id: choiceId, answers }, options);
104
+ }
105
+ /**
106
+ * Uploads a bank statement for processing into proposals. `content` is the file bytes, or a
107
+ * string: base64 of the file by default, or the statement text itself with `{ text: true }`.
108
+ */
109
+ uploadBankStatement(companyId, fileName, content, options = {}) {
110
+ const { text, limit, ...requestOptions } = options;
111
+ const body = { file_name: fileName };
112
+ if (typeof content === 'string') {
113
+ if (text === true)
114
+ body.text = content;
115
+ else
116
+ body.file = content;
117
+ }
118
+ else {
119
+ body.file = bytesToBase64(content instanceof ArrayBuffer ? new Uint8Array(content) : content);
120
+ }
121
+ if (limit !== undefined)
122
+ body.limit = limit;
123
+ return this.batches.createBankStatement(companyId, body, requestOptions);
124
+ }
125
+ /**
126
+ * Sends an event to an incoming automation hook (`/hooks/{token}`). With `secret`, the exact
127
+ * bytes sent are signed in the `X-Signature: sha256=<hex>` header, or in `signatureHeader` for a
128
+ * hook created with its own `signature_header`. The API key is not sent.
129
+ * Same as `client.automations.postHook`.
130
+ */
131
+ sendHook(token, payload, options) {
132
+ return this.automations.postHook(token, payload, options);
133
+ }
134
+ /**
135
+ * Verifies an outgoing webhook and returns the typed event. Uses `options.secret`, else the
136
+ * client's webhook secret. Throws a WebhookVerificationError when the webhook is not authentic.
137
+ */
138
+ async verifyWebhook(body, headers, options = {}) {
139
+ const { secret, ...rest } = options;
140
+ return verifyWebhook(body, headers, this.#client.webhookSecret(secret), rest);
141
+ }
142
+ /** Starts a scenario run and waits until it finishes (see {@link Tungo.waitForRun}). */
143
+ async runScenarioAndWait(companyId, scenarioId, body, options = {}) {
144
+ const requestOptions = { signal: options.signal };
145
+ const started = await this.automations.runScenario(companyId, scenarioId, body, requestOptions);
146
+ return this.waitForRun(companyId, started.id, options);
147
+ }
148
+ /**
149
+ * Polls an automation run until it reaches a final state (done, error, skipped, cancelled). A state this
150
+ * SDK version does not know is treated as "still running". Throws a TimeoutError at the deadline.
151
+ */
152
+ waitForRun(companyId, runId, options = {}) {
153
+ return this.#poll('the automation run to finish', (requestOptions) => this.automations.getRun(companyId, runId, requestOptions).withResponse(), (run, response) => {
154
+ const state = run?.state;
155
+ if (typeof state !== 'string') {
156
+ throw new DecodeError('The automation run has no "state"', { status: response.status, requestId: response.requestId, body: debugJSON(run) });
157
+ }
158
+ return RUN_FINAL_STATES.includes(state);
159
+ }, options);
160
+ }
161
+ /** Polls a batch job until it stops running. Throws a TimeoutError at the deadline. */
162
+ waitForBatch(companyId, batchId, options = {}) {
163
+ return this.#poll('the batch job to finish', (requestOptions) => this.batches.get(companyId, batchId, requestOptions).withResponse(), (job, response) => {
164
+ const running = job?.running;
165
+ if (typeof running !== 'boolean') {
166
+ throw new DecodeError('The batch job has no "running" flag', { status: response.status, requestId: response.requestId, body: debugJSON(job) });
167
+ }
168
+ return !running;
169
+ }, options);
170
+ }
171
+ async #poll(what, load, finished, options) {
172
+ const timeout = options.timeout ?? 600_000;
173
+ const outer = options.signal ?? undefined;
174
+ if (outer !== undefined && outer.aborted)
175
+ throw new AbortError('The wait was aborted', { cause: outer.reason });
176
+ const deadline = Date.now() + timeout;
177
+ let pause = options.pollInterval ?? 1000;
178
+ const longest = Math.max(pause, options.maxPollInterval ?? 5000);
179
+ // One signal ends everything the wait does (a poll request, its retries, the pause between
180
+ // polls) at the deadline, so the wait cannot outlive it by a request timeout or by retries.
181
+ const controller = new AbortController();
182
+ let expired = false;
183
+ const timer = startTimer(() => {
184
+ expired = true;
185
+ controller.abort();
186
+ }, timeout);
187
+ const onAbort = () => {
188
+ controller.abort(outer?.reason);
189
+ };
190
+ if (outer !== undefined)
191
+ outer.addEventListener('abort', onAbort, { once: true });
192
+ const late = (cause) => new TimeoutError('Timed out after ' + timeout + ' ms waiting for ' + what, timeout, { cause });
193
+ try {
194
+ for (;;) {
195
+ const { data, response } = await load({ signal: controller.signal });
196
+ if (finished(data, response))
197
+ return data;
198
+ const left = deadline - Date.now();
199
+ if (left <= 0)
200
+ throw late();
201
+ await sleep(Math.min(pause, left), controller.signal);
202
+ pause = Math.min(pause * 1.5, longest);
203
+ }
204
+ }
205
+ catch (cause) {
206
+ // The deadline aborted whatever was pending: report the deadline, not the abort.
207
+ if (expired && cause instanceof AbortError && !(outer !== undefined && outer.aborted))
208
+ throw late(cause);
209
+ throw cause;
210
+ }
211
+ finally {
212
+ clearTimeout(timer);
213
+ if (outer !== undefined)
214
+ outer.removeEventListener('abort', onAbort);
215
+ }
216
+ }
217
+ /** A description without secrets (the API key is never included). */
218
+ toJSON() {
219
+ return { baseUrl: this.#client.baseUrl, timeout: this.#client.timeout, maxRetries: this.#client.maxRetries };
220
+ }
221
+ }
@@ -0,0 +1,217 @@
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
+ /**
82
+ * Your own `Idempotency-Key` for an operation that declares the header (without it the SDK
83
+ * generates one). Other operations do not send it and are not retried because of it.
84
+ */
85
+ idempotencyKey?: string | undefined;
86
+ /** Cancels the request (and its retries and waits). It is combined with the timeout. */
87
+ signal?: AbortSignal | undefined;
88
+ /** For streams: milliseconds without data before the stream fails. */
89
+ streamIdleTimeout?: number | undefined;
90
+ }
91
+ /** Description of one HTTP call. The generated resource methods build these. */
92
+ export interface RequestSpec {
93
+ method: string;
94
+ /** Path template such as `/v1/companies/{co}`. */
95
+ path: string;
96
+ /** Values of the path parameters; each is validated and percent-encoded as one segment. */
97
+ pathParams?: Record<string, string> | undefined;
98
+ /** Query parameters; null and undefined values are omitted, arrays repeat the key. */
99
+ query?: object | undefined;
100
+ /** JSON body. */
101
+ body?: unknown;
102
+ /** Exact bytes to send instead of a JSON body. */
103
+ rawBody?: Uint8Array | string | undefined;
104
+ /** Content type of `rawBody`. */
105
+ contentType?: string | undefined;
106
+ /** Operation-specific headers. */
107
+ headers?: Record<string, string | undefined> | undefined;
108
+ /** `key`: send the API key. `public` and `hook`: never send credentials. Default: `key`. */
109
+ auth?: 'key' | 'public' | 'hook' | undefined;
110
+ /** Wire name of the idempotency header when the operation declares one. */
111
+ idempotencyHeader?: string | undefined;
112
+ /**
113
+ * Key sent in the idempotency header when the caller gives none (neither `idempotencyKey` nor the
114
+ * header itself, per request or in the client's default headers). Default: a random UUID.
115
+ */
116
+ defaultIdempotencyKey?: string | undefined;
117
+ /** Use the long-running timeout by default. */
118
+ longRunning?: boolean | undefined;
119
+ /** The success response has no body. */
120
+ emptyResult?: boolean | undefined;
121
+ options?: RequestOptions | undefined;
122
+ }
123
+ /** A decoded response together with its status and headers. */
124
+ export interface WithResponse<T> {
125
+ data: T;
126
+ response: ResponseInfo;
127
+ }
128
+ export declare function readEnv(name: string): string | undefined;
129
+ /** A random RFC 4122 version 4 UUID from the platform CSPRNG. */
130
+ export declare function uuid4(): string;
131
+ /**
132
+ * Percent-encodes a value as ONE path segment (`/`, `?`, `#`, spaces, CR/LF and non-ASCII are all
133
+ * encoded). An empty value, `.` and `..` are rejected because they would change the path.
134
+ */
135
+ export declare function encodePathSegment(value: unknown, name?: string): string;
136
+ /** Fills a path template (`/v1/companies/{co}`) with encoded parameter values. */
137
+ export declare function buildPath(template: string, params: Record<string, string> | undefined): string;
138
+ /**
139
+ * Builds a query string (without the leading `?`): booleans as `true`/`false`, dates as RFC 3339,
140
+ * arrays as repeated keys, null and undefined omitted, `+` encoded as `%2B`.
141
+ */
142
+ export declare function buildQuery(query: object | undefined): string;
143
+ /** Delay before retry number `attempt` (0-based), in milliseconds: min(0.5 s * 2^attempt, 8 s) * [0.75, 1]. */
144
+ export declare function backoffDelay(attempt: number, random?: () => number): number;
145
+ /** Statuses after which a request may be repeated. */
146
+ export declare function isRetryableStatus(status: number): boolean;
147
+ /**
148
+ * The retry rule: the failure must be transient (a retryable status, a connection error or a
149
+ * timeout) AND repeating the request must be safe (GET, HEAD, PUT, DELETE, or any request that
150
+ * carries an idempotency key).
151
+ */
152
+ export declare function shouldRetry(method: string, hasIdempotencyKey: boolean, cause: number | 'connection_error' | 'timeout'): boolean;
153
+ /**
154
+ * Starts a timer, or none (undefined) when the delay is infinite or longer than the platform can
155
+ * count: `setTimeout` would fire such a timer at once instead of never.
156
+ */
157
+ export declare function startTimer(callback: () => void, ms: number): ReturnType<typeof setTimeout> | undefined;
158
+ /**
159
+ * Waits `ms` milliseconds; rejects with an AbortError as soon as the signal aborts. A delay above
160
+ * {@link MAX_TIMER_MS} waits until the signal aborts.
161
+ */
162
+ export declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
163
+ /**
164
+ * A promise of a decoded response that also gives access to the raw response:
165
+ * `await client.companies.get(id)` yields the data, `.withResponse()` adds status, headers,
166
+ * request id and rate-limit information of that very response.
167
+ */
168
+ export declare class APIPromise<T> extends Promise<T> {
169
+ #private;
170
+ constructor(result: Promise<WithResponse<T>>);
171
+ /** The decoded data together with the status, headers, request id and rate limit of the response. */
172
+ withResponse(): Promise<WithResponse<T>>;
173
+ /** Only the status, headers, request id and rate limit of the response. */
174
+ asResponse(): Promise<ResponseInfo>;
175
+ then<A = T, B = never>(onfulfilled?: ((value: T) => A | PromiseLike<A>) | null, onrejected?: ((reason: unknown) => B | PromiseLike<B>) | null): Promise<A | B>;
176
+ catch<B = never>(onrejected?: ((reason: unknown) => B | PromiseLike<B>) | null): Promise<T | B>;
177
+ finally(onfinally?: (() => void) | null): Promise<T>;
178
+ static get [Symbol.species](): PromiseConstructor;
179
+ }
180
+ /**
181
+ * A promise of an open stream that can also be iterated directly:
182
+ * `for await (const event of client.feed.listEvents(co))`. Awaiting it gives the stream object
183
+ * (with `response`, `close()` and, for chat streams, `dialogId` and `turnNo`).
184
+ */
185
+ export declare class StreamPromise<T, S extends Stream<T> = Stream<T>> extends Promise<S> implements AsyncIterable<T> {
186
+ #private;
187
+ constructor(stream: Promise<S>);
188
+ then<A = S, B = never>(onfulfilled?: ((value: S) => A | PromiseLike<A>) | null, onrejected?: ((reason: unknown) => B | PromiseLike<B>) | null): Promise<A | B>;
189
+ catch<B = never>(onrejected?: ((reason: unknown) => B | PromiseLike<B>) | null): Promise<S | B>;
190
+ finally(onfinally?: (() => void) | null): Promise<S>;
191
+ [Symbol.asyncIterator](): AsyncGenerator<T, void, undefined>;
192
+ static get [Symbol.species](): PromiseConstructor;
193
+ }
194
+ /**
195
+ * The HTTP engine shared by all resources: configuration, authentication, retries, timeouts,
196
+ * cancellation and decoding. It is immutable after construction and safe to share.
197
+ */
198
+ export declare class APIClient {
199
+ #private;
200
+ /** Base URL without a trailing slash. */
201
+ readonly baseUrl: string;
202
+ /** Default request timeout in milliseconds. */
203
+ readonly timeout: number;
204
+ /** Default timeout of non-streaming chat turns in milliseconds. */
205
+ readonly longRunningTimeout: number;
206
+ /** Default number of retries. */
207
+ readonly maxRetries: number;
208
+ /** Default idle timeout of streams in milliseconds. */
209
+ readonly streamIdleTimeout: number;
210
+ constructor(options?: ClientOptions);
211
+ /** The webhook secret to use: the explicit one, else the client's; a ConfigError when there is none. */
212
+ webhookSecret(explicit?: string): string;
213
+ /** Performs a request and decodes the JSON response. */
214
+ request<T>(spec: RequestSpec): APIPromise<T>;
215
+ /** Opens a server-sent event stream; `make` wraps the connection into the stream object. */
216
+ openStream<S>(spec: RequestSpec, make: (init: StreamInit) => S): Promise<S>;
217
+ }