@tungoai/sdk 0.2.0 → 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 (47) hide show
  1. package/CHANGELOG.md +54 -1
  2. package/README.kk.md +5 -5
  3. package/README.md +7 -7
  4. package/README.ru.md +5 -5
  5. package/dist/cjs/chat.js +3 -2
  6. package/dist/cjs/client.d.ts +2 -1
  7. package/dist/cjs/client.js +5 -3
  8. package/dist/cjs/core.d.ts +9 -2
  9. package/dist/cjs/core.js +191 -17
  10. package/dist/cjs/errors.d.ts +25 -0
  11. package/dist/cjs/errors.js +39 -3
  12. package/dist/cjs/generated/resources.d.ts +92 -2
  13. package/dist/cjs/generated/resources.js +82 -1
  14. package/dist/cjs/generated/types.d.ts +562 -54
  15. package/dist/cjs/index.d.ts +1 -1
  16. package/dist/cjs/index.js +3 -2
  17. package/dist/cjs/json.d.ts +6 -0
  18. package/dist/cjs/json.js +17 -0
  19. package/dist/cjs/pagination.js +2 -1
  20. package/dist/cjs/streaming.d.ts +4 -2
  21. package/dist/cjs/streaming.js +40 -2
  22. package/dist/cjs/version.d.ts +1 -1
  23. package/dist/cjs/version.js +1 -1
  24. package/dist/cjs/webhooks.d.ts +5 -0
  25. package/dist/cjs/webhooks.js +17 -3
  26. package/dist/esm/chat.js +3 -2
  27. package/dist/esm/client.d.ts +2 -1
  28. package/dist/esm/client.js +5 -3
  29. package/dist/esm/core.d.ts +9 -2
  30. package/dist/esm/core.js +191 -17
  31. package/dist/esm/errors.d.ts +25 -0
  32. package/dist/esm/errors.js +36 -1
  33. package/dist/esm/generated/resources.d.ts +92 -2
  34. package/dist/esm/generated/resources.js +82 -1
  35. package/dist/esm/generated/types.d.ts +562 -54
  36. package/dist/esm/index.d.ts +1 -1
  37. package/dist/esm/index.js +1 -1
  38. package/dist/esm/json.d.ts +6 -0
  39. package/dist/esm/json.js +16 -0
  40. package/dist/esm/pagination.js +2 -1
  41. package/dist/esm/streaming.d.ts +4 -2
  42. package/dist/esm/streaming.js +41 -3
  43. package/dist/esm/version.d.ts +1 -1
  44. package/dist/esm/version.js +1 -1
  45. package/dist/esm/webhooks.d.ts +5 -0
  46. package/dist/esm/webhooks.js +17 -3
  47. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -9,6 +9,58 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
9
9
 
10
10
  ## [Unreleased]
11
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
+
12
64
  ## [0.2.0] - 2026-11-12
13
65
 
14
66
  First production-ready release. It contains breaking changes compared with 0.1.0; 0.1.0 should not be used.
@@ -35,6 +87,7 @@ First production-ready release. It contains breaking changes compared with 0.1.0
35
87
 
36
88
  Initial preview. Not suitable for production use.
37
89
 
38
- [Unreleased]: https://github.com/TungoAI/tungo-sdk-typescript/compare/v0.2.0...HEAD
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
39
92
  [0.2.0]: https://github.com/TungoAI/tungo-sdk-typescript/compare/v0.1.0...v0.2.0
40
93
  [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` тақырыбы бар `POST` пен `PATCH`. Келісімшарт осы тақырыпты жариялайтын операциялар үшін SDK кездейсоқ кілтті өзі жасап, оны барлық әрекетте қолданады; өз кілтіңізді беруге болады.
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-інің келісімшартынан жасалған: **ресурстар — 13, әдістер — 82, вебхук оқиғаларының түрлері — 22**.
284
+ Tungo платформасы API-інің келісімшартынан жасалған: **ресурстар — 13, әдістер — 90, вебхук оқиғаларының түрлері — 22**.
285
285
 
286
286
  | Ресурс | Сипаттама | Әдістер |
287
287
  | --- | --- | --- |
@@ -290,8 +290,8 @@ 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` · `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
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` |
@@ -318,7 +318,7 @@ Tungo платформасы API-інің келісімшартынан жас
318
318
 
319
319
  ## Нұсқалар және қолдау
320
320
 
321
- Кітапхана [семантикалық нұсқалауды](https://semver.org/) ұстанады. Жоғарғы нұсқа 0 болып тұрғанда аралық шығарылымда үйлесімсіз өзгерістер болуы мүмкін; олар әрдайым [өзгерістер тарихында](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/CHANGELOG.md) келтіріледі. Бұл README 0.2.0 нұсқасын сипаттайды.
321
+ Кітапхана [семантикалық нұсқалауды](https://semver.org/) ұстанады. Жоғарғы нұсқа 0 болып тұрғанда аралық шығарылымда үйлесімсіз өзгерістер болуы мүмкін; олар әрдайым [өзгерістер тарихында](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/CHANGELOG.md) келтіріледі. Бұл README 0.3.0 нұсқасын сипаттайды.
322
322
 
323
323
  Код генератормен жасалады: мәселелер мен ұсыныстар туралы жасалған файлдарға түзету жібермей, [өтініштерге](https://github.com/TungoAI/tungo-sdk-typescript/issues) жазыңыз. Осалдық туралы [қауіпсіздік саясаты](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/SECURITY.md) бойынша хабарлаңыз.
324
324
 
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 that carry an `Idempotency-Key`. For the operations whose contract declares that header the SDK generates a random key and reuses it for every attempt; you can pass your own.
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: **13 resources, 82 methods, 22 webhook event types**.
304
+ Generated from the Tungo Platform API contract: **13 resources, 90 methods, 22 webhook event types**.
305
305
 
306
306
  | Resource | Description | Methods |
307
307
  | --- | --- | --- |
@@ -310,8 +310,8 @@ 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` · `listMentions` · `getRatingOptions` · `listSuggestions` · `get` · `update` · `delete` · `answer` · `answerStream` · `listEvents` · `rateMessage` · `deleteMessageRating` · `rate` · `dismissRating` · `stop` |
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` |
@@ -338,7 +338,7 @@ The same API is available in ten languages. All SDKs are generated from one cont
338
338
 
339
339
  ## Versioning and support
340
340
 
341
- This library follows [Semantic Versioning](https://semver.org/). While the major version is 0, a minor release may contain breaking changes; they are always listed in the [changelog](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/CHANGELOG.md). This README describes version 0.2.0.
341
+ This library follows [Semantic Versioning](https://semver.org/). While the major version is 0, a minor release may contain breaking changes; they are always listed in the [changelog](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/CHANGELOG.md). This README describes version 0.3.0.
342
342
 
343
343
  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
344
 
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` с заголовком `Idempotency-Key`. Для операций, у которых контракт объявляет этот заголовок, SDK сам создаёт случайный ключ и использует его во всех попытках; можно передать свой.
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: **ресурсов — 13, методов — 82, типов событий вебхуков — 22**.
284
+ Создано из контракта API платформы Tungo: **ресурсов — 13, методов — 90, типов событий вебхуков — 22**.
285
285
 
286
286
  | Ресурс | Описание | Методы |
287
287
  | --- | --- | --- |
@@ -290,8 +290,8 @@ 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` · `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
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` |
@@ -318,7 +318,7 @@ console.log(isValidBinIin('990140000017')); // true
318
318
 
319
319
  ## Версии и поддержка
320
320
 
321
- Библиотека следует [семантическому версионированию](https://semver.org/lang/ru/). Пока старшая версия равна 0, промежуточный выпуск может содержать несовместимые изменения; они всегда перечислены в [истории изменений](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/CHANGELOG.md). Этот README описывает версию 0.2.0.
321
+ Библиотека следует [семантическому версионированию](https://semver.org/lang/ru/). Пока старшая версия равна 0, промежуточный выпуск может содержать несовместимые изменения; они всегда перечислены в [истории изменений](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/CHANGELOG.md). Этот README описывает версию 0.3.0.
322
322
 
323
323
  Код создаётся генератором: пишите о проблемах и идеях в [обращения](https://github.com/TungoAI/tungo-sdk-typescript/issues), а не присылайте правки к созданным файлам. Об уязвимости сообщайте по [политике безопасности](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/SECURITY.md).
324
324
 
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: JSON.stringify(error) ?? '',
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');
@@ -87,7 +87,8 @@ export declare class Tungo {
87
87
  }): APIPromise<T.BatchJob>;
88
88
  /**
89
89
  * Sends an event to an incoming automation hook (`/hooks/{token}`). With `secret`, the exact
90
- * bytes sent are signed in the `X-Signature: sha256=<hex>` header. The API key is not sent.
90
+ * bytes sent are signed in the `X-Signature: sha256=<hex>` header, or in `signatureHeader` for a
91
+ * hook created with its own `signature_header`. The API key is not sent.
91
92
  * Same as `client.automations.postHook`.
92
93
  */
93
94
  sendHook(token: string, payload: HookPayload, options?: SendHookOptions): APIPromise<T.AutomationHookAccepted>;
@@ -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'];
@@ -126,7 +127,8 @@ class Tungo {
126
127
  }
127
128
  /**
128
129
  * 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. The API key is not sent.
130
+ * bytes sent are signed in the `X-Signature: sha256=<hex>` header, or in `signatureHeader` for a
131
+ * hook created with its own `signature_header`. The API key is not sent.
130
132
  * Same as `client.automations.postHook`.
131
133
  */
132
134
  sendHook(token, payload, options) {
@@ -154,7 +156,7 @@ class Tungo {
154
156
  return this.#poll('the automation run to finish', (requestOptions) => this.automations.getRun(companyId, runId, requestOptions).withResponse(), (run, response) => {
155
157
  const state = run?.state;
156
158
  if (typeof state !== 'string') {
157
- throw new errors_js_1.DecodeError('The automation run has no "state"', { status: response.status, requestId: response.requestId, body: JSON.stringify(run) ?? '' });
159
+ 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
160
  }
159
161
  return RUN_FINAL_STATES.includes(state);
160
162
  }, options);
@@ -164,7 +166,7 @@ class Tungo {
164
166
  return this.#poll('the batch job to finish', (requestOptions) => this.batches.get(companyId, batchId, requestOptions).withResponse(), (job, response) => {
165
167
  const running = job?.running;
166
168
  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: JSON.stringify(job) ?? '' });
169
+ 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
170
  }
169
171
  return !running;
170
172
  }, options);
@@ -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
- /** Your own `Idempotency-Key`. Without it the SDK generates one for operations that declare the header. */
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;
package/dist/cjs/core.js CHANGED
@@ -34,6 +34,87 @@ exports.MAX_RETRY_AFTER_SECONDS = 60;
34
34
  exports.MAX_TIMER_MS = 2_147_483_647;
35
35
  const USER_AGENT = 'tungo-sdk-typescript/' + version_js_1.VERSION;
36
36
  /** Reads an environment variable on Node.js, Bun and Deno; undefined elsewhere or when empty. */
37
+ /** Whether a stream call was answered with a stored result replayed by Idempotency-Key. */
38
+ function isReplayedJSON(headers) {
39
+ const mediaType = (headers.get('content-type') ?? '').split(';')[0] ?? '';
40
+ return mediaType.trim().toLowerCase() === 'application/json' && (headers.get('idempotent-replayed') ?? '').trim().toLowerCase() === 'true';
41
+ }
42
+ function isObject(value) {
43
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
44
+ }
45
+ /**
46
+ * Turns a replayed ChatTurnResult into the event stream of the turn it stands for: text (the
47
+ * answer), proposal, question, citation, error, choice and next events, then done. The dialog id and
48
+ * the turn number, which a replay carries only in the body, become the X-Dialog-Id and X-Turn-No
49
+ * headers when they are missing: `headers` are those of the response with them, the other headers
50
+ * (Idempotent-Replayed among them) unchanged. Returns null when the body is not a chat turn result.
51
+ */
52
+ function replayAsEventStream(response, text, requestId) {
53
+ let result;
54
+ try {
55
+ result = (0, json_js_1.parseJSON)(text);
56
+ }
57
+ catch {
58
+ return null;
59
+ }
60
+ if (!isObject(result))
61
+ return null;
62
+ const dialogId = result['dialog_id'];
63
+ if (typeof dialogId !== 'string')
64
+ return null;
65
+ const headers = new Headers(response.headers);
66
+ if ((headers.get('x-dialog-id') ?? '') === '')
67
+ headers.set('x-dialog-id', dialogId);
68
+ const turnNo = result['turn_no'];
69
+ if ((headers.get('x-turn-no') ?? '') === '' && (typeof turnNo === 'number' || typeof turnNo === 'bigint'))
70
+ headers.set('x-turn-no', String(turnNo));
71
+ const entries = (key) => {
72
+ const list = result[key];
73
+ return Array.isArray(list) ? list.filter(isObject) : [];
74
+ };
75
+ let body = '';
76
+ const emit = (type, event) => {
77
+ body += 'event: ' + type + '\ndata: ' + (0, json_js_1.stringifyJSON)({ ...event, type }) + '\n\n';
78
+ };
79
+ const answerValue = result['answer'];
80
+ const answer = typeof answerValue === 'string' ? answerValue : '';
81
+ if (answer !== '')
82
+ emit('text', { delta: answer });
83
+ for (const { id, ...rest } of entries('proposals'))
84
+ emit('proposal', { ...rest, proposal_id: id });
85
+ for (const question of entries('questions'))
86
+ emit('question', question);
87
+ for (const citation of entries('citations'))
88
+ emit('citation', citation);
89
+ for (const error of entries('errors'))
90
+ emit('error', { error, request_id: requestId });
91
+ const done = { answer };
92
+ const stopReason = result['stop_reason'];
93
+ if (typeof stopReason === 'string')
94
+ done['stop_reason'] = stopReason;
95
+ const usageValue = result['usage'];
96
+ if (isObject(usageValue)) {
97
+ const { cost_tiyn: cost, ...usage } = usageValue;
98
+ done['usage'] = usage;
99
+ if (cost !== undefined)
100
+ done['cost_tiyn'] = cost;
101
+ }
102
+ const pending = result['pending_question'];
103
+ if (isObject(pending)) {
104
+ emit('choice', pending);
105
+ done['choice_id'] = pending['choice_id'];
106
+ }
107
+ // A live turn ends its finished answer with next right before done; the stored result keeps it
108
+ // as followups and next_action.
109
+ const followups = Array.isArray(result['followups']) ? result['followups'] : [];
110
+ const action = result['next_action'];
111
+ if (followups.length > 0 || isObject(action))
112
+ emit('next', { followups, action: isObject(action) ? action : null });
113
+ emit('done', done);
114
+ const streamHeaders = new Headers(headers);
115
+ streamHeaders.set('content-type', 'text/event-stream');
116
+ return { response: new Response(body, { status: response.status, headers: streamHeaders }), headers };
117
+ }
37
118
  function readEnv(name) {
38
119
  try {
39
120
  const scope = globalThis;
@@ -49,6 +130,21 @@ function readEnv(name) {
49
130
  }
50
131
  return undefined;
51
132
  }
133
+ /**
134
+ * The `idempotency_key` field of a JSON object body (approving a proposal documents it as the same
135
+ * as the header), trimmed like the API trims it. The API prefers the header over the field, so a
136
+ * generated header would make the caller's own key useless. A key that cannot travel in a header
137
+ * (outside printable ASCII) is ignored here.
138
+ */
139
+ function bodyIdempotencyKey(body) {
140
+ if (typeof body !== 'object' || body === null || Array.isArray(body))
141
+ return undefined;
142
+ const value = body['idempotency_key'];
143
+ if (typeof value !== 'string')
144
+ return undefined;
145
+ const key = value.trim();
146
+ return key !== '' && /^[\x20-\x7e]+$/.test(key) ? key : undefined;
147
+ }
52
148
  /** A random RFC 4122 version 4 UUID from the platform CSPRNG. */
53
149
  function uuid4() {
54
150
  const bytes = new Uint8Array(16);
@@ -201,6 +297,29 @@ function causeText(cause) {
201
297
  }
202
298
  return cause.message;
203
299
  }
300
+ /**
301
+ * The text of a transport failure without the request URL: a custom fetch (node-fetch, a proxy
302
+ * or tracing wrapper) may put the full URL into its message, and the path can carry a hook token
303
+ * and the query search text. The URL and the concrete path become the route template, and any
304
+ * other absolute URL and every path parameter value are cut out.
305
+ */
306
+ function redactedCauseText(cause, baseUrl, url, spec) {
307
+ let text = causeText(cause);
308
+ const path = buildPath(spec.path, spec.pathParams);
309
+ const pathAndQuery = url.slice(baseUrl.length);
310
+ for (const concrete of [url, url.split('?')[0] ?? url, pathAndQuery, path]) {
311
+ if (concrete !== '' && concrete !== '/')
312
+ text = text.split(concrete).join(spec.path);
313
+ }
314
+ text = text.replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s"'<>]*/gi, '[url]');
315
+ for (const value of Object.values(spec.pathParams ?? {})) {
316
+ if (typeof value !== 'string' || value === '')
317
+ continue;
318
+ for (const form of new Set([value, encodeURIComponent(value)]))
319
+ text = text.split(form).join('[redacted]');
320
+ }
321
+ return text;
322
+ }
204
323
  function positive(value, fallback, name, zeroAllowed) {
205
324
  if (value === undefined)
206
325
  return fallback;
@@ -217,10 +336,23 @@ function retries(value, fallback) {
217
336
  }
218
337
  return value;
219
338
  }
339
+ /**
340
+ * Whether a header value can be sent at all: fetch refuses CR, LF and NUL, and a character above
341
+ * U+00FF (a Cyrillic look-alike pasted into a key) is not a byte, so fetch would throw a
342
+ * TypeError that looks like a network failure.
343
+ */
344
+ function sendableHeaderValue(value) {
345
+ for (let i = 0; i < value.length; i++) {
346
+ const code = value.charCodeAt(i);
347
+ if (code === 0 || code === 10 || code === 13 || code > 0xff)
348
+ return false;
349
+ }
350
+ return true;
351
+ }
220
352
  class HeaderBag {
221
353
  #map = new Map();
222
354
  set(name, value) {
223
- if (value.includes('\r') || value.includes('\n') || value.includes('\0') || !/^[!#$%&'*+.^_|~0-9A-Za-z-]+$/.test(name)) {
355
+ if (!sendableHeaderValue(value) || !/^[!#$%&'*+.^_|~0-9A-Za-z-]+$/.test(name)) {
224
356
  throw new errors_js_1.ValidationError('The header "' + name.replace(/[^ -~]/g, '?') + '" has an invalid name or value');
225
357
  }
226
358
  this.#map.set(name.toLowerCase(), [name, value]);
@@ -375,16 +507,29 @@ class APIClient {
375
507
  return new APIPromise(this.#requestJSON(spec));
376
508
  }
377
509
  /** Opens a server-sent event stream; `make` wraps the connection into the stream object. */
378
- openStream(spec, make) {
379
- return this.#exchange(spec, true).then((x) => make({
380
- response: x.info,
381
- body: x.response.body,
382
- controller: x.controller,
383
- signal: spec.options?.signal ?? undefined,
384
- detach: x.detach,
385
- idleTimeout: positive(spec.options?.streamIdleTimeout, this.streamIdleTimeout, 'streamIdleTimeout', true),
386
- route: spec.method.toUpperCase() + ' ' + spec.path,
387
- }));
510
+ async openStream(spec, make) {
511
+ // Checked before anything is sent: once the turn is posted it runs (and is billed) on the
512
+ // server, so a bad option found afterwards would cost a turn and leave the connection open.
513
+ const idleTimeout = positive(spec.options?.streamIdleTimeout, this.streamIdleTimeout, 'streamIdleTimeout', true);
514
+ const x = await this.#exchange(spec, true);
515
+ try {
516
+ return make({
517
+ response: x.info,
518
+ body: x.response.body,
519
+ controller: x.controller,
520
+ signal: spec.options?.signal ?? undefined,
521
+ detach: x.detach,
522
+ idleTimeout,
523
+ route: spec.method.toUpperCase() + ' ' + spec.path,
524
+ });
525
+ }
526
+ catch (error) {
527
+ // The stream object never came to be: nobody else can close the connection.
528
+ x.detach();
529
+ x.controller.abort();
530
+ x.response.body?.cancel().catch(() => undefined);
531
+ throw error;
532
+ }
388
533
  }
389
534
  async #requestJSON(spec) {
390
535
  const x = await this.#exchange(spec, false);
@@ -443,19 +588,30 @@ class APIClient {
443
588
  if (key === undefined) {
444
589
  throw new errors_js_1.ConfigError('No API key: pass "apiKey" to the client or set the TUNGO_API_KEY environment variable');
445
590
  }
591
+ if (!sendableHeaderValue(key)) {
592
+ // Never the key itself: only what is wrong with it.
593
+ throw new errors_js_1.ConfigError('The API key contains a character that cannot be sent in a header (a line break, or a letter outside Latin-1 such as a Cyrillic look-alike): check "apiKey" or TUNGO_API_KEY');
594
+ }
446
595
  if (this.#bearer)
447
596
  bag.set('Authorization', 'Bearer ' + key);
448
597
  else
449
598
  bag.set('x-api-key', key);
450
599
  }
451
- const headerName = spec.idempotencyHeader ?? 'Idempotency-Key';
600
+ if (options.idempotencyKey === '')
601
+ throw new errors_js_1.ValidationError('The idempotency key must not be empty');
602
+ const headerName = spec.idempotencyHeader;
603
+ if (headerName === undefined) {
604
+ // The API ignores a key on an operation that declares none: sending one would make a retry
605
+ // look safe when it repeats the action.
606
+ bag.delete('Idempotency-Key');
607
+ return { headers: bag.toRecord(), hasIdempotencyKey: false };
608
+ }
452
609
  if (options.idempotencyKey !== undefined) {
453
- if (options.idempotencyKey === '')
454
- throw new errors_js_1.ValidationError('The idempotency key must not be empty');
455
610
  bag.set(headerName, options.idempotencyKey);
456
611
  }
457
- else if (spec.idempotencyHeader !== undefined && !bag.has(headerName)) {
458
- bag.set(headerName, uuid4());
612
+ else if (!bag.has(headerName)) {
613
+ const fallback = spec.defaultIdempotencyKey !== undefined && spec.defaultIdempotencyKey !== '' ? spec.defaultIdempotencyKey : bodyIdempotencyKey(spec.body);
614
+ bag.set(headerName, fallback ?? uuid4());
459
615
  }
460
616
  return { headers: bag.toRecord(), hasIdempotencyKey: bag.has(headerName) };
461
617
  }
@@ -537,6 +693,24 @@ class APIClient {
537
693
  attempts: attempt + 1,
538
694
  };
539
695
  if (response.status >= 200 && response.status < 300) {
696
+ if (stream && isReplayedJSON(response.headers)) {
697
+ // A chat turn repeated with the same Idempotency-Key after it finished: the server
698
+ // answers the stored ChatTurnResult instead of a stream. The caller gets its events.
699
+ const replayed = await response.text();
700
+ const synthesized = replayAsEventStream(response, replayed, info.requestId);
701
+ if (synthesized === null) {
702
+ throw new errors_js_1.DecodeError('The response of ' + route + ' (status ' + response.status + ') replays a result that is not a chat turn', {
703
+ status: response.status,
704
+ requestId: info.requestId,
705
+ body: replayed,
706
+ });
707
+ }
708
+ info.headers = synthesized.headers;
709
+ keepOpen = true;
710
+ clearTimeout(timer);
711
+ this.#log({ kind: 'response', method, route: spec.path, attempt: attempt + 1, status: info.status, durationMs: Date.now() - started, requestId: info.requestId });
712
+ return { info, text: '', response: synthesized.response, controller, detach };
713
+ }
540
714
  if (stream) {
541
715
  const contentType = (response.headers.get('content-type') ?? '').trim().toLowerCase();
542
716
  if (!contentType.startsWith('text/event-stream')) {
@@ -576,7 +750,7 @@ class APIClient {
576
750
  cause = 'timeout';
577
751
  }
578
752
  else {
579
- failure = new errors_js_1.ConnectionError('Could not reach the API for ' + route + ': ' + causeText(reason), { cause: reason });
753
+ failure = new errors_js_1.ConnectionError('Could not reach the API for ' + route + ': ' + redactedCauseText(reason, this.baseUrl, url, spec), { cause: reason });
580
754
  cause = 'connection_error';
581
755
  }
582
756
  }