@assistant-ui/core 0.3.15 → 0.3.16

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 (251) hide show
  1. package/dist/internal.d.ts +7 -2
  2. package/dist/internal.js +8 -3
  3. package/dist/model-context/frame/host.d.ts.map +1 -1
  4. package/dist/model-context/frame/host.js +3 -2
  5. package/dist/model-context/frame/host.js.map +1 -1
  6. package/dist/model-context/frame/provider.d.ts +2 -0
  7. package/dist/model-context/frame/provider.d.ts.map +1 -1
  8. package/dist/model-context/frame/provider.js +88 -25
  9. package/dist/model-context/frame/provider.js.map +1 -1
  10. package/dist/model-context/interactable-composer-metadata.d.ts +1 -1
  11. package/dist/model-context/interactable-composer-metadata.js +1 -1
  12. package/dist/model-context/interactable-composer-metadata.js.map +1 -1
  13. package/dist/model-context/registry.d.ts +2 -2
  14. package/dist/model-context/registry.d.ts.map +1 -1
  15. package/dist/model-context/registry.js +9 -28
  16. package/dist/model-context/registry.js.map +1 -1
  17. package/dist/react/client/InMemoryThreadList.d.ts.map +1 -1
  18. package/dist/react/client/InMemoryThreadList.js +24 -20
  19. package/dist/react/client/InMemoryThreadList.js.map +1 -1
  20. package/dist/react/client/Interactables.d.ts.map +1 -1
  21. package/dist/react/client/Interactables.js +59 -177
  22. package/dist/react/client/Interactables.js.map +1 -1
  23. package/dist/react/client/RemoteThreadList.d.ts.map +1 -1
  24. package/dist/react/client/RemoteThreadList.js +23 -56
  25. package/dist/react/client/RemoteThreadList.js.map +1 -1
  26. package/dist/react/index.d.ts +2 -1
  27. package/dist/react/interactables-legacy/Interactables.d.ts.map +1 -1
  28. package/dist/react/interactables-legacy/Interactables.js +56 -174
  29. package/dist/react/interactables-legacy/Interactables.js.map +1 -1
  30. package/dist/react/interactables-shared/useInteractablePersistenceQueue.d.ts +24 -0
  31. package/dist/react/interactables-shared/useInteractablePersistenceQueue.d.ts.map +1 -0
  32. package/dist/react/interactables-shared/useInteractablePersistenceQueue.js +138 -0
  33. package/dist/react/interactables-shared/useInteractablePersistenceQueue.js.map +1 -0
  34. package/dist/react/primitives/composer/ComposerIf.js.map +1 -1
  35. package/dist/react/primitives/composer/ComposerQueue.d.ts +2 -1
  36. package/dist/react/primitives/composer/ComposerQueue.d.ts.map +1 -1
  37. package/dist/react/primitives/message/MessageParts.js.map +1 -1
  38. package/dist/react/runtimes/RemoteThreadListHookInstanceManager.d.ts +1 -1
  39. package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts +1 -1
  40. package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts.map +1 -1
  41. package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js +23 -55
  42. package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js.map +1 -1
  43. package/dist/react/runtimes/assistant-transport/runManager.d.ts.map +1 -1
  44. package/dist/react/runtimes/assistant-transport/runManager.js +2 -12
  45. package/dist/react/runtimes/assistant-transport/runManager.js.map +1 -1
  46. package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.d.ts +3 -10
  47. package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.d.ts.map +1 -1
  48. package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.js +20 -67
  49. package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.js.map +1 -1
  50. package/dist/react/runtimes/cloud/createCloudThreadListAdapterCreateFallback.d.ts +12 -0
  51. package/dist/react/runtimes/cloud/createCloudThreadListAdapterCreateFallback.d.ts.map +1 -0
  52. package/dist/react/runtimes/cloud/createCloudThreadListAdapterCreateFallback.js +10 -0
  53. package/dist/react/runtimes/cloud/createCloudThreadListAdapterCreateFallback.js.map +1 -0
  54. package/dist/react/runtimes/cloud/useCloudThreadListRuntime.js.map +1 -1
  55. package/dist/react/runtimes/createMessageConverter.d.ts +2 -1
  56. package/dist/react/runtimes/createMessageConverter.d.ts.map +1 -1
  57. package/dist/react/runtimes/external-message-converter.d.ts +6 -25
  58. package/dist/react/runtimes/external-message-converter.d.ts.map +1 -1
  59. package/dist/react/runtimes/external-message-converter.js +33 -233
  60. package/dist/react/runtimes/external-message-converter.js.map +1 -1
  61. package/dist/runtime/api/composer-runtime.d.ts +1 -1
  62. package/dist/runtime/api/composer-runtime.js.map +1 -1
  63. package/dist/runtime/api/thread-runtime.d.ts +1 -2
  64. package/dist/runtime/api/thread-runtime.d.ts.map +1 -1
  65. package/dist/runtime/base/base-composer-runtime-core.d.ts +1 -1
  66. package/dist/runtime/base/base-composer-runtime-core.d.ts.map +1 -1
  67. package/dist/runtime/base/base-composer-runtime-core.js +14 -29
  68. package/dist/runtime/base/base-composer-runtime-core.js.map +1 -1
  69. package/dist/runtime/base/base-thread-runtime-core.d.ts +2 -4
  70. package/dist/runtime/base/base-thread-runtime-core.d.ts.map +1 -1
  71. package/dist/runtime/base/base-thread-runtime-core.js +3 -9
  72. package/dist/runtime/base/base-thread-runtime-core.js.map +1 -1
  73. package/dist/runtime/base/default-thread-composer-runtime-core.d.ts +1 -1
  74. package/dist/runtime/base/default-thread-composer-runtime-core.d.ts.map +1 -1
  75. package/dist/runtime/base/default-thread-composer-runtime-core.js +1 -1
  76. package/dist/runtime/base/default-thread-composer-runtime-core.js.map +1 -1
  77. package/dist/runtime/interfaces/composer-runtime-core.d.ts +1 -1
  78. package/dist/runtime/interfaces/thread-runtime-core.d.ts +1 -1
  79. package/dist/runtime/internal.d.ts +2 -1
  80. package/dist/runtime/internal.js +2 -1
  81. package/dist/runtime/queue/external-thread-queue-adapter.d.ts +1 -1
  82. package/dist/runtime/queue/message-queue.d.ts.map +1 -1
  83. package/dist/runtime/queue/message-queue.js +1 -1
  84. package/dist/runtime/queue/message-queue.js.map +1 -1
  85. package/dist/runtime/queue/queue-item.d.ts +12 -0
  86. package/dist/runtime/queue/queue-item.d.ts.map +1 -0
  87. package/dist/runtime/queue/queue-item.js +6 -0
  88. package/dist/runtime/queue/queue-item.js.map +1 -0
  89. package/dist/runtime/utils/abortable-thread-load.d.ts +15 -0
  90. package/dist/runtime/utils/abortable-thread-load.d.ts.map +1 -0
  91. package/dist/runtime/utils/abortable-thread-load.js +35 -0
  92. package/dist/runtime/utils/abortable-thread-load.js.map +1 -0
  93. package/dist/runtime/utils/attachment-add-operations.d.ts +18 -0
  94. package/dist/runtime/utils/attachment-add-operations.d.ts.map +1 -0
  95. package/dist/runtime/utils/attachment-add-operations.js +43 -0
  96. package/dist/runtime/utils/attachment-add-operations.js.map +1 -0
  97. package/dist/runtime/utils/auto-status.d.ts +6 -1
  98. package/dist/runtime/utils/auto-status.d.ts.map +1 -1
  99. package/dist/runtime/utils/auto-status.js +7 -1
  100. package/dist/runtime/utils/auto-status.js.map +1 -1
  101. package/dist/runtime/utils/external-message-conversion.d.ts +47 -0
  102. package/dist/runtime/utils/external-message-conversion.d.ts.map +1 -0
  103. package/dist/runtime/utils/external-message-conversion.js +221 -0
  104. package/dist/runtime/utils/external-message-conversion.js.map +1 -0
  105. package/dist/runtime/utils/external-store-message.d.ts +2 -1
  106. package/dist/runtime/utils/external-store-message.d.ts.map +1 -1
  107. package/dist/runtime/utils/external-store-message.js +2 -1
  108. package/dist/runtime/utils/external-store-message.js.map +1 -1
  109. package/dist/runtime/utils/message-repository-session.d.ts +30 -0
  110. package/dist/runtime/utils/message-repository-session.d.ts.map +1 -0
  111. package/dist/runtime/utils/message-repository-session.js +130 -0
  112. package/dist/runtime/utils/message-repository-session.js.map +1 -0
  113. package/dist/runtime/utils/message-repository.d.ts.map +1 -1
  114. package/dist/runtime/utils/message-repository.js +3 -4
  115. package/dist/runtime/utils/message-repository.js.map +1 -1
  116. package/dist/runtime/utils/pending-tool-calls.d.ts +20 -0
  117. package/dist/runtime/utils/pending-tool-calls.d.ts.map +1 -0
  118. package/dist/runtime/utils/pending-tool-calls.js +22 -0
  119. package/dist/runtime/utils/pending-tool-calls.js.map +1 -0
  120. package/dist/runtime/utils/thread-message-like.d.ts +2 -1
  121. package/dist/runtime/utils/thread-message-like.d.ts.map +1 -1
  122. package/dist/runtime/utils/thread-message-like.js.map +1 -1
  123. package/dist/runtimes/external-store/external-store-thread-list-runtime-core.d.ts +2 -5
  124. package/dist/runtimes/external-store/external-store-thread-list-runtime-core.d.ts.map +1 -1
  125. package/dist/runtimes/external-store/external-store-thread-list-runtime-core.js +3 -10
  126. package/dist/runtimes/external-store/external-store-thread-list-runtime-core.js.map +1 -1
  127. package/dist/runtimes/external-store/external-store-thread-runtime-core.d.ts +19 -1
  128. package/dist/runtimes/external-store/external-store-thread-runtime-core.d.ts.map +1 -1
  129. package/dist/runtimes/external-store/external-store-thread-runtime-core.js +122 -20
  130. package/dist/runtimes/external-store/external-store-thread-runtime-core.js.map +1 -1
  131. package/dist/runtimes/local/local-thread-runtime-core.d.ts +3 -1
  132. package/dist/runtimes/local/local-thread-runtime-core.d.ts.map +1 -1
  133. package/dist/runtimes/local/local-thread-runtime-core.js +20 -2
  134. package/dist/runtimes/local/local-thread-runtime-core.js.map +1 -1
  135. package/dist/runtimes/remote-thread-list/remote-thread-state.d.ts +12 -1
  136. package/dist/runtimes/remote-thread-list/remote-thread-state.d.ts.map +1 -1
  137. package/dist/runtimes/remote-thread-list/remote-thread-state.js +77 -1
  138. package/dist/runtimes/remote-thread-list/remote-thread-state.js.map +1 -1
  139. package/dist/runtimes/tool-invocations/ToolInvocationTracker.d.ts.map +1 -1
  140. package/dist/runtimes/tool-invocations/ToolInvocationTracker.js +2 -0
  141. package/dist/runtimes/tool-invocations/ToolInvocationTracker.js.map +1 -1
  142. package/dist/store/clients/external-thread.d.ts.map +1 -1
  143. package/dist/store/clients/external-thread.js +74 -99
  144. package/dist/store/clients/external-thread.js.map +1 -1
  145. package/dist/store/clients/single-thread-list.d.ts.map +1 -1
  146. package/dist/store/clients/single-thread-list.js +1 -1
  147. package/dist/store/clients/single-thread-list.js.map +1 -1
  148. package/dist/store/clients/suggestions.d.ts.map +1 -1
  149. package/dist/store/clients/suggestions.js +16 -7
  150. package/dist/store/clients/suggestions.js.map +1 -1
  151. package/dist/store/index.d.ts +4 -2
  152. package/dist/store/scope-registration.d.ts +1 -1
  153. package/dist/store/scopes/composer.d.ts +2 -1
  154. package/dist/store/scopes/composer.d.ts.map +1 -1
  155. package/dist/store/scopes/message.d.ts +1 -1
  156. package/dist/store/scopes/queue-item.d.ts +2 -9
  157. package/dist/store/scopes/queue-item.d.ts.map +1 -1
  158. package/dist/store/scopes/queue-item.js +0 -6
  159. package/dist/types/message.d.ts +7 -3
  160. package/dist/types/message.d.ts.map +1 -1
  161. package/dist/types/message.js.map +1 -1
  162. package/dist/utils/data-url.d.ts +14 -1
  163. package/dist/utils/data-url.d.ts.map +1 -1
  164. package/dist/utils/data-url.js +13 -1
  165. package/dist/utils/data-url.js.map +1 -1
  166. package/dist/utils/invoke-user-callback.d.ts +5 -0
  167. package/dist/utils/invoke-user-callback.d.ts.map +1 -0
  168. package/dist/utils/invoke-user-callback.js +19 -0
  169. package/dist/utils/invoke-user-callback.js.map +1 -0
  170. package/dist/utils/normalizePartStatus.js.map +1 -1
  171. package/package.json +10 -10
  172. package/src/internal.ts +12 -0
  173. package/src/model-context/frame/host.test.ts +91 -7
  174. package/src/model-context/frame/host.ts +7 -2
  175. package/src/model-context/frame/provider.test.ts +267 -12
  176. package/src/model-context/frame/provider.ts +113 -31
  177. package/src/model-context/interactable-composer-metadata.ts +1 -1
  178. package/src/model-context/registry.test.ts +44 -0
  179. package/src/model-context/registry.ts +13 -35
  180. package/src/react/client/InMemoryThreadList.test.tsx +49 -0
  181. package/src/react/client/InMemoryThreadList.ts +7 -1
  182. package/src/react/client/Interactables.ts +19 -178
  183. package/src/react/client/RemoteThreadList.test.ts +96 -0
  184. package/src/react/client/RemoteThreadList.ts +27 -59
  185. package/src/react/interactables-legacy/Interactables.ts +20 -177
  186. package/src/react/interactables-shared/useInteractablePersistenceQueue.test.tsx +161 -0
  187. package/src/react/interactables-shared/useInteractablePersistenceQueue.ts +206 -0
  188. package/src/react/runtimes/RemoteThreadListThreadListRuntimeCore.tsx +26 -56
  189. package/src/react/runtimes/assistant-transport/runManager.ts +4 -17
  190. package/src/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.test.tsx +92 -0
  191. package/src/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.ts +40 -141
  192. package/src/react/runtimes/cloud/createCloudThreadListAdapterCreateFallback.test.ts +37 -0
  193. package/src/react/runtimes/cloud/createCloudThreadListAdapterCreateFallback.ts +18 -0
  194. package/src/react/runtimes/external-message-converter.test.ts +0 -14
  195. package/src/react/runtimes/external-message-converter.test.tsx +77 -0
  196. package/src/react/runtimes/external-message-converter.ts +58 -481
  197. package/src/runtime/api/composer-runtime.ts +1 -1
  198. package/src/runtime/api/message-runtime.test.ts +28 -1
  199. package/src/runtime/base/base-composer-runtime-core.ts +20 -40
  200. package/src/runtime/base/base-thread-runtime-core.test.ts +16 -0
  201. package/src/runtime/base/base-thread-runtime-core.ts +6 -11
  202. package/src/runtime/base/default-thread-composer-runtime-core.ts +1 -4
  203. package/src/runtime/interfaces/composer-runtime-core.ts +1 -1
  204. package/src/runtime/interfaces/thread-runtime-core.ts +1 -1
  205. package/src/runtime/internal.ts +5 -0
  206. package/src/runtime/queue/external-thread-queue-adapter.ts +1 -1
  207. package/src/runtime/queue/message-queue.ts +1 -4
  208. package/src/runtime/queue/queue-item.ts +10 -0
  209. package/src/runtime/utils/abortable-thread-load.test.ts +87 -0
  210. package/src/runtime/utils/abortable-thread-load.ts +53 -0
  211. package/src/runtime/utils/attachment-add-operations.ts +59 -0
  212. package/src/runtime/utils/auto-status.ts +33 -0
  213. package/src/runtime/utils/external-message-conversion.test.ts +113 -0
  214. package/src/runtime/utils/external-message-conversion.ts +494 -0
  215. package/src/runtime/utils/external-store-message.ts +2 -0
  216. package/src/runtime/utils/message-repository-session.test.ts +195 -0
  217. package/src/runtime/utils/message-repository-session.ts +176 -0
  218. package/src/runtime/utils/message-repository.ts +7 -4
  219. package/src/runtime/utils/pending-tool-calls.test.ts +57 -0
  220. package/src/runtime/utils/pending-tool-calls.ts +35 -0
  221. package/src/runtime/utils/thread-message-like.ts +2 -0
  222. package/src/runtimes/external-store/external-store-thread-list-runtime-core.ts +6 -14
  223. package/src/runtimes/external-store/external-store-thread-runtime-core.ts +175 -28
  224. package/src/runtimes/local/local-thread-runtime-core.test.ts +172 -1
  225. package/src/runtimes/local/local-thread-runtime-core.ts +48 -3
  226. package/src/runtimes/remote-thread-list/remote-thread-state.test.ts +37 -0
  227. package/src/runtimes/remote-thread-list/remote-thread-state.ts +123 -0
  228. package/src/runtimes/tool-invocations/EDGE_CASES.md +17 -0
  229. package/src/runtimes/tool-invocations/ToolInvocationTracker.test.ts +140 -0
  230. package/src/runtimes/tool-invocations/ToolInvocationTracker.ts +3 -0
  231. package/src/store/clients/external-thread.ts +16 -61
  232. package/src/store/clients/single-thread-list.ts +4 -1
  233. package/src/store/clients/suggestions.test.ts +31 -0
  234. package/src/store/clients/suggestions.ts +18 -19
  235. package/src/store/scopes/message.ts +1 -1
  236. package/src/store/scopes/queue-item.ts +2 -9
  237. package/src/tests/MessageRepository.test.ts +77 -0
  238. package/src/tests/RemoteThreadListThreadListRuntimeCore-load-race.test.ts +194 -0
  239. package/src/tests/RemoteThreadListThreadListRuntimeCore-title-race.test.ts +158 -0
  240. package/src/tests/external-store-thread-runtime-core-adapter.test.ts +164 -0
  241. package/src/tests/external-store-thread-runtime-core.test.ts +642 -0
  242. package/src/tests/external-thread-attachments.test.tsx +173 -0
  243. package/src/tests/single-thread-list-item.test.tsx +47 -0
  244. package/src/tests/thread-message-like.test.ts +39 -1
  245. package/src/types/message.ts +8 -3
  246. package/src/utils/data-url.test.ts +52 -1
  247. package/src/utils/data-url.ts +21 -0
  248. package/src/utils/invoke-user-callback.test.ts +82 -0
  249. package/src/utils/invoke-user-callback.ts +31 -0
  250. package/src/utils/normalizePartStatus.ts +1 -1
  251. package/dist/store/scopes/queue-item.js.map +0 -1
@@ -13,9 +13,13 @@ import { resolveToolApprovalResponse } from "./runtime/utils/resolveToolApproval
13
13
  import { CompositeContextProvider } from "./utils/composite-context-provider.js";
14
14
  import { stableStringifyToolArgs, trackToolArgsKeyOrder } from "./utils/json/stable-stringify-tool-args.js";
15
15
  import { isJSONValue, isRecord } from "./utils/json/is-json.js";
16
- import { dataUrlMediaType, httpUrlPattern, isParsableUrl, parseDataUrl } from "./utils/data-url.js";
16
+ import { FilePartSource, dataUrlMediaType, httpUrlPattern, isParsableUrl, parseDataUrl, resolveFilePartSource } from "./utils/data-url.js";
17
+ import { invokeUserCallback } from "./utils/invoke-user-callback.js";
17
18
  import { detectImageMediaType } from "./utils/image-media-type.js";
18
19
  import { resolveFileMediaType, resolveImageMediaType, toMediaWireUrl } from "./utils/wire-media.js";
20
+ import { createToolCallCancellationStub, scanPendingToolCalls } from "./runtime/utils/pending-tool-calls.js";
21
+ import { AbortableThreadLoadPurpose, createAbortableThreadLoad } from "./runtime/utils/abortable-thread-load.js";
22
+ import { createCloudThreadListAdapterCreateFallback } from "./react/runtimes/cloud/createCloudThreadListAdapterCreateFallback.js";
19
23
  import { ComposerRuntimeCoreBinding, EditComposerRuntimeCoreBinding, MessageStateBinding, ThreadComposerRuntimeCoreBinding } from "./runtime/api/bindings.js";
20
24
  import { BaseAssistantRuntimeCore } from "./runtime/base/base-assistant-runtime-core.js";
21
25
  import { BaseComposerRuntimeCore } from "./runtime/base/base-composer-runtime-core.js";
@@ -30,6 +34,7 @@ import { MessagePartRuntimeImpl } from "./runtime/api/message-part-runtime.js";
30
34
  import { MessageRuntimeImpl } from "./runtime/api/message-runtime.js";
31
35
  import { symbolInnerMessage } from "./runtime/utils/external-store-message.js";
32
36
  import { getAutoStatus, isAutoStatus } from "./runtime/utils/auto-status.js";
37
+ import { MessageRepositorySession, MessageRepositorySessionOptions, createMessageRepositorySession } from "./runtime/utils/message-repository-session.js";
33
38
  import "./runtime/internal.js";
34
39
  import { LocalRuntimeOptionsBase } from "./runtimes/local/local-runtime-options.js";
35
40
  import { LocalThreadRuntimeCore } from "./runtimes/local/local-thread-runtime-core.js";
@@ -48,4 +53,4 @@ import { RemoteThreadData, RemoteThreadState, THREAD_MAPPING_ID, createThreadMap
48
53
  import "./runtimes/internal.js";
49
54
  import { ThreadListItemRuntimeBinding, ThreadRuntimeCoreBinding, ThreadRuntimeImpl, getThreadState } from "./runtime/api/thread-runtime.js";
50
55
  import { AssistantRuntimeImpl } from "./runtime/api/assistant-runtime.js";
51
- export { AssistantRuntimeImpl, AttachmentRuntimeImpl, BaseAssistantRuntimeCore, BaseComposerRuntimeCore, BaseSubject, BaseSubscribable, BaseThreadRuntimeCore, type ComposerRuntimeCoreBinding, ComposerRuntimeImpl, CompositeContextProvider, type ConverterCallback, DefaultEditComposerRuntimeCore, DefaultThreadComposerRuntimeCore, EMPTY_THREAD_CORE, EditComposerAttachmentRuntimeImpl, type EditComposerRuntimeCoreBinding, EditComposerRuntimeImpl, type EventSubscribable, EventSubscriptionSubject, ExportedMessageRepository, type ExportedMessageRepositoryItem, ExternalStoreRuntimeCore, type ExternalStoreThreadFactory, ExternalStoreThreadListRuntimeCore, ExternalStoreThreadRuntimeCore, LazyMemoizeSubject, LocalRuntimeCore, type LocalRuntimeOptionsBase, type LocalThreadFactory, LocalThreadListRuntimeCore, LocalThreadRuntimeCore, MessageAttachmentRuntimeImpl, MessagePartRuntimeImpl, MessageRepository, MessageRuntimeImpl, type MessageStateBinding, type NestedSubscribable, NestedSubscriptionSubject, OptimisticState, ReadonlyThreadRuntimeCore, type RemoteThreadData, type RemoteThreadInitializeResponse, type RemoteThreadListOptions, type RemoteThreadState, SKIP_UPDATE, type SKIP_UPDATE as SKIP_UPDATE_TYPE, ShallowMemoizeSubject, type Subscribable, type SubscribableWithState, type THREAD_MAPPING_ID, ThreadComposerAttachmentRuntimeImpl, type ThreadComposerRuntimeCoreBinding, ThreadComposerRuntimeImpl, type ThreadListItemRuntimeBinding, ThreadListItemRuntimeImpl, type ThreadListItemStateBinding, type ThreadListRuntimeCoreBinding, ThreadListRuntimeImpl, ThreadMessageConverter, type ThreadRuntimeCoreBinding, ThreadRuntimeImpl, ToolInvocationTracker, consumeSuggestionResult, createThreadMappingId, dataUrlMediaType, detectImageMediaType, fileMatchesAccept, fromThreadMessageLike, generateErrorMessageId, generateId, getAutoStatus, getFileDataURL, getThreadData, getThreadMessageText, getThreadState, hasUpcomingMessage, httpUrlPattern, isAutoStatus, isCreateAttachment, isErrorMessageId, isJSONValue, isParsableUrl, isRecord, notifyEventListeners, parseDataUrl, resolveFileMediaType, resolveImageMediaType, resolveToolApprovalResponse, shouldContinue, stableStringifyToolArgs, symbolInnerMessage, toMediaWireUrl, toMessagePartStatus, trackToolArgsKeyOrder, updateStatusReducer };
56
+ export { type AbortableThreadLoadPurpose, AssistantRuntimeImpl, AttachmentRuntimeImpl, BaseAssistantRuntimeCore, BaseComposerRuntimeCore, BaseSubject, BaseSubscribable, BaseThreadRuntimeCore, type ComposerRuntimeCoreBinding, ComposerRuntimeImpl, CompositeContextProvider, type ConverterCallback, DefaultEditComposerRuntimeCore, DefaultThreadComposerRuntimeCore, EMPTY_THREAD_CORE, EditComposerAttachmentRuntimeImpl, type EditComposerRuntimeCoreBinding, EditComposerRuntimeImpl, type EventSubscribable, EventSubscriptionSubject, ExportedMessageRepository, type ExportedMessageRepositoryItem, ExternalStoreRuntimeCore, type ExternalStoreThreadFactory, ExternalStoreThreadListRuntimeCore, ExternalStoreThreadRuntimeCore, type FilePartSource, LazyMemoizeSubject, LocalRuntimeCore, type LocalRuntimeOptionsBase, type LocalThreadFactory, LocalThreadListRuntimeCore, LocalThreadRuntimeCore, MessageAttachmentRuntimeImpl, MessagePartRuntimeImpl, MessageRepository, type MessageRepositorySession, type MessageRepositorySessionOptions, MessageRuntimeImpl, type MessageStateBinding, type NestedSubscribable, NestedSubscriptionSubject, OptimisticState, ReadonlyThreadRuntimeCore, type RemoteThreadData, type RemoteThreadInitializeResponse, type RemoteThreadListOptions, type RemoteThreadState, SKIP_UPDATE, type SKIP_UPDATE as SKIP_UPDATE_TYPE, ShallowMemoizeSubject, type Subscribable, type SubscribableWithState, type THREAD_MAPPING_ID, ThreadComposerAttachmentRuntimeImpl, type ThreadComposerRuntimeCoreBinding, ThreadComposerRuntimeImpl, type ThreadListItemRuntimeBinding, ThreadListItemRuntimeImpl, type ThreadListItemStateBinding, type ThreadListRuntimeCoreBinding, ThreadListRuntimeImpl, ThreadMessageConverter, type ThreadRuntimeCoreBinding, ThreadRuntimeImpl, ToolInvocationTracker, consumeSuggestionResult, createAbortableThreadLoad, createCloudThreadListAdapterCreateFallback, createMessageRepositorySession, createThreadMappingId, createToolCallCancellationStub, dataUrlMediaType, detectImageMediaType, fileMatchesAccept, fromThreadMessageLike, generateErrorMessageId, generateId, getAutoStatus, getFileDataURL, getThreadData, getThreadMessageText, getThreadState, hasUpcomingMessage, httpUrlPattern, invokeUserCallback, isAutoStatus, isCreateAttachment, isErrorMessageId, isJSONValue, isParsableUrl, isRecord, notifyEventListeners, parseDataUrl, resolveFileMediaType, resolveFilePartSource, resolveImageMediaType, resolveToolApprovalResponse, scanPendingToolCalls, shouldContinue, stableStringifyToolArgs, symbolInnerMessage, toMediaWireUrl, toMessagePartStatus, trackToolArgsKeyOrder, updateStatusReducer };
package/dist/internal.js CHANGED
@@ -1,22 +1,26 @@
1
1
  import { isJSONValue, isRecord } from "./utils/json/is-json.js";
2
2
  import { notifyEventListeners } from "./utils/notify-event-listeners.js";
3
3
  import { BaseSubject, BaseSubscribable, EventSubscriptionSubject, LazyMemoizeSubject, NestedSubscriptionSubject, SKIP_UPDATE, ShallowMemoizeSubject } from "./subscribable/subscribable.js";
4
+ import { CompositeContextProvider } from "./utils/composite-context-provider.js";
4
5
  import { generateErrorMessageId, generateId, isErrorMessageId } from "./utils/id.js";
5
6
  import { fileMatchesAccept, getFileDataURL } from "./adapters/attachment.js";
6
7
  import { getThreadMessageText } from "./utils/text.js";
7
8
  import { consumeSuggestionResult } from "./adapters/suggestion.js";
8
- import { dataUrlMediaType, httpUrlPattern, isParsableUrl, parseDataUrl } from "./utils/data-url.js";
9
+ import { dataUrlMediaType, httpUrlPattern, isParsableUrl, parseDataUrl, resolveFilePartSource } from "./utils/data-url.js";
9
10
  import { fromThreadMessageLike } from "./runtime/utils/thread-message-like.js";
10
11
  import { symbolInnerMessage } from "./runtime/utils/external-store-message.js";
11
12
  import { getAutoStatus, isAutoStatus } from "./runtime/utils/auto-status.js";
12
13
  import { ExportedMessageRepository, MessageRepository } from "./runtime/utils/message-repository.js";
13
14
  import { toMessagePartStatus } from "./utils/normalizePartStatus.js";
14
15
  import { resolveToolApprovalResponse } from "./runtime/utils/resolveToolApprovalResponse.js";
15
- import { CompositeContextProvider } from "./utils/composite-context-provider.js";
16
16
  import { isCreateAttachment } from "./types/attachment.js";
17
17
  import { stableStringifyToolArgs, trackToolArgsKeyOrder } from "./utils/json/stable-stringify-tool-args.js";
18
+ import { invokeUserCallback } from "./utils/invoke-user-callback.js";
18
19
  import { detectImageMediaType } from "./utils/image-media-type.js";
19
20
  import { resolveFileMediaType, resolveImageMediaType, toMediaWireUrl } from "./utils/wire-media.js";
21
+ import { createToolCallCancellationStub, scanPendingToolCalls } from "./runtime/utils/pending-tool-calls.js";
22
+ import { createAbortableThreadLoad } from "./runtime/utils/abortable-thread-load.js";
23
+ import { createCloudThreadListAdapterCreateFallback } from "./react/runtimes/cloud/createCloudThreadListAdapterCreateFallback.js";
20
24
  import { BaseAssistantRuntimeCore } from "./runtime/base/base-assistant-runtime-core.js";
21
25
  import { AttachmentRuntimeImpl, EditComposerAttachmentRuntimeImpl, MessageAttachmentRuntimeImpl, ThreadComposerAttachmentRuntimeImpl } from "./runtime/api/attachment-runtime.js";
22
26
  import { ComposerRuntimeImpl, EditComposerRuntimeImpl, ThreadComposerRuntimeImpl } from "./runtime/api/composer-runtime.js";
@@ -30,6 +34,7 @@ import { BaseThreadRuntimeCore } from "./runtime/base/base-thread-runtime-core.j
30
34
  import { ThreadListItemRuntimeImpl } from "./runtime/api/thread-list-item-runtime.js";
31
35
  import { ThreadListRuntimeImpl } from "./runtime/api/thread-list-runtime.js";
32
36
  import { AssistantRuntimeImpl } from "./runtime/api/assistant-runtime.js";
37
+ import { createMessageRepositorySession } from "./runtime/utils/message-repository-session.js";
33
38
  import { shouldContinue } from "./runtimes/local/should-continue.js";
34
39
  import { LocalThreadRuntimeCore } from "./runtimes/local/local-thread-runtime-core.js";
35
40
  import { LocalThreadListRuntimeCore } from "./runtimes/local/local-thread-list-runtime-core.js";
@@ -43,4 +48,4 @@ import { ReadonlyThreadRuntimeCore } from "./runtimes/readonly/ReadonlyThreadRun
43
48
  import { OptimisticState } from "./runtimes/remote-thread-list/optimistic-state.js";
44
49
  import { EMPTY_THREAD_CORE } from "./runtimes/remote-thread-list/empty-thread-core.js";
45
50
  import { createThreadMappingId, getThreadData, updateStatusReducer } from "./runtimes/remote-thread-list/remote-thread-state.js";
46
- export { AssistantRuntimeImpl, AttachmentRuntimeImpl, BaseAssistantRuntimeCore, BaseComposerRuntimeCore, BaseSubject, BaseSubscribable, BaseThreadRuntimeCore, ComposerRuntimeImpl, CompositeContextProvider, DefaultEditComposerRuntimeCore, DefaultThreadComposerRuntimeCore, EMPTY_THREAD_CORE, EditComposerAttachmentRuntimeImpl, EditComposerRuntimeImpl, EventSubscriptionSubject, ExportedMessageRepository, ExternalStoreRuntimeCore, ExternalStoreThreadListRuntimeCore, ExternalStoreThreadRuntimeCore, LazyMemoizeSubject, LocalRuntimeCore, LocalThreadListRuntimeCore, LocalThreadRuntimeCore, MessageAttachmentRuntimeImpl, MessagePartRuntimeImpl, MessageRepository, MessageRuntimeImpl, NestedSubscriptionSubject, OptimisticState, ReadonlyThreadRuntimeCore, SKIP_UPDATE, ShallowMemoizeSubject, ThreadComposerAttachmentRuntimeImpl, ThreadComposerRuntimeImpl, ThreadListItemRuntimeImpl, ThreadListRuntimeImpl, ThreadMessageConverter, ThreadRuntimeImpl, ToolInvocationTracker, consumeSuggestionResult, createThreadMappingId, dataUrlMediaType, detectImageMediaType, fileMatchesAccept, fromThreadMessageLike, generateErrorMessageId, generateId, getAutoStatus, getFileDataURL, getThreadData, getThreadMessageText, getThreadState, hasUpcomingMessage, httpUrlPattern, isAutoStatus, isCreateAttachment, isErrorMessageId, isJSONValue, isParsableUrl, isRecord, notifyEventListeners, parseDataUrl, resolveFileMediaType, resolveImageMediaType, resolveToolApprovalResponse, shouldContinue, stableStringifyToolArgs, symbolInnerMessage, toMediaWireUrl, toMessagePartStatus, trackToolArgsKeyOrder, updateStatusReducer };
51
+ export { AssistantRuntimeImpl, AttachmentRuntimeImpl, BaseAssistantRuntimeCore, BaseComposerRuntimeCore, BaseSubject, BaseSubscribable, BaseThreadRuntimeCore, ComposerRuntimeImpl, CompositeContextProvider, DefaultEditComposerRuntimeCore, DefaultThreadComposerRuntimeCore, EMPTY_THREAD_CORE, EditComposerAttachmentRuntimeImpl, EditComposerRuntimeImpl, EventSubscriptionSubject, ExportedMessageRepository, ExternalStoreRuntimeCore, ExternalStoreThreadListRuntimeCore, ExternalStoreThreadRuntimeCore, LazyMemoizeSubject, LocalRuntimeCore, LocalThreadListRuntimeCore, LocalThreadRuntimeCore, MessageAttachmentRuntimeImpl, MessagePartRuntimeImpl, MessageRepository, MessageRuntimeImpl, NestedSubscriptionSubject, OptimisticState, ReadonlyThreadRuntimeCore, SKIP_UPDATE, ShallowMemoizeSubject, ThreadComposerAttachmentRuntimeImpl, ThreadComposerRuntimeImpl, ThreadListItemRuntimeImpl, ThreadListRuntimeImpl, ThreadMessageConverter, ThreadRuntimeImpl, ToolInvocationTracker, consumeSuggestionResult, createAbortableThreadLoad, createCloudThreadListAdapterCreateFallback, createMessageRepositorySession, createThreadMappingId, createToolCallCancellationStub, dataUrlMediaType, detectImageMediaType, fileMatchesAccept, fromThreadMessageLike, generateErrorMessageId, generateId, getAutoStatus, getFileDataURL, getThreadData, getThreadMessageText, getThreadState, hasUpcomingMessage, httpUrlPattern, invokeUserCallback, isAutoStatus, isCreateAttachment, isErrorMessageId, isJSONValue, isParsableUrl, isRecord, notifyEventListeners, parseDataUrl, resolveFileMediaType, resolveFilePartSource, resolveImageMediaType, resolveToolApprovalResponse, scanPendingToolCalls, shouldContinue, stableStringifyToolArgs, symbolInnerMessage, toMediaWireUrl, toMessagePartStatus, trackToolArgsKeyOrder, updateStatusReducer };
@@ -1 +1 @@
1
- {"version":3,"file":"host.d.ts","names":[],"sources":["../../../src/model-context/frame/host.ts"],"mappings":";;;cAmDa,8BAA8B;UACjC;UACA;UACA;UAOA;UACA;UACA;EAEI,YAAA,cAAc,QAAQ;UAU1B;UA6BA;UAoBA;UAkBA;UAyDA;UAUA;UAYA;EAIR,mBAAmB;EAInB,UAAU,uBAAuB;EAKjC"}
1
+ {"version":3,"file":"host.d.ts","names":[],"sources":["../../../src/model-context/frame/host.ts"],"mappings":";;;cAqDa,8BAA8B;UACjC;UACA;UACA;UAOA;UACA;UACA;EAGN,YAAA,cAAc,QACd;UAWM;UA6BA;UAoBA;UAkBA;UAyDA;UAUA;UAYA;EAIR,mBAAmB;EAInB,UAAU,uBAAuB;EAKjC"}
@@ -2,6 +2,7 @@ import { notifySubscribers } from "../../subscribable/subscribable.js";
2
2
  import { generateId } from "../../utils/id.js";
3
3
  import { FRAME_MESSAGE_CHANNEL } from "./types.js";
4
4
  //#region src/model-context/frame/host.ts
5
+ const getDefaultTargetOrigin = () => window.location.origin;
5
6
  /**
6
7
  * Deserializes tools from JSON Schema format back to Tool objects
7
8
  */
@@ -31,7 +32,7 @@ var AssistantFrameHost = class {
31
32
  _iframeWindow;
32
33
  _targetOrigin;
33
34
  _disposed = false;
34
- constructor(iframeWindow, targetOrigin = "*") {
35
+ constructor(iframeWindow, targetOrigin = getDefaultTargetOrigin()) {
35
36
  this._iframeWindow = iframeWindow;
36
37
  this._targetOrigin = targetOrigin;
37
38
  this.handleMessage = this.handleMessage.bind(this);
@@ -50,7 +51,7 @@ var AssistantFrameHost = class {
50
51
  case "tool-result": {
51
52
  const pending = this._pendingRequests.get(message.id);
52
53
  if (pending) {
53
- if (message.error) pending.reject(new Error(message.error));
54
+ if (typeof message.error === "string") pending.reject(new Error(message.error));
54
55
  else pending.resolve(message.result);
55
56
  this._pendingRequests.delete(message.id);
56
57
  }
@@ -1 +1 @@
1
- {"version":3,"file":"host.js","names":["ModelContextProvider","ModelContext","Unsubscribe","Tool","notifySubscribers","notifyStateSubscribers","generateId","FrameMessage","FRAME_MESSAGE_CHANNEL","SerializedModelContext","SerializedTool","deserializeTool","serializedTool","parameters","description","disabled","undefined","type","deserializeModelContext","serialized","system","tools","Object","fromEntries","entries","map","name","tool","getAbortReason","signal","AbortSignal","reason","error","Error","AssistantFrameHost","_context","_subscribers","Set","_pendingRequests","Map","resolve","value","reject","_iframeWindow","Window","_targetOrigin","_disposed","constructor","iframeWindow","targetOrigin","handleMessage","bind","window","addEventListener","requestContext","event","MessageEvent","origin","source","data","channel","message","updateContext","context","pending","get","id","result","delete","serializedContext","execute","args","abortSignal","callTool","toolName","Promise","sendRequest","T","timeout","timeoutMessage","aborted","timeoutId","ReturnType","setTimeout","onAbort","cancelToolCall","cleanup","clearTimeout","removeEventListener","set","once","postMessage","getModelContext","subscribe","callback","add","dispose","clear"],"sources":["../../../src/model-context/frame/host.ts"],"sourcesContent":["import type { ModelContextProvider, ModelContext } from \"../types\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { Tool } from \"assistant-stream\";\nimport { notifySubscribers as notifyStateSubscribers } from \"../../subscribable/subscribable\";\nimport { generateId } from \"../../utils/id\";\nimport {\n type FrameMessage,\n FRAME_MESSAGE_CHANNEL,\n type SerializedModelContext,\n type SerializedTool,\n} from \"./types\";\n\n/**\n * Deserializes tools from JSON Schema format back to Tool objects\n */\nconst deserializeTool = (serializedTool: SerializedTool): Tool<any, any> =>\n ({\n parameters: serializedTool.parameters,\n ...(serializedTool.description && {\n description: serializedTool.description,\n }),\n ...(serializedTool.disabled !== undefined && {\n disabled: serializedTool.disabled,\n }),\n ...(serializedTool.type && { type: serializedTool.type }),\n }) as Tool<any, any>;\n\n/**\n * Deserializes a ModelContext from transmission format\n */\nconst deserializeModelContext = (\n serialized: SerializedModelContext,\n): ModelContext => ({\n ...(serialized.system !== undefined && { system: serialized.system }),\n ...(serialized.tools && {\n tools: Object.fromEntries(\n Object.entries(serialized.tools).map(([name, tool]) => [\n name,\n deserializeTool(tool),\n ]),\n ),\n }),\n});\n\nconst getAbortReason = (signal: AbortSignal): unknown => {\n if (signal.reason !== undefined) return signal.reason;\n const error = new Error(\"Tool call was aborted\");\n error.name = \"AbortError\";\n return error;\n};\n\nexport class AssistantFrameHost implements ModelContextProvider {\n private _context: ModelContext = {};\n private _subscribers = new Set<() => void>();\n private _pendingRequests = new Map<\n string,\n {\n resolve: (value: any) => void;\n reject: (error: any) => void;\n }\n >();\n private _iframeWindow: Window;\n private _targetOrigin: string;\n private _disposed = false;\n\n constructor(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, context: { abortSignal: AbortSignal }) =>\n this.callTool(name, args, context.abortSignal),\n } as Tool<any, any>,\n ]),\n ),\n };\n this.notifySubscribers();\n }\n\n private callTool(\n toolName: string,\n args: any,\n abortSignal: AbortSignal,\n ): Promise<any> {\n return this.sendRequest(\n {\n type: \"tool-call\",\n id: `tool-${generateId()}`,\n toolName,\n args,\n },\n 30000,\n `Tool call \"${toolName}\" timed out`,\n abortSignal,\n );\n }\n\n private sendRequest<T extends FrameMessage & { id: string }>(\n message: T,\n timeout = 30000,\n timeoutMessage = \"Request timed out\",\n abortSignal?: AbortSignal,\n ): Promise<any> {\n if (this._disposed) {\n return Promise.reject(new Error(\"AssistantFrameHost has been disposed\"));\n }\n if (abortSignal?.aborted) {\n return Promise.reject(getAbortReason(abortSignal));\n }\n\n return new Promise((resolve, reject) => {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n const onAbort = () => {\n if (!abortSignal) return;\n const pending = this._pendingRequests.get(message.id);\n if (pending) {\n this.cancelToolCall(message.id);\n pending.reject(getAbortReason(abortSignal));\n this._pendingRequests.delete(message.id);\n }\n };\n const cleanup = () => {\n if (timeoutId !== undefined) clearTimeout(timeoutId);\n abortSignal?.removeEventListener(\"abort\", onAbort);\n };\n\n this._pendingRequests.set(message.id, {\n resolve: (value: any) => {\n cleanup();\n resolve(value);\n },\n reject: (error: any) => {\n cleanup();\n reject(error);\n },\n });\n\n timeoutId = setTimeout(() => {\n const pending = this._pendingRequests.get(message.id);\n if (pending) {\n this.cancelToolCall(message.id);\n pending.reject(new Error(timeoutMessage));\n this._pendingRequests.delete(message.id);\n }\n }, timeout);\n abortSignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n this._iframeWindow.postMessage(\n { channel: FRAME_MESSAGE_CHANNEL, message },\n this._targetOrigin,\n );\n });\n }\n\n private cancelToolCall(id: string) {\n this._iframeWindow.postMessage(\n {\n channel: FRAME_MESSAGE_CHANNEL,\n message: { type: \"tool-cancel\", id } satisfies FrameMessage,\n },\n this._targetOrigin,\n );\n }\n\n private requestContext() {\n this._iframeWindow.postMessage(\n {\n channel: FRAME_MESSAGE_CHANNEL,\n message: {\n type: \"model-context-request\",\n } as FrameMessage,\n },\n this._targetOrigin,\n );\n }\n\n private notifySubscribers() {\n notifyStateSubscribers(this._subscribers);\n }\n\n getModelContext(): ModelContext {\n return this._context;\n }\n\n subscribe(callback: () => void): Unsubscribe {\n this._subscribers.add(callback);\n return () => this._subscribers.delete(callback);\n }\n\n dispose() {\n this._disposed = true;\n window.removeEventListener(\"message\", this.handleMessage);\n this._subscribers.clear();\n const error = new Error(\"AssistantFrameHost has been disposed\");\n for (const [id, pending] of this._pendingRequests) {\n this.cancelToolCall(id);\n pending.reject(error);\n }\n this._pendingRequests.clear();\n }\n}\n"],"mappings":";;;;;;;AAeA,MAAMW,mBAAmBC,oBACtB;CACCC,YAAYD,eAAeC;CAC3B,GAAID,eAAeE,eAAe,EAChCA,aAAaF,eAAeE,YAC9B;CACA,GAAIF,eAAeG,aAAaC,KAAAA,KAAa,EAC3CD,UAAUH,eAAeG,SAC3B;CACA,GAAIH,eAAeK,QAAQ,EAAEA,MAAML,eAAeK,KAAK;AACzD;;;;AAKF,MAAMC,2BACJC,gBACkB;CAClB,GAAIA,WAAWC,WAAWJ,KAAAA,KAAa,EAAEI,QAAQD,WAAWC,OAAO;CACnE,GAAID,WAAWE,SAAS,EACtBA,OAAOC,OAAOC,YACZD,OAAOE,QAAQL,WAAWE,KAAK,CAAC,CAACI,KAAK,CAACC,MAAMC,UAAU,CACrDD,MACAf,gBAAgBgB,IAAI,CAAC,CACtB,CACH,EACF;AACF;AAEA,MAAMC,kBAAkBC,WAAiC;CACvD,IAAIA,OAAOE,WAAWf,KAAAA,GAAW,OAAOa,OAAOE;CAC/C,MAAMC,wBAAQ,IAAIC,MAAM,uBAAuB;CAC/CD,MAAMN,OAAO;CACb,OAAOM;AACT;AAEA,IAAaE,qBAAb,MAAgE;CAC9D,WAAiC,CAAC;CAClC,+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+B,SAAS,EAAEM,MAAM,KAAK,CAAC;GAE9D,KAAK/C,cAAcgD,YACjB;IAAE/B,SAASpD;IAAuBqD;GAAQ,GAC1C,KAAKhB,aACP;EACF,CAAC;CACH;CAEA,eAAuBqB,IAAY;EACjC,KAAKvB,cAAcgD,YACjB;GACE/B,SAASpD;GACTqD,SAAS;IAAE5C,MAAM;IAAeiD;GAAG;EACrC,GACA,KAAKrB,aACP;CACF;CAEA,iBAAyB;EACvB,KAAKF,cAAcgD,YACjB;GACE/B,SAASpD;GACTqD,SAAS,EACP5C,MAAM,wBACR;EACF,GACA,KAAK4B,aACP;CACF;CAEA,oBAA4B;EAC1BxC,kBAAuB,KAAK+B,YAAY;CAC1C;CAEAwD,kBAAgC;EAC9B,OAAO,KAAKzD;CACd;CAEA0D,UAAUC,UAAmC;EAC3C,KAAK1D,aAAa2D,IAAID,QAAQ;EAC9B,aAAa,KAAK1D,aAAagC,OAAO0B,QAAQ;CAChD;CAEAE,UAAU;EACR,KAAKlD,YAAY;EACjBM,OAAOoC,oBAAoB,WAAW,KAAKtC,aAAa;EACxD,KAAKd,aAAa6D,MAAM;EACxB,MAAMjE,wBAAQ,IAAIC,MAAM,sCAAsC;EAC9D,KAAK,MAAM,CAACiC,IAAIF,YAAY,KAAK1B,kBAAkB;GACjD,KAAK+C,eAAenB,EAAE;GACtBF,QAAQtB,OAAOV,KAAK;EACtB;EACA,KAAKM,iBAAiB2D,MAAM;CAC9B;AACF"}
1
+ {"version":3,"file":"host.js","names":["ModelContextProvider","ModelContext","Unsubscribe","Tool","notifySubscribers","notifyStateSubscribers","generateId","FrameMessage","FRAME_MESSAGE_CHANNEL","SerializedModelContext","SerializedTool","getDefaultTargetOrigin","window","location","origin","deserializeTool","serializedTool","parameters","description","disabled","undefined","type","deserializeModelContext","serialized","system","tools","Object","fromEntries","entries","map","name","tool","getAbortReason","signal","AbortSignal","reason","error","Error","AssistantFrameHost","_context","_subscribers","Set","_pendingRequests","Map","resolve","value","reject","_iframeWindow","Window","_targetOrigin","_disposed","constructor","iframeWindow","targetOrigin","handleMessage","bind","addEventListener","requestContext","event","MessageEvent","source","data","channel","message","updateContext","context","pending","get","id","result","delete","serializedContext","execute","args","abortSignal","callTool","toolName","Promise","sendRequest","T","timeout","timeoutMessage","aborted","timeoutId","ReturnType","setTimeout","onAbort","cancelToolCall","cleanup","clearTimeout","removeEventListener","set","once","postMessage","getModelContext","subscribe","callback","add","dispose","clear"],"sources":["../../../src/model-context/frame/host.ts"],"sourcesContent":["import type { ModelContextProvider, ModelContext } from \"../types\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { Tool } from \"assistant-stream\";\nimport { notifySubscribers as notifyStateSubscribers } from \"../../subscribable/subscribable\";\nimport { generateId } from \"../../utils/id\";\nimport {\n type FrameMessage,\n FRAME_MESSAGE_CHANNEL,\n type SerializedModelContext,\n type SerializedTool,\n} from \"./types\";\n\nconst getDefaultTargetOrigin = () => window.location.origin;\n\n/**\n * Deserializes tools from JSON Schema format back to Tool objects\n */\nconst deserializeTool = (serializedTool: SerializedTool): Tool<any, any> =>\n ({\n parameters: serializedTool.parameters,\n ...(serializedTool.description && {\n description: serializedTool.description,\n }),\n ...(serializedTool.disabled !== undefined && {\n disabled: serializedTool.disabled,\n }),\n ...(serializedTool.type && { type: serializedTool.type }),\n }) as Tool<any, any>;\n\n/**\n * Deserializes a ModelContext from transmission format\n */\nconst deserializeModelContext = (\n serialized: SerializedModelContext,\n): ModelContext => ({\n ...(serialized.system !== undefined && { system: serialized.system }),\n ...(serialized.tools && {\n tools: Object.fromEntries(\n Object.entries(serialized.tools).map(([name, tool]) => [\n name,\n deserializeTool(tool),\n ]),\n ),\n }),\n});\n\nconst getAbortReason = (signal: AbortSignal): unknown => {\n if (signal.reason !== undefined) return signal.reason;\n const error = new Error(\"Tool call was aborted\");\n error.name = \"AbortError\";\n return error;\n};\n\nexport class AssistantFrameHost implements ModelContextProvider {\n private _context: ModelContext = {};\n private _subscribers = new Set<() => void>();\n private _pendingRequests = new Map<\n string,\n {\n resolve: (value: any) => void;\n reject: (error: any) => void;\n }\n >();\n private _iframeWindow: Window;\n private _targetOrigin: string;\n private _disposed = false;\n\n constructor(\n iframeWindow: Window,\n targetOrigin: string = getDefaultTargetOrigin(),\n ) {\n this._iframeWindow = iframeWindow;\n this._targetOrigin = targetOrigin;\n\n this.handleMessage = this.handleMessage.bind(this);\n window.addEventListener(\"message\", this.handleMessage);\n\n this.requestContext();\n }\n\n private handleMessage(event: MessageEvent) {\n if (this._targetOrigin !== \"*\" && event.origin !== this._targetOrigin)\n return;\n if (event.source !== this._iframeWindow) return;\n if (event.data?.channel !== FRAME_MESSAGE_CHANNEL) return;\n\n const message = event.data.message as FrameMessage;\n\n switch (message.type) {\n case \"model-context-update\": {\n this.updateContext(message.context);\n break;\n }\n\n case \"tool-result\": {\n const pending = this._pendingRequests.get(message.id);\n if (pending) {\n if (typeof message.error === \"string\") {\n pending.reject(new Error(message.error));\n } else {\n pending.resolve(message.result);\n }\n this._pendingRequests.delete(message.id);\n }\n break;\n }\n }\n }\n\n private updateContext(serializedContext: SerializedModelContext) {\n const context = deserializeModelContext(serializedContext);\n this._context = {\n ...context,\n tools:\n context.tools &&\n Object.fromEntries(\n Object.entries(context.tools).map(([name, tool]) => [\n name,\n {\n ...tool,\n execute: (args: any, context: { abortSignal: AbortSignal }) =>\n this.callTool(name, args, context.abortSignal),\n } as Tool<any, any>,\n ]),\n ),\n };\n this.notifySubscribers();\n }\n\n private callTool(\n toolName: string,\n args: any,\n abortSignal: AbortSignal,\n ): Promise<any> {\n return this.sendRequest(\n {\n type: \"tool-call\",\n id: `tool-${generateId()}`,\n toolName,\n args,\n },\n 30000,\n `Tool call \"${toolName}\" timed out`,\n abortSignal,\n );\n }\n\n private sendRequest<T extends FrameMessage & { id: string }>(\n message: T,\n timeout = 30000,\n timeoutMessage = \"Request timed out\",\n abortSignal?: AbortSignal,\n ): Promise<any> {\n if (this._disposed) {\n return Promise.reject(new Error(\"AssistantFrameHost has been disposed\"));\n }\n if (abortSignal?.aborted) {\n return Promise.reject(getAbortReason(abortSignal));\n }\n\n return new Promise((resolve, reject) => {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n const onAbort = () => {\n if (!abortSignal) return;\n const pending = this._pendingRequests.get(message.id);\n if (pending) {\n this.cancelToolCall(message.id);\n pending.reject(getAbortReason(abortSignal));\n this._pendingRequests.delete(message.id);\n }\n };\n const cleanup = () => {\n if (timeoutId !== undefined) clearTimeout(timeoutId);\n abortSignal?.removeEventListener(\"abort\", onAbort);\n };\n\n this._pendingRequests.set(message.id, {\n resolve: (value: any) => {\n cleanup();\n resolve(value);\n },\n reject: (error: any) => {\n cleanup();\n reject(error);\n },\n });\n\n timeoutId = setTimeout(() => {\n const pending = this._pendingRequests.get(message.id);\n if (pending) {\n this.cancelToolCall(message.id);\n pending.reject(new Error(timeoutMessage));\n this._pendingRequests.delete(message.id);\n }\n }, timeout);\n abortSignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n this._iframeWindow.postMessage(\n { channel: FRAME_MESSAGE_CHANNEL, message },\n this._targetOrigin,\n );\n });\n }\n\n private cancelToolCall(id: string) {\n this._iframeWindow.postMessage(\n {\n channel: FRAME_MESSAGE_CHANNEL,\n message: { type: \"tool-cancel\", id } satisfies FrameMessage,\n },\n this._targetOrigin,\n );\n }\n\n private requestContext() {\n this._iframeWindow.postMessage(\n {\n channel: FRAME_MESSAGE_CHANNEL,\n message: {\n type: \"model-context-request\",\n } as FrameMessage,\n },\n this._targetOrigin,\n );\n }\n\n private notifySubscribers() {\n notifyStateSubscribers(this._subscribers);\n }\n\n getModelContext(): ModelContext {\n return this._context;\n }\n\n subscribe(callback: () => void): Unsubscribe {\n this._subscribers.add(callback);\n return () => this._subscribers.delete(callback);\n }\n\n dispose() {\n this._disposed = true;\n window.removeEventListener(\"message\", this.handleMessage);\n this._subscribers.clear();\n const error = new Error(\"AssistantFrameHost has been disposed\");\n for (const [id, pending] of this._pendingRequests)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ACA,KAAK4B,aACP;CACF;CAEA,oBAA4B;EAC1B5C,kBAAuB,KAAKmC,YAAY;CAC1C;CAEAsD,kBAAgC;EAC9B,OAAO,KAAKvD;CACd;CAEAwD,UAAUC,UAAmC;EAC3C,KAAKxD,aAAayD,IAAID,QAAQ;EAC9B,aAAa,KAAKxD,aAAa8B,OAAO0B,QAAQ;CAChD;CAEAE,UAAU;EACR,KAAKhD,YAAY;EACjBtC,OAAO8E,oBAAoB,WAAW,KAAKpC,aAAa;EACxD,KAAKd,aAAa2D,MAAM;EACxB,MAAM/D,wBAAQ,IAAIC,MAAM,sCAAsC;EAC9D,KAAK,MAAM,CAAC+B,IAAIF,YAAY,KAAKxB,kBAAkB;GACjD,KAAK6C,eAAenB,EAAE;GACtBF,QAAQpB,OAAOV,KAAK;EACtB;EACA,KAAKM,iBAAiByD,MAAM;CAC9B;AACF"}
@@ -8,6 +8,7 @@ declare class AssistantFrameProvider {
8
8
  private _activeToolCalls;
9
9
  private _targetOrigin;
10
10
  private _strictRegistrations;
11
+ private _wildcardRegistrations;
11
12
  private constructor();
12
13
  private static getInstance;
13
14
  private reconcileTargetOrigin;
@@ -17,6 +18,7 @@ declare class AssistantFrameProvider {
17
18
  private sendMessage;
18
19
  private getModelContext;
19
20
  private broadcastUpdate;
21
+ private removeProvider;
20
22
  static addModelContextProvider(provider: ModelContextProvider, targetOrigin?: string): Unsubscribe;
21
23
  static dispose(): void;
22
24
  }
@@ -1 +1 @@
1
- {"version":3,"file":"provider.d.ts","names":[],"sources":["../../../src/model-context/frame/provider.ts"],"mappings":";;;cA+Ba;iBACI;UAEP;UACA;UAIA;UAIA;UACA;UAED;iBAQQ;UAWP;UAaA;UA0BM;UA2CN;UAOA;UAOA;UAkBA;SAcD,wBACL,UAAU,sBACV,wBACC;SA4BI"}
1
+ {"version":3,"file":"provider.d.ts","names":[],"sources":["../../../src/model-context/frame/provider.ts"],"mappings":";;;cAiCa;iBACI;UAEP;UACA;UACA;UAIA;UACA;UACA;UAED;iBAQQ;UAWP;UAsBA;UA0BM;UA2CN;UAOA;UAOA;UAkBA;UAcA;SAsBD,wBACL,UAAU,sBACV,wBACC;SA2DI"}
@@ -11,14 +11,16 @@ const serializeModelContext = (context) => ({
11
11
  ...context.system !== void 0 && { system: context.system },
12
12
  ...context.tools && { tools: Object.fromEntries(Object.entries(context.tools).map(([name, tool]) => [name, serializeTool(tool)])) }
13
13
  });
14
+ const getDefaultTargetOrigin = () => window.location.origin;
14
15
  var AssistantFrameProvider = class AssistantFrameProvider {
15
16
  static _instance = null;
16
- _providers = /* @__PURE__ */ new Set();
17
+ _providers = /* @__PURE__ */ new Map();
17
18
  _providerUnsubscribes = /* @__PURE__ */ new Map();
18
19
  _activeToolCalls = /* @__PURE__ */ new Map();
19
20
  _targetOrigin;
20
21
  _strictRegistrations = 0;
21
- constructor(targetOrigin = "*") {
22
+ _wildcardRegistrations = 0;
23
+ constructor(targetOrigin = getDefaultTargetOrigin()) {
22
24
  this._targetOrigin = targetOrigin;
23
25
  this.handleMessage = this.handleMessage.bind(this);
24
26
  window.addEventListener("message", this.handleMessage);
@@ -29,8 +31,13 @@ var AssistantFrameProvider = class AssistantFrameProvider {
29
31
  else AssistantFrameProvider._instance.reconcileTargetOrigin(targetOrigin);
30
32
  return AssistantFrameProvider._instance;
31
33
  }
32
- reconcileTargetOrigin(targetOrigin = "*") {
33
- if (targetOrigin === "*" || targetOrigin === this._targetOrigin) return;
34
+ reconcileTargetOrigin(targetOrigin = getDefaultTargetOrigin()) {
35
+ if (targetOrigin === this._targetOrigin) return;
36
+ if (this._providers.size === 0) {
37
+ this._targetOrigin = targetOrigin;
38
+ return;
39
+ }
40
+ if (targetOrigin === "*") return;
34
41
  if (this._targetOrigin === "*") {
35
42
  this._targetOrigin = targetOrigin;
36
43
  return;
@@ -83,7 +90,7 @@ var AssistantFrameProvider = class AssistantFrameProvider {
83
90
  this.sendMessage(event, {
84
91
  type: "tool-result",
85
92
  id: message.id,
86
- ...error ? { error } : { result }
93
+ ...error !== void 0 ? { error } : { result }
87
94
  });
88
95
  }
89
96
  cancelToolCall(id) {
@@ -99,7 +106,7 @@ var AssistantFrameProvider = class AssistantFrameProvider {
99
106
  }, { targetOrigin: event.origin });
100
107
  }
101
108
  getModelContext() {
102
- return Array.from(this._providers).map((p) => p.getModelContext()).reduce((merged, context) => ({
109
+ return Array.from(new Set(this._providers.values())).map((p) => p.getModelContext()).reduce((merged, context) => ({
103
110
  system: context.system ? merged.system ? `${merged.system}\n\n${context.system}` : context.system : merged.system,
104
111
  tools: {
105
112
  ...merged.tools || {},
@@ -119,45 +126,101 @@ var AssistantFrameProvider = class AssistantFrameProvider {
119
126
  }, this._targetOrigin);
120
127
  }
121
128
  }
129
+ removeProvider(id, origin) {
130
+ this._providers.delete(id);
131
+ const unsubscribe = this._providerUnsubscribes.get(id);
132
+ this._providerUnsubscribes.delete(id);
133
+ if (origin === "*") {
134
+ this._wildcardRegistrations -= 1;
135
+ if (this._wildcardRegistrations === 0 && this._strictRegistrations === 0) this._targetOrigin = getDefaultTargetOrigin();
136
+ } else {
137
+ this._strictRegistrations -= 1;
138
+ if (this._strictRegistrations === 0) this._targetOrigin = this._wildcardRegistrations > 0 ? "*" : getDefaultTargetOrigin();
139
+ }
140
+ return unsubscribe;
141
+ }
122
142
  static addModelContextProvider(provider, targetOrigin) {
123
- const origin = targetOrigin ?? "*";
143
+ const origin = targetOrigin ?? getDefaultTargetOrigin();
124
144
  const instance = AssistantFrameProvider.getInstance(origin);
125
- instance._providers.add(provider);
126
- if (origin !== "*") instance._strictRegistrations += 1;
127
- const unsubscribe = provider.subscribe?.(() => instance.broadcastUpdate());
128
- if (unsubscribe) instance._providerUnsubscribes.set(provider, unsubscribe);
129
- instance.broadcastUpdate();
145
+ const id = Symbol();
146
+ instance._providers.set(id, provider);
147
+ if (origin === "*") instance._wildcardRegistrations += 1;
148
+ else instance._strictRegistrations += 1;
149
+ try {
150
+ const unsubscribe = provider.subscribe?.(() => instance.broadcastUpdate());
151
+ if (unsubscribe) instance._providerUnsubscribes.set(id, unsubscribe);
152
+ instance.broadcastUpdate();
153
+ } catch (error) {
154
+ const unsubscribe = instance.removeProvider(id, origin);
155
+ try {
156
+ unsubscribe?.();
157
+ } catch (unsubscribeError) {
158
+ console.error(unsubscribeError);
159
+ }
160
+ try {
161
+ instance.broadcastUpdate();
162
+ } catch (broadcastError) {
163
+ console.error(broadcastError);
164
+ }
165
+ throw error;
166
+ }
130
167
  let released = false;
131
168
  return () => {
132
169
  if (released) return;
133
170
  released = true;
134
- instance._providers.delete(provider);
135
- instance._providerUnsubscribes.get(provider)?.();
136
- instance._providerUnsubscribes.delete(provider);
137
- if (origin !== "*") {
138
- instance._strictRegistrations -= 1;
139
- if (instance._strictRegistrations === 0) instance._targetOrigin = "*";
171
+ const unsubscribe = instance.removeProvider(id, origin);
172
+ let unsubscribeFailed = false;
173
+ let unsubscribeError;
174
+ try {
175
+ unsubscribe?.();
176
+ } catch (error) {
177
+ unsubscribeFailed = true;
178
+ unsubscribeError = error;
140
179
  }
141
- instance.broadcastUpdate();
180
+ try {
181
+ instance.broadcastUpdate();
182
+ } catch (error) {
183
+ if (!unsubscribeFailed) throw error;
184
+ console.error(error);
185
+ }
186
+ if (unsubscribeFailed) throw unsubscribeError;
142
187
  };
143
188
  }
144
189
  static dispose() {
145
190
  if (AssistantFrameProvider._instance) {
146
191
  const instance = AssistantFrameProvider._instance;
147
192
  window.removeEventListener("message", instance.handleMessage);
148
- instance._providerUnsubscribes.forEach((unsubscribe) => unsubscribe?.());
193
+ let cleanupFailed = false;
194
+ let cleanupError;
195
+ const runCleanup = (cleanup) => {
196
+ try {
197
+ cleanup();
198
+ } catch (error) {
199
+ if (cleanupFailed) console.error(error);
200
+ else {
201
+ cleanupFailed = true;
202
+ cleanupError = error;
203
+ }
204
+ }
205
+ };
206
+ instance._providerUnsubscribes.forEach((unsubscribe) => {
207
+ if (unsubscribe) runCleanup(unsubscribe);
208
+ });
149
209
  instance._providerUnsubscribes.clear();
150
210
  instance._providers.clear();
151
211
  instance._activeToolCalls.forEach(({ abortController, event }, id) => {
152
- abortController.abort();
153
- instance.sendMessage(event, {
154
- type: "tool-result",
155
- id,
156
- error: "AssistantFrameProvider has been disposed"
212
+ runCleanup(() => {
213
+ abortController.abort();
214
+ instance.sendMessage(event, {
215
+ type: "tool-result",
216
+ id,
217
+ error: "AssistantFrameProvider has been disposed"
218
+ });
157
219
  });
158
220
  });
159
221
  instance._activeToolCalls.clear();
160
222
  AssistantFrameProvider._instance = null;
223
+ if (cleanupFailed) throw cleanupError;
161
224
  }
162
225
  }
163
226
  };
@@ -1 +1 @@
1
- {"version":3,"file":"provider.js","names":["ModelContextProvider","ModelContext","Unsubscribe","Tool","toJSONSchema","FrameMessage","FRAME_MESSAGE_CHANNEL","SerializedModelContext","SerializedTool","serializeTool","tool","description","parameters","undefined","disabled","type","serializeModelContext","context","system","tools","Object","fromEntries","entries","map","name","AssistantFrameProvider","_instance","_providers","Set","_providerUnsubscribes","Map","_activeToolCalls","abortController","AbortController","event","MessageEvent","_targetOrigin","_strictRegistrations","constructor","targetOrigin","handleMessage","bind","window","addEventListener","setTimeout","broadcastUpdate","getInstance","reconcileTargetOrigin","Error","origin","source","parent","data","channel","message","sendMessage","getModelContext","handleToolCall","cancelToolCall","id","Extract","toolName","get","abort","activeCall","set","result","error","execute","args","toolCallId","abortSignal","signal","human","e","String","delete","postMessage","contexts","Array","from","p","reduce","merged","updateMessage","addModelContextProvider","provider","instance","add","unsubscribe","subscribe","released","dispose","removeEventListener","forEach","clear"],"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 _activeToolCalls = new Map<\n string,\n { abortController: AbortController; event: MessageEvent }\n >();\n private _targetOrigin: string;\n private _strictRegistrations = 0;\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 } else {\n AssistantFrameProvider._instance.reconcileTargetOrigin(targetOrigin);\n }\n return AssistantFrameProvider._instance;\n }\n\n private reconcileTargetOrigin(targetOrigin: string = \"*\") {\n if (targetOrigin === \"*\" || targetOrigin === this._targetOrigin) return;\n\n if (this._targetOrigin === \"*\") {\n this._targetOrigin = targetOrigin;\n return;\n }\n\n throw new Error(\n `AssistantFrameProvider cannot register conflicting target origins: \"${this._targetOrigin}\" and \"${targetOrigin}\"`,\n );\n }\n\n private handleMessage(event: MessageEvent) {\n if (this._targetOrigin !== \"*\" && event.origin !== this._targetOrigin)\n return;\n if (event.source !== window.parent) 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 case \"tool-cancel\":\n this.cancelToolCall(message.id);\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 const abortController = new AbortController();\n this._activeToolCalls.get(message.id)?.abortController.abort();\n const activeCall = { abortController, event };\n this._activeToolCalls.set(message.id, activeCall);\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: 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 if (this._activeToolCalls.get(message.id) !== activeCall) return;\n this._activeToolCalls.delete(message.id);\n\n this.sendMessage(event, {\n type: \"tool-result\",\n id: message.id,\n ...(error ? { error } : { result }),\n });\n }\n\n private cancelToolCall(id: string) {\n const activeCall = this._activeToolCalls.get(id);\n if (!activeCall) return;\n this._activeToolCalls.delete(id);\n activeCall.abortController.abort();\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 origin = targetOrigin ?? \"*\";\n const instance = AssistantFrameProvider.getInstance(origin);\n instance._providers.add(provider);\n if (origin !== \"*\") instance._strictRegistrations += 1;\n\n const unsubscribe = provider.subscribe?.(() => instance.broadcastUpdate());\n if (unsubscribe) {\n instance._providerUnsubscribes.set(provider, unsubscribe);\n }\n\n instance.broadcastUpdate();\n\n let released = false;\n return () => {\n if (released) return;\n released = true;\n instance._providers.delete(provider);\n instance._providerUnsubscribes.get(provider)?.();\n instance._providerUnsubscribes.delete(provider);\n if (origin !== \"*\") {\n instance._strictRegistrations -= 1;\n if (instance._strictRegistrations === 0) instance._targetOrigin = \"*\";\n }\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 instance._activeToolCalls.forEach(({ abortController, event }, id) => {\n abortController.abort();\n instance.sendMessage(event, {\n type: \"tool-result\",\n id,\n error: \"AssistantFrameProvider has been disposed\",\n });\n });\n instance._activeToolCalls.clear();\n\n AssistantFrameProvider._instance = null;\n }\n }\n}\n"],"mappings":";;;AAUA,MAAMS,iBAAiBC,UAA0C;CAC/D,GAAIA,KAAKC,eAAe,EAAEA,aAAaD,KAAKC,YAAY;CACxDC,YAAYF,KAAKE,aAAaR,aAAaM,KAAKE,UAAU,IAAIC,KAAAA;CAC9D,GAAIH,KAAKI,aAAaD,KAAAA,KAAa,EAAEC,UAAUJ,KAAKI,SAAS;CAC7D,GAAIJ,KAAKK,QAAQ,EAAEA,MAAML,KAAKK,KAAK;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EAEzB,IAAI8C,WAAW;EACf,aAAa;GACX,IAAIA,UAAU;GACdA,WAAW;GACXJ,SAAS5D,WAAWiD,OAAOU,QAAQ;GACnCC,SAAS1D,sBAAsBiC,IAAIwB,QAAQ,CAAC,GAAG;GAC/CC,SAAS1D,sBAAsB+C,OAAOU,QAAQ;GAC9C,IAAIrC,WAAW,KAAK;IAClBsC,SAASlD,wBAAwB;IACjC,IAAIkD,SAASlD,yBAAyB,GAAGkD,SAASnD,gBAAgB;GACpE;GACAmD,SAAS1C,gBAAgB;EAC3B;CACF;CAEA,OAAO+C,UAAU;EACf,IAAInE,uBAAuBC,WAAW;GACpC,MAAM6D,WAAW9D,uBAAuBC;GACxCgB,OAAOmD,oBAAoB,WAAWN,SAAS/C,aAAa;GAE5D+C,SAAS1D,sBAAsBiE,SAASL,gBAAgBA,cAAc,CAAC;GACvEF,SAAS1D,sBAAsBkE,MAAM;GACrCR,SAAS5D,WAAWoE,MAAM;GAC1BR,SAASxD,iBAAiB+D,SAAS,EAAE9D,iBAAiBE,SAASyB,OAAO;IACpE3B,gBAAgB+B,MAAM;IACtBwB,SAAShC,YAAYrB,OAAO;KAC1BnB,MAAM;KACN4C;KACAQ,OAAO;IACT,CAAC;GACH,CAAC;GACDoB,SAASxD,iBAAiBgE,MAAM;GAEhCtE,uBAAuBC,YAAY;EACrC;CACF;AACF"}
1
+ {"version":3,"file":"provider.js","names":["ModelContextProvider","ModelContext","Unsubscribe","Tool","toJSONSchema","FrameMessage","FRAME_MESSAGE_CHANNEL","SerializedModelContext","SerializedTool","serializeTool","tool","description","parameters","undefined","disabled","type","serializeModelContext","context","system","tools","Object","fromEntries","entries","map","name","getDefaultTargetOrigin","window","location","origin","AssistantFrameProvider","_instance","_providers","Map","_providerUnsubscribes","_activeToolCalls","abortController","AbortController","event","MessageEvent","_targetOrigin","_strictRegistrations","_wildcardRegistrations","constructor","targetOrigin","handleMessage","bind","addEventListener","setTimeout","broadcastUpdate","getInstance","reconcileTargetOrigin","size","Error","source","parent","data","channel","message","sendMessage","getModelContext","handleToolCall","cancelToolCall","id","Extract","toolName","get","abort","activeCall","set","result","error","execute","args","toolCallId","abortSignal","signal","human","e","String","delete","postMessage","contexts","Array","from","Set","values","p","reduce","merged","updateMessage","removeProvider","unsubscribe","addModelContextProvider","provider","instance","Symbol","subscribe","unsubscribeError","console","broadcastError","released","unsubscribeFailed","dispose","removeEventListener","cleanupFailed","cleanupError","runCleanup","cleanup","forEach","clear"],"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\nconst getDefaultTargetOrigin = () => window.location.origin;\n\nexport class AssistantFrameProvider {\n private static _instance: AssistantFrameProvider | null = null;\n\n private _providers = new Map<symbol, ModelContextProvider>();\n private _providerUnsubscribes = new Map<symbol, Unsubscribe | undefined>();\n private _activeToolCalls = new Map<\n string,\n { abortController: AbortController; event: MessageEvent }\n >();\n private _targetOrigin: string;\n private _strictRegistrations = 0;\n private _wildcardRegistrations = 0;\n\n private constructor(targetOrigin: string = getDefaultTargetOrigin()) {\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 } else {\n AssistantFrameProvider._instance.reconcileTargetOrigin(targetOrigin);\n }\n return AssistantFrameProvider._instance;\n }\n\n private reconcileTargetOrigin(\n targetOrigin: string = getDefaultTargetOrigin(),\n ) {\n if (targetOrigin === this._targetOrigin) return;\n\n if (this._providers.size === 0) {\n this._targetOrigin = targetOrigin;\n return;\n }\n\n if (targetOrigin === \"*\") return;\n\n if (this._targetOrigin === \"*\") {\n this._targetOrigin = targetOrigin;\n return;\n }\n\n throw new Error(\n `AssistantFrameProvider cannot register conflicting target origins: \"${this._targetOrigin}\" and \"${targetOrigin}\"`,\n );\n }\n\n private handleMessage(event: MessageEvent) {\n if (this._targetOrigin !== \"*\" && event.origin !== this._targetOrigin)\n return;\n if (event.source !== window.parent) 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 case \"tool-cancel\":\n this.cancelToolCall(message.id);\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 const abortController = new AbortController();\n this._activeToolCalls.get(message.id)?.abortController.abort();\n const activeCall = { abortController, event };\n this._activeToolCalls.set(message.id, activeCall);\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: 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 if (this._activeToolCalls.get(message.id) !== activeCall) return;\n this._activeToolCalls.delete(message.id);\n\n this.sendMessage(event, {\n type: \"tool-result\",\n id: message.id,\n ...(error !== undefined ? { error } : { result }),\n });\n }\n\n private cancelToolCall(id: string) {\n const activeCall = this._activeToolCalls.get(id);\n if (!activeCall) return;\n this._activeToolCalls.delete(id);\n activeCall.abortController.abort();\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(new Set(this._providers.values())).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 private removeProvider(id: symbol, origin: string): Unsubscribe | undefined {\n this._providers.delete(id);\n const unsubscribe = this._providerUnsubscribes.get(id);\n this._providerUnsubscribes.delete(id);\n if (origin === \"*\") {\n this._wildcardRegistrations -= 1;\n if (\n this._wildcardRegistrations === 0 &&\n this._strictRegistrations === 0\n ) {\n this._targetOrigin = getDefaultTargetOrigin();\n }\n } else {\n this._strictRegistrations -= 1;\n if (this._strictRegistrations === 0) {\n this._targetOrigin =\n this._wildcardRegistrations > 0 ? \"*\" : getDefaultTargetOrigin();\n }\n }\n return unsubscribe;\n }\n\n static addModelContextProvider(\n provider: ModelContextProvider,\n targetOrigin?: string,\n ): Unsubscribe {\n const origin = targetOrigin ?? getDefaultTargetOrigin();\n const instance = AssistantFrameProvider.getInstance(origin);\n const id = Symbol();\n instance._providers.set(id, provider);\n if (origin === \"*\") {\n instance._wildcardRegistrations += 1;\n } else {\n instance._strictRegistrations += 1;\n }\n\n try {\n const unsubscribe = provider.subscribe?.(() =>\n instance.broadcastUpdate(),\n );\n if (unsubscribe) {\n instance._providerUnsubscribes.set(id, unsubscribe);\n }\n\n instance.broadcastUpdate();\n } catch (error) {\n const unsubscribe = instance.removeProvider(id, origin);\n // Rollback failures must not replace the registration error.\n try {\n unsubscribe?.();\n } catch (unsubscribeError) {\n console.error(unsubscribeError);\n }\n try {\n instance.broadcastUpdate();\n } catch (broadcastError) {\n console.error(broadcastError);\n }\n throw error;\n }\n\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const unsubscribe = instance.removeProvider(id, origin);\n let unsubscribeFailed = false;\n let unsubscribeError: unknown;\n try {\n unsubscribe?.();\n } catch (error) {\n unsubscribeFailed = true;\n unsubscribeError = error;\n }\n try {\n instance.broadcastUpdate();\n } catch (error) {\n if (!unsubscribeFailed) throw error;\n console.error(error);\n }\n if (unsubscribeFailed) throw unsubscribeError;\n };\n }\n\n static dispose() {\n if (AssistantFrameProvider._instance) {\n const instance = AssistantFrameProvider._instance;\n window.removeEventListener(\"message\", instance.handleMessage);\n\n let cleanupFailed = false;\n let cleanupError: unknown;\n const runCleanup = (cleanup: () => void) => {\n try {\n cleanup();\n } catch (error) {\n if (cleanupFailed) {\n console.error(error);\n } else {\n cleanupFailed = true;\n cleanupError = error;\n }\n }\n };\n\n instance._providerUnsubscribes.forEach((unsubscribe) => {\n if (unsubscribe) runCleanup(unsubscribe);\n });\n instance._providerUnsubscribes.clear();\n instance._providers.clear();\n instance._activeToolCalls.forEach(({ abortController, event }, id) => {\n runCleanup(() => {\n abortController.abort();\n instance.sendMessage(event, {\n type: \"tool-result\",\n id,\n error: \"AssistantFrameProvider has been disposed\",\n });\n });\n });\n instance._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DwB,SAAS5D,iBAAiB2E,MAAM;GAEhChF,uBAAuBC,YAAY;GACnC,IAAI0E,eAAe,MAAMC;EAC3B;CACF;AACF"}
@@ -29,7 +29,7 @@ type SnapshotCarrierMessage = {
29
29
  * `metadata.custom.interactables`, or `undefined` if none. This is the read
30
30
  * half of the snapshot channel — integrations use it to surface interactable
31
31
  * state to the model (see `unstable_injectInteractableContext` in
32
- * `@assistant-ui/react-ai-sdk` for the AI SDK implementation).
32
+ * `@assistant-ui/ai-sdk` for the AI SDK implementation).
33
33
  *
34
34
  * @deprecated Unstable / Experimental (not actually removed).
35
35
  */
@@ -6,7 +6,7 @@ import { isJSONValueEqual } from "../utils/json/is-json-equal.js";
6
6
  * `metadata.custom.interactables`, or `undefined` if none. This is the read
7
7
  * half of the snapshot channel — integrations use it to surface interactable
8
8
  * state to the model (see `unstable_injectInteractableContext` in
9
- * `@assistant-ui/react-ai-sdk` for the AI SDK implementation).
9
+ * `@assistant-ui/ai-sdk` for the AI SDK implementation).
10
10
  *
11
11
  * @deprecated Unstable / Experimental (not actually removed).
12
12
  */
@@ -1 +1 @@
1
- {"version":3,"file":"interactable-composer-metadata.js","names":["isJSONValueEqual","isJSONValue","isRecord","Unstable_InteractableSnapshotEntry","id","name","state","partial","SnapshotCarrierMessage","role","metadata","content","unstable_getInteractableSnapshots","message","undefined","custom","Record","items","interactables","Array","isArray","unstable_formatInteractableSnapshot","entry","JSON","stringify","interactableToolName","replace","getArrayItemId","item","applyArrayUpdate","prev","update","mintId","next","set","clear","remove","length","ids","Set","filter","has","patches","map","patch","find","candidate","add","added","shallowMergeInteractableState","options","arrayBaseline","idFactory","field","idKeyedFields","ReadonlySet","baseline","key","value","Object","entries","baseValue","shallowDiffInteractableState","known","keys","diff","changed","ToolCallLikePart","type","toolCallId","toolName","args","result","asToolCallPart","part","p","updateCallTargets","success","argsId","createAddedItemIdFactory","addedItemIds","idsByField","Map","stringIds","size","get","shift","Unstable_InteractableVersion","origin","versionsCache","WeakMap","unstable_getInteractableVersions","messages","byName","byId","cached","versions","current","msg","it","push","_id","findModelKnownState","last","gateInteractableComposerMetadata","meta","rest","gated","pending","process","env","NODE_ENV","console","warn"],"sources":["../../src/model-context/interactable-composer-metadata.ts"],"sourcesContent":["import { isJSONValueEqual } from \"../utils/json/is-json-equal\";\nimport { isJSONValue, isRecord } from \"../utils/json/is-json\";\n\n/**\n * Unstable / Experimental — the interactables API is still evolving and may change in any release.\n * @deprecated Unstable / Experimental (not actually removed).\n */\nexport type Unstable_InteractableSnapshotEntry = {\n id: string;\n name: string;\n state: unknown;\n /**\n * When true, `state` carries only the top-level fields that changed since\n * the model's last known state; omitted fields are unchanged. The first\n * snapshot of an instance is always full.\n */\n partial?: boolean | undefined;\n};\n\n/**\n * Minimal message shape needed to read snapshots and `update_*` tool calls out\n * of history. Structurally compatible with both `ThreadMessage` and the AI\n * SDK's `UIMessage`.\n */\ntype SnapshotCarrierMessage = {\n role: string;\n metadata?: unknown;\n content?: readonly unknown[] | undefined;\n};\n\n/**\n * Reads the interactable snapshots stamped on a message's\n * `metadata.custom.interactables`, or `undefined` if none. This is the read\n * half of the snapshot channel — integrations use it to surface interactable\n * state to the model (see `unstable_injectInteractableContext` in\n * `@assistant-ui/react-ai-sdk` for the AI SDK implementation).\n *\n * @deprecated Unstable / Experimental (not actually removed).\n */\nexport function unstable_getInteractableSnapshots(message: {\n metadata?: unknown;\n}): Unstable_InteractableSnapshotEntry[] | undefined {\n const metadata = message.metadata;\n if (!metadata || typeof metadata !== \"object\") return undefined;\n const custom = (metadata as Record<string, unknown>).custom;\n if (!custom || typeof custom !== \"object\") return undefined;\n const items = (custom as Record<string, unknown>).interactables;\n return Array.isArray(items)\n ? (items as Unstable_InteractableSnapshotEntry[])\n : undefined;\n}\n\n/**\n * Canonical model-facing wording for one snapshot entry.\n *\n * @deprecated Unstable / Experimental (not actually removed).\n */\nexport function unstable_formatInteractableSnapshot(\n entry: Unstable_InteractableSnapshotEntry,\n): string {\n if (entry.partial) {\n return `[State of \"${entry.name}\" (id: ${JSON.stringify(entry.id)}) changed — updated fields: ${JSON.stringify(entry.state)}; fields not listed are unchanged]`;\n }\n return `[Current state of \"${entry.name}\" (id: ${JSON.stringify(entry.id)}): ${JSON.stringify(entry.state)}]`;\n}\n\n/** The model-facing tool name for an interactable `name`. One tool per name. */\nexport function interactableToolName(name: string): string {\n return `update_${name.replace(/[^a-zA-Z0-9_-]/g, \"_\")}`;\n}\n\nconst getArrayItemId = (item: unknown): string | number | undefined => {\n if (!isRecord(item)) return undefined;\n const id = item.id;\n return typeof id === \"string\" || typeof id === \"number\" ? id : undefined;\n};\n\nfunction applyArrayUpdate(\n prev: unknown[],\n update: Record<string, unknown>,\n mintId?: () => string | undefined,\n) {\n let next = Array.isArray(update.set) ? [...update.set] : [...prev];\n\n if (update.clear === true) next = [];\n\n if (Array.isArray(update.remove) && update.remove.length > 0) {\n const ids = new Set(update.remove);\n next = next.filter((item) => {\n const id = getArrayItemId(item);\n return id !== undefined ? !ids.has(id) : !ids.has(item);\n });\n }\n\n const patches = update.update;\n if (Array.isArray(patches) && patches.length > 0) {\n next = next.map((item) => {\n const id = getArrayItemId(item);\n if (id === undefined || !isRecord(item)) return item;\n const patch = patches.find(\n (candidate) => isRecord(candidate) && candidate.id === id,\n );\n return patch ? { ...item, ...patch } : item;\n });\n }\n\n if (Array.isArray(update.add) && update.add.length > 0) {\n const added = mintId\n ? update.add.map((item) => {\n if (!isRecord(item) || item.id !== undefined) return item;\n const id = mintId();\n return id === undefined ? item : { ...item, id };\n })\n : update.add;\n next = [...next, ...added];\n }\n\n return next;\n}\n\n/**\n * The merge `update_*` tools apply: top-level keys replace, rest preserved.\n * Array fields also accept operation objects (`add`, `update`, `remove`,\n * `clear`, `set`) so collection edits do not need a companion manage_* tool.\n */\nexport function shallowMergeInteractableState(\n prev: unknown,\n partial: unknown,\n options?:\n | {\n arrayBaseline?: unknown;\n /**\n * Supplies ids for added items in id-keyed array fields. The live\n * execute path mints fresh ids; history folds replay ids previously\n * returned by execute.\n */\n idFactory?: (field: string) => string | undefined;\n idKeyedFields?: ReadonlySet<string>;\n }\n | undefined,\n): unknown {\n if (!isRecord(prev) || !isRecord(partial)) return partial;\n const baseline = isRecord(options?.arrayBaseline)\n ? options.arrayBaseline\n : prev;\n const next = { ...prev };\n for (const [key, value] of Object.entries(partial)) {\n const baseValue = baseline[key];\n if (Array.isArray(baseValue) && isRecord(value)) {\n const mintId =\n options?.idFactory &&\n (options.idKeyedFields === undefined || options.idKeyedFields.has(key))\n ? () => options.idFactory?.(key)\n : undefined;\n next[key] = applyArrayUpdate(baseValue, value, mintId);\n } else {\n next[key] = value;\n }\n }\n return next;\n}\n\n/**\n * The top-level fields of `next` that differ from `known`, for stamping a\n * partial snapshot. Returns `undefined` when a partial stamp has no benefit:\n * the change is not expressible as a shallow merge (non-object states, or a\n * top-level key was removed), or every field changed anyway — the caller\n * falls back to a full snapshot.\n */\nfunction shallowDiffInteractableState(\n known: unknown,\n next: unknown,\n): Record<string, unknown> | undefined {\n if (!isRecord(known) || !isRecord(next)) return undefined;\n for (const key of Object.keys(known)) {\n if (!(key in next)) return undefined;\n }\n const diff: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(next)) {\n if (!(key in known) || !isJSONValueEqual(known[key], value)) {\n diff[key] = value;\n }\n }\n const changed = Object.keys(diff).length;\n if (changed === 0 || changed === Object.keys(next).length) return undefined;\n return diff;\n}\n\ntype ToolCallLikePart = {\n type?: string;\n toolCallId?: string;\n toolName?: string;\n args?: unknown;\n result?: unknown;\n};\n\nconst asToolCallPart = (part: unknown): ToolCallLikePart | undefined => {\n if (!part || typeof part !== \"object\") return undefined;\n const p = part as ToolCallLikePart;\n return p.type === \"tool-call\" ? p : undefined;\n};\n\n/** Whether an accepted `update_*` call addressed instance `id`. */\nconst updateCallTargets = (p: ToolCallLikePart, id: string): boolean => {\n if (!p.args || typeof p.args !== \"object\") return false;\n const result = isRecord(p.result) ? p.result : undefined;\n if (result?.success === false) return false;\n if (typeof result?.id === \"string\") return result.id === id;\n const argsId = (p.args as Record<string, unknown>).id;\n return argsId === id || argsId === undefined;\n};\n\nconst createAddedItemIdFactory = (result: unknown) => {\n const value = isRecord(result) ? result.addedItemIds : undefined;\n if (!isRecord(value)) return undefined;\n\n const idsByField = new Map<string, string[]>();\n for (const [field, ids] of Object.entries(value)) {\n if (!Array.isArray(ids)) continue;\n const stringIds = ids.filter(\n (item): item is string => typeof item === \"string\",\n );\n if (stringIds.length > 0) idsByField.set(field, stringIds);\n }\n if (idsByField.size === 0) return undefined;\n\n return (field: string) => idsByField.get(field)?.shift();\n};\n\n/**\n * Unstable / Experimental — the interactables API is still evolving and may change in any release.\n * @deprecated Unstable / Experimental (not actually removed).\n */\nexport type Unstable_InteractableVersion = {\n /** The full state as of this version. */\n state: unknown;\n origin: \"create\" | \"update\" | \"user-edit\";\n /** For create/update versions, the tool call that produced this version. */\n toolCallId?: string | undefined;\n};\n\n// Without this, every mounted anchor re-folds the whole thread on each streaming\n// token, since the repository hands out a new messages array per token.\nconst versionsCache = new WeakMap<\n readonly SnapshotCarrierMessage[],\n Map<string, Map<string, Unstable_InteractableVersion[]>>\n>();\n\n/**\n * Every version of interactable `id` recorded in the thread, oldest first,\n * folded chronologically:\n *\n * - the tool call whose `toolCallId` equals `id` seeds the baseline with its\n * args (`origin: \"create\"`) — the `id: toolCallId` convention for\n * tool-created interactables,\n * - a snapshot stamped on a user message is a `\"user-edit\"` version (a full\n * snapshot replaces the state; a partial one shallow-merges),\n * - each accepted `update_*` call shallow-merges an `\"update\"` version.\n *\n * The last entry is the state the model knows. Partial snapshots and update\n * calls with no baseline to merge into are skipped.\n *\n * @deprecated Unstable / Experimental (not actually removed).\n */\nexport function unstable_getInteractableVersions(\n messages: readonly SnapshotCarrierMessage[],\n id: string,\n name: string,\n): Unstable_InteractableVersion[] {\n let byName = versionsCache.get(messages);\n if (!byName) {\n byName = new Map();\n versionsCache.set(messages, byName);\n }\n let byId = byName.get(name);\n if (!byId) {\n byId = new Map();\n byName.set(name, byId);\n }\n const cached = byId.get(id);\n if (cached) return cached;\n\n const toolName = interactableToolName(name);\n const versions: Unstable_InteractableVersion[] = [];\n const current = () => versions[versions.length - 1];\n\n for (const msg of messages) {\n if (msg.role === \"user\") {\n const entry = unstable_getInteractableSnapshots(msg)?.find(\n (it) => it.id === id,\n );\n if (!entry) continue;\n if (entry.partial) {\n const prev = current();\n if (prev) {\n versions.push({\n state: shallowMergeInteractableState(prev.state, entry.state),\n origin: \"user-edit\",\n });\n }\n } else {\n versions.push({ state: entry.state, origin: \"user-edit\" });\n }\n continue;\n }\n\n if (msg.role !== \"assistant\") continue;\n for (const part of msg.content ?? []) {\n const p = asToolCallPart(part);\n if (!p) continue;\n if (p.toolCallId === id && p.toolName === name) {\n if (p.args && typeof p.args === \"object\") {\n versions.push({ state: p.args, origin: \"create\", toolCallId: id });\n }\n } else if (p.toolName === toolName && updateCallTargets(p, id)) {\n const prev = current();\n if (prev) {\n const { id: _id, ...partial } = p.args as Record<string, unknown>;\n const idFactory = createAddedItemIdFactory(p.result);\n versions.push({\n state: idFactory\n ? shallowMergeInteractableState(prev.state, partial, {\n idFactory,\n })\n : shallowMergeInteractableState(prev.state, partial),\n origin: \"update\",\n toolCallId: p.toolCallId,\n });\n }\n }\n }\n }\n byId.set(id, versions);\n return versions;\n}\n\n/**\n * The state the model knows for interactable `id` — its latest recorded\n * version, or `undefined` when no baseline exists yet.\n */\nexport function findModelKnownState(\n messages: readonly SnapshotCarrierMessage[],\n id: string,\n name: string,\n): { state: unknown } | undefined {\n const versions = unstable_getInteractableVersions(messages, id, name);\n const last = versions[versions.length - 1];\n return last ? { state: last.state } : undefined;\n}\n\n/**\n * Snapshot gate. Stamps an interactable only when the model doesn't already\n * know its state (no baseline yet, or the live state differs from the folded\n * thread record). A change that fits a shallow merge is stamped as a partial\n * snapshot carrying just the changed fields; otherwise the full state is\n * stamped. Other metadata keys pass through untouched.\n */\nexport function gateInteractableComposerMetadata(\n meta: Record<string, unknown> | undefined,\n messages: readonly SnapshotCarrierMessage[],\n): Record<string, unknown> | undefined {\n if (!meta) return undefined;\n const { interactables, ...rest } = meta as {\n interactables?: Unstable_InteractableSnapshotEntry[];\n } & Record<string, unknown>;\n\n const gated: Record<string, unknown> = { ...rest };\n if (Array.isArray(interactables)) {\n const pending: Unstable_InteractableSnapshotEntry[] = [];\n for (const it of interactables) {\n if (process.env.NODE_ENV !== \"production\" && !isJSONValue(it.state)) {\n console.warn(\n `[Interactables] state for \"${it.name}\" (${it.id}) is not JSON-equatable ` +\n `(an undefined, NaN, Infinity, function, or symbol value?). It will be ` +\n `re-snapshotted on every send, recreating per-message growth. Use plain ` +\n `JSON values.`,\n );\n }\n const known = findModelKnownState(messages, it.id, it.name);\n if (!known) {\n pending.push({ id: it.id, name: it.name, state: it.state });\n continue;\n }\n if (isJSONValueEqual(it.state, known.state)) continue;\n const diff = shallowDiffInteractableState(known.state, it.state);\n pending.push(\n diff\n ? { id: it.id, name: it.name, state: diff, partial: true }\n : { id: it.id, name: it.name, state: it.state },\n );\n }\n if (pending.length) gated.interactables = pending;\n }\n return Object.keys(gated).length ? gated : undefined;\n}\n"],"mappings":";;;;;;;;;;;;AAuCA,SAAgBY,kCAAkCC,SAEG;CACnD,MAAMH,WAAWG,QAAQH;CACzB,IAAI,CAACA,YAAY,OAAOA,aAAa,UAAU,OAAOI,KAAAA;CACtD,MAAMC,SAAUL,SAAqCK;CACrD,IAAI,CAACA,UAAU,OAAOA,WAAW,UAAU,OAAOD,KAAAA;CAClD,MAAMG,QAASF,OAAmCG;CAClD,OAAOC,MAAMC,QAAQH,KAAK,IACrBA,QACDH,KAAAA;AACN;;;;;;AAOA,SAAgBO,oCACdC,OACQ;CACR,IAAIA,MAAMf,SACR,OAAO,cAAce,MAAMjB,KAAI,SAAUkB,KAAKC,UAAUF,MAAMlB,EAAE,EAAC,8BAA+BmB,KAAKC,UAAUF,MAAMhB,KAAK,EAAC;CAE7H,OAAO,sBAAsBgB,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SAASD;CAInC,MAAME,QAAiC,EAAE,GAAGD,KAAK;CACjD,IAAIvF,MAAMC,QAAQF,aAAa,GAAG;EAChC,MAAM0F,UAAgD,CAAA;EACtD,KAAK,MAAMT,MAAMjF,eAAe;GAC9B,IAAI2F,QAAQC,IAAIC,aAAa,gBAAgB,CAAC9G,YAAYkG,GAAG7F,KAAK,GAChE0G,QAAQC,KACN,8BAA8Bd,GAAG9F,KAAI,KAAM8F,GAAG/F,GAAE,kLAIlD;GAEF,MAAM2D,QAAQuC,oBAAoBV,UAAUO,GAAG/F,IAAI+F,GAAG9F,IAAI;GAC1D,IAAI,CAAC0D,OAAO;IACV6C,QAAQR,KAAK;KAAEhG,IAAI+F,GAAG/F;KAAIC,MAAM8F,GAAG9F;KAAMC,OAAO6F,GAAG7F;IAAM,CAAC;IAC1D;GACF;GACA,IAAIN,iBAAiBmG,GAAG7F,OAAOyD,MAAMzD,KAAK,GAAG;GAC7C,MAAM2D,OAAOH,6BAA6BC,MAAMzD,OAAO6F,GAAG7F,KAAK;GAC/DsG,QAAQR,KACNnC,OACI;IAAE7D,IAAI+F,GAAG/F;IAAIC,MAAM8F,GAAG9F;IAAMC,OAAO2D;IAAM1D,SAAS;GAAK,IACvD;IAAEH,IAAI+F,GAAG/F;IAAIC,MAAM8F,GAAG9F;IAAMC,OAAO6F,GAAG7F;GAAM,CAClD;EACF;EACA,IAAIsG,QAAQvE,QAAQsE,MAAMzF,gBAAgB0F;CAC5C;CACA,OAAOjD,OAAOK,KAAK2C,KAAK,CAAC,CAACtE,SAASsE,QAAQ7F,KAAAA;AAC7C"}
1
+ {"version":3,"file":"interactable-composer-metadata.js","names":["isJSONValueEqual","isJSONValue","isRecord","Unstable_InteractableSnapshotEntry","id","name","state","partial","SnapshotCarrierMessage","role","metadata","content","unstable_getInteractableSnapshots","message","undefined","custom","Record","items","interactables","Array","isArray","unstable_formatInteractableSnapshot","entry","JSON","stringify","interactableToolName","replace","getArrayItemId","item","applyArrayUpdate","prev","update","mintId","next","set","clear","remove","length","ids","Set","filter","has","patches","map","patch","find","candidate","add","added","shallowMergeInteractableState","options","arrayBaseline","idFactory","field","idKeyedFields","ReadonlySet","baseline","key","value","Object","entries","baseValue","shallowDiffInteractableState","known","keys","diff","changed","ToolCallLikePart","type","toolCallId","toolName","args","result","asToolCallPart","part","p","updateCallTargets","success","argsId","createAddedItemIdFactory","addedItemIds","idsByField","Map","stringIds","size","get","shift","Unstable_InteractableVersion","origin","versionsCache","WeakMap","unstable_getInteractableVersions","messages","byName","byId","cached","versions","current","msg","it","push","_id","findModelKnownState","last","gateInteractableComposerMetadata","meta","rest","gated","pending","process","env","NODE_ENV","console","warn"],"sources":["../../src/model-context/interactable-composer-metadata.ts"],"sourcesContent":["import { isJSONValueEqual } from \"../utils/json/is-json-equal\";\nimport { isJSONValue, isRecord } from \"../utils/json/is-json\";\n\n/**\n * Unstable / Experimental — the interactables API is still evolving and may change in any release.\n * @deprecated Unstable / Experimental (not actually removed).\n */\nexport type Unstable_InteractableSnapshotEntry = {\n id: string;\n name: string;\n state: unknown;\n /**\n * When true, `state` carries only the top-level fields that changed since\n * the model's last known state; omitted fields are unchanged. The first\n * snapshot of an instance is always full.\n */\n partial?: boolean | undefined;\n};\n\n/**\n * Minimal message shape needed to read snapshots and `update_*` tool calls out\n * of history. Structurally compatible with both `ThreadMessage` and the AI\n * SDK's `UIMessage`.\n */\ntype SnapshotCarrierMessage = {\n role: string;\n metadata?: unknown;\n content?: readonly unknown[] | undefined;\n};\n\n/**\n * Reads the interactable snapshots stamped on a message's\n * `metadata.custom.interactables`, or `undefined` if none. This is the read\n * half of the snapshot channel — integrations use it to surface interactable\n * state to the model (see `unstable_injectInteractableContext` in\n * `@assistant-ui/ai-sdk` for the AI SDK implementation).\n *\n * @deprecated Unstable / Experimental (not actually removed).\n */\nexport function unstable_getInteractableSnapshots(message: {\n metadata?: unknown;\n}): Unstable_InteractableSnapshotEntry[] | undefined {\n const metadata = message.metadata;\n if (!metadata || typeof metadata !== \"object\") return undefined;\n const custom = (metadata as Record<string, unknown>).custom;\n if (!custom || typeof custom !== \"object\") return undefined;\n const items = (custom as Record<string, unknown>).interactables;\n return Array.isArray(items)\n ? (items as Unstable_InteractableSnapshotEntry[])\n : undefined;\n}\n\n/**\n * Canonical model-facing wording for one snapshot entry.\n *\n * @deprecated Unstable / Experimental (not actually removed).\n */\nexport function unstable_formatInteractableSnapshot(\n entry: Unstable_InteractableSnapshotEntry,\n): string {\n if (entry.partial) {\n return `[State of \"${entry.name}\" (id: ${JSON.stringify(entry.id)}) changed — updated fields: ${JSON.stringify(entry.state)}; fields not listed are unchanged]`;\n }\n return `[Current state of \"${entry.name}\" (id: ${JSON.stringify(entry.id)}): ${JSON.stringify(entry.state)}]`;\n}\n\n/** The model-facing tool name for an interactable `name`. One tool per name. */\nexport function interactableToolName(name: string): string {\n return `update_${name.replace(/[^a-zA-Z0-9_-]/g, \"_\")}`;\n}\n\nconst getArrayItemId = (item: unknown): string | number | undefined => {\n if (!isRecord(item)) return undefined;\n const id = item.id;\n return typeof id === \"string\" || typeof id === \"number\" ? id : undefined;\n};\n\nfunction applyArrayUpdate(\n prev: unknown[],\n update: Record<string, unknown>,\n mintId?: () => string | undefined,\n) {\n let next = Array.isArray(update.set) ? [...update.set] : [...prev];\n\n if (update.clear === true) next = [];\n\n if (Array.isArray(update.remove) && update.remove.length > 0) {\n const ids = new Set(update.remove);\n next = next.filter((item) => {\n const id = getArrayItemId(item);\n return id !== undefined ? !ids.has(id) : !ids.has(item);\n });\n }\n\n const patches = update.update;\n if (Array.isArray(patches) && patches.length > 0) {\n next = next.map((item) => {\n const id = getArrayItemId(item);\n if (id === undefined || !isRecord(item)) return item;\n const patch = patches.find(\n (candidate) => isRecord(candidate) && candidate.id === id,\n );\n return patch ? { ...item, ...patch } : item;\n });\n }\n\n if (Array.isArray(update.add) && update.add.length > 0) {\n const added = mintId\n ? update.add.map((item) => {\n if (!isRecord(item) || item.id !== undefined) return item;\n const id = mintId();\n return id === undefined ? item : { ...item, id };\n })\n : update.add;\n next = [...next, ...added];\n }\n\n return next;\n}\n\n/**\n * The merge `update_*` tools apply: top-level keys replace, rest preserved.\n * Array fields also accept operation objects (`add`, `update`, `remove`,\n * `clear`, `set`) so collection edits do not need a companion manage_* tool.\n */\nexport function shallowMergeInteractableState(\n prev: unknown,\n partial: unknown,\n options?:\n | {\n arrayBaseline?: unknown;\n /**\n * Supplies ids for added items in id-keyed array fields. The live\n * execute path mints fresh ids; history folds replay ids previously\n * returned by execute.\n */\n idFactory?: (field: string) => string | undefined;\n idKeyedFields?: ReadonlySet<string>;\n }\n | undefined,\n): unknown {\n if (!isRecord(prev) || !isRecord(partial)) return partial;\n const baseline = isRecord(options?.arrayBaseline)\n ? options.arrayBaseline\n : prev;\n const next = { ...prev };\n for (const [key, value] of Object.entries(partial)) {\n const baseValue = baseline[key];\n if (Array.isArray(baseValue) && isRecord(value)) {\n const mintId =\n options?.idFactory &&\n (options.idKeyedFields === undefined || options.idKeyedFields.has(key))\n ? () => options.idFactory?.(key)\n : undefined;\n next[key] = applyArrayUpdate(baseValue, value, mintId);\n } else {\n next[key] = value;\n }\n }\n return next;\n}\n\n/**\n * The top-level fields of `next` that differ from `known`, for stamping a\n * partial snapshot. Returns `undefined` when a partial stamp has no benefit:\n * the change is not expressible as a shallow merge (non-object states, or a\n * top-level key was removed), or every field changed anyway — the caller\n * falls back to a full snapshot.\n */\nfunction shallowDiffInteractableState(\n known: unknown,\n next: unknown,\n): Record<string, unknown> | undefined {\n if (!isRecord(known) || !isRecord(next)) return undefined;\n for (const key of Object.keys(known)) {\n if (!(key in next)) return undefined;\n }\n const diff: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(next)) {\n if (!(key in known) || !isJSONValueEqual(known[key], value)) {\n diff[key] = value;\n }\n }\n const changed = Object.keys(diff).length;\n if (changed === 0 || changed === Object.keys(next).length) return undefined;\n return diff;\n}\n\ntype ToolCallLikePart = {\n type?: string;\n toolCallId?: string;\n toolName?: string;\n args?: unknown;\n result?: unknown;\n};\n\nconst asToolCallPart = (part: unknown): ToolCallLikePart | undefined => {\n if (!part || typeof part !== \"object\") return undefined;\n const p = part as ToolCallLikePart;\n return p.type === \"tool-call\" ? p : undefined;\n};\n\n/** Whether an accepted `update_*` call addressed instance `id`. */\nconst updateCallTargets = (p: ToolCallLikePart, id: string): boolean => {\n if (!p.args || typeof p.args !== \"object\") return false;\n const result = isRecord(p.result) ? p.result : undefined;\n if (result?.success === false) return false;\n if (typeof result?.id === \"string\") return result.id === id;\n const argsId = (p.args as Record<string, unknown>).id;\n return argsId === id || argsId === undefined;\n};\n\nconst createAddedItemIdFactory = (result: unknown) => {\n const value = isRecord(result) ? result.addedItemIds : undefined;\n if (!isRecord(value)) return undefined;\n\n const idsByField = new Map<string, string[]>();\n for (const [field, ids] of Object.entries(value)) {\n if (!Array.isArray(ids)) continue;\n const stringIds = ids.filter(\n (item): item is string => typeof item === \"string\",\n );\n if (stringIds.length > 0) idsByField.set(field, stringIds);\n }\n if (idsByField.size === 0) return undefined;\n\n return (field: string) => idsByField.get(field)?.shift();\n};\n\n/**\n * Unstable / Experimental — the interactables API is still evolving and may change in any release.\n * @deprecated Unstable / Experimental (not actually removed).\n */\nexport type Unstable_InteractableVersion = {\n /** The full state as of this version. */\n state: unknown;\n origin: \"create\" | \"update\" | \"user-edit\";\n /** For create/update versions, the tool call that produced this version. */\n toolCallId?: string | undefined;\n};\n\n// Without this, every mounted anchor re-folds the whole thread on each streaming\n// token, since the repository hands out a new messages array per token.\nconst versionsCache = new WeakMap<\n readonly SnapshotCarrierMessage[],\n Map<string, Map<string, Unstable_InteractableVersion[]>>\n>();\n\n/**\n * Every version of interactable `id` recorded in the thread, oldest first,\n * folded chronologically:\n *\n * - the tool call whose `toolCallId` equals `id` seeds the baseline with its\n * args (`origin: \"create\"`) — the `id: toolCallId` convention for\n * tool-created interactables,\n * - a snapshot stamped on a user message is a `\"user-edit\"` version (a full\n * snapshot replaces the state; a partial one shallow-merges),\n * - each accepted `update_*` call shallow-merges an `\"update\"` version.\n *\n * The last entry is the state the model knows. Partial snapshots and update\n * calls with no baseline to merge into are skipped.\n *\n * @deprecated Unstable / Experimental (not actually removed).\n */\nexport function unstable_getInteractableVersions(\n messages: readonly SnapshotCarrierMessage[],\n id: string,\n name: string,\n): Unstable_InteractableVersion[] {\n let byName = versionsCache.get(messages);\n if (!byName) {\n byName = new Map();\n versionsCache.set(messages, byName);\n }\n let byId = byName.get(name);\n if (!byId) {\n byId = new Map();\n byName.set(name, byId);\n }\n const cached = byId.get(id);\n if (cached) return cached;\n\n const toolName = interactableToolName(name);\n const versions: Unstable_InteractableVersion[] = [];\n const current = () => versions[versions.length - 1];\n\n for (const msg of messages) {\n if (msg.role === \"user\") {\n const entry = unstable_getInteractableSnapshots(msg)?.find(\n (it) => it.id === id,\n );\n if (!entry) continue;\n if (entry.partial) {\n const prev = current();\n if (prev) {\n versions.push({\n state: shallowMergeInteractableState(prev.state, entry.state),\n origin: \"user-edit\",\n });\n }\n } else {\n versions.push({ state: entry.state, origin: \"user-edit\" });\n }\n continue;\n }\n\n if (msg.role !== \"assistant\") continue;\n for (const part of msg.content ?? []) {\n const p = asToolCallPart(part);\n if (!p) continue;\n if (p.toolCallId === id && p.toolName === name) {\n if (p.args && typeof p.args === \"object\") {\n versions.push({ state: p.args, origin: \"create\", toolCallId: id });\n }\n } else if (p.toolName === toolName && updateCallTargets(p, id)) {\n const prev = current();\n if (prev) {\n const { id: _id, ...partial } = p.args as Record<string, unknown>;\n const idFactory = createAddedItemIdFactory(p.result);\n versions.push({\n state: idFactory\n ? shallowMergeInteractableState(prev.state, partial, {\n idFactory,\n })\n : shallowMergeInteractableState(prev.state, partial),\n origin: \"update\",\n toolCallId: p.toolCallId,\n });\n }\n }\n }\n }\n byId.set(id, versions);\n return versions;\n}\n\n/**\n * The state the model knows for interactable `id` — its latest recorded\n * version, or `undefined` when no baseline exists yet.\n */\nexport function findModelKnownState(\n messages: readonly SnapshotCarrierMessage[],\n id: string,\n name: string,\n): { state: unknown } | undefined {\n const versions = unstable_getInteractableVersions(messages, id, name);\n const last = versions[versions.length - 1];\n return last ? { state: last.state } : undefined;\n}\n\n/**\n * Snapshot gate. Stamps an interactable only when the model doesn't already\n * know its state (no baseline yet, or the live state differs from the folded\n * thread record). A change that fits a shallow merge is stamped as a partial\n * snapshot carrying just the changed fields; otherwise the full state is\n * stamped. Other metadata keys pass through untouched.\n */\nexport function gateInteractableComposerMetadata(\n meta: Record<string, unknown> | undefined,\n messages: readonly SnapshotCarrierMessage[],\n): Record<string, unknown> | undefined {\n if (!meta) return undefined;\n const { interactables, ...rest } = meta as {\n interactables?: Unstable_InteractableSnapshotEntry[];\n } & Record<string, unknown>;\n\n const gated: Record<string, unknown> = { ...rest };\n if (Array.isArray(interactables)) {\n const pending: Unstable_InteractableSnapshotEntry[] = [];\n for (const it of interactables) {\n if (process.env.NODE_ENV !== \"production\" && !isJSONValue(it.state)) {\n console.warn(\n `[Interactables] state for \"${it.name}\" (${it.id}) is not JSON-equatable ` +\n `(an undefined, NaN, Infinity, function, or symbol value?). It will be ` +\n `re-snapshotted on every send, recreating per-message growth. Use plain ` +\n `JSON values.`,\n );\n }\n const known = findModelKnownState(messages, it.id, it.name);\n if (!known) {\n pending.push({ id: it.id, name: it.name, state: it.state });\n continue;\n }\n if (isJSONValueEqual(it.state, known.state)) continue;\n const diff = shallowDiffInteractableState(known.state, it.state);\n pending.push(\n diff\n ? { id: it.id, name: it.name, state: diff, partial: true }\n : { id: it.id, name: it.name, state: it.state },\n );\n }\n if (pending.length) gated.interactables = pending;\n }\n return Object.keys(gated).length ? gated : undefined;\n}\n"],"mappings":";;;;;;;;;;;;AAuCA,SAAgBY,kCAAkCC,SAEG;CACnD,MAAMH,WAAWG,QAAQH;CACzB,IAAI,CAACA,YAAY,OAAOA,aAAa,UAAU,OAAOI,KAAAA;CACtD,MAAMC,SAAUL,SAAqCK;CACrD,IAAI,CAACA,UAAU,OAAOA,WAAW,UAA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2C,KAAK,CAAC,CAACtE,SAASsE,QAAQ7F,KAAAA;AAC7C"}
@@ -5,9 +5,9 @@ import { ModelContextRegistryInstructionHandle, ModelContextRegistryProviderHand
5
5
  declare class ModelContextRegistry implements ModelContextProvider {
6
6
  private _tools;
7
7
  private _instructions;
8
- private _providers;
8
+ private _contextProviders;
9
9
  private _subscribers;
10
- private _providerUnsubscribes;
10
+ constructor();
11
11
  getModelContext(): ModelContext;
12
12
  subscribe(callback: () => void): Unsubscribe;
13
13
  private notifySubscribers;