@assistant-ui/core 0.3.14 → 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 (341) hide show
  1. package/dist/adapters/voice.js +11 -0
  2. package/dist/adapters/voice.js.map +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/internal.d.ts +8 -2
  5. package/dist/internal.js +9 -3
  6. package/dist/model-context/frame/host.d.ts +1 -1
  7. package/dist/model-context/frame/host.d.ts.map +1 -1
  8. package/dist/model-context/frame/host.js +20 -5
  9. package/dist/model-context/frame/host.js.map +1 -1
  10. package/dist/model-context/frame/provider.d.ts +6 -0
  11. package/dist/model-context/frame/provider.d.ts.map +1 -1
  12. package/dist/model-context/frame/provider.js +126 -16
  13. package/dist/model-context/frame/provider.js.map +1 -1
  14. package/dist/model-context/frame/types.d.ts +4 -1
  15. package/dist/model-context/frame/types.d.ts.map +1 -1
  16. package/dist/model-context/frame/types.js.map +1 -1
  17. package/dist/model-context/interactable-composer-metadata.d.ts +1 -1
  18. package/dist/model-context/interactable-composer-metadata.js +1 -1
  19. package/dist/model-context/interactable-composer-metadata.js.map +1 -1
  20. package/dist/model-context/registry.d.ts +2 -2
  21. package/dist/model-context/registry.d.ts.map +1 -1
  22. package/dist/model-context/registry.js +9 -28
  23. package/dist/model-context/registry.js.map +1 -1
  24. package/dist/react/client/InMemoryThreadList.d.ts.map +1 -1
  25. package/dist/react/client/InMemoryThreadList.js +24 -20
  26. package/dist/react/client/InMemoryThreadList.js.map +1 -1
  27. package/dist/react/client/Interactables.d.ts.map +1 -1
  28. package/dist/react/client/Interactables.js +59 -177
  29. package/dist/react/client/Interactables.js.map +1 -1
  30. package/dist/react/client/RemoteThreadList.d.ts +1 -1
  31. package/dist/react/client/RemoteThreadList.d.ts.map +1 -1
  32. package/dist/react/client/RemoteThreadList.js +117 -78
  33. package/dist/react/client/RemoteThreadList.js.map +1 -1
  34. package/dist/react/index.d.ts +2 -1
  35. package/dist/react/interactables-legacy/Interactables.d.ts.map +1 -1
  36. package/dist/react/interactables-legacy/Interactables.js +56 -174
  37. package/dist/react/interactables-legacy/Interactables.js.map +1 -1
  38. package/dist/react/interactables-shared/useInteractablePersistenceQueue.d.ts +24 -0
  39. package/dist/react/interactables-shared/useInteractablePersistenceQueue.d.ts.map +1 -0
  40. package/dist/react/interactables-shared/useInteractablePersistenceQueue.js +138 -0
  41. package/dist/react/interactables-shared/useInteractablePersistenceQueue.js.map +1 -0
  42. package/dist/react/primitive-hooks/useActionBarCopy.js +7 -1
  43. package/dist/react/primitive-hooks/useActionBarCopy.js.map +1 -1
  44. package/dist/react/primitive-hooks/useThreadIsEmpty.d.ts +3 -0
  45. package/dist/react/primitive-hooks/useThreadIsEmpty.d.ts.map +1 -1
  46. package/dist/react/primitive-hooks/useThreadIsEmpty.js +3 -0
  47. package/dist/react/primitive-hooks/useThreadIsEmpty.js.map +1 -1
  48. package/dist/react/primitive-hooks/useThreadIsRunning.d.ts +3 -0
  49. package/dist/react/primitive-hooks/useThreadIsRunning.d.ts.map +1 -1
  50. package/dist/react/primitive-hooks/useThreadIsRunning.js +3 -0
  51. package/dist/react/primitive-hooks/useThreadIsRunning.js.map +1 -1
  52. package/dist/react/primitives/composer/ComposerIf.js.map +1 -1
  53. package/dist/react/primitives/composer/ComposerQueue.d.ts +2 -1
  54. package/dist/react/primitives/composer/ComposerQueue.d.ts.map +1 -1
  55. package/dist/react/primitives/message/MessageParts.js.map +1 -1
  56. package/dist/react/runtimes/RemoteThreadListHookInstanceManager.d.ts +3 -1
  57. package/dist/react/runtimes/RemoteThreadListHookInstanceManager.d.ts.map +1 -1
  58. package/dist/react/runtimes/RemoteThreadListHookInstanceManager.js +6 -0
  59. package/dist/react/runtimes/RemoteThreadListHookInstanceManager.js.map +1 -1
  60. package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts +7 -1
  61. package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts.map +1 -1
  62. package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js +174 -64
  63. package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js.map +1 -1
  64. package/dist/react/runtimes/RemoteThreadResource.d.ts.map +1 -1
  65. package/dist/react/runtimes/RemoteThreadResource.js +2 -0
  66. package/dist/react/runtimes/RemoteThreadResource.js.map +1 -1
  67. package/dist/react/runtimes/assistant-transport/runManager.d.ts.map +1 -1
  68. package/dist/react/runtimes/assistant-transport/runManager.js +2 -12
  69. package/dist/react/runtimes/assistant-transport/runManager.js.map +1 -1
  70. package/dist/react/runtimes/assistant-transport/useAssistantTransportRuntime.d.ts.map +1 -1
  71. package/dist/react/runtimes/assistant-transport/useAssistantTransportRuntime.js +1 -1
  72. package/dist/react/runtimes/assistant-transport/useAssistantTransportRuntime.js.map +1 -1
  73. package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.d.ts +3 -10
  74. package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.d.ts.map +1 -1
  75. package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.js +20 -67
  76. package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.js.map +1 -1
  77. package/dist/react/runtimes/cloud/createCloudThreadListAdapterCreateFallback.d.ts +12 -0
  78. package/dist/react/runtimes/cloud/createCloudThreadListAdapterCreateFallback.d.ts.map +1 -0
  79. package/dist/react/runtimes/cloud/createCloudThreadListAdapterCreateFallback.js +10 -0
  80. package/dist/react/runtimes/cloud/createCloudThreadListAdapterCreateFallback.js.map +1 -0
  81. package/dist/react/runtimes/cloud/useCloudThreadListAdapter.d.ts.map +1 -1
  82. package/dist/react/runtimes/cloud/useCloudThreadListAdapter.js +38 -5
  83. package/dist/react/runtimes/cloud/useCloudThreadListAdapter.js.map +1 -1
  84. package/dist/react/runtimes/cloud/useCloudThreadListRuntime.js.map +1 -1
  85. package/dist/react/runtimes/createMessageConverter.d.ts +2 -1
  86. package/dist/react/runtimes/createMessageConverter.d.ts.map +1 -1
  87. package/dist/react/runtimes/external-message-converter.d.ts +6 -25
  88. package/dist/react/runtimes/external-message-converter.d.ts.map +1 -1
  89. package/dist/react/runtimes/external-message-converter.js +33 -233
  90. package/dist/react/runtimes/external-message-converter.js.map +1 -1
  91. package/dist/runtime/api/composer-runtime.d.ts +1 -1
  92. package/dist/runtime/api/composer-runtime.js.map +1 -1
  93. package/dist/runtime/api/thread-runtime.d.ts +1 -2
  94. package/dist/runtime/api/thread-runtime.d.ts.map +1 -1
  95. package/dist/runtime/base/base-composer-runtime-core.d.ts +1 -1
  96. package/dist/runtime/base/base-composer-runtime-core.d.ts.map +1 -1
  97. package/dist/runtime/base/base-composer-runtime-core.js +14 -29
  98. package/dist/runtime/base/base-composer-runtime-core.js.map +1 -1
  99. package/dist/runtime/base/base-thread-runtime-core.d.ts +2 -4
  100. package/dist/runtime/base/base-thread-runtime-core.d.ts.map +1 -1
  101. package/dist/runtime/base/base-thread-runtime-core.js +3 -9
  102. package/dist/runtime/base/base-thread-runtime-core.js.map +1 -1
  103. package/dist/runtime/base/default-thread-composer-runtime-core.d.ts +1 -1
  104. package/dist/runtime/base/default-thread-composer-runtime-core.d.ts.map +1 -1
  105. package/dist/runtime/base/default-thread-composer-runtime-core.js +1 -1
  106. package/dist/runtime/base/default-thread-composer-runtime-core.js.map +1 -1
  107. package/dist/runtime/interfaces/composer-runtime-core.d.ts +1 -1
  108. package/dist/runtime/interfaces/thread-runtime-core.d.ts +1 -1
  109. package/dist/runtime/internal.d.ts +2 -1
  110. package/dist/runtime/internal.js +2 -1
  111. package/dist/runtime/queue/external-thread-queue-adapter.d.ts +1 -1
  112. package/dist/runtime/queue/message-queue.d.ts.map +1 -1
  113. package/dist/runtime/queue/message-queue.js +1 -1
  114. package/dist/runtime/queue/message-queue.js.map +1 -1
  115. package/dist/runtime/queue/queue-item.d.ts +12 -0
  116. package/dist/runtime/queue/queue-item.d.ts.map +1 -0
  117. package/dist/runtime/queue/queue-item.js +6 -0
  118. package/dist/runtime/queue/queue-item.js.map +1 -0
  119. package/dist/runtime/utils/abortable-thread-load.d.ts +15 -0
  120. package/dist/runtime/utils/abortable-thread-load.d.ts.map +1 -0
  121. package/dist/runtime/utils/abortable-thread-load.js +35 -0
  122. package/dist/runtime/utils/abortable-thread-load.js.map +1 -0
  123. package/dist/runtime/utils/attachment-add-operations.d.ts +18 -0
  124. package/dist/runtime/utils/attachment-add-operations.d.ts.map +1 -0
  125. package/dist/runtime/utils/attachment-add-operations.js +43 -0
  126. package/dist/runtime/utils/attachment-add-operations.js.map +1 -0
  127. package/dist/runtime/utils/auto-status.d.ts +6 -1
  128. package/dist/runtime/utils/auto-status.d.ts.map +1 -1
  129. package/dist/runtime/utils/auto-status.js +7 -1
  130. package/dist/runtime/utils/auto-status.js.map +1 -1
  131. package/dist/runtime/utils/external-message-conversion.d.ts +47 -0
  132. package/dist/runtime/utils/external-message-conversion.d.ts.map +1 -0
  133. package/dist/runtime/utils/external-message-conversion.js +221 -0
  134. package/dist/runtime/utils/external-message-conversion.js.map +1 -0
  135. package/dist/runtime/utils/external-store-message.d.ts +2 -1
  136. package/dist/runtime/utils/external-store-message.d.ts.map +1 -1
  137. package/dist/runtime/utils/external-store-message.js +2 -1
  138. package/dist/runtime/utils/external-store-message.js.map +1 -1
  139. package/dist/runtime/utils/message-repository-session.d.ts +30 -0
  140. package/dist/runtime/utils/message-repository-session.d.ts.map +1 -0
  141. package/dist/runtime/utils/message-repository-session.js +130 -0
  142. package/dist/runtime/utils/message-repository-session.js.map +1 -0
  143. package/dist/runtime/utils/message-repository.d.ts.map +1 -1
  144. package/dist/runtime/utils/message-repository.js +30 -22
  145. package/dist/runtime/utils/message-repository.js.map +1 -1
  146. package/dist/runtime/utils/pending-tool-calls.d.ts +20 -0
  147. package/dist/runtime/utils/pending-tool-calls.d.ts.map +1 -0
  148. package/dist/runtime/utils/pending-tool-calls.js +22 -0
  149. package/dist/runtime/utils/pending-tool-calls.js.map +1 -0
  150. package/dist/runtime/utils/thread-message-like.d.ts +2 -1
  151. package/dist/runtime/utils/thread-message-like.d.ts.map +1 -1
  152. package/dist/runtime/utils/thread-message-like.js.map +1 -1
  153. package/dist/runtimes/external-store/external-store-thread-list-runtime-core.d.ts +2 -5
  154. package/dist/runtimes/external-store/external-store-thread-list-runtime-core.d.ts.map +1 -1
  155. package/dist/runtimes/external-store/external-store-thread-list-runtime-core.js +3 -10
  156. package/dist/runtimes/external-store/external-store-thread-list-runtime-core.js.map +1 -1
  157. package/dist/runtimes/external-store/external-store-thread-runtime-core.d.ts +19 -1
  158. package/dist/runtimes/external-store/external-store-thread-runtime-core.d.ts.map +1 -1
  159. package/dist/runtimes/external-store/external-store-thread-runtime-core.js +124 -20
  160. package/dist/runtimes/external-store/external-store-thread-runtime-core.js.map +1 -1
  161. package/dist/runtimes/inert/InertThreadRuntimeCore.d.ts +102 -0
  162. package/dist/runtimes/inert/InertThreadRuntimeCore.d.ts.map +1 -0
  163. package/dist/runtimes/inert/InertThreadRuntimeCore.js +156 -0
  164. package/dist/runtimes/inert/InertThreadRuntimeCore.js.map +1 -0
  165. package/dist/runtimes/local/local-thread-runtime-core.d.ts +3 -1
  166. package/dist/runtimes/local/local-thread-runtime-core.d.ts.map +1 -1
  167. package/dist/runtimes/local/local-thread-runtime-core.js +45 -8
  168. package/dist/runtimes/local/local-thread-runtime-core.js.map +1 -1
  169. package/dist/runtimes/readonly/ReadonlyThreadRuntimeCore.d.ts +12 -60
  170. package/dist/runtimes/readonly/ReadonlyThreadRuntimeCore.d.ts.map +1 -1
  171. package/dist/runtimes/readonly/ReadonlyThreadRuntimeCore.js +10 -145
  172. package/dist/runtimes/readonly/ReadonlyThreadRuntimeCore.js.map +1 -1
  173. package/dist/runtimes/remote-thread-list/adapter-changed.d.ts +9 -0
  174. package/dist/runtimes/remote-thread-list/adapter-changed.d.ts.map +1 -0
  175. package/dist/runtimes/remote-thread-list/adapter-changed.js +13 -0
  176. package/dist/runtimes/remote-thread-list/adapter-changed.js.map +1 -0
  177. package/dist/runtimes/remote-thread-list/empty-thread-core.d.ts.map +1 -1
  178. package/dist/runtimes/remote-thread-list/empty-thread-core.js +16 -155
  179. package/dist/runtimes/remote-thread-list/empty-thread-core.js.map +1 -1
  180. package/dist/runtimes/remote-thread-list/optimistic-state.d.ts +2 -0
  181. package/dist/runtimes/remote-thread-list/optimistic-state.d.ts.map +1 -1
  182. package/dist/runtimes/remote-thread-list/optimistic-state.js +11 -0
  183. package/dist/runtimes/remote-thread-list/optimistic-state.js.map +1 -1
  184. package/dist/runtimes/remote-thread-list/remote-thread-state.d.ts +12 -1
  185. package/dist/runtimes/remote-thread-list/remote-thread-state.d.ts.map +1 -1
  186. package/dist/runtimes/remote-thread-list/remote-thread-state.js +77 -1
  187. package/dist/runtimes/remote-thread-list/remote-thread-state.js.map +1 -1
  188. package/dist/runtimes/remote-thread-list/types.d.ts +3 -0
  189. package/dist/runtimes/remote-thread-list/types.d.ts.map +1 -1
  190. package/dist/runtimes/tool-invocations/ToolInvocationTracker.d.ts.map +1 -1
  191. package/dist/runtimes/tool-invocations/ToolInvocationTracker.js +2 -0
  192. package/dist/runtimes/tool-invocations/ToolInvocationTracker.js.map +1 -1
  193. package/dist/store/clients/external-thread.d.ts.map +1 -1
  194. package/dist/store/clients/external-thread.js +75 -100
  195. package/dist/store/clients/external-thread.js.map +1 -1
  196. package/dist/store/clients/single-thread-list.d.ts.map +1 -1
  197. package/dist/store/clients/single-thread-list.js +1 -1
  198. package/dist/store/clients/single-thread-list.js.map +1 -1
  199. package/dist/store/clients/suggestions.d.ts.map +1 -1
  200. package/dist/store/clients/suggestions.js +16 -7
  201. package/dist/store/clients/suggestions.js.map +1 -1
  202. package/dist/store/index.d.ts +4 -2
  203. package/dist/store/runtime-clients/handle-runtime-action.d.ts.map +1 -1
  204. package/dist/store/runtime-clients/handle-runtime-action.js +2 -0
  205. package/dist/store/runtime-clients/handle-runtime-action.js.map +1 -1
  206. package/dist/store/scope-registration.d.ts +1 -1
  207. package/dist/store/scopes/composer.d.ts +2 -1
  208. package/dist/store/scopes/composer.d.ts.map +1 -1
  209. package/dist/store/scopes/message.d.ts +1 -1
  210. package/dist/store/scopes/queue-item.d.ts +2 -9
  211. package/dist/store/scopes/queue-item.d.ts.map +1 -1
  212. package/dist/store/scopes/queue-item.js +0 -6
  213. package/dist/types/message.d.ts +8 -4
  214. package/dist/types/message.d.ts.map +1 -1
  215. package/dist/types/message.js.map +1 -1
  216. package/dist/utils/data-url.d.ts +14 -1
  217. package/dist/utils/data-url.d.ts.map +1 -1
  218. package/dist/utils/data-url.js +13 -1
  219. package/dist/utils/data-url.js.map +1 -1
  220. package/dist/utils/invoke-user-callback.d.ts +5 -0
  221. package/dist/utils/invoke-user-callback.d.ts.map +1 -0
  222. package/dist/utils/invoke-user-callback.js +19 -0
  223. package/dist/utils/invoke-user-callback.js.map +1 -0
  224. package/dist/utils/normalizePartStatus.js.map +1 -1
  225. package/dist/utils/silent-runtime-action.d.ts +6 -0
  226. package/dist/utils/silent-runtime-action.d.ts.map +1 -0
  227. package/dist/utils/silent-runtime-action.js +7 -0
  228. package/dist/utils/silent-runtime-action.js.map +1 -0
  229. package/package.json +10 -10
  230. package/src/adapters/voice.test.ts +66 -1
  231. package/src/adapters/voice.ts +8 -0
  232. package/src/internal.ts +13 -0
  233. package/src/model-context/frame/host.test.ts +152 -9
  234. package/src/model-context/frame/host.ts +23 -5
  235. package/src/model-context/frame/provider.test.ts +601 -19
  236. package/src/model-context/frame/provider.ts +158 -20
  237. package/src/model-context/frame/types.ts +5 -0
  238. package/src/model-context/interactable-composer-metadata.ts +1 -1
  239. package/src/model-context/registry.test.ts +44 -0
  240. package/src/model-context/registry.ts +13 -35
  241. package/src/react/client/InMemoryThreadList.test.tsx +49 -0
  242. package/src/react/client/InMemoryThreadList.ts +7 -1
  243. package/src/react/client/Interactables.ts +19 -178
  244. package/src/react/client/RemoteThreadList.test.ts +292 -0
  245. package/src/react/client/RemoteThreadList.ts +119 -82
  246. package/src/react/interactables-legacy/Interactables.ts +20 -177
  247. package/src/react/interactables-shared/useInteractablePersistenceQueue.test.tsx +161 -0
  248. package/src/react/interactables-shared/useInteractablePersistenceQueue.ts +206 -0
  249. package/src/react/primitive-hooks/useActionBarCopy.test.ts +15 -0
  250. package/src/react/primitive-hooks/useActionBarCopy.ts +13 -3
  251. package/src/react/primitive-hooks/useThreadIsEmpty.ts +3 -0
  252. package/src/react/primitive-hooks/useThreadIsRunning.ts +3 -0
  253. package/src/react/runtimes/RemoteThreadListHookInstanceManager.tsx +12 -0
  254. package/src/react/runtimes/RemoteThreadListThreadListRuntimeCore.republish.test.ts +87 -0
  255. package/src/react/runtimes/RemoteThreadListThreadListRuntimeCore.tsx +251 -76
  256. package/src/react/runtimes/RemoteThreadResource.ts +2 -0
  257. package/src/react/runtimes/assistant-transport/runManager.ts +4 -17
  258. package/src/react/runtimes/assistant-transport/useAssistantTransportRuntime.test.tsx +58 -0
  259. package/src/react/runtimes/assistant-transport/useAssistantTransportRuntime.ts +3 -1
  260. package/src/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.test.tsx +92 -0
  261. package/src/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.ts +40 -141
  262. package/src/react/runtimes/cloud/createCloudThreadListAdapterCreateFallback.test.ts +37 -0
  263. package/src/react/runtimes/cloud/createCloudThreadListAdapterCreateFallback.ts +18 -0
  264. package/src/react/runtimes/cloud/useCloudThreadListAdapter.test.tsx +98 -3
  265. package/src/react/runtimes/cloud/useCloudThreadListAdapter.tsx +68 -6
  266. package/src/react/runtimes/external-message-converter.test.ts +0 -14
  267. package/src/react/runtimes/external-message-converter.test.tsx +77 -0
  268. package/src/react/runtimes/external-message-converter.ts +58 -481
  269. package/src/react/runtimes/useLocalRuntime.test.tsx +5 -5
  270. package/src/runtime/api/composer-runtime.ts +1 -1
  271. package/src/runtime/api/message-runtime.test.ts +28 -1
  272. package/src/runtime/base/base-composer-runtime-core.ts +20 -40
  273. package/src/runtime/base/base-thread-runtime-core.test.ts +16 -0
  274. package/src/runtime/base/base-thread-runtime-core.ts +6 -11
  275. package/src/runtime/base/default-thread-composer-runtime-core.ts +1 -4
  276. package/src/runtime/interfaces/composer-runtime-core.ts +1 -1
  277. package/src/runtime/interfaces/thread-runtime-core.ts +1 -1
  278. package/src/runtime/internal.ts +5 -0
  279. package/src/runtime/queue/external-thread-queue-adapter.ts +1 -1
  280. package/src/runtime/queue/message-queue.ts +1 -4
  281. package/src/runtime/queue/queue-item.ts +10 -0
  282. package/src/runtime/utils/abortable-thread-load.test.ts +87 -0
  283. package/src/runtime/utils/abortable-thread-load.ts +53 -0
  284. package/src/runtime/utils/attachment-add-operations.ts +59 -0
  285. package/src/runtime/utils/auto-status.ts +33 -0
  286. package/src/runtime/utils/external-message-conversion.test.ts +113 -0
  287. package/src/runtime/utils/external-message-conversion.ts +494 -0
  288. package/src/runtime/utils/external-store-message.ts +2 -0
  289. package/src/runtime/utils/message-repository-session.test.ts +195 -0
  290. package/src/runtime/utils/message-repository-session.ts +176 -0
  291. package/src/runtime/utils/message-repository.ts +33 -22
  292. package/src/runtime/utils/pending-tool-calls.test.ts +57 -0
  293. package/src/runtime/utils/pending-tool-calls.ts +35 -0
  294. package/src/runtime/utils/thread-message-like.ts +2 -0
  295. package/src/runtimes/external-store/external-store-thread-list-runtime-core.ts +6 -14
  296. package/src/runtimes/external-store/external-store-thread-runtime-core.ts +179 -28
  297. package/src/runtimes/inert/InertThreadRuntimeCore.test.ts +253 -0
  298. package/src/runtimes/inert/InertThreadRuntimeCore.ts +232 -0
  299. package/src/runtimes/local/local-thread-runtime-core.test.ts +491 -1
  300. package/src/runtimes/local/local-thread-runtime-core.ts +86 -11
  301. package/src/runtimes/readonly/ReadonlyThreadRuntimeCore.ts +17 -209
  302. package/src/runtimes/remote-thread-list/adapter-changed.ts +10 -0
  303. package/src/runtimes/remote-thread-list/empty-thread-core.ts +28 -221
  304. package/src/runtimes/remote-thread-list/optimistic-state.test.ts +18 -0
  305. package/src/runtimes/remote-thread-list/optimistic-state.ts +13 -0
  306. package/src/runtimes/remote-thread-list/remote-thread-state.test.ts +37 -0
  307. package/src/runtimes/remote-thread-list/remote-thread-state.ts +123 -0
  308. package/src/runtimes/remote-thread-list/types.ts +4 -0
  309. package/src/runtimes/tool-invocations/EDGE_CASES.md +17 -0
  310. package/src/runtimes/tool-invocations/ToolInvocationTracker.test.ts +140 -0
  311. package/src/runtimes/tool-invocations/ToolInvocationTracker.ts +3 -0
  312. package/src/store/clients/external-thread.ts +17 -62
  313. package/src/store/clients/single-thread-list.ts +4 -1
  314. package/src/store/clients/suggestions.test.ts +31 -0
  315. package/src/store/clients/suggestions.ts +18 -19
  316. package/src/store/runtime-clients/handle-runtime-action.test.ts +40 -0
  317. package/src/store/runtime-clients/handle-runtime-action.ts +3 -0
  318. package/src/store/scopes/message.ts +1 -1
  319. package/src/store/scopes/queue-item.ts +2 -9
  320. package/src/tests/MessageRepository.test.ts +125 -0
  321. package/src/tests/RemoteThreadListThreadListRuntimeCore-errors.test.ts +2 -2
  322. package/src/tests/RemoteThreadListThreadListRuntimeCore-load-race.test.ts +194 -0
  323. package/src/tests/RemoteThreadListThreadListRuntimeCore-loadMore.test.ts +8 -6
  324. package/src/tests/RemoteThreadListThreadListRuntimeCore-title-race.test.ts +158 -0
  325. package/src/tests/empty-thread-core.test.ts +6 -0
  326. package/src/tests/external-store-thread-runtime-core-adapter.test.ts +184 -0
  327. package/src/tests/external-store-thread-runtime-core.test.ts +642 -0
  328. package/src/tests/external-thread-attachments.test.tsx +173 -0
  329. package/src/tests/external-thread-isEmpty.test.tsx +100 -0
  330. package/src/tests/remote-thread-list-adapter-switch.test.ts +383 -0
  331. package/src/tests/single-thread-list-item.test.tsx +47 -0
  332. package/src/tests/thread-message-like.test.ts +39 -1
  333. package/src/tests/useRemoteThreadListRuntime-controlled.test.tsx +67 -0
  334. package/src/types/message.ts +9 -4
  335. package/src/utils/data-url.test.ts +52 -1
  336. package/src/utils/data-url.ts +21 -0
  337. package/src/utils/invoke-user-callback.test.ts +82 -0
  338. package/src/utils/invoke-user-callback.ts +31 -0
  339. package/src/utils/normalizePartStatus.ts +1 -1
  340. package/src/utils/silent-runtime-action.ts +6 -0
  341. package/dist/store/scopes/queue-item.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"local-thread-runtime-core.js","names":["fromThreadMessageLike","generateId","ChatModelAdapter","ChatModelRunResult","shouldContinue","LocalRuntimeOptionsBase","consumeSuggestionResult","AddToolResultOptions","ResumeToolCallOptions","RespondToToolApprovalOptions","ThreadSuggestion","ThreadRuntimeCore","StartRunConfig","ResumeRunConfig","BaseThreadRuntimeCore","AppendMessage","ThreadAssistantMessage","RunConfig","MessageNotSentError","toAssistantError","ModelContextProvider","createMessageQueue","MessageQueueController","QueuePlacement","EMPTY_QUEUE_ITEMS","QueueItemState","captureThreadRuntimeGeneration","invalidateThreadRuntime","isThreadRuntimeGenerationCurrent","AbortError","Error","name","detach","constructor","message","LocalThreadRuntimeCore","capabilities","switchToBranch","switchBranchDuringRun","edit","delete","reload","refetchThread","cancel","unstable_copy","speech","dictation","voice","attachments","feedback","queue","abortController","AbortController","_queue","_queueRunInFlight","_activeRun","cancelled","_runGeneration","_historyWrites","Map","Promise","_chainHistoryWrite","id","write","next","get","resolve","then","stored","set","_persistPausedMessage","parentId","status","type","history","_options","adapters","update","bind","item","runConfig","_lastRunConfig","catch","isDisabled","isSendDisabled","_isLoading","isLoading","_suggestions","_suggestionsController","suggestions","contextProvider","options","__internal_setOptions","_getThreadId","__internal_setGetThreadId","getThreadId","_getInitializePromise","__internal_setGetInitializePromise","getPromise","extras","undefined","previousHistory","hasUpdates","canSpeak","canDictate","canVoice","canAttach","canFeedback","canDelete","canQueue","unstable_enableMessageQueue","run","generation","_runAppend","messages","at","finally","notifyIdle","subscribe","_notifySubscribers","_loadRequested","_loadPromise","length","__internal_load","error","console","promise","load","repo","repository","import","ensureInitialized","resume","unstable_resume","startRun","headId","sourceId","append","isTail","willRun","role","steer","adapter","enqueue","unstable_queueClearOnRewind","clear","getQueueItems","items","getSteerQueueItems","steerItems","moveQueueItem","queueItemId","placement","move","removeQueueItem","remove","_rollbackAppend","messageId","deleteMessage","rawMessage","enrichAppendMetadata","newMessage","reason","addOrUpdateMessage","initPromise","notSent","cause","historyWrite","runResult","historyResult","allSettled","resetHead","getMessages","messageIndex","findIndex","m","resumeRun","stream","startConfig","exportExternalState","importExternalState","unstable_notifySessionReset","runCallback","content","metadata","unstable_state","state","unstable_annotations","unstable_data","steps","custom","createdAt","Date","_runLoop","_notifyEventSubscribers","alreadyPersisted","active","notifyBusy","abort","performRoundtrip","unstable_humanToolNames","queueMicrotask","suggestion","signal","promiseOrGenerator","generate","onUpdate","r","initialContent","initialAnnotations","initialData","initialSteps","initialCustom","updateMessage","Partial","newSteps","newAnnotations","newData","annotations","data","timing","maxSteps","unstable_composerMetadata","_","context","getModelContext","chatModel","abortSignal","threadId","unstable_assistantMessageId","unstable_threadId","unstable_parentId","unstable_getMessage","Symbol","asyncIterator","aborted","e","isTerminal","isPausing","cancelRun","unstable_queueClearOnCancel","notifyCancelled","addToolResult","toolCallId","result","isError","artifact","messageData","getMessage","added","found","newContent","map","c","resumeToolCall","respondToToolApproval","approvalId","approved","optionId","findLast","some","approval","target","find","resolution","targetApproval"],"sources":["../../../src/runtimes/local/local-thread-runtime-core.ts"],"sourcesContent":["import { fromThreadMessageLike } from \"../../runtime/utils/thread-message-like\";\nimport { generateId } from \"../../utils/id\";\nimport type {\n ChatModelAdapter,\n ChatModelRunResult,\n} from \"../../runtime/utils/chat-model-adapter\";\nimport { shouldContinue } from \"./should-continue\";\nimport type { LocalRuntimeOptionsBase } from \"./local-runtime-options\";\nimport { consumeSuggestionResult } from \"../../adapters/suggestion\";\nimport type {\n AddToolResultOptions,\n ResumeToolCallOptions,\n RespondToToolApprovalOptions,\n ThreadSuggestion,\n ThreadRuntimeCore,\n StartRunConfig,\n ResumeRunConfig,\n} from \"../../runtime/interfaces/thread-runtime-core\";\nimport { BaseThreadRuntimeCore } from \"../../runtime/base/base-thread-runtime-core\";\nimport type {\n AppendMessage,\n ThreadAssistantMessage,\n} from \"../../types/message\";\nimport type { RunConfig } from \"../../types/message\";\nimport { MessageNotSentError, toAssistantError } from \"../../types/error\";\nimport type { ModelContextProvider } from \"../../model-context/types\";\nimport {\n createMessageQueue,\n type MessageQueueController,\n} from \"../../runtime/queue/message-queue\";\nimport type { QueuePlacement } from \"../../runtime/queue/external-thread-queue-adapter\";\nimport {\n EMPTY_QUEUE_ITEMS,\n type QueueItemState,\n} from \"../../store/scopes/queue-item\";\nimport {\n captureThreadRuntimeGeneration,\n invalidateThreadRuntime,\n isThreadRuntimeGenerationCurrent,\n} from \"../../runtime/utils/thread-runtime-lifecycle\";\n\nclass AbortError extends Error {\n override name = \"AbortError\";\n detach: boolean;\n\n constructor(detach: boolean, message?: string) {\n super(message);\n this.detach = detach;\n }\n}\n\nexport class LocalThreadRuntimeCore\n extends BaseThreadRuntimeCore\n implements ThreadRuntimeCore\n{\n public readonly capabilities = {\n switchToBranch: true,\n switchBranchDuringRun: true,\n edit: true,\n delete: false,\n reload: true,\n refetchThread: false,\n cancel: true,\n unstable_copy: true,\n speech: false,\n dictation: false,\n voice: false,\n attachments: false,\n feedback: false,\n queue: false,\n };\n\n private abortController: AbortController | null = null;\n\n private _queue: MessageQueueController | null = null;\n private _queueRunInFlight = false;\n private _activeRun: { cancelled: boolean } | null = null;\n private _runGeneration = 0;\n\n private _historyWrites = new Map<string, Promise<void>>();\n\n // Writes for one message id must land in issue order; an earlier paused\n // snapshot arriving after the terminal write would resurrect the pause.\n private _chainHistoryWrite(\n id: string,\n write: () => Promise<void>,\n ): Promise<void> {\n const next = (this._historyWrites.get(id) ?? Promise.resolve()).then(\n write,\n write,\n );\n const stored = next.then(\n () => {},\n () => {},\n );\n this._historyWrites.set(id, stored);\n void stored.then(() => {\n if (this._historyWrites.get(id) === stored) {\n this._historyWrites.delete(id);\n }\n });\n return next;\n }\n\n // A decision recorded on a still-paused message must reach history before\n // the run resumes, or a refresh would restore the message without it.\n private _persistPausedMessage(\n parentId: string | null,\n message: ThreadAssistantMessage,\n ) {\n if (message.status?.type !== \"requires-action\") return;\n const history = this._options.adapters.history;\n if (!history?.update) return;\n const update = history.update.bind(history);\n const item = { parentId, message, runConfig: this._lastRunConfig };\n this._chainHistoryWrite(message.id, () => update(item)).catch(() => {});\n }\n\n public readonly isDisabled = false;\n public readonly isSendDisabled = false;\n\n private _isLoading = false;\n public get isLoading() {\n return this._isLoading;\n }\n\n private _suggestions: readonly ThreadSuggestion[] = [];\n private _suggestionsController: AbortController | null = null;\n public get suggestions(): readonly ThreadSuggestion[] {\n return this._suggestions;\n }\n\n public get adapters() {\n return this._options.adapters;\n }\n\n constructor(\n contextProvider: ModelContextProvider,\n options: LocalRuntimeOptionsBase,\n ) {\n super(contextProvider);\n this.__internal_setOptions(options);\n }\n\n private _options!: LocalRuntimeOptionsBase;\n\n private _lastRunConfig: RunConfig = {};\n\n private _getThreadId?: () => string | undefined;\n\n public __internal_setGetThreadId(getThreadId: () => string | undefined) {\n this._getThreadId = getThreadId;\n }\n\n private _getInitializePromise?: () => Promise<unknown> | undefined;\n\n public __internal_setGetInitializePromise(\n getPromise: () => Promise<unknown> | undefined,\n ) {\n this._getInitializePromise = getPromise;\n }\n\n public get extras() {\n return undefined;\n }\n\n public __internal_setOptions(options: LocalRuntimeOptionsBase) {\n if (this._options === options) return;\n\n const previousHistory = this._options?.adapters.history;\n this._options = options;\n\n let hasUpdates = false;\n\n const canSpeak = options.adapters?.speech !== undefined;\n if (this.capabilities.speech !== canSpeak) {\n this.capabilities.speech = canSpeak;\n hasUpdates = true;\n }\n\n const canDictate = options.adapters?.dictation !== undefined;\n if (this.capabilities.dictation !== canDictate) {\n this.capabilities.dictation = canDictate;\n hasUpdates = true;\n }\n\n const canVoice = options.adapters?.voice !== undefined;\n if (this.capabilities.voice !== canVoice) {\n this.capabilities.voice = canVoice;\n hasUpdates = true;\n }\n\n const canAttach = options.adapters?.attachments !== undefined;\n if (this.capabilities.attachments !== canAttach) {\n this.capabilities.attachments = canAttach;\n hasUpdates = true;\n }\n\n const canFeedback = options.adapters?.feedback !== undefined;\n if (this.capabilities.feedback !== canFeedback) {\n this.capabilities.feedback = canFeedback;\n hasUpdates = true;\n }\n\n const canDelete = options.adapters?.history?.delete !== undefined;\n if (this.capabilities.delete !== canDelete) {\n this.capabilities.delete = canDelete;\n hasUpdates = true;\n }\n\n const canQueue = options.unstable_enableMessageQueue === true;\n if (canQueue && !this._queue) {\n this._queue = createMessageQueue({\n run: (message) => {\n // release the queue when the dispatch settles, even if it rejects\n // before reaching startRun's finally, so a failure can't deadlock it\n this._queueRunInFlight = true;\n const generation = this._runGeneration;\n // the tail may have moved since the message was enqueued\n void this._runAppend({\n ...message,\n parentId: this.messages.at(-1)?.id ?? null,\n })\n .finally(() => {\n this._queueRunInFlight = false;\n // a dispatch that failed before starting a run settles here;\n // runs that did start release from _runLoop\n if (this._runGeneration === generation) this._queue?.notifyIdle();\n })\n .catch(() => {});\n },\n });\n this._queue.subscribe(() => this._notifySubscribers());\n } else if (!canQueue && this._queue) {\n this._queue = null;\n }\n if (this.capabilities.queue !== canQueue) {\n this.capabilities.queue = canQueue;\n hasUpdates = true;\n }\n\n if (hasUpdates) this._notifySubscribers();\n\n if (\n this._loadRequested &&\n !this._loadPromise &&\n !previousHistory &&\n options.adapters.history &&\n this.messages.length === 0\n ) {\n void this.__internal_load().catch((error: unknown) => {\n console.error(\n \"[assistant-ui] local thread history load failed:\",\n error,\n );\n });\n }\n }\n\n private _loadPromise: Promise<void> | undefined;\n private _loadRequested = false;\n public __internal_load() {\n this._loadRequested = true;\n if (this._loadPromise) return this._loadPromise;\n if (!this.adapters.history) return Promise.resolve();\n\n const promise = this.adapters.history.load();\n\n this._isLoading = true;\n this._notifySubscribers();\n\n this._loadPromise = promise\n .then((repo) => {\n if (!repo) return;\n this.repository.import(repo);\n if (repo.messages.length > 0) {\n this.ensureInitialized();\n }\n this._notifySubscribers();\n\n const resume = this.adapters.history?.resume?.bind(\n this.adapters.history,\n );\n if (repo.unstable_resume && resume) {\n this.startRun(\n {\n parentId: this.repository.headId,\n sourceId: this.repository.headId,\n runConfig: this._lastRunConfig,\n },\n resume,\n ).catch(() => {});\n }\n })\n .finally(() => {\n this._isLoading = false;\n this._notifySubscribers();\n });\n\n return this._loadPromise;\n }\n\n public async append(message: AppendMessage): Promise<void> {\n const isTail = message.parentId === (this.messages.at(-1)?.id ?? null);\n const willRun = message.startRun ?? message.role === \"user\";\n if (this._queue && willRun && isTail) {\n if (message.steer ?? this._queueRunInFlight)\n this._queue.adapter.steer(message);\n else this._queue.adapter.enqueue(message);\n return;\n }\n if (\n this._queue &&\n !isTail &&\n (this._options.unstable_queueClearOnRewind ?? true)\n )\n this._queue.clear();\n return this._runAppend(message);\n }\n\n public getQueueItems(): readonly QueueItemState[] {\n // Reads can arrive during base-thread construction, before the queue field\n // is assigned, so guard against the unset field.\n return this._queue?.adapter.items ?? EMPTY_QUEUE_ITEMS;\n }\n\n public getSteerQueueItems(): readonly QueueItemState[] {\n return this._queue?.adapter.steerItems ?? EMPTY_QUEUE_ITEMS;\n }\n\n public moveQueueItem(queueItemId: string, placement: QueuePlacement): void {\n this._queue?.adapter.move(queueItemId, placement);\n }\n\n public removeQueueItem(queueItemId: string): void {\n this._queue?.adapter.remove(queueItemId);\n }\n\n private _rollbackAppend(messageId: string) {\n try {\n this.repository.deleteMessage(messageId);\n } catch {\n return;\n }\n this._notifySubscribers();\n }\n\n private async _runAppend(rawMessage: AppendMessage): Promise<void> {\n // Stamped here rather than in `append` so a queued message is gated after\n // the flush re-pointed its parentId at the current tail.\n const generation = captureThreadRuntimeGeneration(this);\n const message = this.enrichAppendMetadata(rawMessage);\n this.ensureInitialized();\n\n const newMessage = fromThreadMessageLike(message, generateId(), {\n type: \"complete\",\n reason: \"unknown\",\n });\n this.repository.addOrUpdateMessage(message.parentId, newMessage);\n this._notifySubscribers();\n\n // Initialization only gates the history write and the run; the message\n // is already on screen. A failed barrier rolls the optimistic message\n // back and rejects as an unsent message so the composer restores the\n // draft; a thread invalidated mid-wait rolls back silently.\n try {\n const initPromise = this._getInitializePromise?.();\n if (initPromise) {\n await initPromise;\n }\n } catch (error) {\n this._rollbackAppend(newMessage.id);\n if (!isThreadRuntimeGenerationCurrent(this, generation)) return;\n const notSent = new MessageNotSentError();\n notSent.cause = error;\n throw notSent;\n }\n if (!isThreadRuntimeGenerationCurrent(this, generation)) {\n this._rollbackAppend(newMessage.id);\n return;\n }\n const historyWrite = this._options.adapters.history?.append({\n parentId: message.parentId,\n message: newMessage,\n ...(message.runConfig !== undefined && { runConfig: message.runConfig }),\n });\n void historyWrite?.catch(() => {});\n\n const startRun = message.startRun ?? message.role === \"user\";\n if (startRun) {\n const [runResult, historyResult] = await Promise.allSettled([\n this.startRun({\n parentId: newMessage.id,\n sourceId: message.sourceId,\n runConfig: message.runConfig ?? {},\n }),\n historyWrite,\n ]);\n if (runResult.status === \"rejected\") throw runResult.reason;\n if (historyResult.status === \"rejected\") throw historyResult.reason;\n } else {\n this.repository.resetHead(newMessage.id);\n this._notifySubscribers();\n await historyWrite;\n }\n }\n\n public async deleteMessage(messageId: string): Promise<void> {\n const adapter = this._options.adapters.history;\n if (!adapter?.delete)\n throw new Error(\"Runtime does not support deleting messages.\");\n\n const messages = this.repository.getMessages();\n const messageIndex = messages.findIndex((m) => m.id === messageId);\n if (messageIndex === -1) throw new Error(\"Message not found.\");\n\n const message = messages[messageIndex]!;\n const parentId = messages[messageIndex - 1]?.id ?? null;\n const items = [{ parentId, message }];\n\n await adapter.delete(items);\n\n this.repository.deleteMessage(messageId);\n this._notifySubscribers();\n }\n\n public resumeRun({ stream, ...startConfig }: ResumeRunConfig): Promise<void> {\n if (!stream)\n throw new Error(\"You must pass a stream parameter to resume runs.\");\n return this.startRun(startConfig, stream);\n }\n\n public exportExternalState(): any {\n throw new Error(\"Runtime does not support exporting external states.\");\n }\n\n public importExternalState(): void {\n throw new Error(\"Runtime does not support importing external states.\");\n }\n\n public unstable_notifySessionReset(): void {\n throw new Error(\"Runtime does not support resetting sessions.\");\n }\n\n public async startRun(\n { parentId, runConfig }: StartRunConfig,\n runCallback?: ChatModelAdapter[\"run\"],\n ): Promise<void> {\n this.ensureInitialized();\n\n // add assistant message\n const id = generateId();\n const message: ThreadAssistantMessage = {\n id,\n role: \"assistant\",\n status: { type: \"running\" },\n content: [],\n metadata: {\n unstable_state: this.state,\n unstable_annotations: [],\n unstable_data: [],\n steps: [],\n custom: {},\n },\n createdAt: new Date(),\n };\n\n return this._runLoop(parentId, message, runConfig, runCallback);\n }\n\n private async _runLoop(\n parentId: string | null,\n message: ThreadAssistantMessage,\n runConfig: RunConfig | undefined,\n runCallback?: ChatModelAdapter[\"run\"],\n ): Promise<void> {\n this._notifyEventSubscribers(\"runStart\", {});\n\n // A run entered on a requires-action message resumes a pause an\n // update-capable adapter already holds (written at pause time or loaded).\n const alreadyPersisted =\n message.status?.type === \"requires-action\" &&\n this._options.adapters.history?.update !== undefined;\n\n const run = { cancelled: false };\n this._activeRun = run;\n this._runGeneration++;\n\n let active = false;\n try {\n // mark busy for runs not started through the queue (regenerate, resume)\n this._queue?.notifyBusy();\n this._suggestions = [];\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n this._notifySubscribers();\n\n do {\n message = await this.performRoundtrip(\n parentId,\n message,\n runConfig,\n alreadyPersisted,\n runCallback,\n );\n runCallback = undefined;\n } while (shouldContinue(message, this._options.unstable_humanToolNames));\n } finally {\n this._notifyEventSubscribers(\"runEnd\", {});\n // the settle belongs to this run only while it is still the active run\n // or was cancelled (the engine expects a cancelled run's settle); a run\n // superseded by a newer one stays silent\n active = this._activeRun === run;\n if (active) this._activeRun = null;\n if (active || run.cancelled) {\n queueMicrotask(() => this._queue?.notifyIdle());\n }\n }\n\n if (\n active &&\n this.adapters.suggestion &&\n message.status?.type !== \"requires-action\"\n ) {\n this._suggestionsController = new AbortController();\n const signal = this._suggestionsController.signal;\n const adapter = this.adapters.suggestion;\n void (async () => {\n try {\n const promiseOrGenerator = adapter.generate({\n messages: this.messages,\n signal,\n });\n await consumeSuggestionResult(promiseOrGenerator, {\n signal,\n onUpdate: (r) => {\n this._suggestions = r;\n this._notifySubscribers();\n },\n });\n } catch {}\n })();\n }\n }\n\n private async performRoundtrip(\n parentId: string | null,\n message: ThreadAssistantMessage,\n runConfig: RunConfig | undefined,\n alreadyPersisted: boolean,\n runCallback?: ChatModelAdapter[\"run\"],\n ) {\n const messages = parentId ? this.repository.getMessages(parentId) : [];\n\n // abort existing run\n this.abortController?.abort();\n const abortController = new AbortController();\n this.abortController = abortController;\n\n const initialContent = message.content;\n const initialAnnotations = message.metadata?.unstable_annotations;\n const initialData = message.metadata?.unstable_data;\n const initialSteps = message.metadata?.steps;\n const initialCustom = message.metadata?.custom;\n const updateMessage = (m: Partial<ChatModelRunResult>) => {\n const newSteps = m.metadata?.steps;\n const steps = newSteps\n ? [...(initialSteps ?? []), ...newSteps]\n : undefined;\n\n const newAnnotations = m.metadata?.unstable_annotations;\n const newData = m.metadata?.unstable_data;\n const annotations = newAnnotations\n ? [...(initialAnnotations ?? []), ...newAnnotations]\n : undefined;\n const data = newData ? [...(initialData ?? []), ...newData] : undefined;\n\n message = {\n ...message,\n ...(m.content\n ? { content: [...initialContent, ...(m.content ?? [])] }\n : undefined),\n status: m.status ?? message.status,\n ...(m.metadata\n ? {\n metadata: {\n ...message.metadata,\n ...(m.metadata.unstable_state !== undefined\n ? { unstable_state: m.metadata.unstable_state }\n : undefined),\n ...(annotations\n ? { unstable_annotations: annotations }\n : undefined),\n ...(data ? { unstable_data: data } : undefined),\n ...(steps ? { steps } : undefined),\n ...(m.metadata?.timing\n ? { timing: m.metadata.timing }\n : undefined),\n ...(m.metadata?.custom\n ? {\n custom: {\n ...(initialCustom ?? {}),\n ...m.metadata.custom,\n },\n }\n : undefined),\n },\n }\n : undefined),\n };\n this.repository.addOrUpdateMessage(parentId, message);\n this._notifySubscribers();\n };\n\n const maxSteps = this._options.maxSteps ?? 2;\n\n try {\n const steps = message.metadata?.steps?.length ?? 0;\n if (steps >= maxSteps) {\n updateMessage({\n status: {\n type: \"incomplete\",\n reason: \"tool-calls\",\n },\n });\n return message;\n }\n\n updateMessage({\n status: {\n type: \"running\",\n },\n });\n\n // Switch to the new message branch right after adding it for the first time\n this.repository.resetHead(message.id);\n this._notifySubscribers();\n\n this._lastRunConfig = runConfig ?? {};\n // unstable_composerMetadata is composer-only (stamped onto the outgoing\n // message); never expose it to the chat-model adapter's run context.\n const { unstable_composerMetadata: _, ...context } =\n this.getModelContext();\n\n runCallback =\n runCallback ??\n this.adapters.chatModel.run.bind(this.adapters.chatModel);\n\n const abortSignal = abortController.signal;\n const threadId = this._getThreadId?.();\n const promiseOrGenerator = runCallback({\n messages,\n runConfig: this._lastRunConfig,\n abortSignal,\n context,\n unstable_assistantMessageId: message.id,\n unstable_threadId: threadId,\n unstable_parentId: parentId,\n unstable_getMessage() {\n return message;\n },\n });\n\n // handle async iterator for streaming results\n if (Symbol.asyncIterator in promiseOrGenerator) {\n for await (const r of promiseOrGenerator) {\n if (abortSignal.aborted) {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n break;\n }\n\n updateMessage(r);\n }\n } else {\n updateMessage(await promiseOrGenerator);\n }\n\n if (message.status.type === \"running\") {\n updateMessage({\n status: abortSignal.aborted\n ? { type: \"incomplete\", reason: \"cancelled\" }\n : { type: \"complete\", reason: \"unknown\" },\n });\n }\n } catch (e) {\n if (e instanceof AbortError) {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n } else if (e instanceof Error && e.name === \"AbortError\") {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n } else {\n updateMessage({\n status: {\n type: \"incomplete\",\n reason: \"error\",\n error: toAssistantError(e),\n },\n });\n\n throw e;\n }\n } finally {\n if (this.abortController === abortController) {\n this.abortController = null;\n }\n\n const history = this._options.adapters.history;\n const item = {\n parentId,\n message,\n runConfig: this._lastRunConfig,\n };\n const isTerminal =\n message.status.type === \"complete\" ||\n message.status.type === \"incomplete\";\n const isPausing =\n message.status.type === \"requires-action\" &&\n !shouldContinue(message, this._options.unstable_humanToolNames);\n\n // Pauses are written only for adapters that can rewrite the entry later;\n // an append-only adapter would strand a half-finished run in history.\n if (isTerminal || (isPausing && history?.update)) {\n const write =\n alreadyPersisted && history?.update\n ? history.update.bind(history)\n : history?.append.bind(history);\n if (write) {\n await this._chainHistoryWrite(message.id, () => write(item));\n }\n }\n }\n return message;\n }\n\n public detach() {\n invalidateThreadRuntime(this);\n // drop the queue so pending items cannot dispatch on a detached thread\n this._queue = null;\n const error = new AbortError(true);\n this.abortController?.abort(error);\n this.abortController = null;\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n }\n\n public cancelRun() {\n if (this._queue) {\n if (this._options.unstable_queueClearOnCancel ?? true) {\n this._queue.clear();\n } else {\n this._queue.notifyCancelled();\n if (this._activeRun) this._activeRun.cancelled = true;\n }\n }\n const error = new AbortError(false);\n this.abortController?.abort(error);\n this.abortController = null;\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n }\n\n public addToolResult({\n messageId,\n toolCallId,\n result,\n isError,\n artifact,\n }: AddToolResultOptions) {\n const messageData = this.repository.getMessage(messageId);\n const { parentId } = messageData;\n let { message } = messageData;\n\n if (message.role !== \"assistant\")\n throw new Error(\"Tried to add tool result to non-assistant message\");\n\n let added = false;\n let found = false;\n const newContent = message.content.map((c) => {\n if (c.type !== \"tool-call\") return c;\n if (c.toolCallId !== toolCallId) return c;\n found = true;\n if (c.result === undefined) added = true;\n return {\n ...c,\n result,\n artifact,\n isError,\n };\n });\n\n if (!found)\n throw new Error(\"Tried to add tool result to non-existing tool call\");\n\n message = {\n ...message,\n content: newContent,\n };\n this.repository.addOrUpdateMessage(parentId, message);\n this._notifySubscribers();\n\n // a result may arrive mid-run or on a non-head message; the resume\n // intentionally aborts any in-flight run, unlike respondToToolApproval\n if (\n added &&\n shouldContinue(message, this._options.unstable_humanToolNames)\n ) {\n this._runLoop(parentId, message, this._lastRunConfig).catch(() => {});\n } else if (added) {\n this._persistPausedMessage(parentId, message);\n }\n }\n\n public resumeToolCall(_options: ResumeToolCallOptions) {\n throw new Error(\n \"Local runtime does not support resuming tool calls. For human-in-the-loop tools, list the tool in unstable_humanToolNames and complete the call with addToolResult.\",\n );\n }\n\n public respondToToolApproval({\n approvalId,\n approved,\n optionId,\n reason,\n }: RespondToToolApprovalOptions) {\n let message = this.repository\n .getMessages()\n .findLast(\n (m): m is ThreadAssistantMessage =>\n m.role === \"assistant\" &&\n m.content.some(\n (c) => c.type === \"tool-call\" && c.approval?.id === approvalId,\n ),\n );\n\n if (!message)\n throw new Error(\"Tried to respond to a non-existing tool approval\");\n\n if (this.abortController !== null)\n throw new Error(\n \"Tried to respond to a tool approval while a run is in progress\",\n );\n\n if (message.status?.type !== \"requires-action\")\n throw new Error(\n \"Tried to respond to a tool approval on a message whose status is not requires-action\",\n );\n\n const target = message.content.find(\n (c) => c.type === \"tool-call\" && c.approval?.id === approvalId,\n );\n if (target?.type !== \"tool-call\" || !target.approval)\n throw new Error(\"Tried to respond to a non-existing tool approval\");\n if (target.approval.resolution !== undefined)\n throw new Error(\n \"Tried to respond to a tool approval that was cancelled or expired\",\n );\n if (target.approval.approved !== undefined)\n throw new Error(\"Tried to respond to an already decided tool approval\");\n\n const targetApproval = target.approval;\n const newContent = message.content.map((c) => {\n if (c !== target) return c;\n const approval = {\n ...targetApproval,\n approved,\n ...(optionId != null && { optionId }),\n ...(reason != null && { reason }),\n };\n if (approved) return { ...c, approval };\n return {\n ...c,\n approval,\n result: { error: reason || \"Tool approval denied\" },\n isError: true,\n };\n });\n\n message = { ...message, content: newContent };\n const { parentId } = this.repository.getMessage(message.id);\n this.repository.addOrUpdateMessage(parentId, message);\n this._notifySubscribers();\n\n if (\n this.repository.headId === message.id &&\n shouldContinue(message, this._options.unstable_humanToolNames)\n ) {\n this._runLoop(parentId, message, this._lastRunConfig).catch(() => {});\n } else {\n this._persistPausedMessage(parentId, message);\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAyCA,IAAM6B,aAAN,cAAyBC,MAAM;CAC7B,OAAgB;CAChBE;CAEAC,YAAYD,QAAiBE,SAAkB;EAC7C,MAAMA,OAAO;EACb,KAAKF,SAASA;CAChB;AACF;AAEA,IAAaG,yBAAb,cACUrB,sBAEV;CACE,eAA+B;EAC7BuB,gBAAgB;EAChBC,uBAAuB;EACvBC,MAAM;EACNC,QAAQ;EACRC,QAAQ;EACRC,eAAe;EACfC,QAAQ;EACRC,eAAe;EACfC,QAAQ;EACRC,WAAW;EACXC,OAAO;EACPC,aAAa;EACbC,UAAU;EACVC,OAAO;CACT;CAEA,kBAAkD;CAElD,SAAgD;CAChD,oBAA4B;CAC5B,aAAoD;CACpD,iBAAyB;CAEzB,iCAAyB,IAAIS,IAA2B;CAIxD,mBACEG,IACAC,OACe;EACf,MAAMC,QAAQ,KAAKN,eAAeO,IAAIH,EAAE,KAAKF,QAAQM,QAAQ,EAAA,CAAGC,KAC9DJ,OACAA,KACF;EACA,MAAMK,SAASJ,KAAKG,WACZ,CAAC,SACD,CAAC,CACT;EACA,KAAKT,eAAeW,IAAIP,IAAIM,MAAM;EAClC,OAAYD,WAAW;GACrB,IAAI,KAAKT,eAAeO,IAAIH,EAAE,MAAMM,QAClC,KAAKV,eAAelB,OAAOsB,EAAE;EAEjC,CAAC;EACD,OAAOE;CACT;CAIA,sBACEO,UACArC,SACA;EACA,IAAIA,QAAQsC,QAAQC,SAAS,mBAAmB;EAChD,MAAMC,UAAU,KAAKC,SAASC,SAASF;EACvC,IAAI,CAACA,SAASG,QAAQ;EACtB,MAAMA,SAASH,QAAQG,OAAOC,KAAKJ,OAAO;EAC1C,MAAMK,OAAO;GAAER;GAAUrC;GAAS8C,WAAW,KAAKC;EAAe;EACjE,KAAKpB,mBAAmB3B,QAAQ4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7D,KAAKP,SAAS1H,UAAUrC,SAAS,KAAK+C,cAAc,CAAC,CAACC,YAAY,CAAC,CAAC;OAEpE,KAAKZ,sBAAsBC,UAAUrC,OAAO;CAEhD;AACF"}
1
+ {"version":3,"file":"local-thread-runtime-core.js","names":["fromThreadMessageLike","generateId","ChatModelAdapter","ChatModelRunResult","shouldContinue","getAutoStatus","ExportedMessageRepository","LocalRuntimeOptionsBase","consumeSuggestionResult","AddToolResultOptions","ResumeToolCallOptions","RespondToToolApprovalOptions","ThreadSuggestion","ThreadRuntimeCore","StartRunConfig","ResumeRunConfig","BaseThreadRuntimeCore","AppendMessage","ThreadAssistantMessage","RunConfig","ThreadMessage","MessageNotSentError","toAssistantError","ModelContextProvider","createMessageQueue","MessageQueueController","QueuePlacement","EMPTY_QUEUE_ITEMS","QueueItemState","captureThreadRuntimeGeneration","invalidateThreadRuntime","isThreadRuntimeGenerationCurrent","AbortError","Error","name","detach","constructor","message","withLocalPauseReason","role","status","type","reason","content","some","c","result","undefined","interrupt","withLocalPauseReasons","data","messages","map","item","LocalThreadRuntimeCore","capabilities","switchToBranch","switchBranchDuringRun","edit","delete","reload","refetchThread","cancel","unstable_copy","speech","dictation","voice","attachments","feedback","queue","abortController","AbortController","_queue","_queueRunInFlight","_activeRun","cancelled","_runGeneration","_historyWrites","Map","Promise","_chainHistoryWrite","id","write","next","get","resolve","then","stored","set","_persistPausedMessage","parentId","history","_options","adapters","update","bind","runConfig","_lastRunConfig","catch","isDisabled","isSendDisabled","_isLoading","isLoading","_suggestions","_suggestionsController","suggestions","contextProvider","options","__internal_setOptions","_getThreadId","__internal_setGetThreadId","getThreadId","_getInitializePromise","__internal_setGetInitializePromise","getPromise","extras","previousHistory","hasUpdates","canSpeak","canDictate","canVoice","canAttach","canFeedback","canDelete","canQueue","unstable_enableMessageQueue","run","generation","_runAppend","at","finally","notifyIdle","subscribe","_notifySubscribers","_loadRequested","_loadPromise","length","__internal_load","error","console","promise","load","repo","repository","import","ensureInitialized","resume","unstable_resume","startRun","headId","sourceId","append","isTail","willRun","steer","adapter","enqueue","unstable_queueClearOnRewind","clear","getQueueItems","items","getSteerQueueItems","steerItems","moveQueueItem","queueItemId","placement","move","removeQueueItem","remove","_rollbackAppend","messageId","deleteMessage","rawMessage","enrichAppendMetadata","newMessage","addOrUpdateMessage","initPromise","notSent","cause","historyWrite","runResult","historyResult","allSettled","resetHead","getMessages","messageIndex","findIndex","m","resumeRun","stream","startConfig","exportExternalState","importExternalState","unstable_notifySessionReset","runCallback","metadata","unstable_state","state","unstable_annotations","unstable_data","steps","custom","createdAt","Date","_runLoop","_notifyEventSubscribers","alreadyPersisted","active","notifyBusy","abort","performRoundtrip","unstable_humanToolNames","queueMicrotask","suggestion","signal","promiseOrGenerator","generate","onUpdate","r","initialContent","initialAnnotations","initialData","initialSteps","initialCustom","hasStoredMessage","getMessage","ownsMessage","updateMessage","Partial","newSteps","newAnnotations","newData","annotations","timing","maxSteps","unstable_composerMetadata","_","context","getModelContext","chatModel","abortSignal","shouldCancelMessage","aborted","threadId","unstable_assistantMessageId","unstable_threadId","unstable_parentId","unstable_getMessage","Symbol","asyncIterator","e","isTerminal","isPausing","cancelRun","unstable_queueClearOnCancel","notifyCancelled","addToolResult","toolCallId","isError","artifact","messageData","added","found","newContent","resumeToolCall","respondToToolApproval","approvalId","approved","optionId","findLast","approval","target","find","resolution","targetApproval"],"sources":["../../../src/runtimes/local/local-thread-runtime-core.ts"],"sourcesContent":["import { fromThreadMessageLike } from \"../../runtime/utils/thread-message-like\";\nimport { generateId } from \"../../utils/id\";\nimport type {\n ChatModelAdapter,\n ChatModelRunResult,\n} from \"../../runtime/utils/chat-model-adapter\";\nimport { shouldContinue } from \"./should-continue\";\nimport { getAutoStatus } from \"../../runtime/utils/auto-status\";\nimport type { ExportedMessageRepository } from \"../../runtime/utils/message-repository\";\nimport type { LocalRuntimeOptionsBase } from \"./local-runtime-options\";\nimport { consumeSuggestionResult } from \"../../adapters/suggestion\";\nimport type {\n AddToolResultOptions,\n ResumeToolCallOptions,\n RespondToToolApprovalOptions,\n ThreadSuggestion,\n ThreadRuntimeCore,\n StartRunConfig,\n ResumeRunConfig,\n} from \"../../runtime/interfaces/thread-runtime-core\";\nimport { BaseThreadRuntimeCore } from \"../../runtime/base/base-thread-runtime-core\";\nimport type {\n AppendMessage,\n ThreadAssistantMessage,\n} from \"../../types/message\";\nimport type { RunConfig, ThreadMessage } from \"../../types/message\";\nimport { MessageNotSentError, toAssistantError } from \"../../types/error\";\nimport type { ModelContextProvider } from \"../../model-context/types\";\nimport {\n createMessageQueue,\n type MessageQueueController,\n} from \"../../runtime/queue/message-queue\";\nimport type { QueuePlacement } from \"../../runtime/queue/external-thread-queue-adapter\";\nimport {\n EMPTY_QUEUE_ITEMS,\n type QueueItemState,\n} from \"../../runtime/queue/queue-item\";\nimport {\n captureThreadRuntimeGeneration,\n invalidateThreadRuntime,\n isThreadRuntimeGenerationCurrent,\n} from \"../../runtime/utils/thread-runtime-lifecycle\";\n\nclass AbortError extends Error {\n override name = \"AbortError\";\n detach: boolean;\n\n constructor(detach: boolean, message?: string) {\n super(message);\n this.detach = detach;\n }\n}\n\n// `shouldContinue` resumes only on `tool-calls` and `resumeToolCall` throws, so\n// an imported `interrupt` with no interrupt payload would be stranded here.\n// Provenance cannot gate it: a repository that went through JSON has no marker.\n// The replacement stays content-derived, so a message with nothing resultless\n// left to act on lands on `complete` rather than an unactionable pause.\nconst withLocalPauseReason = (message: ThreadMessage): ThreadMessage => {\n if (\n message.role !== \"assistant\" ||\n message.status.type !== \"requires-action\" ||\n message.status.reason !== \"interrupt\" ||\n message.content.some(\n (c) =>\n c.type === \"tool-call\" && c.result === undefined && c.interrupt != null,\n )\n )\n return message;\n return {\n ...message,\n status: getAutoStatus(\n false,\n false,\n false,\n message.content.some(\n (c) => c.type === \"tool-call\" && c.result === undefined,\n ),\n ),\n };\n};\n\nconst withLocalPauseReasons = (\n data: ExportedMessageRepository,\n): ExportedMessageRepository => ({\n ...data,\n messages: data.messages.map((item) => ({\n ...item,\n message: withLocalPauseReason(item.message),\n })),\n});\n\nexport class LocalThreadRuntimeCore\n extends BaseThreadRuntimeCore\n implements ThreadRuntimeCore\n{\n public readonly capabilities = {\n switchToBranch: true,\n switchBranchDuringRun: true,\n edit: true,\n delete: false,\n reload: true,\n refetchThread: false,\n cancel: true,\n unstable_copy: true,\n speech: false,\n dictation: false,\n voice: false,\n attachments: false,\n feedback: false,\n queue: false,\n };\n\n private abortController: AbortController | null = null;\n\n private _queue: MessageQueueController | null = null;\n private _queueRunInFlight = false;\n private _activeRun: { cancelled: boolean } | null = null;\n private _runGeneration = 0;\n\n private _historyWrites = new Map<string, Promise<void>>();\n\n // Writes for one message id must land in issue order; an earlier paused\n // snapshot arriving after the terminal write would resurrect the pause.\n private _chainHistoryWrite(\n id: string,\n write: () => Promise<void>,\n ): Promise<void> {\n const next = (this._historyWrites.get(id) ?? Promise.resolve()).then(\n write,\n write,\n );\n const stored = next.then(\n () => {},\n () => {},\n );\n this._historyWrites.set(id, stored);\n void stored.then(() => {\n if (this._historyWrites.get(id) === stored) {\n this._historyWrites.delete(id);\n }\n });\n return next;\n }\n\n // A decision recorded on a still-paused message must reach history before\n // the run resumes, or a refresh would restore the message without it.\n private _persistPausedMessage(\n parentId: string | null,\n message: ThreadAssistantMessage,\n ) {\n if (message.status?.type !== \"requires-action\") return;\n const history = this._options.adapters.history;\n if (!history?.update) return;\n const update = history.update.bind(history);\n const item = { parentId, message, runConfig: this._lastRunConfig };\n this._chainHistoryWrite(message.id, () => update(item)).catch(() => {});\n }\n\n public readonly isDisabled = false;\n public readonly isSendDisabled = false;\n\n private _isLoading = false;\n public get isLoading() {\n return this._isLoading;\n }\n\n private _suggestions: readonly ThreadSuggestion[] = [];\n private _suggestionsController: AbortController | null = null;\n public get suggestions(): readonly ThreadSuggestion[] {\n return this._suggestions;\n }\n\n public get adapters() {\n return this._options.adapters;\n }\n\n constructor(\n contextProvider: ModelContextProvider,\n options: LocalRuntimeOptionsBase,\n ) {\n super(contextProvider);\n this.__internal_setOptions(options);\n }\n\n private _options!: LocalRuntimeOptionsBase;\n\n private _lastRunConfig: RunConfig = {};\n\n private _getThreadId?: () => string | undefined;\n\n public __internal_setGetThreadId(getThreadId: () => string | undefined) {\n this._getThreadId = getThreadId;\n }\n\n private _getInitializePromise?: () => Promise<unknown> | undefined;\n\n public __internal_setGetInitializePromise(\n getPromise: () => Promise<unknown> | undefined,\n ) {\n this._getInitializePromise = getPromise;\n }\n\n public get extras() {\n return undefined;\n }\n\n public __internal_setOptions(options: LocalRuntimeOptionsBase) {\n if (this._options === options) return;\n\n const previousHistory = this._options?.adapters.history;\n this._options = options;\n\n let hasUpdates = false;\n\n const canSpeak = options.adapters?.speech !== undefined;\n if (this.capabilities.speech !== canSpeak) {\n this.capabilities.speech = canSpeak;\n hasUpdates = true;\n }\n\n const canDictate = options.adapters?.dictation !== undefined;\n if (this.capabilities.dictation !== canDictate) {\n this.capabilities.dictation = canDictate;\n hasUpdates = true;\n }\n\n const canVoice = options.adapters?.voice !== undefined;\n if (this.capabilities.voice !== canVoice) {\n this.capabilities.voice = canVoice;\n hasUpdates = true;\n }\n\n const canAttach = options.adapters?.attachments !== undefined;\n if (this.capabilities.attachments !== canAttach) {\n this.capabilities.attachments = canAttach;\n hasUpdates = true;\n }\n\n const canFeedback = options.adapters?.feedback !== undefined;\n if (this.capabilities.feedback !== canFeedback) {\n this.capabilities.feedback = canFeedback;\n hasUpdates = true;\n }\n\n const canDelete = options.adapters?.history?.delete !== undefined;\n if (this.capabilities.delete !== canDelete) {\n this.capabilities.delete = canDelete;\n hasUpdates = true;\n }\n\n const canQueue = options.unstable_enableMessageQueue === true;\n if (canQueue && !this._queue) {\n this._queue = createMessageQueue({\n run: (message) => {\n // release the queue when the dispatch settles, even if it rejects\n // before reaching startRun's finally, so a failure can't deadlock it\n this._queueRunInFlight = true;\n const generation = this._runGeneration;\n // the tail may have moved since the message was enqueued\n void this._runAppend({\n ...message,\n parentId: this.messages.at(-1)?.id ?? null,\n })\n .finally(() => {\n this._queueRunInFlight = false;\n // a dispatch that failed before starting a run settles here;\n // runs that did start release from _runLoop\n if (this._runGeneration === generation) this._queue?.notifyIdle();\n })\n .catch(() => {});\n },\n });\n this._queue.subscribe(() => this._notifySubscribers());\n } else if (!canQueue && this._queue) {\n this._queue = null;\n }\n if (this.capabilities.queue !== canQueue) {\n this.capabilities.queue = canQueue;\n hasUpdates = true;\n }\n\n if (hasUpdates) this._notifySubscribers();\n\n if (\n this._loadRequested &&\n !this._loadPromise &&\n !previousHistory &&\n options.adapters.history &&\n this.messages.length === 0\n ) {\n void this.__internal_load().catch((error: unknown) => {\n console.error(\n \"[assistant-ui] local thread history load failed:\",\n error,\n );\n });\n }\n }\n\n private _loadPromise: Promise<void> | undefined;\n private _loadRequested = false;\n public __internal_load() {\n this._loadRequested = true;\n if (this._loadPromise) return this._loadPromise;\n if (!this.adapters.history) return Promise.resolve();\n\n const promise = this.adapters.history.load();\n\n this._isLoading = true;\n this._notifySubscribers();\n\n this._loadPromise = promise\n .then((repo) => {\n if (!repo) return;\n this.repository.import(withLocalPauseReasons(repo));\n if (repo.messages.length > 0) {\n this.ensureInitialized();\n }\n this._notifySubscribers();\n\n const resume = this.adapters.history?.resume?.bind(\n this.adapters.history,\n );\n if (repo.unstable_resume && resume) {\n this.startRun(\n {\n parentId: this.repository.headId,\n sourceId: this.repository.headId,\n runConfig: this._lastRunConfig,\n },\n resume,\n ).catch(() => {});\n }\n })\n .finally(() => {\n this._isLoading = false;\n this._notifySubscribers();\n });\n\n return this._loadPromise;\n }\n\n public async append(message: AppendMessage): Promise<void> {\n const isTail = message.parentId === (this.messages.at(-1)?.id ?? null);\n const willRun = message.startRun ?? message.role === \"user\";\n if (this._queue && willRun && isTail) {\n if (message.steer ?? this._queueRunInFlight)\n this._queue.adapter.steer(message);\n else this._queue.adapter.enqueue(message);\n return;\n }\n if (\n this._queue &&\n !isTail &&\n (this._options.unstable_queueClearOnRewind ?? true)\n )\n this._queue.clear();\n return this._runAppend(message);\n }\n\n public getQueueItems(): readonly QueueItemState[] {\n // Reads can arrive during base-thread construction, before the queue field\n // is assigned, so guard against the unset field.\n return this._queue?.adapter.items ?? EMPTY_QUEUE_ITEMS;\n }\n\n public getSteerQueueItems(): readonly QueueItemState[] {\n return this._queue?.adapter.steerItems ?? EMPTY_QUEUE_ITEMS;\n }\n\n public moveQueueItem(queueItemId: string, placement: QueuePlacement): void {\n this._queue?.adapter.move(queueItemId, placement);\n }\n\n public removeQueueItem(queueItemId: string): void {\n this._queue?.adapter.remove(queueItemId);\n }\n\n private _rollbackAppend(messageId: string) {\n try {\n this.repository.deleteMessage(messageId);\n } catch {\n return;\n }\n this._notifySubscribers();\n }\n\n private async _runAppend(rawMessage: AppendMessage): Promise<void> {\n // Stamped here rather than in `append` so a queued message is gated after\n // the flush re-pointed its parentId at the current tail.\n const generation = captureThreadRuntimeGeneration(this);\n const message = this.enrichAppendMetadata(rawMessage);\n this.ensureInitialized();\n\n const newMessage = fromThreadMessageLike(message, generateId(), {\n type: \"complete\",\n reason: \"unknown\",\n });\n this.repository.addOrUpdateMessage(message.parentId, newMessage);\n this._notifySubscribers();\n\n // Initialization only gates the history write and the run; the message\n // is already on screen. A failed barrier rolls the optimistic message\n // back and rejects as an unsent message so the composer restores the\n // draft; a thread invalidated mid-wait rolls back silently.\n try {\n const initPromise = this._getInitializePromise?.();\n if (initPromise) {\n await initPromise;\n }\n } catch (error) {\n this._rollbackAppend(newMessage.id);\n if (!isThreadRuntimeGenerationCurrent(this, generation)) return;\n const notSent = new MessageNotSentError();\n notSent.cause = error;\n throw notSent;\n }\n if (!isThreadRuntimeGenerationCurrent(this, generation)) {\n this._rollbackAppend(newMessage.id);\n return;\n }\n const historyWrite = this._options.adapters.history?.append({\n parentId: message.parentId,\n message: newMessage,\n ...(message.runConfig !== undefined && { runConfig: message.runConfig }),\n });\n void historyWrite?.catch(() => {});\n\n const startRun = message.startRun ?? message.role === \"user\";\n if (startRun) {\n const [runResult, historyResult] = await Promise.allSettled([\n this.startRun({\n parentId: newMessage.id,\n sourceId: message.sourceId,\n runConfig: message.runConfig ?? {},\n }),\n historyWrite,\n ]);\n if (runResult.status === \"rejected\") throw runResult.reason;\n if (historyResult.status === \"rejected\") throw historyResult.reason;\n } else {\n this.repository.resetHead(newMessage.id);\n this._notifySubscribers();\n await historyWrite;\n }\n }\n\n public async deleteMessage(messageId: string): Promise<void> {\n const adapter = this._options.adapters.history;\n if (!adapter?.delete)\n throw new Error(\"Runtime does not support deleting messages.\");\n\n const messages = this.repository.getMessages();\n const messageIndex = messages.findIndex((m) => m.id === messageId);\n if (messageIndex === -1) throw new Error(\"Message not found.\");\n\n const message = messages[messageIndex]!;\n const parentId = messages[messageIndex - 1]?.id ?? null;\n const items = [{ parentId, message }];\n\n await adapter.delete(items);\n\n this.repository.deleteMessage(messageId);\n this._notifySubscribers();\n }\n\n public resumeRun({ stream, ...startConfig }: ResumeRunConfig): Promise<void> {\n if (!stream)\n throw new Error(\"You must pass a stream parameter to resume runs.\");\n return this.startRun(startConfig, stream);\n }\n\n public exportExternalState(): any {\n throw new Error(\"Runtime does not support exporting external states.\");\n }\n\n public override import(data: ExportedMessageRepository) {\n super.import(withLocalPauseReasons(data));\n }\n\n public importExternalState(): void {\n throw new Error(\"Runtime does not support importing external states.\");\n }\n\n public unstable_notifySessionReset(): void {\n throw new Error(\"Runtime does not support resetting sessions.\");\n }\n\n public async startRun(\n { parentId, runConfig }: StartRunConfig,\n runCallback?: ChatModelAdapter[\"run\"],\n ): Promise<void> {\n this.ensureInitialized();\n\n // add assistant message\n const id = generateId();\n const message: ThreadAssistantMessage = {\n id,\n role: \"assistant\",\n status: { type: \"running\" },\n content: [],\n metadata: {\n unstable_state: this.state,\n unstable_annotations: [],\n unstable_data: [],\n steps: [],\n custom: {},\n },\n createdAt: new Date(),\n };\n\n return this._runLoop(parentId, message, runConfig, runCallback);\n }\n\n private async _runLoop(\n parentId: string | null,\n message: ThreadAssistantMessage,\n runConfig: RunConfig | undefined,\n runCallback?: ChatModelAdapter[\"run\"],\n ): Promise<void> {\n this._notifyEventSubscribers(\"runStart\", {});\n\n // A run entered on a requires-action message resumes a pause an\n // update-capable adapter already holds (written at pause time or loaded).\n const alreadyPersisted =\n message.status?.type === \"requires-action\" &&\n this._options.adapters.history?.update !== undefined;\n\n const run = { cancelled: false };\n this._activeRun = run;\n this._runGeneration++;\n\n let active = false;\n try {\n // mark busy for runs not started through the queue (regenerate, resume)\n this._queue?.notifyBusy();\n this._suggestions = [];\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n this._notifySubscribers();\n\n do {\n message = await this.performRoundtrip(\n parentId,\n message,\n runConfig,\n alreadyPersisted,\n run,\n runCallback,\n );\n runCallback = undefined;\n if (this._activeRun !== run) break;\n } while (shouldContinue(message, this._options.unstable_humanToolNames));\n } finally {\n this._notifyEventSubscribers(\"runEnd\", {});\n // the settle belongs to this run only while it is still the active run\n // or was cancelled (the engine expects a cancelled run's settle); a run\n // superseded by a newer one stays silent\n active = this._activeRun === run;\n if (active) this._activeRun = null;\n if (active || run.cancelled) {\n queueMicrotask(() => this._queue?.notifyIdle());\n }\n }\n\n if (\n active &&\n this.adapters.suggestion &&\n message.status?.type !== \"requires-action\"\n ) {\n this._suggestionsController = new AbortController();\n const signal = this._suggestionsController.signal;\n const adapter = this.adapters.suggestion;\n void (async () => {\n try {\n const promiseOrGenerator = adapter.generate({\n messages: this.messages,\n signal,\n });\n await consumeSuggestionResult(promiseOrGenerator, {\n signal,\n onUpdate: (r) => {\n this._suggestions = r;\n this._notifySubscribers();\n },\n });\n } catch {}\n })();\n }\n }\n\n private async performRoundtrip(\n parentId: string | null,\n message: ThreadAssistantMessage,\n runConfig: RunConfig | undefined,\n alreadyPersisted: boolean,\n run: { cancelled: boolean },\n runCallback?: ChatModelAdapter[\"run\"],\n ) {\n const messages = parentId ? this.repository.getMessages(parentId) : [];\n\n // abort existing run\n this.abortController?.abort();\n const abortController = new AbortController();\n this.abortController = abortController;\n\n const initialContent = message.content;\n const initialAnnotations = message.metadata?.unstable_annotations;\n const initialData = message.metadata?.unstable_data;\n const initialSteps = message.metadata?.steps;\n const initialCustom = message.metadata?.custom;\n let hasStoredMessage = true;\n try {\n this.repository.getMessage(message.id);\n } catch {\n hasStoredMessage = false;\n }\n // Other writers replace the stored message object, so identity distinguishes this run from a newer owner.\n const ownsMessage = () => {\n if (!hasStoredMessage) return this._activeRun === run;\n try {\n return this.repository.getMessage(message.id).message === message;\n } catch {\n return false;\n }\n };\n const updateMessage = (m: Partial<ChatModelRunResult>) => {\n if (!ownsMessage()) return;\n const newSteps = m.metadata?.steps;\n const steps = newSteps\n ? [...(initialSteps ?? []), ...newSteps]\n : undefined;\n\n const newAnnotations = m.metadata?.unstable_annotations;\n const newData = m.metadata?.unstable_data;\n const annotations = newAnnotations\n ? [...(initialAnnotations ?? []), ...newAnnotations]\n : undefined;\n const data = newData ? [...(initialData ?? []), ...newData] : undefined;\n\n message = {\n ...message,\n ...(m.content\n ? { content: [...initialContent, ...(m.content ?? [])] }\n : undefined),\n status: m.status ?? message.status,\n ...(m.metadata\n ? {\n metadata: {\n ...message.metadata,\n ...(m.metadata.unstable_state !== undefined\n ? { unstable_state: m.metadata.unstable_state }\n : undefined),\n ...(annotations\n ? { unstable_annotations: annotations }\n : undefined),\n ...(data ? { unstable_data: data } : undefined),\n ...(steps ? { steps } : undefined),\n ...(m.metadata?.timing\n ? { timing: m.metadata.timing }\n : undefined),\n ...(m.metadata?.custom\n ? {\n custom: {\n ...(initialCustom ?? {}),\n ...m.metadata.custom,\n },\n }\n : undefined),\n },\n }\n : undefined),\n };\n this.repository.addOrUpdateMessage(parentId, message);\n hasStoredMessage = true;\n this._notifySubscribers();\n };\n\n const maxSteps = this._options.maxSteps ?? 2;\n\n try {\n const steps = message.metadata?.steps?.length ?? 0;\n if (steps >= maxSteps) {\n updateMessage({\n status: {\n type: \"incomplete\",\n reason: \"tool-calls\",\n },\n });\n return message;\n }\n\n updateMessage({\n status: {\n type: \"running\",\n },\n });\n\n // Switch to the new message branch right after adding it for the first time\n this.repository.resetHead(message.id);\n this._notifySubscribers();\n\n this._lastRunConfig = runConfig ?? {};\n // unstable_composerMetadata is composer-only (stamped onto the outgoing\n // message); never expose it to the chat-model adapter's run context.\n const { unstable_composerMetadata: _, ...context } =\n this.getModelContext();\n\n runCallback =\n runCallback ??\n this.adapters.chatModel.run.bind(this.adapters.chatModel);\n\n const abortSignal = abortController.signal;\n const shouldCancelMessage = () =>\n abortSignal.aborted &&\n (message.status.type === \"running\" ||\n (message.status.type === \"requires-action\" &&\n (this._activeRun !== run ||\n shouldContinue(message, this._options.unstable_humanToolNames))));\n const threadId = this._getThreadId?.();\n const promiseOrGenerator = runCallback({\n messages,\n runConfig: this._lastRunConfig,\n abortSignal,\n context,\n unstable_assistantMessageId: message.id,\n unstable_threadId: threadId,\n unstable_parentId: parentId,\n unstable_getMessage() {\n return message;\n },\n });\n\n // handle async iterator for streaming results\n if (Symbol.asyncIterator in promiseOrGenerator) {\n for await (const r of promiseOrGenerator) {\n if (abortSignal.aborted) {\n if (shouldCancelMessage()) {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n }\n break;\n }\n\n updateMessage(r);\n }\n } else {\n updateMessage(await promiseOrGenerator);\n }\n\n if (shouldCancelMessage()) {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n } else if (message.status.type === \"running\") {\n updateMessage({\n status: { type: \"complete\", reason: \"unknown\" },\n });\n }\n } catch (e) {\n if (e instanceof AbortError) {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n } else if (e instanceof Error && e.name === \"AbortError\") {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n } else {\n updateMessage({\n status: {\n type: \"incomplete\",\n reason: \"error\",\n error: toAssistantError(e),\n },\n });\n\n throw e;\n }\n } finally {\n if (this.abortController === abortController) {\n this.abortController = null;\n }\n\n const history = this._options.adapters.history;\n const item = {\n parentId,\n message,\n runConfig: this._lastRunConfig,\n };\n const isTerminal =\n message.status.type === \"complete\" ||\n message.status.type === \"incomplete\";\n const isPausing =\n message.status.type === \"requires-action\" &&\n !shouldContinue(message, this._options.unstable_humanToolNames);\n\n // Pauses are written only for adapters that can rewrite the entry later;\n // an append-only adapter would strand a half-finished run in history.\n if (ownsMessage() && (isTerminal || (isPausing && history?.update))) {\n const write =\n alreadyPersisted && history?.update\n ? history.update.bind(history)\n : history?.append.bind(history);\n if (write) {\n await this._chainHistoryWrite(message.id, () => write(item));\n }\n }\n }\n return message;\n }\n\n public detach() {\n invalidateThreadRuntime(this);\n // drop the queue so pending items cannot dispatch on a detached thread\n this._queue = null;\n const error = new AbortError(true);\n this.abortController?.abort(error);\n this.abortController = null;\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n }\n\n public cancelRun() {\n if (this._queue) {\n if (this._options.unstable_queueClearOnCancel ?? true) {\n this._queue.clear();\n } else {\n this._queue.notifyCancelled();\n if (this._activeRun) this._activeRun.cancelled = true;\n }\n }\n const error = new AbortError(false);\n this.abortController?.abort(error);\n this.abortController = null;\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n }\n\n public addToolResult({\n messageId,\n toolCallId,\n result,\n isError,\n artifact,\n }: AddToolResultOptions) {\n const messageData = this.repository.getMessage(messageId);\n const { parentId } = messageData;\n let { message } = messageData;\n\n if (message.role !== \"assistant\")\n throw new Error(\"Tried to add tool result to non-assistant message\");\n\n let added = false;\n let found = false;\n const newContent = message.content.map((c) => {\n if (c.type !== \"tool-call\") return c;\n if (c.toolCallId !== toolCallId) return c;\n found = true;\n if (c.result === undefined) added = true;\n return {\n ...c,\n result,\n artifact,\n isError,\n };\n });\n\n if (!found)\n throw new Error(\"Tried to add tool result to non-existing tool call\");\n\n message = {\n ...message,\n content: newContent,\n };\n this.repository.addOrUpdateMessage(parentId, message);\n this._notifySubscribers();\n\n // a result may arrive mid-run or on a non-head message; the resume\n // intentionally aborts any in-flight run, unlike respondToToolApproval\n if (\n added &&\n shouldContinue(message, this._options.unstable_humanToolNames)\n ) {\n this._runLoop(parentId, message, this._lastRunConfig).catch(() => {});\n } else if (added) {\n this._persistPausedMessage(parentId, message);\n }\n }\n\n public resumeToolCall(_options: ResumeToolCallOptions) {\n throw new Error(\n \"Local runtime does not support resuming tool calls. For human-in-the-loop tools, list the tool in unstable_humanToolNames and complete the call with addToolResult.\",\n );\n }\n\n public respondToToolApproval({\n approvalId,\n approved,\n optionId,\n reason,\n }: RespondToToolApprovalOptions) {\n let message = this.repository\n .getMessages()\n .findLast(\n (m): m is ThreadAssistantMessage =>\n m.role === \"assistant\" &&\n m.content.some(\n (c) => c.type === \"tool-call\" && c.approval?.id === approvalId,\n ),\n );\n\n if (!message)\n throw new Error(\"Tried to respond to a non-existing tool approval\");\n\n if (this.abortController !== null)\n throw new Error(\n \"Tried to respond to a tool approval while a run is in progress\",\n );\n\n if (message.status?.type !== \"requires-action\")\n throw new Error(\n \"Tried to respond to a tool approval on a message whose status is not requires-action\",\n );\n\n const target = message.content.find(\n (c) => c.type === \"tool-call\" && c.approval?.id === approvalId,\n );\n if (target?.type !== \"tool-call\" || !target.approval)\n throw new Error(\"Tried to respond to a non-existing tool approval\");\n if (target.approval.resolution !== undefined)\n throw new Error(\n \"Tried to respond to a tool approval that was cancelled or expired\",\n );\n if (target.approval.approved !== undefined)\n throw new Error(\"Tried to respond to an already decided tool approval\");\n\n const targetApproval = target.approval;\n const newContent = message.content.map((c) => {\n if (c !== target) return c;\n const approval = {\n ...targetApproval,\n approved,\n ...(optionId != null && { optionId }),\n ...(reason != null && { reason }),\n };\n if (approved) return { ...c, approval };\n return {\n ...c,\n approval,\n result: { error: reason || \"Tool approval denied\" },\n isError: true,\n };\n });\n\n message = { ...message, content: newContent };\n const { parentId } = this.repository.getMessage(message.id);\n this.repository.addOrUpdateMessage(parentId, message);\n this._notifySubscribers();\n\n if (\n this.repository.headId === message.id &&\n shouldContinue(message, this._options.unstable_humanToolNames)\n ) {\n this._runLoop(parentId, message, this._lastRunConfig).catch(() => {});\n } else {\n this._persistPausedMessage(parentId, message);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AA2CA,IAAMgC,aAAN,cAAyBC,MAAM;CAC7B,OAAgB;CAChBE;CAEAC,YAAYD,QAAiBE,SAAkB;EAC7C,MAAMA,OAAO;EACb,KAAKF,SAASA;CAChB;AACF;AAOA,MAAMG,wBAAwBD,YAA0C;CACtE,IACEA,QAAQE,SAAS,eACjBF,QAAQG,OAAOC,SAAS,qBACxBJ,QAAQG,OAAOE,WAAW,eAC1BL,QAAQM,QAAQC,MACbC,MACCA,EAAEJ,SAAS,eAAeI,EAAEC,WAAWC,KAAAA,KAAaF,EAAEG,aAAa,IACvE,GAEA,OAAOX;CACT,OAAO;EACL,GAAGA;EACHG,QAAQnC,cACN,OACA,OACA,OACAgC,QAAQM,QAAQC,MACbC,MAAMA,EAAEJ,SAAS,eAAeI,EAAEC,WAAWC,KAAAA,CAChD,CACF;CACF;AACF;AAEA,MAAME,yBACJC,UAC+B;CAC/B,GAAGA;CACHC,UAAUD,KAAKC,SAASC,KAAKC,UAAU;EACrC,GAAGA;EACHhB,SAASC,qBAAqBe,KAAKhB,OAAO;CAC5C,EAAE;AACJ;AAEA,IAAaiB,yBAAb,cACUtC,sBAEV;CACE,eAA+B;EAC7BwC,gBAAgB;EAChBC,uBAAuB;EACvBC,MAAM;EACNC,QAAQ;EACRC,QAAQ;EACRC,eAAe;EACfC,QAAQ;EACRC,eAAe;EACfC,QAAQ;EACRC,WAAW;EACXC,OAAO;EACPC,aAAa;EACbC,UAAU;EACVC,OAAO;CACT;CAEA,kBAAkD;CAElD,SAAgD;CAChD,oBAA4B;CAC5B,aAAoD;CACpD,iBAAyB;CAEzB,iCAAyB,IAAIS,IAA2B;CAIxD,mBACEG,IACAC,OACe;EACf,MAAMC,QAAQ,KAAKN,eAAeO,IAAIH,EAAE,KAAKF,QAAQM,QAAQ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AAKP,SAASlH,UAAUrD,SAAS,KAAK4D,cAAc,CAAC,CAACC,YAAY,CAAC,CAAC;OAEpE,KAAKT,sBAAsBC,UAAUrD,OAAO;CAEhD;AACF"}
@@ -1,9 +1,8 @@
1
1
  import { ThreadMessage } from "../../types/message.js";
2
- import { Unsubscribe } from "../../types/unsubscribe.js";
3
- import { ThreadRuntimeCore } from "../../runtime/interfaces/thread-runtime-core.js";
4
- import { BaseSubscribable } from "../../subscribable/subscribable.js";
2
+ import { InertThreadRuntimeCore } from "../inert/InertThreadRuntimeCore.js";
5
3
  //#region src/runtimes/readonly/ReadonlyThreadRuntimeCore.d.ts
6
- declare class ReadonlyThreadRuntimeCore extends BaseSubscribable implements ThreadRuntimeCore {
4
+ declare class ReadonlyThreadRuntimeCore extends InertThreadRuntimeCore {
5
+ protected get error(): Error;
7
6
  private _messages;
8
7
  get messages(): readonly ThreadMessage[];
9
8
  setMessages(messages: readonly ThreadMessage[]): void;
@@ -13,28 +12,12 @@ declare class ReadonlyThreadRuntimeCore extends BaseSubscribable implements Thre
13
12
  index: number;
14
13
  } | undefined;
15
14
  getBranches(messageId: string): string[];
16
- switchToBranch(): void;
17
- append(): void;
18
- deleteMessage(): void;
19
- startRun(): void;
20
- resumeRun(): void;
21
- cancelRun(): void;
22
- addToolResult(): void;
23
- resumeToolCall(): void;
24
- respondToToolApproval(): void;
25
- speak(): void;
26
- stopSpeaking(): void;
27
- connectVoice(): void;
28
- disconnectVoice(): void;
29
- getVoiceVolume: () => number;
30
- subscribeVoiceVolume: () => Unsubscribe;
31
- muteVoice(): void;
32
- unmuteVoice(): void;
33
- submitFeedback(): void;
34
- getModelContext(): {};
35
- exportExternalState(): void;
36
- importExternalState(): void;
37
- unstable_notifySessionReset(): void;
15
+ export(): {
16
+ messages: {
17
+ message: ThreadMessage;
18
+ parentId: string | null;
19
+ }[];
20
+ };
38
21
  composer: {
39
22
  attachments: never[];
40
23
  attachmentAccept: string;
@@ -65,41 +48,10 @@ declare class ReadonlyThreadRuntimeCore extends BaseSubscribable implements Thre
65
48
  subscribe(): () => void;
66
49
  unstable_on(): () => void;
67
50
  };
68
- getEditComposer(): undefined;
69
- beginEdit(): void;
70
- speech: undefined;
71
- voice: undefined;
72
- capabilities: {
73
- readonly switchToBranch: false;
74
- readonly switchBranchDuringRun: false;
75
- readonly edit: false;
76
- readonly delete: false;
77
- readonly reload: false;
78
- readonly refetchThread: false;
79
- readonly cancel: false;
80
- readonly unstable_copy: false;
81
- readonly speech: false;
82
- readonly dictation: false;
83
- readonly voice: false;
84
- readonly attachments: false;
85
- readonly feedback: false;
86
- readonly queue: false;
87
- };
88
- isDisabled: boolean;
89
- isSendDisabled: boolean;
90
51
  isLoading: boolean;
91
- state: null;
92
- suggestions: never[];
93
- extras: undefined;
94
- import(): void;
95
- export(): {
96
- messages: {
97
- message: ThreadMessage;
98
- parentId: string | null;
99
- }[];
100
- };
101
- reset(): void;
102
- unstable_on(): Unsubscribe;
52
+ cancelRun(): void;
53
+ stopSpeaking(): void;
54
+ disconnectVoice(): void;
103
55
  }
104
56
  //#endregion
105
57
  export { ReadonlyThreadRuntimeCore };
@@ -1 +1 @@
1
- {"version":3,"file":"ReadonlyThreadRuntimeCore.d.ts","names":[],"sources":["../../../src/runtimes/readonly/ReadonlyThreadRuntimeCore.ts"],"mappings":";;;;;cASa,kCACH,4BACG;UAEH;MAEJ,qBAAQ;EAIZ,YAAY,mBAAmB;EAM/B,eAAe;;;;;EAUf,YAAY;EAMZ;EAIA;EAIA;EAIA;EAIA;EAIA;EAEA;EAIA;EAIA;EAIA;EAIA;EAEA;EAIA;EAEA;EACA,4BAA2B;EAE3B;EAIA;EAIA;EAIA;EAIA;EAIA;EAIA;EAIA;IACqB;;;;;;;;;;;;;;;;;;IAiDN;;;;;;;;;;;EA6Bf;EAIA;EAIA;EACA;EAEA;;;;;;;;;;;;;;;;EAiBA;EACA;EACA;EAEA;EACA;EACA;EAEA;EAIA;;;;;;EASA;EAIA,eAAe"}
1
+ {"version":3,"file":"ReadonlyThreadRuntimeCore.d.ts","names":[],"sources":["../../../src/runtimes/readonly/ReadonlyThreadRuntimeCore.ts"],"mappings":";;;cAUa,kCAAkC;gBAC/B,SAAK;UAIX;MAEJ,qBAAQ;EAIZ,YAAY,mBAAmB;EAM/B,eAAe;;;;;EAUf,YAAY;EAMZ;;;;;;EASA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAEA;EAES;EAEA;EAEA"}
@@ -1,7 +1,10 @@
1
- import { BaseSubscribable } from "../../subscribable/subscribable.js";
1
+ import { InertThreadRuntimeCore, createInertComposer } from "../inert/InertThreadRuntimeCore.js";
2
2
  //#region src/runtimes/readonly/ReadonlyThreadRuntimeCore.ts
3
3
  const READONLY_THREAD_ERROR = /* @__PURE__ */ new Error("This is a readonly thread. You cannot perform mutations on readonly threads.");
4
- var ReadonlyThreadRuntimeCore = class extends BaseSubscribable {
4
+ var ReadonlyThreadRuntimeCore = class extends InertThreadRuntimeCore {
5
+ get error() {
6
+ return READONLY_THREAD_ERROR;
7
+ }
5
8
  _messages = [];
6
9
  get messages() {
7
10
  return this._messages;
@@ -24,155 +27,17 @@ var ReadonlyThreadRuntimeCore = class extends BaseSubscribable {
24
27
  if (this._messages.findIndex((m) => m.id === messageId) === -1) return [];
25
28
  return [messageId];
26
29
  }
27
- switchToBranch() {
28
- throw READONLY_THREAD_ERROR;
29
- }
30
- append() {
31
- throw READONLY_THREAD_ERROR;
32
- }
33
- deleteMessage() {
34
- throw READONLY_THREAD_ERROR;
35
- }
36
- startRun() {
37
- throw READONLY_THREAD_ERROR;
38
- }
39
- resumeRun() {
40
- throw READONLY_THREAD_ERROR;
41
- }
42
- cancelRun() {}
43
- addToolResult() {
44
- throw READONLY_THREAD_ERROR;
45
- }
46
- resumeToolCall() {
47
- throw READONLY_THREAD_ERROR;
48
- }
49
- respondToToolApproval() {
50
- throw READONLY_THREAD_ERROR;
51
- }
52
- speak() {
53
- throw READONLY_THREAD_ERROR;
54
- }
55
- stopSpeaking() {}
56
- connectVoice() {
57
- throw READONLY_THREAD_ERROR;
58
- }
59
- disconnectVoice() {}
60
- getVoiceVolume = () => 0;
61
- subscribeVoiceVolume = () => () => {};
62
- muteVoice() {
63
- throw READONLY_THREAD_ERROR;
64
- }
65
- unmuteVoice() {
66
- throw READONLY_THREAD_ERROR;
67
- }
68
- submitFeedback() {
69
- throw READONLY_THREAD_ERROR;
70
- }
71
- getModelContext() {
72
- return {};
73
- }
74
- exportExternalState() {
75
- throw READONLY_THREAD_ERROR;
76
- }
77
- importExternalState() {
78
- throw READONLY_THREAD_ERROR;
79
- }
80
- unstable_notifySessionReset() {
81
- throw READONLY_THREAD_ERROR;
82
- }
83
- composer = {
84
- attachments: [],
85
- attachmentAccept: "*",
86
- async addAttachment() {
87
- throw READONLY_THREAD_ERROR;
88
- },
89
- async removeAttachment() {
90
- throw READONLY_THREAD_ERROR;
91
- },
92
- isEditing: false,
93
- canCancel: false,
94
- canSend: false,
95
- isEmpty: true,
96
- text: "",
97
- setText() {
98
- throw READONLY_THREAD_ERROR;
99
- },
100
- role: "user",
101
- setRole() {
102
- throw READONLY_THREAD_ERROR;
103
- },
104
- runConfig: {},
105
- setRunConfig() {
106
- throw READONLY_THREAD_ERROR;
107
- },
108
- async reset() {},
109
- async clearAttachments() {},
110
- send() {
111
- throw READONLY_THREAD_ERROR;
112
- },
113
- cancel() {},
114
- queue: [],
115
- moveQueueItem() {},
116
- removeQueueItem() {},
117
- dictation: void 0,
118
- startDictation() {
119
- throw READONLY_THREAD_ERROR;
120
- },
121
- stopDictation() {},
122
- quote: void 0,
123
- setQuote() {
124
- throw READONLY_THREAD_ERROR;
125
- },
126
- subscribe() {
127
- return () => {};
128
- },
129
- unstable_on() {
130
- return () => {};
131
- }
132
- };
133
- getEditComposer() {}
134
- beginEdit() {
135
- throw READONLY_THREAD_ERROR;
136
- }
137
- speech = void 0;
138
- voice = void 0;
139
- capabilities = {
140
- switchToBranch: false,
141
- switchBranchDuringRun: false,
142
- edit: false,
143
- delete: false,
144
- reload: false,
145
- refetchThread: false,
146
- cancel: false,
147
- unstable_copy: false,
148
- speech: false,
149
- dictation: false,
150
- voice: false,
151
- attachments: false,
152
- feedback: false,
153
- queue: false
154
- };
155
- isDisabled = false;
156
- isSendDisabled = false;
157
- isLoading = false;
158
- state = null;
159
- suggestions = [];
160
- extras = void 0;
161
- import() {
162
- throw READONLY_THREAD_ERROR;
163
- }
164
30
  export() {
165
31
  return { messages: this._messages.map((message, idx) => ({
166
32
  message,
167
33
  parentId: this._messages[idx - 1]?.id ?? null
168
34
  })) };
169
35
  }
170
- reset() {
171
- throw READONLY_THREAD_ERROR;
172
- }
173
- unstable_on() {
174
- return () => {};
175
- }
36
+ composer = createInertComposer(READONLY_THREAD_ERROR, false);
37
+ isLoading = false;
38
+ cancelRun() {}
39
+ stopSpeaking() {}
40
+ disconnectVoice() {}
176
41
  };
177
42
  //#endregion
178
43
  export { ReadonlyThreadRuntimeCore };
@@ -1 +1 @@
1
- {"version":3,"file":"ReadonlyThreadRuntimeCore.js","names":["Unsubscribe","ThreadMessage","ThreadRuntimeCore","BaseSubscribable","READONLY_THREAD_ERROR","Error","ReadonlyThreadRuntimeCore","_messages","messages","setMessages","_notifySubscribers","getMessageById","messageId","idx","findIndex","m","id","undefined","parentId","message","index","getBranches","switchToBranch","append","deleteMessage","startRun","resumeRun","cancelRun","addToolResult","resumeToolCall","respondToToolApproval","speak","stopSpeaking","connectVoice","disconnectVoice","getVoiceVolume","subscribeVoiceVolume","muteVoice","unmuteVoice","submitFeedback","getModelContext","exportExternalState","importExternalState","unstable_notifySessionReset","composer","attachments","attachmentAccept","addAttachment","removeAttachment","isEditing","const","canCancel","canSend","isEmpty","text","setText","role","setRole","runConfig","setRunConfig","reset","clearAttachments","send","cancel","queue","moveQueueItem","removeQueueItem","dictation","startDictation","stopDictation","quote","setQuote","subscribe","unstable_on","getEditComposer","beginEdit","speech","voice","capabilities","switchBranchDuringRun","edit","delete","reload","refetchThread","unstable_copy","feedback","isDisabled","isSendDisabled","isLoading","state","suggestions","extras","import","export","map"],"sources":["../../../src/runtimes/readonly/ReadonlyThreadRuntimeCore.ts"],"sourcesContent":["import type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { ThreadMessage } from \"../../types/message\";\nimport type { ThreadRuntimeCore } from \"../../runtime/interfaces/thread-runtime-core\";\nimport { BaseSubscribable } from \"../../subscribable/subscribable\";\n\nconst READONLY_THREAD_ERROR = new Error(\n \"This is a readonly thread. You cannot perform mutations on readonly threads.\",\n);\n\nexport class ReadonlyThreadRuntimeCore\n extends BaseSubscribable\n implements ThreadRuntimeCore\n{\n private _messages: readonly ThreadMessage[] = [];\n\n get messages() {\n return this._messages;\n }\n\n setMessages(messages: readonly ThreadMessage[]) {\n if (this._messages === messages) return;\n this._messages = messages;\n this._notifySubscribers();\n }\n\n getMessageById(messageId: string) {\n const idx = this._messages.findIndex((m) => m.id === messageId);\n if (idx === -1) return undefined;\n return {\n parentId: this._messages[idx - 1]?.id ?? null,\n message: this._messages[idx]!,\n index: idx,\n };\n }\n\n getBranches(messageId: string) {\n const idx = this._messages.findIndex((m) => m.id === messageId);\n if (idx === -1) return [];\n return [messageId];\n }\n\n switchToBranch(): void {\n throw READONLY_THREAD_ERROR;\n }\n\n append(): void {\n throw READONLY_THREAD_ERROR;\n }\n\n deleteMessage(): void {\n throw READONLY_THREAD_ERROR;\n }\n\n startRun(): void {\n throw READONLY_THREAD_ERROR;\n }\n\n resumeRun(): void {\n throw READONLY_THREAD_ERROR;\n }\n\n cancelRun(): void {}\n\n addToolResult(): void {\n throw READONLY_THREAD_ERROR;\n }\n\n resumeToolCall(): void {\n throw READONLY_THREAD_ERROR;\n }\n\n respondToToolApproval(): void {\n throw READONLY_THREAD_ERROR;\n }\n\n speak(): void {\n throw READONLY_THREAD_ERROR;\n }\n\n stopSpeaking(): void {}\n\n connectVoice(): void {\n throw READONLY_THREAD_ERROR;\n }\n\n disconnectVoice(): void {}\n\n getVoiceVolume = () => 0;\n subscribeVoiceVolume = (): Unsubscribe => () => {};\n\n muteVoice(): void {\n throw READONLY_THREAD_ERROR;\n }\n\n unmuteVoice(): void {\n throw READONLY_THREAD_ERROR;\n }\n\n submitFeedback(): void {\n throw READONLY_THREAD_ERROR;\n }\n\n getModelContext() {\n return {};\n }\n\n exportExternalState() {\n throw READONLY_THREAD_ERROR;\n }\n\n importExternalState(): void {\n throw READONLY_THREAD_ERROR;\n }\n\n unstable_notifySessionReset(): void {\n throw READONLY_THREAD_ERROR;\n }\n\n composer = {\n attachments: [] as never[],\n attachmentAccept: \"*\",\n\n async addAttachment() {\n throw READONLY_THREAD_ERROR;\n },\n\n async removeAttachment() {\n throw READONLY_THREAD_ERROR;\n },\n\n isEditing: false as const,\n canCancel: false,\n canSend: false,\n isEmpty: true,\n text: \"\",\n\n setText() {\n throw READONLY_THREAD_ERROR;\n },\n\n role: \"user\" as const,\n\n setRole() {\n throw READONLY_THREAD_ERROR;\n },\n\n runConfig: {},\n\n setRunConfig() {\n throw READONLY_THREAD_ERROR;\n },\n\n async reset() {\n // noop\n },\n\n async clearAttachments() {\n // noop\n },\n\n send() {\n throw READONLY_THREAD_ERROR;\n },\n\n cancel() {\n // noop\n },\n\n queue: [] as never[],\n moveQueueItem() {},\n removeQueueItem() {},\n\n dictation: undefined,\n\n startDictation() {\n throw READONLY_THREAD_ERROR;\n },\n\n stopDictation() {\n // noop\n },\n\n quote: undefined,\n\n setQuote() {\n throw READONLY_THREAD_ERROR;\n },\n\n subscribe() {\n return () => {};\n },\n\n unstable_on() {\n return () => {};\n },\n };\n\n getEditComposer() {\n return undefined;\n }\n\n beginEdit(): void {\n throw READONLY_THREAD_ERROR;\n }\n\n speech = undefined;\n voice = undefined;\n\n capabilities = {\n switchToBranch: false,\n switchBranchDuringRun: false,\n edit: false,\n delete: false,\n reload: false,\n refetchThread: false,\n cancel: false,\n unstable_copy: false,\n speech: false,\n dictation: false,\n voice: false,\n attachments: false,\n feedback: false,\n queue: false,\n } as const;\n\n isDisabled = false;\n isSendDisabled = false;\n isLoading = false;\n\n state = null;\n suggestions = [] as never[];\n extras = undefined;\n\n import(): void {\n throw READONLY_THREAD_ERROR;\n }\n\n export() {\n return {\n messages: this._messages.map((message, idx) => ({\n message,\n parentId: this._messages[idx - 1]?.id ?? null,\n })),\n };\n }\n\n reset(): void {\n throw READONLY_THREAD_ERROR;\n }\n\n unstable_on(): Unsubscribe {\n return () => {};\n }\n}\n"],"mappings":";;AAKA,MAAMI,wCAAwB,IAAIC,MAChC,8EACF;AAEA,IAAaC,4BAAb,cACUH,iBAEV;CACE,YAA8C,CAAA;CAE9C,IAAIK,WAAW;EACb,OAAO,KAAKD;CACd;CAEAE,YAAYD,UAAoC;EAC9C,IAAI,KAAKD,cAAcC,UAAU;EACjC,KAAKD,YAAYC;EACjB,KAAKE,mBAAmB;CAC1B;CAEAC,eAAeC,WAAmB;EAChC,MAAMC,MAAM,KAAKN,UAAUO,WAAWC,MAAMA,EAAEC,OAAOJ,SAAS;EAC9D,IAAIC,QAAQ,IAAI,OAAOI,KAAAA;EACvB,OAAO;GACLC,UAAU,KAAKX,UAAUM,MAAM,EAAE,EAAEG,MAAM;GACzCG,SAAS,KAAKZ,UAAUM;GACxBO,OAAOP;EACT;CACF;CAEAQ,YAAYT,WAAmB;EAE7B,IADY,KAAKL,UAAUO,WAAWC,MAAMA,EAAEC,OAAOJ,SACjDC,MAAQ,IAAI,OAAO,CAAA;EACvB,OAAO,CAACD,SAAS;CACnB;CAEAU,iBAAuB;EACrB,MAAMlB;CACR;CAEAmB,SAAe;EACb,MAAMnB;CACR;CAEAoB,gBAAsB;EACpB,MAAMpB;CACR;CAEAqB,WAAiB;EACf,MAAMrB;CACR;CAEAsB,YAAkB;EAChB,MAAMtB;CACR;CAEAuB,YAAkB,CAAC;CAEnBC,gBAAsB;EACpB,MAAMxB;CACR;CAEAyB,iBAAuB;EACrB,MAAMzB;CACR;CAEA0B,wBAA8B;EAC5B,MAAM1B;CACR;CAEA2B,Q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ChByD,uBAAuB;EACvBC,MAAM;EACNC,QAAQ;EACRC,QAAQ;EACRC,eAAe;EACfpB,QAAQ;EACRqB,eAAe;EACfR,QAAQ;EACRT,WAAW;EACXU,OAAO;EACPhC,aAAa;EACbwC,UAAU;EACVrB,OAAO;CACT;CAEAsB,aAAa;CACbC,iBAAiB;CACjBC,YAAY;CAEZC,QAAQ;CACRC,cAAc,CAAA;CACdC,SAAS1E,KAAAA;CAET2E,SAAe;EACb,MAAMxF;CACR;CAEAyF,SAAS;EACP,OAAO,EACLrF,UAAU,KAAKD,UAAUuF,KAAK3E,SAASN,SAAS;GAC9CM;GACAD,UAAU,KAAKX,UAAUM,MAAM,EAAE,EAAEG,MAAM;EAC3C,EAAE,EACJ;CACF;CAEA4C,QAAc;EACZ,MAAMxD;CACR;CAEAqE,cAA2B;EACzB,aAAa,CAAC;CAChB;AACF"}
1
+ {"version":3,"file":"ReadonlyThreadRuntimeCore.js","names":["ThreadMessage","InertThreadRuntimeCore","createInertComposer","READONLY_THREAD_ERROR","Error","ReadonlyThreadRuntimeCore","error","_messages","messages","setMessages","_notifySubscribers","getMessageById","messageId","idx","findIndex","m","id","undefined","parentId","message","index","getBranches","export","map","composer","isLoading","cancelRun","stopSpeaking","disconnectVoice"],"sources":["../../../src/runtimes/readonly/ReadonlyThreadRuntimeCore.ts"],"sourcesContent":["import type { ThreadMessage } from \"../../types/message\";\nimport {\n InertThreadRuntimeCore,\n createInertComposer,\n} from \"../inert/InertThreadRuntimeCore\";\n\nconst READONLY_THREAD_ERROR = new Error(\n \"This is a readonly thread. You cannot perform mutations on readonly threads.\",\n);\n\nexport class ReadonlyThreadRuntimeCore extends InertThreadRuntimeCore {\n protected get error() {\n return READONLY_THREAD_ERROR;\n }\n\n private _messages: readonly ThreadMessage[] = [];\n\n get messages() {\n return this._messages;\n }\n\n setMessages(messages: readonly ThreadMessage[]) {\n if (this._messages === messages) return;\n this._messages = messages;\n this._notifySubscribers();\n }\n\n getMessageById(messageId: string) {\n const idx = this._messages.findIndex((m) => m.id === messageId);\n if (idx === -1) return undefined;\n return {\n parentId: this._messages[idx - 1]?.id ?? null,\n message: this._messages[idx]!,\n index: idx,\n };\n }\n\n getBranches(messageId: string) {\n const idx = this._messages.findIndex((m) => m.id === messageId);\n if (idx === -1) return [];\n return [messageId];\n }\n\n export() {\n return {\n messages: this._messages.map((message, idx) => ({\n message,\n parentId: this._messages[idx - 1]?.id ?? null,\n })),\n };\n }\n\n composer = createInertComposer(READONLY_THREAD_ERROR, false);\n\n isLoading = false;\n\n override cancelRun(): void {}\n\n override stopSpeaking(): void {}\n\n override disconnectVoice(): void {}\n}\n"],"mappings":";;AAMA,MAAMG,wCAAwB,IAAIC,MAChC,8EACF;AAEA,IAAaC,4BAAb,cAA+CJ,uBAAuB;CACpE,IAAcK,QAAQ;EACpB,OAAOH;CACT;CAEA,YAA8C,CAAA;CAE9C,IAAIK,WAAW;EACb,OAAO,KAAKD;CACd;CAEAE,YAAYD,UAAoC;EAC9C,IAAI,KAAKD,cAAcC,UAAU;EACjC,KAAKD,YAAYC;EACjB,KAAKE,mBAAmB;CAC1B;CAEAC,eAAeC,WAAmB;EAChC,MAAMC,MAAM,KAAKN,UAAUO,WAAWC,MAAMA,EAAEC,OAAOJ,SAAS;EAC9D,IAAIC,QAAQ,IAAI,OAAOI,KAAAA;EACvB,OAAO;GACLC,UAAU,KAAKX,UAAUM,MAAM,EAAE,EAAEG,MAAM;GACzCG,SAAS,KAAKZ,UAAUM;GACxBO,OAAOP;EACT;CACF;CAEAQ,YAAYT,WAAmB;EAE7B,IADY,KAAKL,UAAUO,WAAWC,MAAMA,EAAEC,OAAOJ,SACjDC,MAAQ,IAAI,OAAO,CAAA;EACvB,OAAO,CAACD,SAAS;CACnB;CAEAU,SAAS;EACP,OAAO,EACLd,UAAU,KAAKD,UAAUgB,KAAKJ,SAASN,SAAS;GAC9CM;GACAD,UAAU,KAAKX,UAAUM,MAAM,EAAE,EAAEG,MAAM;EAC3C,EAAE,EACJ;CACF;CAEAQ,WAAWtB,oBAAoBC,uBAAuB,KAAK;CAE3DsB,YAAY;CAEZ,YAA2B,CAAC;CAE5B,eAA8B,CAAC;CAE/B,kBAAiC,CAAC;AACpC"}
@@ -0,0 +1,9 @@
1
+ import { SILENT_RUNTIME_ACTION } from "../../utils/silent-runtime-action.js";
2
+ //#region src/runtimes/remote-thread-list/adapter-changed.d.ts
3
+ declare class ThreadListAdapterChangedError extends Error {
4
+ readonly [SILENT_RUNTIME_ACTION] = true;
5
+ constructor();
6
+ }
7
+ //#endregion
8
+ export { ThreadListAdapterChangedError };
9
+ //# sourceMappingURL=adapter-changed.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter-changed.d.ts","names":[],"sources":["../../../src/runtimes/remote-thread-list/adapter-changed.ts"],"mappings":";;cAEa,sCAAsC;YACvC"}
@@ -0,0 +1,13 @@
1
+ import { SILENT_RUNTIME_ACTION } from "../../utils/silent-runtime-action.js";
2
+ //#region src/runtimes/remote-thread-list/adapter-changed.ts
3
+ var ThreadListAdapterChangedError = class extends Error {
4
+ [SILENT_RUNTIME_ACTION] = true;
5
+ constructor() {
6
+ super("Thread list adapter changed while an operation was pending.");
7
+ this.name = "ThreadListAdapterChangedError";
8
+ }
9
+ };
10
+ //#endregion
11
+ export { ThreadListAdapterChangedError };
12
+
13
+ //# sourceMappingURL=adapter-changed.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter-changed.js","names":["SILENT_RUNTIME_ACTION","ThreadListAdapterChangedError","Error","constructor","name"],"sources":["../../../src/runtimes/remote-thread-list/adapter-changed.ts"],"sourcesContent":["import { SILENT_RUNTIME_ACTION } from \"../../utils/silent-runtime-action\";\n\nexport class ThreadListAdapterChangedError extends Error {\n readonly [SILENT_RUNTIME_ACTION] = true;\n\n constructor() {\n super(\"Thread list adapter changed while an operation was pending.\");\n this.name = \"ThreadListAdapterChangedError\";\n }\n}\n"],"mappings":";;AAEA,IAAaC,gCAAb,cAAmDC,MAAM;CACvD,CAAUF,yBAAyB;CAEnCG,cAAc;EACZ,MAAM,6DAA6D;EACnE,KAAKC,OAAO;CACd;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"empty-thread-core.d.ts","names":[],"sources":["../../../src/runtimes/remote-thread-list/empty-thread-core.ts"],"mappings":";;cAKa,mBAAmB"}
1
+ {"version":3,"file":"empty-thread-core.d.ts","names":[],"sources":["../../../src/runtimes/remote-thread-list/empty-thread-core.ts"],"mappings":";;cA2Ca,mBAAmB"}