@tungoai/sdk 0.2.0 → 1.0.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 +90 -1
- package/README.kk.md +7 -5
- package/README.md +9 -7
- package/README.ru.md +7 -5
- package/dist/cjs/chat.js +3 -2
- package/dist/cjs/client.d.ts +6 -1
- package/dist/cjs/client.js +11 -3
- package/dist/cjs/core.d.ts +9 -2
- package/dist/cjs/core.js +191 -17
- package/dist/cjs/errors.d.ts +25 -0
- package/dist/cjs/errors.js +39 -3
- package/dist/cjs/generated/resources.d.ts +191 -2
- package/dist/cjs/generated/resources.js +197 -2
- package/dist/cjs/generated/types.d.ts +957 -428
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/index.js +3 -2
- package/dist/cjs/json.d.ts +6 -0
- package/dist/cjs/json.js +17 -0
- package/dist/cjs/pagination.js +2 -1
- package/dist/cjs/streaming.d.ts +4 -2
- package/dist/cjs/streaming.js +40 -2
- package/dist/cjs/version.d.ts +1 -1
- package/dist/cjs/version.js +1 -1
- package/dist/cjs/webhooks.d.ts +5 -0
- package/dist/cjs/webhooks.js +17 -3
- package/dist/esm/chat.js +3 -2
- package/dist/esm/client.d.ts +6 -1
- package/dist/esm/client.js +11 -3
- package/dist/esm/core.d.ts +9 -2
- package/dist/esm/core.js +191 -17
- package/dist/esm/errors.d.ts +25 -0
- package/dist/esm/errors.js +36 -1
- package/dist/esm/generated/resources.d.ts +191 -2
- package/dist/esm/generated/resources.js +194 -1
- package/dist/esm/generated/types.d.ts +957 -428
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/json.d.ts +6 -0
- package/dist/esm/json.js +16 -0
- package/dist/esm/pagination.js +2 -1
- package/dist/esm/streaming.d.ts +4 -2
- package/dist/esm/streaming.js +41 -3
- package/dist/esm/version.d.ts +1 -1
- package/dist/esm/version.js +1 -1
- package/dist/esm/webhooks.d.ts +5 -0
- package/dist/esm/webhooks.js +17 -3
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -9,6 +9,93 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
9
9
|
|
|
10
10
|
## [Unreleased]
|
|
11
11
|
|
|
12
|
+
## [1.0.0] - 2026-11-27
|
|
13
|
+
|
|
14
|
+
First stable release, generated from the platform contract of backend 230d6b82 (the API in production). From 1.0.0 on, minor and patch releases are backwards compatible: the API and the SDKs grow only by additions, a field or method that is to go away is first marked deprecated and kept for at least six months, and breaking changes come only in a new major version. The breaking changes against 0.3 are listed below, each with what to change; most code that only calls methods and reads results needs no change.
|
|
15
|
+
|
|
16
|
+
### Breaking
|
|
17
|
+
|
|
18
|
+
- `ChatAttachment` (the `attachments` of `chat.create`, `chat.answer` and `chat.count_tokens`) is now a union of two shapes: `ChatAttachmentData` (a file in base64: `name`, `data`, optional `media_type`, the 0.3 shape) and `ChatAttachmentUpload` (`upload_id` of an archive uploaded in parts with `chat.create_upload` and `chat.put_upload_part`). The JSON sent for a base64 file is unchanged; only the type used to build it changed (see Migration).
|
|
19
|
+
- `AutomationTriggerHook.hook_id` can be null: the hook of the scenario was deleted, and the scenario is not started by events until it gets another hook (`automations.put_scenario`). The API already answered null in this case; the field is now nullable in every SDK.
|
|
20
|
+
- Models that no SDK method sends or returns are no longer generated: the cabinet's API key management models (`ApiKeyCreate`, `ApiKeyCreated`, `ApiKeyDetails`, `ApiKeyPatch`, `ApiKeyPerson`, `ApiKeyRoll`, `ApiKeyRolled`, `ApiKeyTransfer`, `ApiKeyUpdated`, `ApiKeyWarning` and their enums) and billing models (`CardSession`, `CardSessionState`, `PayForm`, `PaymentMethod`, `PlatformPurchase`, `PlatformPurchaseInput`, `PlatformSettingsInput`, `EpayReturnLinks` and their enums). They describe operations that need a cabinet session, which an API key cannot call; they changed with the cabinet (`CardSession` and `PayForm` gained a redirect form with nullable `script_url` and `payment_object` in this contract) and would have broken the SDKs for nothing. The key in use is described by `api_keys.get_current` (`ApiKey`), as before.
|
|
21
|
+
- New union variants: `ChatEvent` gains `file` (`ChatEventFile`) and `memory` (`ChatEventMemory`); `ChatHistoryBlock` gains `file` (`ChatHistoryFile`) and `memory` (`ChatHistoryMemory`). An exhaustive `switch`/`when`/`match` over these unions needs the new cases (or a default branch).
|
|
22
|
+
- Response models gained required fields: `ChatTurnResult.files`, `ChatAssistantMessage.thinking_parts`, `ChatDialog.memory` and `ChatDialogSummary.memory`, `PlatformAutoReload.monthly_count_max`, the archive limits of `PlatformLimits.files` (`archive_bytes`, `archive_files`, `archives_per_message`, `upload_part_bytes`), `UsageRate.long_context` and `UsageRate.web_search_per_1k_tiyn`. Decoding is unaffected; code that constructs these models itself (test fakes) must pass the new fields.
|
|
23
|
+
|
|
24
|
+
### Migration
|
|
25
|
+
|
|
26
|
+
- Attachments: object literals `{ name, data }` still type-check. Code that reads an attachment narrows it first: `'upload_id' in a ? a.upload_id : a.name`. `trigger.hook_id` is `string | null`.
|
|
27
|
+
- `hook_id` of a hook trigger: handle null (no hook) where the scenario's trigger is read.
|
|
28
|
+
- Removed cabinet models: delete the imports; there is nothing to replace them with in an SDK, because their operations need a cabinet session.
|
|
29
|
+
- Exhaustive matches over `ChatEvent` and `ChatHistoryBlock`: add `file` and `memory`, or a default branch. A default branch also keeps code compiling when later minor releases add variants, which they may do.
|
|
30
|
+
|
|
31
|
+
### Added
|
|
32
|
+
|
|
33
|
+
- Chat archives: `chat.create_upload` (`POST /v1/companies/{co}/chat/uploads`, `ChatUploadCreate`), `chat.put_upload_part` (`PUT …/chat/uploads/{upload}/parts/{n}`, raw bytes) and `chat.delete_upload` upload a .zip, .rar or .7z in parts (`ChatUpload`, `ChatUploadPart`); the finished upload goes into a question as `ChatAttachmentUpload`. Limits: `PlatformLimits.files.archive_bytes`, `archive_files`, `archives_per_message`, `upload_part_bytes`.
|
|
34
|
+
- Chat files made by the AI (Excel, Word, PDF, CSV): `chat.list_files` (`GET /v1/companies/{co}/chat/files`, `ChatFileList`, `ChatFileItem`), `ChatTurnResult.files` (`ChatTurnFile`), the `file` stream event (`ChatEventFile`) and the `file` history block (`ChatHistoryFile`).
|
|
35
|
+
- Chat memory: `memory` on `ChatMessageRequest` (false: a conversation without memory), `ChatDialog` and `ChatDialogSummary`; the `memory` stream event (`ChatEventMemory`) and history block (`ChatHistoryMemory`).
|
|
36
|
+
- Chat thinking: `chat.translate_thinking` (`POST …/chat/{id}/thinking/{tid}/translate`, `ChatThinkingTranslation`); `ChatEventThinking.original` and `translate_id`; `ChatAssistantMessage.thinking_parts` (`ChatThinkingPart`). `ChatEventStatus` gains `chars` and the codes `checking_norm` and `writing`.
|
|
37
|
+
- Chat: `ChatUserMessage.onec_object` (`ChatOnecObject`), the 1C object a question was asked from.
|
|
38
|
+
- `verification` (public, no API key): `verification.get` (`GET /v1/public/verify/{code}`, `PublicVerification`), `verification.check` (`POST /v1/public/verify/{code}/check`, compares a file's SHA-256 with the signed document, `VerifyCheck`), `verification.verify_qr` (`POST /v1/public/verify/qr`, `VerifyQrResult`) and `verification.list_keys` (`GET /v1/public/verify-keys`, the JWKS of the QR signature, `VerifyKeys`).
|
|
39
|
+
- `releases.list` (public, `GET /v1/public/downloads`, `Downloads`): the current releases of the 1C extension and Tungo Connector to download. (The resource is named `releases`, not `downloads`, so that it never clashes with the `Downloads` model.)
|
|
40
|
+
- Platform: `PlatformAutoReload.monthly_count_max`; `UsageRate.long_context` (`UsageRateLongContext`) and `UsageRate.web_search_per_1k_tiyn`; new audit actions; `OneCGateway` value `module`.
|
|
41
|
+
|
|
42
|
+
### Known limitations
|
|
43
|
+
|
|
44
|
+
- Downloads of files (`GET …/chat/{id}/files/{file}`, the batch and proposal exports, and the redirects `GET /v1/public/downloads/connector` and `GET /v1/public/downloads/onec-extension`) are not in this release: the SDKs cannot return a file body yet.
|
|
45
|
+
- A chat turn replayed by `Idempotency-Key` as a stream does not rebuild `file` events; the files of the turn are in `ChatTurnResult.files` of the non-streaming answer and in `chat.list_files`.
|
|
46
|
+
|
|
47
|
+
## [0.3.0] - 2026-11-13
|
|
48
|
+
|
|
49
|
+
Generated from the platform contract of backend 44066d62. It contains breaking type changes compared with 0.2.0.
|
|
50
|
+
|
|
51
|
+
### Breaking
|
|
52
|
+
|
|
53
|
+
- `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?`).
|
|
54
|
+
- `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.
|
|
55
|
+
- `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 `[]`.
|
|
56
|
+
- 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.
|
|
57
|
+
- 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).
|
|
58
|
+
- 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.
|
|
59
|
+
- 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.
|
|
60
|
+
|
|
61
|
+
### Added
|
|
62
|
+
|
|
63
|
+
- `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`).
|
|
64
|
+
- `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`).
|
|
65
|
+
- `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`.
|
|
66
|
+
- 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`).
|
|
67
|
+
- 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`).
|
|
68
|
+
- 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).
|
|
69
|
+
- 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.
|
|
70
|
+
- Errors: rating error codes `dialog_not_ratable`, `message_not_found`, `rating_reason_unknown`, `rating_reason_not_allowed`, `rating_comment_too_long` and `ratings_unavailable`.
|
|
71
|
+
- Batches: `BatchSummary.statement` describes a parsed bank statement by account (`BatchStatement`, `BatchStatementAccount`).
|
|
72
|
+
- 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`.
|
|
73
|
+
- API keys: `no_companies` on the API key models, on `ApiKeyCreate` and on `ApiKeyPatch`; `ApiKeyRolled.key_note`.
|
|
74
|
+
- 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.
|
|
75
|
+
- Billing models used by the cabinet: `CardSessionState`, `CardSession.test_mode`, `PayForm.test_mode`.
|
|
76
|
+
|
|
77
|
+
### Fixed
|
|
78
|
+
|
|
79
|
+
- 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.
|
|
80
|
+
- 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.
|
|
81
|
+
- 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.
|
|
82
|
+
- 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`.
|
|
83
|
+
- Webhook verification treats an infinite tolerance as `invalid_tolerance`.
|
|
84
|
+
- Money: the exponent of a decimal is bounded before it is converted to tiyn.
|
|
85
|
+
- 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).
|
|
86
|
+
- TypeScript: error paths serialise `bigint` safely and keep 64-bit extra fields exact; `debugJSON` returns `''` for a value JSON cannot express.
|
|
87
|
+
- Python: a `datetime` passed for a calendar-date parameter is sent as its date.
|
|
88
|
+
- Go: `UploadBankStatement` sends text that is not UTF-8 as the file instead of failing.
|
|
89
|
+
- 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.
|
|
90
|
+
- PHP: `sendHook` reads the headers of optional request options null-safely.
|
|
91
|
+
- Ruby: the percent-encoded credentials of an explicit proxy are decoded.
|
|
92
|
+
- Swift: the `URLSession` of the SDK has no URL cache.
|
|
93
|
+
- .NET: a custom platform handler that follows redirects, or whose redirect setting cannot be read, is refused.
|
|
94
|
+
|
|
95
|
+
### Known limitations
|
|
96
|
+
|
|
97
|
+
- 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.
|
|
98
|
+
|
|
12
99
|
## [0.2.0] - 2026-11-12
|
|
13
100
|
|
|
14
101
|
First production-ready release. It contains breaking changes compared with 0.1.0; 0.1.0 should not be used.
|
|
@@ -35,6 +122,8 @@ First production-ready release. It contains breaking changes compared with 0.1.0
|
|
|
35
122
|
|
|
36
123
|
Initial preview. Not suitable for production use.
|
|
37
124
|
|
|
38
|
-
[Unreleased]: https://github.com/TungoAI/tungo-sdk-typescript/compare/
|
|
125
|
+
[Unreleased]: https://github.com/TungoAI/tungo-sdk-typescript/compare/v1.0.0...HEAD
|
|
126
|
+
[1.0.0]: https://github.com/TungoAI/tungo-sdk-typescript/compare/v0.3.0...v1.0.0
|
|
127
|
+
[0.3.0]: https://github.com/TungoAI/tungo-sdk-typescript/compare/v0.2.0...v0.3.0
|
|
39
128
|
[0.2.0]: https://github.com/TungoAI/tungo-sdk-typescript/compare/v0.1.0...v0.2.0
|
|
40
129
|
[0.1.0]: https://github.com/TungoAI/tungo-sdk-typescript/releases/tag/v0.1.0
|
package/README.kk.md
CHANGED
|
@@ -145,7 +145,7 @@ try {
|
|
|
145
145
|
|
|
146
146
|
## Қайталаулар және күту уақыты
|
|
147
147
|
|
|
148
|
-
Сұрау байланыс қателерінде, күту уақыты біткенде және 408, 429, 500, 502, 503, 504 күйлерінде 2 ретке дейін қайталанады (барлығы 3 әрекет), бірақ тек қайталау қауіпсіз болғанда: `GET`, `HEAD`, `PUT` және `DELETE` сұраулары, сондай-ақ `Idempotency-Key`
|
|
148
|
+
Сұрау байланыс қателерінде, күту уақыты біткенде және 408, 429, 500, 502, 503, 504 күйлерінде 2 ретке дейін қайталанады (барлығы 3 әрекет), бірақ тек қайталау қауіпсіз болғанда: `GET`, `HEAD`, `PUT` және `DELETE` сұраулары, сондай-ақ келісімшарты `Idempotency-Key` тақырыбын жариялайтын операциялардың `POST` пен `PATCH` сұраулары. Олар үшін SDK кездейсоқ кілтті өзі жасап, оны барлық әрекетте қолданады; өз кілтіңізді беруге болады. Басқа операциялар кілтті, тіпті берілгенін де, жібермейді: API оны онда ескермейді.
|
|
149
149
|
|
|
150
150
|
Әрекеттер арасындағы үзіліс — кездейсоқ ауытқуы бар `min(0,5 с × 2^әрекет, 8 с)`. Жауаптың `retry-after-ms` немесе `Retry-After` тақырыбындағы оң мән оны алмастырады; сервер 60 с-тан ұзақ күтуді сұраса, SDK күтпейді және кідірісі көрсетілген қатені қайтарады.
|
|
151
151
|
|
|
@@ -281,7 +281,7 @@ console.log(isValidBinIin('990140000017')); // true
|
|
|
281
281
|
|
|
282
282
|
## API анықтамалығы
|
|
283
283
|
|
|
284
|
-
Tungo платформасы API-інің келісімшартынан жасалған: **ресурстар —
|
|
284
|
+
Tungo платформасы API-інің келісімшартынан жасалған: **ресурстар — 15, әдістер — 100, вебхук оқиғаларының түрлері — 22**.
|
|
285
285
|
|
|
286
286
|
| Ресурс | Сипаттама | Әдістер |
|
|
287
287
|
| --- | --- | --- |
|
|
@@ -290,14 +290,16 @@ Tungo платформасы API-інің келісімшартынан жас
|
|
|
290
290
|
| `platform` | Платформа балансы, қозғалыстар кітабы, шығын есептері, лимиттер, аудит және модельдер тарифтері | `listUsageRates` · `getAccount` · `getAudit` · `getAuditAll` · `getLedger` · `getLedgerAll` · `listLimits` · `listRequests` · `listRequestsAll` · `getUsage` |
|
|
291
291
|
| `apiKeys` | Ағымдағы API кілті туралы мәлімет және оның шығын статистикасы | `getCurrent` · `getCurrentUsage` · `getUsage` |
|
|
292
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` · `get` · `update` · `delete` · `answer` · `answerStream` · `listEvents` · `stop` |
|
|
294
|
-
| `proposals` | ЖИ-бухгалтер ұсынған құжаттар: қарау, 1С-ке жазуды мақұлдау және қабылдамау | `list` · `listAll` · `approveBatch` · `get` · `approve` · `reject` |
|
|
293
|
+
| `chat` | ЖИ-бухгалтермен диалогтар: сұрақтар, ағынды чат (SSE), токендерді санау және тарих | `list` · `listAll` · `create` · `stream` · `countTokens` · `listFiles` · `listFilesAll` · `listMentions` · `getRatingOptions` · `listSuggestions` · `createUpload` · `deleteUpload` · `putUploadPart` · `get` · `update` · `delete` · `answer` · `answerStream` · `listEvents` · `rateMessage` · `deleteMessageRating` · `rate` · `dismissRating` · `stop` · `translateThinking` |
|
|
294
|
+
| `proposals` | ЖИ-бухгалтер ұсынған құжаттар: қарау, 1С-ке жазуды мақұлдау және қабылдамау | `list` · `listAll` · `approveBatch` · `get` · `approve` · `reject` · `requestApproval` |
|
|
295
295
|
| `feed` | Компанияның оқиғалар мен ұсыныстар таспасы (беттер және тікелей SSE ағыны) | `get` · `getAll` · `listEvents` |
|
|
296
296
|
| `batches` | Банк үзінді көшірмелерін, кіріс ЭШФ-ларды және DirectBank-ті өңдеу бумалары | `list` · `listAll` · `createBankStatement` · `createEsfPurchases` · `get` · `listEvents` · `stop` · `getSummary` · `listStatements` · `listStatementsAll` · `pollDirectbank` |
|
|
297
297
|
| `esf` | Кіріс және шығыс электрондық шот-фактуралар (ЭШФ АЖ) | `getIncoming` · `getIncomingAll` · `getOutgoing` · `getOutgoingAll` |
|
|
298
298
|
| `forms` | Салық нысандары (СЕН 100.00 және басқалары): құрастыру, ИСНА тексеруі және деректердегі алшақтықтар | `list` · `build` · `listDataGaps` · `getIsna` · `listNotes` |
|
|
299
299
|
| `onec` | Компанияның 1С базасына қосылу күйі | `getStatus` |
|
|
300
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
|
+
| `verification` | Tungo құжаттарының электрондық қолтаңбасын ашық тексеру: код, файл, QR блогы бойынша және қолтаңба кілттері (API кілтісіз) | `listKeys` · `verifyQr` · `get` · `check` |
|
|
302
|
+
| `releases` | Ашық жүктеулер тізімі: 1С кеңейтімі және Tungo Connector (API кілтісіз) | `list` |
|
|
301
303
|
|
|
302
304
|
## Басқа SDK-лар
|
|
303
305
|
|
|
@@ -318,7 +320,7 @@ Tungo платформасы API-інің келісімшартынан жас
|
|
|
318
320
|
|
|
319
321
|
## Нұсқалар және қолдау
|
|
320
322
|
|
|
321
|
-
Кітапхана [семантикалық нұсқалауды](https://semver.org/) ұстанады.
|
|
323
|
+
Кітапхана [семантикалық нұсқалауды](https://semver.org/) ұстанады. Аралық және түзету шығарылымдары үйлесімді: API толықтыру арқылы өседі, ал алынатын өріс не әдіс алдымен ескірген деп белгіленіп, кемінде алты ай сақталады. Үйлесімсіз өзгерістер тек жаңа жоғарғы нұсқада болады және ауысу нұсқауларымен бірге [өзгерістер тарихында](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/CHANGELOG.md) келтіріледі. Бұл README 1.0.0 нұсқасын сипаттайды.
|
|
322
324
|
|
|
323
325
|
Код генератормен жасалады: мәселелер мен ұсыныстар туралы жасалған файлдарға түзету жібермей, [өтініштерге](https://github.com/TungoAI/tungo-sdk-typescript/issues) жазыңыз. Осалдық туралы [қауіпсіздік саясаты](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/SECURITY.md) бойынша хабарлаңыз.
|
|
324
326
|
|
package/README.md
CHANGED
|
@@ -143,11 +143,11 @@ try {
|
|
|
143
143
|
}
|
|
144
144
|
```
|
|
145
145
|
|
|
146
|
-
The classes are `InvalidRequestError`, `AuthenticationError`, `PaymentRequiredError`, `PermissionError`, `NotFoundError`, `ConflictError`, `GoneError`, `LimitError`, `InternalServerError` (`api_error`) and `UnavailableError`, all extending `APIError`; and `ConnectionError`, `TimeoutError`, `AbortError` (cancellation through your `AbortSignal`; the signal's reason is the `cause`), `DecodeError`, `ConfigError`, `ValidationError`, `WebhookVerificationError` and `MoneyError`, all extending `TungoError`. `err.message` is an English summary with the status, code and request id; `err.detail` is the API's own message. An error reported by a chat turn inside a successful response (an `error` event of a stream, or `errors` of `client.ask`) is thrown by the chat helpers as the same class by its `error.type` (for example `LimitError`), with `status` undefined because no HTTP error status exists for it, and with what was received in `partialResult`. The Python SDK raises `ChatStreamError` (with `type`, `code`, `request_id`, `extra` and `result`) for the same situation.
|
|
146
|
+
The classes are `InvalidRequestError`, `AuthenticationError`, `PaymentRequiredError`, `PermissionError`, `NotFoundError`, `ConflictError`, `GoneError`, `LimitError`, `InternalServerError` (`api_error`) and `UnavailableError`, all extending `APIError`; and `ConnectionError`, `TimeoutError`, `AbortError` (cancellation through your `AbortSignal`; the signal's reason is the `cause`), `DecodeError`, `StreamError`, `ConfigError`, `ValidationError`, `WebhookVerificationError` and `MoneyError`, all extending `TungoError`. `err.message` is an English summary with the status, code and request id; `err.detail` is the API's own message. An error reported by a chat turn inside a successful response (an `error` event of a stream, or `errors` of `client.ask`) is thrown by the chat helpers as the same class by its `error.type` (for example `LimitError`), with `status` undefined because no HTTP error status exists for it, and with what was received in `partialResult`. The Python SDK raises `ChatStreamError` (with `type`, `code`, `request_id`, `extra` and `result`) for the same situation.
|
|
147
147
|
|
|
148
148
|
## Retries and timeouts
|
|
149
149
|
|
|
150
|
-
A request is retried up to 2 times (3 attempts) on connection errors, timeouts and the statuses 408, 429, 500, 502, 503 and 504, but only when repeating it is safe: `GET`, `HEAD`, `PUT` and `DELETE` requests, and `POST` or `PATCH` requests
|
|
150
|
+
A request is retried up to 2 times (3 attempts) on connection errors, timeouts and the statuses 408, 429, 500, 502, 503 and 504, but only when repeating it is safe: `GET`, `HEAD`, `PUT` and `DELETE` requests, and `POST` or `PATCH` requests of the operations whose contract declares an `Idempotency-Key`. For those the SDK generates a random key and reuses it for every attempt; you can pass your own. Other operations send no key, not even one you pass, because the API would ignore it.
|
|
151
151
|
|
|
152
152
|
The delay between attempts is `min(0.5 s × 2^attempt, 8 s)` with random jitter. A positive `retry-after-ms` or `Retry-After` response header overrides it; if the server asks for more than 60 s the SDK does not wait and raises the error with the delay filled in.
|
|
153
153
|
|
|
@@ -233,7 +233,7 @@ const turn = await client.streamChatWithResult(company, 'And for October?', {
|
|
|
233
233
|
console.log(turn.text, turn.stopReason, turn.costTiyn);
|
|
234
234
|
```
|
|
235
235
|
|
|
236
|
-
`client.chat.listEvents`, `client.batches.listEvents` and `client.feed.listEvents` are plain event streams and work the same way. `stream.close()` closes the connection explicitly; `stream.events()` gives the raw server-sent events and `stream.lastEventId` the id to resume from. The connect timeout of a stream is the request `timeout`; `streamIdleTimeout` (120 s by default) limits the silence between bytes. `finalResult()`, `streamChatWithResult` and `accumulateChatStream` never return a partial turn as a finished one: a stream that ends without its `done` event raises a `DecodeError` (`partialResult` holds what arrived), and a 2xx answer that is not `text/event-stream` raises a `DecodeError` instead of an empty stream. Plain iteration simply ends when the stream ends.
|
|
236
|
+
`client.chat.listEvents`, `client.batches.listEvents` and `client.feed.listEvents` are plain event streams and work the same way. `stream.close()` closes the connection explicitly; `stream.events()` gives the raw server-sent events and `stream.lastEventId` the id to resume from. The connect timeout of a stream is the request `timeout`; `streamIdleTimeout` (120 s by default) limits the silence between bytes. `finalResult()`, `streamChatWithResult` and `accumulateChatStream` never return a partial turn as a finished one: a stream that ends without its `done` event raises a `DecodeError` (`partialResult` holds what arrived), and a 2xx answer that is not `text/event-stream` raises a `DecodeError` instead of an empty stream. The exception is a finished chat turn that the API replays for a repeated `Idempotency-Key` (`application/json` with `Idempotent-Replayed: true`): its stored result arrives as the events of that turn, ending with `next` (follow-ups and the next action, when it has them) and `done`. Plain iteration simply ends when the stream ends. An `error` event of `client.feed.listEvents` (`feed_failed`) is thrown as a `StreamError` with `code` and `detail`: the feed did not finish, so reconnect from the cursor of the last item.
|
|
237
237
|
|
|
238
238
|
## Webhooks
|
|
239
239
|
|
|
@@ -301,7 +301,7 @@ The package has two builds selected by the `exports` map: ES modules for `import
|
|
|
301
301
|
|
|
302
302
|
## API reference
|
|
303
303
|
|
|
304
|
-
Generated from the Tungo Platform API contract: **
|
|
304
|
+
Generated from the Tungo Platform API contract: **15 resources, 100 methods, 22 webhook event types**.
|
|
305
305
|
|
|
306
306
|
| Resource | Description | Methods |
|
|
307
307
|
| --- | --- | --- |
|
|
@@ -310,14 +310,16 @@ Generated from the Tungo Platform API contract: **13 resources, 82 methods, 22 w
|
|
|
310
310
|
| `platform` | Platform balance, ledger, usage reports, limits, audit log and model rates | `listUsageRates` · `getAccount` · `getAudit` · `getAuditAll` · `getLedger` · `getLedgerAll` · `listLimits` · `listRequests` · `listRequestsAll` · `getUsage` |
|
|
311
311
|
| `apiKeys` | The current API key and its usage statistics | `getCurrent` · `getCurrentUsage` · `getUsage` |
|
|
312
312
|
| `webhooks` | Outgoing webhooks of an organisation (Svix): endpoints, event catalogue, deliveries and signature check | `listEndpoints` · `listEndpointsAll` · `createEndpoint` · `getEndpoint` · `updateEndpoint` · `deleteEndpoint` · `listEndpointAttempts` · `listEndpointAttemptsAll` · `rotateEndpointSecret` · `testEndpoint` · `listEventTypes` · `listMessages` · `listMessagesAll` · `listMessageAttempts` · `listMessageAttemptsAll` · `resendMessage` · `getUsage` |
|
|
313
|
-
| `chat` | Conversations with the AI accountant: questions, streaming chat (SSE), token counting and history | `list` · `listAll` · `create` · `stream` · `countTokens` · `get` · `update` · `delete` · `answer` · `answerStream` · `listEvents` · `stop` |
|
|
314
|
-
| `proposals` | Documents proposed by the AI accountant: review, approval for posting to 1C, and rejection | `list` · `listAll` · `approveBatch` · `get` · `approve` · `reject` |
|
|
313
|
+
| `chat` | Conversations with the AI accountant: questions, streaming chat (SSE), token counting and history | `list` · `listAll` · `create` · `stream` · `countTokens` · `listFiles` · `listFilesAll` · `listMentions` · `getRatingOptions` · `listSuggestions` · `createUpload` · `deleteUpload` · `putUploadPart` · `get` · `update` · `delete` · `answer` · `answerStream` · `listEvents` · `rateMessage` · `deleteMessageRating` · `rate` · `dismissRating` · `stop` · `translateThinking` |
|
|
314
|
+
| `proposals` | Documents proposed by the AI accountant: review, approval for posting to 1C, and rejection | `list` · `listAll` · `approveBatch` · `get` · `approve` · `reject` · `requestApproval` |
|
|
315
315
|
| `feed` | The company's feed of events and proposals (pages and a live SSE stream) | `get` · `getAll` · `listEvents` |
|
|
316
316
|
| `batches` | Processing batches for bank statements, incoming e-invoices and DirectBank | `list` · `listAll` · `createBankStatement` · `createEsfPurchases` · `get` · `listEvents` · `stop` · `getSummary` · `listStatements` · `listStatementsAll` · `pollDirectbank` |
|
|
317
317
|
| `esf` | Incoming and outgoing electronic invoices (the ESF system) | `getIncoming` · `getIncomingAll` · `getOutgoing` · `getOutgoingAll` |
|
|
318
318
|
| `forms` | Tax forms (FNO 100.00 and others): building, ISNA checks and data gaps | `list` · `build` · `listDataGaps` · `getIsna` · `listNotes` |
|
|
319
319
|
| `onec` | Status of the company's connection to its 1C database | `getStatus` |
|
|
320
320
|
| `automations` | Company automations: incoming hooks, scenarios, step chains, runs and the AI autonomy level | `postHook` · `listHooks` · `createHook` · `getHook` · `updateHook` · `deleteHook` · `rotateHook` · `testHook` · `listRuns` · `listRunsAll` · `getRun` · `cancelRun` · `retryRun` · `listScenarios` · `createScenario` · `getScenario` · `putScenario` · `updateScenario` · `deleteScenario` · `runScenario` · `getState` · `putState` · `getAutonomy` · `putAutonomy` |
|
|
321
|
+
| `verification` | Public verification of the electronic signature of Tungo documents: by code, by file, by QR block, and the signing keys (no API key needed) | `listKeys` · `verifyQr` · `get` · `check` |
|
|
322
|
+
| `releases` | Public list of downloads: the 1C extension and Tungo Connector (no API key needed) | `list` |
|
|
321
323
|
|
|
322
324
|
## Other SDKs
|
|
323
325
|
|
|
@@ -338,7 +340,7 @@ The same API is available in ten languages. All SDKs are generated from one cont
|
|
|
338
340
|
|
|
339
341
|
## Versioning and support
|
|
340
342
|
|
|
341
|
-
This library follows [Semantic Versioning](https://semver.org/).
|
|
343
|
+
This library follows [Semantic Versioning](https://semver.org/). Minor and patch releases are backwards compatible: the API grows by additions, and a field or method that is to go away is first marked deprecated and kept for at least six months. Breaking changes come only in a new major version and are listed, with migration notes, in the [changelog](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/CHANGELOG.md). This README describes version 1.0.0.
|
|
342
344
|
|
|
343
345
|
The code is generated: please report problems and ideas in the [issue tracker](https://github.com/TungoAI/tungo-sdk-typescript/issues) rather than opening pull requests against generated files. To report a vulnerability, follow the [security policy](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/SECURITY.md).
|
|
344
346
|
|
package/README.ru.md
CHANGED
|
@@ -145,7 +145,7 @@ try {
|
|
|
145
145
|
|
|
146
146
|
## Повторы и тайм-ауты
|
|
147
147
|
|
|
148
|
-
Запрос повторяется до 2 раз (всего 3 попытки) при ошибках соединения, тайм-аутах и статусах 408, 429, 500, 502, 503 и 504, но только когда повтор безопасен: запросы `GET`, `HEAD`, `PUT` и `DELETE`, а также `POST` и `PATCH`
|
|
148
|
+
Запрос повторяется до 2 раз (всего 3 попытки) при ошибках соединения, тайм-аутах и статусах 408, 429, 500, 502, 503 и 504, но только когда повтор безопасен: запросы `GET`, `HEAD`, `PUT` и `DELETE`, а также `POST` и `PATCH` тех операций, у которых контракт объявляет заголовок `Idempotency-Key`. Для них SDK сам создаёт случайный ключ и использует его во всех попытках; можно передать свой. Другие операции ключ не отправляют, даже переданный: API его там не учитывает.
|
|
149
149
|
|
|
150
150
|
Пауза между попытками — `min(0,5 с × 2^попытка, 8 с)` со случайным разбросом. Положительное значение заголовка ответа `retry-after-ms` или `Retry-After` заменяет её; если сервер просит ждать дольше 60 с, SDK не ждёт и возвращает ошибку с указанной задержкой.
|
|
151
151
|
|
|
@@ -281,7 +281,7 @@ console.log(isValidBinIin('990140000017')); // true
|
|
|
281
281
|
|
|
282
282
|
## Справочник API
|
|
283
283
|
|
|
284
|
-
Создано из контракта API платформы Tungo: **ресурсов —
|
|
284
|
+
Создано из контракта API платформы Tungo: **ресурсов — 15, методов — 100, типов событий вебхуков — 22**.
|
|
285
285
|
|
|
286
286
|
| Ресурс | Описание | Методы |
|
|
287
287
|
| --- | --- | --- |
|
|
@@ -290,14 +290,16 @@ console.log(isValidBinIin('990140000017')); // true
|
|
|
290
290
|
| `platform` | Баланс платформы, книга движений, отчёты о расходе, лимиты, аудит и тарифы моделей | `listUsageRates` · `getAccount` · `getAudit` · `getAuditAll` · `getLedger` · `getLedgerAll` · `listLimits` · `listRequests` · `listRequestsAll` · `getUsage` |
|
|
291
291
|
| `apiKeys` | Сведения о текущем ключе API и статистика его расхода | `getCurrent` · `getCurrentUsage` · `getUsage` |
|
|
292
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` · `get` · `update` · `delete` · `answer` · `answerStream` · `listEvents` · `stop` |
|
|
294
|
-
| `proposals` | Предложения документов ИИ-бухгалтера: просмотр, одобрение записи в 1С и отклонение | `list` · `listAll` · `approveBatch` · `get` · `approve` · `reject` |
|
|
293
|
+
| `chat` | Диалоги с ИИ-бухгалтером: вопросы, потоковый чат (SSE), подсчёт токенов и история | `list` · `listAll` · `create` · `stream` · `countTokens` · `listFiles` · `listFilesAll` · `listMentions` · `getRatingOptions` · `listSuggestions` · `createUpload` · `deleteUpload` · `putUploadPart` · `get` · `update` · `delete` · `answer` · `answerStream` · `listEvents` · `rateMessage` · `deleteMessageRating` · `rate` · `dismissRating` · `stop` · `translateThinking` |
|
|
294
|
+
| `proposals` | Предложения документов ИИ-бухгалтера: просмотр, одобрение записи в 1С и отклонение | `list` · `listAll` · `approveBatch` · `get` · `approve` · `reject` · `requestApproval` |
|
|
295
295
|
| `feed` | Лента событий и предложений компании (страницы и живой поток SSE) | `get` · `getAll` · `listEvents` |
|
|
296
296
|
| `batches` | Пачки обработки банковских выписок, входящих ЭСФ и DirectBank | `list` · `listAll` · `createBankStatement` · `createEsfPurchases` · `get` · `listEvents` · `stop` · `getSummary` · `listStatements` · `listStatementsAll` · `pollDirectbank` |
|
|
297
297
|
| `esf` | Входящие и исходящие электронные счета-фактуры (ИС ЭСФ) | `getIncoming` · `getIncomingAll` · `getOutgoing` · `getOutgoingAll` |
|
|
298
298
|
| `forms` | Налоговые формы (ФНО 100.00 и др.): сборка, проверка ИСНА и разрывы данных | `list` · `build` · `listDataGaps` · `getIsna` · `listNotes` |
|
|
299
299
|
| `onec` | Состояние подключения компании к базе 1С | `getStatus` |
|
|
300
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
|
+
| `verification` | Публичная проверка электронной подписи документов Tungo: по коду, по файлу, по блоку QR и ключи подписи (без ключа API) | `listKeys` · `verifyQr` · `get` · `check` |
|
|
302
|
+
| `releases` | Публичный список загрузок: расширение 1С и Tungo Connector (без ключа API) | `list` |
|
|
301
303
|
|
|
302
304
|
## Другие SDK
|
|
303
305
|
|
|
@@ -318,7 +320,7 @@ console.log(isValidBinIin('990140000017')); // true
|
|
|
318
320
|
|
|
319
321
|
## Версии и поддержка
|
|
320
322
|
|
|
321
|
-
Библиотека следует [семантическому версионированию](https://semver.org/lang/ru/).
|
|
323
|
+
Библиотека следует [семантическому версионированию](https://semver.org/lang/ru/). Промежуточные и исправляющие выпуски совместимы: API растёт добавлениями, а поле или метод, которые уйдут, сначала помечаются устаревшими и живут не меньше шести месяцев. Несовместимые изменения бывают только в новой старшей версии и перечислены, с указаниями по переходу, в [истории изменений](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/CHANGELOG.md). Этот README описывает версию 1.0.0.
|
|
322
324
|
|
|
323
325
|
Код создаётся генератором: пишите о проблемах и идеях в [обращения](https://github.com/TungoAI/tungo-sdk-typescript/issues), а не присылайте правки к созданным файлам. Об уязвимости сообщайте по [политике безопасности](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/SECURITY.md).
|
|
324
326
|
|
package/dist/cjs/chat.js
CHANGED
|
@@ -5,6 +5,7 @@ exports.chatTurnError = chatTurnError;
|
|
|
5
5
|
exports.accumulateChatStream = accumulateChatStream;
|
|
6
6
|
// Code generated by tungo-sdkgen. DO NOT EDIT.
|
|
7
7
|
const core_js_1 = require("./core.js");
|
|
8
|
+
const json_js_1 = require("./json.js");
|
|
8
9
|
const errors_js_1 = require("./errors.js");
|
|
9
10
|
const streaming_js_1 = require("./streaming.js");
|
|
10
11
|
/** Folds the events of one chat turn into a {@link ChatStreamResult}. */
|
|
@@ -88,7 +89,7 @@ function chatTurnError(error, requestId, response) {
|
|
|
88
89
|
retryAfter: null,
|
|
89
90
|
rateLimit: response?.rateLimit ?? null,
|
|
90
91
|
headers: response?.headers ?? new Headers(),
|
|
91
|
-
body:
|
|
92
|
+
body: (0, json_js_1.debugJSON)(error),
|
|
92
93
|
extra: detail?.extra ?? {},
|
|
93
94
|
envelope: detail !== null,
|
|
94
95
|
});
|
|
@@ -129,7 +130,7 @@ class ChatStream extends streaming_js_1.Stream {
|
|
|
129
130
|
/** Turn number from the `X-Turn-No` response header; null when absent. */
|
|
130
131
|
turnNo;
|
|
131
132
|
constructor(init) {
|
|
132
|
-
super(init, (event, response) => (0, streaming_js_1.decodeJSONEvent)(event, response));
|
|
133
|
+
super(init, (event, response) => (0, streaming_js_1.decodeJSONEvent)(event, response, true));
|
|
133
134
|
const dialogId = init.response.headers.get('x-dialog-id');
|
|
134
135
|
this.dialogId = dialogId === null || dialogId === '' ? null : dialogId;
|
|
135
136
|
const turnNo = init.response.headers.get('x-turn-no');
|
package/dist/cjs/client.d.ts
CHANGED
|
@@ -54,6 +54,10 @@ export declare class Tungo {
|
|
|
54
54
|
readonly onec: R.OnecResource;
|
|
55
55
|
/** Автоматизации компании: входящие хуки, сценарии, цепочки шагов, запуски и уровень автономности ИИ */
|
|
56
56
|
readonly automations: R.AutomationsResource;
|
|
57
|
+
/** Публичная проверка электронной подписи документов Tungo: по коду, по файлу, по блоку QR и ключи подписи (без ключа API) */
|
|
58
|
+
readonly verification: R.VerificationResource;
|
|
59
|
+
/** Публичный список загрузок: расширение 1С и Tungo Connector (без ключа API) */
|
|
60
|
+
readonly releases: R.ReleasesResource;
|
|
57
61
|
constructor(options?: ClientOptions);
|
|
58
62
|
/** Base URL the client talks to. */
|
|
59
63
|
get baseUrl(): string;
|
|
@@ -87,7 +91,8 @@ export declare class Tungo {
|
|
|
87
91
|
}): APIPromise<T.BatchJob>;
|
|
88
92
|
/**
|
|
89
93
|
* 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
|
|
94
|
+
* bytes sent are signed in the `X-Signature: sha256=<hex>` header, or in `signatureHeader` for a
|
|
95
|
+
* hook created with its own `signature_header`. The API key is not sent.
|
|
91
96
|
* Same as `client.automations.postHook`.
|
|
92
97
|
*/
|
|
93
98
|
sendHook(token: string, payload: HookPayload, options?: SendHookOptions): APIPromise<T.AutomationHookAccepted>;
|
package/dist/cjs/client.js
CHANGED
|
@@ -5,6 +5,7 @@ exports.Tungo = void 0;
|
|
|
5
5
|
const core_js_1 = require("./core.js");
|
|
6
6
|
const chat_js_1 = require("./chat.js");
|
|
7
7
|
const errors_js_1 = require("./errors.js");
|
|
8
|
+
const json_js_1 = require("./json.js");
|
|
8
9
|
const webhooks_js_1 = require("./webhooks.js");
|
|
9
10
|
const R = require("./generated/resources.js");
|
|
10
11
|
const RUN_FINAL_STATES = ['done', 'error', 'skipped', 'cancelled'];
|
|
@@ -45,6 +46,10 @@ class Tungo {
|
|
|
45
46
|
onec;
|
|
46
47
|
/** Автоматизации компании: входящие хуки, сценарии, цепочки шагов, запуски и уровень автономности ИИ */
|
|
47
48
|
automations;
|
|
49
|
+
/** Публичная проверка электронной подписи документов Tungo: по коду, по файлу, по блоку QR и ключи подписи (без ключа API) */
|
|
50
|
+
verification;
|
|
51
|
+
/** Публичный список загрузок: расширение 1С и Tungo Connector (без ключа API) */
|
|
52
|
+
releases;
|
|
48
53
|
#client;
|
|
49
54
|
constructor(options = {}) {
|
|
50
55
|
const client = new core_js_1.APIClient(options);
|
|
@@ -62,6 +67,8 @@ class Tungo {
|
|
|
62
67
|
this.forms = new R.FormsResource(client);
|
|
63
68
|
this.onec = new R.OnecResource(client);
|
|
64
69
|
this.automations = new R.AutomationsResource(client);
|
|
70
|
+
this.verification = new R.VerificationResource(client);
|
|
71
|
+
this.releases = new R.ReleasesResource(client);
|
|
65
72
|
}
|
|
66
73
|
/** Base URL the client talks to. */
|
|
67
74
|
get baseUrl() {
|
|
@@ -126,7 +133,8 @@ class Tungo {
|
|
|
126
133
|
}
|
|
127
134
|
/**
|
|
128
135
|
* Sends an event to an incoming automation hook (`/hooks/{token}`). With `secret`, the exact
|
|
129
|
-
* bytes sent are signed in the `X-Signature: sha256=<hex>` header
|
|
136
|
+
* bytes sent are signed in the `X-Signature: sha256=<hex>` header, or in `signatureHeader` for a
|
|
137
|
+
* hook created with its own `signature_header`. The API key is not sent.
|
|
130
138
|
* Same as `client.automations.postHook`.
|
|
131
139
|
*/
|
|
132
140
|
sendHook(token, payload, options) {
|
|
@@ -154,7 +162,7 @@ class Tungo {
|
|
|
154
162
|
return this.#poll('the automation run to finish', (requestOptions) => this.automations.getRun(companyId, runId, requestOptions).withResponse(), (run, response) => {
|
|
155
163
|
const state = run?.state;
|
|
156
164
|
if (typeof state !== 'string') {
|
|
157
|
-
throw new errors_js_1.DecodeError('The automation run has no "state"', { status: response.status, requestId: response.requestId, body:
|
|
165
|
+
throw new errors_js_1.DecodeError('The automation run has no "state"', { status: response.status, requestId: response.requestId, body: (0, json_js_1.debugJSON)(run) });
|
|
158
166
|
}
|
|
159
167
|
return RUN_FINAL_STATES.includes(state);
|
|
160
168
|
}, options);
|
|
@@ -164,7 +172,7 @@ class Tungo {
|
|
|
164
172
|
return this.#poll('the batch job to finish', (requestOptions) => this.batches.get(companyId, batchId, requestOptions).withResponse(), (job, response) => {
|
|
165
173
|
const running = job?.running;
|
|
166
174
|
if (typeof running !== 'boolean') {
|
|
167
|
-
throw new errors_js_1.DecodeError('The batch job has no "running" flag', { status: response.status, requestId: response.requestId, body:
|
|
175
|
+
throw new errors_js_1.DecodeError('The batch job has no "running" flag', { status: response.status, requestId: response.requestId, body: (0, json_js_1.debugJSON)(job) });
|
|
168
176
|
}
|
|
169
177
|
return !running;
|
|
170
178
|
}, options);
|
package/dist/cjs/core.d.ts
CHANGED
|
@@ -78,7 +78,10 @@ export interface RequestOptions {
|
|
|
78
78
|
maxRetries?: number | undefined;
|
|
79
79
|
/** Extra headers; a null value removes a default header. */
|
|
80
80
|
headers?: Record<string, string | null | undefined> | undefined;
|
|
81
|
-
/**
|
|
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
|
+
*/
|
|
82
85
|
idempotencyKey?: string | undefined;
|
|
83
86
|
/** Cancels the request (and its retries and waits). It is combined with the timeout. */
|
|
84
87
|
signal?: AbortSignal | undefined;
|
|
@@ -106,6 +109,11 @@ export interface RequestSpec {
|
|
|
106
109
|
auth?: 'key' | 'public' | 'hook' | undefined;
|
|
107
110
|
/** Wire name of the idempotency header when the operation declares one. */
|
|
108
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;
|
|
109
117
|
/** Use the long-running timeout by default. */
|
|
110
118
|
longRunning?: boolean | undefined;
|
|
111
119
|
/** The success response has no body. */
|
|
@@ -117,7 +125,6 @@ export interface WithResponse<T> {
|
|
|
117
125
|
data: T;
|
|
118
126
|
response: ResponseInfo;
|
|
119
127
|
}
|
|
120
|
-
/** Reads an environment variable on Node.js, Bun and Deno; undefined elsewhere or when empty. */
|
|
121
128
|
export declare function readEnv(name: string): string | undefined;
|
|
122
129
|
/** A random RFC 4122 version 4 UUID from the platform CSPRNG. */
|
|
123
130
|
export declare function uuid4(): string;
|