@assistant-ui/core 0.2.9 → 0.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (437) hide show
  1. package/dist/adapters/attachment.d.ts.map +1 -1
  2. package/dist/adapters/attachment.js +22 -12
  3. package/dist/adapters/attachment.js.map +1 -1
  4. package/dist/adapters/directive-formatter.js.map +1 -1
  5. package/dist/adapters/speech.js.map +1 -1
  6. package/dist/index.d.ts +3 -1
  7. package/dist/index.js +2 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/internal.js +1 -1
  10. package/dist/model-context/frame/host.js.map +1 -1
  11. package/dist/model-context/frame/provider.js.map +1 -1
  12. package/dist/model-context/registry.js.map +1 -1
  13. package/dist/model-context/tool.d.ts +1 -1
  14. package/dist/model-context/tool.js +1 -1
  15. package/dist/model-context/tool.js.map +1 -1
  16. package/dist/model-context/types.js +17 -2
  17. package/dist/model-context/types.js.map +1 -1
  18. package/dist/react/AssistantProvider.js +1 -1
  19. package/dist/react/AssistantRuntimeProvider.d.ts +1 -1
  20. package/dist/react/AssistantRuntimeProvider.d.ts.map +1 -1
  21. package/dist/react/AssistantRuntimeProvider.js +1 -1
  22. package/dist/react/RuntimeAdapter.js +4 -2
  23. package/dist/react/RuntimeAdapter.js.map +1 -1
  24. package/dist/react/adapters/LocalStorageThreadListAdapter.d.ts.map +1 -1
  25. package/dist/react/adapters/LocalStorageThreadListAdapter.js +13 -3
  26. package/dist/react/adapters/LocalStorageThreadListAdapter.js.map +1 -1
  27. package/dist/react/client/DataRenderers.d.ts.map +1 -1
  28. package/dist/react/client/DataRenderers.js +6 -5
  29. package/dist/react/client/DataRenderers.js.map +1 -1
  30. package/dist/react/client/Interactables.d.ts.map +1 -1
  31. package/dist/react/client/Interactables.js +30 -29
  32. package/dist/react/client/Interactables.js.map +1 -1
  33. package/dist/react/client/Tools.d.ts.map +1 -1
  34. package/dist/react/client/Tools.js +19 -12
  35. package/dist/react/client/Tools.js.map +1 -1
  36. package/dist/react/index.d.ts +10 -5
  37. package/dist/react/index.js +7 -2
  38. package/dist/react/model-context/define-mcp-toolkit.d.ts +12 -0
  39. package/dist/react/model-context/define-mcp-toolkit.d.ts.map +1 -0
  40. package/dist/react/model-context/define-mcp-toolkit.js +14 -0
  41. package/dist/react/model-context/define-mcp-toolkit.js.map +1 -0
  42. package/dist/react/model-context/define-toolkit.d.ts +10 -12
  43. package/dist/react/model-context/define-toolkit.d.ts.map +1 -1
  44. package/dist/react/model-context/define-toolkit.js +2 -15
  45. package/dist/react/model-context/define-toolkit.js.map +1 -1
  46. package/dist/react/model-context/external-tool.d.ts +14 -0
  47. package/dist/react/model-context/external-tool.d.ts.map +1 -0
  48. package/dist/react/model-context/external-tool.js +17 -0
  49. package/dist/react/model-context/external-tool.js.map +1 -0
  50. package/dist/react/model-context/human-tool.d.ts +27 -0
  51. package/dist/react/model-context/human-tool.d.ts.map +1 -0
  52. package/dist/react/model-context/human-tool.js +30 -0
  53. package/dist/react/model-context/human-tool.js.map +1 -0
  54. package/dist/react/model-context/makeAssistantTool.d.ts +8 -0
  55. package/dist/react/model-context/makeAssistantTool.d.ts.map +1 -1
  56. package/dist/react/model-context/makeAssistantTool.js +4 -0
  57. package/dist/react/model-context/makeAssistantTool.js.map +1 -1
  58. package/dist/react/model-context/makeAssistantToolUI.d.ts +8 -0
  59. package/dist/react/model-context/makeAssistantToolUI.d.ts.map +1 -1
  60. package/dist/react/model-context/makeAssistantToolUI.js +4 -0
  61. package/dist/react/model-context/makeAssistantToolUI.js.map +1 -1
  62. package/dist/react/model-context/provider-tool.d.ts +15 -0
  63. package/dist/react/model-context/provider-tool.d.ts.map +1 -0
  64. package/dist/react/model-context/provider-tool.js +12 -0
  65. package/dist/react/model-context/provider-tool.js.map +1 -0
  66. package/dist/react/model-context/stub-tool.d.ts +12 -0
  67. package/dist/react/model-context/stub-tool.d.ts.map +1 -0
  68. package/dist/react/model-context/stub-tool.js +15 -0
  69. package/dist/react/model-context/stub-tool.js.map +1 -0
  70. package/dist/react/model-context/toolbox.d.ts +64 -17
  71. package/dist/react/model-context/toolbox.d.ts.map +1 -1
  72. package/dist/react/model-context/toolbox.js +19 -1
  73. package/dist/react/model-context/toolbox.js.map +1 -1
  74. package/dist/react/model-context/useAssistantContext.js +1 -1
  75. package/dist/react/model-context/useAssistantContext.js.map +1 -1
  76. package/dist/react/model-context/useAssistantDataUI.js +1 -1
  77. package/dist/react/model-context/useAssistantDataUI.js.map +1 -1
  78. package/dist/react/model-context/useAssistantInstructions.js +1 -1
  79. package/dist/react/model-context/useAssistantInstructions.js.map +1 -1
  80. package/dist/react/model-context/useAssistantInteractable.js +1 -1
  81. package/dist/react/model-context/useAssistantInteractable.js.map +1 -1
  82. package/dist/react/model-context/useAssistantTool.d.ts +11 -1
  83. package/dist/react/model-context/useAssistantTool.d.ts.map +1 -1
  84. package/dist/react/model-context/useAssistantTool.js +12 -6
  85. package/dist/react/model-context/useAssistantTool.js.map +1 -1
  86. package/dist/react/model-context/useAssistantToolUI.d.ts +13 -4
  87. package/dist/react/model-context/useAssistantToolUI.d.ts.map +1 -1
  88. package/dist/react/model-context/useAssistantToolUI.js +7 -4
  89. package/dist/react/model-context/useAssistantToolUI.js.map +1 -1
  90. package/dist/react/model-context/useAuiToolOverrides.d.ts +22 -0
  91. package/dist/react/model-context/useAuiToolOverrides.d.ts.map +1 -0
  92. package/dist/react/model-context/useAuiToolOverrides.js +31 -0
  93. package/dist/react/model-context/useAuiToolOverrides.js.map +1 -0
  94. package/dist/react/model-context/useInlineRender.js +1 -1
  95. package/dist/react/model-context/useInlineRender.js.map +1 -1
  96. package/dist/react/model-context/useInteractableState.js +1 -1
  97. package/dist/react/model-context/useInteractableState.js.map +1 -1
  98. package/dist/react/model-context/useToolArgsStatus.js +1 -1
  99. package/dist/react/primitive-hooks/useActionBarCopy.js +1 -1
  100. package/dist/react/primitive-hooks/useActionBarCopy.js.map +1 -1
  101. package/dist/react/primitive-hooks/useActionBarEdit.js +1 -1
  102. package/dist/react/primitive-hooks/useActionBarEdit.js.map +1 -1
  103. package/dist/react/primitive-hooks/useActionBarFeedback.js +1 -1
  104. package/dist/react/primitive-hooks/useActionBarFeedback.js.map +1 -1
  105. package/dist/react/primitive-hooks/useActionBarReload.js +1 -1
  106. package/dist/react/primitive-hooks/useActionBarReload.js.map +1 -1
  107. package/dist/react/primitive-hooks/useActionBarSpeak.js +1 -1
  108. package/dist/react/primitive-hooks/useActionBarSpeak.js.map +1 -1
  109. package/dist/react/primitive-hooks/useActionBarStopSpeaking.js +1 -1
  110. package/dist/react/primitive-hooks/useActionBarStopSpeaking.js.map +1 -1
  111. package/dist/react/primitive-hooks/useBranchPickerNext.js +1 -1
  112. package/dist/react/primitive-hooks/useBranchPickerNext.js.map +1 -1
  113. package/dist/react/primitive-hooks/useBranchPickerPrevious.js +1 -1
  114. package/dist/react/primitive-hooks/useBranchPickerPrevious.js.map +1 -1
  115. package/dist/react/primitive-hooks/useComposerAddAttachment.js +1 -1
  116. package/dist/react/primitive-hooks/useComposerAddAttachment.js.map +1 -1
  117. package/dist/react/primitive-hooks/useComposerCancel.js +1 -1
  118. package/dist/react/primitive-hooks/useComposerCancel.js.map +1 -1
  119. package/dist/react/primitive-hooks/useComposerDictate.js +1 -1
  120. package/dist/react/primitive-hooks/useComposerDictate.js.map +1 -1
  121. package/dist/react/primitive-hooks/useComposerSend.js +1 -1
  122. package/dist/react/primitive-hooks/useComposerSend.js.map +1 -1
  123. package/dist/react/primitive-hooks/useEditComposerCancel.js +1 -1
  124. package/dist/react/primitive-hooks/useEditComposerCancel.js.map +1 -1
  125. package/dist/react/primitive-hooks/useEditComposerSend.js +1 -1
  126. package/dist/react/primitive-hooks/useEditComposerSend.js.map +1 -1
  127. package/dist/react/primitive-hooks/useMessageBranching.js +1 -1
  128. package/dist/react/primitive-hooks/useMessageBranching.js.map +1 -1
  129. package/dist/react/primitive-hooks/useMessageReload.js +1 -1
  130. package/dist/react/primitive-hooks/useMessageReload.js.map +1 -1
  131. package/dist/react/primitive-hooks/useSuggestionTrigger.js +1 -1
  132. package/dist/react/primitive-hooks/useSuggestionTrigger.js.map +1 -1
  133. package/dist/react/primitive-hooks/useThreadListItemArchive.js +1 -1
  134. package/dist/react/primitive-hooks/useThreadListItemArchive.js.map +1 -1
  135. package/dist/react/primitive-hooks/useThreadListItemDelete.js +1 -1
  136. package/dist/react/primitive-hooks/useThreadListItemDelete.js.map +1 -1
  137. package/dist/react/primitive-hooks/useThreadListItemTrigger.js +1 -1
  138. package/dist/react/primitive-hooks/useThreadListItemTrigger.js.map +1 -1
  139. package/dist/react/primitive-hooks/useThreadListItemUnarchive.js +1 -1
  140. package/dist/react/primitive-hooks/useThreadListItemUnarchive.js.map +1 -1
  141. package/dist/react/primitive-hooks/useThreadListLoadMore.js +1 -1
  142. package/dist/react/primitive-hooks/useThreadListLoadMore.js.map +1 -1
  143. package/dist/react/primitive-hooks/useThreadListNew.js +1 -1
  144. package/dist/react/primitive-hooks/useThreadListNew.js.map +1 -1
  145. package/dist/react/primitive-hooks/useVoice.js +1 -1
  146. package/dist/react/primitive-hooks/useVoice.js.map +1 -1
  147. package/dist/react/primitives/chainOfThought/ChainOfThoughtParts.d.ts +1 -1
  148. package/dist/react/primitives/chainOfThought/ChainOfThoughtParts.js +1 -1
  149. package/dist/react/primitives/chainOfThought/ChainOfThoughtParts.js.map +1 -1
  150. package/dist/react/primitives/composer/ComposerAttachments.js +1 -1
  151. package/dist/react/primitives/composer/ComposerAttachments.js.map +1 -1
  152. package/dist/react/primitives/composer/ComposerQueue.js +1 -1
  153. package/dist/react/primitives/composer/ComposerQueue.js.map +1 -1
  154. package/dist/react/primitives/generativeUI/GenerativeUI.js +1 -1
  155. package/dist/react/primitives/generativeUI/GenerativeUI.js.map +1 -1
  156. package/dist/react/primitives/message/MessageAttachments.js +1 -1
  157. package/dist/react/primitives/message/MessageAttachments.js.map +1 -1
  158. package/dist/react/primitives/message/MessageGroupedParts.js +1 -1
  159. package/dist/react/primitives/message/MessageGroupedParts.js.map +1 -1
  160. package/dist/react/primitives/message/MessageParts.d.ts +1 -1
  161. package/dist/react/primitives/message/MessageParts.js +1 -1
  162. package/dist/react/primitives/message/MessageParts.js.map +1 -1
  163. package/dist/react/primitives/message/MessageQuote.js +1 -1
  164. package/dist/react/primitives/part/PartMessages.d.ts +12 -10
  165. package/dist/react/primitives/part/PartMessages.d.ts.map +1 -1
  166. package/dist/react/primitives/part/PartMessages.js +13 -11
  167. package/dist/react/primitives/part/PartMessages.js.map +1 -1
  168. package/dist/react/primitives/thread/ThreadMessages.js +1 -1
  169. package/dist/react/primitives/thread/ThreadMessages.js.map +1 -1
  170. package/dist/react/primitives/thread/ThreadSuggestions.js +1 -1
  171. package/dist/react/primitives/thread/ThreadSuggestions.js.map +1 -1
  172. package/dist/react/primitives/threadList/ThreadListItems.js +1 -1
  173. package/dist/react/primitives/threadList/ThreadListItems.js.map +1 -1
  174. package/dist/react/providers/AttachmentByIndexProvider.js.map +1 -1
  175. package/dist/react/providers/ChainOfThoughtByIndicesProvider.js.map +1 -1
  176. package/dist/react/providers/ChainOfThoughtPartByIndexProvider.js.map +1 -1
  177. package/dist/react/providers/MessageByIndexProvider.js.map +1 -1
  178. package/dist/react/providers/PartByIndexProvider.js.map +1 -1
  179. package/dist/react/providers/QueueItemByIndexProvider.js.map +1 -1
  180. package/dist/react/providers/ReadonlyThreadProvider.js +1 -1
  181. package/dist/react/providers/ReadonlyThreadProvider.js.map +1 -1
  182. package/dist/react/providers/SuggestionByIndexProvider.js.map +1 -1
  183. package/dist/react/providers/TextMessagePartProvider.d.ts.map +1 -1
  184. package/dist/react/providers/TextMessagePartProvider.js +4 -3
  185. package/dist/react/providers/TextMessagePartProvider.js.map +1 -1
  186. package/dist/react/providers/ThreadListItemByIndexProvider.js.map +1 -1
  187. package/dist/react/runtimes/RemoteThreadListHookInstanceManager.d.ts +7 -0
  188. package/dist/react/runtimes/RemoteThreadListHookInstanceManager.d.ts.map +1 -1
  189. package/dist/react/runtimes/RemoteThreadListHookInstanceManager.js +1 -1
  190. package/dist/react/runtimes/RemoteThreadListHookInstanceManager.js.map +1 -1
  191. package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts +8 -0
  192. package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts.map +1 -1
  193. package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js +29 -1
  194. package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js.map +1 -1
  195. package/dist/react/runtimes/RuntimeAdapterProvider.js +1 -1
  196. package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.js +1 -1
  197. package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.js.map +1 -1
  198. package/dist/react/runtimes/cloud/useCloudThreadListAdapter.d.ts.map +1 -1
  199. package/dist/react/runtimes/cloud/useCloudThreadListAdapter.js +10 -3
  200. package/dist/react/runtimes/cloud/useCloudThreadListAdapter.js.map +1 -1
  201. package/dist/react/runtimes/createMessageConverter.d.ts +2 -2
  202. package/dist/react/runtimes/createMessageConverter.d.ts.map +1 -1
  203. package/dist/react/runtimes/createMessageConverter.js.map +1 -1
  204. package/dist/react/runtimes/external-message-converter.d.ts +4 -3
  205. package/dist/react/runtimes/external-message-converter.d.ts.map +1 -1
  206. package/dist/react/runtimes/external-message-converter.js +1 -1
  207. package/dist/react/runtimes/external-message-converter.js.map +1 -1
  208. package/dist/react/runtimes/useExternalStoreRuntime.js +1 -1
  209. package/dist/react/runtimes/useExternalStoreSharedOptions.js +1 -1
  210. package/dist/react/runtimes/useLocalRuntime.d.ts +2 -1
  211. package/dist/react/runtimes/useLocalRuntime.d.ts.map +1 -1
  212. package/dist/react/runtimes/useLocalRuntime.js +4 -3
  213. package/dist/react/runtimes/useLocalRuntime.js.map +1 -1
  214. package/dist/react/runtimes/useRemoteThreadListRuntime.js +1 -1
  215. package/dist/react/runtimes/useRemoteThreadListRuntime.js.map +1 -1
  216. package/dist/react/utils/groupParts.d.ts +1 -1
  217. package/dist/react/utils/groupParts.js.map +1 -1
  218. package/dist/runtime/api/attachment-runtime.js.map +1 -1
  219. package/dist/runtime/api/composer-runtime.d.ts +8 -2
  220. package/dist/runtime/api/composer-runtime.d.ts.map +1 -1
  221. package/dist/runtime/api/composer-runtime.js +14 -0
  222. package/dist/runtime/api/composer-runtime.js.map +1 -1
  223. package/dist/runtime/api/message-part-runtime.js.map +1 -1
  224. package/dist/runtime/api/message-runtime.js +1 -1
  225. package/dist/runtime/api/message-runtime.js.map +1 -1
  226. package/dist/runtime/api/thread-list-item-runtime.d.ts +2 -0
  227. package/dist/runtime/api/thread-list-item-runtime.d.ts.map +1 -1
  228. package/dist/runtime/api/thread-list-item-runtime.js +6 -0
  229. package/dist/runtime/api/thread-list-item-runtime.js.map +1 -1
  230. package/dist/runtime/api/thread-runtime.d.ts +7 -0
  231. package/dist/runtime/api/thread-runtime.d.ts.map +1 -1
  232. package/dist/runtime/api/thread-runtime.js.map +1 -1
  233. package/dist/runtime/base/base-composer-runtime-core.d.ts +4 -0
  234. package/dist/runtime/base/base-composer-runtime-core.d.ts.map +1 -1
  235. package/dist/runtime/base/base-composer-runtime-core.js +7 -1
  236. package/dist/runtime/base/base-composer-runtime-core.js.map +1 -1
  237. package/dist/runtime/base/base-thread-runtime-core.js.map +1 -1
  238. package/dist/runtime/base/default-thread-composer-runtime-core.d.ts +4 -0
  239. package/dist/runtime/base/default-thread-composer-runtime-core.d.ts.map +1 -1
  240. package/dist/runtime/base/default-thread-composer-runtime-core.js +17 -1
  241. package/dist/runtime/base/default-thread-composer-runtime-core.js.map +1 -1
  242. package/dist/runtime/interfaces/composer-runtime-core.d.ts +6 -1
  243. package/dist/runtime/interfaces/composer-runtime-core.d.ts.map +1 -1
  244. package/dist/runtime/interfaces/thread-list-runtime-core.d.ts +1 -0
  245. package/dist/runtime/interfaces/thread-list-runtime-core.d.ts.map +1 -1
  246. package/dist/runtime/interfaces/thread-runtime-core.d.ts +4 -0
  247. package/dist/runtime/interfaces/thread-runtime-core.d.ts.map +1 -1
  248. package/dist/runtime/queue/external-thread-queue-adapter.d.ts +20 -0
  249. package/dist/runtime/queue/external-thread-queue-adapter.d.ts.map +1 -0
  250. package/dist/runtime/queue/external-thread-queue-adapter.js +0 -0
  251. package/dist/runtime/queue/message-queue.d.ts +20 -0
  252. package/dist/runtime/queue/message-queue.d.ts.map +1 -0
  253. package/dist/runtime/queue/message-queue.js +97 -0
  254. package/dist/runtime/queue/message-queue.js.map +1 -0
  255. package/dist/runtime/utils/message-repository.js.map +1 -1
  256. package/dist/runtime/utils/thread-message-like.js.map +1 -1
  257. package/dist/runtimes/external-store/external-store-adapter.d.ts +5 -1
  258. package/dist/runtimes/external-store/external-store-adapter.d.ts.map +1 -1
  259. package/dist/runtimes/external-store/external-store-runtime-core.js.map +1 -1
  260. package/dist/runtimes/external-store/external-store-thread-list-runtime-core.d.ts +1 -0
  261. package/dist/runtimes/external-store/external-store-thread-list-runtime-core.d.ts.map +1 -1
  262. package/dist/runtimes/external-store/external-store-thread-list-runtime-core.js +5 -0
  263. package/dist/runtimes/external-store/external-store-thread-list-runtime-core.js.map +1 -1
  264. package/dist/runtimes/external-store/external-store-thread-runtime-core.d.ts +4 -0
  265. package/dist/runtimes/external-store/external-store-thread-runtime-core.d.ts.map +1 -1
  266. package/dist/runtimes/external-store/external-store-thread-runtime-core.js +20 -2
  267. package/dist/runtimes/external-store/external-store-thread-runtime-core.js.map +1 -1
  268. package/dist/runtimes/local/local-runtime-core.js.map +1 -1
  269. package/dist/runtimes/local/local-runtime-options.d.ts +5 -0
  270. package/dist/runtimes/local/local-runtime-options.d.ts.map +1 -1
  271. package/dist/runtimes/local/local-thread-runtime-core.d.ts +7 -0
  272. package/dist/runtimes/local/local-thread-runtime-core.d.ts.map +1 -1
  273. package/dist/runtimes/local/local-thread-runtime-core.js +45 -0
  274. package/dist/runtimes/local/local-thread-runtime-core.js.map +1 -1
  275. package/dist/runtimes/readonly/ReadonlyThreadRuntimeCore.d.ts +3 -0
  276. package/dist/runtimes/readonly/ReadonlyThreadRuntimeCore.d.ts.map +1 -1
  277. package/dist/runtimes/readonly/ReadonlyThreadRuntimeCore.js +3 -0
  278. package/dist/runtimes/readonly/ReadonlyThreadRuntimeCore.js.map +1 -1
  279. package/dist/runtimes/remote-thread-list/adapter/in-memory.d.ts +1 -0
  280. package/dist/runtimes/remote-thread-list/adapter/in-memory.d.ts.map +1 -1
  281. package/dist/runtimes/remote-thread-list/adapter/in-memory.js +3 -0
  282. package/dist/runtimes/remote-thread-list/adapter/in-memory.js.map +1 -1
  283. package/dist/runtimes/remote-thread-list/empty-thread-core.d.ts.map +1 -1
  284. package/dist/runtimes/remote-thread-list/empty-thread-core.js +3 -0
  285. package/dist/runtimes/remote-thread-list/empty-thread-core.js.map +1 -1
  286. package/dist/runtimes/remote-thread-list/remote-thread-state.js.map +1 -1
  287. package/dist/runtimes/remote-thread-list/types.d.ts +1 -0
  288. package/dist/runtimes/remote-thread-list/types.d.ts.map +1 -1
  289. package/dist/runtimes/tool-invocations/ToolInvocationTracker.js.map +1 -1
  290. package/dist/store/clients/chain-of-thought-client.d.ts.map +1 -1
  291. package/dist/store/clients/chain-of-thought-client.js +6 -5
  292. package/dist/store/clients/chain-of-thought-client.js.map +1 -1
  293. package/dist/store/clients/model-context-client.d.ts.map +1 -1
  294. package/dist/store/clients/model-context-client.js +6 -5
  295. package/dist/store/clients/model-context-client.js.map +1 -1
  296. package/dist/store/clients/no-op-composer-client.d.ts.map +1 -1
  297. package/dist/store/clients/no-op-composer-client.js +4 -3
  298. package/dist/store/clients/no-op-composer-client.js.map +1 -1
  299. package/dist/store/clients/runtime-adapter.d.ts.map +1 -1
  300. package/dist/store/clients/runtime-adapter.js +7 -6
  301. package/dist/store/clients/runtime-adapter.js.map +1 -1
  302. package/dist/store/clients/suggestions.d.ts.map +1 -1
  303. package/dist/store/clients/suggestions.js +7 -6
  304. package/dist/store/clients/suggestions.js.map +1 -1
  305. package/dist/store/clients/thread-message-client.d.ts.map +1 -1
  306. package/dist/store/clients/thread-message-client.js +13 -12
  307. package/dist/store/clients/thread-message-client.js.map +1 -1
  308. package/dist/store/index.d.ts +1 -1
  309. package/dist/store/runtime-clients/attachment-runtime-client.d.ts.map +1 -1
  310. package/dist/store/runtime-clients/attachment-runtime-client.js +3 -3
  311. package/dist/store/runtime-clients/attachment-runtime-client.js.map +1 -1
  312. package/dist/store/runtime-clients/composer-runtime-client.d.ts +12 -5
  313. package/dist/store/runtime-clients/composer-runtime-client.d.ts.map +1 -1
  314. package/dist/store/runtime-clients/composer-runtime-client.js +32 -16
  315. package/dist/store/runtime-clients/composer-runtime-client.js.map +1 -1
  316. package/dist/store/runtime-clients/message-part-runtime-client.d.ts.map +1 -1
  317. package/dist/store/runtime-clients/message-part-runtime-client.js +3 -3
  318. package/dist/store/runtime-clients/message-part-runtime-client.js.map +1 -1
  319. package/dist/store/runtime-clients/message-runtime-client.d.ts +6 -3
  320. package/dist/store/runtime-clients/message-runtime-client.d.ts.map +1 -1
  321. package/dist/store/runtime-clients/message-runtime-client.js +17 -16
  322. package/dist/store/runtime-clients/message-runtime-client.js.map +1 -1
  323. package/dist/store/runtime-clients/thread-list-item-runtime-client.d.ts.map +1 -1
  324. package/dist/store/runtime-clients/thread-list-item-runtime-client.js +9 -7
  325. package/dist/store/runtime-clients/thread-list-item-runtime-client.js.map +1 -1
  326. package/dist/store/runtime-clients/thread-list-runtime-client.d.ts.map +1 -1
  327. package/dist/store/runtime-clients/thread-list-runtime-client.js +11 -10
  328. package/dist/store/runtime-clients/thread-list-runtime-client.js.map +1 -1
  329. package/dist/store/runtime-clients/thread-runtime-client.d.ts.map +1 -1
  330. package/dist/store/runtime-clients/thread-runtime-client.js +15 -14
  331. package/dist/store/runtime-clients/thread-runtime-client.js.map +1 -1
  332. package/dist/store/runtime-clients/useSubscribable.d.ts +7 -0
  333. package/dist/store/runtime-clients/useSubscribable.d.ts.map +1 -0
  334. package/dist/store/runtime-clients/useSubscribable.js +16 -0
  335. package/dist/store/runtime-clients/useSubscribable.js.map +1 -0
  336. package/dist/store/scope-registration.d.ts +1 -1
  337. package/dist/store/scopes/composer.d.ts +1 -1
  338. package/dist/store/scopes/queue-item.d.ts +2 -1
  339. package/dist/store/scopes/queue-item.d.ts.map +1 -1
  340. package/dist/store/scopes/queue-item.js +6 -0
  341. package/dist/store/scopes/queue-item.js.map +1 -0
  342. package/dist/store/scopes/thread-list-item.d.ts +1 -0
  343. package/dist/store/scopes/thread-list-item.d.ts.map +1 -1
  344. package/dist/store/scopes/thread.d.ts +1 -1
  345. package/dist/store/scopes/threads.d.ts +1 -1
  346. package/dist/types/message.d.ts +2 -1
  347. package/dist/types/message.d.ts.map +1 -1
  348. package/dist/types/message.js.map +1 -1
  349. package/dist/utils/composite-context-provider.d.ts +1 -1
  350. package/dist/utils/composite-context-provider.js +3 -1
  351. package/dist/utils/composite-context-provider.js.map +1 -1
  352. package/dist/utils/json/is-json.js.map +1 -1
  353. package/dist/utils/text.js.map +1 -1
  354. package/package.json +15 -11
  355. package/src/adapters/attachment.ts +24 -4
  356. package/src/index.ts +8 -0
  357. package/src/model-context/tool.ts +1 -1
  358. package/src/model-context/types.ts +21 -3
  359. package/src/react/RuntimeAdapter.ts +6 -4
  360. package/src/react/adapters/LocalStorageThreadListAdapter.tsx +15 -2
  361. package/src/react/client/DataRenderers.ts +48 -42
  362. package/src/react/client/Interactables.ts +263 -267
  363. package/src/react/client/Tools.ts +123 -115
  364. package/src/react/index.ts +16 -3
  365. package/src/react/model-context/define-mcp-toolkit.ts +16 -0
  366. package/src/react/model-context/define-toolkit.test.ts +101 -6
  367. package/src/react/model-context/define-toolkit.ts +35 -18
  368. package/src/react/model-context/external-tool.ts +16 -0
  369. package/src/react/model-context/human-tool.ts +32 -0
  370. package/src/react/model-context/makeAssistantTool.ts +8 -0
  371. package/src/react/model-context/makeAssistantToolUI.ts +8 -0
  372. package/src/react/model-context/provider-tool.ts +30 -0
  373. package/src/react/model-context/stub-tool.ts +14 -0
  374. package/src/react/model-context/toolbox.test.ts +182 -0
  375. package/src/react/model-context/toolbox.ts +191 -23
  376. package/src/react/model-context/useAssistantTool.ts +28 -8
  377. package/src/react/model-context/useAssistantToolUI.ts +13 -4
  378. package/src/react/model-context/useAuiToolOverrides.ts +38 -0
  379. package/src/react/primitives/message/MessageGroupedParts.tsx +1 -1
  380. package/src/react/primitives/part/PartMessages.tsx +12 -10
  381. package/src/react/providers/TextMessagePartProvider.tsx +31 -32
  382. package/src/react/runtimes/RemoteThreadListThreadListRuntimeCore.tsx +43 -0
  383. package/src/react/runtimes/cloud/useCloudThreadListAdapter.tsx +9 -0
  384. package/src/react/runtimes/createMessageConverter.ts +2 -1
  385. package/src/react/runtimes/external-message-converter.ts +5 -3
  386. package/src/react/runtimes/useLocalRuntime.ts +2 -0
  387. package/src/runtime/api/composer-runtime.ts +26 -0
  388. package/src/runtime/api/thread-list-item-runtime.ts +15 -0
  389. package/src/runtime/base/base-composer-runtime-core.ts +11 -0
  390. package/src/runtime/base/default-thread-composer-runtime-core.ts +22 -0
  391. package/src/runtime/interfaces/composer-runtime-core.ts +7 -0
  392. package/src/runtime/interfaces/thread-list-runtime-core.ts +4 -0
  393. package/src/runtime/interfaces/thread-runtime-core.ts +5 -0
  394. package/src/runtime/queue/external-thread-queue-adapter.ts +14 -0
  395. package/src/runtime/queue/message-queue.ts +128 -0
  396. package/src/runtimes/external-store/external-store-adapter.ts +10 -0
  397. package/src/runtimes/external-store/external-store-thread-list-runtime-core.ts +13 -0
  398. package/src/runtimes/external-store/external-store-thread-runtime-core.ts +31 -2
  399. package/src/runtimes/local/local-runtime-options.ts +6 -0
  400. package/src/runtimes/local/local-thread-runtime-core.ts +70 -0
  401. package/src/runtimes/readonly/ReadonlyThreadRuntimeCore.ts +4 -0
  402. package/src/runtimes/remote-thread-list/adapter/in-memory.ts +4 -0
  403. package/src/runtimes/remote-thread-list/empty-thread-core.ts +4 -0
  404. package/src/runtimes/remote-thread-list/types.ts +4 -0
  405. package/src/store/clients/chain-of-thought-client.ts +24 -25
  406. package/src/store/clients/model-context-client.test.ts +87 -2
  407. package/src/store/clients/model-context-client.ts +22 -19
  408. package/src/store/clients/no-op-composer-client.ts +69 -66
  409. package/src/store/clients/runtime-adapter.ts +9 -6
  410. package/src/store/clients/suggestions.ts +41 -40
  411. package/src/store/clients/thread-message-client.ts +127 -132
  412. package/src/store/runtime-clients/attachment-runtime-client.ts +7 -3
  413. package/src/store/runtime-clients/composer-runtime-client.ts +142 -113
  414. package/src/store/runtime-clients/message-part-runtime-client.ts +16 -14
  415. package/src/store/runtime-clients/message-runtime-client.ts +124 -122
  416. package/src/store/runtime-clients/thread-list-item-runtime-client.ts +44 -44
  417. package/src/store/runtime-clients/thread-list-runtime-client.ts +83 -80
  418. package/src/store/runtime-clients/thread-runtime-client.ts +113 -119
  419. package/src/store/runtime-clients/{tap-subscribable.ts → useSubscribable.ts} +4 -4
  420. package/src/store/scopes/queue-item.ts +2 -0
  421. package/src/store/scopes/thread-list-item.ts +1 -0
  422. package/src/tests/RemoteThreadListThreadListRuntimeCore-custom-metadata.test.ts +69 -1
  423. package/src/tests/attachment-adapters.test.ts +86 -0
  424. package/src/tests/external-store-thread-runtime-core.test.ts +125 -0
  425. package/src/tests/message-queue.test.ts +168 -0
  426. package/src/tests/thread-list-runtime-getLoadThreadsPromise.test.ts +1 -0
  427. package/src/types/message.ts +2 -0
  428. package/src/utils/composite-context-provider.ts +3 -1
  429. package/dist/react/model-context/hitl.d.ts +0 -19
  430. package/dist/react/model-context/hitl.d.ts.map +0 -1
  431. package/dist/react/model-context/hitl.js +0 -22
  432. package/dist/react/model-context/hitl.js.map +0 -1
  433. package/dist/store/runtime-clients/tap-subscribable.d.ts +0 -7
  434. package/dist/store/runtime-clients/tap-subscribable.d.ts.map +0 -1
  435. package/dist/store/runtime-clients/tap-subscribable.js +0 -16
  436. package/dist/store/runtime-clients/tap-subscribable.js.map +0 -1
  437. package/src/react/model-context/hitl.ts +0 -22
@@ -1,5 +1,7 @@
1
1
  import { generateId } from "../../utils/id.js";
2
2
  import { fromThreadMessageLike } from "../../runtime/utils/thread-message-like.js";
3
+ import { EMPTY_QUEUE_ITEMS } from "../../store/scopes/queue-item.js";
4
+ import { createMessageQueue } from "../../runtime/queue/message-queue.js";
3
5
  import { BaseThreadRuntimeCore } from "../../runtime/base/base-thread-runtime-core.js";
4
6
  import { shouldContinue } from "./should-continue.js";
5
7
  //#region src/runtimes/local/local-thread-runtime-core.ts
@@ -27,6 +29,8 @@ var LocalThreadRuntimeCore = class extends BaseThreadRuntimeCore {
27
29
  queue: false
28
30
  };
29
31
  abortController = null;
32
+ _queue = null;
33
+ _queueRunInFlight = false;
30
34
  isDisabled = false;
31
35
  isSendDisabled = false;
32
36
  _isLoading = false;
@@ -85,6 +89,24 @@ var LocalThreadRuntimeCore = class extends BaseThreadRuntimeCore {
85
89
  this.capabilities.feedback = canFeedback;
86
90
  hasUpdates = true;
87
91
  }
92
+ const canQueue = options.unstable_enableMessageQueue === true;
93
+ if (canQueue && !this._queue) {
94
+ this._queue = createMessageQueue({ run: (message) => {
95
+ this._queueRunInFlight = true;
96
+ this._runAppend(message).finally(() => {
97
+ this._queueRunInFlight = false;
98
+ this._queue?.notifyIdle();
99
+ }).catch(() => {});
100
+ } });
101
+ this._queue.subscribe(() => this._notifySubscribers());
102
+ } else if (!canQueue && this._queue) {
103
+ this._queue.adapter.clear("cancel-run");
104
+ this._queue = null;
105
+ }
106
+ if (this.capabilities.queue !== canQueue) {
107
+ this.capabilities.queue = canQueue;
108
+ hasUpdates = true;
109
+ }
88
110
  if (hasUpdates) this._notifySubscribers();
89
111
  }
90
112
  _loadPromise;
@@ -111,6 +133,25 @@ var LocalThreadRuntimeCore = class extends BaseThreadRuntimeCore {
111
133
  return this._loadPromise;
112
134
  }
113
135
  async append(message) {
136
+ const isTail = message.parentId === (this.messages.at(-1)?.id ?? null);
137
+ const willRun = message.startRun ?? message.role === "user";
138
+ if (this._queue && willRun && isTail) {
139
+ this._queue.adapter.enqueue(message, { steer: message.steer ?? false });
140
+ return;
141
+ }
142
+ if (this._queue && !isTail) this._queue.adapter.clear("edit");
143
+ return this._runAppend(message);
144
+ }
145
+ getQueueItems() {
146
+ return this._queue?.adapter.items ?? EMPTY_QUEUE_ITEMS;
147
+ }
148
+ steerQueueItem(queueItemId) {
149
+ this._queue?.adapter.steer(queueItemId);
150
+ }
151
+ removeQueueItem(queueItemId) {
152
+ this._queue?.adapter.remove(queueItemId);
153
+ }
154
+ async _runAppend(message) {
114
155
  this.ensureInitialized();
115
156
  const initPromise = this._getInitializePromise?.();
116
157
  if (initPromise) await initPromise;
@@ -162,6 +203,7 @@ var LocalThreadRuntimeCore = class extends BaseThreadRuntimeCore {
162
203
  };
163
204
  this._notifyEventSubscribers("runStart", {});
164
205
  try {
206
+ this._queue?.notifyBusy();
165
207
  this._suggestions = [];
166
208
  this._suggestionsController?.abort();
167
209
  this._suggestionsController = null;
@@ -172,6 +214,7 @@ var LocalThreadRuntimeCore = class extends BaseThreadRuntimeCore {
172
214
  } while (shouldContinue(message, this._options.unstable_humanToolNames));
173
215
  } finally {
174
216
  this._notifyEventSubscribers("runEnd", {});
217
+ if (!this._queueRunInFlight) queueMicrotask(() => this._queue?.notifyIdle());
175
218
  }
176
219
  this._suggestionsController = new AbortController();
177
220
  const signal = this._suggestionsController.signal;
@@ -299,11 +342,13 @@ var LocalThreadRuntimeCore = class extends BaseThreadRuntimeCore {
299
342
  return message;
300
343
  }
301
344
  detach() {
345
+ this._queue?.adapter.clear("cancel-run");
302
346
  const error = new AbortError(true);
303
347
  this.abortController?.abort(error);
304
348
  this.abortController = null;
305
349
  }
306
350
  cancelRun() {
351
+ this._queue?.adapter.clear("cancel-run");
307
352
  const error = new AbortError(false);
308
353
  this.abortController?.abort(error);
309
354
  this.abortController = null;
@@ -1 +1 @@
1
- {"version":3,"file":"local-thread-runtime-core.js","names":[],"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 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 type { ModelContextProvider } from \"../../model-context/types\";\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 reload: true,\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 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 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 if (hasUpdates) this._notifySubscribers();\n }\n\n private _loadPromise: Promise<void> | undefined;\n public __internal_load() {\n if (this._loadPromise) return this._loadPromise;\n\n const promise = this.adapters.history?.load() ?? Promise.resolve(null);\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 this.ensureInitialized();\n\n const initPromise = this._getInitializePromise?.();\n if (initPromise) {\n await initPromise;\n }\n\n const newMessage = fromThreadMessageLike(message, generateId(), {\n type: \"complete\",\n reason: \"unknown\",\n });\n this.repository.addOrUpdateMessage(message.parentId, newMessage);\n this._options.adapters.history?.append({\n parentId: message.parentId,\n message: newMessage,\n ...(message.runConfig !== undefined && { runConfig: message.runConfig }),\n });\n\n const startRun = message.startRun ?? message.role === \"user\";\n if (startRun) {\n await this.startRun({\n parentId: newMessage.id,\n sourceId: message.sourceId,\n runConfig: message.runConfig ?? {},\n });\n } else {\n this.repository.resetHead(newMessage.id);\n this._notifySubscribers();\n }\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 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 let 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 this._notifyEventSubscribers(\"runStart\", {});\n\n try {\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 runCallback,\n );\n runCallback = undefined;\n } while (shouldContinue(message, this._options.unstable_humanToolNames));\n } finally {\n this._notifyEventSubscribers(\"runEnd\", {});\n }\n\n this._suggestionsController = new AbortController();\n const signal = this._suggestionsController.signal;\n if (\n this.adapters.suggestion &&\n message.status?.type !== \"requires-action\"\n ) {\n const promiseOrGenerator = this.adapters.suggestion?.generate({\n messages: this.messages,\n });\n\n if (Symbol.asyncIterator in promiseOrGenerator) {\n for await (const r of promiseOrGenerator) {\n if (signal.aborted) break;\n this._suggestions = r;\n this._notifySubscribers();\n }\n } else {\n const result = await promiseOrGenerator;\n if (signal.aborted) return;\n this._suggestions = result;\n this._notifySubscribers();\n }\n }\n }\n\n private async performRoundtrip(\n parentId: string | null,\n message: ThreadAssistantMessage,\n runConfig: RunConfig | undefined,\n runCallback?: ChatModelAdapter[\"run\"],\n ) {\n const messages = parentId ? this.repository.getMessages(parentId) : [];\n\n // abort existing run\n this.abortController?.abort();\n this.abortController = new 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\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 const steps = message.metadata?.steps?.length ?? 0;\n if (steps >= maxSteps) {\n // reached max tool steps\n updateMessage({\n status: {\n type: \"incomplete\",\n reason: \"tool-calls\",\n },\n });\n return message;\n } else {\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\n try {\n this._lastRunConfig = runConfig ?? {};\n const context = this.getModelContext();\n\n runCallback =\n runCallback ??\n this.adapters.chatModel.run.bind(this.adapters.chatModel);\n\n const abortSignal = this.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: { type: \"complete\", reason: \"unknown\" },\n });\n }\n } catch (e) {\n // TODO this should be handled by the run result stream\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:\n e instanceof Error\n ? e.message\n : `[${typeof e}] ${new String(e).toString()}`,\n },\n });\n\n throw e;\n }\n } finally {\n this.abortController = null;\n\n if (\n message.status.type === \"complete\" ||\n message.status.type === \"incomplete\"\n ) {\n await this._options.adapters.history?.append({\n parentId,\n message: message,\n runConfig: this._lastRunConfig,\n });\n }\n }\n return message;\n }\n\n public detach() {\n const error = new AbortError(true);\n this.abortController?.abort(error);\n this.abortController = null;\n }\n\n public cancelRun() {\n const error = new AbortError(false);\n this.abortController?.abort(error);\n this.abortController = 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) 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\n if (\n added &&\n shouldContinue(message, this._options.unstable_humanToolNames)\n ) {\n this.performRoundtrip(parentId, message, this._lastRunConfig).catch(\n () => {},\n );\n }\n }\n\n public resumeToolCall(_options: ResumeToolCallOptions) {\n throw new Error(\"Local runtime does not support resuming tool calls.\");\n }\n\n public respondToToolApproval(_options: RespondToToolApprovalOptions) {\n throw new Error(\"Local runtime does not support tool approvals.\");\n }\n}\n"],"mappings":";;;;;AAyBA,IAAM,aAAN,cAAyB,MAAM;CAC7B,OAAgB;CAChB;CAEA,YAAY,QAAiB,SAAkB;EAC7C,MAAM,OAAO;EACb,KAAK,SAAS;CAChB;AACF;AAEA,IAAa,yBAAb,cACU,sBAEV;CACE,eAA+B;EAC7B,gBAAgB;EAChB,uBAAuB;EACvB,MAAM;EACN,QAAQ;EACR,QAAQ;EACR,eAAe;EACf,QAAQ;EACR,WAAW;EACX,OAAO;EACP,aAAa;EACb,UAAU;EACV,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GACH,SAAS;EACX;EACA,KAAK,WAAW,mBAAmB,UAAU,OAAO;EAEpD,IACE,SACA,eAAe,SAAS,KAAK,SAAS,uBAAuB,GAE7D,KAAK,iBAAiB,UAAU,SAAS,KAAK,cAAc,EAAE,YACtD,CAAC,CACT;CAEJ;CAEA,eAAsB,UAAiC;EACrD,MAAM,IAAI,MAAM,qDAAqD;CACvE;CAEA,sBAA6B,UAAwC;EACnE,MAAM,IAAI,MAAM,gDAAgD;CAClE;AACF"}
1
+ {"version":3,"file":"local-thread-runtime-core.js","names":[],"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 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 type { ModelContextProvider } from \"../../model-context/types\";\nimport {\n createMessageQueue,\n type MessageQueueController,\n} from \"../../runtime/queue/message-queue\";\nimport {\n EMPTY_QUEUE_ITEMS,\n type QueueItemState,\n} from \"../../store/scopes/queue-item\";\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 reload: true,\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\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 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 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 void this._runAppend(message)\n .finally(() => {\n this._queueRunInFlight = false;\n this._queue?.notifyIdle();\n })\n .catch(() => {});\n },\n });\n this._queue.subscribe(() => this._notifySubscribers());\n } else if (!canQueue && this._queue) {\n this._queue.adapter.clear(\"cancel-run\");\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\n private _loadPromise: Promise<void> | undefined;\n public __internal_load() {\n if (this._loadPromise) return this._loadPromise;\n\n const promise = this.adapters.history?.load() ?? Promise.resolve(null);\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 this._queue.adapter.enqueue(message, { steer: message.steer ?? false });\n return;\n }\n if (this._queue && !isTail) this._queue.adapter.clear(\"edit\");\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 steerQueueItem(queueItemId: string): void {\n this._queue?.adapter.steer(queueItemId);\n }\n\n public removeQueueItem(queueItemId: string): void {\n this._queue?.adapter.remove(queueItemId);\n }\n\n private async _runAppend(message: AppendMessage): Promise<void> {\n this.ensureInitialized();\n\n const initPromise = this._getInitializePromise?.();\n if (initPromise) {\n await initPromise;\n }\n\n const newMessage = fromThreadMessageLike(message, generateId(), {\n type: \"complete\",\n reason: \"unknown\",\n });\n this.repository.addOrUpdateMessage(message.parentId, newMessage);\n this._options.adapters.history?.append({\n parentId: message.parentId,\n message: newMessage,\n ...(message.runConfig !== undefined && { runConfig: message.runConfig }),\n });\n\n const startRun = message.startRun ?? message.role === \"user\";\n if (startRun) {\n await this.startRun({\n parentId: newMessage.id,\n sourceId: message.sourceId,\n runConfig: message.runConfig ?? {},\n });\n } else {\n this.repository.resetHead(newMessage.id);\n this._notifySubscribers();\n }\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 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 let 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 this._notifyEventSubscribers(\"runStart\", {});\n\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 runCallback,\n );\n runCallback = undefined;\n } while (shouldContinue(message, this._options.unstable_humanToolNames));\n } finally {\n this._notifyEventSubscribers(\"runEnd\", {});\n // queue-driven runs release from the driver settle handler; a direct\n // run (regenerate, resume) releases here\n if (!this._queueRunInFlight) {\n queueMicrotask(() => this._queue?.notifyIdle());\n }\n }\n\n this._suggestionsController = new AbortController();\n const signal = this._suggestionsController.signal;\n if (\n this.adapters.suggestion &&\n message.status?.type !== \"requires-action\"\n ) {\n const promiseOrGenerator = this.adapters.suggestion?.generate({\n messages: this.messages,\n });\n\n if (Symbol.asyncIterator in promiseOrGenerator) {\n for await (const r of promiseOrGenerator) {\n if (signal.aborted) break;\n this._suggestions = r;\n this._notifySubscribers();\n }\n } else {\n const result = await promiseOrGenerator;\n if (signal.aborted) return;\n this._suggestions = result;\n this._notifySubscribers();\n }\n }\n }\n\n private async performRoundtrip(\n parentId: string | null,\n message: ThreadAssistantMessage,\n runConfig: RunConfig | undefined,\n runCallback?: ChatModelAdapter[\"run\"],\n ) {\n const messages = parentId ? this.repository.getMessages(parentId) : [];\n\n // abort existing run\n this.abortController?.abort();\n this.abortController = new 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\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 const steps = message.metadata?.steps?.length ?? 0;\n if (steps >= maxSteps) {\n // reached max tool steps\n updateMessage({\n status: {\n type: \"incomplete\",\n reason: \"tool-calls\",\n },\n });\n return message;\n } else {\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\n try {\n this._lastRunConfig = runConfig ?? {};\n const context = this.getModelContext();\n\n runCallback =\n runCallback ??\n this.adapters.chatModel.run.bind(this.adapters.chatModel);\n\n const abortSignal = this.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: { type: \"complete\", reason: \"unknown\" },\n });\n }\n } catch (e) {\n // TODO this should be handled by the run result stream\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:\n e instanceof Error\n ? e.message\n : `[${typeof e}] ${new String(e).toString()}`,\n },\n });\n\n throw e;\n }\n } finally {\n this.abortController = null;\n\n if (\n message.status.type === \"complete\" ||\n message.status.type === \"incomplete\"\n ) {\n await this._options.adapters.history?.append({\n parentId,\n message: message,\n runConfig: this._lastRunConfig,\n });\n }\n }\n return message;\n }\n\n public detach() {\n this._queue?.adapter.clear(\"cancel-run\");\n const error = new AbortError(true);\n this.abortController?.abort(error);\n this.abortController = null;\n }\n\n public cancelRun() {\n this._queue?.adapter.clear(\"cancel-run\");\n const error = new AbortError(false);\n this.abortController?.abort(error);\n this.abortController = 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) 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\n if (\n added &&\n shouldContinue(message, this._options.unstable_humanToolNames)\n ) {\n this.performRoundtrip(parentId, message, this._lastRunConfig).catch(\n () => {},\n );\n }\n }\n\n public resumeToolCall(_options: ResumeToolCallOptions) {\n throw new Error(\"Local runtime does not support resuming tool calls.\");\n }\n\n public respondToToolApproval(_options: RespondToToolAp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ACxD,MAAM,EAAE,aAAa;EACrB,IAAI,EAAE,YAAY;EAElB,IAAI,QAAQ,SAAS,aACnB,MAAM,IAAI,MAAM,mDAAmD;EAErE,IAAI,QAAQ;EACZ,IAAI,QAAQ;EACZ,MAAM,aAAa,QAAQ,QAAQ,KAAK,MAAM;GAC5C,IAAI,EAAE,SAAS,aAAa,OAAO;GACnC,IAAI,EAAE,eAAe,YAAY,OAAO;GACxC,QAAQ;GACR,IAAI,CAAC,EAAE,QAAQ,QAAQ;GACvB,OAAO;IACL,GAAG;IACH;IACA;IACA;GACF;EACF,CAAC;EAED,IAAI,CAAC,OACH,MAAM,IAAI,MAAM,oDAAoD;EAEtE,UAAU;GACR,GAAG;GACH,SAAS;EACX;EACA,KAAK,WAAW,mBAAmB,UAAU,OAAO;EAEpD,IACE,SACA,eAAe,SAAS,KAAK,SAAS,uBAAuB,GAE7D,KAAK,iBAAiB,UAAU,SAAS,KAAK,cAAc,CAAC,CAAC,YACtD,CAAC,CACT;CAEJ;CAEA,eAAsB,UAAiC;EACrD,MAAM,IAAI,MAAM,qDAAqD;CACvE;CAEA,sBAA6B,UAAwC;EACnE,MAAM,IAAI,MAAM,gDAAgD;CAClE;AACF"}
@@ -53,6 +53,9 @@ declare class ReadonlyThreadRuntimeCore extends BaseSubscribable implements Thre
53
53
  clearAttachments(): Promise<void>;
54
54
  send(): never;
55
55
  cancel(): void;
56
+ queue: never[];
57
+ steerQueueItem(): void;
58
+ removeQueueItem(): void;
56
59
  dictation: undefined;
57
60
  startDictation(): never;
58
61
  stopDictation(): void;
@@ -1 +1 @@
1
- {"version":3,"file":"ReadonlyThreadRuntimeCore.d.ts","names":[],"sources":["../../../src/runtimes/readonly/ReadonlyThreadRuntimeCore.ts"],"mappings":";;;;;;cASa,yBAAA,SACH,gBAAA,YACG,iBAAA;EAAA,QAEH,SAAA;EAAA,IAEJ,QAAA,aAAQ,aAAA;EAIZ,WAAA,CAAY,QAAA,WAAmB,aAAA;EAM/B,cAAA,CAAe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;;;;EAeA,UAAA;EACA,cAAA;EACA,SAAA;EAEA,KAAA;EACA,WAAA;EACA,MAAA;EAEA,MAAA;EAIA,MAAA;;;;;;EASA,KAAA;EAIA,WAAA,IAAe,WAAA;AAAA"}
@@ -105,6 +105,9 @@ var ReadonlyThreadRuntimeCore = class extends BaseSubscribable {
105
105
  throw READONLY_THREAD_ERROR;
106
106
  },
107
107
  cancel() {},
108
+ queue: [],
109
+ steerQueueItem() {},
110
+ removeQueueItem() {},
108
111
  dictation: void 0,
109
112
  startDictation() {
110
113
  throw READONLY_THREAD_ERROR;
@@ -1 +1 @@
1
- {"version":3,"file":"ReadonlyThreadRuntimeCore.js","names":[],"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 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 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 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 reload: 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,MAAM,wCAAwB,IAAI,MAChC,8EACF;AAEA,IAAa,4BAAb,cACU,iBAEV;CACE,YAA8C,CAAC;CAE/C,IAAI,WAAW;EACb,OAAO,KAAK;CACd;CAEA,YAAY,UAAoC;EAC9C,IAAI,KAAK,cAAc,UAAU;EACjC,KAAK,YAAY;EACjB,KAAK,mBAAmB;CAC1B;CAEA,eAAe,WAAmB;EAChC,MAAM,MAAM,KAAK,UAAU,WAAW,MAAM,EAAE,OAAO,SAAS;EAC9D,IAAI,QAAQ,IAAI,OAAO,KAAA;EACvB,OAAO;GACL,UAAU,KAAK,UAAU,MAAM,IAAI,MAAM;GACzC,SAAS,KAAK,UAAU;GACxB,OAAO;EACT;CACF;CAEA,YAAY,WAAmB;EAE7B,IADY,KAAK,UAAU,WAAW,MAAM,EAAE,OAAO,SAC/C,MAAM,IAAI,OAAO,CAAC;EACxB,OAAO,CAAC,SAAS;CACnB;CAEA,iBAAuB;EACrB,MAAM;CACR;CAEA,SAAe;EACb,MAAM;CACR;CAEA,WAAiB;EACf,MAAM;CACR;CAEA,YAAkB;EAChB,MAAM;CACR;CAEA,YAAkB,CAAC;CAEnB,gBAAsB;EACpB,MAAM;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,iBAAiB;CACjB,YAAY;CAEZ,QAAQ;CACR,cAAc,CAAC;CACf,SAAS,KAAA;CAET,SAAe;EACb,MAAM;CACR;CAEA,SAAS;EACP,OAAO,EACL,UAAU,KAAK,UAAU,KAAK,SAAS,SAAS;GAC9C;GACA,UAAU,KAAK,UAAU,MAAM,IAAI,MAAM;EAC3C,EAAE,EACJ;CACF;CAEA,QAAc;EACZ,MAAM;CACR;CAEA,cAA2B;EACzB,aAAa,CAAC;CAChB;AACF"}
1
+ {"version":3,"file":"ReadonlyThreadRuntimeCore.js","names":[],"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 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 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 steerQueueItem() {},\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 reload: 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,MAAM,wCAAwB,IAAI,MAChC,8EACF;AAEA,IAAa,4BAAb,cACU,iBAEV;CACE,YAA8C,CAAC;CAE/C,IAAI,WAAW;EACb,OAAO,KAAK;CACd;CAEA,YAAY,UAAoC;EAC9C,IAAI,KAAK,cAAc,UAAU;EACjC,KAAK,YAAY;EACjB,KAAK,mBAAmB;CAC1B;CAEA,eAAe,WAAmB;EAChC,MAAM,MAAM,KAAK,UAAU,WAAW,MAAM,EAAE,OAAO,SAAS;EAC9D,IAAI,QAAQ,IAAI,OAAO,KAAA;EACvB,OAAO;GACL,UAAU,KAAK,UAAU,MAAM,EAAE,EAAE,MAAM;GACzC,SAAS,KAAK,UAAU;GACxB,OAAO;EACT;CACF;CAEA,YAAY,WAAmB;EAE7B,IADY,KAAK,UAAU,WAAW,MAAM,EAAE,OAAO,SAC/C,MAAM,IAAI,OAAO,CAAC;EACxB,OAAO,CAAC,SAAS;CACnB;CAEA,iBAAuB;EACrB,MAAM;CACR;CAEA,SAAe;EACb,MAAM;CACR;CAEA,WAAiB;EACf,MAAM;CACR;CAEA,YAAkB;EAChB,MAAM;CACR;CAEA,YAAkB,CAAC;CAEnB,gBAAsB;EACpB,MAAM;CACR;CAEA,iBAAu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EACb,UAAU;EACV,OAAO;CACT;CAEA,aAAa;CACb,iBAAiB;CACjB,YAAY;CAEZ,QAAQ;CACR,cAAc,CAAC;CACf,SAAS,KAAA;CAET,SAAe;EACb,MAAM;CACR;CAEA,SAAS;EACP,OAAO,EACL,UAAU,KAAK,UAAU,KAAK,SAAS,SAAS;GAC9C;GACA,UAAU,KAAK,UAAU,MAAM,EAAE,EAAE,MAAM;EAC3C,EAAE,EACJ;CACF;CAEA,QAAc;EACZ,MAAM;CACR;CAEA,cAA2B;EACzB,aAAa,CAAC;CAChB;AACF"}
@@ -5,6 +5,7 @@ import { AssistantStream } from "assistant-stream";
5
5
  declare class InMemoryThreadListAdapter implements RemoteThreadListAdapter {
6
6
  list(): Promise<RemoteThreadListResponse>;
7
7
  rename(): Promise<void>;
8
+ updateCustom(): Promise<void>;
8
9
  archive(): Promise<void>;
9
10
  unarchive(): Promise<void>;
10
11
  delete(): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"in-memory.d.ts","names":[],"sources":["../../../../src/runtimes/remote-thread-list/adapter/in-memory.ts"],"mappings":";;;;cAQa,yBAAA,YAAqC,uBAAA;EAChD,IAAA,IAAQ,OAAA,CAAQ,wBAAA;EAMhB,MAAA,IAAU,OAAA;EAIV,OAAA,IAAW,OAAA;EAIX,SAAA,IAAa,OAAA;EAIb,MAAA,IAAU,OAAA;EAIV,UAAA,CAAW,QAAA,WAAmB,OAAA,CAAQ,8BAAA;EAItC,aAAA,IAAiB,OAAA,CAAQ,eAAA;EAIzB,KAAA,CAAM,SAAA,WAAoB,OAAA,CAAQ,oBAAA;AAAA"}
1
+ {"version":3,"file":"in-memory.d.ts","names":[],"sources":["../../../../src/runtimes/remote-thread-list/adapter/in-memory.ts"],"mappings":";;;;cAQa,yBAAA,YAAqC,uBAAA;EAChD,IAAA,IAAQ,OAAA,CAAQ,wBAAA;EAMhB,MAAA,IAAU,OAAA;EAIV,YAAA,IAAgB,OAAA;EAIhB,OAAA,IAAW,OAAA;EAIX,SAAA,IAAa,OAAA;EAIb,MAAA,IAAU,OAAA;EAIV,UAAA,CAAW,QAAA,WAAmB,OAAA,CAAQ,8BAAA;EAItC,aAAA,IAAiB,OAAA,CAAQ,eAAA;EAIzB,KAAA,CAAM,SAAA,WAAoB,OAAA,CAAQ,oBAAA;AAAA"}
@@ -6,6 +6,9 @@ var InMemoryThreadListAdapter = class {
6
6
  rename() {
7
7
  return Promise.resolve();
8
8
  }
9
+ updateCustom() {
10
+ return Promise.resolve();
11
+ }
9
12
  archive() {
10
13
  return Promise.resolve();
11
14
  }
@@ -1 +1 @@
1
- {"version":3,"file":"in-memory.js","names":[],"sources":["../../../../src/runtimes/remote-thread-list/adapter/in-memory.ts"],"sourcesContent":["import type { AssistantStream, AssistantStreamChunk } from \"assistant-stream\";\nimport type {\n RemoteThreadInitializeResponse,\n RemoteThreadListAdapter,\n RemoteThreadListResponse,\n RemoteThreadMetadata,\n} from \"../types\";\n\nexport class InMemoryThreadListAdapter implements RemoteThreadListAdapter {\n list(): Promise<RemoteThreadListResponse> {\n return Promise.resolve({\n threads: [],\n });\n }\n\n rename(): Promise<void> {\n return Promise.resolve();\n }\n\n archive(): Promise<void> {\n return Promise.resolve();\n }\n\n unarchive(): Promise<void> {\n return Promise.resolve();\n }\n\n delete(): Promise<void> {\n return Promise.resolve();\n }\n\n initialize(threadId: string): Promise<RemoteThreadInitializeResponse> {\n return Promise.resolve({ remoteId: threadId, externalId: undefined });\n }\n\n generateTitle(): Promise<AssistantStream> {\n return Promise.resolve(new ReadableStream<AssistantStreamChunk>());\n }\n\n fetch(_threadId: string): Promise<RemoteThreadMetadata> {\n return Promise.reject(new Error(\"Thread not found\"));\n }\n}\n"],"mappings":";AAQA,IAAa,4BAAb,MAA0E;CACxE,OAA0C;EACxC,OAAO,QAAQ,QAAQ,EACrB,SAAS,CAAC,EACZ,CAAC;CACH;CAEA,SAAwB;EACtB,OAAO,QAAQ,QAAQ;CACzB;CAEA,UAAyB;EACvB,OAAO,QAAQ,QAAQ;CACzB;CAEA,YAA2B;EACzB,OAAO,QAAQ,QAAQ;CACzB;CAEA,SAAwB;EACtB,OAAO,QAAQ,QAAQ;CACzB;CAEA,WAAW,UAA2D;EACpE,OAAO,QAAQ,QAAQ;GAAE,UAAU;GAAU,YAAY,KAAA;EAAU,CAAC;CACtE;CAEA,gBAA0C;EACxC,OAAO,QAAQ,QAAQ,IAAI,eAAqC,CAAC;CACnE;CAEA,MAAM,WAAkD;EACtD,OAAO,QAAQ,uBAAO,IAAI,MAAM,kBAAkB,CAAC;CACrD;AACF"}
1
+ {"version":3,"file":"in-memory.js","names":[],"sources":["../../../../src/runtimes/remote-thread-list/adapter/in-memory.ts"],"sourcesContent":["import type { AssistantStream, AssistantStreamChunk } from \"assistant-stream\";\nimport type {\n RemoteThreadInitializeResponse,\n RemoteThreadListAdapter,\n RemoteThreadListResponse,\n RemoteThreadMetadata,\n} from \"../types\";\n\nexport class InMemoryThreadListAdapter implements RemoteThreadListAdapter {\n list(): Promise<RemoteThreadListResponse> {\n return Promise.resolve({\n threads: [],\n });\n }\n\n rename(): Promise<void> {\n return Promise.resolve();\n }\n\n updateCustom(): Promise<void> {\n return Promise.resolve();\n }\n\n archive(): Promise<void> {\n return Promise.resolve();\n }\n\n unarchive(): Promise<void> {\n return Promise.resolve();\n }\n\n delete(): Promise<void> {\n return Promise.resolve();\n }\n\n initialize(threadId: string): Promise<RemoteThreadInitializeResponse> {\n return Promise.resolve({ remoteId: threadId, externalId: undefined });\n }\n\n generateTitle(): Promise<AssistantStream> {\n return Promise.resolve(new ReadableStream<AssistantStreamChunk>());\n }\n\n fetch(_threadId: string): Promise<RemoteThreadMetadata> {\n return Promise.reject(new Error(\"Thread not found\"));\n }\n}\n"],"mappings":";AAQA,IAAa,4BAAb,MAA0E;CACxE,OAA0C;EACxC,OAAO,QAAQ,QAAQ,EACrB,SAAS,CAAC,EACZ,CAAC;CACH;CAEA,SAAwB;EACtB,OAAO,QAAQ,QAAQ;CACzB;CAEA,eAA8B;EAC5B,OAAO,QAAQ,QAAQ;CACzB;CAEA,UAAyB;EACvB,OAAO,QAAQ,QAAQ;CACzB;CAEA,YAA2B;EACzB,OAAO,QAAQ,QAAQ;CACzB;CAEA,SAAwB;EACtB,OAAO,QAAQ,QAAQ;CACzB;CAEA,WAAW,UAA2D;EACpE,OAAO,QAAQ,QAAQ;GAAE,UAAU;GAAU,YAAY,KAAA;EAAU,CAAC;CACtE;CAEA,gBAA0C;EACxC,OAAO,QAAQ,QAAQ,IAAI,eAAqC,CAAC;CACnE;CAEA,MAAM,WAAkD;EACtD,OAAO,QAAQ,uBAAO,IAAI,MAAM,kBAAkB,CAAC;CACrD;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,iBAAA,EAAmB,iBA0N/B"}
1
+ {"version":3,"file":"empty-thread-core.d.ts","names":[],"sources":["../../../src/runtimes/remote-thread-list/empty-thread-core.ts"],"mappings":";;;cAKa,iBAAA,EAAmB,iBA8N/B"}
@@ -92,6 +92,9 @@ const EMPTY_THREAD_CORE = {
92
92
  throw EMPTY_THREAD_ERROR;
93
93
  },
94
94
  cancel() {},
95
+ queue: [],
96
+ steerQueueItem() {},
97
+ removeQueueItem() {},
95
98
  dictation: void 0,
96
99
  startDictation() {
97
100
  throw EMPTY_THREAD_ERROR;
@@ -1 +1 @@
1
- {"version":3,"file":"empty-thread-core.js","names":[],"sources":["../../../src/runtimes/remote-thread-list/empty-thread-core.ts"],"sourcesContent":["import type { ThreadRuntimeCore } from \"../../runtime/interfaces/thread-runtime-core\";\n\nconst EMPTY_THREAD_ERROR = new Error(\n \"This is the empty thread, a placeholder for the main thread. You cannot perform any actions on this thread instance. This error is probably because you tried to call a thread method in your render function. Call the method inside a `useEffect` hook instead.\",\n);\nexport const EMPTY_THREAD_CORE: ThreadRuntimeCore = {\n getMessageById() {\n return undefined;\n },\n\n getBranches() {\n return [];\n },\n\n switchToBranch() {\n throw EMPTY_THREAD_ERROR;\n },\n\n append() {\n throw EMPTY_THREAD_ERROR;\n },\n\n startRun() {\n throw EMPTY_THREAD_ERROR;\n },\n\n resumeRun() {\n throw EMPTY_THREAD_ERROR;\n },\n\n cancelRun() {\n throw EMPTY_THREAD_ERROR;\n },\n\n addToolResult() {\n throw EMPTY_THREAD_ERROR;\n },\n\n resumeToolCall() {\n throw EMPTY_THREAD_ERROR;\n },\n\n respondToToolApproval() {\n throw EMPTY_THREAD_ERROR;\n },\n\n speak() {\n throw EMPTY_THREAD_ERROR;\n },\n\n stopSpeaking() {\n throw EMPTY_THREAD_ERROR;\n },\n\n connectVoice() {\n throw EMPTY_THREAD_ERROR;\n },\n\n disconnectVoice() {\n throw EMPTY_THREAD_ERROR;\n },\n\n getVoiceVolume: () => 0,\n subscribeVoiceVolume: () => () => {},\n\n muteVoice() {\n throw EMPTY_THREAD_ERROR;\n },\n\n unmuteVoice() {\n throw EMPTY_THREAD_ERROR;\n },\n\n submitFeedback() {\n throw EMPTY_THREAD_ERROR;\n },\n\n getModelContext() {\n return {};\n },\n\n exportExternalState() {\n throw EMPTY_THREAD_ERROR;\n },\n\n importExternalState() {\n throw EMPTY_THREAD_ERROR;\n },\n\n composer: {\n attachments: [],\n attachmentAccept: \"*\",\n\n async addAttachment() {\n throw EMPTY_THREAD_ERROR;\n },\n\n async removeAttachment() {\n throw EMPTY_THREAD_ERROR;\n },\n\n isEditing: true,\n\n canCancel: false,\n canSend: false,\n isEmpty: true,\n\n text: \"\",\n\n setText() {\n throw EMPTY_THREAD_ERROR;\n },\n\n role: \"user\",\n\n setRole() {\n throw EMPTY_THREAD_ERROR;\n },\n\n runConfig: {},\n\n setRunConfig() {\n throw EMPTY_THREAD_ERROR;\n },\n\n async reset() {\n // noop\n },\n\n async clearAttachments() {\n // noop\n },\n\n send() {\n throw EMPTY_THREAD_ERROR;\n },\n\n cancel() {\n // noop\n },\n\n dictation: undefined,\n\n startDictation() {\n throw EMPTY_THREAD_ERROR;\n },\n\n stopDictation() {\n // noop\n },\n\n quote: undefined,\n\n setQuote() {\n throw EMPTY_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() {\n throw EMPTY_THREAD_ERROR;\n },\n\n speech: undefined,\n voice: undefined,\n\n capabilities: {\n switchToBranch: false,\n switchBranchDuringRun: false,\n edit: false,\n reload: 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 },\n\n isDisabled: false,\n isSendDisabled: false,\n isLoading: true,\n\n messages: [],\n\n state: null,\n\n suggestions: [],\n\n extras: undefined,\n\n subscribe() {\n return () => {};\n },\n\n import() {\n throw EMPTY_THREAD_ERROR;\n },\n\n export() {\n return { messages: [] };\n },\n\n reset() {\n throw EMPTY_THREAD_ERROR;\n },\n\n unstable_on() {\n return () => {};\n },\n};\n"],"mappings":";AAEA,MAAM,qCAAqB,IAAI,MAC7B,mQACF;AACA,MAAa,oBAAuC;CAClD,iBAAiB,CAEjB;CAEA,cAAc;EACZ,OAAO,CAAC;CACV;CAEA,iBAAiB;EACf,MAAM;CACR;CAEA,SAAS;EACP,MAAM;CACR;CAEA,WAAW;EACT,MAAM;CACR;CAEA,YAAY;EACV,MAAM;CACR;CAEA,YAAY;EACV,MAAM;CACR;CAEA,gBAAgB;EACd,MAAM;CACR;CAEA,iBAAiB;EACf,MAAM;CACR;CAEA,wBAAwB;EACtB,MAAM;CACR;CAEA,QAAQ;EACN,MAAM;CACR;CAEA,eAAe;EACb,MAAM;CACR;CAEA,eAAe;EACb,MAAM;CACR;CAEA,kBAAkB;EAChB,MAAM;CACR;CAEA,sBAAsB;CACtB,kCAAkC,CAAC;CAEnC,YAAY;EACV,MAAM;CACR;CAEA,cAAc;EACZ,MAAM;CACR;CAEA,iBAAiB;EACf,MAAM;CACR;CA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-core.js","names":[],"sources":["../../../src/runtimes/remote-thread-list/empty-thread-core.ts"],"sourcesContent":["import type { ThreadRuntimeCore } from \"../../runtime/interfaces/thread-runtime-core\";\n\nconst EMPTY_THREAD_ERROR = new Error(\n \"This is the empty thread, a placeholder for the main thread. You cannot perform any actions on this thread instance. This error is probably because you tried to call a thread method in your render function. Call the method inside a `useEffect` hook instead.\",\n);\nexport const EMPTY_THREAD_CORE: ThreadRuntimeCore = {\n getMessageById() {\n return undefined;\n },\n\n getBranches() {\n return [];\n },\n\n switchToBranch() {\n throw EMPTY_THREAD_ERROR;\n },\n\n append() {\n throw EMPTY_THREAD_ERROR;\n },\n\n startRun() {\n throw EMPTY_THREAD_ERROR;\n },\n\n resumeRun() {\n throw EMPTY_THREAD_ERROR;\n },\n\n cancelRun() {\n throw EMPTY_THREAD_ERROR;\n },\n\n addToolResult() {\n throw EMPTY_THREAD_ERROR;\n },\n\n resumeToolCall() {\n throw EMPTY_THREAD_ERROR;\n },\n\n respondToToolApproval() {\n throw EMPTY_THREAD_ERROR;\n },\n\n speak() {\n throw EMPTY_THREAD_ERROR;\n },\n\n stopSpeaking() {\n throw EMPTY_THREAD_ERROR;\n },\n\n connectVoice() {\n throw EMPTY_THREAD_ERROR;\n },\n\n disconnectVoice() {\n throw EMPTY_THREAD_ERROR;\n },\n\n getVoiceVolume: () => 0,\n subscribeVoiceVolume: () => () => {},\n\n muteVoice() {\n throw EMPTY_THREAD_ERROR;\n },\n\n unmuteVoice() {\n throw EMPTY_THREAD_ERROR;\n },\n\n submitFeedback() {\n throw EMPTY_THREAD_ERROR;\n },\n\n getModelContext() {\n return {};\n },\n\n exportExternalState() {\n throw EMPTY_THREAD_ERROR;\n },\n\n importExternalState() {\n throw EMPTY_THREAD_ERROR;\n },\n\n composer: {\n attachments: [],\n attachmentAccept: \"*\",\n\n async addAttachment() {\n throw EMPTY_THREAD_ERROR;\n },\n\n async removeAttachment() {\n throw EMPTY_THREAD_ERROR;\n },\n\n isEditing: true,\n\n canCancel: false,\n canSend: false,\n isEmpty: true,\n\n text: \"\",\n\n setText() {\n throw EMPTY_THREAD_ERROR;\n },\n\n role: \"user\",\n\n setRole() {\n throw EMPTY_THREAD_ERROR;\n },\n\n runConfig: {},\n\n setRunConfig() {\n throw EMPTY_THREAD_ERROR;\n },\n\n async reset() {\n // noop\n },\n\n async clearAttachments() {\n // noop\n },\n\n send() {\n throw EMPTY_THREAD_ERROR;\n },\n\n cancel() {\n // noop\n },\n\n queue: [] as never[],\n steerQueueItem() {},\n removeQueueItem() {},\n\n dictation: undefined,\n\n startDictation() {\n throw EMPTY_THREAD_ERROR;\n },\n\n stopDictation() {\n // noop\n },\n\n quote: undefined,\n\n setQuote() {\n throw EMPTY_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() {\n throw EMPTY_THREAD_ERROR;\n },\n\n speech: undefined,\n voice: undefined,\n\n capabilities: {\n switchToBranch: false,\n switchBranchDuringRun: false,\n edit: false,\n reload: 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 },\n\n isDisabled: false,\n isSendDisabled: false,\n isLoading: true,\n\n messages: [],\n\n state: null,\n\n suggestions: [],\n\n extras: undefined,\n\n subscribe() {\n return () => {};\n },\n\n import() {\n throw EMPTY_THREAD_ERROR;\n },\n\n export() {\n return { messages: [] };\n },\n\n reset() {\n throw EMPTY_THREAD_ERROR;\n },\n\n unstable_on() {\n return () => {};\n },\n};\n"],"mappings":";AAEA,MAAM,qCAAqB,IAAI,MAC7B,mQACF;AACA,MAAa,oBAAuC;CAClD,iBAAiB,CAEjB;CAEA,cAAc;EACZ,OAAO,CAAC;CACV;CAEA,iBAAiB;EACf,MAAM;CACR;CAEA,SAAS;EACP,MAAM;CACR;CAEA,WAAW;EACT,MAAM;CACR;CAEA,YAAY;EACV,MAAM;CACR;CA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QAAQ;EACR,QAAQ;EACR,eAAe;EACf,QAAQ;EACR,WAAW;EACX,OAAO;EACP,aAAa;EACb,UAAU;EACV,OAAO;CACT;CAEA,YAAY;CACZ,gBAAgB;CAChB,WAAW;CAEX,UAAU,CAAC;CAEX,OAAO;CAEP,aAAa,CAAC;CAEd,QAAQ,KAAA;CAER,YAAY;EACV,aAAa,CAAC;CAChB;CAEA,SAAS;EACP,MAAM;CACR;CAEA,SAAS;EACP,OAAO,EAAE,UAAU,CAAC,EAAE;CACxB;CAEA,QAAQ;EACN,MAAM;CACR;CAEA,cAAc;EACZ,aAAa,CAAC;CAChB;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"remote-thread-state.js","names":["_exhaustiveCheck"],"sources":["../../../src/runtimes/remote-thread-list/remote-thread-state.ts"],"sourcesContent":["import type {\n RemoteThreadInitializeResponse,\n RemoteThreadMetadata,\n} from \"./types\";\n\nexport type RemoteThreadData =\n | {\n readonly id: string;\n readonly remoteId: undefined;\n readonly externalId: undefined;\n readonly status: \"new\";\n readonly title: undefined;\n readonly custom: undefined;\n }\n | {\n readonly id: string;\n readonly initializeTask: Promise<RemoteThreadInitializeResponse>;\n readonly remoteId: undefined;\n readonly externalId: undefined;\n readonly status: \"regular\" | \"archived\";\n readonly title?: string | undefined;\n readonly custom: undefined;\n }\n | {\n readonly id: string;\n readonly initializeTask: Promise<RemoteThreadInitializeResponse>;\n readonly remoteId: string;\n readonly externalId: string | undefined;\n readonly status: \"regular\" | \"archived\";\n readonly title?: string | undefined;\n readonly custom?: Record<string, unknown> | undefined;\n };\n\nexport type THREAD_MAPPING_ID = string & { __brand: \"THREAD_MAPPING_ID\" };\n\nexport function createThreadMappingId(id: string): THREAD_MAPPING_ID {\n return id as THREAD_MAPPING_ID;\n}\n\nexport const normalizeCursor = (c: string | undefined): string | undefined =>\n c || undefined;\n\ntype ClassifyAccumulator = {\n threadIds: string[];\n archivedThreadIds: string[];\n threadIdMap: Record<string, THREAD_MAPPING_ID>;\n threadData: Record<THREAD_MAPPING_ID, RemoteThreadData>;\n};\n\nexport const classifyThreads = (\n threads: readonly RemoteThreadMetadata[],\n acc: ClassifyAccumulator,\n): ClassifyAccumulator => {\n for (const thread of threads) {\n if (acc.threadIdMap[thread.remoteId] !== undefined) continue;\n\n switch (thread.status) {\n case \"regular\":\n acc.threadIds.push(thread.remoteId);\n break;\n case \"archived\":\n acc.archivedThreadIds.push(thread.remoteId);\n break;\n default: {\n const _exhaustiveCheck: never = thread.status;\n throw new Error(`Unsupported state: ${_exhaustiveCheck}`);\n }\n }\n\n const mappingId = createThreadMappingId(thread.remoteId);\n acc.threadIdMap[thread.remoteId] = mappingId;\n acc.threadData[mappingId] = {\n id: thread.remoteId,\n remoteId: thread.remoteId,\n externalId: thread.externalId,\n status: thread.status,\n title: thread.title,\n custom: thread.custom,\n initializeTask: Promise.resolve({\n remoteId: thread.remoteId,\n externalId: thread.externalId,\n }),\n };\n }\n return acc;\n};\n\nexport type RemoteThreadState = {\n readonly isLoading: boolean;\n readonly isLoadingMore: boolean;\n readonly cursor: string | undefined;\n readonly newThreadId: string | undefined;\n readonly threadIds: readonly string[];\n readonly archivedThreadIds: readonly string[];\n readonly threadIdMap: Readonly<Record<string, THREAD_MAPPING_ID>>;\n readonly threadData: Readonly<Record<THREAD_MAPPING_ID, RemoteThreadData>>;\n};\n\nexport const getThreadData = (\n state: RemoteThreadState,\n threadIdOrRemoteId: string,\n) => {\n const idx = state.threadIdMap[threadIdOrRemoteId];\n if (idx === undefined) return undefined;\n return state.threadData[idx];\n};\n\nexport const updateStatusReducer = (\n state: RemoteThreadState,\n threadIdOrRemoteId: string,\n newStatus: \"regular\" | \"archived\" | \"deleted\",\n) => {\n const data = getThreadData(state, threadIdOrRemoteId);\n if (!data) return state;\n\n const { id, remoteId, status: lastStatus } = data;\n if (lastStatus === newStatus) return state;\n\n const newState = { ...state };\n\n // lastStatus\n switch (lastStatus) {\n case \"new\":\n newState.newThreadId = undefined;\n break;\n case \"regular\":\n newState.threadIds = newState.threadIds.filter((t) => t !== id);\n break;\n case \"archived\":\n newState.archivedThreadIds = newState.archivedThreadIds.filter(\n (t) => t !== id,\n );\n break;\n\n default: {\n const _exhaustiveCheck: never = lastStatus;\n throw new Error(`Unsupported state: ${_exhaustiveCheck}`);\n }\n }\n\n // newStatus\n switch (newStatus) {\n case \"regular\":\n newState.threadIds = [id, ...newState.threadIds];\n break;\n\n case \"archived\":\n newState.archivedThreadIds = [id, ...newState.archivedThreadIds];\n break;\n\n case \"deleted\":\n newState.threadData = Object.fromEntries(\n Object.entries(newState.threadData).filter(([key]) => key !== id),\n );\n newState.threadIdMap = Object.fromEntries(\n Object.entries(newState.threadIdMap).filter(\n ([key]) => key !== id && key !== remoteId,\n ),\n );\n break;\n\n default: {\n const _exhaustiveCheck: never = newStatus;\n throw new Error(`Unsupported state: ${_exhaustiveCheck}`);\n }\n }\n\n if (newStatus !== \"deleted\") {\n newState.threadData = {\n ...newState.threadData,\n [id]: {\n ...data,\n status: newStatus,\n },\n };\n }\n\n return newState;\n};\n"],"mappings":";AAmCA,SAAgB,sBAAsB,IAA+B;CACnE,OAAO;AACT;AAEA,MAAa,mBAAmB,MAC9B,KAAK,KAAA;AASP,MAAa,mBACX,SACA,QACwB;CACxB,KAAK,MAAM,UAAU,SAAS;EAC5B,IAAI,IAAI,YAAY,OAAO,cAAc,KAAA,GAAW;EAEpD,QAAQ,OAAO,QAAf;GACE,KAAK;IACH,IAAI,UAAU,KAAK,OAAO,QAAQ;IAClC;GACF,KAAK;IACH,IAAI,kBAAkB,KAAK,OAAO,QAAQ;IAC1C;GACF,SAAS;IACP,MAAM,mBAA0B,OAAO;IACvC,MAAM,IAAI,MAAM,sBAAsB,kBAAkB;GAC1D;EACF;EAEA,MAAM,YAAY,sBAAsB,OAAO,QAAQ;EACvD,IAAI,YAAY,OAAO,YAAY;EACnC,IAAI,WAAW,aAAa;GAC1B,IAAI,OAAO;GACX,UAAU,OAAO;GACjB,YAAY,OAAO;GACnB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pB,GAAG,SAAS;GACX,KAAK;GACJ,GAAG;GACH,QAAQ;EACV;CACF;CAGF,OAAO;AACT"}
1
+ {"version":3,"file":"remote-thread-state.js","names":["_exhaustiveCheck"],"sources":["../../../src/runtimes/remote-thread-list/remote-thread-state.ts"],"sourcesContent":["import type {\n RemoteThreadInitializeResponse,\n RemoteThreadMetadata,\n} from \"./types\";\n\nexport type RemoteThreadData =\n | {\n readonly id: string;\n readonly remoteId: undefined;\n readonly externalId: undefined;\n readonly status: \"new\";\n readonly title: undefined;\n readonly custom: undefined;\n }\n | {\n readonly id: string;\n readonly initializeTask: Promise<RemoteThreadInitializeResponse>;\n readonly remoteId: undefined;\n readonly externalId: undefined;\n readonly status: \"regular\" | \"archived\";\n readonly title?: string | undefined;\n readonly custom: undefined;\n }\n | {\n readonly id: string;\n readonly initializeTask: Promise<RemoteThreadInitializeResponse>;\n readonly remoteId: string;\n readonly externalId: string | undefined;\n readonly status: \"regular\" | \"archived\";\n readonly title?: string | undefined;\n readonly custom?: Record<string, unknown> | undefined;\n };\n\nexport type THREAD_MAPPING_ID = string & { __brand: \"THREAD_MAPPING_ID\" };\n\nexport function createThreadMappingId(id: string): THREAD_MAPPING_ID {\n return id as THREAD_MAPPING_ID;\n}\n\nexport const normalizeCursor = (c: string | undefined): string | undefined =>\n c || undefined;\n\ntype ClassifyAccumulator = {\n threadIds: string[];\n archivedThreadIds: string[];\n threadIdMap: Record<string, THREAD_MAPPING_ID>;\n threadData: Record<THREAD_MAPPING_ID, RemoteThreadData>;\n};\n\nexport const classifyThreads = (\n threads: readonly RemoteThreadMetadata[],\n acc: ClassifyAccumulator,\n): ClassifyAccumulator => {\n for (const thread of threads) {\n if (acc.threadIdMap[thread.remoteId] !== undefined) continue;\n\n switch (thread.status) {\n case \"regular\":\n acc.threadIds.push(thread.remoteId);\n break;\n case \"archived\":\n acc.archivedThreadIds.push(thread.remoteId);\n break;\n default: {\n const _exhaustiveCheck: never = thread.status;\n throw new Error(`Unsupported state: ${_exhaustiveCheck}`);\n }\n }\n\n const mappingId = createThreadMappingId(thread.remoteId);\n acc.threadIdMap[thread.remoteId] = mappingId;\n acc.threadData[mappingId] = {\n id: thread.remoteId,\n remoteId: thread.remoteId,\n externalId: thread.externalId,\n status: thread.status,\n title: thread.title,\n custom: thread.custom,\n initializeTask: Promise.resolve({\n remoteId: thread.remoteId,\n externalId: thread.externalId,\n }),\n };\n }\n return acc;\n};\n\nexport type RemoteThreadState = {\n readonly isLoading: boolean;\n readonly isLoadingMore: boolean;\n readonly cursor: string | undefined;\n readonly newThreadId: string | undefined;\n readonly threadIds: readonly string[];\n readonly archivedThreadIds: readonly string[];\n readonly threadIdMap: Readonly<Record<string, THREAD_MAPPING_ID>>;\n readonly threadData: Readonly<Record<THREAD_MAPPING_ID, RemoteThreadData>>;\n};\n\nexport const getThreadData = (\n state: RemoteThreadState,\n threadIdOrRemoteId: string,\n) => {\n const idx = state.threadIdMap[threadIdOrRemoteId];\n if (idx === undefined) return undefined;\n return state.threadData[idx];\n};\n\nexport const updateStatusReducer = (\n state: RemoteThreadState,\n threadIdOrRemoteId: string,\n newStatus: \"regular\" | \"archived\" | \"deleted\",\n) => {\n const data = getThreadData(state, threadIdOrRemoteId);\n if (!data) return state;\n\n const { id, remoteId, status: lastStatus } = data;\n if (lastStatus === newStatus) return state;\n\n const newState = { ...state };\n\n // lastStatus\n switch (lastStatus) {\n case \"new\":\n newState.newThreadId = undefined;\n break;\n case \"regular\":\n newState.threadIds = newState.threadIds.filter((t) => t !== id);\n break;\n case \"archived\":\n newState.archivedThreadIds = newState.archivedThreadIds.filter(\n (t) => t !== id,\n );\n break;\n\n default: {\n const _exhaustiveCheck: never = lastStatus;\n throw new Error(`Unsupported state: ${_exhaustiveCheck}`);\n }\n }\n\n // newStatus\n switch (newStatus) {\n case \"regular\":\n newState.threadIds = [id, ...newState.threadIds];\n break;\n\n case \"archived\":\n newState.archivedThreadIds = [id, ...newState.archivedThreadIds];\n break;\n\n case \"deleted\":\n newState.threadData = Object.fromEntries(\n Object.entries(newState.threadData).filter(([key]) => key !== id),\n );\n newState.threadIdMap = Object.fromEntries(\n Object.entries(newState.threadIdMap).filter(\n ([key]) => key !== id && key !== remoteId,\n ),\n );\n break;\n\n default: {\n const _exhaustiveCheck: never = newStatus;\n throw new Error(`Unsupported state: ${_exhaustiveCheck}`);\n }\n }\n\n if (newStatus !== \"deleted\") {\n newState.threadData = {\n ...newState.threadData,\n [id]: {\n ...data,\n status: newStatus,\n },\n };\n }\n\n return newState;\n};\n"],"mappings":";AAmCA,SAAgB,sBAAsB,IAA+B;CACnE,OAAO;AACT;AAEA,MAAa,mBAAmB,MAC9B,KAAK,KAAA;AASP,MAAa,mBACX,SACA,QACwB;CACxB,KAAK,MAAM,UAAU,SAAS;EAC5B,IAAI,IAAI,YAAY,OAAO,cAAc,KAAA,GAAW;EAEpD,QAAQ,OAAO,QAAf;GACE,KAAK;IACH,IAAI,UAAU,KAAK,OAAO,QAAQ;IAClC;GACF,KAAK;IACH,IAAI,kBAAkB,KAAK,OAAO,QAAQ;IAC1C;GACF,SAAS;IACP,MAAM,mBAA0B,OAAO;IACvC,MAAM,IAAI,MAAM,sBAAsB,kBAAkB;GAC1D;EACF;EAEA,MAAM,YAAY,sBAAsB,OAAO,QAAQ;EACvD,IAAI,YAAY,OAAO,YAAY;EACnC,IAAI,WAAW,aAAa;GAC1B,IAAI,OAAO;GACX,UAAU,OAAO;GACjB,YAAY,OAAO;GACnB,QAAQ,OAAO;GACf,OAAO,OAAO;GACd,QAAQ,OAAO;GACf,gBAAgB,QAAQ,QAAQ;IAC9B,UAAU,OAAO;IACjB,YAAY,OAAO;GACrB,CAAC;EACH;CACF;CACA,OAAO;AACT;AAaA,MAAa,iBACX,OACA,uBACG;CACH,MAAM,MAAM,MAAM,YAAY;CAC9B,IAAI,QAAQ,KAAA,GAAW,OAAO,KAAA;CAC9B,OAAO,MAAM,WAAW;AAC1B;AAEA,MAAa,uBACX,OACA,oBACA,cACG;CACH,MAAM,OAAO,cAAc,OAAO,kBAAkB;CACpD,IAAI,CAAC,MAAM,OAAO;CAElB,MAAM,EAAE,IAAI,UAAU,QAAQ,eAAe;CAC7C,IAAI,eAAe,WAAW,OAAO;CAErC,MAAM,WAAW,EAAE,GAAG,MAAM;CAG5B,QAAQ,YAAR;EACE,KAAK;GACH,SAAS,cAAc,KAAA;GACvB;EACF,KAAK;GACH,SAAS,YAAY,SAAS,UAAU,QAAQ,MAAM,MAAM,EAAE;GAC9D;EACF,KAAK;GACH,SAAS,oBAAoB,SAAS,kBAAkB,QACrD,MAAM,MAAM,EACf;GACA;EAEF,SAEE,MAAM,IAAI,MAAM,sBAAsBA,YAAkB;CAE5D;CAGA,QAAQ,WAAR;EACE,KAAK;GACH,SAAS,YAAY,CAAC,IAAI,GAAG,SAAS,SAAS;GAC/C;EAEF,KAAK;GACH,SAAS,oBAAoB,CAAC,IAAI,GAAG,SAAS,iBAAiB;GAC/D;EAEF,KAAK;GACH,SAAS,aAAa,OAAO,YAC3B,OAAO,QAAQ,SAAS,UAAU,CAAC,CAAC,QAAQ,CAAC,SAAS,QAAQ,EAAE,CAClE;GACA,SAAS,cAAc,OAAO,YAC5B,OAAO,QAAQ,SAAS,WAAW,CAAC,CAAC,QAClC,CAAC,SAAS,QAAQ,MAAM,QAAQ,QACnC,CACF;GACA;EAEF,SAEE,MAAM,IAAI,MAAM,sBAAsBA,WAAkB;CAE5D;CAEA,IAAI,cAAc,WAChB,SAAS,aAAa;EACpB,GAAG,SAAS;GACX,KAAK;GACJ,GAAG;GACH,QAAQ;EACV;CACF;CAGF,OAAO;AACT"}
@@ -25,6 +25,7 @@ type RemoteThreadListPageOptions = {
25
25
  type RemoteThreadListAdapter = {
26
26
  list(params?: RemoteThreadListPageOptions): Promise<RemoteThreadListResponse>;
27
27
  rename(remoteId: string, newTitle: string): Promise<void>;
28
+ updateCustom?(remoteId: string, custom: Record<string, unknown> | undefined): Promise<void>;
28
29
  archive(remoteId: string): Promise<void>;
29
30
  unarchive(remoteId: string): Promise<void>;
30
31
  delete(remoteId: string): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","names":[],"sources":["../../../src/runtimes/remote-thread-list/types.ts"],"mappings":";;;;;;KAKY,8BAAA;EACV,QAAA;EACA,UAAU;AAAA;AAAA,KAGA,oBAAA;EAAA,SACD,MAAA;EAAA,SACA,QAAA;EAAA,SACA,UAAA;EAAA,SACA,KAAA;EAAA,SACA,MAAA,GAAS,MAAM;AAAA;AAAA,KAGd,wBAAA;EACV,OAAA,EAAS,oBAAoB;EAC7B,UAAA;AAAA;AAAA,KAGU,2BAAA;EACV,KAAK;AAAA;AAAA,KAGK,uBAAA;EACV,IAAA,CAAK,MAAA,GAAS,2BAAA,GAA8B,OAAA,CAAQ,wBAAA;EAEpD,MAAA,CAAO,QAAA,UAAkB,QAAA,WAAmB,OAAA;EAC5C,OAAA,CAAQ,QAAA,WAAmB,OAAA;EAC3B,SAAA,CAAU,QAAA,WAAmB,OAAA;EAC7B,MAAA,CAAO,QAAA,WAAmB,OAAA;EAC1B,UAAA,CAAW,QAAA,WAAmB,OAAA,CAAQ,8BAAA;EACtC,aAAA,CACE,QAAA,UACA,iBAAA,WAA4B,aAAA,KAC3B,OAAA,CAAQ,eAAA;EACX,KAAA,CAAM,QAAA,WAAmB,OAAA,CAAQ,oBAAA;EAnBvB;AAGZ;;;;AACO;AAGP;;;;EAwBE,iBAAA,GAAoB,aAAA,CAAc,iBAAA;AAAA;AAAA,KAGxB,uBAAA;EACV,WAAA,QAAmB,gBAAA;EACnB,OAAA,EAAS,uBAAuB;EAvBN;;;;;;;EAgC1B,eAAA;EAdkC;;;;;EAqBlC,QAAA;EA5CK;;;;;EAmDL,YAAA;AAAA"}
1
+ {"version":3,"file":"types.d.ts","names":[],"sources":["../../../src/runtimes/remote-thread-list/types.ts"],"mappings":";;;;;;KAKY,8BAAA;EACV,QAAA;EACA,UAAU;AAAA;AAAA,KAGA,oBAAA;EAAA,SACD,MAAA;EAAA,SACA,QAAA;EAAA,SACA,UAAA;EAAA,SACA,KAAA;EAAA,SACA,MAAA,GAAS,MAAM;AAAA;AAAA,KAGd,wBAAA;EACV,OAAA,EAAS,oBAAoB;EAC7B,UAAA;AAAA;AAAA,KAGU,2BAAA;EACV,KAAK;AAAA;AAAA,KAGK,uBAAA;EACV,IAAA,CAAK,MAAA,GAAS,2BAAA,GAA8B,OAAA,CAAQ,wBAAA;EAEpD,MAAA,CAAO,QAAA,UAAkB,QAAA,WAAmB,OAAA;EAC5C,YAAA,EACE,QAAA,UACA,MAAA,EAAQ,MAAA,gCACP,OAAA;EACH,OAAA,CAAQ,QAAA,WAAmB,OAAA;EAC3B,SAAA,CAAU,QAAA,WAAmB,OAAA;EAC7B,MAAA,CAAO,QAAA,WAAmB,OAAA;EAC1B,UAAA,CAAW,QAAA,WAAmB,OAAA,CAAQ,8BAAA;EACtC,aAAA,CACE,QAAA,UACA,iBAAA,WAA4B,aAAA,KAC3B,OAAA,CAAQ,eAAA;EACX,KAAA,CAAM,QAAA,WAAmB,OAAA,CAAQ,oBAAA;EApBvB;;;;AACL;AAGP;;;;;EA4BE,iBAAA,GAAoB,aAAA,CAAc,iBAAA;AAAA;AAAA,KAGxB,uBAAA;EACV,WAAA,QAAmB,gBAAA;EACnB,OAAA,EAAS,uBAAuB;EAxBH;;;;;;;EAiC7B,eAAA;EA1ByB;;;;;EAiCzB,QAAA;EAhDc;;;;;EAuDd,YAAA;AAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"ToolInvocationTracker.js","names":[],"sources":["../../../src/runtimes/tool-invocations/ToolInvocationTracker.ts"],"sourcesContent":["declare const process: { env: { NODE_ENV?: string } };\n\nimport {\n createAssistantStreamController,\n type ToolCallStreamController,\n ToolResponse,\n unstable_toolResultStream,\n type Tool,\n type ToolModelContentPart,\n} from \"assistant-stream\";\nimport {\n AssistantMetaTransformStream,\n type ReadonlyJSONValue,\n} from \"assistant-stream/utils\";\nimport { isJSONValueEqual } from \"../../utils/json/is-json-equal\";\nimport type { ThreadMessage } from \"../../types/message\";\n\n/**\n * Streaming execution state for a frontend tool.\n */\nexport type ToolExecutionStatus =\n | { type: \"executing\" }\n | {\n type: \"interrupt\";\n payload: { type: \"human\"; payload: unknown };\n };\n\nexport type AddToolResultCommand = {\n readonly type: \"add-tool-result\";\n readonly toolCallId: string;\n readonly toolName: string;\n readonly result: ReadonlyJSONValue;\n readonly isError: boolean;\n readonly artifact?: ReadonlyJSONValue;\n readonly modelContent?: readonly ToolModelContentPart[];\n};\n\nexport type ToolInvocationTrackerSnapshot = {\n readonly messages: readonly ThreadMessage[];\n /** Whether the producing runtime is currently streaming new output. */\n readonly isRunning: boolean;\n /**\n * Whether the producing runtime is still loading historical state.\n * When `true`, every snapshot is treated as historical (no `streamCall` /\n * `execute` fires). When `false`, processing resumes as live.\n */\n readonly isLoading?: boolean;\n};\n\nexport type ToolInvocationTrackerCallbacks = {\n /**\n * Invoked when a client-side `execute()` returns a result and the runtime\n * needs to feed it back into the conversation.\n */\n onResult: (command: AddToolResultCommand) => void;\n /**\n * Invoked whenever the per-tool-call status map changes (executing /\n * interrupt / cleared). The callback receives a fresh map; mutating the\n * argument is not supported.\n */\n onStatusesChange: (\n statuses: ReadonlyMap<string, ToolExecutionStatus>,\n ) => void;\n};\n\ntype ToolCallEntry = {\n toolName: string;\n argsText: string;\n hasResult: boolean;\n} & (\n | {\n /** Restored phase — observed during a history-load snapshot. */\n controller?: undefined;\n argsComplete?: undefined;\n }\n | {\n /** Active phase — chunks are flowing through `controller`. */\n controller: ToolCallStreamController;\n argsComplete: boolean;\n }\n);\n\nconst isArgsTextComplete = (argsText: string) => {\n try {\n JSON.parse(argsText);\n return true;\n } catch {\n return false;\n }\n};\n\nconst parseArgsText = (argsText: string) => {\n try {\n return JSON.parse(argsText);\n } catch {\n return undefined;\n }\n};\n\nconst isEquivalentCompleteArgsText = (previous: string, next: string) => {\n const previousValue = parseArgsText(previous);\n const nextValue = parseArgsText(next);\n if (previousValue === undefined || nextValue === undefined) return false;\n return isJSONValueEqual(previousValue, nextValue);\n};\n\n/**\n * Plain-class port of the former `useToolInvocations` React hook. Owns the\n * assistant-stream pipeline that drives client-side `streamCall` / `execute`\n * for tool-call parts surfaced by a thread runtime, plus the per-tool-call\n * status map that consumers render against.\n *\n * **Contract**: `streamCall` (and `execute`) fires exactly once per logical\n * `toolCallId`. Args mutations after first completion, result replacement,\n * and result clearing are *not* surfaced through additional `streamCall`\n * invocations — by design — so hosts cannot observe spurious re-fires of\n * side effects. The follow-up `reader.events()` API will expose those\n * post-completion transitions to consumers that opt in.\n *\n * State-transition safety: every public method that observes runtime state\n * (`setState`, `reset`, `abort`, `resume`) wraps its work in try/catch and\n * logs to `console.error` rather than throwing. The tracker is built into\n * the hot message-processing path, so a malformed snapshot must never crash\n * the host runtime. See ./EDGE_CASES.md for the known non-trivial state\n * transitions and what each does today.\n */\nexport class ToolInvocationTracker {\n private readonly _getTools: () => Record<string, Tool> | undefined;\n private readonly _callbacks: ToolInvocationTrackerCallbacks;\n\n private readonly _entries = new Map<string, ToolCallEntry>();\n /**\n * Tool call ids whose `execute` should be short-circuited in the wrapper.\n * Populated when an entry is created with a result already attached\n * (history reload, mid-run resume, etc.) — `execute` is suppressed so\n * client-side side effects don't double-run. Membership outlives the\n * entry: `reset()` deliberately does *not* clear this so post-abort\n * cancellation `result` chunks for pre-resolved entries can still be\n * recognized and dropped. Growth is bounded by the number of pre-resolved\n * tool calls observed in the session.\n */\n private readonly _skipExecuteStreamIds = new Set<string>();\n private readonly _humanInput = new Map<\n string,\n {\n resolve: (payload: unknown) => void;\n reject: (reason: unknown) => void;\n }\n >();\n /** In-flight `execute` invocations keyed by tool call id. */\n private readonly _executing = new Set<string>();\n private readonly _settledResolvers: Array<() => void> = [];\n\n private _statuses = new Map<string, ToolExecutionStatus>();\n\n private _ac: AbortController = new AbortController();\n private _pendingRestore = true;\n\n /** Cached last snapshot, used to skip processing on identical re-renders. */\n private _lastSnapshot: ToolInvocationTrackerSnapshot | null = null;\n private _isRunning = false;\n\n private _controller!: ReturnType<typeof createAssistantStreamController>[1];\n\n /**\n * Set when the assistant-stream pipeline has died (errored out via\n * `.pipeTo(...).catch(...)`). The next `setState` re-initializes the\n * pipeline and demotes all active entries to restored so they survive\n * across the restart without re-firing `streamCall` (preserves the\n * \"exactly once\" contract). Capped at a single auto-restart per session\n * — repeated failures keep the tracker dead with a more visible error.\n */\n private _pipelineDead = false;\n private _pipelineRestartUsed = false;\n\n constructor(\n getTools: () => Record<string, Tool> | undefined,\n callbacks: ToolInvocationTrackerCallbacks,\n ) {\n this._getTools = getTools;\n this._callbacks = callbacks;\n\n this._initPipeline();\n }\n\n /**\n * Build the assistant-stream pipeline. Called once from the constructor\n * and at most once again if `_pipelineDead` is set (see F.4 in\n * EDGE_CASES.md).\n */\n private _initPipeline(): void {\n const [stream, controller] = createAssistantStreamController();\n this._controller = controller;\n\n const transform = unstable_toolResultStream(\n () => this._getWrappedTools(),\n () => this._ac.signal,\n (toolCallId, payload) => this._onHumanInput(toolCallId, payload),\n {\n onExecutionStart: (id) => this._onExecutionStart(id),\n onExecutionEnd: (id) => this._onExecutionEnd(id),\n },\n );\n\n stream\n .pipeThrough(transform)\n .pipeThrough(new AssistantMetaTransformStream())\n .pipeTo(\n new WritableStream({\n write: (chunk) => {\n try {\n if (chunk.type !== \"result\") return;\n this._handleResultChunk(chunk);\n } catch (err) {\n console.error(\n \"[ToolInvocationTracker] result chunk handling failed\",\n err,\n );\n }\n },\n }),\n )\n .catch((err) => {\n console.error(\n \"[ToolInvocationTracker] stream pipeline failed; will attempt single restart on next setState\",\n err,\n );\n this._pipelineDead = true;\n });\n }\n\n // ───────────────────────── public API ─────────────────────────\n\n /**\n * Feed the next observed snapshot into the tracker. Called from the host\n * runtime whenever its message list / running state changes.\n */\n public setState(snapshot: ToolInvocationTrackerSnapshot): void {\n try {\n // Recover from a dead pipeline before processing anything. We demote\n // all active entries to \"restored\" so the rebuilt pipeline does not\n // re-fire `streamCall` for tool calls that already fired pre-death;\n // preserves the \"exactly once per toolCallId\" contract.\n if (this._pipelineDead) {\n if (this._pipelineRestartUsed) {\n // Already retried once and failed again. Stay dead.\n return;\n }\n this._pipelineRestartUsed = true;\n this._pipelineDead = false;\n this._demoteEntriesToRestored();\n this._executing.clear();\n this._ac = new AbortController();\n this._initPipeline();\n // Fall through and process the snapshot against the fresh pipeline.\n }\n\n // Identical snapshot — skip processing entirely. Note: external-store\n // runtimes rebuild the messages array on every adapter update, so this\n // fast-path rarely triggers there; it's primarily for the React-hook\n // shim where state references are stable.\n if (\n this._lastSnapshot &&\n this._lastSnapshot.messages === snapshot.messages &&\n this._lastSnapshot.isRunning === snapshot.isRunning &&\n this._lastSnapshot.isLoading === snapshot.isLoading\n ) {\n return;\n }\n\n // While the host is still loading initial state, treat every snapshot\n // as historical: tool calls are recorded so the next live snapshot can\n // diff against them, but `streamCall` / `execute` do not fire.\n const restoreFromLoading = snapshot.isLoading === true;\n if (restoreFromLoading) {\n this._pendingRestore = true;\n }\n\n // E.4 / AF3 — only mark `_lastSnapshot`/`_isRunning` as observed after\n // processing succeeds. If `_processMessages` throws, the next snapshot\n // (even if identical) gets re-processed against the recovered state.\n const previousIsRunning = this._isRunning;\n this._isRunning = snapshot.isRunning;\n try {\n this._processMessages(snapshot.messages);\n } catch (err) {\n this._isRunning = previousIsRunning;\n throw err;\n }\n this._lastSnapshot = snapshot;\n this._pendingRestore = false;\n } catch (err) {\n console.error(\n \"[ToolInvocationTracker] setState failed; snapshot dropped\",\n err,\n );\n }\n }\n\n /**\n * Reset the tracker so the next observed snapshot is treated as historical.\n * Clears entries and aborts any in-flight executions. Used by callers like\n * `importExternalState` to mark a freshly loaded state as restored.\n */\n public reset(): void {\n try {\n this._pendingRestore = true;\n this._entries.clear();\n this._lastSnapshot = null;\n // `_skipExecuteStreamIds` is intentionally not cleared — see field doc.\n void this.abort().finally(() => {\n this._executing.clear();\n });\n } catch (err) {\n console.error(\"[ToolInvocationTracker] reset failed\", err);\n }\n }\n\n /**\n * Abort any in-flight `execute()` invocations. Resolves once all of them\n * have settled (or immediately if none are running).\n */\n public abort(): Promise<void> {\n try {\n this._humanInput.forEach(({ reject }) => {\n try {\n reject(new Error(\"Tool execution aborted\"));\n } catch {\n // host rejection handler threw — already in the abort path,\n // swallow so we continue cleaning up.\n }\n });\n this._humanInput.clear();\n\n this._ac.abort();\n this._ac = new AbortController();\n\n if (this._executing.size === 0) {\n return Promise.resolve();\n }\n return new Promise<void>((resolve) => {\n this._settledResolvers.push(resolve);\n });\n } catch (err) {\n console.error(\"[ToolInvocationTracker] abort failed\", err);\n return Promise.resolve();\n }\n }\n\n /**\n * Resolve a pending human-input request for the given tool call. Returns\n * `true` if a pending request was resumed, `false` if the tracker has no\n * outstanding request for that id (the caller should fall back to its own\n * dispatch path).\n */\n public resume(toolCallId: string, payload: unknown): boolean {\n try {\n const handlers = this._humanInput.get(toolCallId);\n if (!handlers) return false;\n this._humanInput.delete(toolCallId);\n this._setStatus(toolCallId, { type: \"executing\" });\n handlers.resolve(payload);\n return true;\n } catch (err) {\n console.error(\"[ToolInvocationTracker] resume failed\", err);\n return false;\n }\n }\n\n /**\n * Returns the current tool execution status map. The returned `Map` is\n * the tracker's internal store — do not mutate it. Treat the reference\n * as a snapshot that may be replaced wholesale on the next status\n * transition.\n */\n public getStatuses(): ReadonlyMap<string, ToolExecutionStatus> {\n return this._statuses;\n }\n\n // ───────────────────── internal: tool wrapping ─────────────────────\n\n private _getWrappedTools(): Record<string, Tool> | undefined {\n const tools = this._getTools();\n if (!tools) return undefined;\n\n return Object.fromEntries(\n Object.entries(tools).map(([name, tool]) => {\n const execute = tool.execute;\n if (execute === undefined) return [name, tool];\n\n const wrappedTool = {\n ...tool,\n execute: (\n ...[args, context]: Parameters<NonNullable<typeof execute>>\n ) => {\n if (this._skipExecuteStreamIds.has(context.toolCallId)) {\n // Pre-resolved tool call: never invoke the host's execute.\n // Returning a never-settling Promise keeps the executor's\n // pending entry alive but enqueues nothing.\n return new Promise(() => {}) as never;\n }\n return execute(args, context);\n },\n } as Tool;\n return [name, wrappedTool];\n }),\n ) as Record<string, Tool>;\n }\n\n // ──────────────── internal: execution lifecycle callbacks ────────────────\n\n private _onHumanInput(\n toolCallId: string,\n payload: unknown,\n ): Promise<unknown> {\n return new Promise<unknown>((resolve, reject) => {\n const previous = this._humanInput.get(toolCallId);\n if (previous) {\n try {\n previous.reject(\n new Error(\"Human input request was superseded by a new request\"),\n );\n } catch {\n // host rejection handler threw; ignore and proceed\n }\n }\n this._humanInput.set(toolCallId, { resolve, reject });\n this._setStatus(toolCallId, {\n type: \"interrupt\",\n payload: { type: \"human\", payload },\n });\n });\n }\n\n private _onExecutionStart(toolCallId: string): void {\n if (this._skipExecuteStreamIds.has(toolCallId)) return;\n\n this._executing.add(toolCallId);\n this._setStatus(toolCallId, { type: \"executing\" });\n }\n\n private _onExecutionEnd(toolCallId: string): void {\n if (!this._executing.delete(toolCallId)) return;\n\n this._deleteStatus(toolCallId);\n\n if (this._executing.size === 0) {\n const resolvers = this._settledResolvers.splice(0);\n resolvers.forEach((resolve) => {\n try {\n resolve();\n } catch {\n // ignore — settled-resolver consumer threw\n }\n });\n }\n }\n\n private _handleResultChunk(chunk: {\n type: \"result\";\n result: ReadonlyJSONValue;\n isError: boolean;\n artifact?: ReadonlyJSONValue;\n modelContent?: readonly ToolModelContentPart[];\n meta: { toolCallId: string; toolName: string };\n }): void {\n const toolCallId = chunk.meta.toolCallId;\n const entry = this._entries.get(toolCallId);\n\n // Pre-resolved tool call whose entry has been cleared by `reset()`.\n // The post-abort cancellation chunk lands here after the entry is\n // gone; suppress via the long-lived skip-execute marker.\n if (!entry && this._skipExecuteStreamIds.has(toolCallId)) {\n return;\n }\n\n // The host already set the result (via the live snapshot's\n // `setResponse` path). Suppress the executor's redundant emit.\n if (entry?.hasResult) return;\n\n this._invokeOnResult({\n type: \"add-tool-result\",\n toolCallId,\n toolName: chunk.meta.toolName,\n result: chunk.result,\n isError: chunk.isError,\n ...(chunk.artifact !== undefined && { artifact: chunk.artifact }),\n ...(chunk.modelContent !== undefined && {\n modelContent: chunk.modelContent,\n }),\n });\n }\n\n // ──────────────── internal: callback invocation (AF1/AF2) ────────────────\n\n private _invokeOnResult(command: AddToolResultCommand): void {\n try {\n this._callbacks.onResult(command);\n } catch (err) {\n console.error(\n \"[ToolInvocationTracker] onResult callback threw; result dropped\",\n err,\n );\n }\n }\n\n private _invokeOnStatusesChange(): void {\n try {\n this._callbacks.onStatusesChange(this._statuses);\n } catch (err) {\n console.error(\n \"[ToolInvocationTracker] onStatusesChange callback threw; status change not propagated\",\n err,\n );\n }\n }\n\n // ──────────────── internal: status map mutations ────────────────\n\n private _setStatus(toolCallId: string, status: ToolExecutionStatus): void {\n const next = new Map(this._statuses);\n next.set(toolCallId, status);\n this._statuses = next;\n this._invokeOnStatusesChange();\n }\n\n private _deleteStatus(toolCallId: string): void {\n if (!this._statuses.has(toolCallId)) return;\n const next = new Map(this._statuses);\n next.delete(toolCallId);\n this._statuses = next;\n this._invokeOnStatusesChange();\n }\n\n // ──────────────── internal: snapshot processing ────────────────\n\n private _hasExecutableTool(toolName: string): boolean {\n const tool = this._getTools()?.[toolName];\n return tool?.execute !== undefined || tool?.streamCall !== undefined;\n }\n\n private _shouldCloseArgsStream({\n toolName,\n argsText,\n hasResult,\n }: {\n toolName: string;\n argsText: string;\n hasResult: boolean;\n }): boolean {\n if (hasResult) return true;\n if (!this._hasExecutableTool(toolName)) {\n return !this._isRunning && isArgsTextComplete(argsText);\n }\n return isArgsTextComplete(argsText);\n }\n\n private _startActiveEntry(\n toolCallId: string,\n toolName: string,\n skipExecute: boolean,\n ): ToolCallEntry {\n const toolCallController = this._controller.addToolCallPart({\n toolName,\n toolCallId,\n });\n if (skipExecute) {\n this._skipExecuteStreamIds.add(toolCallId);\n }\n const entry: ToolCallEntry = {\n toolName,\n controller: toolCallController,\n argsText: \"\",\n hasResult: false,\n argsComplete: false,\n };\n this._entries.set(toolCallId, entry);\n return entry;\n }\n\n /**\n * Demote every active entry back to the restored phase. Used by the\n * pipeline-restart path so that, after a fresh pipeline is built, the\n * next observed snapshot does not re-fire `streamCall` for tool calls\n * that already fired pre-death. Args / hasResult tracking is preserved\n * so signature comparisons still work.\n */\n private _demoteEntriesToRestored(): void {\n for (const [toolCallId, entry] of this._entries) {\n if (!entry.controller) continue;\n this._entries.set(toolCallId, {\n toolName: entry.toolName,\n argsText: entry.argsText,\n hasResult: entry.hasResult,\n });\n }\n }\n\n private _processArgsText(\n entry: ToolCallEntry,\n content: {\n toolCallId: string;\n toolName: string;\n argsText: string;\n result?: unknown;\n },\n ): void {\n if (!entry.controller) return;\n const hasResult = content.result !== undefined;\n\n if (content.argsText !== entry.argsText) {\n let shouldWriteArgsText = true;\n\n if (entry.argsComplete) {\n if (isEquivalentCompleteArgsText(entry.argsText, content.argsText)) {\n // A.3 — key reorder. Track new text, no re-fire needed.\n entry.argsText = content.argsText;\n shouldWriteArgsText = false;\n } else {\n // A.4 — args changed after first completion. Under the\n // \"exactly once per toolCallId\" contract we do not restart the\n // stream. The host's existing `streamCall` keeps its original\n // args view; the snapshot's new text is recorded for diffing\n // but not surfaced. Events API in a follow-up will expose this\n // to consumers that opt in.\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n \"[ToolInvocationTracker] argsText changed after first completion; not re-firing streamCall (see EDGE_CASES.md A.4)\",\n {\n previous: entry.argsText,\n next: content.argsText,\n toolCallId: content.toolCallId,\n },\n );\n }\n shouldWriteArgsText = false;\n }\n } else if (!content.argsText.startsWith(entry.argsText)) {\n if (\n isArgsTextComplete(entry.argsText) &&\n isArgsTextComplete(content.argsText) &&\n isEquivalentCompleteArgsText(entry.argsText, content.argsText)\n ) {\n const shouldClose = this._shouldCloseArgsStream({\n toolName: content.toolName,\n argsText: content.argsText,\n hasResult,\n });\n if (shouldClose) entry.controller.argsText.close();\n entry.argsText = content.argsText;\n entry.argsComplete = shouldClose;\n shouldWriteArgsText = false;\n } else {\n // A.2 — args regressed mid-stream. Under the \"exactly once\"\n // contract we do not restart. The controller keeps whatever\n // prefix we already streamed; subsequent prefix-respecting\n // updates can still flow against it. Snapshots that never\n // re-converge to a prefix will leave the controller's args\n // view stale relative to the snapshot. Events API in a\n // follow-up will expose this to consumers that opt in.\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n \"[ToolInvocationTracker] argsText regressed mid-stream; not restarting (see EDGE_CASES.md A.2)\",\n {\n previous: entry.argsText,\n next: content.argsText,\n toolCallId: content.toolCallId,\n },\n );\n }\n shouldWriteArgsText = false;\n }\n }\n\n if (shouldWriteArgsText && entry.controller) {\n const delta = content.argsText.slice(entry.argsText.length);\n entry.controller.argsText.append(delta);\n const shouldClose = this._shouldCloseArgsStream({\n toolName: content.toolName,\n argsText: content.argsText,\n hasResult,\n });\n if (shouldClose) entry.controller.argsText.close();\n entry.argsText = content.argsText;\n entry.argsComplete = shouldClose;\n }\n }\n\n if (!entry.argsComplete && entry.controller) {\n const shouldClose = this._shouldCloseArgsStream({\n toolName: content.toolName,\n argsText: content.argsText,\n hasResult,\n });\n if (shouldClose) {\n entry.controller.argsText.close();\n entry.argsText = content.argsText;\n entry.argsComplete = true;\n }\n }\n }\n\n private _processMessages(messages: readonly ThreadMessage[]): void {\n const isRestore = this._pendingRestore;\n\n for (const message of messages) {\n if (!message || !Array.isArray((message as ThreadMessage).content)) {\n continue;\n }\n for (const content of message.content as readonly ThreadMessage[\"content\"][number][]) {\n if (!content || content.type !== \"tool-call\") continue;\n\n const existing = this._entries.get(content.toolCallId);\n\n if (isRestore) {\n // Don't overwrite an already-active entry (e.g. live tool-call\n // observed before this restore snapshot landed). Restore can\n // only seed entries the runtime has never seen.\n if (!existing?.controller) {\n this._entries.set(content.toolCallId, {\n toolName: content.toolName,\n argsText: content.argsText,\n hasResult: content.result !== undefined,\n });\n }\n if (content.messages) this._processMessages(content.messages);\n continue;\n }\n\n // Live snapshot.\n let entry = existing;\n\n if (entry && !entry.controller) {\n // Restored entry observed in a live snapshot. Promote if its\n // signature has changed; otherwise treat as still-historical.\n const signatureChanged =\n content.argsText !== entry.argsText ||\n (content.result !== undefined) !== entry.hasResult;\n if (!signatureChanged) {\n if (content.messages) this._processMessages(content.messages);\n continue;\n }\n this._entries.delete(content.toolCallId);\n entry = undefined;\n }\n\n if (!entry) {\n entry = this._startActiveEntry(\n content.toolCallId,\n content.toolName,\n content.result !== undefined,\n );\n }\n\n this._processArgsText(entry, content);\n\n if (content.result !== undefined && !entry.hasResult) {\n // `entry` is in active phase from this point — either just\n // created by `_startActiveEntry`, or pre-existing with a live\n // controller. Narrow once instead of asserting at every use.\n const { controller: activeController } = entry;\n if (!activeController) continue;\n entry.hasResult = true;\n entry.argsComplete = true;\n activeController.setResponse(\n new ToolResponse({\n result: content.result as ReadonlyJSONValue,\n artifact: content.artifact as ReadonlyJSONValue | undefined,\n isError: content.isError,\n ...(content.modelContent !== undefined\n ? { modelContent: content.modelContent }\n : {}),\n }),\n );\n activeController.close();\n }\n\n if (content.messages) this._processMessages(content.messages);\n }\n }\n }\n}\n"],"mappings":";;;;AAkFA,MAAM,sBAAsB,aAAqB;CAC/C,IAAI;EACF,KAAK,MAAM,QAAQ;EACnB,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF;AAEA,MAAM,iBAAiB,aAAqB;CAC1C,IAAI;EACF,OAAO,KAAK,MAAM,QAAQ;CAC5B,QAAQ;EACN;CACF;AACF;AAEA,MAAM,gCAAgC,UAAkB,SAAiB;CACvE,MAAM,gBAAgB,cAAc,QAAQ;CAC5C,MAAM,YAAY,cAAc,IAAI;CACpC,IAAI,kBAAkB,KAAA,KAAa,cAAc,KAAA,GAAW,OAAO;CACnE,OAAO,iBAAiB,eAAe,SAAS;AAClD;;;;;;;;;;;;;;;;;;;;;AAsBA,IAAa,wBAAb,MAAmC;CACjC;CACA;CAEA,2BAA4B,IAAI,IAA2B;;;;;;;;;;;CAW3D,wCAAyC,IAAI,IAAY;CACzD,8BA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,UAAU,KAAK,iBAAiB,QAAQ,QAAQ;KAC5D;IACF;IAGA,IAAI,QAAQ;IAEZ,IAAI,SAAS,CAAC,MAAM,YAAY;KAM9B,IAAI,EAFF,QAAQ,aAAa,MAAM,YAC1B,QAAQ,WAAW,KAAA,MAAe,MAAM,YACpB;MACrB,IAAI,QAAQ,UAAU,KAAK,iBAAiB,QAAQ,QAAQ;MAC5D;KACF;KACA,KAAK,SAAS,OAAO,QAAQ,UAAU;KACvC,QAAQ,KAAA;IACV;IAEA,IAAI,CAAC,OACH,QAAQ,KAAK,kBACX,QAAQ,YACR,QAAQ,UACR,QAAQ,WAAW,KAAA,CACrB;IAGF,KAAK,iBAAiB,OAAO,OAAO;IAEpC,IAAI,QAAQ,WAAW,KAAA,KAAa,CAAC,MAAM,WAAW;KAIpD,MAAM,EAAE,YAAY,qBAAqB;KACzC,IAAI,CAAC,kBAAkB;KACvB,MAAM,YAAY;KAClB,MAAM,eAAe;KACrB,iBAAiB,YACf,IAAI,aAAa;MACf,QAAQ,QAAQ;MAChB,UAAU,QAAQ;MAClB,SAAS,QAAQ;MACjB,GAAI,QAAQ,iBAAiB,KAAA,IACzB,EAAE,cAAc,QAAQ,aAAa,IACrC,CAAC;KACP,CAAC,CACH;KACA,iBAAiB,MAAM;IACzB;IAEA,IAAI,QAAQ,UAAU,KAAK,iBAAiB,QAAQ,QAAQ;GAC9D;EACF;CACF;AACF"}
1
+ {"version":3,"file":"ToolInvocationTracker.js","names":[],"sources":["../../../src/runtimes/tool-invocations/ToolInvocationTracker.ts"],"sourcesContent":["declare const process: { env: { NODE_ENV?: string } };\n\nimport {\n createAssistantStreamController,\n type ToolCallStreamController,\n ToolResponse,\n unstable_toolResultStream,\n type Tool,\n type ToolModelContentPart,\n} from \"assistant-stream\";\nimport {\n AssistantMetaTransformStream,\n type ReadonlyJSONValue,\n} from \"assistant-stream/utils\";\nimport { isJSONValueEqual } from \"../../utils/json/is-json-equal\";\nimport type { ThreadMessage } from \"../../types/message\";\n\n/**\n * Streaming execution state for a frontend tool.\n */\nexport type ToolExecutionStatus =\n | { type: \"executing\" }\n | {\n type: \"interrupt\";\n payload: { type: \"human\"; payload: unknown };\n };\n\nexport type AddToolResultCommand = {\n readonly type: \"add-tool-result\";\n readonly toolCallId: string;\n readonly toolName: string;\n readonly result: ReadonlyJSONValue;\n readonly isError: boolean;\n readonly artifact?: ReadonlyJSONValue;\n readonly modelContent?: readonly ToolModelContentPart[];\n};\n\nexport type ToolInvocationTrackerSnapshot = {\n readonly messages: readonly ThreadMessage[];\n /** Whether the producing runtime is currently streaming new output. */\n readonly isRunning: boolean;\n /**\n * Whether the producing runtime is still loading historical state.\n * When `true`, every snapshot is treated as historical (no `streamCall` /\n * `execute` fires). When `false`, processing resumes as live.\n */\n readonly isLoading?: boolean;\n};\n\nexport type ToolInvocationTrackerCallbacks = {\n /**\n * Invoked when a client-side `execute()` returns a result and the runtime\n * needs to feed it back into the conversation.\n */\n onResult: (command: AddToolResultCommand) => void;\n /**\n * Invoked whenever the per-tool-call status map changes (executing /\n * interrupt / cleared). The callback receives a fresh map; mutating the\n * argument is not supported.\n */\n onStatusesChange: (\n statuses: ReadonlyMap<string, ToolExecutionStatus>,\n ) => void;\n};\n\ntype ToolCallEntry = {\n toolName: string;\n argsText: string;\n hasResult: boolean;\n} & (\n | {\n /** Restored phase — observed during a history-load snapshot. */\n controller?: undefined;\n argsComplete?: undefined;\n }\n | {\n /** Active phase — chunks are flowing through `controller`. */\n controller: ToolCallStreamController;\n argsComplete: boolean;\n }\n);\n\nconst isArgsTextComplete = (argsText: string) => {\n try {\n JSON.parse(argsText);\n return true;\n } catch {\n return false;\n }\n};\n\nconst parseArgsText = (argsText: string) => {\n try {\n return JSON.parse(argsText);\n } catch {\n return undefined;\n }\n};\n\nconst isEquivalentCompleteArgsText = (previous: string, next: string) => {\n const previousValue = parseArgsText(previous);\n const nextValue = parseArgsText(next);\n if (previousValue === undefined || nextValue === undefined) return false;\n return isJSONValueEqual(previousValue, nextValue);\n};\n\n/**\n * Plain-class port of the former `useToolInvocations` React hook. Owns the\n * assistant-stream pipeline that drives client-side `streamCall` / `execute`\n * for tool-call parts surfaced by a thread runtime, plus the per-tool-call\n * status map that consumers render against.\n *\n * **Contract**: `streamCall` (and `execute`) fires exactly once per logical\n * `toolCallId`. Args mutations after first completion, result replacement,\n * and result clearing are *not* surfaced through additional `streamCall`\n * invocations — by design — so hosts cannot observe spurious re-fires of\n * side effects. The follow-up `reader.events()` API will expose those\n * post-completion transitions to consumers that opt in.\n *\n * State-transition safety: every public method that observes runtime state\n * (`setState`, `reset`, `abort`, `resume`) wraps its work in try/catch and\n * logs to `console.error` rather than throwing. The tracker is built into\n * the hot message-processing path, so a malformed snapshot must never crash\n * the host runtime. See ./EDGE_CASES.md for the known non-trivial state\n * transitions and what each does today.\n */\nexport class ToolInvocationTracker {\n private readonly _getTools: () => Record<string, Tool> | undefined;\n private readonly _callbacks: ToolInvocationTrackerCallbacks;\n\n private readonly _entries = new Map<string, ToolCallEntry>();\n /**\n * Tool call ids whose `execute` should be short-circuited in the wrapper.\n * Populated when an entry is created with a result already attached\n * (history reload, mid-run resume, etc.) — `execute` is suppressed so\n * client-side side effects don't double-run. Membership outlives the\n * entry: `reset()` deliberately does *not* clear this so post-abort\n * cancellation `result` chunks for pre-resolved entries can still be\n * recognized and dropped. Growth is bounded by the number of pre-resolved\n * tool calls observed in the session.\n */\n private readonly _skipExecuteStreamIds = new Set<string>();\n private readonly _humanInput = new Map<\n string,\n {\n resolve: (payload: unknown) => void;\n reject: (reason: unknown) => void;\n }\n >();\n /** In-flight `execute` invocations keyed by tool call id. */\n private readonly _executing = new Set<string>();\n private readonly _settledResolvers: Array<() => void> = [];\n\n private _statuses = new Map<string, ToolExecutionStatus>();\n\n private _ac: AbortController = new AbortController();\n private _pendingRestore = true;\n\n /** Cached last snapshot, used to skip processing on identical re-renders. */\n private _lastSnapshot: ToolInvocationTrackerSnapshot | null = null;\n private _isRunning = false;\n\n private _controller!: ReturnType<typeof createAssistantStreamController>[1];\n\n /**\n * Set when the assistant-stream pipeline has died (errored out via\n * `.pipeTo(...).catch(...)`). The next `setState` re-initializes the\n * pipeline and demotes all active entries to restored so they survive\n * across the restart without re-firing `streamCall` (preserves the\n * \"exactly once\" contract). Capped at a single auto-restart per session\n * — repeated failures keep the tracker dead with a more visible error.\n */\n private _pipelineDead = false;\n private _pipelineRestartUsed = false;\n\n constructor(\n getTools: () => Record<string, Tool> | undefined,\n callbacks: ToolInvocationTrackerCallbacks,\n ) {\n this._getTools = getTools;\n this._callbacks = callbacks;\n\n this._initPipeline();\n }\n\n /**\n * Build the assistant-stream pipeline. Called once from the constructor\n * and at most once again if `_pipelineDead` is set (see F.4 in\n * EDGE_CASES.md).\n */\n private _initPipeline(): void {\n const [stream, controller] = createAssistantStreamController();\n this._controller = controller;\n\n const transform = unstable_toolResultStream(\n () => this._getWrappedTools(),\n () => this._ac.signal,\n (toolCallId, payload) => this._onHumanInput(toolCallId, payload),\n {\n onExecutionStart: (id) => this._onExecutionStart(id),\n onExecutionEnd: (id) => this._onExecutionEnd(id),\n },\n );\n\n stream\n .pipeThrough(transform)\n .pipeThrough(new AssistantMetaTransformStream())\n .pipeTo(\n new WritableStream({\n write: (chunk) => {\n try {\n if (chunk.type !== \"result\") return;\n this._handleResultChunk(chunk);\n } catch (err) {\n console.error(\n \"[ToolInvocationTracker] result chunk handling failed\",\n err,\n );\n }\n },\n }),\n )\n .catch((err) => {\n console.error(\n \"[ToolInvocationTracker] stream pipeline failed; will attempt single restart on next setState\",\n err,\n );\n this._pipelineDead = true;\n });\n }\n\n // ───────────────────────── public API ─────────────────────────\n\n /**\n * Feed the next observed snapshot into the tracker. Called from the host\n * runtime whenever its message list / running state changes.\n */\n public setState(snapshot: ToolInvocationTrackerSnapshot): void {\n try {\n // Recover from a dead pipeline before processing anything. We demote\n // all active entries to \"restored\" so the rebuilt pipeline does not\n // re-fire `streamCall` for tool calls that already fired pre-death;\n // preserves the \"exactly once per toolCallId\" contract.\n if (this._pipelineDead) {\n if (this._pipelineRestartUsed) {\n // Already retried once and failed again. Stay dead.\n return;\n }\n this._pipelineRestartUsed = true;\n this._pipelineDead = false;\n this._demoteEntriesToRestored();\n this._executing.clear();\n this._ac = new AbortController();\n this._initPipeline();\n // Fall through and process the snapshot against the fresh pipeline.\n }\n\n // Identical snapshot — skip processing entirely. Note: external-store\n // runtimes rebuild the messages array on every adapter update, so this\n // fast-path rarely triggers there; it's primarily for the React-hook\n // shim where state references are stable.\n if (\n this._lastSnapshot &&\n this._lastSnapshot.messages === snapshot.messages &&\n this._lastSnapshot.isRunning === snapshot.isRunning &&\n this._lastSnapshot.isLoading === snapshot.isLoading\n ) {\n return;\n }\n\n // While the host is still loading initial state, treat every snapshot\n // as historical: tool calls are recorded so the next live snapshot can\n // diff against them, but `streamCall` / `execute` do not fire.\n const restoreFromLoading = snapshot.isLoading === true;\n if (restoreFromLoading) {\n this._pendingRestore = true;\n }\n\n // E.4 / AF3 — only mark `_lastSnapshot`/`_isRunning` as observed after\n // processing succeeds. If `_processMessages` throws, the next snapshot\n // (even if identical) gets re-processed against the recovered state.\n const previousIsRunning = this._isRunning;\n this._isRunning = snapshot.isRunning;\n try {\n this._processMessages(snapshot.messages);\n } catch (err) {\n this._isRunning = previousIsRunning;\n throw err;\n }\n this._lastSnapshot = snapshot;\n this._pendingRestore = false;\n } catch (err) {\n console.error(\n \"[ToolInvocationTracker] setState failed; snapshot dropped\",\n err,\n );\n }\n }\n\n /**\n * Reset the tracker so the next observed snapshot is treated as historical.\n * Clears entries and aborts any in-flight executions. Used by callers like\n * `importExternalState` to mark a freshly loaded state as restored.\n */\n public reset(): void {\n try {\n this._pendingRestore = true;\n this._entries.clear();\n this._lastSnapshot = null;\n // `_skipExecuteStreamIds` is intentionally not cleared — see field doc.\n void this.abort().finally(() => {\n this._executing.clear();\n });\n } catch (err) {\n console.error(\"[ToolInvocationTracker] reset failed\", err);\n }\n }\n\n /**\n * Abort any in-flight `execute()` invocations. Resolves once all of them\n * have settled (or immediately if none are running).\n */\n public abort(): Promise<void> {\n try {\n this._humanInput.forEach(({ reject }) => {\n try {\n reject(new Error(\"Tool execution aborted\"));\n } catch {\n // host rejection handler threw — already in the abort path,\n // swallow so we continue cleaning up.\n }\n });\n this._humanInput.clear();\n\n this._ac.abort();\n this._ac = new AbortController();\n\n if (this._executing.size === 0) {\n return Promise.resolve();\n }\n return new Promise<void>((resolve) => {\n this._settledResolvers.push(resolve);\n });\n } catch (err) {\n console.error(\"[ToolInvocationTracker] abort failed\", err);\n return Promise.resolve();\n }\n }\n\n /**\n * Resolve a pending human-input request for the given tool call. Returns\n * `true` if a pending request was resumed, `false` if the tracker has no\n * outstanding request for that id (the caller should fall back to its own\n * dispatch path).\n */\n public resume(toolCallId: string, payload: unknown): boolean {\n try {\n const handlers = this._humanInput.get(toolCallId);\n if (!handlers) return false;\n this._humanInput.delete(toolCallId);\n this._setStatus(toolCallId, { type: \"executing\" });\n handlers.resolve(payload);\n return true;\n } catch (err) {\n console.error(\"[ToolInvocationTracker] resume failed\", err);\n return false;\n }\n }\n\n /**\n * Returns the current tool execution status map. The returned `Map` is\n * the tracker's internal store — do not mutate it. Treat the reference\n * as a snapshot that may be replaced wholesale on the next status\n * transition.\n */\n public getStatuses(): ReadonlyMap<string, ToolExecutionStatus> {\n return this._statuses;\n }\n\n // ───────────────────── internal: tool wrapping ─────────────────────\n\n private _getWrappedTools(): Record<string, Tool> | undefined {\n const tools = this._getTools();\n if (!tools) return undefined;\n\n return Object.fromEntries(\n Object.entries(tools).map(([name, tool]) => {\n const execute = tool.execute;\n if (execute === undefined) return [name, tool];\n\n const wrappedTool = {\n ...tool,\n execute: (\n ...[args, context]: Parameters<NonNullable<typeof execute>>\n ) => {\n if (this._skipExecuteStreamIds.has(context.toolCallId)) {\n // Pre-resolved tool call: never invoke the host's execute.\n // Returning a never-settling Promise keeps the executor's\n // pending entry alive but enqueues nothing.\n return new Promise(() => {}) as never;\n }\n return execute(args, context);\n },\n } as Tool;\n return [name, wrappedTool];\n }),\n ) as Record<string, Tool>;\n }\n\n // ──────────────── internal: execution lifecycle callbacks ────────────────\n\n private _onHumanInput(\n toolCallId: string,\n payload: unknown,\n ): Promise<unknown> {\n return new Promise<unknown>((resolve, reject) => {\n const previous = this._humanInput.get(toolCallId);\n if (previous) {\n try {\n previous.reject(\n new Error(\"Human input request was superseded by a new request\"),\n );\n } catch {\n // host rejection handler threw; ignore and proceed\n }\n }\n this._humanInput.set(toolCallId, { resolve, reject });\n this._setStatus(toolCallId, {\n type: \"interrupt\",\n payload: { type: \"human\", payload },\n });\n });\n }\n\n private _onExecutionStart(toolCallId: string): void {\n if (this._skipExecuteStreamIds.has(toolCallId)) return;\n\n this._executing.add(toolCallId);\n this._setStatus(toolCallId, { type: \"executing\" });\n }\n\n private _onExecutionEnd(toolCallId: string): void {\n if (!this._executing.delete(toolCallId)) return;\n\n this._deleteStatus(toolCallId);\n\n if (this._executing.size === 0) {\n const resolvers = this._settledResolvers.splice(0);\n resolvers.forEach((resolve) => {\n try {\n resolve();\n } catch {\n // ignore — settled-resolver consumer threw\n }\n });\n }\n }\n\n private _handleResultChunk(chunk: {\n type: \"result\";\n result: ReadonlyJSONValue;\n isError: boolean;\n artifact?: ReadonlyJSONValue;\n modelContent?: readonly ToolModelContentPart[];\n meta: { toolCallId: string; toolName: string };\n }): void {\n const toolCallId = chunk.meta.toolCallId;\n const entry = this._entries.get(toolCallId);\n\n // Pre-resolved tool call whose entry has been cleared by `reset()`.\n // The post-abort cancellation chunk lands here after the entry is\n // gone; suppress via the long-lived skip-execute marker.\n if (!entry && this._skipExecuteStreamIds.has(toolCallId)) {\n return;\n }\n\n // The host already set the result (via the live snapshot's\n // `setResponse` path). Suppress the executor's redundant emit.\n if (entry?.hasResult) return;\n\n this._invokeOnResult({\n type: \"add-tool-result\",\n toolCallId,\n toolName: chunk.meta.toolName,\n result: chunk.result,\n isError: chunk.isError,\n ...(chunk.artifact !== undefined && { artifact: chunk.artifact }),\n ...(chunk.modelContent !== undefined && {\n modelContent: chunk.modelContent,\n }),\n });\n }\n\n // ──────────────── internal: callback invocation (AF1/AF2) ────────────────\n\n private _invokeOnResult(command: AddToolResultCommand): void {\n try {\n this._callbacks.onResult(command);\n } catch (err) {\n console.error(\n \"[ToolInvocationTracker] onResult callback threw; result dropped\",\n err,\n );\n }\n }\n\n private _invokeOnStatusesChange(): void {\n try {\n this._callbacks.onStatusesChange(this._statuses);\n } catch (err) {\n console.error(\n \"[ToolInvocationTracker] onStatusesChange callback threw; status change not propagated\",\n err,\n );\n }\n }\n\n // ──────────────── internal: status map mutations ────────────────\n\n private _setStatus(toolCallId: string, status: ToolExecutionStatus): void {\n const next = new Map(this._statuses);\n next.set(toolCallId, status);\n this._statuses = next;\n this._invokeOnStatusesChange();\n }\n\n private _deleteStatus(toolCallId: string): void {\n if (!this._statuses.has(toolCallId)) return;\n const next = new Map(this._statuses);\n next.delete(toolCallId);\n this._statuses = next;\n this._invokeOnStatusesChange();\n }\n\n // ──────────────── internal: snapshot processing ────────────────\n\n private _hasExecutableTool(toolName: string): boolean {\n const tool = this._getTools()?.[toolName];\n return tool?.execute !== undefined || tool?.streamCall !== undefined;\n }\n\n private _shouldCloseArgsStream({\n toolName,\n argsText,\n hasResult,\n }: {\n toolName: string;\n argsText: string;\n hasResult: boolean;\n }): boolean {\n if (hasResult) return true;\n if (!this._hasExecutableTool(toolName)) {\n return !this._isRunning && isArgsTextComplete(argsText);\n }\n return isArgsTextComplete(argsText);\n }\n\n private _startActiveEntry(\n toolCallId: string,\n toolName: string,\n skipExecute: boolean,\n ): ToolCallEntry {\n const toolCallController = this._controller.addToolCallPart({\n toolName,\n toolCallId,\n });\n if (skipExecute) {\n this._skipExecuteStreamIds.add(toolCallId);\n }\n const entry: ToolCallEntry = {\n toolName,\n controller: toolCallController,\n argsText: \"\",\n hasResult: false,\n argsComplete: false,\n };\n this._entries.set(toolCallId, entry);\n return entry;\n }\n\n /**\n * Demote every active entry back to the restored phase. Used by the\n * pipeline-restart path so that, after a fresh pipeline is built, the\n * next observed snapshot does not re-fire `streamCall` for tool calls\n * that already fired pre-death. Args / hasResult tracking is preserved\n * so signature comparisons still work.\n */\n private _demoteEntriesToRestored(): void {\n for (const [toolCallId, entry] of this._entries) {\n if (!entry.controller) continue;\n this._entries.set(toolCallId, {\n toolName: entry.toolName,\n argsText: entry.argsText,\n hasResult: entry.hasResult,\n });\n }\n }\n\n private _processArgsText(\n entry: ToolCallEntry,\n content: {\n toolCallId: string;\n toolName: string;\n argsText: string;\n result?: unknown;\n },\n ): void {\n if (!entry.controller) return;\n const hasResult = content.result !== undefined;\n\n if (content.argsText !== entry.argsText) {\n let shouldWriteArgsText = true;\n\n if (entry.argsComplete) {\n if (isEquivalentCompleteArgsText(entry.argsText, content.argsText)) {\n // A.3 — key reorder. Track new text, no re-fire needed.\n entry.argsText = content.argsText;\n shouldWriteArgsText = false;\n } else {\n // A.4 — args changed after first completion. Under the\n // \"exactly once per toolCallId\" contract we do not restart the\n // stream. The host's existing `streamCall` keeps its original\n // args view; the snapshot's new text is recorded for diffing\n // but not surfaced. Events API in a follow-up will expose this\n // to consumers that opt in.\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n \"[ToolInvocationTracker] argsText changed after first completion; not re-firing streamCall (see EDGE_CASES.md A.4)\",\n {\n previous: entry.argsText,\n next: content.argsText,\n toolCallId: content.toolCallId,\n },\n );\n }\n shouldWriteArgsText = false;\n }\n } else if (!content.argsText.startsWith(entry.argsText)) {\n if (\n isArgsTextComplete(entry.argsText) &&\n isArgsTextComplete(content.argsText) &&\n isEquivalentCompleteArgsText(entry.argsText, content.argsText)\n ) {\n const shouldClose = this._shouldCloseArgsStream({\n toolName: content.toolName,\n argsText: content.argsText,\n hasResult,\n });\n if (shouldClose) entry.controller.argsText.close();\n entry.argsText = content.argsText;\n entry.argsComplete = shouldClose;\n shouldWriteArgsText = false;\n } else {\n // A.2 — args regressed mid-stream. Under the \"exactly once\"\n // contract we do not restart. The controller keeps whatever\n // prefix we already streamed; subsequent prefix-respecting\n // updates can still flow against it. Snapshots that never\n // re-converge to a prefix will leave the controller's args\n // view stale relative to the snapshot. Events API in a\n // follow-up will expose this to consumers that opt in.\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n \"[ToolInvocationTracker] argsText regressed mid-stream; not restarting (see EDGE_CASES.md A.2)\",\n {\n previous: entry.argsText,\n next: content.argsText,\n toolCallId: content.toolCallId,\n },\n );\n }\n shouldWriteArgsText = false;\n }\n }\n\n if (shouldWriteArgsText && entry.controller) {\n const delta = content.argsText.slice(entry.argsText.length);\n entry.controller.argsText.append(delta);\n const shouldClose = this._shouldCloseArgsStream({\n toolName: content.toolName,\n argsText: content.argsText,\n hasResult,\n });\n if (shouldClose) entry.controller.argsText.close();\n entry.argsText = content.argsText;\n entry.argsComplete = shouldClose;\n }\n }\n\n if (!entry.argsComplete && entry.controller) {\n const shouldClose = this._shouldCloseArgsStream({\n toolName: content.toolName,\n argsText: content.argsText,\n hasResult,\n });\n if (shouldClose) {\n entry.controller.argsText.close();\n entry.argsText = content.argsText;\n entry.argsComplete = true;\n }\n }\n }\n\n private _processMessages(messages: readonly ThreadMessage[]): void {\n const isRestore = this._pendingRestore;\n\n for (const message of messages) {\n if (!message || !Array.isArray((message as ThreadMessage).content)) {\n continue;\n }\n for (const content of message.content as readonly ThreadMessage[\"content\"][number][]) {\n if (!content || content.type !== \"tool-call\") continue;\n\n const existing = this._entries.get(content.toolCallId);\n\n if (isRestore) {\n // Don't overwrite an already-active entry (e.g. live tool-call\n // observed before this restore snapshot landed). Restore can\n // only seed entries the runtime has never seen.\n if (!existing?.controller) {\n this._entries.set(content.toolCallId, {\n toolName: content.toolName,\n argsText: content.argsText,\n hasResult: content.result !== undefined,\n });\n }\n if (content.messages) this._processMessages(content.messages);\n continue;\n }\n\n // Live snapshot.\n let entry = existing;\n\n if (entry && !entry.controller) {\n // Restored entry observed in a live snapshot. Promote if its\n // signature has changed; otherwise treat as still-historical.\n const signatureChanged =\n content.argsText !== entry.argsText ||\n (content.result !== undefined) !== entry.hasResult;\n if (!signatureChanged) {\n if (content.messages) this._processMessages(content.messages);\n continue;\n }\n this._entries.delete(content.toolCallId);\n entry = undefined;\n }\n\n if (!entry) {\n entry = this._startActiveEntry(\n content.toolCallId,\n content.toolName,\n content.result !== undefined,\n );\n }\n\n this._processArgsText(entry, content);\n\n if (content.result !== undefined && !entry.hasResult) {\n // `entry` is in active phase from this point — either just\n // created by `_startActiveEntry`, or pre-existing with a live\n // controller. Narrow once instead of asserting at every use.\n const { controller: activeController } = entry;\n if (!activeController) continue;\n entry.hasResult = true;\n entry.argsComplete = true;\n activeController.setResponse(\n new ToolResponse({\n result: content.result as ReadonlyJSONValue,\n artifact: content.artifact as ReadonlyJSONValue | undefined,\n isError: content.isError,\n ...(content.modelContent !== undefined\n ? { modelContent: content.modelContent }\n : {}),\n }),\n );\n activeController.close();\n }\n\n if (content.messages) this._processMessages(content.messages);\n }\n }\n }\n}\n"],"mappings":";;;;AAkFA,MAAM,sBAAsB,aAAqB;CAC/C,IAAI;EACF,KAAK,MAAM,QAAQ;EACnB,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF;AAEA,MAAM,iBAAiB,aAAqB;CAC1C,IAAI;EACF,OAAO,KAAK,MAAM,QAAQ;CAC5B,QAAQ;EACN;CACF;AACF;AAEA,MAAM,gCAAgC,UAAkB,SAAiB;CACvE,MAAM,gBAAgB,cAAc,QAAQ;CAC5C,MAAM,YAAY,cAAc,IAAI;CACpC,IAAI,kBAAkB,KAAA,KAAa,cAAc,KAAA,GAAW,OAAO;CACnE,OAAO,iBAAiB,eAAe,SAAS;AAClD;;;;;;;;;;;;;;;;;;;;;AAsBA,IAAa,wBAAb,MAAmC;CACjC;CACA;CAEA,2BAA4B,IAAI,IAA2B;;;;;;;;;;;CAW3D,wCAAyC,IAAI,IAAY;CACzD,8BAA+B,IAAI,IAMjC;;CAEF,6BAA8B,IAAI,IAAY;C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U,KAAK,iBAAiB,QAAQ,QAAQ;KAC5D;IACF;IAGA,IAAI,QAAQ;IAEZ,IAAI,SAAS,CAAC,MAAM,YAAY;KAM9B,IAAI,EAFF,QAAQ,aAAa,MAAM,YAC1B,QAAQ,WAAW,KAAA,MAAe,MAAM,YACpB;MACrB,IAAI,QAAQ,UAAU,KAAK,iBAAiB,QAAQ,QAAQ;MAC5D;KACF;KACA,KAAK,SAAS,OAAO,QAAQ,UAAU;KACvC,QAAQ,KAAA;IACV;IAEA,IAAI,CAAC,OACH,QAAQ,KAAK,kBACX,QAAQ,YACR,QAAQ,UACR,QAAQ,WAAW,KAAA,CACrB;IAGF,KAAK,iBAAiB,OAAO,OAAO;IAEpC,IAAI,QAAQ,WAAW,KAAA,KAAa,CAAC,MAAM,WAAW;KAIpD,MAAM,EAAE,YAAY,qBAAqB;KACzC,IAAI,CAAC,kBAAkB;KACvB,MAAM,YAAY;KAClB,MAAM,eAAe;KACrB,iBAAiB,YACf,IAAI,aAAa;MACf,QAAQ,QAAQ;MAChB,UAAU,QAAQ;MAClB,SAAS,QAAQ;MACjB,GAAI,QAAQ,iBAAiB,KAAA,IACzB,EAAE,cAAc,QAAQ,aAAa,IACrC,CAAC;KACP,CAAC,CACH;KACA,iBAAiB,MAAM;IACzB;IAEA,IAAI,QAAQ,UAAU,KAAK,iBAAiB,QAAQ,QAAQ;GAC9D;EACF;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"chain-of-thought-client.d.ts","names":[],"sources":["../../../src/store/clients/chain-of-thought-client.ts"],"mappings":";;;;;cAaa,oBAAA,GAAoB,KAAA;kBAKb,kBAAA;mBACC,QAAA;IAAY,KAAA;EAAA,MAAoB,WAAA;AAAA;kBADjC,kBAAA;mBACC,QAAA;IAAY,KAAA;EAAA,MAAoB,WAAA;AAAA"}
1
+ {"version":3,"file":"chain-of-thought-client.d.ts","names":[],"sources":["../../../src/store/clients/chain-of-thought-client.ts"],"mappings":";;;;;cAca,oBAAA,GAAoB,KAAA;kBAIf,kBAAA;mBACC,QAAA;IAAY,KAAA;EAAA,MAAoB,WAAA;AAAA;kBADjC,kBAAA;mBACC,QAAA;IAAY,KAAA;EAAA,MAAoB,WAAA;AAAA"}