@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.
- package/CHANGELOG.md +93 -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 +152 -0
- package/dist/cjs/client.d.ts +117 -0
- package/dist/cjs/client.js +225 -0
- package/dist/cjs/core.d.ts +217 -0
- package/dist/cjs/core.js +779 -0
- package/dist/cjs/errors.d.ts +237 -0
- package/dist/cjs/errors.js +446 -0
- package/dist/cjs/generated/resources.d.ts +1149 -0
- package/dist/cjs/generated/resources.js +1145 -0
- package/dist/cjs/generated/types.d.ts +5435 -0
- package/dist/cjs/generated/types.js +11 -0
- package/dist/cjs/index.d.ts +12 -0
- package/dist/cjs/index.js +81 -0
- package/dist/cjs/json.d.ts +16 -0
- package/dist/cjs/json.js +137 -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 +114 -0
- package/dist/cjs/streaming.d.ts +76 -0
- package/dist/cjs/streaming.js +291 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +6 -0
- package/dist/cjs/webhooks.d.ts +79 -0
- package/dist/cjs/webhooks.js +262 -0
- package/dist/esm/chat.d.ts +85 -0
- package/dist/esm/chat.js +144 -0
- package/dist/esm/client.d.ts +117 -0
- package/dist/esm/client.js +221 -0
- package/dist/esm/core.d.ts +217 -0
- package/dist/esm/core.js +763 -0
- package/dist/esm/errors.d.ts +237 -0
- package/dist/esm/errors.js +416 -0
- package/dist/esm/generated/resources.d.ts +1149 -0
- package/dist/esm/generated/resources.js +1129 -0
- package/dist/esm/generated/types.d.ts +5435 -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 +16 -0
- package/dist/esm/json.js +132 -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 +108 -0
- package/dist/esm/streaming.d.ts +76 -0
- package/dist/esm/streaming.js +285 -0
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +3 -0
- package/dist/esm/webhooks.d.ts +79 -0
- package/dist/esm/webhooks.js +253 -0
- package/package.json +67 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to the Tungo SDK for TypeScript are documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
<!-- Generated by tungo-sdkgen: edit changelogReleases in the generator, not this file. -->
|
|
9
|
+
|
|
10
|
+
## [Unreleased]
|
|
11
|
+
|
|
12
|
+
## [0.3.0] - 2026-11-13
|
|
13
|
+
|
|
14
|
+
Generated from the platform contract of backend 44066d62. It contains breaking type changes compared with 0.2.0.
|
|
15
|
+
|
|
16
|
+
### Breaking
|
|
17
|
+
|
|
18
|
+
- `Company.legal_form` and `CompanyListItem.legal_form` can be null: the legal form of a company is not set yet (it is set with `PATCH /v1/companies/{co}`). The field is now nullable or optional in every SDK (`CompanyLegalForm | null`, `Optional[CompanyLegalForm]`, `*CompanyLegalForm`, `Option<CompanyLegalForm>`, `Optional<CompanyLegalForm>`, `CompanyLegalForm?`).
|
|
19
|
+
- `ApiKeyRolled.key` is null when a key roll is replayed by `Idempotency-Key`; the new `key_note` says why and what to do if the new secret was lost. The field is now nullable in every SDK.
|
|
20
|
+
- `ApiKeyCreate.permissions` is optional (a key with `no_companies: true` gets no company permissions). Constructors and builders no longer require it (Rust: `ApiKeyCreate::new(name)`), accessors return an optional value, and Go leaves the field out for a nil list instead of sending `[]`.
|
|
21
|
+
- New union variants: `ChatEvent` gains `next` (`ChatEventNext`) and `title` (`ChatEventTitle`), `ChatHistoryBlock` gains `batch` (`ChatHistoryBatch`). An exhaustive `switch`/`when`/`match` over these unions needs the new cases.
|
|
22
|
+
- PHP and Kotlin: `proposals.list` and `listAll` gained the optional filters `approval_requested`, `batch_id` and `source` before existing parameters, so positional arguments after the company shift. Pass these parameters by name (PHP named arguments, Kotlin named arguments).
|
|
23
|
+
- An `Idempotency-Key` is sent only to operations that declare it: a caller's own `Idempotency-Key` on any other operation is no longer sent, and no longer makes a POST retryable. Approving a proposal uses the `idempotency_key` of the body as the header instead of generating one.
|
|
24
|
+
- Response models gained required fields (`no_companies` on the `ApiKey*` models; `title_source` on `ChatDialog`, `ChatDialogSummary` and `ChatDialogRenamed`; `followups` and `next_action` on `ChatAssistantMessage` and `ChatTurnResult`; `turn_no` and `rating` on `ChatAssistantMessage`; `rating` and `rating_prompt` on `ChatDialog`; `label` and `document` on `ChatCitation` and `ChatEventCitation`; `approval_request`, `origin` and `status_reason` on `ProposalCard` and `ProposalListItem`; `approval_requested_count` on `ProposalPage`; `object` on `AuditEntry`; `statement` on `BatchSummary`; `total` and `total_more` on the platform audit and request lists; and others). Decoding is unaffected; code that constructs these models itself (test fakes) must pass the new fields.
|
|
25
|
+
|
|
26
|
+
### Added
|
|
27
|
+
|
|
28
|
+
- `chat.list_mentions` (`GET /v1/companies/{co}/chat/mentions`): finds proposals, batches and counterparties to mention in a question (`ChatMentionSearch`, `ChatMentionItem`, `ChatMentionUnavailable`). Questions take `mentions` (`ChatMention`), and history shows them (`ChatUserMessage.mentions`, `ChatHistoryMention`).
|
|
29
|
+
- `chat.list_suggestions` (`GET /v1/companies/{co}/chat/suggestions`, `lang` `ru` or `kk`): suggested questions grouped by topic (`ChatSuggestions`, `ChatSuggestionGroup`, `ChatSuggestion` with `code`, `action`, `title`, `hint`, `prompt` and `seasonal`).
|
|
30
|
+
- `proposals.request_approval` (`POST /v1/companies/{co}/proposals/{id}/request-approval`, optional `note`): asks the people who may approve a proposal to look at it (`ProposalApprovalRequestResult`). Proposals carry `approval_request` (`ProposalApprovalRequest`, `ProposalApprovalRequested`), `origin` (`ProposalOrigin`) and `status_reason`; `proposals.list` filters by `approval_requested`, `batch_id` and `source`; `ProposalHistoryEvent.code`.
|
|
31
|
+
- Chat: the dialog title has a `title_source` (`ChatTitleSource`: `first_message`, `ai`, `user`) and a `title` stream event (`ChatEventTitle`, sent to cabinet sessions only); a turn ends with suggested follow-ups and a next action (`followups`, `next_action`, `ChatNextAction`, event `next`); questions take `effort` (`low` to `max`); choice questions have `confirm`, answers `skipped`, and history shows the answer (`ChatHistoryQuestion.answer`); history shows batch jobs (`ChatHistoryBatch`).
|
|
32
|
+
- Chat ratings: `chat.rate_message` (`PUT /v1/companies/{co}/chat/{id}/messages/{turn}/rating`, `ChatMessageRatingBody` with `vote` `up` or `down`, optional `reason` and `comment`) rates one answer and `chat.delete_message_rating` (`DELETE` on the same path) removes that rating, both answering `ChatMessageRated`; `chat.rate` (`PUT /v1/companies/{co}/chat/{id}/rating`, `ChatDialogRatingBody` with `score` 1 to 5 and optional `comment`) rates the whole dialog (`ChatDialogRated`); `chat.dismiss_rating` (`POST /v1/companies/{co}/chat/{id}/rating/dismiss`) closes the offer to rate it (`ChatRatingDismissed`); `chat.get_rating_options` (`GET /v1/companies/{co}/chat/rating-options`, `lang` `ru` or `kk`) returns what a rating form needs (`ChatRatingOptions`: `reasons`, `comment_chars`, `dialog_scores`).
|
|
33
|
+
- Chat history: an assistant message has its `turn_no` (the `turn` of the rating methods) and its `rating` (`ChatMessageRating`); a dialog has its `rating` (`ChatDialogRating`) and `rating_prompt`, and the `done` stream event has an optional `rating_prompt` when it is time to offer rating the dialog (cabinet sessions only: with an API key it is always false or absent).
|
|
34
|
+
- Chat citations: `ChatCitation` and the `citation` stream event (`ChatEventCitation`) have a display `label` and the `document`, and optionally `article`, `point`, `subpoint`, `chapter`, `heading`, `edition_date` and `note` (a status mark such as a repealed norm, to be shown); `ChatCitation.mentions` lists how the answer text names the source, so those fragments can link to it.
|
|
35
|
+
- Errors: rating error codes `dialog_not_ratable`, `message_not_found`, `rating_reason_unknown`, `rating_reason_not_allowed`, `rating_comment_too_long` and `ratings_unavailable`.
|
|
36
|
+
- Batches: `BatchSummary.statement` describes a parsed bank statement by account (`BatchStatement`, `BatchStatementAccount`).
|
|
37
|
+
- Errors: `ErrorDetail` gains `free_blocked_reason`, `retry_after_seconds`, `next_request_at`, `amount_tiyn` and `payment_id`; chat turn errors gain the code `parallel_turns_limit` and limit kinds `disabled`, `meter`, `plan` and `turn`.
|
|
38
|
+
- API keys: `no_companies` on the API key models, on `ApiKeyCreate` and on `ApiKeyPatch`; `ApiKeyRolled.key_note`.
|
|
39
|
+
- Platform: `total` and `total_more` on the audit and request lists; `PlatformRequest.cost_tiyn`; `PlatformLedgerEntry.documents` (invoice, act and receipt); `PlatformAccountPurchaseLimits.today_tiyn`; `UsageRate.title` and `UsageRate.cache_write_1h_per_mtok_tiyn`; `AuditEntry.object` (`AuditEntryObject`) and new audit actions.
|
|
40
|
+
- Billing models used by the cabinet: `CardSessionState`, `CardSession.test_mode`, `PayForm.test_mode`.
|
|
41
|
+
|
|
42
|
+
### Fixed
|
|
43
|
+
|
|
44
|
+
- A chat turn replayed by `Idempotency-Key`, including a stream call retried after a 502, arrives as its events; Python typed streams expose `last_event_id` for resuming.
|
|
45
|
+
- A replayed chat turn keeps its follow-ups and next action: when the stored result has `followups` or a `next_action`, the rebuilt stream yields the `next` event right before `done`, as a live turn does.
|
|
46
|
+
- An `error` event of the feed stream ends the stream with a typed error; Kotlin delivers the event that the end of a stream completes.
|
|
47
|
+
- Incoming hooks: the event id is the default `Idempotency-Key` (a caller's own header wins), and the signature goes into the hook's own `signature_header`.
|
|
48
|
+
- Webhook verification treats an infinite tolerance as `invalid_tolerance`.
|
|
49
|
+
- Money: the exponent of a decimal is bounded before it is converted to tiyn.
|
|
50
|
+
- Bad header values and base URLs fail locally without a request; transport and timeout errors no longer include the URL (Go, TypeScript); a decode error's debug output does not show the body (Rust).
|
|
51
|
+
- TypeScript: error paths serialise `bigint` safely and keep 64-bit extra fields exact; `debugJSON` returns `''` for a value JSON cannot express.
|
|
52
|
+
- Python: a `datetime` passed for a calendar-date parameter is sent as its date.
|
|
53
|
+
- Go: `UploadBankStatement` sends text that is not UTF-8 as the file instead of failing.
|
|
54
|
+
- Java: `close()` fails the asynchronous calls still waiting in the owned pool; `Retry-After` reads the RFC 850 date with a two-digit year; a key or header value with a control character is never quoted; error envelope fields are read in a way that works with Jackson 2.14, the documented minimum.
|
|
55
|
+
- PHP: `sendHook` reads the headers of optional request options null-safely.
|
|
56
|
+
- Ruby: the percent-encoded credentials of an explicit proxy are decoded.
|
|
57
|
+
- Swift: the `URLSession` of the SDK has no URL cache.
|
|
58
|
+
- .NET: a custom platform handler that follows redirects, or whose redirect setting cannot be read, is refused.
|
|
59
|
+
|
|
60
|
+
### Known limitations
|
|
61
|
+
|
|
62
|
+
- Batch and proposal export downloads (xlsx, csv, pdf: `GET /v1/companies/{co}/batch/{id}/export` and `GET /v1/companies/{co}/proposals/{id}/export`) are not in this release: the SDKs cannot return a file body yet.
|
|
63
|
+
|
|
64
|
+
## [0.2.0] - 2026-11-12
|
|
65
|
+
|
|
66
|
+
First production-ready release. It contains breaking changes compared with 0.1.0; 0.1.0 should not be used.
|
|
67
|
+
|
|
68
|
+
### Changed
|
|
69
|
+
|
|
70
|
+
- The package is renamed from `@tungo/sdk` to `@tungoai/sdk`.
|
|
71
|
+
- Requests and responses use typed models generated from the API contract.
|
|
72
|
+
- Errors are classified by the `error.type` of the API error envelope, with the HTTP status as a fallback; the `hint` field, which the API never sent, is removed.
|
|
73
|
+
- Retries happen only for requests that are safe to repeat (idempotent methods, or requests carrying an `Idempotency-Key`), with jittered exponential backoff that honours `retry-after-ms` and `Retry-After`.
|
|
74
|
+
- Timeouts cover the whole request, are configurable per client and per request, and combine with caller-supplied cancellation.
|
|
75
|
+
- Server-sent events are delivered incrementally; closing or abandoning a stream closes the connection.
|
|
76
|
+
- List methods return typed pages and offer an auto-paging iterator.
|
|
77
|
+
- Webhook verification enforces the timestamp tolerance against the system clock and reports every failure as a typed error.
|
|
78
|
+
- Money helpers parse decimal strings exactly; tiyn amounts are 64-bit integers.
|
|
79
|
+
- The default base URL is `https://api.tungo.kz`; it can be set with `TUNGO_BASE_URL`.
|
|
80
|
+
- The package ships ES modules and CommonJS with type declarations for both, and runs on Node.js 20+, Deno, Bun, Cloudflare Workers and browsers (Web Crypto and `fetch` only; no Node.js-only APIs).
|
|
81
|
+
- Webhook verification and hook signing are asynchronous (`await client.verifyWebhook(...)`) because they use Web Crypto.
|
|
82
|
+
- Every call returns an `APIPromise` with `.withResponse()`; list methods return a `Page` that is also an async iterator; streams are typed (`ChatEvent`) and closeable.
|
|
83
|
+
- Error classes are renamed: `APIError` with one subclass per `error.type`, plus `ConnectionError`, `TimeoutError`, `AbortError`, `DecodeError`, `ConfigError`, `ValidationError`.
|
|
84
|
+
- Client options `timeoutMs`, `useBearerAuth`, `companyId`, `workspaceId`, `debug`, `onRequest`, `onResponse` and the request option `clientRequestId` are removed; use `timeout`, `authScheme`, `logger` and explicit ids.
|
|
85
|
+
|
|
86
|
+
## [0.1.0] - 2026-11-09
|
|
87
|
+
|
|
88
|
+
Initial preview. Not suitable for production use.
|
|
89
|
+
|
|
90
|
+
[Unreleased]: https://github.com/TungoAI/tungo-sdk-typescript/compare/v0.3.0...HEAD
|
|
91
|
+
[0.3.0]: https://github.com/TungoAI/tungo-sdk-typescript/compare/v0.2.0...v0.3.0
|
|
92
|
+
[0.2.0]: https://github.com/TungoAI/tungo-sdk-typescript/compare/v0.1.0...v0.2.0
|
|
93
|
+
[0.1.0]: https://github.com/TungoAI/tungo-sdk-typescript/releases/tag/v0.1.0
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Tungo AI (https://tungo.kz)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.kk.md
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
<!-- Generated by tungo-sdkgen. Do not edit: the file is rewritten on every generation. -->
|
|
2
|
+
|
|
3
|
+
<div align="center">
|
|
4
|
+
|
|
5
|
+
<picture>
|
|
6
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/TungoAI/.github/main/assets/logo02.svg" />
|
|
7
|
+
<source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/TungoAI/.github/main/assets/logo03.svg" />
|
|
8
|
+
<img alt="Tungo AI" src="https://raw.githubusercontent.com/TungoAI/.github/main/assets/logo03.svg" width="240" />
|
|
9
|
+
</picture>
|
|
10
|
+
|
|
11
|
+
# TypeScript үшін Tungo SDK
|
|
12
|
+
|
|
13
|
+
**Tungo платформасының API-іне арналған ресми TypeScript кітапханасы**
|
|
14
|
+
|
|
15
|
+
[](https://www.npmjs.com/package/@tungoai/sdk)
|
|
16
|
+
[](https://github.com/TungoAI/tungo-sdk-typescript/actions/workflows/ci.yml)
|
|
17
|
+
[](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/LICENSE)
|
|
18
|
+
|
|
19
|
+
[English](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/README.md) · [Русский](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/README.ru.md) · **Қазақша**
|
|
20
|
+
|
|
21
|
+
[tungo.kz](https://tungo.kz) · [Жылдам бастау](#жылдам-бастау) · [API анықтамалығы](#api-анықтамалығы) · [Өзгерістер тарихы](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/CHANGELOG.md) · [Өтініштер](https://github.com/TungoAI/tungo-sdk-typescript/issues)
|
|
22
|
+
|
|
23
|
+
</div>
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
Tungo платформасының API-іне (`https://api.tungo.kz`) арналған ресми TypeScript кітапханасы: ЖИ-бухгалтер, 1С-пен жұмыс, банк үзінді көшірмелері, электрондық шот-фактуралар, салық нысандары және [Tungo AI](https://tungo.kz) автоматтандырулары.
|
|
28
|
+
|
|
29
|
+
Кітапхана API-дің OpenAPI келісімшартынан жасалады, сондықтан оның әдістері мен модельдері өзі жиналған келісімшартқа әрдайым сәйкес келеді.
|
|
30
|
+
|
|
31
|
+
> Тек осы тілге қатысты ескертпелері бар толық нұсқа — [ағылшынша README](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/README.md) файлында.
|
|
32
|
+
|
|
33
|
+
## Талаптар
|
|
34
|
+
|
|
35
|
+
Қолдау көрсетілетін нұсқалар мен тәуелділіктер [ағылшынша README](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/README.md#requirements) файлында келтірілген.
|
|
36
|
+
|
|
37
|
+
## Орнату
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
npm install @tungoai/sdk
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Жылдам бастау
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
import { Tungo } from '@tungoai/sdk';
|
|
47
|
+
|
|
48
|
+
const client = new Tungo(); // reads TUNGO_API_KEY
|
|
49
|
+
|
|
50
|
+
const { data: companies } = await client.companies.list();
|
|
51
|
+
for (const company of companies) {
|
|
52
|
+
console.log(company.id, company.name);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const reply = await client.ask('co_01h455vb4pex5vsknk084sn02q', 'What VAT applies to the last sale?');
|
|
56
|
+
console.log(reply.answer);
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Аутентификация және баптау
|
|
60
|
+
|
|
61
|
+
Бір клиент жасап, оны барлық жерде қолданыңыз: ол өзгермейді және бірнеше ағыннан немесе тапсырмадан қауіпсіз пайдаланылады. Кез келген параметрді анық беруге болады; берілмесе, олардың үшеуі орта айнымалыларынан алынады.
|
|
62
|
+
|
|
63
|
+
| Параметр | Орта айнымалысы | Әдепкі мәні |
|
|
64
|
+
| --- | --- | --- |
|
|
65
|
+
| API кілті | `TUNGO_API_KEY` | жоқ |
|
|
66
|
+
| Негізгі мекенжай | `TUNGO_BASE_URL` | `https://api.tungo.kz` |
|
|
67
|
+
| Вебхук құпиясы | `TUNGO_WEBHOOK_SECRET` | жоқ |
|
|
68
|
+
| Күту уақыты | | 60 с (чаттың ағынсыз жауаптары үшін 600 с) |
|
|
69
|
+
| Қайталаудың ең көп саны | | 2 |
|
|
70
|
+
| Әдепкі тақырыптар, HTTP-клиент | | жоқ, кіріктірілген |
|
|
71
|
+
|
|
72
|
+
API кілті тек оны талап ететін операцияларға жіберіледі: ашық мекенжайлар мен кіріс хуктар оны алмайды, әрі ол қате мәтіндері мен жөндеу шығысына ешқашан түспейді. Кілт қажет операцияны кілтсіз шақыру сұрау жіберілмей тұрып, сол жерде қатемен аяқталады.
|
|
73
|
+
|
|
74
|
+
Әр әдіс жеке сұраудың параметрлерін де қабылдайды: күту уақыты, қайталау саны, қосымша тақырыптар, идемпотенттік кілті және тоқтату.
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
import { Tungo } from '@tungoai/sdk';
|
|
78
|
+
|
|
79
|
+
const client = new Tungo({
|
|
80
|
+
apiKey: 'tg_...', // default: TUNGO_API_KEY
|
|
81
|
+
baseUrl: 'https://api.tungo.kz', // default: TUNGO_BASE_URL
|
|
82
|
+
webhookSecret: 'whsec_...', // default: TUNGO_WEBHOOK_SECRET
|
|
83
|
+
timeout: 30_000, // milliseconds, covers the whole request
|
|
84
|
+
longRunningTimeout: 300_000, // non-streaming chat turns
|
|
85
|
+
maxRetries: 3,
|
|
86
|
+
defaultHeaders: { 'X-App': 'billing' },
|
|
87
|
+
fetch: (url, init) => fetch(url, init), // any fetch-compatible function: proxy, tracing, mock
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
// Per-request options are the last argument of every method.
|
|
91
|
+
const controller = new AbortController();
|
|
92
|
+
const company = await client.companies.get('co_01h455vb4pex5vsknk084sn02q', {
|
|
93
|
+
timeout: 5_000,
|
|
94
|
+
maxRetries: 0,
|
|
95
|
+
headers: { 'X-Trace-Id': 'trace-123' },
|
|
96
|
+
signal: controller.signal,
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
// Status, headers, request id and rate limit of any call.
|
|
100
|
+
const { data, response } = await client.companies.get(company.id).withResponse();
|
|
101
|
+
console.log(data.name, response.status, response.requestId, response.rateLimit?.remaining);
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## Қателер
|
|
105
|
+
|
|
106
|
+
Кез келген ақау — SDK-ның негізгі қатесінің ішкі түрі. HTTP қатесі бар жауап API қатесіне айналады: оның түрі жауап денесіндегі `error.type` өрісі бойынша, ал дене API-дің стандартты қатесі болмаса, HTTP күйі бойынша таңдалады:
|
|
107
|
+
|
|
108
|
+
| `error.type` | Күйі |
|
|
109
|
+
| --- | --- |
|
|
110
|
+
| `invalid_request_error` | 400 |
|
|
111
|
+
| `authentication_error` | 401 |
|
|
112
|
+
| `payment_required_error` | 402 |
|
|
113
|
+
| `permission_error` | 403 |
|
|
114
|
+
| `not_found_error` | 404 |
|
|
115
|
+
| `conflict_error` | 409 |
|
|
116
|
+
| `gone_error` | 410 |
|
|
117
|
+
| `limit_error` | 429 |
|
|
118
|
+
| `api_error` | 500 |
|
|
119
|
+
| `unavailable_error` | 503 |
|
|
120
|
+
|
|
121
|
+
API қатесінде күй, түр, код, хабарлама, сұрау идентификаторы, өріс қателері, қайталау алдындағы талданған кідіріс, жауап тақырыптары және бастапқы дене болады. Жауапсыз болған ақаулардың өз түрлері бар: байланыс қатесі, күту уақытының бітуі, талдау қатесі (денесі жарамсыз сәтті жауап), баптау немесе аргументтерді тексеру қатесі (сұрауға дейін туындайды).
|
|
122
|
+
|
|
123
|
+
```ts
|
|
124
|
+
import { APIError, ConnectionError, LimitError, NotFoundError, TimeoutError, Tungo } from '@tungoai/sdk';
|
|
125
|
+
|
|
126
|
+
const client = new Tungo();
|
|
127
|
+
|
|
128
|
+
try {
|
|
129
|
+
await client.proposals.approve('co_01h455vb4pex5vsknk084sn02q', 'P-000042');
|
|
130
|
+
} catch (err) {
|
|
131
|
+
if (err instanceof NotFoundError) {
|
|
132
|
+
console.log('No such proposal');
|
|
133
|
+
} else if (err instanceof LimitError) {
|
|
134
|
+
console.log('Retry in', err.retryAfter, 'seconds; the limit resets at', err.extra['resets_at']);
|
|
135
|
+
} else if (err instanceof APIError) {
|
|
136
|
+
// status, error.type, error.code, the API's message, the id to quote to support, field errors
|
|
137
|
+
console.log(err.status, err.type, err.code, err.detail, err.requestId, err.fields);
|
|
138
|
+
} else if (err instanceof TimeoutError || err instanceof ConnectionError) {
|
|
139
|
+
console.log('Network problem:', err.message);
|
|
140
|
+
} else {
|
|
141
|
+
throw err;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
## Қайталаулар және күту уақыты
|
|
147
|
+
|
|
148
|
+
Сұрау байланыс қателерінде, күту уақыты біткенде және 408, 429, 500, 502, 503, 504 күйлерінде 2 ретке дейін қайталанады (барлығы 3 әрекет), бірақ тек қайталау қауіпсіз болғанда: `GET`, `HEAD`, `PUT` және `DELETE` сұраулары, сондай-ақ келісімшарты `Idempotency-Key` тақырыбын жариялайтын операциялардың `POST` пен `PATCH` сұраулары. Олар үшін SDK кездейсоқ кілтті өзі жасап, оны барлық әрекетте қолданады; өз кілтіңізді беруге болады. Басқа операциялар кілтті, тіпті берілгенін де, жібермейді: API оны онда ескермейді.
|
|
149
|
+
|
|
150
|
+
Әрекеттер арасындағы үзіліс — кездейсоқ ауытқуы бар `min(0,5 с × 2^әрекет, 8 с)`. Жауаптың `retry-after-ms` немесе `Retry-After` тақырыбындағы оң мән оны алмастырады; сервер 60 с-тан ұзақ күтуді сұраса, SDK күтпейді және кідірісі көрсетілген қатені қайтарады.
|
|
151
|
+
|
|
152
|
+
Күту уақыты денені оқуды қоса алғанда бүкіл сұрауды қамтиды. Ағынды шақыруларда жалпы күту уақыты жоқ — тек қосылу уақыты және 120 с бос тұру уақыты бар. Шақырушы код берген тоқтату күту уақытымен бірге әрекет етеді.
|
|
153
|
+
|
|
154
|
+
```ts
|
|
155
|
+
import { Tungo } from '@tungoai/sdk';
|
|
156
|
+
|
|
157
|
+
const client = new Tungo({ maxRetries: 5, timeout: 20_000 });
|
|
158
|
+
|
|
159
|
+
// Override per request.
|
|
160
|
+
await client.companies.list({ maxRetries: 0, timeout: 2_000 });
|
|
161
|
+
|
|
162
|
+
// A POST is retried only when it carries an Idempotency-Key. The SDK generates one for the
|
|
163
|
+
// operations that declare the header; pass your own to make a retry of your own code safe too.
|
|
164
|
+
await client.proposals.approve('co_01h455vb4pex5vsknk084sn02q', 'P-000042', {}, { idempotencyKey: 'approve-P-000042' });
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
## Беттеп шығару
|
|
168
|
+
|
|
169
|
+
Тізімдер курсор арқылы беріледі (`{ data, next_cursor }`). Қарапайым әдіс бір типтелген бетті қайтарады: ол келесі беттің бар-жоғын біледі және оны сұрай алады. Автоматты парақтайтын нұсқа — жалқау итератор: келесі бетті тек қажет болғанда сұрайды, сүзгілеріңізді сақтайды және сіз аралауды тоқтатқан бойда сұрауды доғарады.
|
|
170
|
+
|
|
171
|
+
```ts
|
|
172
|
+
import { Tungo } from '@tungoai/sdk';
|
|
173
|
+
|
|
174
|
+
const client = new Tungo();
|
|
175
|
+
const company = 'co_01h455vb4pex5vsknk084sn02q';
|
|
176
|
+
|
|
177
|
+
// One page.
|
|
178
|
+
const page = await client.proposals.list(company, { status: 'awaiting_approval', limit: 50 });
|
|
179
|
+
console.log(page.data.length, 'of', page.body.total, 'next cursor:', page.nextCursor);
|
|
180
|
+
if (page.hasNextPage()) {
|
|
181
|
+
const next = await page.getNextPage();
|
|
182
|
+
console.log(next.data.length);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// Every item of every page, fetched lazily.
|
|
186
|
+
for await (const proposal of client.proposals.listAll(company, { status: 'awaiting_approval' })) {
|
|
187
|
+
console.log(proposal.id);
|
|
188
|
+
if (proposal.id === 'P-000100') break; // no further pages are requested
|
|
189
|
+
}
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
## Ағынды беру
|
|
193
|
+
|
|
194
|
+
Ағынды операциялар server-sent events қолданады және типтелген оқиғаларды келген бойда береді. Циклден ерте шығу немесе ағынды жабу қосылымды жабады. Ағынды сұрау тек алғашқы байт алынғанға дейін қайталанады; қатесі бар жауап кәдімгі шақырулардағыдай типтелген API қатесіне айналады. Соңғы оқиғаға жетпей үзілген чат ағыны қате деп саналады және ешқашан дайын жауап ретінде берілмейді.
|
|
195
|
+
|
|
196
|
+
```ts
|
|
197
|
+
import { Tungo } from '@tungoai/sdk';
|
|
198
|
+
|
|
199
|
+
const client = new Tungo();
|
|
200
|
+
const company = 'co_01h455vb4pex5vsknk084sn02q';
|
|
201
|
+
|
|
202
|
+
const stream = await client.chat.stream(company, { message: 'Check the November bank statement' });
|
|
203
|
+
console.log('dialog', stream.dialogId, 'turn', stream.turnNo);
|
|
204
|
+
for await (const event of stream) {
|
|
205
|
+
switch (event.type) {
|
|
206
|
+
case 'text':
|
|
207
|
+
console.log(event.delta);
|
|
208
|
+
break;
|
|
209
|
+
case 'tool':
|
|
210
|
+
console.log(event.name, event.status);
|
|
211
|
+
break;
|
|
212
|
+
case 'error':
|
|
213
|
+
console.error(event.error.code, event.error.message);
|
|
214
|
+
break;
|
|
215
|
+
case 'done':
|
|
216
|
+
console.log('finished:', event.stop_reason);
|
|
217
|
+
break;
|
|
218
|
+
default:
|
|
219
|
+
break; // a newer API version may send event types this SDK does not know
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// Or let the SDK assemble the turn. A mid-stream error event is thrown as a typed APIError.
|
|
224
|
+
const turn = await client.streamChatWithResult(company, 'And for October?', {
|
|
225
|
+
onTextDelta: (delta) => console.log(delta),
|
|
226
|
+
});
|
|
227
|
+
console.log(turn.text, turn.stopReason, turn.costTiyn);
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
## Вебхуктар
|
|
231
|
+
|
|
232
|
+
Шығыс вебхуктарға Standard Webhooks (Svix) ерекшелігі бойынша қол қойылады. Тексеру функциясы сұраудың бастапқы денесі мен тақырыптарын (`webhook-*` немесе `svix-*`) қабылдайды, HMAC-SHA256 қолтаңбасын тұрақты уақытта, ал уақыт белгісін жүйелік сағаттан 300 с шегінде тексереді де, типтелген оқиғаны қайтарады. Кез келген мәселе вебхукты тексеру қатесі ретінде хабарланады. Құпия берілмесе, клиенттің вебхук құпиясы қолданылады.
|
|
233
|
+
|
|
234
|
+
Хук жіберу функциясы оқиғаны кіріс хукқа (`/hooks/{token}`) жібереді және құпия берілсе, жіберетін байттардың дәл өзіне `X-Signature: sha256=<hex>` тақырыбында қол қояды. API кілті хуктарға ешқашан жіберілмейді.
|
|
235
|
+
|
|
236
|
+
```ts
|
|
237
|
+
import { Tungo, WebhookVerificationError } from '@tungoai/sdk';
|
|
238
|
+
|
|
239
|
+
const client = new Tungo(); // webhook secret from TUNGO_WEBHOOK_SECRET
|
|
240
|
+
|
|
241
|
+
// A fetch-style handler (Workers, Deno, Bun, Next.js route handlers, Hono, ...).
|
|
242
|
+
export async function handleWebhook(request: Request): Promise<Response> {
|
|
243
|
+
const rawBody = await request.text(); // the exact body: do not parse and re-serialise it
|
|
244
|
+
try {
|
|
245
|
+
const event = await client.verifyWebhook(rawBody, request.headers);
|
|
246
|
+
if (event.type === 'proposal.written') {
|
|
247
|
+
console.log('written to 1C:', event.data.proposal_id);
|
|
248
|
+
}
|
|
249
|
+
return new Response(null, { status: 204 });
|
|
250
|
+
} catch (err) {
|
|
251
|
+
if (err instanceof WebhookVerificationError) {
|
|
252
|
+
return new Response('invalid signature', { status: 400 });
|
|
253
|
+
}
|
|
254
|
+
throw err;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// Send an event to an incoming hook; the body is signed with the hook's secret.
|
|
259
|
+
const accepted = await client.sendHook(
|
|
260
|
+
'th_your_hook_token',
|
|
261
|
+
{ id: 'order_1532', amount_tiyn: 4500000 },
|
|
262
|
+
{ secret: 'your hook secret', eventId: 'order_1532' },
|
|
263
|
+
);
|
|
264
|
+
console.log(accepted.event_id, accepted.duplicate);
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
## Ақша
|
|
268
|
+
|
|
269
|
+
API сомаларды тиынмен (теңгенің 1/100 бөлігі) 64 биттік бүтін сандар түрінде береді. Ақша функциялары ондық жолдар мен дәл ондық мәндерді бөлшек сандардың қателігінсіз тиынға айналдырады, жартыны нөлден әрі қарай дөңгелектейді (`"1.005"` → `101`) және тиынды көрсету үшін пішімдейді (`4500000` → `45 000,00 ₸`). Жарамсыз енгізу типтелген қате тудырады.
|
|
270
|
+
|
|
271
|
+
```ts
|
|
272
|
+
import { TungoMoney, isValidBinIin } from '@tungoai/sdk';
|
|
273
|
+
|
|
274
|
+
console.log(TungoMoney.toTiyn('1.005')); // 101
|
|
275
|
+
console.log(TungoMoney.toTiyn(45000.5)); // 4500050
|
|
276
|
+
console.log(TungoMoney.formatTiyn(4500000)); // 45 000,00 ₸
|
|
277
|
+
console.log(TungoMoney.formatTiyn(-50)); // -0,50 ₸
|
|
278
|
+
console.log(TungoMoney.toTiynBigInt('92233720368547758.07')); // 9223372036854775807n
|
|
279
|
+
console.log(isValidBinIin('990140000017')); // true
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
## API анықтамалығы
|
|
283
|
+
|
|
284
|
+
Tungo платформасы API-інің келісімшартынан жасалған: **ресурстар — 13, әдістер — 90, вебхук оқиғаларының түрлері — 22**.
|
|
285
|
+
|
|
286
|
+
| Ресурс | Сипаттама | Әдістер |
|
|
287
|
+
| --- | --- | --- |
|
|
288
|
+
| `workspaces` | API кілтіне қолжетімді ұйымдар (workspace) | `list` |
|
|
289
|
+
| `companies` | Ұйымның компаниялары және олардың карточкалары | `list` · `get` |
|
|
290
|
+
| `platform` | Платформа балансы, қозғалыстар кітабы, шығын есептері, лимиттер, аудит және модельдер тарифтері | `listUsageRates` · `getAccount` · `getAudit` · `getAuditAll` · `getLedger` · `getLedgerAll` · `listLimits` · `listRequests` · `listRequestsAll` · `getUsage` |
|
|
291
|
+
| `apiKeys` | Ағымдағы API кілті туралы мәлімет және оның шығын статистикасы | `getCurrent` · `getCurrentUsage` · `getUsage` |
|
|
292
|
+
| `webhooks` | Ұйымның шығыс вебхуктары (Svix): мекенжайлар, оқиғалар каталогы, жеткізулер және қолтаңбаны тексеру | `listEndpoints` · `listEndpointsAll` · `createEndpoint` · `getEndpoint` · `updateEndpoint` · `deleteEndpoint` · `listEndpointAttempts` · `listEndpointAttemptsAll` · `rotateEndpointSecret` · `testEndpoint` · `listEventTypes` · `listMessages` · `listMessagesAll` · `listMessageAttempts` · `listMessageAttemptsAll` · `resendMessage` · `getUsage` |
|
|
293
|
+
| `chat` | ЖИ-бухгалтермен диалогтар: сұрақтар, ағынды чат (SSE), токендерді санау және тарих | `list` · `listAll` · `create` · `stream` · `countTokens` · `listMentions` · `getRatingOptions` · `listSuggestions` · `get` · `update` · `delete` · `answer` · `answerStream` · `listEvents` · `rateMessage` · `deleteMessageRating` · `rate` · `dismissRating` · `stop` |
|
|
294
|
+
| `proposals` | ЖИ-бухгалтер ұсынған құжаттар: қарау, 1С-ке жазуды мақұлдау және қабылдамау | `list` · `listAll` · `approveBatch` · `get` · `approve` · `reject` · `requestApproval` |
|
|
295
|
+
| `feed` | Компанияның оқиғалар мен ұсыныстар таспасы (беттер және тікелей SSE ағыны) | `get` · `getAll` · `listEvents` |
|
|
296
|
+
| `batches` | Банк үзінді көшірмелерін, кіріс ЭШФ-ларды және DirectBank-ті өңдеу бумалары | `list` · `listAll` · `createBankStatement` · `createEsfPurchases` · `get` · `listEvents` · `stop` · `getSummary` · `listStatements` · `listStatementsAll` · `pollDirectbank` |
|
|
297
|
+
| `esf` | Кіріс және шығыс электрондық шот-фактуралар (ЭШФ АЖ) | `getIncoming` · `getIncomingAll` · `getOutgoing` · `getOutgoingAll` |
|
|
298
|
+
| `forms` | Салық нысандары (СЕН 100.00 және басқалары): құрастыру, ИСНА тексеруі және деректердегі алшақтықтар | `list` · `build` · `listDataGaps` · `getIsna` · `listNotes` |
|
|
299
|
+
| `onec` | Компанияның 1С базасына қосылу күйі | `getStatus` |
|
|
300
|
+
| `automations` | Компания автоматтандырулары: кіріс хуктар, сценарийлер, қадамдар тізбегі, іске қосулар және ЖИ дербестігінің деңгейі | `postHook` · `listHooks` · `createHook` · `getHook` · `updateHook` · `deleteHook` · `rotateHook` · `testHook` · `listRuns` · `listRunsAll` · `getRun` · `cancelRun` · `retryRun` · `listScenarios` · `createScenario` · `getScenario` · `putScenario` · `updateScenario` · `deleteScenario` · `runScenario` · `getState` · `putState` · `getAutonomy` · `putAutonomy` |
|
|
301
|
+
|
|
302
|
+
## Басқа SDK-лар
|
|
303
|
+
|
|
304
|
+
Сол API он тілде қолжетімді. Барлық SDK бір келісімшарттан жасалады және бірдей жұмыс істейді.
|
|
305
|
+
|
|
306
|
+
| Тіл | Репозиторий | Пакет |
|
|
307
|
+
| --- | --- | --- |
|
|
308
|
+
| **TypeScript** | [tungo-sdk-typescript](https://github.com/TungoAI/tungo-sdk-typescript) | `@tungoai/sdk` |
|
|
309
|
+
| Python | [tungo-sdk-python](https://github.com/TungoAI/tungo-sdk-python) | `tungoai` |
|
|
310
|
+
| Go | [tungo-sdk-go](https://github.com/TungoAI/tungo-sdk-go) | `github.com/TungoAI/tungo-sdk-go` |
|
|
311
|
+
| Rust | [tungo-sdk-rust](https://github.com/TungoAI/tungo-sdk-rust) | `tungo-sdk` |
|
|
312
|
+
| PHP | [tungo-sdk-php](https://github.com/TungoAI/tungo-sdk-php) | `tungo/sdk` |
|
|
313
|
+
| Java | [tungo-sdk-java](https://github.com/TungoAI/tungo-sdk-java) | `kz.tungo:tungo-sdk` |
|
|
314
|
+
| Kotlin | [tungo-sdk-kotlin](https://github.com/TungoAI/tungo-sdk-kotlin) | `kz.tungo:tungo-sdk-kotlin` |
|
|
315
|
+
| Swift | [tungo-sdk-swift](https://github.com/TungoAI/tungo-sdk-swift) | `TungoSDK` |
|
|
316
|
+
| Ruby | [tungo-sdk-ruby](https://github.com/TungoAI/tungo-sdk-ruby) | `tungo-sdk` |
|
|
317
|
+
| .NET | [tungo-sdk-dotnet](https://github.com/TungoAI/tungo-sdk-dotnet) | `Tungo.Sdk` |
|
|
318
|
+
|
|
319
|
+
## Нұсқалар және қолдау
|
|
320
|
+
|
|
321
|
+
Кітапхана [семантикалық нұсқалауды](https://semver.org/) ұстанады. Жоғарғы нұсқа 0 болып тұрғанда аралық шығарылымда үйлесімсіз өзгерістер болуы мүмкін; олар әрдайым [өзгерістер тарихында](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/CHANGELOG.md) келтіріледі. Бұл README 0.3.0 нұсқасын сипаттайды.
|
|
322
|
+
|
|
323
|
+
Код генератормен жасалады: мәселелер мен ұсыныстар туралы жасалған файлдарға түзету жібермей, [өтініштерге](https://github.com/TungoAI/tungo-sdk-typescript/issues) жазыңыз. Осалдық туралы [қауіпсіздік саясаты](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/SECURITY.md) бойынша хабарлаңыз.
|
|
324
|
+
|
|
325
|
+
## Лицензия
|
|
326
|
+
|
|
327
|
+
[MIT](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/LICENSE)
|