@assistant-ui/core 0.3.18 → 0.3.19

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 (274) hide show
  1. package/dist/adapters/speech.d.ts.map +1 -1
  2. package/dist/adapters/speech.js +13 -3
  3. package/dist/adapters/speech.js.map +1 -1
  4. package/dist/adapters/thread-history.d.ts +4 -0
  5. package/dist/adapters/thread-history.d.ts.map +1 -1
  6. package/dist/index.d.ts +2 -2
  7. package/dist/index.js.map +1 -1
  8. package/dist/internal.d.ts +1 -1
  9. package/dist/model-context/frame/host.d.ts.map +1 -1
  10. package/dist/model-context/frame/host.js +26 -11
  11. package/dist/model-context/frame/host.js.map +1 -1
  12. package/dist/model-context/interactable-composer-metadata.js +11 -9
  13. package/dist/model-context/interactable-composer-metadata.js.map +1 -1
  14. package/dist/react/adapters/LocalStorageThreadListAdapter.d.ts.map +1 -1
  15. package/dist/react/adapters/LocalStorageThreadListAdapter.js +45 -7
  16. package/dist/react/adapters/LocalStorageThreadListAdapter.js.map +1 -1
  17. package/dist/react/client/DataRenderers.d.ts.map +1 -1
  18. package/dist/react/client/DataRenderers.js +20 -15
  19. package/dist/react/client/DataRenderers.js.map +1 -1
  20. package/dist/react/client/Interactables.d.ts.map +1 -1
  21. package/dist/react/client/Interactables.js +11 -5
  22. package/dist/react/client/Interactables.js.map +1 -1
  23. package/dist/react/client/RemoteThreadList.d.ts.map +1 -1
  24. package/dist/react/client/RemoteThreadList.js +3 -2
  25. package/dist/react/client/RemoteThreadList.js.map +1 -1
  26. package/dist/react/client/interactable-model-context.d.ts.map +1 -1
  27. package/dist/react/client/interactable-model-context.js +3 -2
  28. package/dist/react/client/interactable-model-context.js.map +1 -1
  29. package/dist/react/index.d.ts +2 -2
  30. package/dist/react/index.js +2 -2
  31. package/dist/react/interactables-legacy/useAssistantInteractable.d.ts.map +1 -1
  32. package/dist/react/interactables-legacy/useAssistantInteractable.js +3 -0
  33. package/dist/react/interactables-legacy/useAssistantInteractable.js.map +1 -1
  34. package/dist/react/model-context/useInteractable.d.ts.map +1 -1
  35. package/dist/react/model-context/useInteractable.js +4 -1
  36. package/dist/react/model-context/useInteractable.js.map +1 -1
  37. package/dist/react/model-context/useInteractableVersions.js +1 -1
  38. package/dist/react/primitives/message/MessageGroupedParts.d.ts +11 -2
  39. package/dist/react/primitives/message/MessageGroupedParts.d.ts.map +1 -1
  40. package/dist/react/primitives/message/MessageGroupedParts.js +3 -2
  41. package/dist/react/primitives/message/MessageGroupedParts.js.map +1 -1
  42. package/dist/react/primitives/part/PartMessages.d.ts +1 -0
  43. package/dist/react/primitives/part/PartMessages.d.ts.map +1 -1
  44. package/dist/react/primitives/part/PartMessages.js +1 -0
  45. package/dist/react/primitives/part/PartMessages.js.map +1 -1
  46. package/dist/react/primitives/thread/ThreadMessages.d.ts.map +1 -1
  47. package/dist/react/primitives/thread/ThreadMessages.js +6 -5
  48. package/dist/react/primitives/thread/ThreadMessages.js.map +1 -1
  49. package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts.map +1 -1
  50. package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js +2 -1
  51. package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js.map +1 -1
  52. package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.d.ts +2 -24
  53. package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.d.ts.map +1 -1
  54. package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.js +135 -374
  55. package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.js.map +1 -1
  56. package/dist/react/runtimes/cloud/CloudFileAttachmentAdapter.d.ts +1 -0
  57. package/dist/react/runtimes/cloud/CloudFileAttachmentAdapter.d.ts.map +1 -1
  58. package/dist/react/runtimes/cloud/CloudFileAttachmentAdapter.js +22 -2
  59. package/dist/react/runtimes/cloud/CloudFileAttachmentAdapter.js.map +1 -1
  60. package/dist/react/runtimes/cloud/auiV0.d.ts +40 -15
  61. package/dist/react/runtimes/cloud/auiV0.d.ts.map +1 -1
  62. package/dist/react/runtimes/cloud/auiV0.js +62 -15
  63. package/dist/react/runtimes/cloud/auiV0.js.map +1 -1
  64. package/dist/react/runtimes/cloud/createCloudThreadListAdapter.d.ts +2 -1
  65. package/dist/react/runtimes/cloud/createCloudThreadListAdapter.d.ts.map +1 -1
  66. package/dist/react/runtimes/cloud/createCloudThreadListAdapter.js +4 -0
  67. package/dist/react/runtimes/cloud/createCloudThreadListAdapter.js.map +1 -1
  68. package/dist/react/runtimes/cloud/sdkIdentity.d.ts +6 -0
  69. package/dist/react/runtimes/cloud/sdkIdentity.d.ts.map +1 -0
  70. package/dist/react/runtimes/cloud/sdkIdentity.js +9 -0
  71. package/dist/react/runtimes/cloud/sdkIdentity.js.map +1 -0
  72. package/dist/react/runtimes/external-message-converter.d.ts +12 -2
  73. package/dist/react/runtimes/external-message-converter.d.ts.map +1 -1
  74. package/dist/react/runtimes/external-message-converter.js +26 -61
  75. package/dist/react/runtimes/external-message-converter.js.map +1 -1
  76. package/dist/react/runtimes/useRemoteThreadListRuntime.js +1 -1
  77. package/dist/react/runtimes/useRemoteThreadListRuntime.js.map +1 -1
  78. package/dist/react/utils/groupParts.d.ts +6 -1
  79. package/dist/react/utils/groupParts.d.ts.map +1 -1
  80. package/dist/react/utils/groupParts.js +6 -0
  81. package/dist/react/utils/groupParts.js.map +1 -1
  82. package/dist/react/utils/useJSONEqual.d.ts +3 -1
  83. package/dist/react/utils/useJSONEqual.d.ts.map +1 -1
  84. package/dist/react/utils/useJSONEqual.js +6 -1
  85. package/dist/react/utils/useJSONEqual.js.map +1 -1
  86. package/dist/react/utils/useJSONSchemaDependency.d.ts +7 -0
  87. package/dist/react/utils/useJSONSchemaDependency.d.ts.map +1 -0
  88. package/dist/react/utils/useJSONSchemaDependency.js +20 -0
  89. package/dist/react/utils/useJSONSchemaDependency.js.map +1 -0
  90. package/dist/runtime/api/thread-runtime.d.ts.map +1 -1
  91. package/dist/runtime/api/thread-runtime.js +2 -5
  92. package/dist/runtime/api/thread-runtime.js.map +1 -1
  93. package/dist/runtime/base/base-composer-runtime-core.d.ts +1 -0
  94. package/dist/runtime/base/base-composer-runtime-core.d.ts.map +1 -1
  95. package/dist/runtime/base/base-composer-runtime-core.js +46 -10
  96. package/dist/runtime/base/base-composer-runtime-core.js.map +1 -1
  97. package/dist/runtime/base/base-thread-runtime-core.d.ts +2 -0
  98. package/dist/runtime/base/base-thread-runtime-core.d.ts.map +1 -1
  99. package/dist/runtime/base/base-thread-runtime-core.js +155 -64
  100. package/dist/runtime/base/base-thread-runtime-core.js.map +1 -1
  101. package/dist/runtime/interfaces/thread-runtime-core.d.ts +6 -0
  102. package/dist/runtime/interfaces/thread-runtime-core.d.ts.map +1 -1
  103. package/dist/runtime/queue/message-queue.d.ts +5 -0
  104. package/dist/runtime/queue/message-queue.d.ts.map +1 -1
  105. package/dist/runtime/queue/message-queue.js +61 -6
  106. package/dist/runtime/queue/message-queue.js.map +1 -1
  107. package/dist/runtime/utils/auto-status.d.ts +6 -2
  108. package/dist/runtime/utils/auto-status.d.ts.map +1 -1
  109. package/dist/runtime/utils/auto-status.js +12 -4
  110. package/dist/runtime/utils/auto-status.js.map +1 -1
  111. package/dist/runtime/utils/external-message-conversion.d.ts +16 -4
  112. package/dist/runtime/utils/external-message-conversion.d.ts.map +1 -1
  113. package/dist/runtime/utils/external-message-conversion.js +48 -12
  114. package/dist/runtime/utils/external-message-conversion.js.map +1 -1
  115. package/dist/runtime/utils/message-repository.js +3 -3
  116. package/dist/runtime/utils/message-repository.js.map +1 -1
  117. package/dist/runtime/utils/thread-message-like.d.ts +2 -1
  118. package/dist/runtime/utils/thread-message-like.d.ts.map +1 -1
  119. package/dist/runtime/utils/thread-message-like.js +4 -2
  120. package/dist/runtime/utils/thread-message-like.js.map +1 -1
  121. package/dist/runtimes/external-store/external-store-thread-runtime-core.d.ts.map +1 -1
  122. package/dist/runtimes/external-store/external-store-thread-runtime-core.js +8 -1
  123. package/dist/runtimes/external-store/external-store-thread-runtime-core.js.map +1 -1
  124. package/dist/runtimes/internal.d.ts +1 -1
  125. package/dist/runtimes/local/local-thread-runtime-core.d.ts +1 -1
  126. package/dist/runtimes/local/local-thread-runtime-core.d.ts.map +1 -1
  127. package/dist/runtimes/local/local-thread-runtime-core.js +4 -1
  128. package/dist/runtimes/local/local-thread-runtime-core.js.map +1 -1
  129. package/dist/runtimes/tool-invocations/ToolInvocationTracker.d.ts.map +1 -1
  130. package/dist/runtimes/tool-invocations/ToolInvocationTracker.js +2 -1
  131. package/dist/runtimes/tool-invocations/ToolInvocationTracker.js.map +1 -1
  132. package/dist/store/clients/external-thread.d.ts.map +1 -1
  133. package/dist/store/clients/external-thread.js +241 -200
  134. package/dist/store/clients/external-thread.js.map +1 -1
  135. package/dist/store/clients/thread-tasks.d.ts +13 -0
  136. package/dist/store/clients/thread-tasks.d.ts.map +1 -0
  137. package/dist/store/clients/thread-tasks.js +69 -0
  138. package/dist/store/clients/thread-tasks.js.map +1 -0
  139. package/dist/store/index.d.ts +3 -2
  140. package/dist/store/index.js +3 -3
  141. package/dist/store/primitive-predicates.d.ts.map +1 -1
  142. package/dist/store/primitive-predicates.js +4 -4
  143. package/dist/store/primitive-predicates.js.map +1 -1
  144. package/dist/store/runtime-clients/thread-runtime-client.d.ts.map +1 -1
  145. package/dist/store/runtime-clients/thread-runtime-client.js +176 -128
  146. package/dist/store/runtime-clients/thread-runtime-client.js.map +1 -1
  147. package/dist/store/scope-registration.d.ts +2 -0
  148. package/dist/store/scope-registration.d.ts.map +1 -1
  149. package/dist/store/scopes/task.d.ts +36 -0
  150. package/dist/store/scopes/task.d.ts.map +1 -0
  151. package/dist/store/scopes/task.js +0 -0
  152. package/dist/store/scopes/thread.d.ts +20 -0
  153. package/dist/store/scopes/thread.d.ts.map +1 -1
  154. package/dist/subscribable/subscribable.d.ts +2 -1
  155. package/dist/subscribable/subscribable.d.ts.map +1 -1
  156. package/dist/subscribable/subscribable.js +23 -15
  157. package/dist/subscribable/subscribable.js.map +1 -1
  158. package/dist/types/index.d.ts +2 -2
  159. package/dist/types/message.d.ts +8 -1
  160. package/dist/types/message.d.ts.map +1 -1
  161. package/dist/types/message.js.map +1 -1
  162. package/dist/utils/abortable-iterable.d.ts.map +1 -1
  163. package/dist/utils/abortable-iterable.js +30 -14
  164. package/dist/utils/abortable-iterable.js.map +1 -1
  165. package/dist/utils/getGroupStatus.d.ts +18 -2
  166. package/dist/utils/getGroupStatus.d.ts.map +1 -1
  167. package/dist/utils/getGroupStatus.js +32 -7
  168. package/dist/utils/getGroupStatus.js.map +1 -1
  169. package/dist/utils/wire-media.d.ts.map +1 -1
  170. package/dist/utils/wire-media.js +2 -2
  171. package/dist/utils/wire-media.js.map +1 -1
  172. package/package.json +6 -6
  173. package/src/adapters/speech.test.ts +236 -0
  174. package/src/adapters/speech.ts +17 -10
  175. package/src/adapters/thread-history.ts +3 -0
  176. package/src/index.ts +1 -0
  177. package/src/model-context/frame/host.test.ts +113 -1
  178. package/src/model-context/frame/host.ts +39 -12
  179. package/src/model-context/interactable-composer-metadata.test.ts +30 -0
  180. package/src/model-context/interactable-composer-metadata.ts +10 -10
  181. package/src/react/adapters/LocalStorageThreadListAdapter.test.ts +244 -0
  182. package/src/react/adapters/LocalStorageThreadListAdapter.tsx +104 -7
  183. package/src/react/client/DataRenderers.test.tsx +45 -0
  184. package/src/react/client/DataRenderers.ts +13 -9
  185. package/src/react/client/Interactables.test.ts +44 -1
  186. package/src/react/client/Interactables.ts +7 -1
  187. package/src/react/client/RemoteThreadList.test.ts +41 -1
  188. package/src/react/client/RemoteThreadList.ts +15 -2
  189. package/src/react/client/interactable-model-context.test.ts +44 -0
  190. package/src/react/client/interactable-model-context.ts +3 -2
  191. package/src/react/index.ts +5 -1
  192. package/src/react/interactables-legacy/useAssistantInteractable.test.tsx +132 -0
  193. package/src/react/interactables-legacy/useAssistantInteractable.ts +10 -1
  194. package/src/react/model-context/useInteractable.test.tsx +177 -0
  195. package/src/react/model-context/useInteractable.ts +3 -0
  196. package/src/react/primitive-hooks/useActionBarCopy.test.ts +0 -1
  197. package/src/react/primitive-hooks/useSuggestionTrigger.test.ts +0 -1
  198. package/src/react/primitives/message/MessageGroupedParts.test.tsx +96 -0
  199. package/src/react/primitives/message/MessageGroupedParts.tsx +15 -4
  200. package/src/react/primitives/part/PartMessages.test.tsx +104 -1
  201. package/src/react/primitives/part/PartMessages.tsx +1 -0
  202. package/src/react/primitives/thread/ThreadMessages.test.tsx +142 -0
  203. package/src/react/primitives/thread/ThreadMessages.tsx +8 -5
  204. package/src/react/providers/ReadonlyThreadProvider.test.tsx +56 -0
  205. package/src/react/runtimes/RemoteThreadListThreadListRuntimeCore.tsx +7 -1
  206. package/src/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.test.ts +20 -14
  207. package/src/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.test.tsx +221 -1
  208. package/src/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.ts +166 -512
  209. package/src/react/runtimes/cloud/CloudFileAttachmentAdapter.test.ts +77 -0
  210. package/src/react/runtimes/cloud/CloudFileAttachmentAdapter.ts +27 -1
  211. package/src/react/runtimes/cloud/auiV0.ts +160 -25
  212. package/src/react/runtimes/cloud/createCloudThreadListAdapter.test.ts +21 -0
  213. package/src/react/runtimes/cloud/createCloudThreadListAdapter.ts +7 -1
  214. package/src/react/runtimes/cloud/sdkIdentity.ts +9 -0
  215. package/src/react/runtimes/cloud/useCloudThreadListAdapter.test.tsx +18 -4
  216. package/src/react/runtimes/external-message-converter.test.ts +136 -1
  217. package/src/react/runtimes/external-message-converter.ts +39 -93
  218. package/src/react/runtimes/useRemoteThreadListRuntime.ts +1 -1
  219. package/src/react/utils/groupParts.ts +12 -1
  220. package/src/react/utils/useJSONEqual.ts +9 -0
  221. package/src/react/utils/useJSONSchemaDependency.ts +22 -0
  222. package/src/runtime/api/thread-runtime.test.ts +58 -0
  223. package/src/runtime/api/thread-runtime.ts +2 -4
  224. package/src/runtime/base/base-composer-runtime-core.ts +69 -16
  225. package/src/runtime/base/base-thread-runtime-core.test.ts +1008 -1
  226. package/src/runtime/base/base-thread-runtime-core.ts +222 -83
  227. package/src/runtime/interfaces/thread-runtime-core.ts +6 -0
  228. package/src/runtime/queue/message-queue.ts +68 -6
  229. package/src/runtime/utils/auto-status.test.ts +112 -1
  230. package/src/runtime/utils/auto-status.ts +31 -5
  231. package/src/runtime/utils/external-message-conversion.test.ts +134 -0
  232. package/src/runtime/utils/external-message-conversion.ts +122 -31
  233. package/src/runtime/utils/message-repository.test.ts +49 -0
  234. package/src/runtime/utils/message-repository.ts +3 -3
  235. package/src/runtime/utils/thread-message-like.test.ts +52 -0
  236. package/src/runtime/utils/thread-message-like.ts +4 -0
  237. package/src/runtimes/external-store/external-store-thread-runtime-core.ts +31 -1
  238. package/src/runtimes/local/local-thread-runtime-core.test.ts +21 -0
  239. package/src/runtimes/local/local-thread-runtime-core.ts +11 -1
  240. package/src/runtimes/tool-invocations/EDGE_CASES.md +2 -6
  241. package/src/runtimes/tool-invocations/ToolInvocationTracker.test.ts +133 -0
  242. package/src/runtimes/tool-invocations/ToolInvocationTracker.ts +10 -6
  243. package/src/store/clients/external-thread.ts +19 -1
  244. package/src/store/clients/thread-tasks.test.ts +274 -0
  245. package/src/store/clients/thread-tasks.ts +138 -0
  246. package/src/store/index.ts +8 -0
  247. package/src/store/primitive-predicates.test.ts +48 -5
  248. package/src/store/primitive-predicates.ts +7 -2
  249. package/src/store/runtime-clients/thread-runtime-client.ts +31 -1
  250. package/src/store/scope-registration.ts +2 -0
  251. package/src/store/scopes/task.ts +34 -0
  252. package/src/store/scopes/thread.ts +16 -0
  253. package/src/store/thread-tasks.test.tsx +209 -0
  254. package/src/subscribable/subscribable.test.ts +156 -1
  255. package/src/subscribable/subscribable.ts +25 -15
  256. package/src/tests/MessageRepository.test.ts +1 -5
  257. package/src/tests/auiV0Encode.test.ts +300 -0
  258. package/src/tests/base-composer-runtime-core-send.test.ts +51 -0
  259. package/src/tests/base-composer-runtime-core.test.ts +314 -2
  260. package/src/tests/external-store-thread-runtime-core-adapter.test.ts +151 -0
  261. package/src/tests/external-thread-attachments.test.tsx +69 -0
  262. package/src/tests/external-thread-parity.test.tsx +34 -0
  263. package/src/tests/groupParts.test.ts +71 -0
  264. package/src/tests/message-queue.test.ts +253 -0
  265. package/src/tests/remote-thread-list-reactive-threadId.test.ts +51 -0
  266. package/src/tests/useRemoteThreadListRuntime-controlled.test.tsx +43 -0
  267. package/src/types/index.ts +1 -0
  268. package/src/types/message.ts +8 -0
  269. package/src/utils/abortable-iterable.test.ts +115 -0
  270. package/src/utils/abortable-iterable.ts +34 -23
  271. package/src/utils/getGroupStatus.test.ts +70 -4
  272. package/src/utils/getGroupStatus.ts +35 -12
  273. package/src/utils/wire-media.test.ts +10 -0
  274. package/src/utils/wire-media.ts +6 -2
@@ -1 +1 @@
1
- {"version":3,"file":"speech.d.ts","names":[],"sources":["../../src/adapters/speech.ts"],"mappings":";;kBAGiB;OACH;IAEN;;IAGA;IACA;IACA;;OAGM;IACV,QAAQ;IACR;IACA,YAAY,yBAAyB;;;KAI7B;EACV,QAAQ,iBAAiB,uBAAuB;;kBAGjC;OACH;IAEN;;IAGA;IACA;;OAGM;IACV;IACA;;OAGU;IACV,QAAQ;IACR,YAAY;IACZ;IACA,gBAAgB,yBAAyB;IACzC,cAAc,WAAW,QAAQ,oBAAoB;IACrD,WAAW,WAAW,QAAQ,oBAAoB;;;KAI1C;EACV,cAAc,iBAAiB;EAC/B;;cAGW,qCAAqC;EAChD,MAAM,eAAe,uBAAuB;;UA4EpC,kCAAkC;EAC1C;EACA;EACA;EACA;EACA;EACA;;UAGQ;UACA;;QAGF;YACI;IACR,oBAAoB;IACpB,0BAA0B;;;cAWjB,qCAAqC;UACxC;UACA;UACA;EAGN,YAAA;IACE;IACA;IACA;;SAYG;EAIP,UAAU,iBAAiB"}
1
+ {"version":3,"file":"speech.d.ts","names":[],"sources":["../../src/adapters/speech.ts"],"mappings":";;kBAGiB;OACH;IAEN;;IAGA;IACA;IACA;;OAGM;IACV,QAAQ;IACR;IACA,YAAY,yBAAyB;;;KAI7B;EACV,QAAQ,iBAAiB,uBAAuB;;kBAGjC;OACH;IAEN;;IAGA;IACA;;OAGM;IACV;IACA;;OAGU;IACV,QAAQ;IACR,YAAY;IACZ;IACA,gBAAgB,yBAAyB;IACzC,cAAc,WAAW,QAAQ,oBAAoB;IACrD,WAAW,WAAW,QAAQ,oBAAoB;;;KAI1C;EACV,cAAc,iBAAiB;EAC/B;;cAGW,qCAAqC;EAChD,MAAM,eAAe,uBAAuB;;UA6EpC,kCAAkC;EAC1C;EACA;EACA;EACA;EACA;EACA;;UAGQ;UACA;;QAGF;YACI;IACR,oBAAoB;IACpB,0BAA0B;;;cAWjB,qCAAqC;UACxC;UACA;UACA;EAGN,YAAA;IACE;IACA;IACA;;SAYG;EAIP,UAAU,iBAAiB"}
@@ -19,6 +19,7 @@ var WebSpeechSynthesisAdapter = class {
19
19
  const res = {
20
20
  status: { type: "running" },
21
21
  cancel: () => {
22
+ if (res.status.type === "ended") return;
22
23
  window.speechSynthesis.cancel();
23
24
  handleEnd("cancelled");
24
25
  },
@@ -70,6 +71,8 @@ var WebSpeechDictationAdapter = class {
70
71
  const speechEndCallbacks = /* @__PURE__ */ new Set();
71
72
  const speechCallbacks = /* @__PURE__ */ new Set();
72
73
  let finalTranscript = "";
74
+ let hasInterimTranscript = false;
75
+ let firstInterimIndex = 0;
73
76
  const session = {
74
77
  status: { type: "starting" },
75
78
  stop: async () => {
@@ -115,18 +118,25 @@ var WebSpeechDictationAdapter = class {
115
118
  });
116
119
  recognition.addEventListener("result", (event) => {
117
120
  const speechEvent = event;
118
- for (let i = speechEvent.resultIndex; i < speechEvent.results.length; i++) {
121
+ let interimTranscript = "";
122
+ for (let i = firstInterimIndex; i < speechEvent.results.length; i++) {
119
123
  const result = speechEvent.results[i];
120
124
  if (!result) continue;
121
125
  const transcript = result[0]?.transcript ?? "";
122
126
  if (result.isFinal) {
127
+ firstInterimIndex = i + 1;
123
128
  finalTranscript += transcript;
129
+ hasInterimTranscript = false;
124
130
  notifyEventListeners(speechCallbacks, () => ({
125
131
  transcript,
126
132
  isFinal: true
127
133
  }), "Dictation");
128
- } else notifyEventListeners(speechCallbacks, () => ({
129
- transcript,
134
+ } else interimTranscript += transcript;
135
+ }
136
+ if (interimTranscript || hasInterimTranscript) {
137
+ hasInterimTranscript = interimTranscript.length > 0;
138
+ notifyEventListeners(speechCallbacks, () => ({
139
+ transcript: interimTranscript,
130
140
  isFinal: false
131
141
  }), "Dictation");
132
142
  }
@@ -1 +1 @@
1
- {"version":3,"file":"speech.js","names":["Unsubscribe","notifyEventListeners","SpeechSynthesisAdapter","Status","type","reason","error","Utterance","status","cancel","subscribe","callback","speak","text","DictationAdapter","Result","transcript","isFinal","Session","stop","Promise","onSpeechStart","onSpeechEnd","result","onSpeech","listen","disableInputDuringDictation","WebSpeechSynthesisAdapter","utterance","SpeechSynthesisUtterance","subscribers","Set","handleEnd","res","undefined","addEventListener","e","window","speechSynthesis","cancelled","queueMicrotask","add","delete","SpeechRecognitionResultItem","confidence","SpeechRecognitionResult","length","item","index","SpeechRecognitionResultList","SpeechRecognitionEvent","Event","resultIndex","results","SpeechRecognitionErrorEvent","message","SpeechRecognitionInstance","EventTarget","lang","continuous","interimResults","start","abort","SpeechRecognitionConstructor","global","Window","SpeechRecognition","webkitSpeechRecognition","getSpeechRecognitionAPI","WebSpeechDictationAdapter","_language","_continuous","_interimResults","constructor","options","language","defaultLanguage","navigator","isSupported","SpeechRecognitionAPI","Error","recognition","speechStartCallbacks","speechEndCallbacks","speechCallbacks","finalTranscript","session","resolve","checkEnded","setTimeout","updateStatus","newStatus","event","speechEvent","i","currentStatus","errorEvent","console"],"sources":["../../src/adapters/speech.ts"],"sourcesContent":["import type { Unsubscribe } from \"../types/unsubscribe\";\nimport { notifyEventListeners } from \"../utils/notify-event-listeners\";\n\nexport namespace SpeechSynthesisAdapter {\n export type Status =\n | {\n type: \"starting\" | \"running\";\n }\n | {\n type: \"ended\";\n reason: \"finished\" | \"cancelled\" | \"error\";\n error?: unknown;\n };\n\n export type Utterance = {\n status: Status;\n cancel: () => void;\n subscribe: (callback: () => void) => Unsubscribe;\n };\n}\n\nexport type SpeechSynthesisAdapter = {\n speak: (text: string) => SpeechSynthesisAdapter.Utterance;\n};\n\nexport namespace DictationAdapter {\n export type Status =\n | {\n type: \"starting\" | \"running\";\n }\n | {\n type: \"ended\";\n reason: \"stopped\" | \"cancelled\" | \"error\";\n };\n\n export type Result = {\n transcript: string;\n isFinal?: boolean;\n };\n\n export type Session = {\n status: Status;\n stop: () => Promise<void>;\n cancel: () => void;\n onSpeechStart: (callback: () => void) => Unsubscribe;\n onSpeechEnd: (callback: (result: Result) => void) => Unsubscribe;\n onSpeech: (callback: (result: Result) => void) => Unsubscribe;\n };\n}\n\nexport type DictationAdapter = {\n listen: () => DictationAdapter.Session;\n disableInputDuringDictation?: boolean;\n};\n\nexport class WebSpeechSynthesisAdapter implements SpeechSynthesisAdapter {\n speak(text: string): SpeechSynthesisAdapter.Utterance {\n const utterance = new SpeechSynthesisUtterance(text);\n\n const subscribers = new Set<() => void>();\n const handleEnd = (\n reason: \"finished\" | \"error\" | \"cancelled\",\n error?: unknown,\n ) => {\n if (res.status.type === \"ended\") return;\n\n res.status = { type: \"ended\", reason, error };\n notifyEventListeners(subscribers, undefined, \"Speech synthesis\");\n };\n\n utterance.addEventListener(\"end\", () => handleEnd(\"finished\"));\n utterance.addEventListener(\"error\", (e) => handleEnd(\"error\", e.error));\n\n window.speechSynthesis.speak(utterance);\n\n const res: SpeechSynthesisAdapter.Utterance = {\n status: { type: \"running\" },\n cancel: () => {\n window.speechSynthesis.cancel();\n handleEnd(\"cancelled\");\n },\n subscribe: (callback) => {\n if (res.status.type === \"ended\") {\n let cancelled = false;\n queueMicrotask(() => {\n if (!cancelled) {\n notifyEventListeners([callback], undefined, \"Speech synthesis\");\n }\n });\n return () => {\n cancelled = true;\n };\n } else {\n subscribers.add(callback);\n return () => {\n subscribers.delete(callback);\n };\n }\n },\n };\n return res;\n }\n}\n\ninterface SpeechRecognitionResultItem {\n transcript: string;\n confidence: number;\n}\n\ninterface SpeechRecognitionResult {\n readonly length: number;\n item(index: number): SpeechRecognitionResultItem;\n readonly isFinal: boolean;\n [index: number]: SpeechRecognitionResultItem;\n}\n\ninterface SpeechRecognitionResultList {\n readonly length: number;\n item(index: number): SpeechRecognitionResult;\n [index: number]: SpeechRecognitionResult;\n}\n\ninterface SpeechRecognitionEvent extends Event {\n readonly resultIndex: number;\n readonly results: SpeechRecognitionResultList;\n}\n\ninterface SpeechRecognitionErrorEvent extends Event {\n readonly error: string;\n readonly message: string;\n}\n\ninterface SpeechRecognitionInstance extends EventTarget {\n lang: string;\n continuous: boolean;\n interimResults: boolean;\n start(): void;\n stop(): void;\n abort(): void;\n}\n\ninterface SpeechRecognitionConstructor {\n new (): SpeechRecognitionInstance;\n}\n\ndeclare global {\n interface Window {\n SpeechRecognition?: SpeechRecognitionConstructor;\n webkitSpeechRecognition?: SpeechRecognitionConstructor;\n }\n}\n\nconst getSpeechRecognitionAPI = ():\n | SpeechRecognitionConstructor\n | undefined => {\n if (typeof window === \"undefined\") return undefined;\n return window.SpeechRecognition ?? window.webkitSpeechRecognition;\n};\n\nexport class WebSpeechDictationAdapter implements DictationAdapter {\n private _language: string;\n private _continuous: boolean;\n private _interimResults: boolean;\n\n constructor(\n options: {\n language?: string;\n continuous?: boolean;\n interimResults?: boolean;\n } = {},\n ) {\n const defaultLanguage =\n typeof navigator !== \"undefined\" && navigator.language\n ? navigator.language\n : \"en-US\";\n this._language = options.language ?? defaultLanguage;\n this._continuous = options.continuous ?? true;\n this._interimResults = options.interimResults ?? true;\n }\n\n static isSupported(): boolean {\n return getSpeechRecognitionAPI() !== undefined;\n }\n\n listen(): DictationAdapter.Session {\n const SpeechRecognitionAPI = getSpeechRecognitionAPI();\n if (!SpeechRecognitionAPI) {\n throw new Error(\n \"SpeechRecognition is not supported in this browser. \" +\n \"Try using Chrome, Edge, or Safari.\",\n );\n }\n\n const recognition = new SpeechRecognitionAPI();\n recognition.lang = this._language;\n recognition.continuous = this._continuous;\n recognition.interimResults = this._interimResults;\n\n const speechStartCallbacks = new Set<() => void>();\n const speechEndCallbacks = new Set<\n (result: DictationAdapter.Result) => void\n >();\n const speechCallbacks = new Set<\n (result: DictationAdapter.Result) => void\n >();\n\n let finalTranscript = \"\";\n\n const session: DictationAdapter.Session = {\n status: { type: \"starting\" },\n\n stop: async () => {\n recognition.stop();\n return new Promise<void>((resolve) => {\n const checkEnded = () => {\n if (session.status.type === \"ended\") {\n resolve();\n } else {\n setTimeout(checkEnded, 50);\n }\n };\n checkEnded();\n });\n },\n\n cancel: () => {\n recognition.abort();\n },\n\n onSpeechStart: (callback: () => void): Unsubscribe => {\n speechStartCallbacks.add(callback);\n return () => {\n speechStartCallbacks.delete(callback);\n };\n },\n\n onSpeechEnd: (\n callback: (result: DictationAdapter.Result) => void,\n ): Unsubscribe => {\n speechEndCallbacks.add(callback);\n return () => {\n speechEndCallbacks.delete(callback);\n };\n },\n\n onSpeech: (\n callback: (result: DictationAdapter.Result) => void,\n ): Unsubscribe => {\n speechCallbacks.add(callback);\n return () => {\n speechCallbacks.delete(callback);\n };\n },\n };\n\n const updateStatus = (newStatus: DictationAdapter.Status) => {\n session.status = newStatus;\n };\n\n recognition.addEventListener(\"speechstart\", () => {\n notifyEventListeners(speechStartCallbacks, undefined, \"Dictation\");\n });\n\n recognition.addEventListener(\"start\", () => {\n updateStatus({ type: \"running\" });\n });\n\n recognition.addEventListener(\"result\", (event) => {\n const speechEvent = event as unknown as SpeechRecognitionEvent;\n\n for (\n let i = speechEvent.resultIndex;\n i < speechEvent.results.length;\n i++\n ) {\n const result = speechEvent.results[i];\n if (!result) continue;\n\n const transcript = result[0]?.transcript ?? \"\";\n\n if (result.isFinal) {\n finalTranscript += transcript;\n notifyEventListeners(\n speechCallbacks,\n () => ({ transcript, isFinal: true }),\n \"Dictation\",\n );\n } else {\n notifyEventListeners(\n speechCallbacks,\n () => ({ transcript, isFinal: false }),\n \"Dictation\",\n );\n }\n }\n });\n\n recognition.addEventListener(\"speechend\", () => {\n // speechend fires when user stops speaking, but 'end' handles final cleanup\n });\n\n recognition.addEventListener(\"end\", () => {\n const currentStatus = session.status;\n if (currentStatus.type !== \"ended\") {\n updateStatus({ type: \"ended\", reason: \"stopped\" });\n }\n if (finalTranscript) {\n notifyEventListeners(\n speechEndCallbacks,\n () => ({ transcript: finalTranscript }),\n \"Dictation\",\n );\n finalTranscript = \"\";\n }\n });\n\n recognition.addEventListener(\"error\", (event) => {\n const errorEvent = event as unknown as SpeechRecognitionErrorEvent;\n if (errorEvent.error === \"aborted\") {\n updateStatus({ type: \"ended\", reason: \"cancelled\" });\n } else {\n updateStatus({ type: \"ended\", reason: \"error\" });\n console.error(\"Dictation error:\", errorEvent.error, errorEvent.message);\n }\n });\n\n try {\n recognition.start();\n } catch (error) {\n updateStatus({ type: \"ended\", reason: \"error\" });\n throw error;\n }\n\n return session;\n }\n}\n"],"mappings":";;AAuDA,IAAa2B,4BAAb,MAAyE;CACvEf,MAAMC,MAAgD;EACpD,MAAMe,YAAY,IAAIC,yBAAyBhB,IAAI;EAEnD,MAAMiB,8BAAc,IAAIC,IAAgB;EACxC,MAAMC,aACJ3B,QACAC,UACG;GACH,IAAI2B,IAAIzB,OAAOJ,SAAS,SAAS;GAEjC6B,IAAIzB,SAAS;IAAEJ,MAAM;IAASC;IAAQC;GAAM;GAC5CL,qBAAqB6B,aAAaI,KAAAA,GAAW,kBAAkB;EACjE;EAEAN,UAAUO,iBAAiB,aAAaH,UAAU,UAAU,CAAC;EAC7DJ,UAAUO,iBAAiB,UAAUC,MAAMJ,UAAU,SAASI,EAAE9B,KAAK,CAAC;EAEtE+B,OAAOC,gBAAgB1B,MAAMgB,SAAS;EAEtC,MAA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O;MAAEpE;MAAYC,SAAS;KAAK,IACnC,WACF;IACF,OACEhB,qBACEmF,wBACO;KAAEpE;KAAYC,SAAS;IAAM,IACpC,WACF;GAEJ;EACF,CAAC;EAEDgE,YAAY9C,iBAAiB,mBAAmB,CAC9C,CACD;EAED8C,YAAY9C,iBAAiB,aAAa;GAExC,IADsBmD,QAAQ9E,OACZJ,SAAS,SACzBsF,aAAa;IAAEtF,MAAM;IAASC,QAAQ;GAAU,CAAC;GAEnD,IAAIgF,iBAAiB;IACnBpF,qBACEkF,2BACO,EAAEnE,YAAYqE,gBAAgB,IACrC,WACF;IACAA,kBAAkB;GACpB;EACF,CAAC;EAEDJ,YAAY9C,iBAAiB,UAAUyD,UAAU;GAC/C,MAAMI,aAAaJ;GACnB,IAAII,WAAW1F,UAAU,WACvBoF,aAAa;IAAEtF,MAAM;IAASC,QAAQ;GAAY,CAAC;QAC9C;IACLqF,aAAa;KAAEtF,MAAM;KAASC,QAAQ;IAAQ,CAAC;IAC/C4F,QAAQ3F,MAAM,oBAAoB0F,WAAW1F,OAAO0F,WAAWzC,OAAO;GACxE;EACF,CAAC;EAED,IAAI;GACF0B,YAAYpB,MAAM;EACpB,SAASvD,OAAO;GACdoF,aAAa;IAAEtF,MAAM;IAASC,QAAQ;GAAQ,CAAC;GAC/C,MAAMC;EACR;EAEA,OAAOgF;CACT;AACF"}
1
+ {"version":3,"file":"speech.js","names":["Unsubscribe","notifyEventListeners","SpeechSynthesisAdapter","Status","type","reason","error","Utterance","status","cancel","subscribe","callback","speak","text","DictationAdapter","Result","transcript","isFinal","Session","stop","Promise","onSpeechStart","onSpeechEnd","result","onSpeech","listen","disableInputDuringDictation","WebSpeechSynthesisAdapter","utterance","SpeechSynthesisUtterance","subscribers","Set","handleEnd","res","undefined","addEventListener","e","window","speechSynthesis","cancelled","queueMicrotask","add","delete","SpeechRecognitionResultItem","confidence","SpeechRecognitionResult","length","item","index","SpeechRecognitionResultList","SpeechRecognitionEvent","Event","resultIndex","results","SpeechRecognitionErrorEvent","message","SpeechRecognitionInstance","EventTarget","lang","continuous","interimResults","start","abort","SpeechRecognitionConstructor","global","Window","SpeechRecognition","webkitSpeechRecognition","getSpeechRecognitionAPI","WebSpeechDictationAdapter","_language","_continuous","_interimResults","constructor","options","language","defaultLanguage","navigator","isSupported","SpeechRecognitionAPI","Error","recognition","speechStartCallbacks","speechEndCallbacks","speechCallbacks","finalTranscript","hasInterimTranscript","firstInterimIndex","session","resolve","checkEnded","setTimeout","updateStatus","newStatus","event","speechEvent","interimTranscript","i","currentStatus","errorEvent","console"],"sources":["../../src/adapters/speech.ts"],"sourcesContent":["import type { Unsubscribe } from \"../types/unsubscribe\";\nimport { notifyEventListeners } from \"../utils/notify-event-listeners\";\n\nexport namespace SpeechSynthesisAdapter {\n export type Status =\n | {\n type: \"starting\" | \"running\";\n }\n | {\n type: \"ended\";\n reason: \"finished\" | \"cancelled\" | \"error\";\n error?: unknown;\n };\n\n export type Utterance = {\n status: Status;\n cancel: () => void;\n subscribe: (callback: () => void) => Unsubscribe;\n };\n}\n\nexport type SpeechSynthesisAdapter = {\n speak: (text: string) => SpeechSynthesisAdapter.Utterance;\n};\n\nexport namespace DictationAdapter {\n export type Status =\n | {\n type: \"starting\" | \"running\";\n }\n | {\n type: \"ended\";\n reason: \"stopped\" | \"cancelled\" | \"error\";\n };\n\n export type Result = {\n transcript: string;\n isFinal?: boolean;\n };\n\n export type Session = {\n status: Status;\n stop: () => Promise<void>;\n cancel: () => void;\n onSpeechStart: (callback: () => void) => Unsubscribe;\n onSpeechEnd: (callback: (result: Result) => void) => Unsubscribe;\n onSpeech: (callback: (result: Result) => void) => Unsubscribe;\n };\n}\n\nexport type DictationAdapter = {\n listen: () => DictationAdapter.Session;\n disableInputDuringDictation?: boolean;\n};\n\nexport class WebSpeechSynthesisAdapter implements SpeechSynthesisAdapter {\n speak(text: string): SpeechSynthesisAdapter.Utterance {\n const utterance = new SpeechSynthesisUtterance(text);\n\n const subscribers = new Set<() => void>();\n const handleEnd = (\n reason: \"finished\" | \"error\" | \"cancelled\",\n error?: unknown,\n ) => {\n if (res.status.type === \"ended\") return;\n\n res.status = { type: \"ended\", reason, error };\n notifyEventListeners(subscribers, undefined, \"Speech synthesis\");\n };\n\n utterance.addEventListener(\"end\", () => handleEnd(\"finished\"));\n utterance.addEventListener(\"error\", (e) => handleEnd(\"error\", e.error));\n\n window.speechSynthesis.speak(utterance);\n\n const res: SpeechSynthesisAdapter.Utterance = {\n status: { type: \"running\" },\n cancel: () => {\n if (res.status.type === \"ended\") return;\n window.speechSynthesis.cancel();\n handleEnd(\"cancelled\");\n },\n subscribe: (callback) => {\n if (res.status.type === \"ended\") {\n let cancelled = false;\n queueMicrotask(() => {\n if (!cancelled) {\n notifyEventListeners([callback], undefined, \"Speech synthesis\");\n }\n });\n return () => {\n cancelled = true;\n };\n } else {\n subscribers.add(callback);\n return () => {\n subscribers.delete(callback);\n };\n }\n },\n };\n return res;\n }\n}\n\ninterface SpeechRecognitionResultItem {\n transcript: string;\n confidence: number;\n}\n\ninterface SpeechRecognitionResult {\n readonly length: number;\n item(index: number): SpeechRecognitionResultItem;\n readonly isFinal: boolean;\n [index: number]: SpeechRecognitionResultItem;\n}\n\ninterface SpeechRecognitionResultList {\n readonly length: number;\n item(index: number): SpeechRecognitionResult;\n [index: number]: SpeechRecognitionResult;\n}\n\ninterface SpeechRecognitionEvent extends Event {\n readonly resultIndex: number;\n readonly results: SpeechRecognitionResultList;\n}\n\ninterface SpeechRecognitionErrorEvent extends Event {\n readonly error: string;\n readonly message: string;\n}\n\ninterface SpeechRecognitionInstance extends EventTarget {\n lang: string;\n continuous: boolean;\n interimResults: boolean;\n start(): void;\n stop(): void;\n abort(): void;\n}\n\ninterface SpeechRecognitionConstructor {\n new (): SpeechRecognitionInstance;\n}\n\ndeclare global {\n interface Window {\n SpeechRecognition?: SpeechRecognitionConstructor;\n webkitSpeechRecognition?: SpeechRecognitionConstructor;\n }\n}\n\nconst getSpeechRecognitionAPI = ():\n | SpeechRecognitionConstructor\n | undefined => {\n if (typeof window === \"undefined\") return undefined;\n return window.SpeechRecognition ?? window.webkitSpeechRecognition;\n};\n\nexport class WebSpeechDictationAdapter implements DictationAdapter {\n private _language: string;\n private _continuous: boolean;\n private _interimResults: boolean;\n\n constructor(\n options: {\n language?: string;\n continuous?: boolean;\n interimResults?: boolean;\n } = {},\n ) {\n const defaultLanguage =\n typeof navigator !== \"undefined\" && navigator.language\n ? navigator.language\n : \"en-US\";\n this._language = options.language ?? defaultLanguage;\n this._continuous = options.continuous ?? true;\n this._interimResults = options.interimResults ?? true;\n }\n\n static isSupported(): boolean {\n return getSpeechRecognitionAPI() !== undefined;\n }\n\n listen(): DictationAdapter.Session {\n const SpeechRecognitionAPI = getSpeechRecognitionAPI();\n if (!SpeechRecognitionAPI) {\n throw new Error(\n \"SpeechRecognition is not supported in this browser. \" +\n \"Try using Chrome, Edge, or Safari.\",\n );\n }\n\n const recognition = new SpeechRecognitionAPI();\n recognition.lang = this._language;\n recognition.continuous = this._continuous;\n recognition.interimResults = this._interimResults;\n\n const speechStartCallbacks = new Set<() => void>();\n const speechEndCallbacks = new Set<\n (result: DictationAdapter.Result) => void\n >();\n const speechCallbacks = new Set<\n (result: DictationAdapter.Result) => void\n >();\n\n let finalTranscript = \"\";\n let hasInterimTranscript = false;\n let firstInterimIndex = 0;\n\n const session: DictationAdapter.Session = {\n status: { type: \"starting\" },\n\n stop: async () => {\n recognition.stop();\n return new Promise<void>((resolve) => {\n const checkEnded = () => {\n if (session.status.type === \"ended\") {\n resolve();\n } else {\n setTimeout(checkEnded, 50);\n }\n };\n checkEnded();\n });\n },\n\n cancel: () => {\n recognition.abort();\n },\n\n onSpeechStart: (callback: () => void): Unsubscribe => {\n speechStartCallbacks.add(callback);\n return () => {\n speechStartCallbacks.delete(callback);\n };\n },\n\n onSpeechEnd: (\n callback: (result: DictationAdapter.Result) => void,\n ): Unsubscribe => {\n speechEndCallbacks.add(callback);\n return () => {\n speechEndCallbacks.delete(callback);\n };\n },\n\n onSpeech: (\n callback: (result: DictationAdapter.Result) => void,\n ): Unsubscribe => {\n speechCallbacks.add(callback);\n return () => {\n speechCallbacks.delete(callback);\n };\n },\n };\n\n const updateStatus = (newStatus: DictationAdapter.Status) => {\n session.status = newStatus;\n };\n\n recognition.addEventListener(\"speechstart\", () => {\n notifyEventListeners(speechStartCallbacks, undefined, \"Dictation\");\n });\n\n recognition.addEventListener(\"start\", () => {\n updateStatus({ type: \"running\" });\n });\n\n recognition.addEventListener(\"result\", (event) => {\n const speechEvent = event as unknown as SpeechRecognitionEvent;\n let interimTranscript = \"\";\n\n for (let i = firstInterimIndex; i < speechEvent.results.length; i++) {\n const result = speechEvent.results[i];\n if (!result) continue;\n\n const transcript = result[0]?.transcript ?? \"\";\n\n if (result.isFinal) {\n firstInterimIndex = i + 1;\n finalTranscript += transcript;\n hasInterimTranscript = false;\n notifyEventListeners(\n speechCallbacks,\n () => ({ transcript, isFinal: true }),\n \"Dictation\",\n );\n } else {\n interimTranscript += transcript;\n }\n }\n\n if (interimTranscript || hasInterimTranscript) {\n hasInterimTranscript = interimTranscript.length > 0;\n notifyEventListeners(\n speechCallbacks,\n () => ({ transcript: interimTranscript, isFinal: false }),\n \"Dictation\",\n );\n }\n });\n\n recognition.addEventListener(\"speechend\", () => {\n // speechend fires when user stops speaking, but 'end' handles final cleanup\n });\n\n recognition.addEventListener(\"end\", () => {\n const currentStatus = session.status;\n if (currentStatus.type !== \"ended\") {\n updateStatus({ type: \"ended\", reason: \"stopped\" });\n }\n if (finalTranscript) {\n notifyEventListeners(\n speechEndCallbacks,\n () => ({ transcript: finalTranscript }),\n \"Dictation\",\n );\n finalTranscript = \"\";\n }\n });\n\n recognition.addEventListener(\"error\", (event) => {\n const errorEvent = event as unknown as SpeechRecognitionErrorEvent;\n if (errorEvent.error === \"aborted\") {\n updateStatus({ type: \"ended\", reason: \"cancelled\" });\n } else {\n updateStatus({ type: \"ended\", reason: \"error\" });\n console.error(\"Dictation error:\", errorEvent.error, errorEvent.message);\n }\n });\n\n try {\n recognition.start();\n } catch (error) {\n updateStatus({ type: \"ended\", reason: \"error\" });\n throw error;\n }\n\n return session;\n }\n}\n"],"mappings":";;AAuDA,IAAa2B,4BAAb,MAAyE;CACvEf,MAAMC,MAAgD;EACpD,MAAMe,YAAY,IAAIC,yBAAyBhB,IAAI;EAEnD,MAAMiB,8BAAc,IAAIC,IAAgB;EACxC,MAAMC,aACJ3B,QACAC,UACG;GACH,IAAI2B,IAAIzB,OAAOJ,SAAS,SAAS;GAEjC6B,IAAIzB,SAAS;IAAEJ,MAAM;IAASC;IAAQC;GAAM;GAC5CL,qBAAqB6B,aAAaI,KAAAA,GAAW,kBAAkB;EACjE;EAEAN,UAAUO,iBAAiB,aAAaH,UAAU,UAAU,CAAC;EAC7DJ,UAAUO,iBAAiB,UAAUC,MAAMJ,UAAU,SAASI,EAAE9B,KAAK,CAAC;EAEtE+B,OAAOC,gBAAgB1B,MAAMgB,SAAS;EAEtC,MAAMK,MAAwC;GAC5CzB,QAAQ,EAAEJ,MAAM,UAAU;GAC1BK,cAAc;IACZ,IAAIwB,IAAIzB,OAAOJ,SAAS,SAAS;IACjCiC,OAAOC,gBAAgB7B,OAAO;IAC9BuB,UAAU,WAAW;GACvB;GACAtB,YAAYC,aAAa;IACvB,IAAIsB,IAAIzB,OAAOJ,SAAS,SAAS;KAC/B,IAAImC,YAAY;KAChBC,qBAAqB;MACnB,IAAI,CAACD,WACHtC,qBAAqB,CAACU,QAAQ,GAAGuB,KAAAA,GAAW,kBAAkB;KAElE,CAAC;KACD,aAAa;MACXK,YAAY;KACd;IACF,OAAO;KACLT,YAAYW,IAAI9B,QAAQ;KACxB,aAAa;MACXmB,YAAYY,OAAO/B,QAAQ;KAC7B;IACF;GACF;EACF;EACA,OAAOsB;CACT;AACF;AAkDA,MAAMmC,gCAEW;CACf,IAAI,OAAO/B,WAAW,aAAa,OAAOH,KAAAA;CAC1C,OAAOG,OAAO6B,qBAAqB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gB,IACrC,WACF;IACAA,kBAAkB;GACpB;EACF,CAAC;EAEDJ,YAAY9C,iBAAiB,UAAU2D,UAAU;GAC/C,MAAMK,aAAaL;GACnB,IAAIK,WAAW7F,UAAU,WACvBsF,aAAa;IAAExF,MAAM;IAASC,QAAQ;GAAY,CAAC;QAC9C;IACLuF,aAAa;KAAExF,MAAM;KAASC,QAAQ;IAAQ,CAAC;IAC/C+F,QAAQ9F,MAAM,oBAAoB6F,WAAW7F,OAAO6F,WAAW5C,OAAO;GACxE;EACF,CAAC;EAED,IAAI;GACF0B,YAAYpB,MAAM;EACpB,SAASvD,OAAO;GACdsF,aAAa;IAAExF,MAAM;IAASC,QAAQ;GAAQ,CAAC;GAC/C,MAAMC;EACR;EAEA,OAAOkF;CACT;AACF"}
@@ -1,5 +1,7 @@
1
+ import { ThreadMessage } from "../types/message.js";
1
2
  import { ChatModelRunOptions, ChatModelRunResult } from "../runtime/utils/chat-model-adapter.js";
2
3
  import { ExportedMessageRepository, ExportedMessageRepositoryItem } from "../runtime/utils/message-repository.js";
4
+ import "../types/index.js";
3
5
  import { ReadonlyJSONValue } from "assistant-stream/utils";
4
6
  //#region src/adapters/thread-history.d.ts
5
7
  interface MessageStorageEntry<TPayload> {
@@ -35,6 +37,8 @@ type GenericThreadHistoryAdapter<TMessage> = {
35
37
  start_ms: number;
36
38
  end_ms: number;
37
39
  }[];
40
+ /** The thread message the items were persisted from; its status and timing complete a report the stored format cannot carry. */
41
+ message?: ThreadMessage;
38
42
  }): void;
39
43
  };
40
44
  type ThreadHistoryAdapter = {
@@ -1 +1 @@
1
- {"version":3,"file":"thread-history.d.ts","names":[],"sources":["../../src/adapters/thread-history.ts"],"mappings":";;;;UAUiB,oBAAoB;EACnC;EACA;EACA;EACA,SAAS;;UAGM,kBAAkB;EACjC;EACA,SAAS;;UAGM,wBAAwB;EACvC;EACA,UAAU,kBAAkB;;UAGb,qBACf,UACA,uBAAuB;EAEvB;EACA,OAAO,MAAM,kBAAkB,YAAY;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;EAEjD,YAAY,UAAU,uBAAuB,yBAC3C,eAAe,qBAAqB,UAAU,kBAC7C,4BAA4B"}
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /// <reference path="./store/scope-registration.d.ts" />
2
- import { AppendMessage, DataMessagePart, FileMessagePart, GenerativeUIMessagePart, GenerativeUINode, GenerativeUISpec, ImageMessagePart, MCP_APP_URI_SCHEME, McpAppMetadata, MessagePartStatus, MessagePartStreamStatus, MessageRole, MessageStatus, MessageTiming, PartProviderMetadata, ReasoningMessagePart, RunConfig, SourceMessagePart, SourceProviderMetadata, TextMessagePart, ThreadAssistantMessage, ThreadAssistantMessagePart, ThreadMessage, ThreadStep, ThreadSystemMessage, ThreadUserMessage, ThreadUserMessagePart, ToolApprovalDisplay, ToolApprovalOption, ToolApprovalOptionKind, ToolApprovalResponse, ToolCallMessagePart, ToolCallMessagePartMcpMetadata, ToolCallMessagePartStatus, ToolCallTiming, ToolModelContentPart, Unstable_AudioMessagePart, isMcpAppUri, toolApprovalAcceptsText } from "./types/message.js";
2
+ import { AppendMessage, DataMessagePart, FileMessagePart, GenerativeUIMessagePart, GenerativeUINode, GenerativeUISpec, ImageMessagePart, MCP_APP_URI_SCHEME, McpAppMetadata, MessageModality, MessagePartStatus, MessagePartStreamStatus, MessageRole, MessageStatus, MessageTiming, PartProviderMetadata, ReasoningMessagePart, RunConfig, SourceMessagePart, SourceProviderMetadata, TextMessagePart, ThreadAssistantMessage, ThreadAssistantMessagePart, ThreadMessage, ThreadStep, ThreadSystemMessage, ThreadUserMessage, ThreadUserMessagePart, ToolApprovalDisplay, ToolApprovalOption, ToolApprovalOptionKind, ToolApprovalResponse, ToolCallMessagePart, ToolCallMessagePartMcpMetadata, ToolCallMessagePartStatus, ToolCallTiming, ToolModelContentPart, Unstable_AudioMessagePart, isMcpAppUri, toolApprovalAcceptsText } from "./types/message.js";
3
3
  import { Attachment, AttachmentStatus, CompleteAttachment, CompleteAttachmentStatus, CreateAttachment, PendingAttachment, PendingAttachmentStatus } from "./types/attachment.js";
4
4
  import { AttachmentAdapter, CompositeAttachmentAdapter, SimpleImageAttachmentAdapter, SimpleTextAttachmentAdapter } from "./adapters/attachment.js";
5
5
  import { Unstable_TriggerCategory, Unstable_TriggerItem } from "./types/trigger.js";
@@ -53,4 +53,4 @@ import { ExternalStoreSharedOptions, pickExternalStoreSharedOptions } from "./ru
53
53
  import { MessageQueueController, MessageQueueDriver, createMessageQueue } from "./runtime/queue/message-queue.js";
54
54
  import { InMemoryThreadListAdapter } from "./runtimes/remote-thread-list/adapter/in-memory.js";
55
55
  import { createRequestHeaders } from "./runtimes/assistant-transport/utils.js";
56
- export { type AddToolResultOptions, type AppendMessage, type Assistant, type AssistantContextConfig, type AssistantError, type AssistantErrorCode, AssistantFrameHost, AssistantFrameProvider, type AssistantInstructionsConfig, type AssistantRuntime, type AssistantRuntimeCore, type AssistantToolProps, type Attachment, type AttachmentAdapter, type AttachmentAddErrorEvent, type AttachmentAddErrorReason, type AttachmentRuntime, type AttachmentRuntimePath, type AttachmentState, type AttachmentStatus, type ChatModelAdapter, type ChatModelRunOptions, type ChatModelRunResult, type ChatModelRunUpdate, type CompleteAttachment, type CompleteAttachmentStatus, type ComposerRuntime, type ComposerRuntimeCore, type ComposerRuntimeEventCallback, type ComposerRuntimeEventPayload, type ComposerRuntimeEventType, type ComposerRuntimePath, type ComposerState, CompositeAttachmentAdapter, type CoreChatModelRunResult, type CreateAppendMessage, type CreateAttachment, type CreateResumeRunConfig, type CreateStartRunConfig, type CreateSuggestionAdapterOptions, type DataMessagePart, type DictationAdapter, type DictationState, type EditComposerRuntime, type EditComposerRuntimeCore, type EditComposerState, type ErrorDisplay, type ErrorSeverity, ExportedMessageRepository, type ExportedMessageRepositoryItem, type ExternalStoreAdapter, type ExternalStoreBranchChange, type ExternalStoreMessageConverter, type ExternalStoreSharedOptions, type ExternalStoreThreadData, type ExternalStoreThreadListAdapter, type ExternalThreadBranchAdapter, type ExternalThreadQueueAdapter, FRAME_MESSAGE_CHANNEL, type FeedbackAdapter, type FileMessagePart, type FrameMessage, type FrameMessageType, type GenerativeUIMessagePart, type GenerativeUINode, type GenerativeUISpec, type GenericThreadHistoryAdapter, type ImageMessagePart, InMemoryThreadListAdapter, type LanguageModelConfig, type LanguageModelV1CallSettings, type LocalRuntimeOptionsBase, MCP_APP_URI_SCHEME, type McpAppMetadata, type MessageFormatAdapter, type MessageFormatItem, type MessageFormatRepository, MessageNotSentError, type MessagePartRuntime, type MessagePartRuntimePath, type MessagePartState, type MessagePartStatus, type MessagePartStreamStatus, type MessageQueueController, type MessageQueueDriver, type MessageRole, type MessageRuntime, type MessageRuntimePath, type MessageState, type MessageStatus, type MessageStorageEntry, type MessageTiming, type ModelContext, type ModelContextProvider, ModelContextRegistry, type ModelContextRegistryInstructionHandle, type ModelContextRegistryProviderHandle, type ModelContextRegistryToolHandle, type PartProviderMetadata, type PendingAttachment, type PendingAttachmentStatus, type QueuePlacement, type QuoteInfo, type RealtimeVoiceAdapter, type ReasoningMessagePart, type RemoteThreadInitializeResponse, type RemoteThreadListAdapter, type RemoteThreadListOptions, type RemoteThreadListPageOptions, type RemoteThreadListProviderComponent, type RemoteThreadListResponse, type RemoteThreadMetadata, type RespondToToolApprovalOptions, type ResumeRunConfig, type ResumeToolCallOptions, type RunConfig, type RuntimeAdapters, type RuntimeCapabilities, type SendOptions, type SerializedModelContext, type SerializedTool, SimpleImageAttachmentAdapter, SimpleTextAttachmentAdapter, type SourceMessagePart, type SourceProviderMetadata, type SpeechState, type SpeechSynthesisAdapter, type StartRunConfig, type StreamingTimingAccessors, type StreamingTimingOptions, type StreamingTimingState, type SubmitFeedbackOptions, type SubmittedFeedback, type SuggestionAdapter, type SuggestionAdapterGenerateOptions, type TextMessagePart, type ThreadAssistantMessage, type ThreadAssistantMessagePart, type ThreadComposerRuntime, type ThreadComposerRuntimeCore, type ThreadComposerState, type ThreadHistoryAdapter, type ThreadListItemCoreState, type ThreadListItemEventCallback, type ThreadListItemEventPayload, type ThreadListItemEventType, type ThreadListItemGenerateTitleOptions, type ThreadListItemRuntime, type ThreadListItemRuntimePath, type ThreadListItemState, type ThreadListItemStatus, type ThreadListRuntime, type ThreadListRuntimeCore, type ThreadListState, type ThreadMessage, type ThreadMessageLike, type ThreadRuntime, type ThreadRuntimeCore, type ThreadRuntimeEventCallback, type ThreadRuntimeEventPayload, type ThreadRuntimeEventType, type ThreadRuntimePath, type ThreadState, type ThreadStep, type ThreadSuggestion, type ThreadSystemMessage, type ThreadUserMessage, type ThreadUserMessagePart, type ToolApprovalDisplay, type ToolApprovalOption, type ToolApprovalOptionKind, type ToolApprovalResponse, type ToolCallMessagePart, type ToolCallMessagePartMcpMetadata, type ToolCallMessagePartStatus, type ToolCallTiming, type ToolExecutionStatus, type ToolModelContentPart, type Unstable_AudioMessagePart, type Unstable_DirectiveFormatter, type Unstable_DirectiveSegment, type Unstable_InteractableSnapshotEntry, type Unstable_InteractableVersion, type Unstable_TriggerAdapter, type Unstable_TriggerCategory, type Unstable_TriggerItem, type Unsubscribe, type UserCommands, type UserExternalState, type VoiceSessionControls, type VoiceSessionHelpers, type VoiceSessionState, WebSpeechDictationAdapter, WebSpeechSynthesisAdapter, bindExternalStoreMessage, createMessageQueue, createRequestHeaders, createSuggestionAdapter, createVoiceSession, fromThreadMessageLike, generateId, getExternalStoreMessages, isAssistantError, isMcpAppUri, isMessageNotSentError, mergeModelContexts, pickExternalStoreSharedOptions, stepStreamingTiming, toAssistantError, tool, toolApprovalAcceptsText, unstable_defaultDirectiveFormatter, unstable_formatInteractableSnapshot, unstable_getInteractableSnapshots, unstable_getInteractableVersions };
56
+ export { type AddToolResultOptions, type AppendMessage, type Assistant, type AssistantContextConfig, type AssistantError, type AssistantErrorCode, AssistantFrameHost, AssistantFrameProvider, type AssistantInstructionsConfig, type AssistantRuntime, type AssistantRuntimeCore, type AssistantToolProps, type Attachment, type AttachmentAdapter, type AttachmentAddErrorEvent, type AttachmentAddErrorReason, type AttachmentRuntime, type AttachmentRuntimePath, type AttachmentState, type AttachmentStatus, type ChatModelAdapter, type ChatModelRunOptions, type ChatModelRunResult, type ChatModelRunUpdate, type CompleteAttachment, type CompleteAttachmentStatus, type ComposerRuntime, type ComposerRuntimeCore, type ComposerRuntimeEventCallback, type ComposerRuntimeEventPayload, type ComposerRuntimeEventType, type ComposerRuntimePath, type ComposerState, CompositeAttachmentAdapter, type CoreChatModelRunResult, type CreateAppendMessage, type CreateAttachment, type CreateResumeRunConfig, type CreateStartRunConfig, type CreateSuggestionAdapterOptions, type DataMessagePart, type DictationAdapter, type DictationState, type EditComposerRuntime, type EditComposerRuntimeCore, type EditComposerState, type ErrorDisplay, type ErrorSeverity, ExportedMessageRepository, type ExportedMessageRepositoryItem, type ExternalStoreAdapter, type ExternalStoreBranchChange, type ExternalStoreMessageConverter, type ExternalStoreSharedOptions, type ExternalStoreThreadData, type ExternalStoreThreadListAdapter, type ExternalThreadBranchAdapter, type ExternalThreadQueueAdapter, FRAME_MESSAGE_CHANNEL, type FeedbackAdapter, type FileMessagePart, type FrameMessage, type FrameMessageType, type GenerativeUIMessagePart, type GenerativeUINode, type GenerativeUISpec, type GenericThreadHistoryAdapter, type ImageMessagePart, InMemoryThreadListAdapter, type LanguageModelConfig, type LanguageModelV1CallSettings, type LocalRuntimeOptionsBase, MCP_APP_URI_SCHEME, type McpAppMetadata, type MessageFormatAdapter, type MessageFormatItem, type MessageFormatRepository, type MessageModality, MessageNotSentError, type MessagePartRuntime, type MessagePartRuntimePath, type MessagePartState, type MessagePartStatus, type MessagePartStreamStatus, type MessageQueueController, type MessageQueueDriver, type MessageRole, type MessageRuntime, type MessageRuntimePath, type MessageState, type MessageStatus, type MessageStorageEntry, type MessageTiming, type ModelContext, type ModelContextProvider, ModelContextRegistry, type ModelContextRegistryInstructionHandle, type ModelContextRegistryProviderHandle, type ModelContextRegistryToolHandle, type PartProviderMetadata, type PendingAttachment, type PendingAttachmentStatus, type QueuePlacement, type QuoteInfo, type RealtimeVoiceAdapter, type ReasoningMessagePart, type RemoteThreadInitializeResponse, type RemoteThreadListAdapter, type RemoteThreadListOptions, type RemoteThreadListPageOptions, type RemoteThreadListProviderComponent, type RemoteThreadListResponse, type RemoteThreadMetadata, type RespondToToolApprovalOptions, type ResumeRunConfig, type ResumeToolCallOptions, type RunConfig, type RuntimeAdapters, type RuntimeCapabilities, type SendOptions, type SerializedModelContext, type SerializedTool, SimpleImageAttachmentAdapter, SimpleTextAttachmentAdapter, type SourceMessagePart, type SourceProviderMetadata, type SpeechState, type SpeechSynthesisAdapter, type StartRunConfig, type StreamingTimingAccessors, type StreamingTimingOptions, type StreamingTimingState, type SubmitFeedbackOptions, type SubmittedFeedback, type SuggestionAdapter, type SuggestionAdapterGenerateOptions, type TextMessagePart, type ThreadAssistantMessage, type ThreadAssistantMessagePart, type ThreadComposerRuntime, type ThreadComposerRuntimeCore, type ThreadComposerState, type ThreadHistoryAdapter, type ThreadListItemCoreState, type ThreadListItemEventCallback, type ThreadListItemEventPayload, type ThreadListItemEventType, type ThreadListItemGenerateTitleOptions, type ThreadListItemRuntime, type ThreadListItemRuntimePath, type ThreadListItemState, type ThreadListItemStatus, type ThreadListRuntime, type ThreadListRuntimeCore, type ThreadListState, type ThreadMessage, type ThreadMessageLike, type ThreadRuntime, type ThreadRuntimeCore, type ThreadRuntimeEventCallback, type ThreadRuntimeEventPayload, type ThreadRuntimeEventType, type ThreadRuntimePath, type ThreadState, type ThreadStep, type ThreadSuggestion, type ThreadSystemMessage, type ThreadUserMessage, type ThreadUserMessagePart, type ToolApprovalDisplay, type ToolApprovalOption, type ToolApprovalOptionKind, type ToolApprovalResponse, type ToolCallMessagePart, type ToolCallMessagePartMcpMetadata, type ToolCallMessagePartStatus, type ToolCallTiming, type ToolExecutionStatus, type ToolModelContentPart, type Unstable_AudioMessagePart, type Unstable_DirectiveFormatter, type Unstable_DirectiveSegment, type Unstable_InteractableSnapshotEntry, type Unstable_InteractableVersion, type Unstable_TriggerAdapter, type Unstable_TriggerCategory, type Unstable_TriggerItem, type Unsubscribe, type UserCommands, type UserExternalState, type VoiceSessionControls, type VoiceSessionHelpers, type VoiceSessionState, WebSpeechDictationAdapter, WebSpeechSynthesisAdapter, bindExternalStoreMessage, createMessageQueue, createRequestHeaders, createSuggestionAdapter, createVoiceSession, fromThreadMessageLike, generateId, getExternalStoreMessages, isAssistantError, isMcpAppUri, isMessageNotSentError, mergeModelContexts, pickExternalStoreSharedOptions, stepStreamingTiming, toAssistantError, tool, toolApprovalAcceptsText, unstable_defaultDirectiveFormatter, unstable_formatInteractableSnapshot, unstable_getInteractableSnapshots, unstable_getInteractableVersions };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["checkDuplicateCore","process","env","NODE_ENV","TextMessagePart","ReasoningMessagePart","PartProviderMetadata","SourceProviderMetadata","SourceMessagePart","ImageMessagePart","FileMessagePart","DataMessagePart","GenerativeUIMessagePart","GenerativeUINode","GenerativeUISpec","Unstable_AudioMessagePart","ToolApprovalDisplay","ToolApprovalOption","ToolApprovalOptionKind","ToolApprovalResponse","ToolCallMessagePart","ToolCallTiming","ToolCallMessagePartMcpMetadata","McpAppMetadata","ToolModelContentPart","ThreadUserMessagePart","ThreadAssistantMessagePart","MessagePartStatus","MessagePartStreamStatus","ToolCallMessagePartStatus","MessageStatus","MessageTiming","ThreadStep","ThreadSystemMessage","ThreadUserMessage","ThreadAssistantMessage","ThreadMessage","MessageRole","RunConfig","AppendMessage","MCP_APP_URI_SCHEME","isMcpAppUri","toolApprovalAcceptsText","Attachment","PendingAttachment","PendingAttachmentStatus","CompleteAttachment","CompleteAttachmentStatus","AttachmentStatus","CreateAttachment","Unsubscribe","Assistant","UserCommands","UserExternalState","QuoteInfo","Unstable_DirectiveSegment","Unstable_DirectiveFormatter","Unstable_TriggerItem","Unstable_TriggerCategory","Unstable_TriggerAdapter","LanguageModelV1CallSettings","LanguageModelConfig","ModelContext","ModelContextProvider","AssistantToolProps","AssistantInstructionsConfig","AssistantContextConfig","mergeModelContexts","tool","unstable_getInteractableSnapshots","unstable_formatInteractableSnapshot","unstable_getInteractableVersions","Unstable_InteractableSnapshotEntry","Unstable_InteractableVersion","ToolExecutionStatus","ModelContextRegistry","ModelContextRegistryToolHandle","ModelContextRegistryInstructionHandle","ModelContextRegistryProviderHandle","AssistantFrameHost","AssistantFrameProvider","SerializedTool","SerializedModelContext","FrameMessageType","FrameMessage","FRAME_MESSAGE_CHANNEL","AttachmentAdapter","SimpleImageAttachmentAdapter","SimpleTextAttachmentAdapter","CompositeAttachmentAdapter","SpeechSynthesisAdapter","DictationAdapter","WebSpeechSynthesisAdapter","WebSpeechDictationAdapter","RealtimeVoiceAdapter","createVoiceSession","VoiceSessionControls","VoiceSessionHelpers","FeedbackAdapter","SuggestionAdapter","SuggestionAdapterGenerateOptions","CreateSuggestionAdapterOptions","createSuggestionAdapter","unstable_defaultDirectiveFormatter","ThreadHistoryAdapter","GenericThreadHistoryAdapter","MessageFormatAdapter","MessageFormatItem","MessageFormatRepository","MessageStorageEntry","ThreadListItemRuntimePath","ThreadRuntimePath","MessageRuntimePath","MessagePartRuntimePath","AttachmentRuntimePath","ComposerRuntimePath","AttachmentAddErrorEvent","AttachmentAddErrorReason","ComposerRuntimeCore","ComposerRuntimeEventCallback","ComposerRuntimeEventPayload","ComposerRuntimeEventType","DictationState","EditComposerRuntimeCore","SendOptions","ThreadComposerRuntimeCore","ErrorSeverity","ErrorDisplay","AssistantErrorCode","AssistantError","toAssistantError","isAssistantError","MessageNotSentError","isMessageNotSentError","RuntimeCapabilities","AddToolResultOptions","ResumeToolCallOptions","RespondToToolApprovalOptions","SubmitFeedbackOptions","ThreadSuggestion","SpeechState","VoiceSessionState","SubmittedFeedback","ThreadRuntimeEventCallback","ThreadRuntimeEventPayload","ThreadRuntimeEventType","StartRunConfig","ResumeRunConfig","ThreadRuntimeCore","ThreadListItemStatus","ThreadListItemCoreState","ThreadListRuntimeCore","AssistantRuntimeCore","AssistantRuntime","CreateStartRunConfig","CreateResumeRunConfig","CreateAppendMessage","ThreadState","ThreadRuntime","ThreadListState","ThreadListRuntime","ThreadListItemEventCallback","ThreadListItemEventPayload","ThreadListItemEventType","ThreadListItemGenerateTitleOptions","ThreadListItemRuntime","ThreadListItemState","MessageState","MessageRuntime","MessagePartState","MessagePartRuntime","ThreadComposerState","EditComposerState","ComposerState","ComposerRuntime","ThreadComposerRuntime","EditComposerRuntime","AttachmentState","AttachmentRuntime","ChatModelRunUpdate","ChatModelRunResult","CoreChatModelRunResult","ChatModelRunOptions","ChatModelAdapter","ThreadMessageLike","fromThreadMessageLike","StreamingTimingAccessors","StreamingTimingOptions","StreamingTimingState","stepStreamingTiming","generateId","getExternalStoreMessages","bindExternalStoreMessage","ExportedMessageRepositoryItem","ExportedMessageRepository","LocalRuntimeOptionsBase","ExternalStoreAdapter","ExternalStoreMessageConverter","ExternalStoreThreadListAdapter","ExternalStoreThreadData","ExternalStoreBranchChange","ExternalStoreSharedOptions","pickExternalStoreSharedOptions","ExternalThreadQueueAdapter","QueuePlacement","ExternalThreadBranchAdapter","createMessageQueue","MessageQueueDriver","MessageQueueController","RemoteThreadListAdapter","RuntimeAdapters","RemoteThreadListOptions","RemoteThreadListProviderComponent","RemoteThreadInitializeResponse","RemoteThreadMetadata","RemoteThreadListResponse","RemoteThreadListPageOptions","InMemoryThreadListAdapter","createRequestHeaders"],"sources":["../src/index.ts"],"sourcesContent":["// @assistant-ui/core - Framework-agnostic core runtime (public API)\n\n/// <reference path=\"./store/scope-registration.ts\" />\n\nimport { checkDuplicateCore } from \"./internal/duplicate-detection\";\n\nif (process.env.NODE_ENV !== \"production\") {\n checkDuplicateCore();\n}\n\nexport type {\n // Message parts\n TextMessagePart,\n ReasoningMessagePart,\n PartProviderMetadata,\n SourceProviderMetadata,\n SourceMessagePart,\n ImageMessagePart,\n FileMessagePart,\n DataMessagePart,\n GenerativeUIMessagePart,\n GenerativeUINode,\n GenerativeUISpec,\n Unstable_AudioMessagePart,\n ToolApprovalDisplay,\n ToolApprovalOption,\n ToolApprovalOptionKind,\n ToolApprovalResponse,\n ToolCallMessagePart,\n ToolCallTiming,\n ToolCallMessagePartMcpMetadata,\n McpAppMetadata,\n ToolModelContentPart,\n ThreadUserMessagePart,\n ThreadAssistantMessagePart,\n // Message status\n MessagePartStatus,\n MessagePartStreamStatus,\n ToolCallMessagePartStatus,\n MessageStatus,\n // Thread messages\n MessageTiming,\n ThreadStep,\n ThreadSystemMessage,\n ThreadUserMessage,\n ThreadAssistantMessage,\n ThreadMessage,\n MessageRole,\n // Config\n RunConfig,\n AppendMessage,\n} from \"./types/message\";\n\nexport {\n MCP_APP_URI_SCHEME,\n isMcpAppUri,\n toolApprovalAcceptsText,\n} from \"./types/message\";\n\nexport type {\n Attachment,\n PendingAttachment,\n PendingAttachmentStatus,\n CompleteAttachment,\n CompleteAttachmentStatus,\n AttachmentStatus,\n CreateAttachment,\n} from \"./types/attachment\";\n\nexport type { Unsubscribe } from \"./types/unsubscribe\";\n\nexport type {\n Assistant,\n UserCommands,\n UserExternalState,\n} from \"./types/augmentations\";\n\nexport type { QuoteInfo } from \"./types/quote\";\n\nexport type {\n Unstable_DirectiveSegment,\n Unstable_DirectiveFormatter,\n} from \"./types/directive\";\n\nexport type {\n Unstable_TriggerItem,\n Unstable_TriggerCategory,\n} from \"./types/trigger\";\n\nexport type { Unstable_TriggerAdapter } from \"./adapters/trigger\";\n\nexport type {\n // Language model settings\n LanguageModelV1CallSettings,\n LanguageModelConfig,\n // Model context\n ModelContext,\n ModelContextProvider,\n // Tool & instruction config\n AssistantToolProps,\n AssistantInstructionsConfig,\n AssistantContextConfig,\n} from \"./model-context/types\";\nexport { mergeModelContexts } from \"./model-context/types\";\n\nexport { tool } from \"./model-context/tool\";\n\nexport {\n unstable_getInteractableSnapshots,\n unstable_formatInteractableSnapshot,\n unstable_getInteractableVersions,\n type Unstable_InteractableSnapshotEntry,\n type Unstable_InteractableVersion,\n} from \"./model-context/interactable-composer-metadata\";\n\nexport type { ToolExecutionStatus } from \"./runtimes/tool-invocations/ToolInvocationTracker\";\n\nexport { ModelContextRegistry } from \"./model-context/registry\";\nexport type {\n ModelContextRegistryToolHandle,\n ModelContextRegistryInstructionHandle,\n ModelContextRegistryProviderHandle,\n} from \"./model-context/registry-handles\";\n\nexport { AssistantFrameHost } from \"./model-context/frame/host\";\nexport { AssistantFrameProvider } from \"./model-context/frame/provider\";\nexport type {\n SerializedTool,\n SerializedModelContext,\n FrameMessageType,\n FrameMessage,\n} from \"./model-context/frame/types\";\nexport { FRAME_MESSAGE_CHANNEL } from \"./model-context/frame/types\";\n\n// Attachment adapters\nexport type { AttachmentAdapter } from \"./adapters/attachment\";\nexport {\n SimpleImageAttachmentAdapter,\n SimpleTextAttachmentAdapter,\n CompositeAttachmentAdapter,\n} from \"./adapters/attachment\";\n\n// Speech adapters\nexport type {\n SpeechSynthesisAdapter,\n DictationAdapter,\n} from \"./adapters/speech\";\nexport {\n WebSpeechSynthesisAdapter,\n WebSpeechDictationAdapter,\n} from \"./adapters/speech\";\n\n// Voice adapter\nexport type { RealtimeVoiceAdapter } from \"./adapters/voice\";\nexport { createVoiceSession } from \"./adapters/voice\";\nexport type {\n VoiceSessionControls,\n VoiceSessionHelpers,\n} from \"./adapters/voice\";\n\n// Feedback adapter\nexport type { FeedbackAdapter } from \"./adapters/feedback\";\n\n// Suggestion adapter\nexport type {\n SuggestionAdapter,\n SuggestionAdapterGenerateOptions,\n CreateSuggestionAdapterOptions,\n} from \"./adapters/suggestion\";\nexport { createSuggestionAdapter } from \"./adapters/suggestion\";\n\n// Directive formatter\nexport { unstable_defaultDirectiveFormatter } from \"./adapters/directive-formatter\";\n\n// Thread history adapters\nexport type {\n ThreadHistoryAdapter,\n GenericThreadHistoryAdapter,\n MessageFormatAdapter,\n MessageFormatItem,\n MessageFormatRepository,\n MessageStorageEntry,\n} from \"./adapters/thread-history\";\n\n// Path Types\nexport type {\n ThreadListItemRuntimePath,\n ThreadRuntimePath,\n MessageRuntimePath,\n MessagePartRuntimePath,\n AttachmentRuntimePath,\n ComposerRuntimePath,\n} from \"./runtime/api/paths\";\n\n// Runtime Core Interface Types\nexport type {\n AttachmentAddErrorEvent,\n AttachmentAddErrorReason,\n ComposerRuntimeCore,\n ComposerRuntimeEventCallback,\n ComposerRuntimeEventPayload,\n ComposerRuntimeEventType,\n DictationState,\n EditComposerRuntimeCore,\n SendOptions,\n ThreadComposerRuntimeCore,\n} from \"./runtime/interfaces/composer-runtime-core\";\n\nexport type {\n ErrorSeverity,\n ErrorDisplay,\n AssistantErrorCode,\n AssistantError,\n} from \"./types/error\";\nexport { toAssistantError, isAssistantError } from \"./types/error\";\nexport { MessageNotSentError, isMessageNotSentError } from \"./types/error\";\n\nexport type {\n RuntimeCapabilities,\n AddToolResultOptions,\n ResumeToolCallOptions,\n RespondToToolApprovalOptions,\n SubmitFeedbackOptions,\n ThreadSuggestion,\n SpeechState,\n VoiceSessionState,\n SubmittedFeedback,\n ThreadRuntimeEventCallback,\n ThreadRuntimeEventPayload,\n ThreadRuntimeEventType,\n StartRunConfig,\n ResumeRunConfig,\n ThreadRuntimeCore,\n} from \"./runtime/interfaces/thread-runtime-core\";\n\nexport type {\n ThreadListItemStatus,\n ThreadListItemCoreState,\n ThreadListRuntimeCore,\n} from \"./runtime/interfaces/thread-list-runtime-core\";\n\nexport type { AssistantRuntimeCore } from \"./runtime/interfaces/assistant-runtime-core\";\n\n// Public Runtime Types\nexport type { AssistantRuntime } from \"./runtime/api/assistant-runtime\";\n\nexport type {\n CreateStartRunConfig,\n CreateResumeRunConfig,\n CreateAppendMessage,\n ThreadState,\n ThreadRuntime,\n} from \"./runtime/api/thread-runtime\";\n\nexport type {\n ThreadListState,\n ThreadListRuntime,\n} from \"./runtime/api/thread-list-runtime\";\n\nexport type {\n ThreadListItemEventCallback,\n ThreadListItemEventPayload,\n ThreadListItemEventType,\n ThreadListItemGenerateTitleOptions,\n ThreadListItemRuntime,\n} from \"./runtime/api/thread-list-item-runtime\";\n\nexport type { ThreadListItemState } from \"./runtime/api/bindings\";\n\nexport type {\n MessageState,\n MessageRuntime,\n} from \"./runtime/api/message-runtime\";\nexport type {\n MessagePartState,\n MessagePartRuntime,\n} from \"./runtime/api/message-part-runtime\";\n\nexport type {\n ThreadComposerState,\n EditComposerState,\n ComposerState,\n ComposerRuntime,\n ThreadComposerRuntime,\n EditComposerRuntime,\n} from \"./runtime/api/composer-runtime\";\n\nexport type {\n AttachmentState,\n AttachmentRuntime,\n} from \"./runtime/api/attachment-runtime\";\n\n// ChatModel Types\nexport type {\n ChatModelRunUpdate,\n ChatModelRunResult,\n CoreChatModelRunResult,\n ChatModelRunOptions,\n ChatModelAdapter,\n} from \"./runtime/utils/chat-model-adapter\";\n\n// ThreadMessageLike\nexport type { ThreadMessageLike } from \"./runtime/utils/thread-message-like\";\nexport { fromThreadMessageLike } from \"./runtime/utils/thread-message-like\";\n\n// Streaming timing (client-side)\nexport type {\n StreamingTimingAccessors,\n StreamingTimingOptions,\n StreamingTimingState,\n} from \"./runtime/utils/streaming-timing\";\nexport { stepStreamingTiming } from \"./runtime/utils/streaming-timing\";\n\n// ID generation\nexport { generateId } from \"./utils/id\";\n\n// External Store Message Utilities\nexport {\n getExternalStoreMessages,\n bindExternalStoreMessage,\n} from \"./runtime/utils/external-store-message\";\n\n// ExportedMessageRepository\nexport type { ExportedMessageRepositoryItem } from \"./runtime/utils/message-repository\";\nexport { ExportedMessageRepository } from \"./runtime/utils/message-repository\";\n\n// Local Runtime Options\nexport type { LocalRuntimeOptionsBase } from \"./runtimes/local/local-runtime-options\";\n\n// External Store Adapter Types (user-facing)\nexport type {\n ExternalStoreAdapter,\n ExternalStoreMessageConverter,\n ExternalStoreThreadListAdapter,\n ExternalStoreThreadData,\n ExternalStoreBranchChange,\n} from \"./runtimes/external-store/external-store-adapter\";\nexport type { ExternalStoreSharedOptions } from \"./runtimes/external-store/external-store-shared-options\";\nexport { pickExternalStoreSharedOptions } from \"./runtimes/external-store/external-store-shared-options\";\n\n// Message queue\nexport type {\n ExternalThreadQueueAdapter,\n QueuePlacement,\n} from \"./runtime/queue/external-thread-queue-adapter\";\nexport type { ExternalThreadBranchAdapter } from \"./runtime/branch/external-thread-branch-adapter\";\nexport {\n createMessageQueue,\n type MessageQueueDriver,\n type MessageQueueController,\n} from \"./runtime/queue/message-queue\";\n\n// Remote Thread List (user-facing)\nexport type {\n RemoteThreadListAdapter,\n RuntimeAdapters,\n RemoteThreadListOptions,\n RemoteThreadListProviderComponent,\n RemoteThreadInitializeResponse,\n RemoteThreadMetadata,\n RemoteThreadListResponse,\n RemoteThreadListPageOptions,\n} from \"./runtimes/remote-thread-list/types\";\n\nexport { InMemoryThreadListAdapter } from \"./runtimes/remote-thread-list/adapter/in-memory\";\n\n// Assistant Transport Utilities\nexport { createRequestHeaders } from \"./runtimes/assistant-transport/utils\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAMA,IAAIC,QAAQC,IAAIC,aAAa,cAC3BH,mBAAmB"}
1
+ {"version":3,"file":"index.js","names":["checkDuplicateCore","process","env","NODE_ENV","TextMessagePart","ReasoningMessagePart","PartProviderMetadata","SourceProviderMetadata","SourceMessagePart","ImageMessagePart","FileMessagePart","DataMessagePart","GenerativeUIMessagePart","GenerativeUINode","GenerativeUISpec","Unstable_AudioMessagePart","ToolApprovalDisplay","ToolApprovalOption","ToolApprovalOptionKind","ToolApprovalResponse","ToolCallMessagePart","ToolCallTiming","ToolCallMessagePartMcpMetadata","McpAppMetadata","ToolModelContentPart","ThreadUserMessagePart","ThreadAssistantMessagePart","MessagePartStatus","MessagePartStreamStatus","ToolCallMessagePartStatus","MessageStatus","MessageTiming","MessageModality","ThreadStep","ThreadSystemMessage","ThreadUserMessage","ThreadAssistantMessage","ThreadMessage","MessageRole","RunConfig","AppendMessage","MCP_APP_URI_SCHEME","isMcpAppUri","toolApprovalAcceptsText","Attachment","PendingAttachment","PendingAttachmentStatus","CompleteAttachment","CompleteAttachmentStatus","AttachmentStatus","CreateAttachment","Unsubscribe","Assistant","UserCommands","UserExternalState","QuoteInfo","Unstable_DirectiveSegment","Unstable_DirectiveFormatter","Unstable_TriggerItem","Unstable_TriggerCategory","Unstable_TriggerAdapter","LanguageModelV1CallSettings","LanguageModelConfig","ModelContext","ModelContextProvider","AssistantToolProps","AssistantInstructionsConfig","AssistantContextConfig","mergeModelContexts","tool","unstable_getInteractableSnapshots","unstable_formatInteractableSnapshot","unstable_getInteractableVersions","Unstable_InteractableSnapshotEntry","Unstable_InteractableVersion","ToolExecutionStatus","ModelContextRegistry","ModelContextRegistryToolHandle","ModelContextRegistryInstructionHandle","ModelContextRegistryProviderHandle","AssistantFrameHost","AssistantFrameProvider","SerializedTool","SerializedModelContext","FrameMessageType","FrameMessage","FRAME_MESSAGE_CHANNEL","AttachmentAdapter","SimpleImageAttachmentAdapter","SimpleTextAttachmentAdapter","CompositeAttachmentAdapter","SpeechSynthesisAdapter","DictationAdapter","WebSpeechSynthesisAdapter","WebSpeechDictationAdapter","RealtimeVoiceAdapter","createVoiceSession","VoiceSessionControls","VoiceSessionHelpers","FeedbackAdapter","SuggestionAdapter","SuggestionAdapterGenerateOptions","CreateSuggestionAdapterOptions","createSuggestionAdapter","unstable_defaultDirectiveFormatter","ThreadHistoryAdapter","GenericThreadHistoryAdapter","MessageFormatAdapter","MessageFormatItem","MessageFormatRepository","MessageStorageEntry","ThreadListItemRuntimePath","ThreadRuntimePath","MessageRuntimePath","MessagePartRuntimePath","AttachmentRuntimePath","ComposerRuntimePath","AttachmentAddErrorEvent","AttachmentAddErrorReason","ComposerRuntimeCore","ComposerRuntimeEventCallback","ComposerRuntimeEventPayload","ComposerRuntimeEventType","DictationState","EditComposerRuntimeCore","SendOptions","ThreadComposerRuntimeCore","ErrorSeverity","ErrorDisplay","AssistantErrorCode","AssistantError","toAssistantError","isAssistantError","MessageNotSentError","isMessageNotSentError","RuntimeCapabilities","AddToolResultOptions","ResumeToolCallOptions","RespondToToolApprovalOptions","SubmitFeedbackOptions","ThreadSuggestion","SpeechState","VoiceSessionState","SubmittedFeedback","ThreadRuntimeEventCallback","ThreadRuntimeEventPayload","ThreadRuntimeEventType","StartRunConfig","ResumeRunConfig","ThreadRuntimeCore","ThreadListItemStatus","ThreadListItemCoreState","ThreadListRuntimeCore","AssistantRuntimeCore","AssistantRuntime","CreateStartRunConfig","CreateResumeRunConfig","CreateAppendMessage","ThreadState","ThreadRuntime","ThreadListState","ThreadListRuntime","ThreadListItemEventCallback","ThreadListItemEventPayload","ThreadListItemEventType","ThreadListItemGenerateTitleOptions","ThreadListItemRuntime","ThreadListItemState","MessageState","MessageRuntime","MessagePartState","MessagePartRuntime","ThreadComposerState","EditComposerState","ComposerState","ComposerRuntime","ThreadComposerRuntime","EditComposerRuntime","AttachmentState","AttachmentRuntime","ChatModelRunUpdate","ChatModelRunResult","CoreChatModelRunResult","ChatModelRunOptions","ChatModelAdapter","ThreadMessageLike","fromThreadMessageLike","StreamingTimingAccessors","StreamingTimingOptions","StreamingTimingState","stepStreamingTiming","generateId","getExternalStoreMessages","bindExternalStoreMessage","ExportedMessageRepositoryItem","ExportedMessageRepository","LocalRuntimeOptionsBase","ExternalStoreAdapter","ExternalStoreMessageConverter","ExternalStoreThreadListAdapter","ExternalStoreThreadData","ExternalStoreBranchChange","ExternalStoreSharedOptions","pickExternalStoreSharedOptions","ExternalThreadQueueAdapter","QueuePlacement","ExternalThreadBranchAdapter","createMessageQueue","MessageQueueDriver","MessageQueueController","RemoteThreadListAdapter","RuntimeAdapters","RemoteThreadListOptions","RemoteThreadListProviderComponent","RemoteThreadInitializeResponse","RemoteThreadMetadata","RemoteThreadListResponse","RemoteThreadListPageOptions","InMemoryThreadListAdapter","createRequestHeaders"],"sources":["../src/index.ts"],"sourcesContent":["// @assistant-ui/core - Framework-agnostic core runtime (public API)\n\n/// <reference path=\"./store/scope-registration.ts\" />\n\nimport { checkDuplicateCore } from \"./internal/duplicate-detection\";\n\nif (process.env.NODE_ENV !== \"production\") {\n checkDuplicateCore();\n}\n\nexport type {\n // Message parts\n TextMessagePart,\n ReasoningMessagePart,\n PartProviderMetadata,\n SourceProviderMetadata,\n SourceMessagePart,\n ImageMessagePart,\n FileMessagePart,\n DataMessagePart,\n GenerativeUIMessagePart,\n GenerativeUINode,\n GenerativeUISpec,\n Unstable_AudioMessagePart,\n ToolApprovalDisplay,\n ToolApprovalOption,\n ToolApprovalOptionKind,\n ToolApprovalResponse,\n ToolCallMessagePart,\n ToolCallTiming,\n ToolCallMessagePartMcpMetadata,\n McpAppMetadata,\n ToolModelContentPart,\n ThreadUserMessagePart,\n ThreadAssistantMessagePart,\n // Message status\n MessagePartStatus,\n MessagePartStreamStatus,\n ToolCallMessagePartStatus,\n MessageStatus,\n // Thread messages\n MessageTiming,\n MessageModality,\n ThreadStep,\n ThreadSystemMessage,\n ThreadUserMessage,\n ThreadAssistantMessage,\n ThreadMessage,\n MessageRole,\n // Config\n RunConfig,\n AppendMessage,\n} from \"./types/message\";\n\nexport {\n MCP_APP_URI_SCHEME,\n isMcpAppUri,\n toolApprovalAcceptsText,\n} from \"./types/message\";\n\nexport type {\n Attachment,\n PendingAttachment,\n PendingAttachmentStatus,\n CompleteAttachment,\n CompleteAttachmentStatus,\n AttachmentStatus,\n CreateAttachment,\n} from \"./types/attachment\";\n\nexport type { Unsubscribe } from \"./types/unsubscribe\";\n\nexport type {\n Assistant,\n UserCommands,\n UserExternalState,\n} from \"./types/augmentations\";\n\nexport type { QuoteInfo } from \"./types/quote\";\n\nexport type {\n Unstable_DirectiveSegment,\n Unstable_DirectiveFormatter,\n} from \"./types/directive\";\n\nexport type {\n Unstable_TriggerItem,\n Unstable_TriggerCategory,\n} from \"./types/trigger\";\n\nexport type { Unstable_TriggerAdapter } from \"./adapters/trigger\";\n\nexport type {\n // Language model settings\n LanguageModelV1CallSettings,\n LanguageModelConfig,\n // Model context\n ModelContext,\n ModelContextProvider,\n // Tool & instruction config\n AssistantToolProps,\n AssistantInstructionsConfig,\n AssistantContextConfig,\n} from \"./model-context/types\";\nexport { mergeModelContexts } from \"./model-context/types\";\n\nexport { tool } from \"./model-context/tool\";\n\nexport {\n unstable_getInteractableSnapshots,\n unstable_formatInteractableSnapshot,\n unstable_getInteractableVersions,\n type Unstable_InteractableSnapshotEntry,\n type Unstable_InteractableVersion,\n} from \"./model-context/interactable-composer-metadata\";\n\nexport type { ToolExecutionStatus } from \"./runtimes/tool-invocations/ToolInvocationTracker\";\n\nexport { ModelContextRegistry } from \"./model-context/registry\";\nexport type {\n ModelContextRegistryToolHandle,\n ModelContextRegistryInstructionHandle,\n ModelContextRegistryProviderHandle,\n} from \"./model-context/registry-handles\";\n\nexport { AssistantFrameHost } from \"./model-context/frame/host\";\nexport { AssistantFrameProvider } from \"./model-context/frame/provider\";\nexport type {\n SerializedTool,\n SerializedModelContext,\n FrameMessageType,\n FrameMessage,\n} from \"./model-context/frame/types\";\nexport { FRAME_MESSAGE_CHANNEL } from \"./model-context/frame/types\";\n\n// Attachment adapters\nexport type { AttachmentAdapter } from \"./adapters/attachment\";\nexport {\n SimpleImageAttachmentAdapter,\n SimpleTextAttachmentAdapter,\n CompositeAttachmentAdapter,\n} from \"./adapters/attachment\";\n\n// Speech adapters\nexport type {\n SpeechSynthesisAdapter,\n DictationAdapter,\n} from \"./adapters/speech\";\nexport {\n WebSpeechSynthesisAdapter,\n WebSpeechDictationAdapter,\n} from \"./adapters/speech\";\n\n// Voice adapter\nexport type { RealtimeVoiceAdapter } from \"./adapters/voice\";\nexport { createVoiceSession } from \"./adapters/voice\";\nexport type {\n VoiceSessionControls,\n VoiceSessionHelpers,\n} from \"./adapters/voice\";\n\n// Feedback adapter\nexport type { FeedbackAdapter } from \"./adapters/feedback\";\n\n// Suggestion adapter\nexport type {\n SuggestionAdapter,\n SuggestionAdapterGenerateOptions,\n CreateSuggestionAdapterOptions,\n} from \"./adapters/suggestion\";\nexport { createSuggestionAdapter } from \"./adapters/suggestion\";\n\n// Directive formatter\nexport { unstable_defaultDirectiveFormatter } from \"./adapters/directive-formatter\";\n\n// Thread history adapters\nexport type {\n ThreadHistoryAdapter,\n GenericThreadHistoryAdapter,\n MessageFormatAdapter,\n MessageFormatItem,\n MessageFormatRepository,\n MessageStorageEntry,\n} from \"./adapters/thread-history\";\n\n// Path Types\nexport type {\n ThreadListItemRuntimePath,\n ThreadRuntimePath,\n MessageRuntimePath,\n MessagePartRuntimePath,\n AttachmentRuntimePath,\n ComposerRuntimePath,\n} from \"./runtime/api/paths\";\n\n// Runtime Core Interface Types\nexport type {\n AttachmentAddErrorEvent,\n AttachmentAddErrorReason,\n ComposerRuntimeCore,\n ComposerRuntimeEventCallback,\n ComposerRuntimeEventPayload,\n ComposerRuntimeEventType,\n DictationState,\n EditComposerRuntimeCore,\n SendOptions,\n ThreadComposerRuntimeCore,\n} from \"./runtime/interfaces/composer-runtime-core\";\n\nexport type {\n ErrorSeverity,\n ErrorDisplay,\n AssistantErrorCode,\n AssistantError,\n} from \"./types/error\";\nexport { toAssistantError, isAssistantError } from \"./types/error\";\nexport { MessageNotSentError, isMessageNotSentError } from \"./types/error\";\n\nexport type {\n RuntimeCapabilities,\n AddToolResultOptions,\n ResumeToolCallOptions,\n RespondToToolApprovalOptions,\n SubmitFeedbackOptions,\n ThreadSuggestion,\n SpeechState,\n VoiceSessionState,\n SubmittedFeedback,\n ThreadRuntimeEventCallback,\n ThreadRuntimeEventPayload,\n ThreadRuntimeEventType,\n StartRunConfig,\n ResumeRunConfig,\n ThreadRuntimeCore,\n} from \"./runtime/interfaces/thread-runtime-core\";\n\nexport type {\n ThreadListItemStatus,\n ThreadListItemCoreState,\n ThreadListRuntimeCore,\n} from \"./runtime/interfaces/thread-list-runtime-core\";\n\nexport type { AssistantRuntimeCore } from \"./runtime/interfaces/assistant-runtime-core\";\n\n// Public Runtime Types\nexport type { AssistantRuntime } from \"./runtime/api/assistant-runtime\";\n\nexport type {\n CreateStartRunConfig,\n CreateResumeRunConfig,\n CreateAppendMessage,\n ThreadState,\n ThreadRuntime,\n} from \"./runtime/api/thread-runtime\";\n\nexport type {\n ThreadListState,\n ThreadListRuntime,\n} from \"./runtime/api/thread-list-runtime\";\n\nexport type {\n ThreadListItemEventCallback,\n ThreadListItemEventPayload,\n ThreadListItemEventType,\n ThreadListItemGenerateTitleOptions,\n ThreadListItemRuntime,\n} from \"./runtime/api/thread-list-item-runtime\";\n\nexport type { ThreadListItemState } from \"./runtime/api/bindings\";\n\nexport type {\n MessageState,\n MessageRuntime,\n} from \"./runtime/api/message-runtime\";\nexport type {\n MessagePartState,\n MessagePartRuntime,\n} from \"./runtime/api/message-part-runtime\";\n\nexport type {\n ThreadComposerState,\n EditComposerState,\n ComposerState,\n ComposerRuntime,\n ThreadComposerRuntime,\n EditComposerRuntime,\n} from \"./runtime/api/composer-runtime\";\n\nexport type {\n AttachmentState,\n AttachmentRuntime,\n} from \"./runtime/api/attachment-runtime\";\n\n// ChatModel Types\nexport type {\n ChatModelRunUpdate,\n ChatModelRunResult,\n CoreChatModelRunResult,\n ChatModelRunOptions,\n ChatModelAdapter,\n} from \"./runtime/utils/chat-model-adapter\";\n\n// ThreadMessageLike\nexport type { ThreadMessageLike } from \"./runtime/utils/thread-message-like\";\nexport { fromThreadMessageLike } from \"./runtime/utils/thread-message-like\";\n\n// Streaming timing (client-side)\nexport type {\n StreamingTimingAccessors,\n StreamingTimingOptions,\n StreamingTimingState,\n} from \"./runtime/utils/streaming-timing\";\nexport { stepStreamingTiming } from \"./runtime/utils/streaming-timing\";\n\n// ID generation\nexport { generateId } from \"./utils/id\";\n\n// External Store Message Utilities\nexport {\n getExternalStoreMessages,\n bindExternalStoreMessage,\n} from \"./runtime/utils/external-store-message\";\n\n// ExportedMessageRepository\nexport type { ExportedMessageRepositoryItem } from \"./runtime/utils/message-repository\";\nexport { ExportedMessageRepository } from \"./runtime/utils/message-repository\";\n\n// Local Runtime Options\nexport type { LocalRuntimeOptionsBase } from \"./runtimes/local/local-runtime-options\";\n\n// External Store Adapter Types (user-facing)\nexport type {\n ExternalStoreAdapter,\n ExternalStoreMessageConverter,\n ExternalStoreThreadListAdapter,\n ExternalStoreThreadData,\n ExternalStoreBranchChange,\n} from \"./runtimes/external-store/external-store-adapter\";\nexport type { ExternalStoreSharedOptions } from \"./runtimes/external-store/external-store-shared-options\";\nexport { pickExternalStoreSharedOptions } from \"./runtimes/external-store/external-store-shared-options\";\n\n// Message queue\nexport type {\n ExternalThreadQueueAdapter,\n QueuePlacement,\n} from \"./runtime/queue/external-thread-queue-adapter\";\nexport type { ExternalThreadBranchAdapter } from \"./runtime/branch/external-thread-branch-adapter\";\nexport {\n createMessageQueue,\n type MessageQueueDriver,\n type MessageQueueController,\n} from \"./runtime/queue/message-queue\";\n\n// Remote Thread List (user-facing)\nexport type {\n RemoteThreadListAdapter,\n RuntimeAdapters,\n RemoteThreadListOptions,\n RemoteThreadListProviderComponent,\n RemoteThreadInitializeResponse,\n RemoteThreadMetadata,\n RemoteThreadListResponse,\n RemoteThreadListPageOptions,\n} from \"./runtimes/remote-thread-list/types\";\n\nexport { InMemoryThreadListAdapter } from \"./runtimes/remote-thread-list/adapter/in-memory\";\n\n// Assistant Transport Utilities\nexport { createRequestHeaders } from \"./runtimes/assistant-transport/utils\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAMA,IAAIC,QAAQC,IAAIC,aAAa,cAC3BH,mBAAmB"}
@@ -44,10 +44,10 @@ import { LocalThreadFactory, LocalThreadListRuntimeCore } from "./runtimes/local
44
44
  import { LocalRuntimeCore } from "./runtimes/local/local-runtime-core.js";
45
45
  import { shouldContinue } from "./runtimes/local/should-continue.js";
46
46
  import { RemoteThreadInitializeResponse, RemoteThreadListOptions } from "./runtimes/remote-thread-list/types.js";
47
+ import { ConverterCallback, ThreadMessageConverter } from "./runtimes/external-store/thread-message-converter.js";
47
48
  import { ExternalStoreThreadRuntimeCore, hasUpcomingMessage } from "./runtimes/external-store/external-store-thread-runtime-core.js";
48
49
  import { ExternalStoreThreadFactory, ExternalStoreThreadListRuntimeCore } from "./runtimes/external-store/external-store-thread-list-runtime-core.js";
49
50
  import { ExternalStoreRuntimeCore } from "./runtimes/external-store/external-store-runtime-core.js";
50
- import { ConverterCallback, ThreadMessageConverter } from "./runtimes/external-store/thread-message-converter.js";
51
51
  import { ReadonlyThreadRuntimeCore } from "./runtimes/readonly/ReadonlyThreadRuntimeCore.js";
52
52
  import { OptimisticState } from "./runtimes/remote-thread-list/optimistic-state.js";
53
53
  import { EMPTY_THREAD_CORE } from "./runtimes/remote-thread-list/empty-thread-core.js";
@@ -1 +1 @@
1
- {"version":3,"file":"host.d.ts","names":[],"sources":["../../../src/model-context/frame/host.ts"],"mappings":";;;cAqDa,8BAA8B;UACjC;UACA;UACA;UAOA;UACA;UACA;EAGN,YAAA,cAAc,QACd;UAWM;UA6BA;UAoBA;UAkBA;UA+DA;UAUA;UAYA;EAIR,mBAAmB;EAInB,UAAU,uBAAuB;EAKjC"}
1
+ {"version":3,"file":"host.d.ts","names":[],"sources":["../../../src/model-context/frame/host.ts"],"mappings":";;;cA4Da,8BAA8B;UACjC;UACA;UACA;UAOA;UACA;UACA;EAGN,YAAA,cAAc,QACd;UAYM;UA6BA;UAoBA;UAkBA;UA+DA;UAiBA;UAYA;EAIR,mBAAmB;EAInB,UAAU,uBAAuB;EAKjC"}
@@ -3,6 +3,9 @@ import { generateId } from "../../utils/id.js";
3
3
  import { FRAME_MESSAGE_CHANNEL } from "./types.js";
4
4
  //#region src/model-context/frame/host.ts
5
5
  const getDefaultTargetOrigin = () => window.location.origin;
6
+ const logCancellationFailure = (error) => {
7
+ console.error("[assistant-ui] AssistantFrameHost tool cancellation could not be sent.", error);
8
+ };
6
9
  /**
7
10
  * Deserializes tools from JSON Schema format back to Tool objects
8
11
  */
@@ -36,8 +39,8 @@ var AssistantFrameHost = class {
36
39
  this._iframeWindow = iframeWindow;
37
40
  this._targetOrigin = targetOrigin;
38
41
  this.handleMessage = this.handleMessage.bind(this);
39
- window.addEventListener("message", this.handleMessage);
40
42
  this.requestContext();
43
+ window.addEventListener("message", this.handleMessage);
41
44
  }
42
45
  handleMessage(event) {
43
46
  if (this._targetOrigin !== "*" && event.origin !== this._targetOrigin) return;
@@ -127,14 +130,18 @@ var AssistantFrameHost = class {
127
130
  }
128
131
  });
129
132
  }
130
- cancelToolCall(id) {
131
- this._iframeWindow.postMessage({
132
- channel: FRAME_MESSAGE_CHANNEL,
133
- message: {
134
- type: "tool-cancel",
135
- id
136
- }
137
- }, this._targetOrigin);
133
+ cancelToolCall(id, onError = logCancellationFailure) {
134
+ try {
135
+ this._iframeWindow.postMessage({
136
+ channel: FRAME_MESSAGE_CHANNEL,
137
+ message: {
138
+ type: "tool-cancel",
139
+ id
140
+ }
141
+ }, this._targetOrigin);
142
+ } catch (error) {
143
+ onError(error);
144
+ }
138
145
  }
139
146
  requestContext() {
140
147
  this._iframeWindow.postMessage({
@@ -157,11 +164,19 @@ var AssistantFrameHost = class {
157
164
  window.removeEventListener("message", this.handleMessage);
158
165
  this._subscribers.clear();
159
166
  const error = /* @__PURE__ */ new Error("AssistantFrameHost has been disposed");
167
+ let cancellationFailed = false;
168
+ let cancellationError;
160
169
  for (const [id, pending] of this._pendingRequests) {
161
- this.cancelToolCall(id);
170
+ this._pendingRequests.delete(id);
171
+ this.cancelToolCall(id, (error) => {
172
+ if (!cancellationFailed) {
173
+ cancellationFailed = true;
174
+ cancellationError = error;
175
+ } else logCancellationFailure(error);
176
+ });
162
177
  pending.reject(error);
163
178
  }
164
- this._pendingRequests.clear();
179
+ if (cancellationFailed) throw cancellationError;
165
180
  }
166
181
  };
167
182
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"host.js","names":["ModelContextProvider","ModelContext","Unsubscribe","Tool","notifySubscribers","notifyStateSubscribers","generateId","FrameMessage","FRAME_MESSAGE_CHANNEL","SerializedModelContext","SerializedTool","getDefaultTargetOrigin","window","location","origin","deserializeTool","serializedTool","parameters","description","disabled","undefined","type","deserializeModelContext","serialized","system","tools","Object","fromEntries","entries","map","name","tool","getAbortReason","signal","AbortSignal","reason","error","Error","AssistantFrameHost","_context","_subscribers","Set","_pendingRequests","Map","resolve","value","reject","_iframeWindow","Window","_targetOrigin","_disposed","constructor","iframeWindow","targetOrigin","handleMessage","bind","addEventListener","requestContext","event","MessageEvent","source","data","channel","message","updateContext","context","pending","get","id","result","delete","serializedContext","execute","args","abortSignal","callTool","toolName","Promise","sendRequest","T","timeout","timeoutMessage","aborted","timeoutId","ReturnType","setTimeout","onAbort","cancelToolCall","cleanup","clearTimeout","removeEventListener","set","once","postMessage","getModelContext","subscribe","callback","add","dispose","clear"],"sources":["../../../src/model-context/frame/host.ts"],"sourcesContent":["import type { ModelContextProvider, ModelContext } from \"../types\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { Tool } from \"assistant-stream\";\nimport { notifySubscribers as notifyStateSubscribers } from \"../../subscribable/subscribable\";\nimport { generateId } from \"../../utils/id\";\nimport {\n type FrameMessage,\n FRAME_MESSAGE_CHANNEL,\n type SerializedModelContext,\n type SerializedTool,\n} from \"./types\";\n\nconst getDefaultTargetOrigin = () => window.location.origin;\n\n/**\n * Deserializes tools from JSON Schema format back to Tool objects\n */\nconst deserializeTool = (serializedTool: SerializedTool): Tool<any, any> =>\n ({\n parameters: serializedTool.parameters,\n ...(serializedTool.description && {\n description: serializedTool.description,\n }),\n ...(serializedTool.disabled !== undefined && {\n disabled: serializedTool.disabled,\n }),\n ...(serializedTool.type && { type: serializedTool.type }),\n }) as Tool<any, any>;\n\n/**\n * Deserializes a ModelContext from transmission format\n */\nconst deserializeModelContext = (\n serialized: SerializedModelContext,\n): ModelContext => ({\n ...(serialized.system !== undefined && { system: serialized.system }),\n ...(serialized.tools && {\n tools: Object.fromEntries(\n Object.entries(serialized.tools).map(([name, tool]) => [\n name,\n deserializeTool(tool),\n ]),\n ),\n }),\n});\n\nconst getAbortReason = (signal: AbortSignal): unknown => {\n if (signal.reason !== undefined) return signal.reason;\n const error = new Error(\"Tool call was aborted\");\n error.name = \"AbortError\";\n return error;\n};\n\nexport class AssistantFrameHost implements ModelContextProvider {\n private _context: ModelContext = {};\n private _subscribers = new Set<() => void>();\n private _pendingRequests = new Map<\n string,\n {\n resolve: (value: any) => void;\n reject: (error: any) => void;\n }\n >();\n private _iframeWindow: Window;\n private _targetOrigin: string;\n private _disposed = false;\n\n constructor(\n iframeWindow: Window,\n targetOrigin: string = getDefaultTargetOrigin(),\n ) {\n this._iframeWindow = iframeWindow;\n this._targetOrigin = targetOrigin;\n\n this.handleMessage = this.handleMessage.bind(this);\n window.addEventListener(\"message\", this.handleMessage);\n\n this.requestContext();\n }\n\n private handleMessage(event: MessageEvent) {\n if (this._targetOrigin !== \"*\" && event.origin !== this._targetOrigin)\n return;\n if (event.source !== this._iframeWindow) return;\n if (event.data?.channel !== FRAME_MESSAGE_CHANNEL) return;\n\n const message = event.data.message as FrameMessage;\n\n switch (message.type) {\n case \"model-context-update\": {\n this.updateContext(message.context);\n break;\n }\n\n case \"tool-result\": {\n const pending = this._pendingRequests.get(message.id);\n if (pending) {\n if (typeof message.error === \"string\") {\n pending.reject(new Error(message.error));\n } else {\n pending.resolve(message.result);\n }\n this._pendingRequests.delete(message.id);\n }\n break;\n }\n }\n }\n\n private updateContext(serializedContext: SerializedModelContext) {\n const context = deserializeModelContext(serializedContext);\n this._context = {\n ...context,\n tools:\n context.tools &&\n Object.fromEntries(\n Object.entries(context.tools).map(([name, tool]) => [\n name,\n {\n ...tool,\n execute: (args: any, context: { abortSignal: AbortSignal }) =>\n this.callTool(name, args, context.abortSignal),\n } as Tool<any, any>,\n ]),\n ),\n };\n this.notifySubscribers();\n }\n\n private callTool(\n toolName: string,\n args: any,\n abortSignal: AbortSignal,\n ): Promise<any> {\n return this.sendRequest(\n {\n type: \"tool-call\",\n id: `tool-${generateId()}`,\n toolName,\n args,\n },\n 30000,\n `Tool call \"${toolName}\" timed out`,\n abortSignal,\n );\n }\n\n private sendRequest<T extends FrameMessage & { id: string }>(\n message: T,\n timeout = 30000,\n timeoutMessage = \"Request timed out\",\n abortSignal?: AbortSignal,\n ): Promise<any> {\n if (this._disposed) {\n return Promise.reject(new Error(\"AssistantFrameHost has been disposed\"));\n }\n if (abortSignal?.aborted) {\n return Promise.reject(getAbortReason(abortSignal));\n }\n\n return new Promise((resolve, reject) => {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n const onAbort = () => {\n if (!abortSignal) return;\n const pending = this._pendingRequests.get(message.id);\n if (pending) {\n this.cancelToolCall(message.id);\n pending.reject(getAbortReason(abortSignal));\n this._pendingRequests.delete(message.id);\n }\n };\n const cleanup = () => {\n if (timeoutId !== undefined) clearTimeout(timeoutId);\n abortSignal?.removeEventListener(\"abort\", onAbort);\n };\n\n this._pendingRequests.set(message.id, {\n resolve: (value: any) => {\n cleanup();\n resolve(value);\n },\n reject: (error: any) => {\n cleanup();\n reject(error);\n },\n });\n\n timeoutId = setTimeout(() => {\n const pending = this._pendingRequests.get(message.id);\n if (pending) {\n this.cancelToolCall(message.id);\n pending.reject(new Error(timeoutMessage));\n this._pendingRequests.delete(message.id);\n }\n }, timeout);\n abortSignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n try {\n this._iframeWindow.postMessage(\n { channel: FRAME_MESSAGE_CHANNEL, message },\n this._targetOrigin,\n );\n } catch (error) {\n const pending = this._pendingRequests.get(message.id);\n this._pendingRequests.delete(message.id);\n pending?.reject(error);\n }\n });\n }\n\n private cancelToolCall(id: string) {\n this._iframeWindow.postMessage(\n {\n channel: FRAME_MESSAGE_CHANNEL,\n message: { type: \"tool-cancel\", id } satisfies FrameMessage,\n },\n this._targetOrigin,\n );\n }\n\n private requestContext() {\n this._iframeWindow.postMessage(\n {\n channel: FRAME_MESSAGE_CHANNEL,\n message: {\n type: \"model-context-request\",\n } as FrameMessage,\n },\n this._targetOrigin,\n );\n }\n\n private notifySubscribers() {\n notifyStateSubscribers(this._subscribers);\n }\n\n getModelContext(): ModelContext {\n return this._context;\n }\n\n subscribe(callback: () => void): Unsubscribe {\n this._subscribers.add(callback);\n return () => this._subscribers.delete(callback);\n }\n\n dispose() {\n this._disposed = true;\n window.removeEventListener(\"message\", this.handleMessage);\n this._subscribers.clear();\n const error = new Error(\"AssistantFrameHost has been disposed\");\n for (const [id, pending] of this._pendingRequests) {\n this.cancelToolCall(id);\n pending.reject(error);\n }\n this._pendingRequests.clear();\n }\n}\n"],"mappings":";;;;AAYA,MAAMW,+BAA+BC,OAAOC,SAASC;;;;AAKrD,MAAMC,mBAAmBC,oBACtB;CACCC,YAAYD,eAAeC;CAC3B,GAAID,eAAeE,eAAe,EAChCA,aAAaF,eAAeE,YAC9B;CACA,GAAIF,eAAeG,aAAaC,KAAAA,KAAa,EAC3CD,UAAUH,eAAeG,SAC3B;CACA,GAAIH,eAAeK,QAAQ,EAAEA,MAAML,eAAeK,KAAK;AACzD;;;;AAKF,MAAMC,2BACJC,gBACkB;CAClB,GAAIA,WAAWC,WAAWJ,KAAAA,KAAa,EAAEI,QAAQD,WAAWC,OAAO;CACnE,GAAID,WAAWE,SAAS,EACtBA,OAAOC,OAAOC,YACZD,OAAOE,QAAQL,WAAWE,KAAK,CAAC,CAACI,KAAK,CAACC,MAAMC,UAAU,CACrDD,MACAf,gBAAgBgB,IAAI,CAAC,CACtB,CACH,EACF;AACF;AAEA,MAAMC,kBAAkBC,WAAiC;CACvD,IAAIA,OAAOE,WAAWf,KAAAA,GAAW,OAAOa,OAAOE;CAC/C,MAAMC,wBAAQ,IAAIC,MAAM,uBAAuB;CAC/CD,MAAMN,OAAO;CACb,OAAOM;AACT;AAEA,IAAaE,qBAAb,MAAgE;CAC9D,WAAiC,CAAC;CAClC,+BAAuB,IAAIG,IAAgB;CAC3C,mCAA2B,IAAIE,IAM7B;CACF;CACA;CACA,YAAoB;CAEpBQ,YACEC,cACAC,eAAuB1C,uBAAuB,GAC9C;EACA,KAAKoC,gBAAgBK;EACrB,KAAKH,gBAAgBI;EAErB,KAAKC,gBAAgB,KAAKA,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AAiByB,IAAIJ,QAAQK,EAAE;IACpD,KAAK1B,iBAAiB4B,OAAOP,QAAQK,EAAE;IACvCF,SAASpB,OAAOV,KAAK;GACvB;EACF,CAAC;CACH;CAEA,eAAuBgC,IAAY;EACjC,KAAKrB,cAAc8C,YACjB;GACE/B,SAAStD;GACTuD,SAAS;IAAE1C,MAAM;IAAe+C;GAAG;EACrC,GACA,KAAKnB,aACP;CACF;CAEA,iBAAyB;EACvB,KAAKF,cAAc8C,YACjB;GACE/B,SAAStD;GACTuD,SAAS,EACP1C,MAAM,wBACR;EACF,GACA,KAAK4B,aACP;CACF;CAEA,oBAA4B;EAC1B5C,kBAAuB,KAAKmC,YAAY;CAC1C;CAEAsD,kBAAgC;EAC9B,OAAO,KAAKvD;CACd;CAEAwD,UAAUC,UAAmC;EAC3C,KAAKxD,aAAayD,IAAID,QAAQ;EAC9B,aAAa,KAAKxD,aAAa8B,OAAO0B,QAAQ;CAChD;CAEAE,UAAU;EACR,KAAKhD,YAAY;EACjBtC,OAAO8E,oBAAoB,WAAW,KAAKpC,aAAa;EACxD,KAAKd,aAAa2D,MAAM;EACxB,MAAM/D,wBAAQ,IAAIC,MAAM,sCAAsC;EAC9D,KAAK,MAAM,CAAC+B,IAAIF,YAAY,KAAKxB,kBAAkB;GACjD,KAAK6C,eAAenB,EAAE;GACtBF,QAAQpB,OAAOV,KAAK;EACtB;EACA,KAAKM,iBAAiByD,MAAM;CAC9B;AACF"}
1
+ {"version":3,"file":"host.js","names":["ModelContextProvider","ModelContext","Unsubscribe","Tool","notifySubscribers","notifyStateSubscribers","generateId","FrameMessage","FRAME_MESSAGE_CHANNEL","SerializedModelContext","SerializedTool","getDefaultTargetOrigin","window","location","origin","logCancellationFailure","error","console","deserializeTool","serializedTool","parameters","description","disabled","undefined","type","deserializeModelContext","serialized","system","tools","Object","fromEntries","entries","map","name","tool","getAbortReason","signal","AbortSignal","reason","Error","AssistantFrameHost","_context","_subscribers","Set","_pendingRequests","Map","resolve","value","reject","_iframeWindow","Window","_targetOrigin","_disposed","constructor","iframeWindow","targetOrigin","handleMessage","bind","requestContext","addEventListener","event","MessageEvent","source","data","channel","message","updateContext","context","pending","get","id","result","delete","serializedContext","execute","args","abortSignal","callTool","toolName","Promise","sendRequest","T","timeout","timeoutMessage","aborted","timeoutId","ReturnType","setTimeout","onAbort","cancelToolCall","cleanup","clearTimeout","removeEventListener","set","once","postMessage","onError","getModelContext","subscribe","callback","add","dispose","clear","cancellationFailed","cancellationError"],"sources":["../../../src/model-context/frame/host.ts"],"sourcesContent":["import type { ModelContextProvider, ModelContext } from \"../types\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { Tool } from \"assistant-stream\";\nimport { notifySubscribers as notifyStateSubscribers } from \"../../subscribable/subscribable\";\nimport { generateId } from \"../../utils/id\";\nimport {\n type FrameMessage,\n FRAME_MESSAGE_CHANNEL,\n type SerializedModelContext,\n type SerializedTool,\n} from \"./types\";\n\nconst getDefaultTargetOrigin = () => window.location.origin;\n\nconst logCancellationFailure = (error: unknown) => {\n console.error(\n \"[assistant-ui] AssistantFrameHost tool cancellation could not be sent.\",\n error,\n );\n};\n\n/**\n * Deserializes tools from JSON Schema format back to Tool objects\n */\nconst deserializeTool = (serializedTool: SerializedTool): Tool<any, any> =>\n ({\n parameters: serializedTool.parameters,\n ...(serializedTool.description && {\n description: serializedTool.description,\n }),\n ...(serializedTool.disabled !== undefined && {\n disabled: serializedTool.disabled,\n }),\n ...(serializedTool.type && { type: serializedTool.type }),\n }) as Tool<any, any>;\n\n/**\n * Deserializes a ModelContext from transmission format\n */\nconst deserializeModelContext = (\n serialized: SerializedModelContext,\n): ModelContext => ({\n ...(serialized.system !== undefined && { system: serialized.system }),\n ...(serialized.tools && {\n tools: Object.fromEntries(\n Object.entries(serialized.tools).map(([name, tool]) => [\n name,\n deserializeTool(tool),\n ]),\n ),\n }),\n});\n\nconst getAbortReason = (signal: AbortSignal): unknown => {\n if (signal.reason !== undefined) return signal.reason;\n const error = new Error(\"Tool call was aborted\");\n error.name = \"AbortError\";\n return error;\n};\n\nexport class AssistantFrameHost implements ModelContextProvider {\n private _context: ModelContext = {};\n private _subscribers = new Set<() => void>();\n private _pendingRequests = new Map<\n string,\n {\n resolve: (value: any) => void;\n reject: (error: any) => void;\n }\n >();\n private _iframeWindow: Window;\n private _targetOrigin: string;\n private _disposed = false;\n\n constructor(\n iframeWindow: Window,\n targetOrigin: string = getDefaultTargetOrigin(),\n ) {\n this._iframeWindow = iframeWindow;\n this._targetOrigin = targetOrigin;\n\n this.handleMessage = this.handleMessage.bind(this);\n // A posted message cannot be delivered before this constructor returns, so\n // requesting first means a failed request leaves no listener to clean up.\n this.requestContext();\n window.addEventListener(\"message\", this.handleMessage);\n }\n\n private handleMessage(event: MessageEvent) {\n if (this._targetOrigin !== \"*\" && event.origin !== this._targetOrigin)\n return;\n if (event.source !== this._iframeWindow) return;\n if (event.data?.channel !== FRAME_MESSAGE_CHANNEL) return;\n\n const message = event.data.message as FrameMessage;\n\n switch (message.type) {\n case \"model-context-update\": {\n this.updateContext(message.context);\n break;\n }\n\n case \"tool-result\": {\n const pending = this._pendingRequests.get(message.id);\n if (pending) {\n if (typeof message.error === \"string\") {\n pending.reject(new Error(message.error));\n } else {\n pending.resolve(message.result);\n }\n this._pendingRequests.delete(message.id);\n }\n break;\n }\n }\n }\n\n private updateContext(serializedContext: SerializedModelContext) {\n const context = deserializeModelContext(serializedContext);\n this._context = {\n ...context,\n tools:\n context.tools &&\n Object.fromEntries(\n Object.entries(context.tools).map(([name, tool]) => [\n name,\n {\n ...tool,\n execute: (args: any, context: { abortSignal: AbortSignal }) =>\n this.callTool(name, args, context.abortSignal),\n } as Tool<any, any>,\n ]),\n ),\n };\n this.notifySubscribers();\n }\n\n private callTool(\n toolName: string,\n args: any,\n abortSignal: AbortSignal,\n ): Promise<any> {\n return this.sendRequest(\n {\n type: \"tool-call\",\n id: `tool-${generateId()}`,\n toolName,\n args,\n },\n 30000,\n `Tool call \"${toolName}\" timed out`,\n abortSignal,\n );\n }\n\n private sendRequest<T extends FrameMessage & { id: string }>(\n message: T,\n timeout = 30000,\n timeoutMessage = \"Request timed out\",\n abortSignal?: AbortSignal,\n ): Promise<any> {\n if (this._disposed) {\n return Promise.reject(new Error(\"AssistantFrameHost has been disposed\"));\n }\n if (abortSignal?.aborted) {\n return Promise.reject(getAbortReason(abortSignal));\n }\n\n return new Promise((resolve, reject) => {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n const onAbort = () => {\n if (!abortSignal) return;\n const pending = this._pendingRequests.get(message.id);\n if (pending) {\n this.cancelToolCall(message.id);\n pending.reject(getAbortReason(abortSignal));\n this._pendingRequests.delete(message.id);\n }\n };\n const cleanup = () => {\n if (timeoutId !== undefined) clearTimeout(timeoutId);\n abortSignal?.removeEventListener(\"abort\", onAbort);\n };\n\n this._pendingRequests.set(message.id, {\n resolve: (value: any) => {\n cleanup();\n resolve(value);\n },\n reject: (error: any) => {\n cleanup();\n reject(error);\n },\n });\n\n timeoutId = setTimeout(() => {\n const pending = this._pendingRequests.get(message.id);\n if (pending) {\n this.cancelToolCall(message.id);\n pending.reject(new Error(timeoutMessage));\n this._pendingRequests.delete(message.id);\n }\n }, timeout);\n abortSignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n try {\n this._iframeWindow.postMessage(\n { channel: FRAME_MESSAGE_CHANNEL, message },\n this._targetOrigin,\n );\n } catch (error) {\n const pending = this._pendingRequests.get(message.id);\n this._pendingRequests.delete(message.id);\n pending?.reject(error);\n }\n });\n }\n\n private cancelToolCall(\n id: string,\n onError: (error: unknown) => void = logCancellationFailure,\n ) {\n try {\n this._iframeWindow.postMessage(\n {\n channel: FRAME_MESSAGE_CHANNEL,\n message: { type: \"tool-cancel\", id } satisfies FrameMessage,\n },\n this._targetOrigin,\n );\n } catch (error) {\n onError(error);\n }\n }\n\n private requestContext() {\n this._iframeWindow.postMessage(\n {\n channel: FRAME_MESSAGE_CHANNEL,\n message: {\n type: \"model-context-request\",\n } as FrameMessage,\n },\n this._targetOrigin,\n );\n }\n\n private notifySubscribers() {\n notifyStateSubscribers(this._subscribers);\n }\n\n getModelContext(): ModelContext {\n return this._context;\n }\n\n subscribe(callback: () => void): Unsubscribe {\n this._subscribers.add(callback);\n return () => this._subscribers.delete(callback);\n }\n\n dispose() {\n this._disposed = true;\n window.removeEventListener(\"message\", this.handleMessage);\n this._subscribers.clear();\n const error = new Error(\"AssistantFrameHost has been disposed\");\n let cancellationFailed = false;\n let cancellationError: unknown;\n\n for (const [id, pending] of this._pendingRequests) {\n this._pendingRequests.delete(id);\n this.cancelToolCall(id, (error) => {\n if (!cancellationFailed) {\n cancellationFailed = true;\n cancellationError = error;\n } else {\n logCancellationFailure(error);\n }\n });\n pending.reject(error);\n }\n\n if (cancellationFailed) throw cancellationError;\n }\n}\n"],"mappings":";;;;AAYA,MAAMW,+BAA+BC,OAAOC,SAASC;AAErD,MAAMC,0BAA0BC,UAAmB;CACjDC,QAAQD,MACN,0EACAA,KACF;AACF;;;;AAKA,MAAME,mBAAmBC,oBACtB;CACCC,YAAYD,eAAeC;CAC3B,GAAID,eAAeE,eAAe,EAChCA,aAAaF,eAAeE,YAC9B;CACA,GAAIF,eAAeG,aAAaC,KAAAA,KAAa,EAC3CD,UAAUH,eAAeG,SAC3B;CACA,GAAIH,eAAeK,QAAQ,EAAEA,MAAML,eAAeK,KAAK;AACzD;;;;AAKF,MAAMC,2BACJC,gBACkB;CAClB,GAAIA,WAAWC,WAAWJ,KAAAA,KAAa,EAAEI,QAAQD,WAAWC,OAAO;CACnE,GAAID,WAAWE,SAAS,EACtBA,OAAOC,OAAOC,YACZD,OAAOE,QAAQL,WAAWE,KAAK,CAAC,CAACI,KAAK,CAACC,MAAMC,UAAU,CACrDD,MACAf,gBAAgBgB,IAAI,CAAC,CACtB,CACH,EACF;AACF;AAEA,MAAMC,kBAAkBC,WAAiC;CACvD,IAAIA,OAAOE,WAAWf,KAAAA,GAAW,OAAOa,OAAOE;CAC/C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kB;GACjD,KAAKA,iBAAiB4B,OAAOF,EAAE;GAC/B,KAAKmB,eAAenB,KAAKtD,UAAU;IACjC,IAAI,CAACuF,oBAAoB;KACvBA,qBAAqB;KACrBC,oBAAoBxF;IACtB,OACED,uBAAuBC,KAAK;GAEhC,CAAC;GACDoD,QAAQpB,OAAOhC,KAAK;EACtB;EAEA,IAAIuF,oBAAoB,MAAMC;CAChC;AACF"}
@@ -84,13 +84,15 @@ function applyArrayUpdate(prev, update, mintId) {
84
84
  function shallowMergeInteractableState(prev, partial, options) {
85
85
  if (!isRecord(prev) || !isRecord(partial)) return partial;
86
86
  const baseline = isRecord(options?.arrayBaseline) ? options.arrayBaseline : prev;
87
- const next = { ...prev };
87
+ const next = Object.entries(prev);
88
88
  for (const [key, value] of Object.entries(partial)) {
89
89
  const baseValue = baseline[key];
90
- if (Array.isArray(baseValue) && isRecord(value)) next[key] = applyArrayUpdate(baseValue, value, options?.idFactory && (options.idKeyedFields === void 0 || options.idKeyedFields.has(key)) ? () => options.idFactory?.(key) : void 0);
91
- else next[key] = value;
90
+ if (Array.isArray(baseValue) && isRecord(value)) {
91
+ const mintId = options?.idFactory && (options.idKeyedFields === void 0 || options.idKeyedFields.has(key)) ? () => options.idFactory?.(key) : void 0;
92
+ next.push([key, applyArrayUpdate(baseValue, value, mintId)]);
93
+ } else next.push([key, value]);
92
94
  }
93
- return next;
95
+ return Object.fromEntries(next);
94
96
  }
95
97
  /**
96
98
  * The top-level fields of `next` that differ from `known`, for stamping a
@@ -101,12 +103,12 @@ function shallowMergeInteractableState(prev, partial, options) {
101
103
  */
102
104
  function shallowDiffInteractableState(known, next) {
103
105
  if (!isRecord(known) || !isRecord(next)) return void 0;
104
- for (const key of Object.keys(known)) if (!(key in next)) return void 0;
105
- const diff = {};
106
- for (const [key, value] of Object.entries(next)) if (!(key in known) || !isJSONValueEqual(known[key], value)) diff[key] = value;
107
- const changed = Object.keys(diff).length;
106
+ for (const key of Object.keys(known)) if (!Object.hasOwn(next, key)) return void 0;
107
+ const diff = [];
108
+ for (const [key, value] of Object.entries(next)) if (!Object.hasOwn(known, key) || !isJSONValueEqual(known[key], value)) diff.push([key, value]);
109
+ const changed = diff.length;
108
110
  if (changed === 0 || changed === Object.keys(next).length) return void 0;
109
- return diff;
111
+ return Object.fromEntries(diff);
110
112
  }
111
113
  const asToolCallPart = (part) => {
112
114
  if (!part || typeof part !== "object") return void 0;