@devicai/ui 0.57.0 → 0.59.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 (223) hide show
  1. package/README.md +186 -0
  2. package/dist/cjs/api/assistantInfo.js.map +1 -1
  3. package/dist/cjs/api/client.js +17 -1
  4. package/dist/cjs/api/client.js.map +1 -1
  5. package/dist/cjs/api/types.js.map +1 -1
  6. package/dist/cjs/components/AICommandBar/AICommandBar.js +12 -8
  7. package/dist/cjs/components/AICommandBar/AICommandBar.js.map +1 -1
  8. package/dist/cjs/components/AICommandBar/useAICommandBar.js +12 -6
  9. package/dist/cjs/components/AICommandBar/useAICommandBar.js.map +1 -1
  10. package/dist/cjs/components/AIElementWrapper/AIElementWrapper.js +19 -15
  11. package/dist/cjs/components/AIElementWrapper/AIElementWrapper.js.map +1 -1
  12. package/dist/cjs/components/AIElementWrapper/activeWrapperRegistry.js.map +1 -1
  13. package/dist/cjs/components/AIElementWrapper/useAIElementWrapper.js +12 -6
  14. package/dist/cjs/components/AIElementWrapper/useAIElementWrapper.js.map +1 -1
  15. package/dist/cjs/components/AIGenerationButton/AIGenerationButton.js +13 -7
  16. package/dist/cjs/components/AIGenerationButton/AIGenerationButton.js.map +1 -1
  17. package/dist/cjs/components/AIGenerationButton/useAIGenerationButton.js +11 -5
  18. package/dist/cjs/components/AIGenerationButton/useAIGenerationButton.js.map +1 -1
  19. package/dist/cjs/components/ChatDrawer/ChatDrawer.js +28 -13
  20. package/dist/cjs/components/ChatDrawer/ChatDrawer.js.map +1 -1
  21. package/dist/cjs/components/ChatDrawer/ChatInput.js +21 -15
  22. package/dist/cjs/components/ChatDrawer/ChatInput.js.map +1 -1
  23. package/dist/cjs/components/ChatDrawer/ChatMessages.js +54 -13
  24. package/dist/cjs/components/ChatDrawer/ChatMessages.js.map +1 -1
  25. package/dist/cjs/components/ChatDrawer/CompactionWidget.js +13 -4
  26. package/dist/cjs/components/ChatDrawer/CompactionWidget.js.map +1 -1
  27. package/dist/cjs/components/ChatDrawer/ConversationSelector.js +6 -4
  28. package/dist/cjs/components/ChatDrawer/ConversationSelector.js.map +1 -1
  29. package/dist/cjs/components/ChatDrawer/ErrorBoundary.js.map +1 -1
  30. package/dist/cjs/components/ChatDrawer/GuardrailNotice.js +40 -0
  31. package/dist/cjs/components/ChatDrawer/GuardrailNotice.js.map +1 -0
  32. package/dist/cjs/components/ChatDrawer/HandoffSubagentWidget.js +3 -1
  33. package/dist/cjs/components/ChatDrawer/HandoffSubagentWidget.js.map +1 -1
  34. package/dist/cjs/components/ChatDrawer/LimitBanner.js +19 -9
  35. package/dist/cjs/components/ChatDrawer/LimitBanner.js.map +1 -1
  36. package/dist/cjs/components/ChatDrawer/QueueNotice.js +19 -7
  37. package/dist/cjs/components/ChatDrawer/QueueNotice.js.map +1 -1
  38. package/dist/cjs/components/ChatDrawer/RecalledMemoriesWidget.js +17 -5
  39. package/dist/cjs/components/ChatDrawer/RecalledMemoriesWidget.js.map +1 -1
  40. package/dist/cjs/components/ChatDrawer/ReferenceChip.js +3 -1
  41. package/dist/cjs/components/ChatDrawer/ReferenceChip.js.map +1 -1
  42. package/dist/cjs/components/ChatDrawer/ToolTimeline.js.map +1 -1
  43. package/dist/cjs/components/ChatDrawer/UsageBar.js +23 -18
  44. package/dist/cjs/components/ChatDrawer/UsageBar.js.map +1 -1
  45. package/dist/cjs/components/ChatDrawer/pastedText.js.map +1 -1
  46. package/dist/cjs/components/CoreMemoryModal/CoreMemoryModal.js +20 -9
  47. package/dist/cjs/components/CoreMemoryModal/CoreMemoryModal.js.map +1 -1
  48. package/dist/cjs/components/Feedback/FeedbackModal.js +5 -1
  49. package/dist/cjs/components/Feedback/FeedbackModal.js.map +1 -1
  50. package/dist/cjs/components/Feedback/MessageActions.js +3 -1
  51. package/dist/cjs/components/Feedback/MessageActions.js.map +1 -1
  52. package/dist/cjs/components/IntegrationsModal/ConnectFieldsForm.js +12 -8
  53. package/dist/cjs/components/IntegrationsModal/ConnectFieldsForm.js.map +1 -1
  54. package/dist/cjs/components/IntegrationsModal/IntegrationLogo.js.map +1 -1
  55. package/dist/cjs/components/IntegrationsModal/IntegrationsHint.js +5 -3
  56. package/dist/cjs/components/IntegrationsModal/IntegrationsHint.js.map +1 -1
  57. package/dist/cjs/components/IntegrationsModal/IntegrationsLauncher.js +12 -3
  58. package/dist/cjs/components/IntegrationsModal/IntegrationsLauncher.js.map +1 -1
  59. package/dist/cjs/components/IntegrationsModal/IntegrationsModal.js.map +1 -1
  60. package/dist/cjs/components/IntegrationsModal/IntegrationsPanel.js +34 -24
  61. package/dist/cjs/components/IntegrationsModal/IntegrationsPanel.js.map +1 -1
  62. package/dist/cjs/components/IntegrationsModal/IntegrationsToggle.js +15 -6
  63. package/dist/cjs/components/IntegrationsModal/IntegrationsToggle.js.map +1 -1
  64. package/dist/cjs/components/IntegrationsModal/McpConnectForm.js +15 -7
  65. package/dist/cjs/components/IntegrationsModal/McpConnectForm.js.map +1 -1
  66. package/dist/cjs/components/IntegrationsModal/McpServersSection.js +32 -19
  67. package/dist/cjs/components/IntegrationsModal/McpServersSection.js.map +1 -1
  68. package/dist/cjs/components/IntegrationsModal/integrationChoice.js.map +1 -1
  69. package/dist/cjs/components/IntegrationsModal/useIntegrations.js +3 -1
  70. package/dist/cjs/components/IntegrationsModal/useIntegrations.js.map +1 -1
  71. package/dist/cjs/components/IntegrationsModal/useTenantMcp.js +3 -1
  72. package/dist/cjs/components/IntegrationsModal/useTenantMcp.js.map +1 -1
  73. package/dist/cjs/components/ThreadStateTag/ThreadStateTag.js +63 -40
  74. package/dist/cjs/components/ThreadStateTag/ThreadStateTag.js.map +1 -1
  75. package/dist/cjs/components/theme.js.map +1 -1
  76. package/dist/cjs/hooks/useDevicChat.js +21 -7
  77. package/dist/cjs/hooks/useDevicChat.js.map +1 -1
  78. package/dist/cjs/hooks/useModelInterface.js.map +1 -1
  79. package/dist/cjs/hooks/usePolling.js +117 -7
  80. package/dist/cjs/hooks/usePolling.js.map +1 -1
  81. package/dist/cjs/hooks/useSpeechRecording.js +8 -4
  82. package/dist/cjs/hooks/useSpeechRecording.js.map +1 -1
  83. package/dist/cjs/i18n/translate.js +48 -0
  84. package/dist/cjs/i18n/translate.js.map +1 -0
  85. package/dist/cjs/i18n/useTranslations.js +57 -0
  86. package/dist/cjs/i18n/useTranslations.js.map +1 -0
  87. package/dist/cjs/index.js +11 -0
  88. package/dist/cjs/index.js.map +1 -1
  89. package/dist/cjs/provider/DevicContext.js.map +1 -1
  90. package/dist/cjs/provider/DevicProvider.js +5 -1
  91. package/dist/cjs/provider/DevicProvider.js.map +1 -1
  92. package/dist/cjs/provider/sharedSession.js.map +1 -1
  93. package/dist/cjs/styles.css +1 -1
  94. package/dist/cjs/utils/avatar.js.map +1 -1
  95. package/dist/cjs/utils/consumeChatStream.js +44 -0
  96. package/dist/cjs/utils/consumeChatStream.js.map +1 -0
  97. package/dist/cjs/utils/index.js.map +1 -1
  98. package/dist/cjs/utils/logger.js.map +1 -1
  99. package/dist/cjs/utils/toolGroups.js.map +1 -1
  100. package/dist/esm/api/assistantInfo.js.map +1 -1
  101. package/dist/esm/api/client.d.ts +5 -1
  102. package/dist/esm/api/client.js +17 -1
  103. package/dist/esm/api/client.js.map +1 -1
  104. package/dist/esm/api/types.d.ts +12 -1
  105. package/dist/esm/api/types.js.map +1 -1
  106. package/dist/esm/components/AICommandBar/AICommandBar.js +13 -9
  107. package/dist/esm/components/AICommandBar/AICommandBar.js.map +1 -1
  108. package/dist/esm/components/AICommandBar/AICommandBar.types.d.ts +16 -0
  109. package/dist/esm/components/AICommandBar/useAICommandBar.d.ts +2 -0
  110. package/dist/esm/components/AICommandBar/useAICommandBar.js +13 -7
  111. package/dist/esm/components/AICommandBar/useAICommandBar.js.map +1 -1
  112. package/dist/esm/components/AIElementWrapper/AIElementWrapper.js +19 -15
  113. package/dist/esm/components/AIElementWrapper/AIElementWrapper.js.map +1 -1
  114. package/dist/esm/components/AIElementWrapper/AIElementWrapper.types.d.ts +16 -0
  115. package/dist/esm/components/AIElementWrapper/activeWrapperRegistry.js.map +1 -1
  116. package/dist/esm/components/AIElementWrapper/useAIElementWrapper.d.ts +2 -0
  117. package/dist/esm/components/AIElementWrapper/useAIElementWrapper.js +13 -7
  118. package/dist/esm/components/AIElementWrapper/useAIElementWrapper.js.map +1 -1
  119. package/dist/esm/components/AIGenerationButton/AIGenerationButton.js +14 -8
  120. package/dist/esm/components/AIGenerationButton/AIGenerationButton.js.map +1 -1
  121. package/dist/esm/components/AIGenerationButton/AIGenerationButton.types.d.ts +16 -0
  122. package/dist/esm/components/AIGenerationButton/useAIGenerationButton.d.ts +2 -0
  123. package/dist/esm/components/AIGenerationButton/useAIGenerationButton.js +12 -6
  124. package/dist/esm/components/AIGenerationButton/useAIGenerationButton.js.map +1 -1
  125. package/dist/esm/components/ChatDrawer/ChatDrawer.js +29 -14
  126. package/dist/esm/components/ChatDrawer/ChatDrawer.js.map +1 -1
  127. package/dist/esm/components/ChatDrawer/ChatDrawer.types.d.ts +41 -0
  128. package/dist/esm/components/ChatDrawer/ChatInput.js +21 -15
  129. package/dist/esm/components/ChatDrawer/ChatInput.js.map +1 -1
  130. package/dist/esm/components/ChatDrawer/ChatMessages.d.ts +1 -1
  131. package/dist/esm/components/ChatDrawer/ChatMessages.js +54 -13
  132. package/dist/esm/components/ChatDrawer/ChatMessages.js.map +1 -1
  133. package/dist/esm/components/ChatDrawer/CompactionWidget.js +13 -4
  134. package/dist/esm/components/ChatDrawer/CompactionWidget.js.map +1 -1
  135. package/dist/esm/components/ChatDrawer/ConversationSelector.js +6 -4
  136. package/dist/esm/components/ChatDrawer/ConversationSelector.js.map +1 -1
  137. package/dist/esm/components/ChatDrawer/ErrorBoundary.js.map +1 -1
  138. package/dist/esm/components/ChatDrawer/GuardrailNotice.d.ts +36 -0
  139. package/dist/esm/components/ChatDrawer/GuardrailNotice.js +38 -0
  140. package/dist/esm/components/ChatDrawer/GuardrailNotice.js.map +1 -0
  141. package/dist/esm/components/ChatDrawer/HandoffSubagentWidget.js +3 -1
  142. package/dist/esm/components/ChatDrawer/HandoffSubagentWidget.js.map +1 -1
  143. package/dist/esm/components/ChatDrawer/LimitBanner.js +19 -9
  144. package/dist/esm/components/ChatDrawer/LimitBanner.js.map +1 -1
  145. package/dist/esm/components/ChatDrawer/QueueNotice.js +19 -7
  146. package/dist/esm/components/ChatDrawer/QueueNotice.js.map +1 -1
  147. package/dist/esm/components/ChatDrawer/RecalledMemoriesWidget.js +17 -5
  148. package/dist/esm/components/ChatDrawer/RecalledMemoriesWidget.js.map +1 -1
  149. package/dist/esm/components/ChatDrawer/ReferenceChip.js +3 -1
  150. package/dist/esm/components/ChatDrawer/ReferenceChip.js.map +1 -1
  151. package/dist/esm/components/ChatDrawer/ToolTimeline.js.map +1 -1
  152. package/dist/esm/components/ChatDrawer/UsageBar.js +23 -18
  153. package/dist/esm/components/ChatDrawer/UsageBar.js.map +1 -1
  154. package/dist/esm/components/ChatDrawer/index.d.ts +2 -0
  155. package/dist/esm/components/ChatDrawer/pastedText.js.map +1 -1
  156. package/dist/esm/components/CoreMemoryModal/CoreMemoryModal.js +20 -9
  157. package/dist/esm/components/CoreMemoryModal/CoreMemoryModal.js.map +1 -1
  158. package/dist/esm/components/Feedback/FeedbackModal.js +5 -1
  159. package/dist/esm/components/Feedback/FeedbackModal.js.map +1 -1
  160. package/dist/esm/components/Feedback/MessageActions.js +3 -1
  161. package/dist/esm/components/Feedback/MessageActions.js.map +1 -1
  162. package/dist/esm/components/IntegrationsModal/ConnectFieldsForm.js +12 -8
  163. package/dist/esm/components/IntegrationsModal/ConnectFieldsForm.js.map +1 -1
  164. package/dist/esm/components/IntegrationsModal/IntegrationLogo.js.map +1 -1
  165. package/dist/esm/components/IntegrationsModal/IntegrationsHint.js +5 -3
  166. package/dist/esm/components/IntegrationsModal/IntegrationsHint.js.map +1 -1
  167. package/dist/esm/components/IntegrationsModal/IntegrationsLauncher.js +12 -3
  168. package/dist/esm/components/IntegrationsModal/IntegrationsLauncher.js.map +1 -1
  169. package/dist/esm/components/IntegrationsModal/IntegrationsModal.js.map +1 -1
  170. package/dist/esm/components/IntegrationsModal/IntegrationsPanel.d.ts +1 -1
  171. package/dist/esm/components/IntegrationsModal/IntegrationsPanel.js +34 -24
  172. package/dist/esm/components/IntegrationsModal/IntegrationsPanel.js.map +1 -1
  173. package/dist/esm/components/IntegrationsModal/IntegrationsToggle.d.ts +1 -1
  174. package/dist/esm/components/IntegrationsModal/IntegrationsToggle.js +15 -6
  175. package/dist/esm/components/IntegrationsModal/IntegrationsToggle.js.map +1 -1
  176. package/dist/esm/components/IntegrationsModal/McpConnectForm.js +15 -7
  177. package/dist/esm/components/IntegrationsModal/McpConnectForm.js.map +1 -1
  178. package/dist/esm/components/IntegrationsModal/McpServersSection.js +32 -19
  179. package/dist/esm/components/IntegrationsModal/McpServersSection.js.map +1 -1
  180. package/dist/esm/components/IntegrationsModal/integrationChoice.js.map +1 -1
  181. package/dist/esm/components/IntegrationsModal/useIntegrations.js +3 -1
  182. package/dist/esm/components/IntegrationsModal/useIntegrations.js.map +1 -1
  183. package/dist/esm/components/IntegrationsModal/useTenantMcp.js +3 -1
  184. package/dist/esm/components/IntegrationsModal/useTenantMcp.js.map +1 -1
  185. package/dist/esm/components/ThreadStateTag/ThreadStateTag.js +63 -40
  186. package/dist/esm/components/ThreadStateTag/ThreadStateTag.js.map +1 -1
  187. package/dist/esm/components/theme.js.map +1 -1
  188. package/dist/esm/hooks/index.d.ts +1 -1
  189. package/dist/esm/hooks/useDevicChat.d.ts +6 -0
  190. package/dist/esm/hooks/useDevicChat.js +23 -9
  191. package/dist/esm/hooks/useDevicChat.js.map +1 -1
  192. package/dist/esm/hooks/useModelInterface.js.map +1 -1
  193. package/dist/esm/hooks/usePolling.d.ts +35 -0
  194. package/dist/esm/hooks/usePolling.js +114 -8
  195. package/dist/esm/hooks/usePolling.js.map +1 -1
  196. package/dist/esm/hooks/useSpeechRecording.js +8 -4
  197. package/dist/esm/hooks/useSpeechRecording.js.map +1 -1
  198. package/dist/esm/i18n/index.d.ts +4 -0
  199. package/dist/esm/i18n/translate.d.ts +23 -0
  200. package/dist/esm/i18n/translate.js +43 -0
  201. package/dist/esm/i18n/translate.js.map +1 -0
  202. package/dist/esm/i18n/types.d.ts +27 -0
  203. package/dist/esm/i18n/useTranslations.d.ts +32 -0
  204. package/dist/esm/i18n/useTranslations.js +53 -0
  205. package/dist/esm/i18n/useTranslations.js.map +1 -0
  206. package/dist/esm/index.d.ts +4 -2
  207. package/dist/esm/index.js +3 -0
  208. package/dist/esm/index.js.map +1 -1
  209. package/dist/esm/provider/DevicContext.js.map +1 -1
  210. package/dist/esm/provider/DevicProvider.d.ts +1 -1
  211. package/dist/esm/provider/DevicProvider.js +5 -1
  212. package/dist/esm/provider/DevicProvider.js.map +1 -1
  213. package/dist/esm/provider/sharedSession.js.map +1 -1
  214. package/dist/esm/provider/types.d.ts +51 -0
  215. package/dist/esm/styles.css +1 -1
  216. package/dist/esm/utils/avatar.js.map +1 -1
  217. package/dist/esm/utils/consumeChatStream.d.ts +6 -0
  218. package/dist/esm/utils/consumeChatStream.js +42 -0
  219. package/dist/esm/utils/consumeChatStream.js.map +1 -0
  220. package/dist/esm/utils/index.js.map +1 -1
  221. package/dist/esm/utils/logger.js.map +1 -1
  222. package/dist/esm/utils/toolGroups.js.map +1 -1
  223. package/package.json +3 -1
package/README.md CHANGED
@@ -12,6 +12,7 @@ React component library for integrating Devic AI assistants into your applicatio
12
12
  - **Model Interface Protocol** - Support for client-side tool execution
13
13
  - **Message queue** - Write while the assistant is still answering, on assistants that allow it
14
14
  - **Message Feedback** - Built-in thumbs up/down feedback with comments
15
+ - **Translations** - A `text: translation` dictionary for every text the library renders
15
16
  - **CSS Variables** - Easy theming with CSS custom properties
16
17
  - **TypeScript** - Full type definitions included
17
18
  - **React 17+** - Compatible with React 17 and above
@@ -96,6 +97,8 @@ Context provider for global configuration.
96
97
  tenantId="tenant-123" // Optional global tenant
97
98
  tenantMetadata={{ ... }} // Optional global metadata
98
99
  pollingInterval={1000} // How often a conversation in progress is polled
100
+ streaming={false} // Follow conversations over SSE instead of polling (opt-in)
101
+ translations={{ ... }} // Optional `English text -> your text` dictionary
99
102
  >
100
103
  <App />
101
104
  </DevicProvider>
@@ -134,6 +137,33 @@ Values below 250 ms are clamped — below that the widget floods the API instead
134
137
  of answering sooner. The handoff widget, which only watches a subagent run,
135
138
  keeps its own 5 s default when nothing is configured.
136
139
 
140
+ #### Streaming instead of polling
141
+
142
+ Opt in with `streaming` and a conversation in progress is followed over a
143
+ server-sent event stream instead: the assistant's reply appears as it is
144
+ produced, and the poll only runs while the stream is down. It is off by
145
+ default for now and will become the default once it has been exercised in the
146
+ field; a component can still refuse it with `streaming={false}`.
147
+
148
+ ```tsx
149
+ <DevicProvider apiKey="devic-xxx" streaming>
150
+ <ChatDrawer assistantId="support" />
151
+ <AICommandBar assistantId="support" streaming={false} />
152
+ </DevicProvider>
153
+ ```
154
+
155
+ The stream is `GET /api/v1/assistants/:id/chats/:chatUid/stream`, served by the
156
+ same API with the same credential as the poll. Against an API that does not
157
+ serve it the widgets notice and keep polling, so turning it on is safe before
158
+ the API you talk to has caught up. The handoff widget, which watches a subagent
159
+ run rather than a conversation, always polls.
160
+
161
+ #### Texts in another language
162
+
163
+ `translations` replaces the texts the library renders itself, keyed by the
164
+ English text — `{ 'New chat': 'Nueva conversación' }`. See
165
+ [Translations](#translations).
166
+
137
167
  #### Tenant sessions — proving who the end user is
138
168
 
139
169
  With an API key alone, the tenant is whatever the page says it is. The key sits
@@ -318,6 +348,7 @@ A complete chat drawer component.
318
348
  tenantMetadata={{ userId: '123' }}
319
349
  apiKey="override-key" // Override provider
320
350
  pollingInterval={1000} // Override provider (ms, min 250)
351
+ streaming={false} // Override provider (SSE instead of polling)
321
352
 
322
353
  // Callbacks
323
354
  onMessageSent={(message) => {}}
@@ -408,6 +439,48 @@ Both are also available from the hook: `useDevicChat().compactions` (the
408
439
  checkpoints, oldest first) and `useDevicChat().compaction` (the one being
409
440
  written right now, or `null`).
410
441
 
442
+ #### Turns stopped by a guardrail
443
+
444
+ An assistant with guardrails configured can have a turn stopped before it ever
445
+ reaches the model. The backend records that as a `guard_rail` message, and the
446
+ drawer draws it as a notice naming the guardrail that fired — not as a bubble,
447
+ because nobody said it.
448
+
449
+ To say it in another language, translate its texts like any other
450
+ ([Translations](#translations)):
451
+
452
+ ```ts
453
+ translations: {
454
+ 'Your message was stopped by the “{name}” guardrail.':
455
+ 'Tu mensaje ha sido bloqueado por el guardrail «{name}».',
456
+ 'This message was stopped by a guardrail.':
457
+ 'Este mensaje ha sido bloqueado por un guardrail.',
458
+ }
459
+ ```
460
+
461
+ Supply a renderer instead when the notice needs a different shape — to drop the
462
+ guardrail's name, for example, if end users should not see it:
463
+
464
+ ```tsx
465
+ <ChatDrawer
466
+ assistantId="my-assistant"
467
+ options={{
468
+ guardrailRenderer: ({ payload }) => (
469
+ <MyNotice tone="warning">
470
+ {`No puedo ayudarte con eso (${payload?.info?.guardrail_name ?? 'guardrail'}).`}
471
+ </MyNotice>
472
+ ),
473
+ }}
474
+ />
475
+ ```
476
+
477
+ `payload` is the provider result the backend recorded — `info.guardrail_name`,
478
+ `info.confidence`, `info.threshold` and `info.stage_name` (`"input"` when the
479
+ person's message was stopped, otherwise the answer was). `text` carries the
480
+ message instead when the backend sent a plain sentence. Return `null` to hide
481
+ the notice entirely, though a conversation that simply stops with no answer and
482
+ no explanation reads as a bug to the person in it.
483
+
411
484
  ### CoreMemoryModal
412
485
 
413
486
  Modal showing — and letting the end user edit — the **core memory** of an
@@ -905,6 +978,7 @@ const {
905
978
  enabledTools: ['tool1', 'tool2'],
906
979
  modelInterfaceTools: [...],
907
980
  pollingInterval: 1000, // Overrides the provider's (ms, min 250)
981
+ streaming: false, // Overrides the provider's (SSE instead of polling)
908
982
  messageQueue: undefined, // Follows the assistant's setting; true/false pins it
909
983
  onMessageSent: (message) => {},
910
984
  onMessageReceived: (message) => {},
@@ -1135,6 +1209,118 @@ Or use the `color` option in ChatDrawer:
1135
1209
  />
1136
1210
  ```
1137
1211
 
1212
+ ## Translations
1213
+
1214
+ Every text the library renders itself — the drawer header, the composer, the
1215
+ buttons, tooltips and dialogs — goes through a dictionary you can replace.
1216
+ It is a plain `English text → your text` map:
1217
+
1218
+ ```tsx
1219
+ <DevicProvider
1220
+ apiKey="devic-xxx"
1221
+ translations={{
1222
+ 'New chat': 'Nueva conversación',
1223
+ 'Type a message...': 'Escribe un mensaje...',
1224
+ 'Close chat': 'Cerrar el chat',
1225
+ 'Send message': 'Enviar mensaje',
1226
+ }}
1227
+ >
1228
+ <ChatDrawer assistantId="my-assistant" />
1229
+ </DevicProvider>
1230
+ ```
1231
+
1232
+ That is the whole mechanism. There is no i18n runtime bundled here and no key
1233
+ catalogue to learn: the key is what you see on screen, and the values come
1234
+ from whatever you already use — i18next, react-intl, a JSON file per locale.
1235
+ Hand it the strings for the current language and re-render when it changes:
1236
+
1237
+ ```tsx
1238
+ const { t, i18n } = useTranslation('devic');
1239
+
1240
+ <DevicProvider
1241
+ apiKey="devic-xxx"
1242
+ // Re-created when the language changes, which is what re-renders the widget.
1243
+ translations={useMemo(
1244
+ () => ({
1245
+ 'New chat': t('newChat'),
1246
+ 'Type a message...': t('inputPlaceholder'),
1247
+ }),
1248
+ [i18n.language]
1249
+ )}
1250
+ >
1251
+ ```
1252
+
1253
+ **Anything you leave out stays in English**, so a partial dictionary is fine —
1254
+ translate the drawer today and the apps dialog when you get to it.
1255
+
1256
+ ### Placeholders
1257
+
1258
+ Texts that carry a value use `{name}` placeholders. Keep them in the
1259
+ translation; they are filled after the lookup, so they may be reordered:
1260
+
1261
+ ```tsx
1262
+ translations={{
1263
+ '{count} messages': '{count} mensajes',
1264
+ 'Resets in {count} minutes.': 'Quedan {count} minutos para el reinicio.',
1265
+ '{label} — {count} switched off': '{count} desactivadas de {label}',
1266
+ }}
1267
+ ```
1268
+
1269
+ Counted texts come in a singular and a plural entry (`1 message` and
1270
+ `{count} messages`), so a language that inflects differently has somewhere to
1271
+ say so.
1272
+
1273
+ ### Per component
1274
+
1275
+ Each component takes its own `translations`, merged on top of the provider's.
1276
+ Use it when one widget must read differently from the rest of the page:
1277
+
1278
+ ```tsx
1279
+ <ChatDrawer
1280
+ assistantId="support"
1281
+ options={{ translations: { 'New chat': 'Nueva consulta' } }}
1282
+ />
1283
+ ```
1284
+
1285
+ Available on `ChatDrawer`, `AICommandBar`, `AIGenerationButton` and
1286
+ `AIElementWrapper`, and it reaches everything they mount — the message list,
1287
+ the composer and the dialogs they open. For anything else, wrap a subtree:
1288
+
1289
+ ```tsx
1290
+ import { DevicTranslationsProvider } from '@devicai/ui';
1291
+
1292
+ <DevicTranslationsProvider translations={{ Close: 'Cerrar' }}>
1293
+ <IntegrationsPanel assistantId="my-assistant" />
1294
+ </DevicTranslationsProvider>
1295
+ ```
1296
+
1297
+ Later layers win: provider → enclosing component → the component's own option.
1298
+
1299
+ ### What takes precedence
1300
+
1301
+ Texts that already have an option of their own (`welcomeMessage`,
1302
+ `inputPlaceholder`, `title`, `integrationsLabel`, `coreMemoryLabels`, …) keep
1303
+ winning over the dictionary — the dictionary only supplies their defaults. So
1304
+ a host that has always set `inputPlaceholder` sees no change, and one that
1305
+ never did gets it translated.
1306
+
1307
+ ### The full list
1308
+
1309
+ [TRANSLATIONS.md](./TRANSLATIONS.md) lists every text, grouped by where it
1310
+ appears. Two things to watch: copy the key exactly (same case, same `…` and
1311
+ `·`), and note that `AIElementWrapper` has shipped Spanish defaults since it
1312
+ was added, so its keys are Spanish.
1313
+
1314
+ ### Reading the dictionary yourself
1315
+
1316
+ `useTranslations` returns the same translator the components use, for a custom
1317
+ UI built on `useDevicChat`:
1318
+
1319
+ ```tsx
1320
+ const t = useTranslations();
1321
+ <button>{t('Send message')}</button>
1322
+ ```
1323
+
1138
1324
  ## Message Queue
1139
1325
 
1140
1326
  Assistants can be configured to accept messages sent while they are still
@@ -1 +1 @@
1
- {"version":3,"file":"assistantInfo.js","sources":["../../../../src/api/assistantInfo.ts"],"sourcesContent":["import { useEffect, useState } from 'react';\nimport { DevicApiClient } from './client';\nimport type { AssistantSpecialization } from './types';\n\n/**\n * One in-flight request per assistant, shared by everything that asks.\n *\n * An assistant's description does not depend on who is looking or on anything\n * that changes while a page is open, so asking twice can only ever produce the\n * same answer. It was being asked more than twice: the header wants the avatar,\n * the connected-apps control wants to know whether it should exist, and a host\n * that remounts the drawer to reset a conversation — which the console does —\n * made every one of them ask again.\n *\n * Cached as the promise rather than the result, so callers that arrive while\n * the first request is still open wait for it instead of starting a second.\n */\nconst inFlight = new Map<string, Promise<AssistantSpecialization | null>>();\n\n/**\n * Same assistant, same deployment, same credential — anything else is a\n * different answer. The credential is part of it because an API key carries\n * the account: two keys can each have an assistant under the same identifier.\n */\nfunction cacheKey(\n baseUrl: string,\n assistantId: string,\n credential: string\n): string {\n return `${baseUrl}|${credential}|${assistantId}`;\n}\n\n/** Forget what is known about an assistant, so the next ask reaches the API. */\nexport function forgetAssistant(\n baseUrl: string,\n assistantId: string,\n credential = 'session'\n): void {\n inFlight.delete(cacheKey(baseUrl, assistantId, credential));\n}\n\nexport interface UseAssistantInfoOptions {\n assistantId: string;\n client: DevicApiClient | null;\n baseUrl: string;\n /** Distinguishes accounts in the cache key. */\n credential?: string;\n /** Ask only when this is true. */\n enabled?: boolean;\n}\n\nexport interface AssistantInfoState {\n assistant: AssistantSpecialization | null;\n /**\n * True once an answer — or a failure — has arrived. Callers that gate on the\n * assistant must wait for this rather than for `assistant`, or they would\n * read a null that only means \"not yet\".\n */\n settled: boolean;\n}\n\n/**\n * What the API says about an assistant, fetched at most once per assistant.\n *\n * A failure resolves to `null` and `settled: true`: not knowing is an ordinary\n * outcome here, and every caller is expected to have something reasonable to do\n * without the answer.\n */\nexport function useAssistantInfo(\n options: UseAssistantInfoOptions\n): AssistantInfoState {\n const {\n assistantId,\n client,\n baseUrl,\n credential = 'session',\n enabled = true,\n } = options;\n\n const [state, setState] = useState<AssistantInfoState>({\n assistant: null,\n settled: false,\n });\n\n useEffect(() => {\n if (!enabled || !client || !assistantId) return;\n\n const key = cacheKey(baseUrl, assistantId, credential);\n let cancelled = false;\n\n let request = inFlight.get(key);\n if (!request) {\n request = client.getAssistant(assistantId).catch(() => null);\n inFlight.set(key, request);\n }\n\n setState((prev) => (prev.settled ? { ...prev, settled: false } : prev));\n void request.then((assistant) => {\n if (!cancelled) setState({ assistant, settled: true });\n });\n\n return () => {\n cancelled = true;\n };\n }, [enabled, client, assistantId, baseUrl, credential]);\n\n return state;\n}\n"],"names":["useState","useEffect"],"mappings":";;;;AAIA;;;;;;;;;;;;AAYG;AACH,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAmD;AAE3E;;;;AAIG;AACH,SAAS,QAAQ,CACf,OAAe,EACf,WAAmB,EACnB,UAAkB,EAAA;AAElB,IAAA,OAAO,GAAG,OAAO,CAAA,CAAA,EAAI,UAAU,CAAA,CAAA,EAAI,WAAW,EAAE;AAClD;AAEA;AACM,SAAU,eAAe,CAC7B,OAAe,EACf,WAAmB,EACnB,UAAU,GAAG,SAAS,EAAA;AAEtB,IAAA,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,WAAW,EAAE,UAAU,CAAC,CAAC;AAC7D;AAsBA;;;;;;AAMG;AACG,SAAU,gBAAgB,CAC9B,OAAgC,EAAA;AAEhC,IAAA,MAAM,EACJ,WAAW,EACX,MAAM,EACN,OAAO,EACP,UAAU,GAAG,SAAS,EACtB,OAAO,GAAG,IAAI,GACf,GAAG,OAAO;AAEX,IAAA,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC,GAAGA,cAAQ,CAAqB;AACrD,QAAA,SAAS,EAAE,IAAI;AACf,QAAA,OAAO,EAAE,KAAK;AACf,KAAA,CAAC;IAEFC,eAAS,CAAC,MAAK;AACb,QAAA,IAAI,CAAC,OAAO,IAAI,CAAC,MAAM,IAAI,CAAC,WAAW;YAAE;QAEzC,MAAM,GAAG,GAAG,QAAQ,CAAC,OAAO,EAAE,WAAW,EAAE,UAAU,CAAC;QACtD,IAAI,SAAS,GAAG,KAAK;QAErB,IAAI,OAAO,GAAG,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC;QAC/B,IAAI,CAAC,OAAO,EAAE;AACZ,YAAA,OAAO,GAAG,MAAM,CAAC,YAAY,CAAC,WAAW,CAAC,CAAC,KAAK,CAAC,MAAM,IAAI,CAAC;AAC5D,YAAA,QAAQ,CAAC,GAAG,CAAC,GAAG,EAAE,OAAO,CAAC;QAC5B;QAEA,QAAQ,CAAC,CAAC,IAAI,MAAM,IAAI,CAAC,OAAO,GAAG,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC,CAAC;AACvE,QAAA,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC,SAAS,KAAI;AAC9B,YAAA,IAAI,CAAC,SAAS;gBAAE,QAAQ,CAAC,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;AACxD,QAAA,CAAC,CAAC;AAEF,QAAA,OAAO,MAAK;YACV,SAAS,GAAG,IAAI;AAClB,QAAA,CAAC;AACH,IAAA,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,UAAU,CAAC,CAAC;AAEvD,IAAA,OAAO,KAAK;AACd;;;"}
1
+ {"version":3,"file":"assistantInfo.js","sources":["../../../../src/api/assistantInfo.ts"],"sourcesContent":["import { useEffect, useState } from 'react';\nimport { DevicApiClient } from './client';\nimport type { AssistantSpecialization } from './types';\n\n/**\n * One in-flight request per assistant, shared by everything that asks.\n *\n * An assistant's description does not depend on who is looking or on anything\n * that changes while a page is open, so asking twice can only ever produce the\n * same answer. It was being asked more than twice: the header wants the avatar,\n * the connected-apps control wants to know whether it should exist, and a host\n * that remounts the drawer to reset a conversation — which the console does —\n * made every one of them ask again.\n *\n * Cached as the promise rather than the result, so callers that arrive while\n * the first request is still open wait for it instead of starting a second.\n */\nconst inFlight = new Map<string, Promise<AssistantSpecialization | null>>();\n\n/**\n * Same assistant, same deployment, same credential — anything else is a\n * different answer. The credential is part of it because an API key carries\n * the account: two keys can each have an assistant under the same identifier.\n */\nfunction cacheKey(\n baseUrl: string,\n assistantId: string,\n credential: string\n): string {\n return `${baseUrl}|${credential}|${assistantId}`;\n}\n\n/** Forget what is known about an assistant, so the next ask reaches the API. */\nexport function forgetAssistant(\n baseUrl: string,\n assistantId: string,\n credential = 'session'\n): void {\n inFlight.delete(cacheKey(baseUrl, assistantId, credential));\n}\n\nexport interface UseAssistantInfoOptions {\n assistantId: string;\n client: DevicApiClient | null;\n baseUrl: string;\n /** Distinguishes accounts in the cache key. */\n credential?: string;\n /** Ask only when this is true. */\n enabled?: boolean;\n}\n\nexport interface AssistantInfoState {\n assistant: AssistantSpecialization | null;\n /**\n * True once an answer — or a failure — has arrived. Callers that gate on the\n * assistant must wait for this rather than for `assistant`, or they would\n * read a null that only means \"not yet\".\n */\n settled: boolean;\n}\n\n/**\n * What the API says about an assistant, fetched at most once per assistant.\n *\n * A failure resolves to `null` and `settled: true`: not knowing is an ordinary\n * outcome here, and every caller is expected to have something reasonable to do\n * without the answer.\n */\nexport function useAssistantInfo(\n options: UseAssistantInfoOptions\n): AssistantInfoState {\n const {\n assistantId,\n client,\n baseUrl,\n credential = 'session',\n enabled = true,\n } = options;\n\n const [state, setState] = useState<AssistantInfoState>({\n assistant: null,\n settled: false,\n });\n\n useEffect(() => {\n if (!enabled || !client || !assistantId) return;\n\n const key = cacheKey(baseUrl, assistantId, credential);\n let cancelled = false;\n\n let request = inFlight.get(key);\n if (!request) {\n request = client.getAssistant(assistantId).catch(() => null);\n inFlight.set(key, request);\n }\n\n setState((prev) => (prev.settled ? { ...prev, settled: false } : prev));\n void request.then((assistant) => {\n if (!cancelled) setState({ assistant, settled: true });\n });\n\n return () => {\n cancelled = true;\n };\n }, [enabled, client, assistantId, baseUrl, credential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AC;QAC5B;QAEA,QAAQ,CAAC,CAAC,IAAI,MAAM,IAAI,CAAC,OAAO,GAAG,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC,CAAC;AACvE,QAAA,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC,SAAS,KAAI;AAC9B,YAAA,IAAI,CAAC,SAAS;gBAAE,QAAQ,CAAC,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;AACxD,QAAA,CAAC,CAAC;AAEF,QAAA,OAAO,MAAK;YACV,SAAS,GAAG,IAAI;AAClB,QAAA,CAAC;AACH,IAAA,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,UAAU,CAAC,CAAC;AAEvD,IAAA,OAAO,KAAK;AACd;;;;;"}
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ var consumeChatStream = require('../utils/consumeChatStream.js');
4
+
3
5
  /** Renew this long before expiry, so a request never leaves with a dead token. */
4
6
  const RENEWAL_MARGIN_MS = 60000;
5
7
  /**
@@ -204,8 +206,22 @@ class DevicApiClient {
204
206
  return this.request(`/api/v1/assistants/tags`);
205
207
  }
206
208
  /**
207
- * Get real-time chat history (for polling in async mode)
209
+ * Follow a conversation in progress over its server-sent event stream.
210
+ * Resolves when the server closes the stream; rejects when it is not a
211
+ * stream at all (an older API) or the connection fails. `onActivity` fires
212
+ * on every chunk received, keep-alives included.
208
213
  */
214
+ async streamRealtimeHistory(assistantId, chatUid, onSnapshot, signal, onActivity) {
215
+ const url = `${this.config.baseUrl}/api/v1/assistants/${encodeURIComponent(assistantId)}/chats/${encodeURIComponent(chatUid)}/stream`;
216
+ let credential = await this.authorization();
217
+ const open = () => fetch(url, { signal, headers: { Authorization: `Bearer ${credential}`, Accept: 'text/event-stream', 'devic-api-source': 'ui' } });
218
+ let response = await open();
219
+ if (response.status === 401 && this.config.getTenantSession && await this.recoverSession(credential)) {
220
+ credential = await this.authorization();
221
+ response = await open();
222
+ }
223
+ await consumeChatStream.consumeChatStream(response, onSnapshot, onActivity);
224
+ }
209
225
  async getRealtimeHistory(assistantId, chatUid) {
210
226
  return this.request(`/api/v1/assistants/${assistantId}/chats/${chatUid}/realtime`);
211
227
  }
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sources":["../../../../src/api/client.ts"],"sourcesContent":["import type {\n ProcessMessageDto,\n ChatMessage,\n AsyncResponse,\n RealtimeChatHistory,\n ChatHistory,\n AssistantSpecialization,\n ApiError,\n ToolCallResponse,\n ConversationSummary,\n ListConversationsResponse,\n FeedbackSubmission,\n FeedbackEntry,\n AgentThreadDto,\n AgentDto,\n WhisperTranscriptionResponse,\n TenantUsage,\n TenantUsageHistoryRow,\n TenantUsageHistoryQuery,\n CoreMemoryList,\n CoreMemoryEntry,\n Integration,\n TenantMcpAuthInput,\n TenantMcpConnectResult,\n TenantMcpListing,\n IntegrationAuthScheme,\n IntegrationSetupRequired,\n ModelInterfaceToolSchema,\n StopChatResponse,\n} from \"./types\";\n\n/**\n * A tenant session, as the integrator's backend hands it over.\n *\n * A bare string is accepted too — the expiry is then read out of the token\n * itself, so the simplest possible source still gets proactive renewal.\n */\nexport interface TenantSessionToken {\n token: string;\n /** Epoch milliseconds. */\n expiresAt?: number;\n /** Seconds from now. Used when `expiresAt` is absent. */\n expiresIn?: number;\n}\n\nexport interface DevicApiClientConfig {\n /**\n * The public API key. Optional when `getTenantSession` is supplied — a page\n * using tenant sessions has no reason to carry one.\n */\n apiKey?: string;\n baseUrl: string;\n /**\n * Where the tenant session comes from.\n *\n * Supplying this changes what the tenant IS: with an API key alone the tenant\n * is whatever the page says it is, and the page can say anything. With a\n * session it is what your server signed.\n *\n * A function rather than a value because it is called again on its own —\n * before the token expires and after the API rejects one. It does not have to\n * reach your backend: reading a cookie your login already set is a perfectly\n * good answer, and then the whole thing is `async () => readCookie(…)`.\n *\n * It is called with `force: true` when the API has just rejected the token in\n * hand, meaning a cached answer is known to be dead. Your own function can\n * ignore the argument — `DevicProvider` uses it to share one session across\n * every component without ever serving a refused token back.\n */\n getTenantSession?: (force?: boolean) => Promise<string | TenantSessionToken>;\n /**\n * Called when the session is dead and cannot be replaced — the API rejected\n * it and `getTenantSession` handed back the same expired token.\n *\n * Matters most when the session comes from a cookie with no way to renew it:\n * without this the widget simply stops answering, at the exact moment the\n * user's own login has also expired. Refresh the page, send them to log in,\n * or say something — but say it.\n */\n onSessionExpired?: () => void;\n}\n\n/** Renew this long before expiry, so a request never leaves with a dead token. */\nconst RENEWAL_MARGIN_MS = 60_000;\n\n/**\n * The expiry inside a JWT, in epoch milliseconds.\n *\n * Read rather than required, so the session source can return just the string.\n * Any failure means \"no idea\", and the token is then renewed only when the API\n * rejects it — correct, just less graceful.\n */\nfunction expiryOf(token: string): number | undefined {\n try {\n const payload = token.split(\".\")[1];\n if (!payload) return undefined;\n const json = atob(payload.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n const exp = JSON.parse(json)?.exp;\n return typeof exp === \"number\" ? exp * 1000 : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Devic API client using native fetch\n */\nexport class DevicApiClient {\n private config: DevicApiClientConfig;\n private session?: { token: string; expiresAt?: number };\n /** In flight renewal, shared so a burst of calls fetches one token. */\n private renewing?: Promise<string>;\n /** So a page full of widgets reports one expiry, not one per widget. */\n private expiryReported = false;\n\n constructor(config: DevicApiClientConfig) {\n this.config = config;\n }\n\n /**\n * Update client configuration\n */\n setConfig(config: Partial<DevicApiClientConfig>): void {\n const previous = this.config;\n this.config = { ...this.config, ...config };\n // A new session source speaks for a different end user; keeping the old\n // token would show them the previous one's conversations.\n if (\n config.getTenantSession &&\n config.getTenantSession !== previous.getTenantSession\n ) {\n this.session = undefined;\n this.expiryReported = false;\n }\n }\n\n /** The credential for the next request, renewed if it is about to expire. */\n private async authorization(force = false): Promise<string> {\n if (!this.config.getTenantSession) return this.config.apiKey ?? \"\";\n\n const current = this.session;\n const stillGood =\n current &&\n (current.expiresAt === undefined ||\n current.expiresAt - Date.now() > RENEWAL_MARGIN_MS);\n if (stillGood && !force) return current.token;\n\n return this.renew(force);\n }\n\n private renew(force = false): Promise<string> {\n if (!this.renewing) {\n this.renewing = Promise.resolve(this.config.getTenantSession!(force))\n .then((result) => {\n const token = typeof result === \"string\" ? result : result.token;\n const declared =\n typeof result === \"string\"\n ? undefined\n : (result.expiresAt ??\n (result.expiresIn\n ? Date.now() + result.expiresIn * 1000\n : undefined));\n this.session = { token, expiresAt: declared ?? expiryOf(token) };\n return token;\n })\n .finally(() => {\n this.renewing = undefined;\n });\n }\n return this.renewing;\n }\n\n /**\n * Whether a rejected request is worth retrying, having got a live session.\n *\n * Takes the token the request actually went out with, not the current one:\n * with several requests in flight another may already have replaced it, and\n * comparing against the current one would read that success as a failure.\n *\n * False means the session is dead and cannot be replaced — a cookie set at\n * login, now expired, with nowhere to renew it from. That is worth telling\n * the host application about, once.\n */\n private async recoverSession(rejected: string): Promise<boolean> {\n if (this.session && this.session.token !== rejected) {\n this.expiryReported = false;\n return true;\n }\n\n let fresh: string | undefined;\n try {\n // Forced: whatever is cached upstream is the token that was just\n // refused, so asking for it again would only confirm the refusal.\n fresh = await this.renew(true);\n } catch {\n fresh = undefined;\n }\n if (fresh && fresh !== rejected) {\n this.expiryReported = false;\n return true;\n }\n\n if (!this.expiryReported) {\n this.expiryReported = true;\n this.config.onSessionExpired?.();\n }\n return false;\n }\n\n /**\n * Make an authenticated request to the API\n */\n private async request<T>(\n endpoint: string,\n options: RequestInit = {},\n isRetry = false,\n ): Promise<T> {\n const url = `${this.config.baseUrl}${endpoint}`;\n const credential = await this.authorization();\n\n const headers: HeadersInit = {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${credential}`,\n \"devic-api-source\": \"ui\",\n ...options.headers,\n };\n\n const response = await fetch(url, {\n ...options,\n headers,\n });\n\n // A session can die between being checked and being used — a clock adrift,\n // a tab asleep for an hour, the key revoked. One retry with a fresh token\n // turns that into a pause instead of a broken conversation.\n if (response.status === 401 && this.config.getTenantSession && !isRetry) {\n if (await this.recoverSession(credential)) {\n return this.request<T>(endpoint, options, true);\n }\n }\n\n if (!response.ok) {\n let errorData: ApiError;\n try {\n errorData = await response.json();\n } catch {\n errorData = {\n statusCode: response.status,\n message: response.statusText,\n };\n }\n // Not every refusal carries its own status in the body. A 409 raised with\n // an object (`{ error: 'CHAT_BUSY', ... }`) is returned verbatim, so\n // reading the code off the body alone leaves it undefined and every\n // `statusCode === 409` branch silently misses it.\n if (typeof errorData?.statusCode !== \"number\") {\n errorData = { ...errorData, statusCode: response.status };\n }\n throw new DevicApiError(errorData);\n }\n\n // Handle responses that may have a wrapper structure\n const data = await response.json();\n\n // If the response has a data property, extract it (common wrapper pattern)\n if (data && typeof data === \"object\" && \"data\" in data) {\n return data.data as T;\n }\n\n return data as T;\n }\n\n /**\n * Get all assistant specializations\n */\n async getAssistants(external = false): Promise<AssistantSpecialization[]> {\n const query = external ? \"?external=true\" : \"\";\n return this.request<AssistantSpecialization[]>(\n `/api/v1/assistants${query}`,\n );\n }\n\n /**\n * Get a specific assistant specialization\n */\n async getAssistant(identifier: string): Promise<AssistantSpecialization> {\n return this.request<AssistantSpecialization>(\n `/api/v1/assistants/${identifier}`,\n );\n }\n\n /**\n * Send a message to an assistant (sync mode)\n */\n async sendMessage(\n assistantId: string,\n dto: ProcessMessageDto,\n signal?: AbortSignal,\n ): Promise<ChatMessage[]> {\n return this.request<ChatMessage[]>(\n `/api/v1/assistants/${assistantId}/messages${dto.skipSummarization ? \"?skipSummarization=true\" : \"\"}`,\n {\n method: \"POST\",\n body: JSON.stringify(dto),\n signal,\n },\n );\n }\n\n /**\n * Send a message to an assistant (async mode)\n */\n async sendMessageAsync(\n assistantId: string,\n dto: ProcessMessageDto,\n ): Promise<AsyncResponse> {\n return this.request<AsyncResponse>(\n `/api/v1/assistants/${assistantId}/messages?async=true${dto.skipSummarization ? \"&skipSummarization=true\" : \"\"}`,\n {\n method: \"POST\",\n body: JSON.stringify(dto),\n },\n );\n }\n\n /**\n * Get the list of unique tags used across this account's chat histories.\n * Backed by GET /api/v1/assistants/tags. Useful for autocompletion / filters.\n */\n async getChatTags(): Promise<string[]> {\n return this.request<string[]>(`/api/v1/assistants/tags`);\n }\n\n /**\n * Get real-time chat history (for polling in async mode)\n */\n async getRealtimeHistory(\n assistantId: string,\n chatUid: string,\n ): Promise<RealtimeChatHistory> {\n return this.request<RealtimeChatHistory>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}/realtime`,\n );\n }\n\n /**\n * Get chat history for a specific conversation\n */\n async getChatHistory(\n assistantId: string,\n chatUid: string,\n options?: { tenantId?: string },\n ): Promise<ChatHistory> {\n const params = new URLSearchParams();\n if (options?.tenantId) {\n params.set(\"tenantId\", options.tenantId);\n }\n const query = params.toString();\n return this.request<ChatHistory>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}${query ? `?${query}` : \"\"}`,\n );\n }\n\n /**\n * List conversations for an assistant\n */\n async listConversations(\n assistantId: string,\n options?: {\n tenantId?: string;\n subtenantId?: string;\n offset?: number;\n limit?: number;\n },\n ): Promise<ListConversationsResponse> {\n const params = new URLSearchParams();\n if (options?.tenantId) {\n params.set(\"tenantId\", options.tenantId);\n }\n if (options?.subtenantId) {\n params.set(\"subtenantId\", options.subtenantId);\n }\n if (options?.offset != null) {\n params.set(\"offset\", String(options.offset));\n }\n if (options?.limit != null) {\n params.set(\"limit\", String(options.limit));\n }\n params.set(\"omitContent\", \"true\");\n const query = params.toString();\n return this.request<ListConversationsResponse>(\n `/api/v1/assistants/${assistantId}/chats${query ? `?${query}` : \"\"}`,\n );\n }\n\n /**\n * Send tool call responses back to the assistant.\n *\n * `toolSchemas` re-states the client-side tools for the continuation. The\n * API takes them from the first response of the batch, and without them the\n * turn resumes with no client tools at all — the model stops being able to\n * call them after the first round.\n */\n async sendToolResponses(\n assistantId: string,\n chatUid: string,\n responses: ToolCallResponse[],\n toolSchemas?: ModelInterfaceToolSchema[],\n ): Promise<AsyncResponse> {\n const body =\n toolSchemas?.length && responses.length > 0\n ? responses.map((response, index) =>\n index === 0 ? { ...response, tools: toolSchemas } : response,\n )\n : responses;\n\n return this.request<AsyncResponse>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}/tool-response`,\n {\n method: \"POST\",\n body: JSON.stringify({ responses: body }),\n },\n );\n }\n\n /**\n * Submit feedback for a chat message\n */\n async submitChatFeedback(\n assistantId: string,\n chatUid: string,\n data: FeedbackSubmission,\n ): Promise<FeedbackEntry> {\n return this.request<FeedbackEntry>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}/feedback`,\n {\n method: \"POST\",\n body: JSON.stringify(data),\n },\n );\n }\n\n /**\n * Get all feedback for a chat\n */\n async getChatFeedback(\n assistantId: string,\n chatUid: string,\n ): Promise<FeedbackEntry[]> {\n return this.request<FeedbackEntry[]>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}/feedback`,\n );\n }\n\n /**\n * Get an agent thread by ID\n */\n async getThreadById(\n threadId: string,\n withTasks = false,\n ): Promise<AgentThreadDto> {\n const query = withTasks ? \"?withTasks=true\" : \"\";\n return this.request<AgentThreadDto>(\n `/api/v1/agents/threads/${threadId}${query}`,\n );\n }\n\n /**\n * Get agent details\n */\n async getAgentDetails(agentId: string): Promise<AgentDto> {\n return this.request<AgentDto>(`/api/v1/agents/${agentId}`);\n }\n\n /**\n * Get an AI-generated explanation of a thread's execution\n */\n async explainAgentThread(threadId: string): Promise<string> {\n return this.request<string>(\n `/api/v1/agents/threads/${threadId}/explain`,\n );\n }\n\n /**\n * Pause or resume a thread\n */\n async pauseResumeThread(\n threadId: string,\n action: \"paused\" | \"queued\",\n ): Promise<void> {\n return this.request<void>(\n `/api/v1/agents/threads/${threadId}/pause-resume`,\n {\n method: \"POST\",\n body: JSON.stringify({ action }),\n },\n );\n }\n\n /**\n * Handle thread approval (approve/reject)\n */\n async handleThreadApproval(\n threadId: string,\n approved: boolean,\n retry: boolean,\n message: string,\n ): Promise<void> {\n return this.request<void>(\n `/api/v1/agents/threads/${threadId}/approval`,\n {\n method: \"POST\",\n body: JSON.stringify({\n action: approved ? \"approved\" : \"rejected\",\n message,\n retry,\n }),\n },\n );\n }\n\n /**\n * Manually complete a thread\n */\n async completeThread(\n threadId: string,\n completionState: string,\n ): Promise<void> {\n return this.request<void>(\n `/api/v1/agents/threads/${threadId}/complete`,\n {\n method: \"POST\",\n body: JSON.stringify({ state: completionState }),\n },\n );\n }\n\n /**\n * Continue an existing thread with a new user message. The backend decides how\n * to apply it based on the thread state: a finished/failed/waiting thread is\n * re-queued and re-run with the message appended, while a running/queued thread\n * receives it on its next turn (right after the pending tool response). Returns\n * the updated thread.\n */\n async sendThreadMessage(\n threadId: string,\n message: string | Record<string, unknown>,\n ): Promise<AgentThreadDto> {\n return this.request<AgentThreadDto>(\n `/api/v1/agents/threads/${threadId}/messages`,\n {\n method: \"POST\",\n body: JSON.stringify({ message }),\n },\n );\n }\n\n /**\n * Stop an in-progress async chat.\n * The current LLM call or tool execution will finish, then the chat\n * will be marked as completed with the history accumulated so far.\n */\n async stopChat(\n assistantId: string,\n chatUid: string,\n ): Promise<StopChatResponse> {\n return this.request<StopChatResponse>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}/stop`,\n { method: \"POST\" },\n );\n }\n\n /**\n * Upload a file and get a download URL\n */\n async uploadFile(\n file: File,\n isRetry = false,\n ): Promise<{ name: string; downloadUrl: string; fileType: string }> {\n const url = `${this.config.baseUrl}/api/v1/files/upload`;\n\n const formData = new FormData();\n formData.append(\"file\", file);\n\n const credential = await this.authorization();\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${credential}`,\n \"devic-api-source\": \"ui\",\n },\n body: formData,\n });\n\n // The FormData is rebuilt from `file` on the way back in, so unlike a\n // consumed stream this retry is safe.\n if (response.status === 401 && this.config.getTenantSession && !isRetry) {\n if (await this.recoverSession(credential)) return this.uploadFile(file, true);\n }\n\n if (!response.ok) {\n let errorData: { statusCode: number; message: string };\n try {\n errorData = await response.json();\n } catch {\n errorData = {\n statusCode: response.status,\n message: response.statusText,\n };\n }\n // See `request`: a body-shaped refusal need not carry its own status.\n if (typeof errorData?.statusCode !== \"number\") {\n errorData = { ...errorData, statusCode: response.status };\n }\n throw new DevicApiError(errorData);\n }\n\n const data = await response.json();\n if (data && typeof data === \"object\" && \"data\" in data) {\n return data.data;\n }\n return data;\n }\n\n /**\n * Transcribe audio to text using the /whisper endpoint.\n * Accepts either an audio binary (Blob/File, sent as multipart/form-data) or\n * a download URL string (sent as `audioUrl`). The backend stores the binary\n * and runs speech-to-text with Devic's own OpenAI key. Returns the text and a\n * `transcriptId` to attach to the resulting message.\n */\n async transcribeAudio(\n audio: Blob | string,\n options?: {\n language?: string;\n messageUid?: string;\n chatUid?: string;\n tenantId?: string;\n fileName?: string;\n },\n isRetry = false,\n ): Promise<WhisperTranscriptionResponse> {\n const url = `${this.config.baseUrl}/api/v1/whisper`;\n\n const formData = new FormData();\n if (typeof audio === \"string\") {\n formData.append(\"audioUrl\", audio);\n } else {\n formData.append(\"audio\", audio, options?.fileName || \"recording.webm\");\n }\n if (options?.language) formData.append(\"language\", options.language);\n if (options?.messageUid) formData.append(\"messageUid\", options.messageUid);\n if (options?.chatUid) formData.append(\"chatUid\", options.chatUid);\n if (options?.tenantId) formData.append(\"tenantId\", options.tenantId);\n\n const credential = await this.authorization();\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${credential}`,\n \"devic-api-source\": \"ui\",\n },\n body: formData,\n });\n\n if (response.status === 401 && this.config.getTenantSession && !isRetry) {\n if (await this.recoverSession(credential)) {\n return this.transcribeAudio(audio, options, true);\n }\n }\n\n if (!response.ok) {\n let errorData: { statusCode: number; message: string };\n try {\n errorData = await response.json();\n } catch {\n errorData = {\n statusCode: response.status,\n message: response.statusText,\n };\n }\n // See `request`: a body-shaped refusal need not carry its own status.\n if (typeof errorData?.statusCode !== \"number\") {\n errorData = { ...errorData, statusCode: response.status };\n }\n throw new DevicApiError(errorData);\n }\n\n const data = await response.json();\n if (data && typeof data === \"object\" && \"data\" in data) {\n return data.data;\n }\n return data;\n }\n\n /**\n * Fetch a single speech-to-text transcript by its id (the `transcriptId`\n * stored on a message). Returns the transcribed text and the download URL of\n * the source audio so the chat can offer playback of a dictated message.\n */\n async getTranscript(\n transcriptId: string,\n ): Promise<WhisperTranscriptionResponse> {\n return this.request<WhisperTranscriptionResponse>(\n `/api/v1/whisper/${encodeURIComponent(transcriptId)}`,\n );\n }\n\n /**\n * Get chat history content (full conversation after handoff)\n */\n async getChatHistoryContent(\n assistantId: string,\n chatUid: string,\n ): Promise<ChatMessage[]> {\n return this.request<ChatMessage[]>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}/content`,\n );\n }\n\n /**\n * Get the current usage limits + consumption for a tenant (or a specific\n * subtenant). Read-only — backed by `GET /api/v1/tenant-usage/:tenantId`\n * (or `/:tenantId/subtenants/:subtenantId`), which is part of the devic-ui\n * key preset. Returns the effective rules with their live consumption and the\n * active tier. Use it to render a usage bar.\n */\n async getTenantUsage(\n tenantId: string,\n subtenantId?: string,\n ): Promise<TenantUsage> {\n const path = subtenantId\n ? `/api/v1/tenant-usage/${encodeURIComponent(tenantId)}/subtenants/${encodeURIComponent(subtenantId)}`\n : `/api/v1/tenant-usage/${encodeURIComponent(tenantId)}`;\n return this.request<TenantUsage>(path);\n }\n\n /**\n * Get the durable per-window usage history for a tenant (or subtenant).\n * Read-only — backed by `GET /api/v1/tenant-usage/:tenantId/history`.\n */\n async getTenantUsageHistory(\n tenantId: string,\n options?: TenantUsageHistoryQuery,\n ): Promise<TenantUsageHistoryRow[]> {\n const params = new URLSearchParams();\n if (options?.subtenantId) params.set(\"subtenantId\", options.subtenantId);\n if (options?.scope) params.set(\"scope\", options.scope);\n if (options?.metric) params.set(\"metric\", options.metric);\n if (options?.windowUnit) params.set(\"windowUnit\", options.windowUnit);\n if (options?.from != null) params.set(\"from\", String(options.from));\n if (options?.to != null) params.set(\"to\", String(options.to));\n if (options?.limit != null) params.set(\"limit\", String(options.limit));\n if (options?.skip != null) params.set(\"skip\", String(options.skip));\n const query = params.toString();\n return this.request<TenantUsageHistoryRow[]>(\n `/api/v1/tenant-usage/${encodeURIComponent(tenantId)}/history${query ? `?${query}` : \"\"}`,\n );\n }\n\n private coreMemoryPath(\n assistantId: string,\n tenantId?: string,\n subtenantId?: string,\n entryId?: number,\n ): string {\n const params = new URLSearchParams();\n if (tenantId) params.set(\"tenantId\", tenantId);\n if (subtenantId) params.set(\"subtenantId\", subtenantId);\n const query = params.toString();\n return `/api/v1/memory/assistants/${encodeURIComponent(assistantId)}/core${\n entryId != null ? `/${entryId}` : \"\"\n }${query ? `?${query}` : \"\"}`;\n }\n\n /**\n * Core memory entries of the bucket the assistant resolves for a\n * tenant/subtenant combination — what the assistant permanently remembers\n * there. `enabled: false` when the assistant has no core memory tier.\n */\n async getCoreMemory(\n assistantId: string,\n options?: { tenantId?: string; subtenantId?: string },\n ): Promise<CoreMemoryList> {\n return this.request<CoreMemoryList>(\n this.coreMemoryPath(assistantId, options?.tenantId, options?.subtenantId),\n );\n }\n\n /** Add a standing core memory entry to the assistant's resolved bucket. */\n async addCoreMemoryEntry(\n assistantId: string,\n entry: { content: string; section?: string; pinned?: boolean },\n options?: { tenantId?: string; subtenantId?: string },\n ): Promise<{ entry?: CoreMemoryEntry; deduped: boolean }> {\n return this.request(\n this.coreMemoryPath(assistantId, options?.tenantId, options?.subtenantId),\n { method: \"POST\", body: JSON.stringify(entry) },\n );\n }\n\n /** Edit the text, section or pinned flag of a core memory entry. */\n async updateCoreMemoryEntry(\n assistantId: string,\n entryId: number,\n patch: { content?: string; section?: string; pinned?: boolean },\n options?: { tenantId?: string; subtenantId?: string },\n ): Promise<CoreMemoryEntry> {\n return this.request<CoreMemoryEntry>(\n this.coreMemoryPath(\n assistantId,\n options?.tenantId,\n options?.subtenantId,\n entryId,\n ),\n { method: \"PATCH\", body: JSON.stringify(patch) },\n );\n }\n\n /** Remove (archive) a core memory entry. */\n async deleteCoreMemoryEntry(\n assistantId: string,\n entryId: number,\n options?: { tenantId?: string; subtenantId?: string },\n ): Promise<{ removed: boolean; id?: number }> {\n return this.request(\n this.coreMemoryPath(\n assistantId,\n options?.tenantId,\n options?.subtenantId,\n entryId,\n ),\n { method: \"DELETE\" },\n );\n }\n\n // ── Connected apps of the end user ────────────────────────────────\n //\n // Backed by `/api/v1/tenant-integrations`: the tenant is resolved on the\n // server and never taken from the path. The tenant/subtenant sent here\n // identify the end user in front of the widget, so one tenant's accounts are\n // never reachable from another's.\n\n private integrationsQuery(options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n returnTo?: string;\n }): string {\n const params = new URLSearchParams({ assistantId: options.assistantId });\n if (options.tenantId) params.set(\"tenantId\", options.tenantId);\n if (options.subtenantId) params.set(\"subtenantId\", options.subtenantId);\n if (options.returnTo) params.set(\"returnTo\", options.returnTo);\n return params.toString();\n }\n\n /** Apps this assistant offers, with the end user's own connection status. */\n async getIntegrations(options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n }): Promise<Integration[]> {\n return this.request<Integration[]>(\n `/api/v1/tenant-integrations?${this.integrationsQuery(options)}`,\n );\n }\n\n /**\n * How this app can be connected, and what it asks the end user for.\n *\n * Scoped like everything else here: the schemes of an app this assistant\n * does not offer cannot be read by asking for them.\n */\n async getIntegrationAuth(\n app: string,\n options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n },\n ): Promise<{ schemes: IntegrationAuthScheme[] }> {\n return this.request(\n `/api/v1/tenant-integrations/${encodeURIComponent(app)}/auth?${this.integrationsQuery(options)}`,\n );\n }\n\n /**\n * Connects an account, in one of two ways.\n *\n * `connected: true` means it is done: the app authenticates with a key the\n * user supplied, so there is nobody to authorise with. Otherwise\n * `authorizationUrl` must be opened in a popup.\n *\n * `returnTo` is where the callback posts the result back to, and the server\n * refuses any value that does not match the origin this request came from —\n * so it cannot be turned into an open redirector.\n *\n * Rejects with a `DevicApiError` carrying `setupRequired` when the app needs\n * values that were not sent.\n */\n async connectIntegration(\n app: string,\n options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n returnTo?: string;\n /** Which scheme to use, from {@link getIntegrationAuth}. */\n authScheme?: string;\n /** This account's own values: its API key, its subdomain. */\n accountFields?: Record<string, string>;\n },\n ): Promise<{ connected: boolean; authorizationUrl?: string }> {\n const { authScheme, accountFields, ...query } = options;\n return this.request(\n `/api/v1/tenant-integrations/${encodeURIComponent(app)}/connect?${this.integrationsQuery(query)}`,\n {\n method: \"POST\",\n body: JSON.stringify({ authScheme, accountFields }),\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n /** Disconnects one of the end user's own accounts. */\n async disconnectIntegration(\n accountId: string,\n options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n },\n ): Promise<{ disconnected: boolean }> {\n return this.request(\n `/api/v1/tenant-integrations/accounts/${encodeURIComponent(accountId)}?${this.integrationsQuery(options)}`,\n { method: \"DELETE\" },\n );\n }\n\n /**\n * Drops the server's short-lived cache of the end user's connections.\n *\n * Called right after the OAuth popup closes: without it the freshly connected\n * app would keep reading as disconnected until the cache expires, which looks\n * like the connection silently failed.\n */\n async refreshIntegrations(options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n }): Promise<{ refreshed: boolean }> {\n return this.request(\n `/api/v1/tenant-integrations/refresh?${this.integrationsQuery(options)}`,\n { method: \"POST\" },\n );\n }\n\n // ---------------------------------------------------------------------------\n // MCP servers the end user connects for themselves\n // ---------------------------------------------------------------------------\n // Backed by `/api/v1/tenant-mcp`, scoped exactly like the integrations above:\n // the tenant is resolved on the server, never taken from the path. Sending a\n // `subtenantId` makes the connection that end user's own; omitting it puts it\n // on the tenant, where every one of its end users shares it.\n\n /** The MCP servers this assistant offers, and the ones this tenant connected. */\n async getMcpServers(options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n }): Promise<TenantMcpListing> {\n return this.request<TenantMcpListing>(\n `/api/v1/tenant-mcp?${this.integrationsQuery(options)}`,\n );\n }\n\n /**\n * Connects a server: one the developer offers (`templateId`) or one the end\n * user brings (`url`).\n *\n * `returnTo` is where the callback posts the result back to, and the server\n * refuses any value that does not match the origin this request came from —\n * so it cannot be turned into an open redirector.\n */\n async connectMcpServer(options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n returnTo?: string;\n templateId?: string;\n url?: string;\n name?: string;\n auth?: TenantMcpAuthInput;\n }): Promise<TenantMcpConnectResult> {\n const { templateId, url, name, auth, returnTo, ...query } = options;\n return this.request(`/api/v1/tenant-mcp?${this.integrationsQuery(query)}`, {\n method: \"POST\",\n // The scope travels in the body as well as the query string: it is what\n // decides whether this connection is the end user's own or the tenant's,\n // and the server reads it from there on writes.\n body: JSON.stringify({\n templateId,\n url,\n name,\n auth,\n returnTo,\n tenantId: options.tenantId,\n subtenantId: options.subtenantId,\n }),\n headers: { \"Content-Type\": \"application/json\" },\n });\n }\n\n /** Authorises again, for a server whose credentials expired or were revoked. */\n async reconnectMcpServer(\n id: string,\n options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n returnTo?: string;\n auth?: TenantMcpAuthInput;\n },\n ): Promise<TenantMcpConnectResult> {\n const { auth, returnTo, ...query } = options;\n return this.request(\n `/api/v1/tenant-mcp/${encodeURIComponent(id)}/reconnect?${this.integrationsQuery(query)}`,\n {\n method: \"POST\",\n body: JSON.stringify({\n auth,\n returnTo,\n tenantId: options.tenantId,\n subtenantId: options.subtenantId,\n }),\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n /** Disconnects one of the end user's own MCP servers. */\n async disconnectMcpServer(\n id: string,\n options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n },\n ): Promise<{ disconnected: boolean }> {\n return this.request(\n `/api/v1/tenant-mcp/${encodeURIComponent(id)}?${this.integrationsQuery(options)}`,\n { method: \"DELETE\" },\n );\n }\n}\n\n/**\n * Custom error class for API errors\n */\nexport class DevicApiError extends Error {\n public statusCode: number;\n public errorType?: string;\n /** Structured error details (e.g. usage-limit blocking info on a 429). */\n public details?: any;\n /** What connecting an app is still waiting for, when that is why it failed.\n * Carried whole because the fields *are* the form to render. */\n public setupRequired?: IntegrationSetupRequired;\n\n constructor(error: ApiError) {\n super(error.message);\n this.name = \"DevicApiError\";\n this.statusCode = error.statusCode;\n this.errorType = error.error;\n this.details = error.details;\n if ((error as any)?.code === \"INTEGRATION_SETUP_REQUIRED\") {\n this.setupRequired = error as unknown as IntegrationSetupRequired;\n }\n }\n}\n"],"names":[],"mappings":";;AAkFA;AACA,MAAM,iBAAiB,GAAG,KAAM;AAEhC;;;;;;AAMG;AACH,SAAS,QAAQ,CAAC,KAAa,EAAA;AAC7B,IAAA,IAAI;QACF,MAAM,OAAO,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;AACnC,QAAA,IAAI,CAAC,OAAO;AAAE,YAAA,OAAO,SAAS;QAC9B,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;QAChE,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,GAAG;AACjC,QAAA,OAAO,OAAO,GAAG,KAAK,QAAQ,GAAG,GAAG,GAAG,IAAI,GAAG,SAAS;IACzD;AAAE,IAAA,MAAM;AACN,QAAA,OAAO,SAAS;IAClB;AACF;AAEA;;AAEG;MACU,cAAc,CAAA;AAQzB,IAAA,WAAA,CAAY,MAA4B,EAAA;;QAFhC,IAAA,CAAA,cAAc,GAAG,KAAK;AAG5B,QAAA,IAAI,CAAC,MAAM,GAAG,MAAM;IACtB;AAEA;;AAEG;AACH,IAAA,SAAS,CAAC,MAAqC,EAAA;AAC7C,QAAA,MAAM,QAAQ,GAAG,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AACd,YAAA,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC;gBACnB,IAAI;gBACJ,QAAQ;gBACR,QAAQ,EAAE,OAAO,CAAC,QAAQ;gBAC1B,WAAW,EAAE,OAAO,CAAC,WAAW;aACjC,CAAC;AACF,YAAA,OAAO,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE;AAChD,SAAA,CACF;IACH;;AAGA,IAAA,MAAM,mBAAmB,CACvB,EAAU,EACV,OAIC,EAAA;QAED,OAAO,IAAI,CAAC,OAAO,CACjB,CAAA,mBAAA,EAAsB,kBAAkB,CAAC,EAAE,CAAC,CAAA,CAAA,EAAI,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAA,CAAE,EACjF,EAAE,MAAM,EAAE,QAAQ,EAAE,CACrB;IACH;AACD;AAED;;AAEG;AACG,MAAO,aAAc,SAAQ,KAAK,CAAA;AAStC,IAAA,WAAA,CAAY,KAAe,EAAA;AACzB,QAAA,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC;AACpB,QAAA,IAAI,CAAC,IAAI,GAAG,eAAe;AAC3B,QAAA,IAAI,CAAC,UAAU,GAAG,KAAK,CAAC,UAAU;AAClC,QAAA,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC,KAAK;AAC5B,QAAA,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC,OAAO;AAC5B,QAAA,IAAK,KAAa,EAAE,IAAI,KAAK,4BAA4B,EAAE;AACzD,YAAA,IAAI,CAAC,aAAa,GAAG,KAA4C;QACnE;IACF;AACD;;;"}
1
+ {"version":3,"file":"client.js","sources":["../../../../src/api/client.ts"],"sourcesContent":["import { consumeChatStream } from '../utils/consumeChatStream';\nimport type {\n ProcessMessageDto,\n ChatMessage,\n AsyncResponse,\n RealtimeChatHistory,\n ChatHistory,\n AssistantSpecialization,\n ApiError,\n ToolCallResponse,\n ConversationSummary,\n ListConversationsResponse,\n FeedbackSubmission,\n FeedbackEntry,\n AgentThreadDto,\n AgentDto,\n WhisperTranscriptionResponse,\n TenantUsage,\n TenantUsageHistoryRow,\n TenantUsageHistoryQuery,\n CoreMemoryList,\n CoreMemoryEntry,\n Integration,\n TenantMcpAuthInput,\n TenantMcpConnectResult,\n TenantMcpListing,\n IntegrationAuthScheme,\n IntegrationSetupRequired,\n ModelInterfaceToolSchema,\n StopChatResponse,\n} from \"./types\";\n\n/**\n * A tenant session, as the integrator's backend hands it over.\n *\n * A bare string is accepted too — the expiry is then read out of the token\n * itself, so the simplest possible source still gets proactive renewal.\n */\nexport interface TenantSessionToken {\n token: string;\n /** Epoch milliseconds. */\n expiresAt?: number;\n /** Seconds from now. Used when `expiresAt` is absent. */\n expiresIn?: number;\n}\n\nexport interface DevicApiClientConfig {\n /**\n * The public API key. Optional when `getTenantSession` is supplied — a page\n * using tenant sessions has no reason to carry one.\n */\n apiKey?: string;\n baseUrl: string;\n /**\n * Where the tenant session comes from.\n *\n * Supplying this changes what the tenant IS: with an API key alone the tenant\n * is whatever the page says it is, and the page can say anything. With a\n * session it is what your server signed.\n *\n * A function rather than a value because it is called again on its own —\n * before the token expires and after the API rejects one. It does not have to\n * reach your backend: reading a cookie your login already set is a perfectly\n * good answer, and then the whole thing is `async () => readCookie(…)`.\n *\n * It is called with `force: true` when the API has just rejected the token in\n * hand, meaning a cached answer is known to be dead. Your own function can\n * ignore the argument — `DevicProvider` uses it to share one session across\n * every component without ever serving a refused token back.\n */\n getTenantSession?: (force?: boolean) => Promise<string | TenantSessionToken>;\n /**\n * Called when the session is dead and cannot be replaced — the API rejected\n * it and `getTenantSession` handed back the same expired token.\n *\n * Matters most when the session comes from a cookie with no way to renew it:\n * without this the widget simply stops answering, at the exact moment the\n * user's own login has also expired. Refresh the page, send them to log in,\n * or say something — but say it.\n */\n onSessionExpired?: () => void;\n}\n\n/** Renew this long before expiry, so a request never leaves with a dead token. */\nconst RENEWAL_MARGIN_MS = 60_000;\n\n/**\n * The expiry inside a JWT, in epoch milliseconds.\n *\n * Read rather than required, so the session source can return just the string.\n * Any failure means \"no idea\", and the token is then renewed only when the API\n * rejects it — correct, just less graceful.\n */\nfunction expiryOf(token: string): number | undefined {\n try {\n const payload = token.split(\".\")[1];\n if (!payload) return undefined;\n const json = atob(payload.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n const exp = JSON.parse(json)?.exp;\n return typeof exp === \"number\" ? exp * 1000 : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Devic API client using native fetch\n */\nexport class DevicApiClient {\n private config: DevicApiClientConfig;\n private session?: { token: string; expiresAt?: number };\n /** In flight renewal, shared so a burst of calls fetches one token. */\n private renewing?: Promise<string>;\n /** So a page full of widgets reports one expiry, not one per widget. */\n private expiryReported = false;\n\n constructor(config: DevicApiClientConfig) {\n this.config = config;\n }\n\n /**\n * Update client configuration\n */\n setConfig(config: Partial<DevicApiClientConfig>): void {\n const previous = this.config;\n this.config = { ...this.config, ...config };\n // A new session source speaks for a different end user; keeping the old\n // token would show them the previous one's conversations.\n if (\n config.getTenantSession &&\n config.getTenantSession !== previous.getTenantSession\n ) {\n this.session = undefined;\n this.expiryReported = false;\n }\n }\n\n /** The credential for the next request, renewed if it is about to expire. */\n private async authorization(force = false): Promise<string> {\n if (!this.config.getTenantSession) return this.config.apiKey ?? \"\";\n\n const current = this.session;\n const stillGood =\n current &&\n (current.expiresAt === undefined ||\n current.expiresAt - Date.now() > RENEWAL_MARGIN_MS);\n if (stillGood && !force) return current.token;\n\n return this.renew(force);\n }\n\n private renew(force = false): Promise<string> {\n if (!this.renewing) {\n this.renewing = Promise.resolve(this.config.getTenantSession!(force))\n .then((result) => {\n const token = typeof result === \"string\" ? result : result.token;\n const declared =\n typeof result === \"string\"\n ? undefined\n : (result.expiresAt ??\n (result.expiresIn\n ? Date.now() + result.expiresIn * 1000\n : undefined));\n this.session = { token, expiresAt: declared ?? expiryOf(token) };\n return token;\n })\n .finally(() => {\n this.renewing = undefined;\n });\n }\n return this.renewing;\n }\n\n /**\n * Whether a rejected request is worth retrying, having got a live session.\n *\n * Takes the token the request actually went out with, not the current one:\n * with several requests in flight another may already have replaced it, and\n * comparing against the current one would read that success as a failure.\n *\n * False means the session is dead and cannot be replaced — a cookie set at\n * login, now expired, with nowhere to renew it from. That is worth telling\n * the host application about, once.\n */\n private async recoverSession(rejected: string): Promise<boolean> {\n if (this.session && this.session.token !== rejected) {\n this.expiryReported = false;\n return true;\n }\n\n let fresh: string | undefined;\n try {\n // Forced: whatever is cached upstream is the token that was just\n // refused, so asking for it again would only confirm the refusal.\n fresh = await this.renew(true);\n } catch {\n fresh = undefined;\n }\n if (fresh && fresh !== rejected) {\n this.expiryReported = false;\n return true;\n }\n\n if (!this.expiryReported) {\n this.expiryReported = true;\n this.config.onSessionExpired?.();\n }\n return false;\n }\n\n /**\n * Make an authenticated request to the API\n */\n private async request<T>(\n endpoint: string,\n options: RequestInit = {},\n isRetry = false,\n ): Promise<T> {\n const url = `${this.config.baseUrl}${endpoint}`;\n const credential = await this.authorization();\n\n const headers: HeadersInit = {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${credential}`,\n \"devic-api-source\": \"ui\",\n ...options.headers,\n };\n\n const response = await fetch(url, {\n ...options,\n headers,\n });\n\n // A session can die between being checked and being used — a clock adrift,\n // a tab asleep for an hour, the key revoked. One retry with a fresh token\n // turns that into a pause instead of a broken conversation.\n if (response.status === 401 && this.config.getTenantSession && !isRetry) {\n if (await this.recoverSession(credential)) {\n return this.request<T>(endpoint, options, true);\n }\n }\n\n if (!response.ok) {\n let errorData: ApiError;\n try {\n errorData = await response.json();\n } catch {\n errorData = {\n statusCode: response.status,\n message: response.statusText,\n };\n }\n // Not every refusal carries its own status in the body. A 409 raised with\n // an object (`{ error: 'CHAT_BUSY', ... }`) is returned verbatim, so\n // reading the code off the body alone leaves it undefined and every\n // `statusCode === 409` branch silently misses it.\n if (typeof errorData?.statusCode !== \"number\") {\n errorData = { ...errorData, statusCode: response.status };\n }\n throw new DevicApiError(errorData);\n }\n\n // Handle responses that may have a wrapper structure\n const data = await response.json();\n\n // If the response has a data property, extract it (common wrapper pattern)\n if (data && typeof data === \"object\" && \"data\" in data) {\n return data.data as T;\n }\n\n return data as T;\n }\n\n /**\n * Get all assistant specializations\n */\n async getAssistants(external = false): Promise<AssistantSpecialization[]> {\n const query = external ? \"?external=true\" : \"\";\n return this.request<AssistantSpecialization[]>(\n `/api/v1/assistants${query}`,\n );\n }\n\n /**\n * Get a specific assistant specialization\n */\n async getAssistant(identifier: string): Promise<AssistantSpecialization> {\n return this.request<AssistantSpecialization>(\n `/api/v1/assistants/${identifier}`,\n );\n }\n\n /**\n * Send a message to an assistant (sync mode)\n */\n async sendMessage(\n assistantId: string,\n dto: ProcessMessageDto,\n signal?: AbortSignal,\n ): Promise<ChatMessage[]> {\n return this.request<ChatMessage[]>(\n `/api/v1/assistants/${assistantId}/messages${dto.skipSummarization ? \"?skipSummarization=true\" : \"\"}`,\n {\n method: \"POST\",\n body: JSON.stringify(dto),\n signal,\n },\n );\n }\n\n /**\n * Send a message to an assistant (async mode)\n */\n async sendMessageAsync(\n assistantId: string,\n dto: ProcessMessageDto,\n ): Promise<AsyncResponse> {\n return this.request<AsyncResponse>(\n `/api/v1/assistants/${assistantId}/messages?async=true${dto.skipSummarization ? \"&skipSummarization=true\" : \"\"}`,\n {\n method: \"POST\",\n body: JSON.stringify(dto),\n },\n );\n }\n\n /**\n * Get the list of unique tags used across this account's chat histories.\n * Backed by GET /api/v1/assistants/tags. Useful for autocompletion / filters.\n */\n async getChatTags(): Promise<string[]> {\n return this.request<string[]>(`/api/v1/assistants/tags`);\n }\n\n /**\n * Follow a conversation in progress over its server-sent event stream.\n * Resolves when the server closes the stream; rejects when it is not a\n * stream at all (an older API) or the connection fails. `onActivity` fires\n * on every chunk received, keep-alives included.\n */\n async streamRealtimeHistory(\n assistantId: string,\n chatUid: string,\n onSnapshot: (snapshot: RealtimeChatHistory) => void | Promise<void>,\n signal: AbortSignal,\n onActivity?: () => void,\n ): Promise<void> {\n const url = `${this.config.baseUrl}/api/v1/assistants/${encodeURIComponent(assistantId)}/chats/${encodeURIComponent(chatUid)}/stream`;\n let credential = await this.authorization();\n const open = () => fetch(url, { signal, headers: { Authorization: `Bearer ${credential}`, Accept: 'text/event-stream', 'devic-api-source': 'ui' } });\n let response = await open();\n if (response.status === 401 && this.config.getTenantSession && await this.recoverSession(credential)) {\n credential = await this.authorization(); response = await open();\n }\n await consumeChatStream(response, onSnapshot, onActivity);\n }\n\n async getRealtimeHistory(\n assistantId: string,\n chatUid: string,\n ): Promise<RealtimeChatHistory> {\n return this.request<RealtimeChatHistory>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}/realtime`,\n );\n }\n\n /**\n * Get chat history for a specific conversation\n */\n async getChatHistory(\n assistantId: string,\n chatUid: string,\n options?: { tenantId?: string },\n ): Promise<ChatHistory> {\n const params = new URLSearchParams();\n if (options?.tenantId) {\n params.set(\"tenantId\", options.tenantId);\n }\n const query = params.toString();\n return this.request<ChatHistory>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}${query ? `?${query}` : \"\"}`,\n );\n }\n\n /**\n * List conversations for an assistant\n */\n async listConversations(\n assistantId: string,\n options?: {\n tenantId?: string;\n subtenantId?: string;\n offset?: number;\n limit?: number;\n },\n ): Promise<ListConversationsResponse> {\n const params = new URLSearchParams();\n if (options?.tenantId) {\n params.set(\"tenantId\", options.tenantId);\n }\n if (options?.subtenantId) {\n params.set(\"subtenantId\", options.subtenantId);\n }\n if (options?.offset != null) {\n params.set(\"offset\", String(options.offset));\n }\n if (options?.limit != null) {\n params.set(\"limit\", String(options.limit));\n }\n params.set(\"omitContent\", \"true\");\n const query = params.toString();\n return this.request<ListConversationsResponse>(\n `/api/v1/assistants/${assistantId}/chats${query ? `?${query}` : \"\"}`,\n );\n }\n\n /**\n * Send tool call responses back to the assistant.\n *\n * `toolSchemas` re-states the client-side tools for the continuation. The\n * API takes them from the first response of the batch, and without them the\n * turn resumes with no client tools at all — the model stops being able to\n * call them after the first round.\n */\n async sendToolResponses(\n assistantId: string,\n chatUid: string,\n responses: ToolCallResponse[],\n toolSchemas?: ModelInterfaceToolSchema[],\n ): Promise<AsyncResponse> {\n const body =\n toolSchemas?.length && responses.length > 0\n ? responses.map((response, index) =>\n index === 0 ? { ...response, tools: toolSchemas } : response,\n )\n : responses;\n\n return this.request<AsyncResponse>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}/tool-response`,\n {\n method: \"POST\",\n body: JSON.stringify({ responses: body }),\n },\n );\n }\n\n /**\n * Submit feedback for a chat message\n */\n async submitChatFeedback(\n assistantId: string,\n chatUid: string,\n data: FeedbackSubmission,\n ): Promise<FeedbackEntry> {\n return this.request<FeedbackEntry>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}/feedback`,\n {\n method: \"POST\",\n body: JSON.stringify(data),\n },\n );\n }\n\n /**\n * Get all feedback for a chat\n */\n async getChatFeedback(\n assistantId: string,\n chatUid: string,\n ): Promise<FeedbackEntry[]> {\n return this.request<FeedbackEntry[]>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}/feedback`,\n );\n }\n\n /**\n * Get an agent thread by ID\n */\n async getThreadById(\n threadId: string,\n withTasks = false,\n ): Promise<AgentThreadDto> {\n const query = withTasks ? \"?withTasks=true\" : \"\";\n return this.request<AgentThreadDto>(\n `/api/v1/agents/threads/${threadId}${query}`,\n );\n }\n\n /**\n * Get agent details\n */\n async getAgentDetails(agentId: string): Promise<AgentDto> {\n return this.request<AgentDto>(`/api/v1/agents/${agentId}`);\n }\n\n /**\n * Get an AI-generated explanation of a thread's execution\n */\n async explainAgentThread(threadId: string): Promise<string> {\n return this.request<string>(\n `/api/v1/agents/threads/${threadId}/explain`,\n );\n }\n\n /**\n * Pause or resume a thread\n */\n async pauseResumeThread(\n threadId: string,\n action: \"paused\" | \"queued\",\n ): Promise<void> {\n return this.request<void>(\n `/api/v1/agents/threads/${threadId}/pause-resume`,\n {\n method: \"POST\",\n body: JSON.stringify({ action }),\n },\n );\n }\n\n /**\n * Handle thread approval (approve/reject)\n */\n async handleThreadApproval(\n threadId: string,\n approved: boolean,\n retry: boolean,\n message: string,\n ): Promise<void> {\n return this.request<void>(\n `/api/v1/agents/threads/${threadId}/approval`,\n {\n method: \"POST\",\n body: JSON.stringify({\n action: approved ? \"approved\" : \"rejected\",\n message,\n retry,\n }),\n },\n );\n }\n\n /**\n * Manually complete a thread\n */\n async completeThread(\n threadId: string,\n completionState: string,\n ): Promise<void> {\n return this.request<void>(\n `/api/v1/agents/threads/${threadId}/complete`,\n {\n method: \"POST\",\n body: JSON.stringify({ state: completionState }),\n },\n );\n }\n\n /**\n * Continue an existing thread with a new user message. The backend decides how\n * to apply it based on the thread state: a finished/failed/waiting thread is\n * re-queued and re-run with the message appended, while a running/queued thread\n * receives it on its next turn (right after the pending tool response). Returns\n * the updated thread.\n */\n async sendThreadMessage(\n threadId: string,\n message: string | Record<string, unknown>,\n ): Promise<AgentThreadDto> {\n return this.request<AgentThreadDto>(\n `/api/v1/agents/threads/${threadId}/messages`,\n {\n method: \"POST\",\n body: JSON.stringify({ message }),\n },\n );\n }\n\n /**\n * Stop an in-progress async chat.\n * The current LLM call or tool execution will finish, then the chat\n * will be marked as completed with the history accumulated so far.\n */\n async stopChat(\n assistantId: string,\n chatUid: string,\n ): Promise<StopChatResponse> {\n return this.request<StopChatResponse>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}/stop`,\n { method: \"POST\" },\n );\n }\n\n /**\n * Upload a file and get a download URL\n */\n async uploadFile(\n file: File,\n isRetry = false,\n ): Promise<{ name: string; downloadUrl: string; fileType: string }> {\n const url = `${this.config.baseUrl}/api/v1/files/upload`;\n\n const formData = new FormData();\n formData.append(\"file\", file);\n\n const credential = await this.authorization();\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${credential}`,\n \"devic-api-source\": \"ui\",\n },\n body: formData,\n });\n\n // The FormData is rebuilt from `file` on the way back in, so unlike a\n // consumed stream this retry is safe.\n if (response.status === 401 && this.config.getTenantSession && !isRetry) {\n if (await this.recoverSession(credential)) return this.uploadFile(file, true);\n }\n\n if (!response.ok) {\n let errorData: { statusCode: number; message: string };\n try {\n errorData = await response.json();\n } catch {\n errorData = {\n statusCode: response.status,\n message: response.statusText,\n };\n }\n // See `request`: a body-shaped refusal need not carry its own status.\n if (typeof errorData?.statusCode !== \"number\") {\n errorData = { ...errorData, statusCode: response.status };\n }\n throw new DevicApiError(errorData);\n }\n\n const data = await response.json();\n if (data && typeof data === \"object\" && \"data\" in data) {\n return data.data;\n }\n return data;\n }\n\n /**\n * Transcribe audio to text using the /whisper endpoint.\n * Accepts either an audio binary (Blob/File, sent as multipart/form-data) or\n * a download URL string (sent as `audioUrl`). The backend stores the binary\n * and runs speech-to-text with Devic's own OpenAI key. Returns the text and a\n * `transcriptId` to attach to the resulting message.\n */\n async transcribeAudio(\n audio: Blob | string,\n options?: {\n language?: string;\n messageUid?: string;\n chatUid?: string;\n tenantId?: string;\n fileName?: string;\n },\n isRetry = false,\n ): Promise<WhisperTranscriptionResponse> {\n const url = `${this.config.baseUrl}/api/v1/whisper`;\n\n const formData = new FormData();\n if (typeof audio === \"string\") {\n formData.append(\"audioUrl\", audio);\n } else {\n formData.append(\"audio\", audio, options?.fileName || \"recording.webm\");\n }\n if (options?.language) formData.append(\"language\", options.language);\n if (options?.messageUid) formData.append(\"messageUid\", options.messageUid);\n if (options?.chatUid) formData.append(\"chatUid\", options.chatUid);\n if (options?.tenantId) formData.append(\"tenantId\", options.tenantId);\n\n const credential = await this.authorization();\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${credential}`,\n \"devic-api-source\": \"ui\",\n },\n body: formData,\n });\n\n if (response.status === 401 && this.config.getTenantSession && !isRetry) {\n if (await this.recoverSession(credential)) {\n return this.transcribeAudio(audio, options, true);\n }\n }\n\n if (!response.ok) {\n let errorData: { statusCode: number; message: string };\n try {\n errorData = await response.json();\n } catch {\n errorData = {\n statusCode: response.status,\n message: response.statusText,\n };\n }\n // See `request`: a body-shaped refusal need not carry its own status.\n if (typeof errorData?.statusCode !== \"number\") {\n errorData = { ...errorData, statusCode: response.status };\n }\n throw new DevicApiError(errorData);\n }\n\n const data = await response.json();\n if (data && typeof data === \"object\" && \"data\" in data) {\n return data.data;\n }\n return data;\n }\n\n /**\n * Fetch a single speech-to-text transcript by its id (the `transcriptId`\n * stored on a message). Returns the transcribed text and the download URL of\n * the source audio so the chat can offer playback of a dictated message.\n */\n async getTranscript(\n transcriptId: string,\n ): Promise<WhisperTranscriptionResponse> {\n return this.request<WhisperTranscriptionResponse>(\n `/api/v1/whisper/${encodeURIComponent(transcriptId)}`,\n );\n }\n\n /**\n * Get chat history content (full conversation after handoff)\n */\n async getChatHistoryContent(\n assistantId: string,\n chatUid: string,\n ): Promise<ChatMessage[]> {\n return this.request<ChatMessage[]>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}/content`,\n );\n }\n\n /**\n * Get the current usage limits + consumption for a tenant (or a specific\n * subtenant). Read-only — backed by `GET /api/v1/tenant-usage/:tenantId`\n * (or `/:tenantId/subtenants/:subtenantId`), which is part of the devic-ui\n * key preset. Returns the effective rules with their live consumption and the\n * active tier. Use it to render a usage bar.\n */\n async getTenantUsage(\n tenantId: string,\n subtenantId?: string,\n ): Promise<TenantUsage> {\n const path = subtenantId\n ? `/api/v1/tenant-usage/${encodeURIComponent(tenantId)}/subtenants/${encodeURIComponent(subtenantId)}`\n : `/api/v1/tenant-usage/${encodeURIComponent(tenantId)}`;\n return this.request<TenantUsage>(path);\n }\n\n /**\n * Get the durable per-window usage history for a tenant (or subtenant).\n * Read-only — backed by `GET /api/v1/tenant-usage/:tenantId/history`.\n */\n async getTenantUsageHistory(\n tenantId: string,\n options?: TenantUsageHistoryQuery,\n ): Promise<TenantUsageHistoryRow[]> {\n const params = new URLSearchParams();\n if (options?.subtenantId) params.set(\"subtenantId\", options.subtenantId);\n if (options?.scope) params.set(\"scope\", options.scope);\n if (options?.metric) params.set(\"metric\", options.metric);\n if (options?.windowUnit) params.set(\"windowUnit\", options.windowUnit);\n if (options?.from != null) params.set(\"from\", String(options.from));\n if (options?.to != null) params.set(\"to\", String(options.to));\n if (options?.limit != null) params.set(\"limit\", String(options.limit));\n if (options?.skip != null) params.set(\"skip\", String(options.skip));\n const query = params.toString();\n return this.request<TenantUsageHistoryRow[]>(\n `/api/v1/tenant-usage/${encodeURIComponent(tenantId)}/history${query ? `?${query}` : \"\"}`,\n );\n }\n\n private coreMemoryPath(\n assistantId: string,\n tenantId?: string,\n subtenantId?: string,\n entryId?: number,\n ): string {\n const params = new URLSearchParams();\n if (tenantId) params.set(\"tenantId\", tenantId);\n if (subtenantId) params.set(\"subtenantId\", subtenantId);\n const query = params.toString();\n return `/api/v1/memory/assistants/${encodeURIComponent(assistantId)}/core${\n entryId != null ? `/${entryId}` : \"\"\n }${query ? `?${query}` : \"\"}`;\n }\n\n /**\n * Core memory entries of the bucket the assistant resolves for a\n * tenant/subtenant combination — what the assistant permanently remembers\n * there. `enabled: false` when the assistant has no core memory tier.\n */\n async getCoreMemory(\n assistantId: string,\n options?: { tenantId?: string; subtenantId?: string },\n ): Promise<CoreMemoryList> {\n return this.request<CoreMemoryList>(\n this.coreMemoryPath(assistantId, options?.tenantId, options?.subtenantId),\n );\n }\n\n /** Add a standing core memory entry to the assistant's resolved bucket. */\n async addCoreMemoryEntry(\n assistantId: string,\n entry: { content: string; section?: string; pinned?: boolean },\n options?: { tenantId?: string; subtenantId?: string },\n ): Promise<{ entry?: CoreMemoryEntry; deduped: boolean }> {\n return this.request(\n this.coreMemoryPath(assistantId, options?.tenantId, options?.subtenantId),\n { method: \"POST\", body: JSON.stringify(entry) },\n );\n }\n\n /** Edit the text, section or pinned flag of a core memory entry. */\n async updateCoreMemoryEntry(\n assistantId: string,\n entryId: number,\n patch: { content?: string; section?: string; pinned?: boolean },\n options?: { tenantId?: string; subtenantId?: string },\n ): Promise<CoreMemoryEntry> {\n return this.request<CoreMemoryEntry>(\n this.coreMemoryPath(\n assistantId,\n options?.tenantId,\n options?.subtenantId,\n entryId,\n ),\n { method: \"PATCH\", body: JSON.stringify(patch) },\n );\n }\n\n /** Remove (archive) a core memory entry. */\n async deleteCoreMemoryEntry(\n assistantId: string,\n entryId: number,\n options?: { tenantId?: string; subtenantId?: string },\n ): Promise<{ removed: boolean; id?: number }> {\n return this.request(\n this.coreMemoryPath(\n assistantId,\n options?.tenantId,\n options?.subtenantId,\n entryId,\n ),\n { method: \"DELETE\" },\n );\n }\n\n // ── Connected apps of the end user ────────────────────────────────\n //\n // Backed by `/api/v1/tenant-integrations`: the tenant is resolved on the\n // server and never taken from the path. The tenant/subtenant sent here\n // identify the end user in front of the widget, so one tenant's accounts are\n // never reachable from another's.\n\n private integrationsQuery(options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n returnTo?: string;\n }): string {\n const params = new URLSearchParams({ assistantId: options.assistantId });\n if (options.tenantId) params.set(\"tenantId\", options.tenantId);\n if (options.subtenantId) params.set(\"subtenantId\", options.subtenantId);\n if (options.returnTo) params.set(\"returnTo\", options.returnTo);\n return params.toString();\n }\n\n /** Apps this assistant offers, with the end user's own connection status. */\n async getIntegrations(options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n }): Promise<Integration[]> {\n return this.request<Integration[]>(\n `/api/v1/tenant-integrations?${this.integrationsQuery(options)}`,\n );\n }\n\n /**\n * How this app can be connected, and what it asks the end user for.\n *\n * Scoped like everything else here: the schemes of an app this assistant\n * does not offer cannot be read by asking for them.\n */\n async getIntegrationAuth(\n app: string,\n options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n },\n ): Promise<{ schemes: IntegrationAuthScheme[] }> {\n return this.request(\n `/api/v1/tenant-integrations/${encodeURIComponent(app)}/auth?${this.integrationsQuery(options)}`,\n );\n }\n\n /**\n * Connects an account, in one of two ways.\n *\n * `connected: true` means it is done: the app authenticates with a key the\n * user supplied, so there is nobody to authorise with. Otherwise\n * `authorizationUrl` must be opened in a popup.\n *\n * `returnTo` is where the callback posts the result back to, and the server\n * refuses any value that does not match the origin this request came from —\n * so it cannot be turned into an open redirector.\n *\n * Rejects with a `DevicApiError` carrying `setupRequired` when the app needs\n * values that were not sent.\n */\n async connectIntegration(\n app: string,\n options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n returnTo?: string;\n /** Which scheme to use, from {@link getIntegrationAuth}. */\n authScheme?: string;\n /** This account's own values: its API key, its subdomain. */\n accountFields?: Record<string, string>;\n },\n ): Promise<{ connected: boolean; authorizationUrl?: string }> {\n const { authScheme, accountFields, ...query } = options;\n return this.request(\n `/api/v1/tenant-integrations/${encodeURIComponent(app)}/connect?${this.integrationsQuery(query)}`,\n {\n method: \"POST\",\n body: JSON.stringify({ authScheme, accountFields }),\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n /** Disconnects one of the end user's own accounts. */\n async disconnectIntegration(\n accountId: string,\n options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n },\n ): Promise<{ disconnected: boolean }> {\n return this.request(\n `/api/v1/tenant-integrations/accounts/${encodeURIComponent(accountId)}?${this.integrationsQuery(options)}`,\n { method: \"DELETE\" },\n );\n }\n\n /**\n * Drops the server's short-lived cache of the end user's connections.\n *\n * Called right after the OAuth popup closes: without it the freshly connected\n * app would keep reading as disconnected until the cache expires, which looks\n * like the connection silently failed.\n */\n async refreshIntegrations(options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n }): Promise<{ refreshed: boolean }> {\n return this.request(\n `/api/v1/tenant-integrations/refresh?${this.integrationsQuery(options)}`,\n { method: \"POST\" },\n );\n }\n\n // ---------------------------------------------------------------------------\n // MCP servers the end user connects for themselves\n // ---------------------------------------------------------------------------\n // Backed by `/api/v1/tenant-mcp`, scoped exactly like the integrations above:\n // the tenant is resolved on the server, never taken from the path. Sending a\n // `subtenantId` makes the connection that end user's own; omitting it puts it\n // on the tenant, where every one of its end users shares it.\n\n /** The MCP servers this assistant offers, and the ones this tenant connected. */\n async getMcpServers(options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n }): Promise<TenantMcpListing> {\n return this.request<TenantMcpListing>(\n `/api/v1/tenant-mcp?${this.integrationsQuery(options)}`,\n );\n }\n\n /**\n * Connects a server: one the developer offers (`templateId`) or one the end\n * user brings (`url`).\n *\n * `returnTo` is where the callback posts the result back to, and the server\n * refuses any value that does not match the origin this request came from —\n * so it cannot be turned into an open redirector.\n */\n async connectMcpServer(options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n returnTo?: string;\n templateId?: string;\n url?: string;\n name?: string;\n auth?: TenantMcpAuthInput;\n }): Promise<TenantMcpConnectResult> {\n const { templateId, url, name, auth, returnTo, ...query } = options;\n return this.request(`/api/v1/tenant-mcp?${this.integrationsQuery(query)}`, {\n method: \"POST\",\n // The scope travels in the body as well as the query string: it is what\n // decides whether this connection is the end user's own or the tenant's,\n // and the server reads it from there on writes.\n body: JSON.stringify({\n templateId,\n url,\n name,\n auth,\n returnTo,\n tenantId: options.tenantId,\n subtenantId: options.subtenantId,\n }),\n headers: { \"Content-Type\": \"application/json\" },\n });\n }\n\n /** Authorises again, for a server whose credentials expired or were revoked. */\n async reconnectMcpServer(\n id: string,\n options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n returnTo?: string;\n auth?: TenantMcpAuthInput;\n },\n ): Promise<TenantMcpConnectResult> {\n const { auth, returnTo, ...query } = options;\n return this.request(\n `/api/v1/tenant-mcp/${encodeURIComponent(id)}/reconnect?${this.integrationsQuery(query)}`,\n {\n method: \"POST\",\n body: JSON.stringify({\n auth,\n returnTo,\n tenantId: options.tenantId,\n subtenantId: options.subtenantId,\n }),\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n /** Disconnects one of the end user's own MCP servers. */\n async disconnectMcpServer(\n id: string,\n options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n },\n ): Promise<{ disconnected: boolean }> {\n return this.request(\n `/api/v1/tenant-mcp/${encodeURIComponent(id)}?${this.integrationsQuery(options)}`,\n { method: \"DELETE\" },\n );\n }\n}\n\n/**\n * Custom error class for API errors\n */\nexport class DevicApiError extends Error {\n public statusCode: number;\n public errorType?: string;\n /** Structured error details (e.g. usage-limit blocking info on a 429). */\n public details?: any;\n /** What connecting an app is still waiting for, when that is why it failed.\n * Carried whole because the fields *are* the form to render. */\n public setupRequired?: IntegrationSetupRequired;\n\n constructor(error: ApiError) {\n super(error.message);\n this.name = \"DevicApiError\";\n this.statusCode = error.statusCode;\n this.errorType = error.error;\n this.details = error.details;\n if ((error as any)?.code === \"INTEGRATION_SETUP_REQUIRED\") {\n this.setupRequired = error as unknown as IntegrationSetupRequired;\n }\n }\n}\n"],"names":["consumeChatStream"],"mappings":";;;;AAmFA;AACA,MAAM,iBAAiB,GAAG,KAAM;AAEhC;;;;;;AAMG;AACH,SAAS,QAAQ,CAAC,KAAa,EAAA;AAC7B,IAAA,IAAI;QACF,MAAM,OAAO,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;AACnC,QAAA,IAAI,CAAC,OAAO;AAAE,YAAA,OAAO,SAAS;QAC9B,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;QAChE,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,GAAG;AACjC,QAAA,OAAO,OAAO,GAAG,KAAK,QAAQ,GAAG,GAAG,GAAG,IAAI,GAAG,SAAS;IACzD;AAAE,IAAA,MAAM;AACN,QAAA,OAAO,SAAS;IAClB;AACF;AAEA;;AAEG;MACU,cAAc,CAAA;AAQzB,IAAA,WAAA,CAAY,MAA4B,EAAA;;QAFhC,IAAA,CAAA,cAAc,GAAG,KAAK;AAG5B,QAAA,IAAI,CAAC,MAAM,GAAG,MAAM;IACt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