@assistant-ui/core 0.2.9 → 0.2.11

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 (437) hide show
  1. package/dist/adapters/attachment.d.ts.map +1 -1
  2. package/dist/adapters/attachment.js +22 -12
  3. package/dist/adapters/attachment.js.map +1 -1
  4. package/dist/adapters/directive-formatter.js.map +1 -1
  5. package/dist/adapters/speech.js.map +1 -1
  6. package/dist/index.d.ts +3 -1
  7. package/dist/index.js +2 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/internal.js +1 -1
  10. package/dist/model-context/frame/host.js.map +1 -1
  11. package/dist/model-context/frame/provider.js.map +1 -1
  12. package/dist/model-context/registry.js.map +1 -1
  13. package/dist/model-context/tool.d.ts +1 -1
  14. package/dist/model-context/tool.js +1 -1
  15. package/dist/model-context/tool.js.map +1 -1
  16. package/dist/model-context/types.js +17 -2
  17. package/dist/model-context/types.js.map +1 -1
  18. package/dist/react/AssistantProvider.js +1 -1
  19. package/dist/react/AssistantRuntimeProvider.d.ts +1 -1
  20. package/dist/react/AssistantRuntimeProvider.d.ts.map +1 -1
  21. package/dist/react/AssistantRuntimeProvider.js +1 -1
  22. package/dist/react/RuntimeAdapter.js +4 -2
  23. package/dist/react/RuntimeAdapter.js.map +1 -1
  24. package/dist/react/adapters/LocalStorageThreadListAdapter.d.ts.map +1 -1
  25. package/dist/react/adapters/LocalStorageThreadListAdapter.js +13 -3
  26. package/dist/react/adapters/LocalStorageThreadListAdapter.js.map +1 -1
  27. package/dist/react/client/DataRenderers.d.ts.map +1 -1
  28. package/dist/react/client/DataRenderers.js +6 -5
  29. package/dist/react/client/DataRenderers.js.map +1 -1
  30. package/dist/react/client/Interactables.d.ts.map +1 -1
  31. package/dist/react/client/Interactables.js +30 -29
  32. package/dist/react/client/Interactables.js.map +1 -1
  33. package/dist/react/client/Tools.d.ts.map +1 -1
  34. package/dist/react/client/Tools.js +19 -12
  35. package/dist/react/client/Tools.js.map +1 -1
  36. package/dist/react/index.d.ts +10 -5
  37. package/dist/react/index.js +7 -2
  38. package/dist/react/model-context/define-mcp-toolkit.d.ts +12 -0
  39. package/dist/react/model-context/define-mcp-toolkit.d.ts.map +1 -0
  40. package/dist/react/model-context/define-mcp-toolkit.js +14 -0
  41. package/dist/react/model-context/define-mcp-toolkit.js.map +1 -0
  42. package/dist/react/model-context/define-toolkit.d.ts +10 -12
  43. package/dist/react/model-context/define-toolkit.d.ts.map +1 -1
  44. package/dist/react/model-context/define-toolkit.js +2 -15
  45. package/dist/react/model-context/define-toolkit.js.map +1 -1
  46. package/dist/react/model-context/external-tool.d.ts +14 -0
  47. package/dist/react/model-context/external-tool.d.ts.map +1 -0
  48. package/dist/react/model-context/external-tool.js +17 -0
  49. package/dist/react/model-context/external-tool.js.map +1 -0
  50. package/dist/react/model-context/human-tool.d.ts +27 -0
  51. package/dist/react/model-context/human-tool.d.ts.map +1 -0
  52. package/dist/react/model-context/human-tool.js +30 -0
  53. package/dist/react/model-context/human-tool.js.map +1 -0
  54. package/dist/react/model-context/makeAssistantTool.d.ts +8 -0
  55. package/dist/react/model-context/makeAssistantTool.d.ts.map +1 -1
  56. package/dist/react/model-context/makeAssistantTool.js +4 -0
  57. package/dist/react/model-context/makeAssistantTool.js.map +1 -1
  58. package/dist/react/model-context/makeAssistantToolUI.d.ts +8 -0
  59. package/dist/react/model-context/makeAssistantToolUI.d.ts.map +1 -1
  60. package/dist/react/model-context/makeAssistantToolUI.js +4 -0
  61. package/dist/react/model-context/makeAssistantToolUI.js.map +1 -1
  62. package/dist/react/model-context/provider-tool.d.ts +15 -0
  63. package/dist/react/model-context/provider-tool.d.ts.map +1 -0
  64. package/dist/react/model-context/provider-tool.js +12 -0
  65. package/dist/react/model-context/provider-tool.js.map +1 -0
  66. package/dist/react/model-context/stub-tool.d.ts +12 -0
  67. package/dist/react/model-context/stub-tool.d.ts.map +1 -0
  68. package/dist/react/model-context/stub-tool.js +15 -0
  69. package/dist/react/model-context/stub-tool.js.map +1 -0
  70. package/dist/react/model-context/toolbox.d.ts +64 -17
  71. package/dist/react/model-context/toolbox.d.ts.map +1 -1
  72. package/dist/react/model-context/toolbox.js +19 -1
  73. package/dist/react/model-context/toolbox.js.map +1 -1
  74. package/dist/react/model-context/useAssistantContext.js +1 -1
  75. package/dist/react/model-context/useAssistantContext.js.map +1 -1
  76. package/dist/react/model-context/useAssistantDataUI.js +1 -1
  77. package/dist/react/model-context/useAssistantDataUI.js.map +1 -1
  78. package/dist/react/model-context/useAssistantInstructions.js +1 -1
  79. package/dist/react/model-context/useAssistantInstructions.js.map +1 -1
  80. package/dist/react/model-context/useAssistantInteractable.js +1 -1
  81. package/dist/react/model-context/useAssistantInteractable.js.map +1 -1
  82. package/dist/react/model-context/useAssistantTool.d.ts +11 -1
  83. package/dist/react/model-context/useAssistantTool.d.ts.map +1 -1
  84. package/dist/react/model-context/useAssistantTool.js +12 -6
  85. package/dist/react/model-context/useAssistantTool.js.map +1 -1
  86. package/dist/react/model-context/useAssistantToolUI.d.ts +13 -4
  87. package/dist/react/model-context/useAssistantToolUI.d.ts.map +1 -1
  88. package/dist/react/model-context/useAssistantToolUI.js +7 -4
  89. package/dist/react/model-context/useAssistantToolUI.js.map +1 -1
  90. package/dist/react/model-context/useAuiToolOverrides.d.ts +22 -0
  91. package/dist/react/model-context/useAuiToolOverrides.d.ts.map +1 -0
  92. package/dist/react/model-context/useAuiToolOverrides.js +31 -0
  93. package/dist/react/model-context/useAuiToolOverrides.js.map +1 -0
  94. package/dist/react/model-context/useInlineRender.js +1 -1
  95. package/dist/react/model-context/useInlineRender.js.map +1 -1
  96. package/dist/react/model-context/useInteractableState.js +1 -1
  97. package/dist/react/model-context/useInteractableState.js.map +1 -1
  98. package/dist/react/model-context/useToolArgsStatus.js +1 -1
  99. package/dist/react/primitive-hooks/useActionBarCopy.js +1 -1
  100. package/dist/react/primitive-hooks/useActionBarCopy.js.map +1 -1
  101. package/dist/react/primitive-hooks/useActionBarEdit.js +1 -1
  102. package/dist/react/primitive-hooks/useActionBarEdit.js.map +1 -1
  103. package/dist/react/primitive-hooks/useActionBarFeedback.js +1 -1
  104. package/dist/react/primitive-hooks/useActionBarFeedback.js.map +1 -1
  105. package/dist/react/primitive-hooks/useActionBarReload.js +1 -1
  106. package/dist/react/primitive-hooks/useActionBarReload.js.map +1 -1
  107. package/dist/react/primitive-hooks/useActionBarSpeak.js +1 -1
  108. package/dist/react/primitive-hooks/useActionBarSpeak.js.map +1 -1
  109. package/dist/react/primitive-hooks/useActionBarStopSpeaking.js +1 -1
  110. package/dist/react/primitive-hooks/useActionBarStopSpeaking.js.map +1 -1
  111. package/dist/react/primitive-hooks/useBranchPickerNext.js +1 -1
  112. package/dist/react/primitive-hooks/useBranchPickerNext.js.map +1 -1
  113. package/dist/react/primitive-hooks/useBranchPickerPrevious.js +1 -1
  114. package/dist/react/primitive-hooks/useBranchPickerPrevious.js.map +1 -1
  115. package/dist/react/primitive-hooks/useComposerAddAttachment.js +1 -1
  116. package/dist/react/primitive-hooks/useComposerAddAttachment.js.map +1 -1
  117. package/dist/react/primitive-hooks/useComposerCancel.js +1 -1
  118. package/dist/react/primitive-hooks/useComposerCancel.js.map +1 -1
  119. package/dist/react/primitive-hooks/useComposerDictate.js +1 -1
  120. package/dist/react/primitive-hooks/useComposerDictate.js.map +1 -1
  121. package/dist/react/primitive-hooks/useComposerSend.js +1 -1
  122. package/dist/react/primitive-hooks/useComposerSend.js.map +1 -1
  123. package/dist/react/primitive-hooks/useEditComposerCancel.js +1 -1
  124. package/dist/react/primitive-hooks/useEditComposerCancel.js.map +1 -1
  125. package/dist/react/primitive-hooks/useEditComposerSend.js +1 -1
  126. package/dist/react/primitive-hooks/useEditComposerSend.js.map +1 -1
  127. package/dist/react/primitive-hooks/useMessageBranching.js +1 -1
  128. package/dist/react/primitive-hooks/useMessageBranching.js.map +1 -1
  129. package/dist/react/primitive-hooks/useMessageReload.js +1 -1
  130. package/dist/react/primitive-hooks/useMessageReload.js.map +1 -1
  131. package/dist/react/primitive-hooks/useSuggestionTrigger.js +1 -1
  132. package/dist/react/primitive-hooks/useSuggestionTrigger.js.map +1 -1
  133. package/dist/react/primitive-hooks/useThreadListItemArchive.js +1 -1
  134. package/dist/react/primitive-hooks/useThreadListItemArchive.js.map +1 -1
  135. package/dist/react/primitive-hooks/useThreadListItemDelete.js +1 -1
  136. package/dist/react/primitive-hooks/useThreadListItemDelete.js.map +1 -1
  137. package/dist/react/primitive-hooks/useThreadListItemTrigger.js +1 -1
  138. package/dist/react/primitive-hooks/useThreadListItemTrigger.js.map +1 -1
  139. package/dist/react/primitive-hooks/useThreadListItemUnarchive.js +1 -1
  140. package/dist/react/primitive-hooks/useThreadListItemUnarchive.js.map +1 -1
  141. package/dist/react/primitive-hooks/useThreadListLoadMore.js +1 -1
  142. package/dist/react/primitive-hooks/useThreadListLoadMore.js.map +1 -1
  143. package/dist/react/primitive-hooks/useThreadListNew.js +1 -1
  144. package/dist/react/primitive-hooks/useThreadListNew.js.map +1 -1
  145. package/dist/react/primitive-hooks/useVoice.js +1 -1
  146. package/dist/react/primitive-hooks/useVoice.js.map +1 -1
  147. package/dist/react/primitives/chainOfThought/ChainOfThoughtParts.d.ts +1 -1
  148. package/dist/react/primitives/chainOfThought/ChainOfThoughtParts.js +1 -1
  149. package/dist/react/primitives/chainOfThought/ChainOfThoughtParts.js.map +1 -1
  150. package/dist/react/primitives/composer/ComposerAttachments.js +1 -1
  151. package/dist/react/primitives/composer/ComposerAttachments.js.map +1 -1
  152. package/dist/react/primitives/composer/ComposerQueue.js +1 -1
  153. package/dist/react/primitives/composer/ComposerQueue.js.map +1 -1
  154. package/dist/react/primitives/generativeUI/GenerativeUI.js +1 -1
  155. package/dist/react/primitives/generativeUI/GenerativeUI.js.map +1 -1
  156. package/dist/react/primitives/message/MessageAttachments.js +1 -1
  157. package/dist/react/primitives/message/MessageAttachments.js.map +1 -1
  158. package/dist/react/primitives/message/MessageGroupedParts.js +1 -1
  159. package/dist/react/primitives/message/MessageGroupedParts.js.map +1 -1
  160. package/dist/react/primitives/message/MessageParts.d.ts +1 -1
  161. package/dist/react/primitives/message/MessageParts.js +1 -1
  162. package/dist/react/primitives/message/MessageParts.js.map +1 -1
  163. package/dist/react/primitives/message/MessageQuote.js +1 -1
  164. package/dist/react/primitives/part/PartMessages.d.ts +12 -10
  165. package/dist/react/primitives/part/PartMessages.d.ts.map +1 -1
  166. package/dist/react/primitives/part/PartMessages.js +13 -11
  167. package/dist/react/primitives/part/PartMessages.js.map +1 -1
  168. package/dist/react/primitives/thread/ThreadMessages.js +1 -1
  169. package/dist/react/primitives/thread/ThreadMessages.js.map +1 -1
  170. package/dist/react/primitives/thread/ThreadSuggestions.js +1 -1
  171. package/dist/react/primitives/thread/ThreadSuggestions.js.map +1 -1
  172. package/dist/react/primitives/threadList/ThreadListItems.js +1 -1
  173. package/dist/react/primitives/threadList/ThreadListItems.js.map +1 -1
  174. package/dist/react/providers/AttachmentByIndexProvider.js.map +1 -1
  175. package/dist/react/providers/ChainOfThoughtByIndicesProvider.js.map +1 -1
  176. package/dist/react/providers/ChainOfThoughtPartByIndexProvider.js.map +1 -1
  177. package/dist/react/providers/MessageByIndexProvider.js.map +1 -1
  178. package/dist/react/providers/PartByIndexProvider.js.map +1 -1
  179. package/dist/react/providers/QueueItemByIndexProvider.js.map +1 -1
  180. package/dist/react/providers/ReadonlyThreadProvider.js +1 -1
  181. package/dist/react/providers/ReadonlyThreadProvider.js.map +1 -1
  182. package/dist/react/providers/SuggestionByIndexProvider.js.map +1 -1
  183. package/dist/react/providers/TextMessagePartProvider.d.ts.map +1 -1
  184. package/dist/react/providers/TextMessagePartProvider.js +4 -3
  185. package/dist/react/providers/TextMessagePartProvider.js.map +1 -1
  186. package/dist/react/providers/ThreadListItemByIndexProvider.js.map +1 -1
  187. package/dist/react/runtimes/RemoteThreadListHookInstanceManager.d.ts +7 -0
  188. package/dist/react/runtimes/RemoteThreadListHookInstanceManager.d.ts.map +1 -1
  189. package/dist/react/runtimes/RemoteThreadListHookInstanceManager.js +1 -1
  190. package/dist/react/runtimes/RemoteThreadListHookInstanceManager.js.map +1 -1
  191. package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts +8 -0
  192. package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts.map +1 -1
  193. package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js +29 -1
  194. package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js.map +1 -1
  195. package/dist/react/runtimes/RuntimeAdapterProvider.js +1 -1
  196. package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.js +1 -1
  197. package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.js.map +1 -1
  198. package/dist/react/runtimes/cloud/useCloudThreadListAdapter.d.ts.map +1 -1
  199. package/dist/react/runtimes/cloud/useCloudThreadListAdapter.js +10 -3
  200. package/dist/react/runtimes/cloud/useCloudThreadListAdapter.js.map +1 -1
  201. package/dist/react/runtimes/createMessageConverter.d.ts +2 -2
  202. package/dist/react/runtimes/createMessageConverter.d.ts.map +1 -1
  203. package/dist/react/runtimes/createMessageConverter.js.map +1 -1
  204. package/dist/react/runtimes/external-message-converter.d.ts +4 -3
  205. package/dist/react/runtimes/external-message-converter.d.ts.map +1 -1
  206. package/dist/react/runtimes/external-message-converter.js +1 -1
  207. package/dist/react/runtimes/external-message-converter.js.map +1 -1
  208. package/dist/react/runtimes/useExternalStoreRuntime.js +1 -1
  209. package/dist/react/runtimes/useExternalStoreSharedOptions.js +1 -1
  210. package/dist/react/runtimes/useLocalRuntime.d.ts +2 -1
  211. package/dist/react/runtimes/useLocalRuntime.d.ts.map +1 -1
  212. package/dist/react/runtimes/useLocalRuntime.js +4 -3
  213. package/dist/react/runtimes/useLocalRuntime.js.map +1 -1
  214. package/dist/react/runtimes/useRemoteThreadListRuntime.js +1 -1
  215. package/dist/react/runtimes/useRemoteThreadListRuntime.js.map +1 -1
  216. package/dist/react/utils/groupParts.d.ts +1 -1
  217. package/dist/react/utils/groupParts.js.map +1 -1
  218. package/dist/runtime/api/attachment-runtime.js.map +1 -1
  219. package/dist/runtime/api/composer-runtime.d.ts +8 -2
  220. package/dist/runtime/api/composer-runtime.d.ts.map +1 -1
  221. package/dist/runtime/api/composer-runtime.js +14 -0
  222. package/dist/runtime/api/composer-runtime.js.map +1 -1
  223. package/dist/runtime/api/message-part-runtime.js.map +1 -1
  224. package/dist/runtime/api/message-runtime.js +1 -1
  225. package/dist/runtime/api/message-runtime.js.map +1 -1
  226. package/dist/runtime/api/thread-list-item-runtime.d.ts +2 -0
  227. package/dist/runtime/api/thread-list-item-runtime.d.ts.map +1 -1
  228. package/dist/runtime/api/thread-list-item-runtime.js +6 -0
  229. package/dist/runtime/api/thread-list-item-runtime.js.map +1 -1
  230. package/dist/runtime/api/thread-runtime.d.ts +7 -0
  231. package/dist/runtime/api/thread-runtime.d.ts.map +1 -1
  232. package/dist/runtime/api/thread-runtime.js.map +1 -1
  233. package/dist/runtime/base/base-composer-runtime-core.d.ts +4 -0
  234. package/dist/runtime/base/base-composer-runtime-core.d.ts.map +1 -1
  235. package/dist/runtime/base/base-composer-runtime-core.js +7 -1
  236. package/dist/runtime/base/base-composer-runtime-core.js.map +1 -1
  237. package/dist/runtime/base/base-thread-runtime-core.js.map +1 -1
  238. package/dist/runtime/base/default-thread-composer-runtime-core.d.ts +4 -0
  239. package/dist/runtime/base/default-thread-composer-runtime-core.d.ts.map +1 -1
  240. package/dist/runtime/base/default-thread-composer-runtime-core.js +17 -1
  241. package/dist/runtime/base/default-thread-composer-runtime-core.js.map +1 -1
  242. package/dist/runtime/interfaces/composer-runtime-core.d.ts +6 -1
  243. package/dist/runtime/interfaces/composer-runtime-core.d.ts.map +1 -1
  244. package/dist/runtime/interfaces/thread-list-runtime-core.d.ts +1 -0
  245. package/dist/runtime/interfaces/thread-list-runtime-core.d.ts.map +1 -1
  246. package/dist/runtime/interfaces/thread-runtime-core.d.ts +4 -0
  247. package/dist/runtime/interfaces/thread-runtime-core.d.ts.map +1 -1
  248. package/dist/runtime/queue/external-thread-queue-adapter.d.ts +20 -0
  249. package/dist/runtime/queue/external-thread-queue-adapter.d.ts.map +1 -0
  250. package/dist/runtime/queue/external-thread-queue-adapter.js +0 -0
  251. package/dist/runtime/queue/message-queue.d.ts +20 -0
  252. package/dist/runtime/queue/message-queue.d.ts.map +1 -0
  253. package/dist/runtime/queue/message-queue.js +97 -0
  254. package/dist/runtime/queue/message-queue.js.map +1 -0
  255. package/dist/runtime/utils/message-repository.js.map +1 -1
  256. package/dist/runtime/utils/thread-message-like.js.map +1 -1
  257. package/dist/runtimes/external-store/external-store-adapter.d.ts +5 -1
  258. package/dist/runtimes/external-store/external-store-adapter.d.ts.map +1 -1
  259. package/dist/runtimes/external-store/external-store-runtime-core.js.map +1 -1
  260. package/dist/runtimes/external-store/external-store-thread-list-runtime-core.d.ts +1 -0
  261. package/dist/runtimes/external-store/external-store-thread-list-runtime-core.d.ts.map +1 -1
  262. package/dist/runtimes/external-store/external-store-thread-list-runtime-core.js +5 -0
  263. package/dist/runtimes/external-store/external-store-thread-list-runtime-core.js.map +1 -1
  264. package/dist/runtimes/external-store/external-store-thread-runtime-core.d.ts +4 -0
  265. package/dist/runtimes/external-store/external-store-thread-runtime-core.d.ts.map +1 -1
  266. package/dist/runtimes/external-store/external-store-thread-runtime-core.js +20 -2
  267. package/dist/runtimes/external-store/external-store-thread-runtime-core.js.map +1 -1
  268. package/dist/runtimes/local/local-runtime-core.js.map +1 -1
  269. package/dist/runtimes/local/local-runtime-options.d.ts +5 -0
  270. package/dist/runtimes/local/local-runtime-options.d.ts.map +1 -1
  271. package/dist/runtimes/local/local-thread-runtime-core.d.ts +7 -0
  272. package/dist/runtimes/local/local-thread-runtime-core.d.ts.map +1 -1
  273. package/dist/runtimes/local/local-thread-runtime-core.js +45 -0
  274. package/dist/runtimes/local/local-thread-runtime-core.js.map +1 -1
  275. package/dist/runtimes/readonly/ReadonlyThreadRuntimeCore.d.ts +3 -0
  276. package/dist/runtimes/readonly/ReadonlyThreadRuntimeCore.d.ts.map +1 -1
  277. package/dist/runtimes/readonly/ReadonlyThreadRuntimeCore.js +3 -0
  278. package/dist/runtimes/readonly/ReadonlyThreadRuntimeCore.js.map +1 -1
  279. package/dist/runtimes/remote-thread-list/adapter/in-memory.d.ts +1 -0
  280. package/dist/runtimes/remote-thread-list/adapter/in-memory.d.ts.map +1 -1
  281. package/dist/runtimes/remote-thread-list/adapter/in-memory.js +3 -0
  282. package/dist/runtimes/remote-thread-list/adapter/in-memory.js.map +1 -1
  283. package/dist/runtimes/remote-thread-list/empty-thread-core.d.ts.map +1 -1
  284. package/dist/runtimes/remote-thread-list/empty-thread-core.js +3 -0
  285. package/dist/runtimes/remote-thread-list/empty-thread-core.js.map +1 -1
  286. package/dist/runtimes/remote-thread-list/remote-thread-state.js.map +1 -1
  287. package/dist/runtimes/remote-thread-list/types.d.ts +1 -0
  288. package/dist/runtimes/remote-thread-list/types.d.ts.map +1 -1
  289. package/dist/runtimes/tool-invocations/ToolInvocationTracker.js.map +1 -1
  290. package/dist/store/clients/chain-of-thought-client.d.ts.map +1 -1
  291. package/dist/store/clients/chain-of-thought-client.js +6 -5
  292. package/dist/store/clients/chain-of-thought-client.js.map +1 -1
  293. package/dist/store/clients/model-context-client.d.ts.map +1 -1
  294. package/dist/store/clients/model-context-client.js +6 -5
  295. package/dist/store/clients/model-context-client.js.map +1 -1
  296. package/dist/store/clients/no-op-composer-client.d.ts.map +1 -1
  297. package/dist/store/clients/no-op-composer-client.js +4 -3
  298. package/dist/store/clients/no-op-composer-client.js.map +1 -1
  299. package/dist/store/clients/runtime-adapter.d.ts.map +1 -1
  300. package/dist/store/clients/runtime-adapter.js +7 -6
  301. package/dist/store/clients/runtime-adapter.js.map +1 -1
  302. package/dist/store/clients/suggestions.d.ts.map +1 -1
  303. package/dist/store/clients/suggestions.js +7 -6
  304. package/dist/store/clients/suggestions.js.map +1 -1
  305. package/dist/store/clients/thread-message-client.d.ts.map +1 -1
  306. package/dist/store/clients/thread-message-client.js +13 -12
  307. package/dist/store/clients/thread-message-client.js.map +1 -1
  308. package/dist/store/index.d.ts +1 -1
  309. package/dist/store/runtime-clients/attachment-runtime-client.d.ts.map +1 -1
  310. package/dist/store/runtime-clients/attachment-runtime-client.js +3 -3
  311. package/dist/store/runtime-clients/attachment-runtime-client.js.map +1 -1
  312. package/dist/store/runtime-clients/composer-runtime-client.d.ts +12 -5
  313. package/dist/store/runtime-clients/composer-runtime-client.d.ts.map +1 -1
  314. package/dist/store/runtime-clients/composer-runtime-client.js +32 -16
  315. package/dist/store/runtime-clients/composer-runtime-client.js.map +1 -1
  316. package/dist/store/runtime-clients/message-part-runtime-client.d.ts.map +1 -1
  317. package/dist/store/runtime-clients/message-part-runtime-client.js +3 -3
  318. package/dist/store/runtime-clients/message-part-runtime-client.js.map +1 -1
  319. package/dist/store/runtime-clients/message-runtime-client.d.ts +6 -3
  320. package/dist/store/runtime-clients/message-runtime-client.d.ts.map +1 -1
  321. package/dist/store/runtime-clients/message-runtime-client.js +17 -16
  322. package/dist/store/runtime-clients/message-runtime-client.js.map +1 -1
  323. package/dist/store/runtime-clients/thread-list-item-runtime-client.d.ts.map +1 -1
  324. package/dist/store/runtime-clients/thread-list-item-runtime-client.js +9 -7
  325. package/dist/store/runtime-clients/thread-list-item-runtime-client.js.map +1 -1
  326. package/dist/store/runtime-clients/thread-list-runtime-client.d.ts.map +1 -1
  327. package/dist/store/runtime-clients/thread-list-runtime-client.js +11 -10
  328. package/dist/store/runtime-clients/thread-list-runtime-client.js.map +1 -1
  329. package/dist/store/runtime-clients/thread-runtime-client.d.ts.map +1 -1
  330. package/dist/store/runtime-clients/thread-runtime-client.js +15 -14
  331. package/dist/store/runtime-clients/thread-runtime-client.js.map +1 -1
  332. package/dist/store/runtime-clients/useSubscribable.d.ts +7 -0
  333. package/dist/store/runtime-clients/useSubscribable.d.ts.map +1 -0
  334. package/dist/store/runtime-clients/useSubscribable.js +16 -0
  335. package/dist/store/runtime-clients/useSubscribable.js.map +1 -0
  336. package/dist/store/scope-registration.d.ts +1 -1
  337. package/dist/store/scopes/composer.d.ts +1 -1
  338. package/dist/store/scopes/queue-item.d.ts +2 -1
  339. package/dist/store/scopes/queue-item.d.ts.map +1 -1
  340. package/dist/store/scopes/queue-item.js +6 -0
  341. package/dist/store/scopes/queue-item.js.map +1 -0
  342. package/dist/store/scopes/thread-list-item.d.ts +1 -0
  343. package/dist/store/scopes/thread-list-item.d.ts.map +1 -1
  344. package/dist/store/scopes/thread.d.ts +1 -1
  345. package/dist/store/scopes/threads.d.ts +1 -1
  346. package/dist/types/message.d.ts +2 -1
  347. package/dist/types/message.d.ts.map +1 -1
  348. package/dist/types/message.js.map +1 -1
  349. package/dist/utils/composite-context-provider.d.ts +1 -1
  350. package/dist/utils/composite-context-provider.js +3 -1
  351. package/dist/utils/composite-context-provider.js.map +1 -1
  352. package/dist/utils/json/is-json.js.map +1 -1
  353. package/dist/utils/text.js.map +1 -1
  354. package/package.json +15 -11
  355. package/src/adapters/attachment.ts +24 -4
  356. package/src/index.ts +8 -0
  357. package/src/model-context/tool.ts +1 -1
  358. package/src/model-context/types.ts +21 -3
  359. package/src/react/RuntimeAdapter.ts +6 -4
  360. package/src/react/adapters/LocalStorageThreadListAdapter.tsx +15 -2
  361. package/src/react/client/DataRenderers.ts +48 -42
  362. package/src/react/client/Interactables.ts +263 -267
  363. package/src/react/client/Tools.ts +123 -115
  364. package/src/react/index.ts +16 -3
  365. package/src/react/model-context/define-mcp-toolkit.ts +16 -0
  366. package/src/react/model-context/define-toolkit.test.ts +101 -6
  367. package/src/react/model-context/define-toolkit.ts +35 -18
  368. package/src/react/model-context/external-tool.ts +16 -0
  369. package/src/react/model-context/human-tool.ts +32 -0
  370. package/src/react/model-context/makeAssistantTool.ts +8 -0
  371. package/src/react/model-context/makeAssistantToolUI.ts +8 -0
  372. package/src/react/model-context/provider-tool.ts +30 -0
  373. package/src/react/model-context/stub-tool.ts +14 -0
  374. package/src/react/model-context/toolbox.test.ts +182 -0
  375. package/src/react/model-context/toolbox.ts +191 -23
  376. package/src/react/model-context/useAssistantTool.ts +28 -8
  377. package/src/react/model-context/useAssistantToolUI.ts +13 -4
  378. package/src/react/model-context/useAuiToolOverrides.ts +38 -0
  379. package/src/react/primitives/message/MessageGroupedParts.tsx +1 -1
  380. package/src/react/primitives/part/PartMessages.tsx +12 -10
  381. package/src/react/providers/TextMessagePartProvider.tsx +31 -32
  382. package/src/react/runtimes/RemoteThreadListThreadListRuntimeCore.tsx +43 -0
  383. package/src/react/runtimes/cloud/useCloudThreadListAdapter.tsx +9 -0
  384. package/src/react/runtimes/createMessageConverter.ts +2 -1
  385. package/src/react/runtimes/external-message-converter.ts +5 -3
  386. package/src/react/runtimes/useLocalRuntime.ts +2 -0
  387. package/src/runtime/api/composer-runtime.ts +26 -0
  388. package/src/runtime/api/thread-list-item-runtime.ts +15 -0
  389. package/src/runtime/base/base-composer-runtime-core.ts +11 -0
  390. package/src/runtime/base/default-thread-composer-runtime-core.ts +22 -0
  391. package/src/runtime/interfaces/composer-runtime-core.ts +7 -0
  392. package/src/runtime/interfaces/thread-list-runtime-core.ts +4 -0
  393. package/src/runtime/interfaces/thread-runtime-core.ts +5 -0
  394. package/src/runtime/queue/external-thread-queue-adapter.ts +14 -0
  395. package/src/runtime/queue/message-queue.ts +128 -0
  396. package/src/runtimes/external-store/external-store-adapter.ts +10 -0
  397. package/src/runtimes/external-store/external-store-thread-list-runtime-core.ts +13 -0
  398. package/src/runtimes/external-store/external-store-thread-runtime-core.ts +31 -2
  399. package/src/runtimes/local/local-runtime-options.ts +6 -0
  400. package/src/runtimes/local/local-thread-runtime-core.ts +70 -0
  401. package/src/runtimes/readonly/ReadonlyThreadRuntimeCore.ts +4 -0
  402. package/src/runtimes/remote-thread-list/adapter/in-memory.ts +4 -0
  403. package/src/runtimes/remote-thread-list/empty-thread-core.ts +4 -0
  404. package/src/runtimes/remote-thread-list/types.ts +4 -0
  405. package/src/store/clients/chain-of-thought-client.ts +24 -25
  406. package/src/store/clients/model-context-client.test.ts +87 -2
  407. package/src/store/clients/model-context-client.ts +22 -19
  408. package/src/store/clients/no-op-composer-client.ts +69 -66
  409. package/src/store/clients/runtime-adapter.ts +9 -6
  410. package/src/store/clients/suggestions.ts +41 -40
  411. package/src/store/clients/thread-message-client.ts +127 -132
  412. package/src/store/runtime-clients/attachment-runtime-client.ts +7 -3
  413. package/src/store/runtime-clients/composer-runtime-client.ts +142 -113
  414. package/src/store/runtime-clients/message-part-runtime-client.ts +16 -14
  415. package/src/store/runtime-clients/message-runtime-client.ts +124 -122
  416. package/src/store/runtime-clients/thread-list-item-runtime-client.ts +44 -44
  417. package/src/store/runtime-clients/thread-list-runtime-client.ts +83 -80
  418. package/src/store/runtime-clients/thread-runtime-client.ts +113 -119
  419. package/src/store/runtime-clients/{tap-subscribable.ts → useSubscribable.ts} +4 -4
  420. package/src/store/scopes/queue-item.ts +2 -0
  421. package/src/store/scopes/thread-list-item.ts +1 -0
  422. package/src/tests/RemoteThreadListThreadListRuntimeCore-custom-metadata.test.ts +69 -1
  423. package/src/tests/attachment-adapters.test.ts +86 -0
  424. package/src/tests/external-store-thread-runtime-core.test.ts +125 -0
  425. package/src/tests/message-queue.test.ts +168 -0
  426. package/src/tests/thread-list-runtime-getLoadThreadsPromise.test.ts +1 -0
  427. package/src/types/message.ts +2 -0
  428. package/src/utils/composite-context-provider.ts +3 -1
  429. package/dist/react/model-context/hitl.d.ts +0 -19
  430. package/dist/react/model-context/hitl.d.ts.map +0 -1
  431. package/dist/react/model-context/hitl.js +0 -22
  432. package/dist/react/model-context/hitl.js.map +0 -1
  433. package/dist/store/runtime-clients/tap-subscribable.d.ts +0 -7
  434. package/dist/store/runtime-clients/tap-subscribable.d.ts.map +0 -1
  435. package/dist/store/runtime-clients/tap-subscribable.js +0 -16
  436. package/dist/store/runtime-clients/tap-subscribable.js.map +0 -1
  437. package/src/react/model-context/h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AA,cAUR,0BAAA,YAAsC,iBAAA;EAAA,QACzC,SAAA;EAED,MAAA;cAEK,QAAA,EAAU,iBAAA;EAgBf,GAAA,CAAI,KAAA;IAAS,IAAA,EAAM,IAAA;EAAA,IAAM,OAAA,CAAA,iBAAA,IAAA,cAAA,CAAA,iBAAA;EASnB,IAAA,CAAK,UAAA,EAAY,iBAAA,GAAiB,OAAA,CAAA,kBAAA;EAUlC,MAAA,CAAO,UAAA,EAAY,UAAA,GAAU,OAAA;AAAA"}
@@ -27,12 +27,19 @@ var SimpleImageAttachmentAdapter = class {
27
27
  }
28
28
  async remove() {}
29
29
  };
30
- const getFileDataURL = (file) => new Promise((resolve, reject) => {
31
- const reader = new FileReader();
32
- reader.onload = () => resolve(reader.result);
33
- reader.onerror = (error) => reject(error);
34
- reader.readAsDataURL(file);
35
- });
30
+ const bytesToBase64 = (bytes) => globalThis.Buffer.from(bytes).toString("base64");
31
+ const getFileDataURL = async (file) => {
32
+ if (typeof FileReader === "undefined") {
33
+ const buffer = await file.arrayBuffer();
34
+ return `data:${file.type};base64,${bytesToBase64(new Uint8Array(buffer))}`;
35
+ }
36
+ return new Promise((resolve, reject) => {
37
+ const reader = new FileReader();
38
+ reader.onload = () => resolve(reader.result);
39
+ reader.onerror = (error) => reject(error);
40
+ reader.readAsDataURL(file);
41
+ });
42
+ };
36
43
  var SimpleTextAttachmentAdapter = class {
37
44
  accept = "text/plain,text/html,text/markdown,text/csv,text/xml,text/json,text/css";
38
45
  async add(state) {
@@ -60,12 +67,15 @@ var SimpleTextAttachmentAdapter = class {
60
67
  }
61
68
  async remove() {}
62
69
  };
63
- const getFileText = (file) => new Promise((resolve, reject) => {
64
- const reader = new FileReader();
65
- reader.onload = () => resolve(reader.result);
66
- reader.onerror = (error) => reject(error);
67
- reader.readAsText(file);
68
- });
70
+ const getFileText = async (file) => {
71
+ if (typeof FileReader === "undefined") return file.text();
72
+ return new Promise((resolve, reject) => {
73
+ const reader = new FileReader();
74
+ reader.onload = () => resolve(reader.result);
75
+ reader.onerror = (error) => reject(error);
76
+ reader.readAsText(file);
77
+ });
78
+ };
69
79
  function fileMatchesAccept(file, acceptString) {
70
80
  if (acceptString === "*") return true;
71
81
  const allowedTypes = acceptString.split(",").map((type) => type.trim().toLowerCase());
@@ -1 +1 @@
1
- {"version":3,"file":"attachment.js","names":[],"sources":["../../src/adapters/attachment.ts"],"sourcesContent":["import type {\n Attachment,\n PendingAttachment,\n CompleteAttachment,\n} from \"../types/attachment\";\nimport type { ThreadUserMessagePart } from \"../types/message\";\nimport { generateId } from \"../utils/id\";\n\nexport type AttachmentAdapter = {\n accept: string;\n add(state: {\n file: File;\n }): Promise<PendingAttachment> | AsyncGenerator<PendingAttachment, void>;\n remove(attachment: Attachment): Promise<void>;\n send(attachment: PendingAttachment): Promise<CompleteAttachment>;\n};\n\nexport class SimpleImageAttachmentAdapter implements AttachmentAdapter {\n public accept = \"image/*\";\n\n public async add(state: { file: File }): Promise<PendingAttachment> {\n return {\n id: state.file.name,\n type: \"image\",\n name: state.file.name,\n contentType: state.file.type,\n file: state.file,\n status: { type: \"requires-action\", reason: \"composer-send\" },\n };\n }\n\n public async send(\n attachment: PendingAttachment,\n ): Promise<CompleteAttachment> {\n return {\n ...attachment,\n status: { type: \"complete\" },\n content: [\n {\n type: \"image\",\n image: await getFileDataURL(attachment.file),\n },\n ],\n };\n }\n\n public async remove() {\n // noop\n }\n}\n\nconst getFileDataURL = (file: File) =>\n new Promise<string>((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result as string);\n reader.onerror = (error) => reject(error);\n reader.readAsDataURL(file);\n });\n\nexport class SimpleTextAttachmentAdapter implements AttachmentAdapter {\n public accept =\n \"text/plain,text/html,text/markdown,text/csv,text/xml,text/json,text/css\";\n\n public async add(state: { file: File }): Promise<PendingAttachment> {\n return {\n id: state.file.name,\n type: \"document\",\n name: state.file.name,\n contentType: state.file.type,\n file: state.file,\n status: { type: \"requires-action\", reason: \"composer-send\" },\n };\n }\n\n public async send(\n attachment: PendingAttachment,\n ): Promise<CompleteAttachment> {\n return {\n ...attachment,\n status: { type: \"complete\" },\n content: [\n {\n type: \"text\",\n text: `<attachment name=${attachment.name}>\\n${await getFileText(attachment.file)}\\n</attachment>`,\n },\n ],\n };\n }\n\n public async remove() {\n // noop\n }\n}\n\nconst getFileText = (file: File) =>\n new Promise<string>((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result as string);\n reader.onerror = (error) => reject(error);\n reader.readAsText(file);\n });\n\nexport function fileMatchesAccept(\n file: { name: string; type: string },\n acceptString: string,\n) {\n if (acceptString === \"*\") {\n return true;\n }\n\n const allowedTypes = acceptString\n .split(\",\")\n .map((type) => type.trim().toLowerCase());\n\n const fileExtension = `.${file.name.split(\".\").pop()!.toLowerCase()}`;\n const fileMimeType = file.type.toLowerCase();\n\n for (const type of allowedTypes) {\n if (type.startsWith(\".\") && type === fileExtension) {\n return true;\n }\n\n if (type.includes(\"/\") && type === fileMimeType) {\n return true;\n }\n\n if (type.endsWith(\"/*\")) {\n const generalType = type.split(\"/\")[0]!;\n if (fileMimeType.startsWith(`${generalType}/`)) {\n return true;\n }\n }\n }\n\n return false;\n}\n\nexport function attachmentsEqual(\n a: readonly CompleteAttachment[],\n b: readonly CompleteAttachment[],\n): boolean {\n if (a.length !== b.length) return false;\n return a.every((att, i) => att.id === b[i]!.id);\n}\n\nexport function partToCompleteAttachment(\n part: Exclude<ThreadUserMessagePart, { type: \"text\" }>,\n): CompleteAttachment {\n const id = generateId();\n\n if (part.type === \"image\") {\n return {\n id,\n type: \"image\",\n name: part.filename ?? \"image\",\n content: [part],\n status: { type: \"complete\" },\n };\n }\n\n if (part.type === \"file\") {\n return {\n id,\n type: \"document\",\n name: part.filename ?? \"document\",\n contentType: part.mimeType,\n content: [part],\n status: { type: \"complete\" },\n };\n }\n\n if (part.type === \"audio\") {\n return {\n id,\n type: \"audio\",\n name: `audio.${part.audio.format}`,\n contentType: `audio/${part.audio.format}`,\n content: [part],\n status: { type: \"complete\" },\n };\n }\n\n return {\n id,\n type: \"data\",\n name: part.name,\n content: [part],\n status: { type: \"complete\" },\n };\n}\n\nexport function liftNonTextParts(\n content: readonly ThreadUserMessagePart[],\n): CompleteAttachment[] {\n const result: CompleteAttachment[] = [];\n for (const part of content) {\n if (part.type !== \"text\") {\n result.push(partToCompleteAttachment(part));\n }\n }\n return result;\n}\n\nexport class CompositeAttachmentAdapter implements AttachmentAdapter {\n private _adapters: AttachmentAdapter[];\n\n public accept: string;\n\n constructor(adapters: AttachmentAdapter[]) {\n this._adapters = adapters;\n\n const wildcardIdx = adapters.findIndex((a) => a.accept === \"*\");\n if (wildcardIdx !== -1) {\n if (wildcardIdx !== adapters.length - 1)\n throw new Error(\n \"A wildcard adapter (handling all files) can only be specified as the last adapter.\",\n );\n\n this.accept = \"*\";\n } else {\n this.accept = adapters.map((a) => a.accept).join(\",\");\n }\n }\n\n public add(state: { file: File }) {\n for (const adapter of this._adapters) {\n if (fileMatchesAccept(state.file, adapter.accept)) {\n return adapter.add(state);\n }\n }\n throw new Error(\"No matching adapter found for file\");\n }\n\n public async send(attachment: PendingAttachment) {\n const adapters = this._adapters.slice();\n for (const adapter of adapters) {\n if (fileMatchesAccept(attachment.file, adapter.accept)) {\n return adapter.send(attachment);\n }\n }\n throw new Error(\"No matching adapter found for attachment\");\n }\n\n public async remove(attachment: Attachment) {\n const adapters = this._adapters.slice();\n for (const adapter of adapters) {\n if (\n fileMatchesAccept(\n {\n name: attachment.name,\n type: attachment.contentType ?? \"\",\n },\n adapter.accept,\n )\n ) {\n return adapter.remove(attachment);\n }\n }\n throw new Error(\"No matching adapter found for attachment\");\n }\n}\n"],"mappings":";;AAiBA,IAAa,+BAAb,MAAuE;CACrE,SAAgB;CAEhB,MAAa,IAAI,OAAmD;EAClE,OAAO;GACL,IAAI,MAAM,KAAK;GACf,MAAM;GACN,MAAM,MAAM,KAAK;GACjB,aAAa,MAAM,KAAK;GACxB,MAAM,MAAM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B,CAAC;CACtC,KAAK,MAAM,QAAQ,SACjB,IAAI,KAAK,SAAS,QAChB,OAAO,KAAK,yBAAyB,IAAI,CAAC;CAG9C,OAAO;AACT;AAEA,IAAa,6BAAb,MAAqE;CACnE;CAEA;CAEA,YAAY,UAA+B;EACzC,KAAK,YAAY;EAEjB,MAAM,cAAc,SAAS,WAAW,MAAM,EAAE,WAAW,GAAG;EAC9D,IAAI,gBAAgB,IAAI;GACtB,IAAI,gBAAgB,SAAS,SAAS,GACpC,MAAM,IAAI,MACR,oFACF;GAEF,KAAK,SAAS;EAChB,OACE,KAAK,SAAS,SAAS,KAAK,MAAM,EAAE,MAAM,EAAE,KAAK,GAAG;CAExD;CAEA,IAAW,OAAuB;EAChC,KAAK,MAAM,WAAW,KAAK,WACzB,IAAI,kBAAkB,MAAM,MAAM,QAAQ,MAAM,GAC9C,OAAO,QAAQ,IAAI,KAAK;EAG5B,MAAM,IAAI,MAAM,oCAAoC;CACtD;CAEA,MAAa,KAAK,YAA+B;EAC/C,MAAM,WAAW,KAAK,UAAU,MAAM;EACtC,KAAK,MAAM,WAAW,UACpB,IAAI,kBAAkB,WAAW,MAAM,QAAQ,MAAM,GACnD,OAAO,QAAQ,KAAK,UAAU;EAGlC,MAAM,IAAI,MAAM,0CAA0C;CAC5D;CAEA,MAAa,OAAO,YAAwB;EAC1C,MAAM,WAAW,KAAK,UAAU,MAAM;EACtC,KAAK,MAAM,WAAW,UACpB,IACE,kBACE;GACE,MAAM,WAAW;GACjB,MAAM,WAAW,eAAe;EAClC,GACA,QAAQ,MACV,GAEA,OAAO,QAAQ,OAAO,UAAU;EAGpC,MAAM,IAAI,MAAM,0CAA0C;CAC5D;AACF"}
1
+ {"version":3,"file":"attachment.js","names":[],"sources":["../../src/adapters/attachment.ts"],"sourcesContent":["import type {\n Attachment,\n PendingAttachment,\n CompleteAttachment,\n} from \"../types/attachment\";\nimport type { ThreadUserMessagePart } from \"../types/message\";\nimport { generateId } from \"../utils/id\";\n\nexport type AttachmentAdapter = {\n accept: string;\n add(state: {\n file: File;\n }): Promise<PendingAttachment> | AsyncGenerator<PendingAttachment, void>;\n remove(attachment: Attachment): Promise<void>;\n send(attachment: PendingAttachment): Promise<CompleteAttachment>;\n};\n\nexport class SimpleImageAttachmentAdapter implements AttachmentAdapter {\n public accept = \"image/*\";\n\n public async add(state: { file: File }): Promise<PendingAttachment> {\n return {\n id: state.file.name,\n type: \"image\",\n name: state.file.name,\n contentType: state.file.type,\n file: state.file,\n status: { type: \"requires-action\", reason: \"composer-send\" },\n };\n }\n\n public async send(\n attachment: PendingAttachment,\n ): Promise<CompleteAttachment> {\n return {\n ...attachment,\n status: { type: \"complete\" },\n content: [\n {\n type: \"image\",\n image: await getFileDataURL(attachment.file),\n },\n ],\n };\n }\n\n public async remove() {\n // noop\n }\n}\n\nconst bytesToBase64 = (bytes: Uint8Array): string =>\n (\n globalThis as {\n Buffer: {\n from(bytes: Uint8Array): { toString(encoding: string): string };\n };\n }\n ).Buffer.from(bytes).toString(\"base64\");\n\n// React Native's Blob polyfill has FileReader but not file.text()/arrayBuffer(); Node has\n// the reverse. Prefer FileReader when present, falling back to the Blob methods otherwise.\nconst getFileDataURL = async (file: File): Promise<string> => {\n if (typeof FileReader === \"undefined\") {\n const buffer = await file.arrayBuffer();\n return `data:${file.type};base64,${bytesToBase64(new Uint8Array(buffer))}`;\n }\n return new Promise<string>((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result as string);\n reader.onerror = (error) => reject(error);\n reader.readAsDataURL(file);\n });\n};\n\nexport class SimpleTextAttachmentAdapter implements AttachmentAdapter {\n public accept =\n \"text/plain,text/html,text/markdown,text/csv,text/xml,text/json,text/css\";\n\n public async add(state: { file: File }): Promise<PendingAttachment> {\n return {\n id: state.file.name,\n type: \"document\",\n name: state.file.name,\n contentType: state.file.type,\n file: state.file,\n status: { type: \"requires-action\", reason: \"composer-send\" },\n };\n }\n\n public async send(\n attachment: PendingAttachment,\n ): Promise<CompleteAttachment> {\n return {\n ...attachment,\n status: { type: \"complete\" },\n content: [\n {\n type: \"text\",\n text: `<attachment name=${attachment.name}>\\n${await getFileText(attachment.file)}\\n</attachment>`,\n },\n ],\n };\n }\n\n public async remove() {\n // noop\n }\n}\n\nconst getFileText = async (file: File): Promise<string> => {\n if (typeof FileReader === \"undefined\") {\n return file.text();\n }\n return new Promise<string>((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result as string);\n reader.onerror = (error) => reject(error);\n reader.readAsText(file);\n });\n};\n\nexport function fileMatchesAccept(\n file: { name: string; type: string },\n acceptString: string,\n) {\n if (acceptString === \"*\") {\n return true;\n }\n\n const allowedTypes = acceptString\n .split(\",\")\n .map((type) => type.trim().toLowerCase());\n\n const fileExtension = `.${file.name.split(\".\").pop()!.toLowerCase()}`;\n const fileMimeType = file.type.toLowerCase();\n\n for (const type of allowedTypes) {\n if (type.startsWith(\".\") && type === fileExtension) {\n return true;\n }\n\n if (type.includes(\"/\") && type === fileMimeType) {\n return true;\n }\n\n if (type.endsWith(\"/*\")) {\n const generalType = type.split(\"/\")[0]!;\n if (fileMimeType.startsWith(`${generalType}/`)) {\n return true;\n }\n }\n }\n\n return false;\n}\n\nexport function attachmentsEqual(\n a: readonly CompleteAttachment[],\n b: readonly CompleteAttachment[],\n): boolean {\n if (a.length !== b.length) return false;\n return a.every((att, i) => att.id === b[i]!.id);\n}\n\nexport function partToCompleteAttachment(\n part: Exclude<ThreadUserMessagePart, { type: \"text\" }>,\n): CompleteAttachment {\n const id = generateId();\n\n if (part.type === \"image\") {\n return {\n id,\n type: \"image\",\n name: part.filename ?? \"image\",\n content: [part],\n status: { type: \"complete\" },\n };\n }\n\n if (part.type === \"file\") {\n return {\n id,\n type: \"document\",\n name: part.filename ?? \"document\",\n contentType: part.mimeType,\n content: [part],\n status: { type: \"complete\" },\n };\n }\n\n if (part.type === \"audio\") {\n return {\n id,\n type: \"audio\",\n name: `audio.${part.audio.format}`,\n contentType: `audio/${part.audio.format}`,\n content: [part],\n status: { type: \"complete\" },\n };\n }\n\n return {\n id,\n type: \"data\",\n name: part.name,\n content: [part],\n status: { type: \"complete\" },\n };\n}\n\nexport function liftNonTextParts(\n content: readonly ThreadUserMessagePart[],\n): CompleteAttachment[] {\n const result: CompleteAttachment[] = [];\n for (const part of content) {\n if (part.type !== \"text\") {\n result.push(partToCompleteAttachment(part));\n }\n }\n return result;\n}\n\nexport class CompositeAttachmentAdapter implements AttachmentAdapter {\n private _adapters: AttachmentAdapter[];\n\n public accept: string;\n\n constructor(adapters: AttachmentAdapter[]) {\n this._adapters = adapters;\n\n const wildcardIdx = adapters.findIndex((a) => a.accept === \"*\");\n if (wildcardIdx !== -1) {\n if (wildcardIdx !== adapters.length - 1)\n throw new Error(\n \"A wildcard adapter (handling all files) can only be specified as the last adapter.\",\n );\n\n this.accept = \"*\";\n } else {\n this.accept = adapters.map((a) => a.accept).join(\",\");\n }\n }\n\n public add(state: { file: File }) {\n for (const adapter of this._adapters) {\n if (fileMatchesAccept(state.file, adapter.accept)) {\n return adapter.add(state);\n }\n }\n throw new Error(\"No matching adapter found for file\");\n }\n\n public async send(attachment: PendingAttachment) {\n const adapters = this._adapters.slice();\n for (const adapter of adapters) {\n if (fileMatchesAccept(attachment.file, adapter.accept)) {\n return adapter.send(attachment);\n }\n }\n throw new Error(\"No matching adapter found for attachment\");\n }\n\n public async remove(attachment: Attachment) {\n const adapters = this._adapters.slice();\n for (const adapter of adapters) {\n if (\n fileMatchesAccept(\n {\n name: attachment.name,\n type: attachment.contentType ?? \"\",\n },\n adapter.accept,\n )\n ) {\n return adapter.remove(attachment);\n }\n }\n throw new Error(\"No matching adapter found for attachment\");\n }\n}\n"],"mappings":";;AAiBA,IAAa,+BAAb,MAAuE;CACrE,SAAgB;CAEhB,MAAa,IAAI,OAAmD;EAClE,OAAO;GACL,IAAI,MAAM,KAAK;GACf,MAAM;GACN,MAAM,MAAM,KAAK;GACjB,aAAa,MAAM,KAAK;GACxB,MAAM,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C,KAAK,MAAM,WAAW,UACpB,IACE,kBACE;GACE,MAAM,WAAW;GACjB,MAAM,WAAW,eAAe;EAClC,GACA,QAAQ,MACV,GAEA,OAAO,QAAQ,OAAO,UAAU;EAGpC,MAAM,IAAI,MAAM,0CAA0C;CAC5D;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"directive-formatter.js","names":[],"sources":["../../src/adapters/directive-formatter.ts"],"sourcesContent":["import type {\n Unstable_DirectiveFormatter,\n Unstable_DirectiveSegment,\n} from \"../types/directive\";\nimport type { Unstable_TriggerItem } from \"../types/trigger\";\n\nconst DIRECTIVE_RE =\n /:([\\w-]{1,64})\\[([^\\]\\n]{1,1024})\\](?:\\{name=([^}\\n]{1,1024})\\})?/gu;\n\n/**\n * Default directive formatter using the `:type[label]{name=id}` syntax.\n *\n * When `id` equals `label`, the `{name=…}` attribute is omitted for brevity.\n */\nexport const unstable_defaultDirectiveFormatter: Unstable_DirectiveFormatter = {\n serialize(item: Unstable_TriggerItem): string {\n const attrs = item.id !== item.label ? `{name=${item.id}}` : \"\";\n return `:${item.type}[${item.label}]${attrs}`;\n },\n\n parse(text: string): Unstable_DirectiveSegment[] {\n const segments: Unstable_DirectiveSegment[] = [];\n let lastIndex = 0;\n\n for (const match of text.matchAll(DIRECTIVE_RE)) {\n if (match.index > lastIndex) {\n segments.push({\n kind: \"text\",\n text: text.slice(lastIndex, match.index),\n });\n }\n const label = match[2]!;\n segments.push({\n kind: \"mention\",\n type: match[1]!,\n label,\n id: match[3] ?? label,\n });\n lastIndex = match.index + match[0].length;\n }\n\n if (lastIndex < text.length) {\n segments.push({ kind: \"text\", text: text.slice(lastIndex) });\n }\n\n return segments;\n },\n};\n"],"mappings":";AAMA,MAAM,eACJ;;;;;;AAOF,MAAa,qCAAkE;CAC7E,UAAU,MAAoC;EAC5C,MAAM,QAAQ,KAAK,OAAO,KAAK,QAAQ,SAAS,KAAK,GAAG,KAAK;EAC7D,OAAO,IAAI,KAAK,KAAK,GAAG,KAAK,MAAM,GAAG;CACxC;CAEA,MAAM,MAA2C;EAC/C,MAAM,WAAwC,CAAC;EAC/C,IAAI,YAAY;EAEhB,KAAK,MAAM,SAAS,KAAK,SAAS,YAAY,GAAG;GAC/C,IAAI,MAAM,QAAQ,WAChB,SAAS,KAAK;IACZ,MAAM;IACN,MAAM,KAAK,MAAM,WAAW,MAAM,KAAK;GACzC,CAAC;GAEH,MAAM,QAAQ,MAAM;GACpB,SAAS,KAAK;IACZ,MAAM;IACN,MAAM,MAAM;IACZ;IACA,IAAI,MAAM,MAAM;GAClB,CAAC;GACD,YAAY,MAAM,QAAQ,MAAM,GAAG;EACrC;EAEA,IAAI,YAAY,KAAK,QACnB,SAAS,KAAK;GAAE,MAAM;GAAQ,MAAM,KAAK,MAAM,SAAS;EAAE,CAAC;EAG7D,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"directive-formatter.js","names":[],"sources":["../../src/adapters/directive-formatter.ts"],"sourcesContent":["import type {\n Unstable_DirectiveFormatter,\n Unstable_DirectiveSegment,\n} from \"../types/directive\";\nimport type { Unstable_TriggerItem } from \"../types/trigger\";\n\nconst DIRECTIVE_RE =\n /:([\\w-]{1,64})\\[([^\\]\\n]{1,1024})\\](?:\\{name=([^}\\n]{1,1024})\\})?/gu;\n\n/**\n * Default directive formatter using the `:type[label]{name=id}` syntax.\n *\n * When `id` equals `label`, the `{name=…}` attribute is omitted for brevity.\n */\nexport const unstable_defaultDirectiveFormatter: Unstable_DirectiveFormatter = {\n serialize(item: Unstable_TriggerItem): string {\n const attrs = item.id !== item.label ? `{name=${item.id}}` : \"\";\n return `:${item.type}[${item.label}]${attrs}`;\n },\n\n parse(text: string): Unstable_DirectiveSegment[] {\n const segments: Unstable_DirectiveSegment[] = [];\n let lastIndex = 0;\n\n for (const match of text.matchAll(DIRECTIVE_RE)) {\n if (match.index > lastIndex) {\n segments.push({\n kind: \"text\",\n text: text.slice(lastIndex, match.index),\n });\n }\n const label = match[2]!;\n segments.push({\n kind: \"mention\",\n type: match[1]!,\n label,\n id: match[3] ?? label,\n });\n lastIndex = match.index + match[0].length;\n }\n\n if (lastIndex < text.length) {\n segments.push({ kind: \"text\", text: text.slice(lastIndex) });\n }\n\n return segments;\n },\n};\n"],"mappings":";AAMA,MAAM,eACJ;;;;;;AAOF,MAAa,qCAAkE;CAC7E,UAAU,MAAoC;EAC5C,MAAM,QAAQ,KAAK,OAAO,KAAK,QAAQ,SAAS,KAAK,GAAG,KAAK;EAC7D,OAAO,IAAI,KAAK,KAAK,GAAG,KAAK,MAAM,GAAG;CACxC;CAEA,MAAM,MAA2C;EAC/C,MAAM,WAAwC,CAAC;EAC/C,IAAI,YAAY;EAEhB,KAAK,MAAM,SAAS,KAAK,SAAS,YAAY,GAAG;GAC/C,IAAI,MAAM,QAAQ,WAChB,SAAS,KAAK;IACZ,MAAM;IACN,MAAM,KAAK,MAAM,WAAW,MAAM,KAAK;GACzC,CAAC;GAEH,MAAM,QAAQ,MAAM;GACpB,SAAS,KAAK;IACZ,MAAM;IACN,MAAM,MAAM;IACZ;IACA,IAAI,MAAM,MAAM;GAClB,CAAC;GACD,YAAY,MAAM,QAAQ,MAAM,EAAE,CAAC;EACrC;EAEA,IAAI,YAAY,KAAK,QACnB,SAAS,KAAK;GAAE,MAAM;GAAQ,MAAM,KAAK,MAAM,SAAS;EAAE,CAAC;EAG7D,OAAO;CACT;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"speech.js","names":[],"sources":["../../src/adapters/speech.ts"],"sourcesContent":["import type { Unsubscribe } from \"../types/unsubscribe\";\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 subscribers.forEach((handler) => handler());\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) callback();\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 for (const cb of speechStartCallbacks) cb();\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 for (const cb of speechCallbacks) cb({ transcript, isFinal: true });\n } else {\n for (const cb of speechCallbacks) cb({ transcript, isFinal: false });\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 for (const cb of speechEndCallbacks)\n cb({ transcript: finalTranscript });\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":";AAsDA,IAAa,4BAAb,MAAyE;CACvE,MAAM,MAAgD;EACpD,MAAM,YAAY,IAAI,yBAAyB,IAAI;EAEnD,MAAM,8BAAc,IAAI,IAAgB;EACxC,MAAM,aACJ,QACA,UACG;GACH,IAAI,IAAI,OAAO,SAAS,SAAS;GAEjC,IAAI,SAAS;IAAE,MAAM;IAAS;IAAQ;GAAM;GAC5C,YAAY,SAAS,YAAY,QAAQ,CAAC;EAC5C;EAEA,UAAU,iBAAiB,aAAa,UAAU,UAAU,CAAC;EAC7D,UAAU,iBAAiB,UAAU,MAAM,UAAU,SAAS,EAAE,KAAK,CAAC;EAEtE,OAAO,gBAAgB,MAAM,SAAS;EAEtC,MAAM,MAAwC;GAC5C,QAAQ,EAAE,MAAM,UAAU;GAC1B,cAAc;IACZ,OAAO,gBAAgB,OAAO;IAC9B,UAAU,WAAW;GACvB;GACA,YAAY,aAAa;IACvB,IAAI,IAAI,OAAO,SAAS,SAAS;KAC/B,IAAI,YAAY;KAChB,qBAAqB;MACnB,IAAI,CAAC,WAAW,SAAS;KAC3B,CAAC;KACD,aAAa;MACX,YAAY;KACd;IACF,OAAO;KACL,YAAY,IAAI,QAAQ;KACxB,aAAa;MACX,YAAY,OAAO,QAAQ;KAC7B;IACF;GACF;EACF;EACA,OAAO;CACT;AACF;AAkDA,MAAM,gCAEW;CACf,IAAI,OAAO,WAAW,aAAa,OAAO,KAAA;CAC1C,OAAO,OAAO,qBAAqB,OAAO;AAC5C;AAEA,IAAa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],"sources":["../../src/adapters/speech.ts"],"sourcesContent":["import type { Unsubscribe } from \"../types/unsubscribe\";\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 subscribers.forEach((handler) => handler());\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) callback();\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 for (const cb of speechStartCallbacks) cb();\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 for (const cb of speechCallbacks) cb({ transcript, isFinal: true });\n } else {\n for (const cb of speechCallbacks) cb({ transcript, isFinal: false });\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 for (const cb of speechEndCallbacks)\n cb({ transcript: finalTranscript });\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":";AAsDA,IAAa,4BAAb,MAAyE;CACvE,MAAM,MAAgD;EACpD,MAAM,YAAY,IAAI,yBAAyB,IAAI;EAEnD,MAAM,8BAAc,IAAI,IAAgB;EACxC,MAAM,aACJ,QACA,UACG;GACH,IAAI,IAAI,OAAO,SAAS,SAAS;GAEjC,IAAI,SAAS;IAAE,MAAM;IAAS;IAAQ;GAAM;GAC5C,YAAY,SAAS,YAAY,QAAQ,CAAC;EAC5C;EAEA,UAAU,iBAAiB,aAAa,UAAU,UAAU,CAAC;EAC7D,UAAU,iBAAiB,UAAU,MAAM,UAAU,SAAS,EAAE,KAAK,CAAC;EAEtE,OAAO,gBAAgB,MAAM,SAAS;EAEtC,MAAM,MAAwC;GAC5C,QAAQ,EAAE,MAAM,UAAU;GAC1B,cAAc;IACZ,OAAO,gBAAgB,OAAO;IAC9B,UAAU,WAAW;GACvB;GACA,YAAY,aAAa;IACvB,IAAI,IAAI,OAAO,SAAS,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U,WACvB,aAAa;IAAE,MAAM;IAAS,QAAQ;GAAY,CAAC;QAC9C;IACL,aAAa;KAAE,MAAM;KAAS,QAAQ;IAAQ,CAAC;IAC/C,QAAQ,MAAM,oBAAoB,WAAW,OAAO,WAAW,OAAO;GACxE;EACF,CAAC;EAED,IAAI;GACF,YAAY,MAAM;EACpB,SAAS,OAAO;GACd,aAAa;IAAE,MAAM;IAAS,QAAQ;GAAQ,CAAC;GAC/C,MAAM;EACR;EAEA,OAAO;CACT;AACF"}
package/dist/index.d.ts CHANGED
@@ -38,11 +38,13 @@ import { MessagePartRuntime, MessagePartState } from "./runtime/api/message-part
38
38
  import { MessageRuntime, MessageState } from "./runtime/api/message-runtime.js";
39
39
  import { bindExternalStoreMessage, getExternalStoreMessages } from "./runtime/utils/external-store-message.js";
40
40
  import { LocalRuntimeOptionsBase } from "./runtimes/local/local-runtime-options.js";
41
+ import { ExternalThreadQueueAdapter } from "./runtime/queue/external-thread-queue-adapter.js";
41
42
  import { ExternalStoreAdapter, ExternalStoreMessageConverter, ExternalStoreThreadData, ExternalStoreThreadListAdapter } from "./runtimes/external-store/external-store-adapter.js";
42
43
  import { RemoteThreadInitializeResponse, RemoteThreadListAdapter, RemoteThreadListOptions, RemoteThreadListPageOptions, RemoteThreadListResponse, RemoteThreadMetadata } from "./runtimes/remote-thread-list/types.js";
43
44
  import { CreateAppendMessage, CreateResumeRunConfig, CreateStartRunConfig, ThreadRuntime, ThreadState } from "./runtime/api/thread-runtime.js";
44
45
  import { AssistantRuntime } from "./runtime/api/assistant-runtime.js";
45
46
  import { ExternalStoreSharedOptions, pickExternalStoreSharedOptions } from "./runtimes/external-store/external-store-shared-options.js";
47
+ import { MessageQueueController, MessageQueueDriver, createMessageQueue } from "./runtime/queue/message-queue.js";
46
48
  import { InMemoryThreadListAdapter } from "./runtimes/remote-thread-list/adapter/in-memory.js";
47
49
  import { createRequestHeaders } from "./runtimes/assistant-transport/utils.js";
48
- export { type AddToolResultOptions, type AppendMessage, type AssistantContextConfig, 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 DataMessagePart, type DictationAdapter, type DictationState, type EditComposerRuntime, type EditComposerRuntimeCore, type EditComposerState, ExportedMessageRepository, type ExportedMessageRepositoryItem, type ExternalStoreAdapter, type ExternalStoreMessageConverter, type ExternalStoreSharedOptions, type ExternalStoreThreadData, type ExternalStoreThreadListAdapter, 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 MessagePartRuntime, type MessagePartRuntimePath, type MessagePartState, type MessagePartStatus, 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 PendingAttachment, type PendingAttachmentStatus, type QuoteInfo, type RealtimeVoiceAdapter, type ReasoningMessagePart, type RemoteThreadInitializeResponse, type RemoteThreadListAdapter, type RemoteThreadListOptions, type RemoteThreadListPageOptions, type RemoteThreadListResponse, type RemoteThreadMetadata, type RespondToToolApprovalOptions, type ResumeRunConfig, type ResumeToolCallOptions, type RunConfig, type RuntimeCapabilities, type SendOptions, type SerializedModelContext, type SerializedTool, SimpleImageAttachmentAdapter, SimpleTextAttachmentAdapter, type SourceMessagePart, type SourceProviderMetadata, type SpeechState, type SpeechSynthesisAdapter, type StartRunConfig, type SubmitFeedbackOptions, type SubmittedFeedback, type SuggestionAdapter, type TextMessagePart, type ThreadAssistantMessage, type ThreadAssistantMessagePart, type ThreadComposerRuntime, type ThreadComposerRuntimeCore, type ThreadComposerState, type ThreadHistoryAdapter, type ThreadListItemCoreState, type ThreadListItemEventCallback, type ThreadListItemEventPayload, type ThreadListItemEventType, 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 ToolCallMessagePart, type ToolCallMessagePartMcpMetadata, type ToolCallMessagePartStatus, type ToolExecutionStatus, type ToolModelContentPart, type Unstable_AudioMessagePart, type Unstable_DirectiveFormatter, type Unstable_DirectiveSegment, type Unstable_TriggerAdapter, type Unstable_TriggerCategory, type Unstable_TriggerItem, type Unsubscribe, type VoiceSessionControls, type VoiceSessionHelpers, type VoiceSessionState, WebSpeechDictationAdapter, WebSpeechSynthesisAdapter, bindExternalStoreMessage, createRequestHeaders, createVoiceSession, getExternalStoreMessages, isMcpAppUri, mergeModelContexts, pickExternalStoreSharedOptions, tool, unstable_defaultDirectiveFormatter };
50
+ export { type AddToolResultOptions, type AppendMessage, type AssistantContextConfig, 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 DataMessagePart, type DictationAdapter, type DictationState, type EditComposerRuntime, type EditComposerRuntimeCore, type EditComposerState, ExportedMessageRepository, type ExportedMessageRepositoryItem, type ExternalStoreAdapter, type ExternalStoreMessageConverter, type ExternalStoreSharedOptions, type ExternalStoreThreadData, type ExternalStoreThreadListAdapter, 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 MessagePartRuntime, type MessagePartRuntimePath, type MessagePartState, type MessagePartStatus, 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 PendingAttachment, type PendingAttachmentStatus, type QuoteInfo, type RealtimeVoiceAdapter, type ReasoningMessagePart, type RemoteThreadInitializeResponse, type RemoteThreadListAdapter, type RemoteThreadListOptions, type RemoteThreadListPageOptions, type RemoteThreadListResponse, type RemoteThreadMetadata, type RespondToToolApprovalOptions, type ResumeRunConfig, type ResumeToolCallOptions, type RunConfig, type RuntimeCapabilities, type SendOptions, type SerializedModelContext, type SerializedTool, SimpleImageAttachmentAdapter, SimpleTextAttachmentAdapter, type SourceMessagePart, type SourceProviderMetadata, type SpeechState, type SpeechSynthesisAdapter, type StartRunConfig, type SubmitFeedbackOptions, type SubmittedFeedback, type SuggestionAdapter, type TextMessagePart, type ThreadAssistantMessage, type ThreadAssistantMessagePart, type ThreadComposerRuntime, type ThreadComposerRuntimeCore, type ThreadComposerState, type ThreadHistoryAdapter, type ThreadListItemCoreState, type ThreadListItemEventCallback, type ThreadListItemEventPayload, type ThreadListItemEventType, 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 ToolCallMessagePart, type ToolCallMessagePartMcpMetadata, type ToolCallMessagePartStatus, type ToolExecutionStatus, type ToolModelContentPart, type Unstable_AudioMessagePart, type Unstable_DirectiveFormatter, type Unstable_DirectiveSegment, type Unstable_TriggerAdapter, type Unstable_TriggerCategory, type Unstable_TriggerItem, type Unsubscribe, type VoiceSessionControls, type VoiceSessionHelpers, type VoiceSessionState, WebSpeechDictationAdapter, WebSpeechSynthesisAdapter, bindExternalStoreMessage, createMessageQueue, createRequestHeaders, createVoiceSession, getExternalStoreMessages, isMcpAppUri, mergeModelContexts, pickExternalStoreSharedOptions, tool, unstable_defaultDirectiveFormatter };
package/dist/index.js CHANGED
@@ -13,11 +13,12 @@ import { unstable_defaultDirectiveFormatter } from "./adapters/directive-formatt
13
13
  import { bindExternalStoreMessage, getExternalStoreMessages } from "./runtime/utils/external-store-message.js";
14
14
  import { ExportedMessageRepository } from "./runtime/utils/message-repository.js";
15
15
  import { pickExternalStoreSharedOptions } from "./runtimes/external-store/external-store-shared-options.js";
16
+ import { createMessageQueue } from "./runtime/queue/message-queue.js";
16
17
  import { InMemoryThreadListAdapter } from "./runtimes/remote-thread-list/adapter/in-memory.js";
17
18
  import { createRequestHeaders } from "./runtimes/assistant-transport/utils.js";
18
19
  //#region src/index.ts
19
20
  if (process.env.NODE_ENV !== "production") checkDuplicateCore();
20
21
  //#endregion
21
- export { AssistantFrameHost, AssistantFrameProvider, CompositeAttachmentAdapter, ExportedMessageRepository, FRAME_MESSAGE_CHANNEL, InMemoryThreadListAdapter, MCP_APP_URI_SCHEME, ModelContextRegistry, SimpleImageAttachmentAdapter, SimpleTextAttachmentAdapter, WebSpeechDictationAdapter, WebSpeechSynthesisAdapter, bindExternalStoreMessage, createRequestHeaders, createVoiceSession, getExternalStoreMessages, isMcpAppUri, mergeModelContexts, pickExternalStoreSharedOptions, tool, unstable_defaultDirectiveFormatter };
22
+ export { AssistantFrameHost, AssistantFrameProvider, CompositeAttachmentAdapter, ExportedMessageRepository, FRAME_MESSAGE_CHANNEL, InMemoryThreadListAdapter, MCP_APP_URI_SCHEME, ModelContextRegistry, SimpleImageAttachmentAdapter, SimpleTextAttachmentAdapter, WebSpeechDictationAdapter, WebSpeechSynthesisAdapter, bindExternalStoreMessage, createMessageQueue, createRequestHeaders, createVoiceSession, getExternalStoreMessages, isMcpAppUri, mergeModelContexts, pickExternalStoreSharedOptions, tool, unstable_defaultDirectiveFormatter };
22
23
 
23
24
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"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 SourceProviderMetadata,\n SourceMessagePart,\n ImageMessagePart,\n FileMessagePart,\n DataMessagePart,\n GenerativeUIMessagePart,\n GenerativeUINode,\n GenerativeUISpec,\n Unstable_AudioMessagePart,\n ToolCallMessagePart,\n ToolCallMessagePartMcpMetadata,\n McpAppMetadata,\n ToolModelContentPart,\n ThreadUserMessagePart,\n ThreadAssistantMessagePart,\n // Message status\n MessagePartStatus,\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 { MCP_APP_URI_SCHEME, isMcpAppUri } 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 { 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 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 { SuggestionAdapter } 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 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 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\";\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} 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// Remote Thread List (user-facing)\nexport type {\n RemoteThreadListAdapter,\n RemoteThreadListOptions,\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,IAAI,QAAQ,IAAI,aAAa,cAC3B,mBAAmB"}
1
+ {"version":3,"file":"index.js","names":[],"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 SourceProviderMetadata,\n SourceMessagePart,\n ImageMessagePart,\n FileMessagePart,\n DataMessagePart,\n GenerativeUIMessagePart,\n GenerativeUINode,\n GenerativeUISpec,\n Unstable_AudioMessagePart,\n ToolCallMessagePart,\n ToolCallMessagePartMcpMetadata,\n McpAppMetadata,\n ToolModelContentPart,\n ThreadUserMessagePart,\n ThreadAssistantMessagePart,\n // Message status\n MessagePartStatus,\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 { MCP_APP_URI_SCHEME, isMcpAppUri } 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 { 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 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 { SuggestionAdapter } 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 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 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\";\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} 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 { ExternalThreadQueueAdapter } from \"./runtime/queue/external-thread-queue-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 RemoteThreadListOptions,\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,IAAI,QAAQ,IAAI,aAAa,cAC3B,mBAAmB"}
package/dist/internal.js CHANGED
@@ -3,8 +3,8 @@ import { symbolInnerMessage } from "./runtime/utils/external-store-message.js";
3
3
  import { getAutoStatus, isAutoStatus } from "./runtime/utils/auto-status.js";
4
4
  import { fromThreadMessageLike } from "./runtime/utils/thread-message-like.js";
5
5
  import { ExportedMessageRepository, MessageRepository } from "./runtime/utils/message-repository.js";
6
- import { BaseSubject, BaseSubscribable, EventSubscriptionSubject, LazyMemoizeSubject, NestedSubscriptionSubject, SKIP_UPDATE, ShallowMemoizeSubject } from "./subscribable/subscribable.js";
7
6
  import { getThreadMessageText } from "./utils/text.js";
7
+ import { BaseSubject, BaseSubscribable, EventSubscriptionSubject, LazyMemoizeSubject, NestedSubscriptionSubject, SKIP_UPDATE, ShallowMemoizeSubject } from "./subscribable/subscribable.js";
8
8
  import { CompositeContextProvider } from "./utils/composite-context-provider.js";
9
9
  import { BaseAssistantRuntimeCore } from "./runtime/base/base-assistant-runtime-core.js";
10
10
  import { BaseComposerRuntimeCore } from "./runtime/base/base-composer-runtime-core.js";
@@ -1 +1 @@
1
- {"version":3,"file":"host.js","names":[],"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 {\n type FrameMessage,\n FRAME_MESSAGE_CHANNEL,\n type SerializedModelContext,\n type SerializedTool,\n} from \"./types\";\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\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 _requestCounter = 0;\n private _iframeWindow: Window;\n private _targetOrigin: string;\n\n constructor(iframeWindow: Window, targetOrigin: string = \"*\") {\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 (message.error) {\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) => this.callTool(name, args),\n } as Tool<any, any>,\n ]),\n ),\n };\n this.notifySubscribers();\n }\n\n private callTool(toolName: string, args: any): Promise<any> {\n return this.sendRequest(\n {\n type: \"tool-call\",\n id: `tool-${this._requestCounter++}`,\n toolName,\n args,\n },\n 30000,\n `Tool call \"${toolName}\" timed out`,\n );\n }\n\n private sendRequest<T extends FrameMessage & { id: string }>(\n message: T,\n timeout = 30000,\n timeoutMessage = \"Request timed out\",\n ): Promise<any> {\n return new Promise((resolve, reject) => {\n this._pendingRequests.set(message.id, { resolve, reject });\n\n this._iframeWindow.postMessage(\n { channel: FRAME_MESSAGE_CHANNEL, message },\n this._targetOrigin,\n );\n\n const timeoutId = setTimeout(() => {\n const pending = this._pendingRequests.get(message.id);\n if (pending) {\n pending.reject(new Error(timeoutMessage));\n this._pendingRequests.delete(message.id);\n }\n }, timeout);\n\n const originalResolve = this._pendingRequests.get(message.id)!.resolve;\n const originalReject = this._pendingRequests.get(message.id)!.reject;\n\n this._pendingRequests.set(message.id, {\n resolve: (value: any) => {\n clearTimeout(timeoutId);\n originalResolve(value);\n },\n reject: (error: any) => {\n clearTimeout(timeoutId);\n originalReject(error);\n },\n });\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 this._subscribers.forEach((callback) => callback());\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 window.removeEventListener(\"message\", this.handleMessage);\n this._subscribers.clear();\n this._pendingRequests.clear();\n }\n}\n"],"mappings":";;;;;AAaA,MAAM,mBAAmB,oBACtB;CACC,YAAY,eAAe;CAC3B,GAAI,eAAe,eAAe,EAChC,aAAa,eAAe,YAC9B;CACA,GAAI,eAAe,aAAa,KAAA,KAAa,EAC3C,UAAU,eAAe,SAC3B;CACA,GAAI,eAAe,QAAQ,EAAE,MAAM,eAAe,KAAK;AACzD;;;;AAKF,MAAM,2BACJ,gBACkB;CAClB,GAAI,WAAW,WAAW,KAAA,KAAa,EAAE,QAAQ,WAAW,OAAO;CACnE,GAAI,WAAW,SAAS,EACtB,OAAO,OAAO,YACZ,OAAO,QAAQ,WAAW,KAAK,EAAE,KAAK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version":3,"file":"host.js","names":[],"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 {\n type FrameMessage,\n FRAME_MESSAGE_CHANNEL,\n type SerializedModelContext,\n type SerializedTool,\n} from \"./types\";\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\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 _requestCounter = 0;\n private _iframeWindow: Window;\n private _targetOrigin: string;\n\n constructor(iframeWindow: Window, targetOrigin: string = \"*\") {\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 (message.error) {\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) => this.callTool(name, args),\n } as Tool<any, any>,\n ]),\n ),\n };\n this.notifySubscribers();\n }\n\n private callTool(toolName: string, args: any): Promise<any> {\n return this.sendRequest(\n {\n type: \"tool-call\",\n id: `tool-${this._requestCounter++}`,\n toolName,\n args,\n },\n 30000,\n `Tool call \"${toolName}\" timed out`,\n );\n }\n\n private sendRequest<T extends FrameMessage & { id: string }>(\n message: T,\n timeout = 30000,\n timeoutMessage = \"Request timed out\",\n ): Promise<any> {\n return new Promise((resolve, reject) => {\n this._pendingRequests.set(message.id, { resolve, reject });\n\n this._iframeWindow.postMessage(\n { channel: FRAME_MESSAGE_CHANNEL, message },\n this._targetOrigin,\n );\n\n const timeoutId = setTimeout(() => {\n const pending = this._pendingRequests.get(message.id);\n if (pending) {\n pending.reject(new Error(timeoutMessage));\n this._pendingRequests.delete(message.id);\n }\n }, timeout);\n\n const originalResolve = this._pendingRequests.get(message.id)!.resolve;\n const originalReject = this._pendingRequests.get(message.id)!.reject;\n\n this._pendingRequests.set(message.id, {\n resolve: (value: any) => {\n clearTimeout(timeoutId);\n originalResolve(value);\n },\n reject: (error: any) => {\n clearTimeout(timeoutId);\n originalReject(error);\n },\n });\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 this._subscribers.forEach((callback) => callback());\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 window.removeEventListener(\"message\", this.handleMessage);\n this._subscribers.clear();\n this._pendingRequests.clear();\n }\n}\n"],"mappings":";;;;;AAaA,MAAM,mBAAmB,oBACtB;CACC,YAAY,eAAe;CAC3B,GAAI,eAAe,eAAe,EAChC,aAAa,eAAe,YAC9B;CACA,GAAI,eAAe,aAAa,KAAA,KAAa,EAC3C,UAAU,eAAe,SAC3B;CACA,GAAI,eAAe,QAAQ,EAAE,MAAM,eAAe,KAAK;AACzD;;;;AAKF,MAAM,2BACJ,gBACkB;CAClB,GAAI,WAAW,WAAW,KAAA,KAAa,EAAE,QAAQ,WAAW,OAAO;CACnE,GAAI,WAAW,SAAS,EACtB,OAAO,OAAO,YACZ,OAAO,QAAQ,WAAW,KAAK,CAAC,CAAC,KAAK,CAAC,MAAM,UAAU,CACrD,MACA,gBAAgB,IAAI,CACtB,CAAC,CACH,EACF;AACF;AAEA,IAAa,qBAAb,MAAgE;CAC9D,WAAiC,CAAC;CAClC,+BAAuB,IAAI,IAAgB;CAC3C,mCAA2B,IAAI,IAM7B;CACF,kBAA0B;CAC1B;CACA;CAEA,YAAY,cAAsB,eAAuB,KAAK;EAC5D,KAAK,gBAAgB;EACrB,KAAK,gBAAgB;EAErB,KAAK,gBAAgB,KAAK,cAAc,KAAK,IAAI;EACjD,OAAO,iBAAiB,WAAW,KAAK,aAAa;EAErD,KAAK,eAAe;CACtB;CAEA,cAAsB,OAAqB;EACzC,IAAI,KAAK,kBAAkB,OAAO,MAAM,WAAW,KAAK,eACtD;EACF,IAAI,MAAM,WAAW,KAAK,eAAe;EACzC,IAAI,MAAM,MAAM,YAAA,sBAAmC;EAEnD,MAAM,UAAU,MAAM,KAAK;EAE3B,QAAQ,QAAQ,MAAhB;GACE,KAAK;IACH,KAAK,cAAc,QAAQ,OAAO;IAClC;GAGF,KAAK,e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iBAAiB,IAAI,QAAQ,IAAI;IACpC,UAAU,UAAe;KACvB,aAAa,SAAS;KACtB,gBAAgB,KAAK;IACvB;IACA,SAAS,UAAe;KACtB,aAAa,SAAS;KACtB,eAAe,KAAK;IACtB;GACF,CAAC;EACH,CAAC;CACH;CAEA,iBAAyB;EACvB,KAAK,cAAc,YACjB;GACE,SAAS;GACT,SAAS,EACP,MAAM,wBACR;EACF,GACA,KAAK,aACP;CACF;CAEA,oBAA4B;EAC1B,KAAK,aAAa,SAAS,aAAa,SAAS,CAAC;CACpD;CAEA,kBAAgC;EAC9B,OAAO,KAAK;CACd;CAEA,UAAU,UAAmC;EAC3C,KAAK,aAAa,IAAI,QAAQ;EAC9B,aAAa,KAAK,aAAa,OAAO,QAAQ;CAChD;CAEA,UAAU;EACR,OAAO,oBAAoB,WAAW,KAAK,aAAa;EACxD,KAAK,aAAa,MAAM;EACxB,KAAK,iBAAiB,MAAM;CAC9B;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"provider.js","names":[],"sources":["../../../src/model-context/frame/provider.ts"],"sourcesContent":["import type { ModelContextProvider, ModelContext } from \"../types\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport { type Tool, toJSONSchema } from \"assistant-stream\";\nimport {\n type FrameMessage,\n FRAME_MESSAGE_CHANNEL,\n type SerializedModelContext,\n type SerializedTool,\n} from \"./types\";\n\nconst serializeTool = (tool: Tool<any, any>): SerializedTool => ({\n ...(tool.description && { description: tool.description }),\n parameters: tool.parameters ? toJSONSchema(tool.parameters) : undefined,\n ...(tool.disabled !== undefined && { disabled: tool.disabled }),\n ...(tool.type && { type: tool.type }),\n});\n\nconst serializeModelContext = (\n context: ModelContext,\n): SerializedModelContext => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools && {\n tools: Object.fromEntries(\n Object.entries(context.tools).map(([name, tool]) => [\n name,\n serializeTool(tool),\n ]),\n ),\n }),\n});\n\nexport class AssistantFrameProvider {\n private static _instance: AssistantFrameProvider | null = null;\n\n private _providers = new Set<ModelContextProvider>();\n private _providerUnsubscribes = new Map<\n ModelContextProvider,\n Unsubscribe | undefined\n >();\n private _targetOrigin: string;\n\n private constructor(targetOrigin: string = \"*\") {\n this._targetOrigin = targetOrigin;\n this.handleMessage = this.handleMessage.bind(this);\n window.addEventListener(\"message\", this.handleMessage);\n\n setTimeout(() => this.broadcastUpdate(), 0);\n }\n\n private static getInstance(targetOrigin?: string): AssistantFrameProvider {\n if (!AssistantFrameProvider._instance) {\n AssistantFrameProvider._instance = new AssistantFrameProvider(\n targetOrigin,\n );\n }\n return AssistantFrameProvider._instance;\n }\n\n private handleMessage(event: MessageEvent) {\n if (this._targetOrigin !== \"*\" && event.origin !== this._targetOrigin)\n 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-request\":\n this.sendMessage(event, {\n type: \"model-context-update\",\n context: serializeModelContext(this.getModelContext()),\n });\n break;\n\n case \"tool-call\":\n this.handleToolCall(message, event);\n break;\n }\n }\n\n private async handleToolCall(\n message: Extract<FrameMessage, { type: \"tool-call\" }>,\n event: MessageEvent,\n ) {\n const tool = this.getModelContext().tools?.[message.toolName];\n\n let result: any;\n let error: string | undefined;\n\n if (!tool) {\n error = `Tool \"${message.toolName}\" not found`;\n } else {\n try {\n result = tool.execute\n ? await tool.execute(message.args, {\n toolCallId: message.id,\n abortSignal: new AbortController().signal,\n human: async () => {\n throw new Error(\n \"Tool human input is not supported in frame context\",\n );\n },\n })\n : undefined;\n } catch (e) {\n error = e instanceof Error ? e.message : String(e);\n }\n }\n\n this.sendMessage(event, {\n type: \"tool-result\",\n id: message.id,\n ...(error ? { error } : { result }),\n });\n }\n\n private sendMessage(event: MessageEvent, message: FrameMessage) {\n event.source?.postMessage(\n { channel: FRAME_MESSAGE_CHANNEL, message },\n { targetOrigin: event.origin },\n );\n }\n\n private getModelContext(): ModelContext {\n const contexts = Array.from(this._providers).map((p) =>\n p.getModelContext(),\n );\n\n return contexts.reduce(\n (merged, context) => ({\n system: context.system\n ? merged.system\n ? `${merged.system}\\n\\n${context.system}`\n : context.system\n : merged.system,\n tools: { ...(merged.tools || {}), ...(context.tools || {}) },\n }),\n {} as ModelContext,\n );\n }\n\n private broadcastUpdate() {\n if (window.parent && window.parent !== window) {\n const updateMessage: FrameMessage = {\n type: \"model-context-update\",\n context: serializeModelContext(this.getModelContext()),\n };\n\n window.parent.postMessage(\n { channel: FRAME_MESSAGE_CHANNEL, message: updateMessage },\n this._targetOrigin,\n );\n }\n }\n\n static addModelContextProvider(\n provider: ModelContextProvider,\n targetOrigin?: string,\n ): Unsubscribe {\n const instance = AssistantFrameProvider.getInstance(targetOrigin);\n instance._providers.add(provider);\n\n const unsubscribe = provider.subscribe?.(() => instance.broadcastUpdate());\n if (unsubscribe) {\n instance._providerUnsubscribes.set(provider, unsubscribe);\n }\n\n instance.broadcastUpdate();\n\n return () => {\n instance._providers.delete(provider);\n instance._providerUnsubscribes.get(provider)?.();\n instance._providerUnsubscribes.delete(provider);\n instance.broadcastUpdate();\n };\n }\n\n static dispose() {\n if (AssistantFrameProvider._instance) {\n const instance = AssistantFrameProvider._instance;\n window.removeEventListener(\"message\", instance.handleMessage);\n\n instance._providerUnsubscribes.forEach((unsubscribe) => unsubscribe?.());\n instance._providerUnsubscribes.clear();\n instance._providers.clear();\n\n AssistantFrameProvider._instance = null;\n }\n }\n}\n"],"mappings":";;;AAUA,MAAM,iBAAiB,UAA0C;CAC/D,GAAI,KAAK,eAAe,EAAE,aAAa,KAAK,YAAY;CACxD,YAAY,KAAK,aAAa,aAAa,KAAK,UAAU,IAAI,KAAA;CAC9D,GAAI,KAAK,aAAa,KAAA,KAAa,EAAE,UAAU,KAAK,SAAS;CAC7D,GAAI,KAAK,QAAQ,EAAE,MAAM,KAAK,KAAK;AACrC;AAEA,MAAM,yBACJ,aAC4B;CAC5B,GAAI,QAAQ,WAAW,KAAA,KAAa,EAAE,QAAQ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AS,gBAAgB;EAC3B;CACF;CAEA,OAAO,UAAU;EACf,IAAI,uBAAuB,WAAW;GACpC,MAAM,WAAW,uBAAuB;GACxC,OAAO,oBAAoB,WAAW,SAAS,aAAa;GAE5D,SAAS,sBAAsB,SAAS,gBAAgB,cAAc,CAAC;GACvE,SAAS,sBAAsB,MAAM;GACrC,SAAS,WAAW,MAAM;GAE1B,uBAAuB,YAAY;EACrC;CACF;AACF"}
1
+ {"version":3,"file":"provider.js","names":[],"sources":["../../../src/model-context/frame/provider.ts"],"sourcesContent":["import type { ModelContextProvider, ModelContext } from \"../types\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport { type Tool, toJSONSchema } from \"assistant-stream\";\nimport {\n type FrameMessage,\n FRAME_MESSAGE_CHANNEL,\n type SerializedModelContext,\n type SerializedTool,\n} from \"./types\";\n\nconst serializeTool = (tool: Tool<any, any>): SerializedTool => ({\n ...(tool.description && { description: tool.description }),\n parameters: tool.parameters ? toJSONSchema(tool.parameters) : undefined,\n ...(tool.disabled !== undefined && { disabled: tool.disabled }),\n ...(tool.type && { type: tool.type }),\n});\n\nconst serializeModelContext = (\n context: ModelContext,\n): SerializedModelContext => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools && {\n tools: Object.fromEntries(\n Object.entries(context.tools).map(([name, tool]) => [\n name,\n serializeTool(tool),\n ]),\n ),\n }),\n});\n\nexport class AssistantFrameProvider {\n private static _instance: AssistantFrameProvider | null = null;\n\n private _providers = new Set<ModelContextProvider>();\n private _providerUnsubscribes = new Map<\n ModelContextProvider,\n Unsubscribe | undefined\n >();\n private _targetOrigin: string;\n\n private constructor(targetOrigin: string = \"*\") {\n this._targetOrigin = targetOrigin;\n this.handleMessage = this.handleMessage.bind(this);\n window.addEventListener(\"message\", this.handleMessage);\n\n setTimeout(() => this.broadcastUpdate(), 0);\n }\n\n private static getInstance(targetOrigin?: string): AssistantFrameProvider {\n if (!AssistantFrameProvider._instance) {\n AssistantFrameProvider._instance = new AssistantFrameProvider(\n targetOrigin,\n );\n }\n return AssistantFrameProvider._instance;\n }\n\n private handleMessage(event: MessageEvent) {\n if (this._targetOrigin !== \"*\" && event.origin !== this._targetOrigin)\n 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-request\":\n this.sendMessage(event, {\n type: \"model-context-update\",\n context: serializeModelContext(this.getModelContext()),\n });\n break;\n\n case \"tool-call\":\n this.handleToolCall(message, event);\n break;\n }\n }\n\n private async handleToolCall(\n message: Extract<FrameMessage, { type: \"tool-call\" }>,\n event: MessageEvent,\n ) {\n const tool = this.getModelContext().tools?.[message.toolName];\n\n let result: any;\n let error: string | undefined;\n\n if (!tool) {\n error = `Tool \"${message.toolName}\" not found`;\n } else {\n try {\n result = tool.execute\n ? await tool.execute(message.args, {\n toolCallId: message.id,\n abortSignal: new AbortController().signal,\n human: async () => {\n throw new Error(\n \"Tool human input is not supported in frame context\",\n );\n },\n })\n : undefined;\n } catch (e) {\n error = e instanceof Error ? e.message : String(e);\n }\n }\n\n this.sendMessage(event, {\n type: \"tool-result\",\n id: message.id,\n ...(error ? { error } : { result }),\n });\n }\n\n private sendMessage(event: MessageEvent, message: FrameMessage) {\n event.source?.postMessage(\n { channel: FRAME_MESSAGE_CHANNEL, message },\n { targetOrigin: event.origin },\n );\n }\n\n private getModelContext(): ModelContext {\n const contexts = Array.from(this._providers).map((p) =>\n p.getModelContext(),\n );\n\n return contexts.reduce(\n (merged, context) => ({\n system: context.system\n ? merged.system\n ? `${merged.system}\\n\\n${context.system}`\n : context.system\n : merged.system,\n tools: { ...(merged.tools || {}), ...(context.tools || {}) },\n }),\n {} as ModelContext,\n );\n }\n\n private broadcastUpdate() {\n if (window.parent && window.parent !== window) {\n const updateMessage: FrameMessage = {\n type: \"model-context-update\",\n context: serializeModelContext(this.getModelContext()),\n };\n\n window.parent.postMessage(\n { channel: FRAME_MESSAGE_CHANNEL, message: updateMessage },\n this._targetOrigin,\n );\n }\n }\n\n static addModelContextProvider(\n provider: ModelContextProvider,\n targetOrigin?: string,\n ): Unsubscribe {\n const instance = AssistantFrameProvider.getInstance(targetOrigin);\n instance._providers.add(provider);\n\n const unsubscribe = provider.subscribe?.(() => instance.broadcastUpdate());\n if (unsubscribe) {\n instance._providerUnsubscribes.set(provider, unsubscribe);\n }\n\n instance.broadcastUpdate();\n\n return () => {\n instance._providers.delete(provider);\n instance._providerUnsubscribes.get(provider)?.();\n instance._providerUnsubscribes.delete(provider);\n instance.broadcastUpdate();\n };\n }\n\n static dispose() {\n if (AssistantFrameProvider._instance) {\n const instance = AssistantFrameProvider._instance;\n window.removeEventListener(\"message\", instance.handleMessage);\n\n instance._providerUnsubscribes.forEach((unsubscribe) => unsubscribe?.());\n instance._providerUnsubscribes.clear();\n instance._providers.clear();\n\n AssistantFrameProvider._instance = null;\n }\n }\n}\n"],"mappings":";;;AAUA,MAAM,iBAAiB,UAA0C;CAC/D,GAAI,KAAK,eAAe,EAAE,aAAa,KAAK,YAAY;CACxD,YAAY,KAAK,aAAa,aAAa,KAAK,UAAU,IAAI,KAAA;CAC9D,GAAI,KAAK,aAAa,KAAA,KAAa,EAAE,UAAU,KAAK,SAAS;CAC7D,GAAI,KAAK,QAAQ,EAAE,MAAM,KAAK,KAAK;AACrC;AAEA,MAAM,yBACJ,aAC4B;CAC5B,GAAI,QAAQ,WAAW,KAAA,KAAa,EAAE,QAAQ,QAAQ,OAAO;CAC7D,GAAI,QAAQ,SAAS,EACnB,OAAO,OAAO,YACZ,OAAO,QAAQ,QAAQ,KAAK,CAAC,CAAC,KAAK,CAAC,MAAM,UAAU,CAClD,MACA,cAAc,IAAI,CACpB,CAAC,CACH,EACF;AACF;AAEA,IAAa,yBAAb,MAAa,uBAAuB;CAClC,OAAe,YAA2C;CAE1D,6BAAqB,IAAI,IAA0B;CACnD,wCAAgC,IAAI,IAGlC;CACF;CAEA,YAAoB,eAAuB,KAAK;EAC9C,KAAK,gB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file":"registry.js","names":[],"sources":["../../src/model-context/registry.ts"],"sourcesContent":["import type { Tool } from \"assistant-stream\";\nimport {\n type ModelContext,\n type ModelContextProvider,\n mergeModelContexts,\n type AssistantToolProps,\n type AssistantInstructionsConfig,\n} from \"./types\";\nimport type { Unsubscribe } from \"../types/unsubscribe\";\nimport type {\n ModelContextRegistryToolHandle,\n ModelContextRegistryInstructionHandle,\n ModelContextRegistryProviderHandle,\n} from \"./registry-handles\";\n\nexport class ModelContextRegistry implements ModelContextProvider {\n private _tools = new Map<symbol, AssistantToolProps<any, any>>();\n private _instructions = new Map<symbol, string>();\n private _providers = new Map<symbol, ModelContextProvider>();\n private _subscribers = new Set<() => void>();\n private _providerUnsubscribes = new Map<symbol, Unsubscribe | undefined>();\n\n getModelContext(): ModelContext {\n const instructions = Array.from(this._instructions.values()).filter(\n Boolean,\n );\n\n const system =\n instructions.length > 0 ? instructions.join(\"\\n\\n\") : undefined;\n\n const tools: Record<string, Tool<any, any>> = {};\n for (const toolProps of this._tools.values()) {\n const { toolName, render, ...tool } = toolProps;\n tools[toolName] = tool;\n }\n\n const providerContexts = mergeModelContexts(\n new Set(this._providers.values()),\n );\n\n const context: ModelContext = {\n system,\n tools: Object.keys(tools).length > 0 ? tools : undefined,\n };\n\n if (providerContexts.system) {\n context.system = context.system\n ? `${context.system}\\n\\n${providerContexts.system}`\n : providerContexts.system;\n }\n\n if (providerContexts.tools) {\n context.tools = { ...(context.tools || {}), ...providerContexts.tools };\n }\n\n if (providerContexts.callSettings) {\n context.callSettings = providerContexts.callSettings;\n }\n\n if (providerContexts.config) {\n context.config = providerContexts.config;\n }\n\n return context;\n }\n\n subscribe(callback: () => void): Unsubscribe {\n this._subscribers.add(callback);\n return () => this._subscribers.delete(callback);\n }\n\n private notifySubscribers(): void {\n for (const callback of this._subscribers) {\n callback();\n }\n }\n\n addTool<TArgs extends Record<string, unknown>, TResult>(\n tool: AssistantToolProps<TArgs, TResult>,\n ): ModelContextRegistryToolHandle<TArgs, TResult> {\n const id = Symbol();\n\n this._tools.set(id, tool);\n this.notifySubscribers();\n\n return {\n update: (newTool: AssistantToolProps<TArgs, TResult>) => {\n if (this._tools.has(id)) {\n this._tools.set(id, newTool);\n this.notifySubscribers();\n }\n },\n remove: () => {\n this._tools.delete(id);\n this.notifySubscribers();\n },\n };\n }\n\n addInstruction(\n config: string | AssistantInstructionsConfig,\n ): ModelContextRegistryInstructionHandle {\n const id = Symbol();\n\n const instruction =\n typeof config === \"string\" ? config : config.instruction;\n const disabled = typeof config === \"object\" ? config.disabled : false;\n\n if (!disabled) {\n this._instructions.set(id, instruction);\n this.notifySubscribers();\n }\n\n return {\n update: (newConfig: string | AssistantInstructionsConfig) => {\n const newInstruction =\n typeof newConfig === \"string\" ? newConfig : newConfig.instruction;\n const newDisabled =\n typeof newConfig === \"object\" ? newConfig.disabled : false;\n\n if (newDisabled) {\n this._instructions.delete(id);\n } else {\n this._instructions.set(id, newInstruction);\n }\n this.notifySubscribers();\n },\n remove: () => {\n this._instructions.delete(id);\n this.notifySubscribers();\n },\n };\n }\n\n addProvider(\n provider: ModelContextProvider,\n ): ModelContextRegistryProviderHandle {\n const id = Symbol();\n\n this._providers.set(id, provider);\n\n const unsubscribe = provider.subscribe?.(() => {\n this.notifySubscribers();\n });\n this._providerUnsubscribes.set(id, unsubscribe);\n\n this.notifySubscribers();\n\n return {\n remove: () => {\n this._providers.delete(id);\n const unsubscribe = this._providerUnsubscribes.get(id);\n unsubscribe?.();\n this._providerUnsubscribes.delete(id);\n this.notifySubscribers();\n },\n };\n }\n}\n"],"mappings":";;AAeA,IAAa,uBAAb,MAAkE;CAChE,yBAAiB,IAAI,IAA0C;CAC/D,gCAAwB,IAAI,IAAoB;CAChD,6BAAqB,IAAI,IAAkC;CAC3D,+BAAuB,IAAI,IAAgB;CAC3C,wCAAgC,IAAI,IAAqC;CAEzE,kBAAgC;EAC9B,MAAM,eAAe,MAAM,KAAK,KAAK,cAAc,OAAO,CAAC,EAAE,OAC3D,O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O,WAAW,WAAW,SAAS,OAAO;EAG/C,IAAI,EAFa,OAAO,WAAW,WAAW,OAAO,WAAW,QAEjD;GACb,KAAK,cAAc,IAAI,IAAI,WAAW;GACtC,KAAK,kBAAkB;EACzB;EAEA,OAAO;GACL,SAAS,cAAoD;IAC3D,MAAM,iBACJ,OAAO,cAAc,WAAW,YAAY,UAAU;IAIxD,IAFE,OAAO,cAAc,WAAW,UAAU,WAAW,OAGrD,KAAK,cAAc,OAAO,EAAE;SAE5B,KAAK,cAAc,IAAI,IAAI,cAAc;IAE3C,KAAK,kBAAkB;GACzB;GACA,cAAc;IACZ,KAAK,cAAc,OAAO,EAAE;IAC5B,KAAK,kBAAkB;GACzB;EACF;CACF;CAEA,YACE,UACoC;EACpC,MAAM,KAAK,OAAO;EAElB,KAAK,WAAW,IAAI,IAAI,QAAQ;EAEhC,MAAM,cAAc,SAAS,kBAAkB;GAC7C,KAAK,kBAAkB;EACzB,CAAC;EACD,KAAK,sBAAsB,IAAI,IAAI,WAAW;EAE9C,KAAK,kBAAkB;EAEvB,OAAO,EACL,cAAc;GACZ,KAAK,WAAW,OAAO,EAAE;GAEzB,KADyB,sBAAsB,IAAI,EACzC,IAAI;GACd,KAAK,sBAAsB,OAAO,EAAE;GACpC,KAAK,kBAAkB;EACzB,EACF;CACF;AACF"}
1
+ {"version":3,"file":"registry.js","names":[],"sources":["../../src/model-context/registry.ts"],"sourcesContent":["import type { Tool } from \"assistant-stream\";\nimport {\n type ModelContext,\n type ModelContextProvider,\n mergeModelContexts,\n type AssistantToolProps,\n type AssistantInstructionsConfig,\n} from \"./types\";\nimport type { Unsubscribe } from \"../types/unsubscribe\";\nimport type {\n ModelContextRegistryToolHandle,\n ModelContextRegistryInstructionHandle,\n ModelContextRegistryProviderHandle,\n} from \"./registry-handles\";\n\nexport class ModelContextRegistry implements ModelContextProvider {\n private _tools = new Map<symbol, AssistantToolProps<any, any>>();\n private _instructions = new Map<symbol, string>();\n private _providers = new Map<symbol, ModelContextProvider>();\n private _subscribers = new Set<() => void>();\n private _providerUnsubscribes = new Map<symbol, Unsubscribe | undefined>();\n\n getModelContext(): ModelContext {\n const instructions = Array.from(this._instructions.values()).filter(\n Boolean,\n );\n\n const system =\n instructions.length > 0 ? instructions.join(\"\\n\\n\") : undefined;\n\n const tools: Record<string, Tool<any, any>> = {};\n for (const toolProps of this._tools.values()) {\n const { toolName, render, ...tool } = toolProps;\n tools[toolName] = tool;\n }\n\n const providerContexts = mergeModelContexts(\n new Set(this._providers.values()),\n );\n\n const context: ModelContext = {\n system,\n tools: Object.keys(tools).length > 0 ? tools : undefined,\n };\n\n if (providerContexts.system) {\n context.system = context.system\n ? `${context.system}\\n\\n${providerContexts.system}`\n : providerContexts.system;\n }\n\n if (providerContexts.tools) {\n context.tools = { ...(context.tools || {}), ...providerContexts.tools };\n }\n\n if (providerContexts.callSettings) {\n context.callSettings = providerContexts.callSettings;\n }\n\n if (providerContexts.config) {\n context.config = providerContexts.config;\n }\n\n return context;\n }\n\n subscribe(callback: () => void): Unsubscribe {\n this._subscribers.add(callback);\n return () => this._subscribers.delete(callback);\n }\n\n private notifySubscribers(): void {\n for (const callback of this._subscribers) {\n callback();\n }\n }\n\n addTool<TArgs extends Record<string, unknown>, TResult>(\n tool: AssistantToolProps<TArgs, TResult>,\n ): ModelContextRegistryToolHandle<TArgs, TResult> {\n const id = Symbol();\n\n this._tools.set(id, tool);\n this.notifySubscribers();\n\n return {\n update: (newTool: AssistantToolProps<TArgs, TResult>) => {\n if (this._tools.has(id)) {\n this._tools.set(id, newTool);\n this.notifySubscribers();\n }\n },\n remove: () => {\n this._tools.delete(id);\n this.notifySubscribers();\n },\n };\n }\n\n addInstruction(\n config: string | AssistantInstructionsConfig,\n ): ModelContextRegistryInstructionHandle {\n const id = Symbol();\n\n const instruction =\n typeof config === \"string\" ? config : config.instruction;\n const disabled = typeof config === \"object\" ? config.disabled : false;\n\n if (!disabled) {\n this._instructions.set(id, instruction);\n this.notifySubscribers();\n }\n\n return {\n update: (newConfig: string | AssistantInstructionsConfig) => {\n const newInstruction =\n typeof newConfig === \"string\" ? newConfig : newConfig.instruction;\n const newDisabled =\n typeof newConfig === \"object\" ? newConfig.disabled : false;\n\n if (newDisabled) {\n this._instructions.delete(id);\n } else {\n this._instructions.set(id, newInstruction);\n }\n this.notifySubscribers();\n },\n remove: () => {\n this._instructions.delete(id);\n this.notifySubscribers();\n },\n };\n }\n\n addProvider(\n provider: ModelContextProvider,\n ): ModelContextRegistryProviderHandle {\n const id = Symbol();\n\n this._providers.set(id, provider);\n\n const unsubscribe = provider.subscribe?.(() => {\n this.notifySubscribers();\n });\n this._providerUnsubscribes.set(id, unsubscribe);\n\n this.notifySubscribers();\n\n return {\n remove: () => {\n this._providers.delete(id);\n const unsubscribe = this._providerUnsubscribes.get(id);\n unsubscribe?.();\n this._providerUnsubscribes.delete(id);\n this.notifySubscribers();\n },\n };\n }\n}\n"],"mappings":";;AAeA,IAAa,uBAAb,MAAkE;CAChE,yBAAiB,IAAI,IAA0C;CAC/D,gCAAwB,IAAI,IAAoB;CAChD,6BAAqB,IAAI,IAAkC;CAC3D,+BAAuB,IAAI,IAAgB;CAC3C,wCAAgC,IAAI,IAAqC;CAEzE,kBAAgC;EAC9B,MAAM,eAAe,MAAM,KAAK,KAAK,cAAc,OAAO,CAAC,CAAC,CAAC,OAC3D,OACF;EAEA,MAAM,SACJ,aAAa,SAAS,IAAI,aAAa,KAAK,MAAM,IAAI,KAAA;EAExD,MAAM,QAAwC,CAAC;EAC/C,KAAK,MAAM,aAAa,KAAK,OAAO,OAAO,GAAG;GAC5C,MAAM,EAAE,UAAU,QAAQ,GAAG,SAAS;GACtC,MAAM,YAAY;EACpB;EAEA,MAAM,mBAAmB,mBACvB,IAAI,IAAI,KAAK,WAAW,OAAO,CAAC,CAClC;EAEA,MAAM,UAAwB;GAC5B;GACA,OAAO,OAAO,KAAK,KAAK,CAAC,CAAC,SAAS,IAAI,QAAQ,KAAA;EACjD;EAEA,IAAI,iBA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c,OAAO,EAAE;IAC5B,KAAK,kBAAkB;GACzB;EACF;CACF;CAEA,YACE,UACoC;EACpC,MAAM,KAAK,OAAO;EAElB,KAAK,WAAW,IAAI,IAAI,QAAQ;EAEhC,MAAM,cAAc,SAAS,kBAAkB;GAC7C,KAAK,kBAAkB;EACzB,CAAC;EACD,KAAK,sBAAsB,IAAI,IAAI,WAAW;EAE9C,KAAK,kBAAkB;EAEvB,OAAO,EACL,cAAc;GACZ,KAAK,WAAW,OAAO,EAAE;GAEzB,KADyB,sBAAsB,IAAI,EACzC,CAAC,GAAG;GACd,KAAK,sBAAsB,OAAO,EAAE;GACpC,KAAK,kBAAkB;EACzB,EACF;CACF;AACF"}
@@ -6,7 +6,7 @@ import { Tool } from "assistant-stream";
6
6
  * optional model-output conversion.
7
7
  *
8
8
  * This helper keeps reusable tool definitions type-checked and convenient to
9
- * export for a {@link Toolkit}, {@link Tools}, or {@link useAssistantTool}.
9
+ * export for a {@link Toolkit} registered with {@link Tools}.
10
10
  * Inference from parameter schemas is currently limited, so provide generic
11
11
  * arguments when you need precise args or result types.
12
12
  *
@@ -4,7 +4,7 @@
4
4
  * optional model-output conversion.
5
5
  *
6
6
  * This helper keeps reusable tool definitions type-checked and convenient to
7
- * export for a {@link Toolkit}, {@link Tools}, or {@link useAssistantTool}.
7
+ * export for a {@link Toolkit} registered with {@link Tools}.
8
8
  * Inference from parameter schemas is currently limited, so provide generic
9
9
  * arguments when you need precise args or result types.
10
10
  *
@@ -1 +1 @@
1
- {"version":3,"file":"tool.js","names":[],"sources":["../../src/model-context/tool.ts"],"sourcesContent":["import type { Tool } from \"assistant-stream\";\n\n// TODO re-add the inferrence of the parameters\n\n/**\n * Defines a model tool with its argument schema, execution behavior, and\n * optional model-output conversion.\n *\n * This helper keeps reusable tool definitions type-checked and convenient to\n * export for a {@link Toolkit}, {@link Tools}, or {@link useAssistantTool}.\n * Inference from parameter schemas is currently limited, so provide generic\n * arguments when you need precise args or result types.\n *\n * @param tool - Tool definition to expose to the assistant model.\n *\n * @example\n * ```ts\n * const getWeather = tool<{ city: string }, string>({\n * type: \"frontend\",\n * description: \"Get the weather for a city.\",\n * parameters: {\n * type: \"object\",\n * properties: { city: { type: \"string\" } },\n * required: [\"city\"],\n * },\n * execute: async ({ city }) => `Sunny in ${city}`,\n * });\n * ```\n */\nexport function tool<TArgs extends Record<string, unknown>, TResult = any>(\n tool: Tool<TArgs, TResult>,\n): Tool<TArgs, TResult> {\n return tool;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,KACd,MACsB;CACtB,OAAO;AACT"}
1
+ {"version":3,"file":"tool.js","names":[],"sources":["../../src/model-context/tool.ts"],"sourcesContent":["import type { Tool } from \"assistant-stream\";\n\n// TODO re-add the inferrence of the parameters\n\n/**\n * Defines a model tool with its argument schema, execution behavior, and\n * optional model-output conversion.\n *\n * This helper keeps reusable tool definitions type-checked and convenient to\n * export for a {@link Toolkit} registered with {@link Tools}.\n * Inference from parameter schemas is currently limited, so provide generic\n * arguments when you need precise args or result types.\n *\n * @param tool - Tool definition to expose to the assistant model.\n *\n * @example\n * ```ts\n * const getWeather = tool<{ city: string }, string>({\n * type: \"frontend\",\n * description: \"Get the weather for a city.\",\n * parameters: {\n * type: \"object\",\n * properties: { city: { type: \"string\" } },\n * required: [\"city\"],\n * },\n * execute: async ({ city }) => `Sunny in ${city}`,\n * });\n * ```\n */\nexport function tool<TArgs extends Record<string, unknown>, TResult = any>(\n tool: Tool<TArgs, TResult>,\n): Tool<TArgs, TResult> {\n return tool;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,KACd,MACsB;CACtB,OAAO;AACT"}
@@ -1,13 +1,28 @@
1
1
  //#region src/model-context/types.ts
2
2
  const mergeModelContexts = (configSet) => {
3
- return Array.from(configSet).map((c) => c.getModelContext()).sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0)).reduce((acc, config) => {
3
+ const configs = Array.from(configSet).map((c) => c.getModelContext()).sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
4
+ const toolPriorities = {};
5
+ return configs.reduce((acc, config) => {
6
+ const priority = config.priority ?? 0;
4
7
  if (config.system) if (acc.system) acc.system += `\n\n${config.system}`;
5
8
  else acc.system = config.system;
6
9
  if (config.tools) for (const [name, tool] of Object.entries(config.tools)) {
7
10
  const existing = acc.tools?.[name];
8
- if (existing && existing !== tool) throw new Error(`You tried to define a tool with the name ${name}, but it already exists.`);
11
+ if (existing && existing !== tool) {
12
+ const existingPriority = toolPriorities[name];
13
+ if (existingPriority === priority) throw new Error(`You tried to define a tool with the name ${name}, but it already exists.`);
14
+ const higherPriorityTool = existingPriority > priority ? existing : tool;
15
+ const lowerPriorityTool = existingPriority > priority ? tool : existing;
16
+ acc.tools[name] = {
17
+ ...lowerPriorityTool,
18
+ ...higherPriorityTool
19
+ };
20
+ toolPriorities[name] = Math.max(existingPriority, priority);
21
+ continue;
22
+ }
9
23
  if (!acc.tools) acc.tools = {};
10
24
  acc.tools[name] = tool;
25
+ toolPriorities[name] ??= priority;
11
26
  }
12
27
  if (config.config) acc.config = {
13
28
  ...acc.config,
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","names":[],"sources":["../../src/model-context/types.ts"],"sourcesContent":["import type { Unsubscribe } from \"../types/unsubscribe\";\nimport type { Tool } from \"assistant-stream\";\n\nexport type LanguageModelV1CallSettings = {\n maxTokens?: number;\n temperature?: number;\n topP?: number;\n presencePenalty?: number;\n frequencyPenalty?: number;\n seed?: number;\n headers?: Record<string, string | undefined>;\n};\n\nexport type LanguageModelConfig = {\n apiKey?: string;\n baseUrl?: string;\n modelName?: string;\n};\n\nexport type ModelContext = {\n priority?: number | undefined;\n system?: string | undefined;\n tools?: Record<string, Tool<any, any>> | undefined;\n callSettings?: LanguageModelV1CallSettings | undefined;\n config?: LanguageModelConfig | undefined;\n};\n\nexport type ModelContextProvider = {\n getModelContext: () => ModelContext;\n subscribe?: (callback: () => void) => Unsubscribe;\n};\n\nexport type AssistantToolProps<\n TArgs extends Record<string, unknown>,\n TResult,\n> = Tool<TArgs, TResult> & {\n toolName: string;\n render?: unknown;\n};\n\nexport type AssistantInstructionsConfig = {\n disabled?: boolean | undefined;\n instruction: string;\n};\n\nexport type AssistantContextConfig = {\n getContext: () => string;\n disabled?: boolean | undefined;\n};\n\nexport const mergeModelContexts = (\n configSet: Set<ModelContextProvider>,\n): ModelContext => {\n const configs = Array.from(configSet)\n .map((c) => c.getModelContext())\n .sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));\n\n return configs.reduce((acc, config) => {\n if (config.system) {\n if (acc.system) {\n acc.system += `\\n\\n${config.system}`;\n } else {\n acc.system = config.system;\n }\n }\n if (config.tools) {\n for (const [name, tool] of Object.entries(config.tools)) {\n const existing = acc.tools?.[name];\n if (existing && existing !== tool) {\n throw new Error(\n `You tried to define a tool with the name ${name}, but it already exists.`,\n );\n }\n\n if (!acc.tools) acc.tools = {};\n acc.tools[name] = tool;\n }\n }\n if (config.config) {\n acc.config = {\n ...acc.config,\n ...config.config,\n };\n }\n if (config.callSettings) {\n acc.callSettings = {\n ...acc.callSettings,\n ...config.callSettings,\n };\n }\n return acc;\n }, {} as ModelContext);\n};\n"],"mappings":";AAkDA,MAAa,sBACX,cACiB;CAKjB,OAJgB,MAAM,KAAK,SAAS,EACjC,KAAK,MAAM,EAAE,gBAAgB,CAAC,EAC9B,MAAM,GAAG,OAAO,EAAE,YAAY,MAAM,EAAE,YAAY,EAExC,EAAE,QAAQ,KAAK,WAAW;EACrC,IAAI,OAAO,QACT,IAAI,IAAI,QACN,IAAI,UAAU,OAAO,OAAO;OAE5B,IAAI,SAAS,OAAO;EAGxB,IAAI,OAAO,OACT,KAAK,MAAM,CAAC,MAAM,SAAS,OAAO,QAAQ,OAAO,KAAK,GAAG;GACvD,MAAM,WAAW,IAAI,QAAQ;GAC7B,IAAI,YAAY,aAAa,MAC3B,MAAM,IAAI,MACR,4CAA4C,KAAK,yBACnD;GAGF,IAAI,CAAC,IAAI,OAAO,IAAI,QAAQ,CAAC;GAC7B,IAAI,MAAM,QAAQ;EACpB;EAEF,IAAI,OAAO,QACT,IAAI,SAAS;GACX,GAAG,IAAI;GACP,GAAG,OAAO;EACZ;EAEF,IAAI,OAAO,cACT,IAAI,eAAe;GACjB,GAAG,IAAI;GACP,GAAG,OAAO;EACZ;EAEF,OAAO;CACT,GAAG,CAAC,CAAiB;AACvB"}
1
+ {"version":3,"file":"types.js","names":[],"sources":["../../src/model-context/types.ts"],"sourcesContent":["import type { Unsubscribe } from \"../types/unsubscribe\";\nimport type { Tool } from \"assistant-stream\";\n\nexport type LanguageModelV1CallSettings = {\n maxTokens?: number;\n temperature?: number;\n topP?: number;\n presencePenalty?: number;\n frequencyPenalty?: number;\n seed?: number;\n headers?: Record<string, string | undefined>;\n};\n\nexport type LanguageModelConfig = {\n apiKey?: string;\n baseUrl?: string;\n modelName?: string;\n};\n\nexport type ModelContext = {\n priority?: number | undefined;\n system?: string | undefined;\n tools?: Record<string, Tool<any, any>> | undefined;\n callSettings?: LanguageModelV1CallSettings | undefined;\n config?: LanguageModelConfig | undefined;\n};\n\nexport type ModelContextProvider = {\n getModelContext: () => ModelContext;\n subscribe?: (callback: () => void) => Unsubscribe;\n};\n\nexport type AssistantToolProps<\n TArgs extends Record<string, unknown>,\n TResult,\n> = Tool<TArgs, TResult> & {\n toolName: string;\n render?: unknown;\n};\n\nexport type AssistantInstructionsConfig = {\n disabled?: boolean | undefined;\n instruction: string;\n};\n\nexport type AssistantContextConfig = {\n getContext: () => string;\n disabled?: boolean | undefined;\n};\n\nexport const mergeModelContexts = (\n configSet: Set<ModelContextProvider>,\n): ModelContext => {\n const configs = Array.from(configSet)\n .map((c) => c.getModelContext())\n .sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));\n\n const toolPriorities: Record<string, number> = {};\n\n return configs.reduce((acc, config) => {\n const priority = config.priority ?? 0;\n if (config.system) {\n if (acc.system) {\n acc.system += `\\n\\n${config.system}`;\n } else {\n acc.system = config.system;\n }\n }\n if (config.tools) {\n for (const [name, tool] of Object.entries(config.tools)) {\n const existing = acc.tools?.[name];\n if (existing && existing !== tool) {\n const existingPriority = toolPriorities[name]!;\n if (existingPriority === priority) {\n throw new Error(\n `You tried to define a tool with the name ${name}, but it already exists.`,\n );\n }\n\n const higherPriorityTool =\n existingPriority > priority ? existing : tool;\n const lowerPriorityTool =\n existingPriority > priority ? tool : existing;\n acc.tools![name] = {\n ...lowerPriorityTool,\n ...higherPriorityTool,\n } as Tool<any, any>;\n toolPriorities[name] = Math.max(existingPriority, priority);\n continue;\n }\n\n if (!acc.tools) acc.tools = {};\n acc.tools[name] = tool;\n toolPriorities[name] ??= priority;\n }\n }\n if (config.config) {\n acc.config = {\n ...acc.config,\n ...config.config,\n };\n }\n if (config.callSettings) {\n acc.callSettings = {\n ...acc.callSettings,\n ...config.callSettings,\n };\n }\n return acc;\n }, {} as ModelContext);\n};\n"],"mappings":";AAkDA,MAAa,sBACX,cACiB;CACjB,MAAM,UAAU,MAAM,KAAK,SAAS,CAAC,CAClC,KAAK,MAAM,EAAE,gBAAgB,CAAC,CAAC,CAC/B,MAAM,GAAG,OAAO,EAAE,YAAY,MAAM,EAAE,YAAY,EAAE;CAEvD,MAAM,iBAAyC,CAAC;CAEhD,OAAO,QAAQ,QAAQ,KAAK,WAAW;EACrC,MAAM,WAAW,OAAO,YAAY;EACpC,IAAI,OAAO,QACT,IAAI,IAAI,QACN,IAAI,UAAU,OAAO,OAAO;OAE5B,IAAI,SAAS,OAAO;EAGxB,IAAI,OAAO,OACT,KAAK,MAAM,CAAC,MAAM,SAAS,OAAO,QAAQ,OAAO,KAAK,GAAG;GACvD,MAAM,WAAW,IAAI,QAAQ;GAC7B,IAAI,YAAY,aAAa,MAAM;IACjC,MAAM,mBAAmB,eAAe;IACxC,IAAI,qBAAqB,UACvB,MAAM,IAAI,MACR,4CAA4C,KAAK,yBACnD;IAGF,MAAM,qBACJ,mBAAmB,WAAW,WAAW;IAC3C,MAAM,oBACJ,mBAAmB,WAAW,OAAO;IACvC,IAAI,MAAO,QAAQ;KACjB,GAAG;KACH,GAAG;IACL;IACA,eAAe,QAAQ,KAAK,IAAI,kBAAkB,QAAQ;IAC1D;GACF;GAEA,IAAI,CAAC,IAAI,OAAO,IAAI,QAAQ,CAAC;GAC7B,IAAI,MAAM,QAAQ;GAClB,eAAe,UAAU;EAC3B;EAEF,IAAI,OAAO,QACT,IAAI,SAAS;GACX,GAAG,IAAI;GACP,GAAG,OAAO;EACZ;EAEF,IAAI,OAAO,cACT,IAAI,eAAe;GACjB,GAAG,IAAI;GACP,GAAG,OAAO;EACZ;EAEF,OAAO;CACT,GAAG,CAAC,CAAiB;AACvB"}
@@ -1,5 +1,5 @@
1
1
  import { RuntimeAdapter } from "./RuntimeAdapter.js";
2
- import { memo } from "react";
2
+ import { memo } from "@assistant-ui/tap/react-shim";
3
3
  import { AuiProvider, useAui } from "@assistant-ui/store";
4
4
  import { jsx, jsxs } from "react/jsx-runtime";
5
5
  //#region src/react/AssistantProvider.tsx
@@ -44,7 +44,7 @@ declare const AssistantRuntimeProvider: import("react").MemoExoticComponent<({
44
44
  */
45
45
  aui?: AssistantClient | null;
46
46
  children: ReactNode;
47
- }) => import("react/jsx-runtime").JSX.Element>;
47
+ }) => import("react").JSX.Element>;
48
48
  //#endregion
49
49
  export { AssistantRuntimeProvider };
50
50
  //# sourceMappingURL=AssistantRuntimeProvider.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantRuntimeProvider.d.ts","names":[],"sources":["../../src/react/AssistantRuntimeProvider.tsx"],"mappings":";;;;;;;AA2BA;;;;;;;;;;;;;;;;;;;;cAAa,wBAAA,kBAAwB,mBAAA;EAAA,OAAA;EAAA,GAAA;EAAA;AAAA;EAkB3B;;;;;EAPN,OAAA,EAAS,gBAAA;EASV;;;;;;EAFC,GAAA,GAAM,eAAA;EACN,QAAA,EAAU,SAAA;AAAA,kCACX,GAAA,CAAA,OAAA"}
1
+ {"version":3,"file":"AssistantRuntimeProvider.d.ts","names":[],"sources":["../../src/react/AssistantRuntimeProvider.tsx"],"mappings":";;;;;;;AA2BA;;;;;;;;;;;;;;;;;;;;cAAa,wBAAA,kBAAwB,mBAAA;EAAA,OAAA;EAAA,GAAA;EAAA;AAAA;EAkB3B;;;;;EAPN,OAAA,EAAS,gBAAA;EASV;;;;;;EAFC,GAAA,GAAM,eAAA;EACN,QAAA,EAAU,SAAA;AAAA,sBACX,GAAA,CAAA,OAAA"}
@@ -1,5 +1,5 @@
1
1
  import { AssistantProviderBase } from "./AssistantProvider.js";
2
- import { memo } from "react";
2
+ import { memo } from "@assistant-ui/tap/react-shim";
3
3
  import { jsx } from "react/jsx-runtime";
4
4
  //#region src/react/AssistantRuntimeProvider.tsx
5
5
  /**
@@ -2,9 +2,11 @@ import { RuntimeAdapterResource, baseRuntimeAdapterTransformScopes } from "../st
2
2
  import { DataRenderers } from "./client/DataRenderers.js";
3
3
  import { Tools } from "./client/Tools.js";
4
4
  import { attachTransformScopes } from "@assistant-ui/store";
5
- import { resource, tapResource } from "@assistant-ui/tap";
5
+ import { resource, useResource } from "@assistant-ui/tap";
6
6
  //#region src/react/RuntimeAdapter.ts
7
- const RuntimeAdapter = resource((runtime) => tapResource(RuntimeAdapterResource(runtime)));
7
+ const RuntimeAdapter = resource(function RuntimeAdapter(runtime) {
8
+ return useResource(RuntimeAdapterResource(runtime));
9
+ });
8
10
  attachTransformScopes(RuntimeAdapter, (scopes, parent) => {
9
11
  baseRuntimeAdapterTransformScopes(scopes, parent);
10
12
  if (!scopes.tools && parent.tools.source === null) scopes.tools = Tools({});
@@ -1 +1 @@
1
- {"version":3,"file":"RuntimeAdapter.js","names":[],"sources":["../../src/react/RuntimeAdapter.ts"],"sourcesContent":["import { resource, tapResource } from \"@assistant-ui/tap\";\nimport type { AssistantRuntime } from \"..\";\nimport {\n RuntimeAdapterResource,\n baseRuntimeAdapterTransformScopes,\n} from \"../store/internal\";\nimport { attachTransformScopes } from \"@assistant-ui/store\";\nimport { DataRenderers } from \"./client/DataRenderers\";\nimport { Tools } from \"./client/Tools\";\n\nexport const RuntimeAdapter = resource((runtime: AssistantRuntime) =>\n tapResource(RuntimeAdapterResource(runtime)),\n);\n\nattachTransformScopes(RuntimeAdapter, (scopes, parent) => {\n baseRuntimeAdapterTransformScopes(scopes, parent);\n\n if (!scopes.tools && parent.tools.source === null) {\n scopes.tools = Tools({});\n }\n\n if (!scopes.dataRenderers && parent.dataRenderers.source === null) {\n scopes.dataRenderers = DataRenderers();\n }\n});\n"],"mappings":";;;;;;AAUA,MAAa,iBAAiB,UAAU,YACtC,YAAY,uBAAuB,OAAO,CAAC,CAC7C;AAEA,sBAAsB,iBAAiB,QAAQ,WAAW;CACxD,kCAAkC,QAAQ,MAAM;CAEhD,IAAI,CAAC,OAAO,SAAS,OAAO,MAAM,WAAW,MAC3C,OAAO,QAAQ,MAAM,CAAC,CAAC;CAGzB,IAAI,CAAC,OAAO,iBAAiB,OAAO,cAAc,WAAW,MAC3D,OAAO,gBAAgB,cAAc;AAEzC,CAAC"}
1
+ {"version":3,"file":"RuntimeAdapter.js","names":[],"sources":["../../src/react/RuntimeAdapter.ts"],"sourcesContent":["import { useResource, resource } from \"@assistant-ui/tap\";\nimport type { AssistantRuntime } from \"..\";\nimport {\n RuntimeAdapterResource,\n baseRuntimeAdapterTransformScopes,\n} from \"../store/internal\";\nimport { attachTransformScopes } from \"@assistant-ui/store\";\nimport { DataRenderers } from \"./client/DataRenderers\";\nimport { Tools } from \"./client/Tools\";\n\nexport const RuntimeAdapter = resource(function RuntimeAdapter(\n runtime: AssistantRuntime,\n) {\n return useResource(RuntimeAdapterResource(runtime));\n});\n\nattachTransformScopes(RuntimeAdapter, (scopes, parent) => {\n baseRuntimeAdapterTransformScopes(scopes, parent);\n\n if (!scopes.tools && parent.tools.source === null) {\n scopes.tools = Tools({});\n }\n\n if (!scopes.dataRenderers && parent.dataRenderers.source === null) {\n scopes.dataRenderers = DataRenderers();\n }\n});\n"],"mappings":";;;;;;AAUA,MAAa,iBAAiB,SAAS,SAAS,eAC9C,SACA;CACA,OAAO,YAAY,uBAAuB,OAAO,CAAC;AACpD,CAAC;AAED,sBAAsB,iBAAiB,QAAQ,WAAW;CACxD,kCAAkC,QAAQ,MAAM;CAEhD,IAAI,CAAC,OAAO,SAAS,OAAO,MAAM,WAAW,MAC3C,OAAO,QAAQ,MAAM,CAAC,CAAC;CAGzB,IAAI,CAAC,OAAO,iBAAiB,OAAO,cAAc,WAAW,MAC3D,OAAO,gBAAgB,cAAc;AAEzC,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"LocalStorageThreadListAdapter.d.ts","names":[],"sources":["../../../src/react/adapters/LocalStorageThreadListAdapter.tsx"],"mappings":";;;;KAkBY,gBAAA;EACV,OAAA,CAAQ,GAAA,WAAc,OAAA;EACtB,OAAA,CAAQ,GAAA,UAAa,KAAA,WAAgB,OAAA;EACrC,UAAA,CAAW,GAAA,WAAc,OAAA;AAAA;AAAA,KAGtB,0BAAA;EACH,OAAA,EAAS,gBAAA;EACT,MAAA;EACA,cAAA,GAAiB,sBAAsB;AAAA;AAAA,cA4E5B,yBAAA,GACX,OAAA,EAAS,0BAAA,KACR,uBA2HF"}
1
+ {"version":3,"file":"LocalStorageThreadListAdapter.d.ts","names":[],"sources":["../../../src/react/adapters/LocalStorageThreadListAdapter.tsx"],"mappings":";;;;KAkBY,gBAAA;EACV,OAAA,CAAQ,GAAA,WAAc,OAAA;EACtB,OAAA,CAAQ,GAAA,UAAa,KAAA,WAAgB,OAAA;EACrC,UAAA,CAAW,GAAA,WAAc,OAAA;AAAA;AAAA,KAGtB,0BAAA;EACH,OAAA,EAAS,gBAAA;EACT,MAAA;EACA,cAAA,GAAiB,sBAAsB;AAAA;AAAA,cA2E5B,yBAAA,GACX,OAAA,EAAS,0BAAA,KACR,uBAyIF"}