@messenger-box/tailwind-ui-inbox 10.0.3-alpha.100

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 (373) hide show
  1. package/CHANGELOG.md +104 -0
  2. package/LICENSE +21 -0
  3. package/jest.config.js +9 -0
  4. package/lib/cdm-locales/en/translations.json +31 -0
  5. package/lib/cdm-locales/es/translations.json +31 -0
  6. package/lib/components/AIAgent/AIAgent.d.ts +21 -0
  7. package/lib/components/AIAgent/AIAgent.d.ts.map +1 -0
  8. package/lib/components/AIAgent/AIAgent.js +904 -0
  9. package/lib/components/AIAgent/AIAgent.js.map +1 -0
  10. package/lib/components/AIAgent/index.d.ts +2 -0
  11. package/lib/components/AIAgent/index.d.ts.map +1 -0
  12. package/lib/components/InboxMessage/CommonMessage.d.ts +8 -0
  13. package/lib/components/InboxMessage/CommonMessage.d.ts.map +1 -0
  14. package/lib/components/InboxMessage/CommonMessage.js +35 -0
  15. package/lib/components/InboxMessage/CommonMessage.js.map +1 -0
  16. package/lib/components/InboxMessage/ConversationItem.d.ts +14 -0
  17. package/lib/components/InboxMessage/ConversationItem.d.ts.map +1 -0
  18. package/lib/components/InboxMessage/ConversationItem.js +200 -0
  19. package/lib/components/InboxMessage/ConversationItem.js.map +1 -0
  20. package/lib/components/InboxMessage/InputComponent.d.ts +12 -0
  21. package/lib/components/InboxMessage/InputComponent.d.ts.map +1 -0
  22. package/lib/components/InboxMessage/InputComponent.js +359 -0
  23. package/lib/components/InboxMessage/InputComponent.js.map +1 -0
  24. package/lib/components/InboxMessage/LeftSidebar.d.ts +20 -0
  25. package/lib/components/InboxMessage/LeftSidebar.d.ts.map +1 -0
  26. package/lib/components/InboxMessage/LeftSidebar.js +102 -0
  27. package/lib/components/InboxMessage/LeftSidebar.js.map +1 -0
  28. package/lib/components/InboxMessage/MessageInput.d.ts +9 -0
  29. package/lib/components/InboxMessage/MessageInput.d.ts.map +1 -0
  30. package/lib/components/InboxMessage/MessageInput.js +154 -0
  31. package/lib/components/InboxMessage/MessageInput.js.map +1 -0
  32. package/lib/components/InboxMessage/MessageInputComponent.d.ts +9 -0
  33. package/lib/components/InboxMessage/MessageInputComponent.d.ts.map +1 -0
  34. package/lib/components/InboxMessage/Messages.d.ts +17 -0
  35. package/lib/components/InboxMessage/Messages.d.ts.map +1 -0
  36. package/lib/components/InboxMessage/Messages.js +99 -0
  37. package/lib/components/InboxMessage/Messages.js.map +1 -0
  38. package/lib/components/InboxMessage/MessagesBuilderUi.d.ts +17 -0
  39. package/lib/components/InboxMessage/MessagesBuilderUi.d.ts.map +1 -0
  40. package/lib/components/InboxMessage/Popover.d.ts +3 -0
  41. package/lib/components/InboxMessage/Popover.d.ts.map +1 -0
  42. package/lib/components/InboxMessage/Popover.js +31 -0
  43. package/lib/components/InboxMessage/Popover.js.map +1 -0
  44. package/lib/components/InboxMessage/RightSidebar.d.ts +9 -0
  45. package/lib/components/InboxMessage/RightSidebar.d.ts.map +1 -0
  46. package/lib/components/InboxMessage/RightSidebar.js +9 -0
  47. package/lib/components/InboxMessage/RightSidebar.js.map +1 -0
  48. package/lib/components/InboxMessage/RightSidebarAi.d.ts +23 -0
  49. package/lib/components/InboxMessage/RightSidebarAi.d.ts.map +1 -0
  50. package/lib/components/InboxMessage/RightSidebarAi.js +9 -0
  51. package/lib/components/InboxMessage/RightSidebarAi.js.map +1 -0
  52. package/lib/components/InboxMessage/ServiceConversationItem.d.ts +12 -0
  53. package/lib/components/InboxMessage/ServiceConversationItem.d.ts.map +1 -0
  54. package/lib/components/InboxMessage/ServiceConversationItem.js +185 -0
  55. package/lib/components/InboxMessage/ServiceConversationItem.js.map +1 -0
  56. package/lib/components/InboxMessage/ServiceInboxItem.d.ts +12 -0
  57. package/lib/components/InboxMessage/ServiceInboxItem.d.ts.map +1 -0
  58. package/lib/components/InboxMessage/ServiceInboxItem.js +182 -0
  59. package/lib/components/InboxMessage/ServiceInboxItem.js.map +1 -0
  60. package/lib/components/InboxMessage/SubscriptionHandler.d.ts +19 -0
  61. package/lib/components/InboxMessage/SubscriptionHandler.d.ts.map +1 -0
  62. package/lib/components/InboxMessage/SubscriptionHandler.js +41 -0
  63. package/lib/components/InboxMessage/SubscriptionHandler.js.map +1 -0
  64. package/lib/components/InboxMessage/UploadImageButton.d.ts +7 -0
  65. package/lib/components/InboxMessage/UploadImageButton.d.ts.map +1 -0
  66. package/lib/components/InboxMessage/UploadImageButton.js +34 -0
  67. package/lib/components/InboxMessage/UploadImageButton.js.map +1 -0
  68. package/lib/components/InboxMessage/UserModalContent.d.ts +3 -0
  69. package/lib/components/InboxMessage/UserModalContent.d.ts.map +1 -0
  70. package/lib/components/InboxMessage/UserModalContent.js +60 -0
  71. package/lib/components/InboxMessage/UserModalContent.js.map +1 -0
  72. package/lib/components/InboxMessage/index.d.ts +17 -0
  73. package/lib/components/InboxMessage/index.d.ts.map +1 -0
  74. package/lib/components/InboxMessage/message-widgets/CommonMessage.d.ts +11 -0
  75. package/lib/components/InboxMessage/message-widgets/CommonMessage.d.ts.map +1 -0
  76. package/lib/components/InboxMessage/message-widgets/CommonMessage.js +44 -0
  77. package/lib/components/InboxMessage/message-widgets/CommonMessage.js.map +1 -0
  78. package/lib/components/InboxMessage/message-widgets/ErrorFixCard.d.ts +11 -0
  79. package/lib/components/InboxMessage/message-widgets/ErrorFixCard.d.ts.map +1 -0
  80. package/lib/components/InboxMessage/message-widgets/ErrorFixCard.js +194 -0
  81. package/lib/components/InboxMessage/message-widgets/ErrorFixCard.js.map +1 -0
  82. package/lib/components/InboxMessage/message-widgets/MessageCard.d.ts +8 -0
  83. package/lib/components/InboxMessage/message-widgets/MessageCard.d.ts.map +1 -0
  84. package/lib/components/InboxMessage/message-widgets/MessageSliceRenderer.d.ts +12 -0
  85. package/lib/components/InboxMessage/message-widgets/MessageSliceRenderer.d.ts.map +1 -0
  86. package/lib/components/InboxMessage/message-widgets/MessageSliceRenderer.js +37 -0
  87. package/lib/components/InboxMessage/message-widgets/MessageSliceRenderer.js.map +1 -0
  88. package/lib/components/InboxMessage/message-widgets/ModernMessageGroup.d.ts +18 -0
  89. package/lib/components/InboxMessage/message-widgets/ModernMessageGroup.d.ts.map +1 -0
  90. package/lib/components/InboxMessage/message-widgets/ModernMessageGroup.js +1082 -0
  91. package/lib/components/InboxMessage/message-widgets/ModernMessageGroup.js.map +1 -0
  92. package/lib/components/InboxMessage/message-widgets/PlainMessage.d.ts +8 -0
  93. package/lib/components/InboxMessage/message-widgets/PlainMessage.d.ts.map +1 -0
  94. package/lib/components/InboxMessage/message-widgets/PlainMessage.js +14 -0
  95. package/lib/components/InboxMessage/message-widgets/PlainMessage.js.map +1 -0
  96. package/lib/components/InboxMessage/message-widgets/PropertyMessageWidget.d.ts +9 -0
  97. package/lib/components/InboxMessage/message-widgets/PropertyMessageWidget.d.ts.map +1 -0
  98. package/lib/components/InboxMessage/message-widgets/SlackLikeMessageGroup.d.ts +14 -0
  99. package/lib/components/InboxMessage/message-widgets/SlackLikeMessageGroup.d.ts.map +1 -0
  100. package/lib/components/InboxMessage/message-widgets/SlackLikeMessageGroup.js +333 -0
  101. package/lib/components/InboxMessage/message-widgets/SlackLikeMessageGroup.js.map +1 -0
  102. package/lib/components/InboxMessage/message-widgets/index.d.ts +4 -0
  103. package/lib/components/InboxMessage/message-widgets/index.d.ts.map +1 -0
  104. package/lib/components/ModelConfigPanel.d.ts +37 -0
  105. package/lib/components/ModelConfigPanel.d.ts.map +1 -0
  106. package/lib/components/ModelConfigPanel.js +317 -0
  107. package/lib/components/ModelConfigPanel.js.map +1 -0
  108. package/lib/components/filler-components/RightSiderBar.d.ts +24 -0
  109. package/lib/components/filler-components/RightSiderBar.d.ts.map +1 -0
  110. package/lib/components/filler-components/RightSiderBar.js +335 -0
  111. package/lib/components/filler-components/RightSiderBar.js.map +1 -0
  112. package/lib/components/inbox/FilesList.d.ts +20 -0
  113. package/lib/components/inbox/FilesList.d.ts.map +1 -0
  114. package/lib/components/inbox/FilesList.js +68 -0
  115. package/lib/components/inbox/FilesList.js.map +1 -0
  116. package/lib/components/inbox/MessageItem.d.ts +17 -0
  117. package/lib/components/inbox/MessageItem.d.ts.map +1 -0
  118. package/lib/components/inbox/MessageItem.js +50 -0
  119. package/lib/components/inbox/MessageItem.js.map +1 -0
  120. package/lib/components/inbox/ThreadItem.d.ts +11 -0
  121. package/lib/components/inbox/ThreadItem.d.ts.map +1 -0
  122. package/lib/components/inbox/ThreadItem.js +147 -0
  123. package/lib/components/inbox/ThreadItem.js.map +1 -0
  124. package/lib/components/inbox/index.d.ts +4 -0
  125. package/lib/components/inbox/index.d.ts.map +1 -0
  126. package/lib/components/index.d.ts +7 -0
  127. package/lib/components/index.d.ts.map +1 -0
  128. package/lib/components/live-code-editor/hybrid-live-editor.d.ts +20 -0
  129. package/lib/components/live-code-editor/hybrid-live-editor.d.ts.map +1 -0
  130. package/lib/components/live-code-editor/hybrid-live-editor.js +68 -0
  131. package/lib/components/live-code-editor/hybrid-live-editor.js.map +1 -0
  132. package/lib/components/live-code-editor/index.d.ts +4 -0
  133. package/lib/components/live-code-editor/index.d.ts.map +1 -0
  134. package/lib/components/live-code-editor/live-code-editor.d.ts +14 -0
  135. package/lib/components/live-code-editor/live-code-editor.d.ts.map +1 -0
  136. package/lib/components/live-code-editor/live-code-editor.js +207 -0
  137. package/lib/components/live-code-editor/live-code-editor.js.map +1 -0
  138. package/lib/components/slot-fill/chat-message-filler.d.ts +4 -0
  139. package/lib/components/slot-fill/chat-message-filler.d.ts.map +1 -0
  140. package/lib/components/slot-fill/chat-message-filler.js +5 -0
  141. package/lib/components/slot-fill/chat-message-filler.js.map +1 -0
  142. package/lib/components/slot-fill/chat-message-slot.d.ts +11 -0
  143. package/lib/components/slot-fill/chat-message-slot.d.ts.map +1 -0
  144. package/lib/components/slot-fill/chat-message-slot.js +6 -0
  145. package/lib/components/slot-fill/chat-message-slot.js.map +1 -0
  146. package/lib/components/slot-fill/index.d.ts +4 -0
  147. package/lib/components/slot-fill/index.d.ts.map +1 -0
  148. package/lib/components/slot-fill/right-sidebar-filler.d.ts +4 -0
  149. package/lib/components/slot-fill/right-sidebar-filler.d.ts.map +1 -0
  150. package/lib/components/slot-fill/right-sidebar-filler.js +13 -0
  151. package/lib/components/slot-fill/right-sidebar-filler.js.map +1 -0
  152. package/lib/components/ui/button.d.ts +9 -0
  153. package/lib/components/ui/button.d.ts.map +1 -0
  154. package/lib/compute.d.ts +8 -0
  155. package/lib/compute.d.ts.map +1 -0
  156. package/lib/compute.js +137 -0
  157. package/lib/compute.js.map +1 -0
  158. package/lib/config/env-config.d.ts +13 -0
  159. package/lib/config/env-config.d.ts.map +1 -0
  160. package/lib/config/env-config.js +34 -0
  161. package/lib/config/env-config.js.map +1 -0
  162. package/lib/config/index.d.ts +2 -0
  163. package/lib/config/index.d.ts.map +1 -0
  164. package/lib/constants/breakpoints.d.ts +8 -0
  165. package/lib/constants/breakpoints.d.ts.map +1 -0
  166. package/lib/constants/index.d.ts +3 -0
  167. package/lib/constants/index.d.ts.map +1 -0
  168. package/lib/container/AiInbox.d.ts +15 -0
  169. package/lib/container/AiInbox.d.ts.map +1 -0
  170. package/lib/container/AiInboxWithLoader.d.ts +36 -0
  171. package/lib/container/AiInboxWithLoader.d.ts.map +1 -0
  172. package/lib/container/AiLandingInput.d.ts +4 -0
  173. package/lib/container/AiLandingInput.d.ts.map +1 -0
  174. package/lib/container/AiLandingInput.js +101 -0
  175. package/lib/container/AiLandingInput.js.map +1 -0
  176. package/lib/container/Inbox.d.ts +15 -0
  177. package/lib/container/Inbox.d.ts.map +1 -0
  178. package/lib/container/Inbox.js +955 -0
  179. package/lib/container/Inbox.js.map +1 -0
  180. package/lib/container/InboxAiMessagesLoader.d.ts +15 -0
  181. package/lib/container/InboxAiMessagesLoader.d.ts.map +1 -0
  182. package/lib/container/InboxAiMessagesLoader.js +30 -0
  183. package/lib/container/InboxAiMessagesLoader.js.map +1 -0
  184. package/lib/container/InboxContainer.d.ts +12 -0
  185. package/lib/container/InboxContainer.d.ts.map +1 -0
  186. package/lib/container/InboxContainer.js +31 -0
  187. package/lib/container/InboxContainer.js.map +1 -0
  188. package/lib/container/InboxTemplate1.d.ts +15 -0
  189. package/lib/container/InboxTemplate1.d.ts.map +1 -0
  190. package/lib/container/InboxTemplate1WithLoader.d.ts +36 -0
  191. package/lib/container/InboxTemplate1WithLoader.d.ts.map +1 -0
  192. package/lib/container/InboxTemplate2.d.ts +15 -0
  193. package/lib/container/InboxTemplate2.d.ts.map +1 -0
  194. package/lib/container/InboxWithAiLoader.d.ts +15 -0
  195. package/lib/container/InboxWithAiLoader.d.ts.map +1 -0
  196. package/lib/container/InboxWithAiLoader.js +56 -0
  197. package/lib/container/InboxWithAiLoader.js.map +1 -0
  198. package/lib/container/InboxWithLoader.d.ts +36 -0
  199. package/lib/container/InboxWithLoader.d.ts.map +1 -0
  200. package/lib/container/InboxWithLoader.js +277 -0
  201. package/lib/container/InboxWithLoader.js.map +1 -0
  202. package/lib/container/ServiceInbox.d.ts +9 -0
  203. package/lib/container/ServiceInbox.d.ts.map +1 -0
  204. package/lib/container/ServiceInbox.js +144 -0
  205. package/lib/container/ServiceInbox.js.map +1 -0
  206. package/lib/container/ThreadMessages.d.ts +13 -0
  207. package/lib/container/ThreadMessages.d.ts.map +1 -0
  208. package/lib/container/ThreadMessages.js +314 -0
  209. package/lib/container/ThreadMessages.js.map +1 -0
  210. package/lib/container/ThreadMessagesInbox.d.ts +14 -0
  211. package/lib/container/ThreadMessagesInbox.d.ts.map +1 -0
  212. package/lib/container/ThreadMessagesInbox.js +341 -0
  213. package/lib/container/ThreadMessagesInbox.js.map +1 -0
  214. package/lib/container/Threads.d.ts +8 -0
  215. package/lib/container/Threads.d.ts.map +1 -0
  216. package/lib/container/Threads.js +231 -0
  217. package/lib/container/Threads.js.map +1 -0
  218. package/lib/container/ThreadsInbox.d.ts +21 -0
  219. package/lib/container/ThreadsInbox.d.ts.map +1 -0
  220. package/lib/container/ThreadsInbox.js +244 -0
  221. package/lib/container/ThreadsInbox.js.map +1 -0
  222. package/lib/container/apply-footer-styles.d.ts +2 -0
  223. package/lib/container/apply-footer-styles.d.ts.map +1 -0
  224. package/lib/container/apply-footer-styles.js +16 -0
  225. package/lib/container/apply-footer-styles.js.map +1 -0
  226. package/lib/container/index.d.ts +13 -0
  227. package/lib/container/index.d.ts.map +1 -0
  228. package/lib/enums/index.d.ts +2 -0
  229. package/lib/enums/index.d.ts.map +1 -0
  230. package/lib/enums/messenger-slot-fill-name-enum.d.ts +5 -0
  231. package/lib/enums/messenger-slot-fill-name-enum.d.ts.map +1 -0
  232. package/lib/enums/messenger-slot-fill-name-enum.js +5 -0
  233. package/lib/enums/messenger-slot-fill-name-enum.js.map +1 -0
  234. package/lib/hooks/index.d.ts +3 -0
  235. package/lib/hooks/index.d.ts.map +1 -0
  236. package/lib/hooks/use-file-sync.d.ts +16 -0
  237. package/lib/hooks/use-file-sync.d.ts.map +1 -0
  238. package/lib/hooks/use-file-sync.js +63 -0
  239. package/lib/hooks/use-file-sync.js.map +1 -0
  240. package/lib/hooks/usePersistentModelConfig.d.ts +15 -0
  241. package/lib/hooks/usePersistentModelConfig.d.ts.map +1 -0
  242. package/lib/hooks/usePersistentModelConfig.js +46 -0
  243. package/lib/hooks/usePersistentModelConfig.js.map +1 -0
  244. package/lib/index.d.ts +10 -0
  245. package/lib/index.d.ts.map +1 -0
  246. package/lib/index.js +1 -0
  247. package/lib/index.js.map +1 -0
  248. package/lib/interfaces/index.d.ts +2 -0
  249. package/lib/interfaces/index.d.ts.map +1 -0
  250. package/lib/interfaces/message-widgets.interface.d.ts +21 -0
  251. package/lib/interfaces/message-widgets.interface.d.ts.map +1 -0
  252. package/lib/machines/aiAgentMachine.d.ts +3 -0
  253. package/lib/machines/aiAgentMachine.d.ts.map +1 -0
  254. package/lib/machines/aiAgentMachine.js +1083 -0
  255. package/lib/machines/aiAgentMachine.js.map +1 -0
  256. package/lib/machines/aiAgentMachine.simple.d.ts +3 -0
  257. package/lib/machines/aiAgentMachine.simple.d.ts.map +1 -0
  258. package/lib/machines/aiAgentMachine.simple.js +108 -0
  259. package/lib/machines/aiAgentMachine.simple.js.map +1 -0
  260. package/lib/machines/index.d.ts +3 -0
  261. package/lib/machines/index.d.ts.map +1 -0
  262. package/lib/machines/types.d.ts +77 -0
  263. package/lib/machines/types.d.ts.map +1 -0
  264. package/lib/module.d.ts +7 -0
  265. package/lib/module.d.ts.map +1 -0
  266. package/lib/module.js +26 -0
  267. package/lib/module.js.map +1 -0
  268. package/lib/routes.json +98 -0
  269. package/lib/styles/responsive.css +76 -0
  270. package/lib/templates/InboxWithAi.d.ts +15 -0
  271. package/lib/templates/InboxWithAi.d.ts.map +1 -0
  272. package/lib/templates/InboxWithAi.js +440 -0
  273. package/lib/templates/InboxWithAi.js.map +1 -0
  274. package/lib/templates/InboxWithAi.tsx +533 -0
  275. package/lib/templates/index.d.ts +2 -0
  276. package/lib/templates/index.d.ts.map +1 -0
  277. package/lib/templates/index.ts +1 -0
  278. package/lib/utils/utils.d.ts +2 -0
  279. package/lib/utils/utils.d.ts.map +1 -0
  280. package/lib/utils/utils.js +3 -0
  281. package/lib/utils/utils.js.map +1 -0
  282. package/package.json +62 -0
  283. package/rollup.config.mjs +35 -0
  284. package/src/cdm-locales/en/translations.json +31 -0
  285. package/src/cdm-locales/es/translations.json +31 -0
  286. package/src/components/AIAgent/AIAgent.tsx +1103 -0
  287. package/src/components/AIAgent/AIAgent.tsx.bk +1365 -0
  288. package/src/components/AIAgent/README.md +82 -0
  289. package/src/components/AIAgent/index.ts +1 -0
  290. package/src/components/InboxMessage/CommonMessage.tsx +40 -0
  291. package/src/components/InboxMessage/ConversationItem.tsx +255 -0
  292. package/src/components/InboxMessage/InputComponent.tsx +462 -0
  293. package/src/components/InboxMessage/LeftSidebar.tsx +140 -0
  294. package/src/components/InboxMessage/MessageInput.tsx +209 -0
  295. package/src/components/InboxMessage/MessageInputComponent.tsx +245 -0
  296. package/src/components/InboxMessage/Messages.tsx +137 -0
  297. package/src/components/InboxMessage/MessagesBuilderUi.tsx +205 -0
  298. package/src/components/InboxMessage/Popover.tsx +42 -0
  299. package/src/components/InboxMessage/RightSidebar.tsx +22 -0
  300. package/src/components/InboxMessage/RightSidebarAi.tsx +37 -0
  301. package/src/components/InboxMessage/ServiceConversationItem.tsx +234 -0
  302. package/src/components/InboxMessage/ServiceInboxItem.tsx +223 -0
  303. package/src/components/InboxMessage/SubscriptionHandler.tsx +55 -0
  304. package/src/components/InboxMessage/UploadImageButton.tsx +46 -0
  305. package/src/components/InboxMessage/UserModalContent.tsx +60 -0
  306. package/src/components/InboxMessage/index.ts +16 -0
  307. package/src/components/InboxMessage/message-widgets/CommonMessage.tsx +69 -0
  308. package/src/components/InboxMessage/message-widgets/ErrorFixCard.tsx +240 -0
  309. package/src/components/InboxMessage/message-widgets/MessageCard.tsx +127 -0
  310. package/src/components/InboxMessage/message-widgets/MessageSliceRenderer.tsx +40 -0
  311. package/src/components/InboxMessage/message-widgets/ModernMessageGroup.tsx +1295 -0
  312. package/src/components/InboxMessage/message-widgets/PlainMessage.tsx +18 -0
  313. package/src/components/InboxMessage/message-widgets/PropertyMessageWidget.tsx +29 -0
  314. package/src/components/InboxMessage/message-widgets/SlackLikeMessageGroup.tsx +492 -0
  315. package/src/components/InboxMessage/message-widgets/index.ts +3 -0
  316. package/src/components/ModelConfigPanel.tsx +345 -0
  317. package/src/components/filler-components/RightSiderBar.tsx +408 -0
  318. package/src/components/inbox/FilesList.tsx +89 -0
  319. package/src/components/inbox/MessageItem.tsx +50 -0
  320. package/src/components/inbox/ThreadItem.tsx +295 -0
  321. package/src/components/inbox/index.ts +3 -0
  322. package/src/components/index.ts +22 -0
  323. package/src/components/live-code-editor/hybrid-live-editor.tsx +105 -0
  324. package/src/components/live-code-editor/index.ts +3 -0
  325. package/src/components/live-code-editor/live-code-editor.tsx +257 -0
  326. package/src/components/slot-fill/chat-message-filler.tsx +18 -0
  327. package/src/components/slot-fill/chat-message-slot.tsx +18 -0
  328. package/src/components/slot-fill/index.ts +3 -0
  329. package/src/components/slot-fill/right-sidebar-filler.tsx +39 -0
  330. package/src/components/ui/button.tsx +32 -0
  331. package/src/compute.ts +134 -0
  332. package/src/config/env-config.ts +17 -0
  333. package/src/config/index.ts +1 -0
  334. package/src/constants/breakpoints.ts +7 -0
  335. package/src/constants/index.ts +5 -0
  336. package/src/container/AiInbox.tsx +1819 -0
  337. package/src/container/AiInboxWithLoader.tsx +356 -0
  338. package/src/container/AiLandingInput.tsx +221 -0
  339. package/src/container/Inbox.tsx +1092 -0
  340. package/src/container/InboxAiMessagesLoader.tsx +44 -0
  341. package/src/container/InboxContainer.tsx +35 -0
  342. package/src/container/InboxTemplate1.tsx +1542 -0
  343. package/src/container/InboxTemplate1WithLoader.tsx +338 -0
  344. package/src/container/InboxTemplate2.tsx +1606 -0
  345. package/src/container/InboxWithAiLoader.tsx +76 -0
  346. package/src/container/InboxWithLoader.tsx +341 -0
  347. package/src/container/ServiceInbox.tsx +190 -0
  348. package/src/container/ThreadMessages.tsx +371 -0
  349. package/src/container/ThreadMessagesInbox.tsx +450 -0
  350. package/src/container/Threads.tsx +270 -0
  351. package/src/container/ThreadsInbox.tsx +354 -0
  352. package/src/container/apply-footer-styles.ts +17 -0
  353. package/src/container/index.ts +31 -0
  354. package/src/enums/index.ts +1 -0
  355. package/src/enums/messenger-slot-fill-name-enum.ts +4 -0
  356. package/src/hooks/index.ts +2 -0
  357. package/src/hooks/use-file-sync.ts +91 -0
  358. package/src/hooks/usePersistentModelConfig.ts +63 -0
  359. package/src/index.ts +37 -0
  360. package/src/interfaces/index.ts +1 -0
  361. package/src/interfaces/message-widgets.interface.ts +21 -0
  362. package/src/machines/aiAgentMachine.simple.ts +89 -0
  363. package/src/machines/aiAgentMachine.ts +1296 -0
  364. package/src/machines/aiAgentMachine.ts.bk +1296 -0
  365. package/src/machines/index.ts +2 -0
  366. package/src/machines/types.ts +59 -0
  367. package/src/module.tsx +32 -0
  368. package/src/styles/responsive.css +76 -0
  369. package/src/templates/InboxWithAi.tsx +533 -0
  370. package/src/templates/index.ts +1 -0
  371. package/src/utils/utils.ts +3 -0
  372. package/tsconfig.json +14 -0
  373. package/webpack.config.js +92 -0
@@ -0,0 +1,1083 @@
1
+ import {createMachine,assign,fromPromise}from'xstate';import {config}from'../config/env-config.js';const {
2
+ CLIENT_URL,
3
+ NEWS_API_KEY
4
+ } = config;
5
+ const env = {
6
+ NEWS_API_KEY: NEWS_API_KEY
7
+ };
8
+ // API configuration - using environment variables from dev.env
9
+ // Read persisted model configuration saved by usePersistentModelConfig
10
+ function getUserModelConfig() {
11
+ try {
12
+ if (typeof window === 'undefined') return {};
13
+ const raw = window.localStorage.getItem('mbx:model-config');
14
+ if (!raw) return {};
15
+ const parsed = JSON.parse(raw);
16
+ return {
17
+ provider: parsed?.provider,
18
+ model: parsed?.model,
19
+ apiKey: parsed?.apiKey
20
+ };
21
+ } catch {
22
+ return {};
23
+ }
24
+ }
25
+ const USER_MODEL_CONFIG = getUserModelConfig();
26
+ const API_CONFIG = {
27
+ // Only non-AI keys from env (public APIs allowed)
28
+ NEWS_API_KEY: env?.NEWS_API_KEY,
29
+ // Configurable proxy endpoints
30
+ ANTHROPIC_ENDPOINT: '/api/anthropic/messages',
31
+ OPENAI_ENDPOINT: '/api/openai',
32
+ // Direct MCP search APIs (these are public and don't have CORS issues)
33
+ NEWS_API_ENDPOINT: 'https://newsapi.org/v2/everything',
34
+ REDDIT_SEARCH_ENDPOINT: 'https://www.reddit.com/search.json',
35
+ REDDIT_TRENDING_ENDPOINT: 'https://www.reddit.com/r/news/hot.json',
36
+ DUCKDUCKGO_ENDPOINT: 'https://api.duckduckgo.com/',
37
+ // Model configuration
38
+ DEFAULT_MODEL: 'claude-3-5-haiku-20241022',
39
+ OPENAI_MODEL: 'gpt-4o-mini',
40
+ // User-provided model configuration (from localStorage)
41
+ get userProvider() {
42
+ return USER_MODEL_CONFIG?.provider;
43
+ },
44
+ get userModel() {
45
+ return USER_MODEL_CONFIG?.model;
46
+ },
47
+ get userApiKey() {
48
+ return USER_MODEL_CONFIG?.apiKey;
49
+ },
50
+ // Check which AI provider is available (ONLY from user config)
51
+ get availableProvider() {
52
+ if (this.userApiKey && this.userProvider) {
53
+ if (this.userProvider === 'anthropic') return 'anthropic';
54
+ if (this.userProvider === 'openai') return 'openai';
55
+ }
56
+ return null;
57
+ },
58
+ // Get the appropriate endpoint based on available provider
59
+ get primaryEndpoint() {
60
+ if (this.availableProvider === 'anthropic') return this.ANTHROPIC_ENDPOINT;
61
+ if (this.availableProvider === 'openai') return this.OPENAI_ENDPOINT;
62
+ return '';
63
+ },
64
+ // Get the appropriate model based on available provider
65
+ get primaryModel() {
66
+ if (this.userModel) return this.userModel;
67
+ if (this.availableProvider === 'anthropic') return this.DEFAULT_MODEL;
68
+ if (this.availableProvider === 'openai') return this.OPENAI_MODEL;
69
+ return this.DEFAULT_MODEL;
70
+ }
71
+ };
72
+ // Log configuration on startup
73
+ console.log('🤖 AI Agent Machine Configuration:');
74
+ console.log(` Available Provider (user): ${API_CONFIG.availableProvider || 'None'}`);
75
+ console.log(` Primary Endpoint: ${API_CONFIG.primaryEndpoint}`);
76
+ console.log(` Primary Model: ${API_CONFIG.primaryModel}`);
77
+ console.log(` Using Proxy for AI APIs: ✅ (avoids CORS issues)`);
78
+ console.log(` Using Direct APIs for MCP Search: ✅ (public APIs)`);
79
+ console.log(` User API Key: ${API_CONFIG.userApiKey ? '✅ Configured' : '❌ Not configured'}`);
80
+ console.log(` News API Key: ${API_CONFIG.NEWS_API_KEY ? '✅ Configured' : '❌ Not configured'}`);
81
+ // Test API configuration
82
+ if (!API_CONFIG.availableProvider) {
83
+ console.error('🚨 CRITICAL: No AI API provider configured!');
84
+ console.error('🚨 Please add your API key in Model Settings.');
85
+ } else {
86
+ console.log(`✅ AI API provider configured: ${API_CONFIG.availableProvider}`);
87
+ }
88
+ // Helper function to get the base URL for proxy calls
89
+ function getProxyBaseUrl() {
90
+ // Use Vite dev server proxy to avoid CORS issues
91
+ return CLIENT_URL || 'http://localhost:3011'; // Vite dev server
92
+ }
93
+ // Log the current proxy configuration
94
+ console.log(`🌐 Proxy Configuration: ${getProxyBaseUrl()}`);
95
+ // Helper function to make API calls through proxy (avoids CORS)
96
+ async function makeApiCall(endpoint, options) {
97
+ try {
98
+ const baseUrl = getProxyBaseUrl();
99
+ const url = endpoint ? `${baseUrl}${endpoint}` : '';
100
+ console.log(`🌐 Making API call through proxy to: ${url}`);
101
+ console.log(`📤 Request options:`, {
102
+ method: options.method,
103
+ headers: options.headers,
104
+ body: options.body ? JSON.parse(options.body) : undefined
105
+ });
106
+ // Do not call if no endpoint (no provider configured)
107
+ if (!endpoint) {
108
+ throw new Error('AI provider is not configured. Please add your API key in Model Settings.');
109
+ }
110
+ // Inject API key headers from user config if available
111
+ const headers = new Headers(options.headers || {});
112
+ if (API_CONFIG.userApiKey) {
113
+ if (API_CONFIG.availableProvider === 'anthropic') {
114
+ headers.set('x-api-key', API_CONFIG.userApiKey);
115
+ headers.set('anthropic-version', '2023-06-01');
116
+ headers.set('anthropic-dangerous-direct-browser-access', 'true');
117
+ } else if (API_CONFIG.availableProvider === 'openai') {
118
+ headers.set('Authorization', `Bearer ${API_CONFIG.userApiKey}`);
119
+ }
120
+ }
121
+ const response = await fetch(url, {
122
+ ...options,
123
+ headers
124
+ });
125
+ if (!response.ok) {
126
+ const errorData = await response.json().catch(() => ({}));
127
+ console.error('🚨 API Error:', response.status, errorData);
128
+ let errorMessage = 'API request failed';
129
+ if (errorData.error) {
130
+ if (typeof errorData.error === 'string') {
131
+ errorMessage = errorData.error;
132
+ } else if (errorData.error.message) {
133
+ errorMessage = errorData.error.message;
134
+ } else if (errorData.error.type) {
135
+ errorMessage = `${errorData.error.type}: ${errorData.error.message || 'Unknown error'}`;
136
+ }
137
+ }
138
+ throw new Error(errorMessage);
139
+ }
140
+ return response;
141
+ } catch (error) {
142
+ console.error('🚨 API call error:', error);
143
+ throw error;
144
+ }
145
+ }
146
+ // Helper function to fetch news from NewsAPI directly
147
+ async function fetchNewsFromNewsAPI(query) {
148
+ if (!API_CONFIG.NEWS_API_KEY) {
149
+ console.warn('⚠️ News API key not found, skipping NewsAPI');
150
+ return [];
151
+ }
152
+ try {
153
+ const response = await fetch(`${API_CONFIG.NEWS_API_ENDPOINT}?q=${encodeURIComponent(query)}&apiKey=${API_CONFIG.NEWS_API_KEY}&language=en&sortBy=publishedAt&pageSize=5`);
154
+ if (!response.ok) {
155
+ console.error('NewsAPI error:', response.status);
156
+ return [];
157
+ }
158
+ const data = await response.json();
159
+ if (data.articles) {
160
+ return data.articles.map(article => ({
161
+ title: article.title,
162
+ url: article.url,
163
+ description: article.description || article.title,
164
+ publishedAt: article.publishedAt,
165
+ source: {
166
+ name: article.source.name
167
+ }
168
+ }));
169
+ }
170
+ } catch (error) {
171
+ console.error('NewsAPI error:', error);
172
+ }
173
+ return [];
174
+ }
175
+ // Helper function to fetch from Reddit API directly
176
+ async function fetchAlternativeNews(query) {
177
+ try {
178
+ const response = await fetch(`${API_CONFIG.REDDIT_SEARCH_ENDPOINT}?q=${encodeURIComponent(query)}&sort=new&t=day&limit=3&restrict_sr=false&type=link`);
179
+ if (!response.ok) {
180
+ console.error('Reddit API error:', response.status);
181
+ return [];
182
+ }
183
+ const data = await response.json();
184
+ if (data?.data?.children) {
185
+ return data.data.children.filter(post => post.data.url && !post.data.is_self).slice(0, 3).map(post => ({
186
+ title: post.data.title,
187
+ url: post.data.url,
188
+ description: `Discussion: ${post.data.title} (${post.data.score} upvotes)`,
189
+ publishedAt: new Date(post.data.created_utc * 1000).toISOString(),
190
+ source: {
191
+ name: `r/${post.data.subreddit}`
192
+ }
193
+ }));
194
+ }
195
+ } catch (error) {
196
+ console.error('Reddit API error:', error);
197
+ }
198
+ return [];
199
+ }
200
+ // Helper function to search DuckDuckGo directly
201
+ async function searchDuckDuckGo(query) {
202
+ try {
203
+ const response = await fetch(`${API_CONFIG.DUCKDUCKGO_ENDPOINT}?q=${encodeURIComponent(query)}&format=json&no_html=1&skip_disambig=1`);
204
+ if (!response.ok) {
205
+ console.error('DuckDuckGo API error:', response.status);
206
+ return [];
207
+ }
208
+ const data = await response.json();
209
+ const results = [];
210
+ // Add abstract if available
211
+ if (data.Abstract) {
212
+ results.push({
213
+ title: data.Heading || `About ${query}`,
214
+ url: data.AbstractURL || `https://duckduckgo.com/?q=${encodeURIComponent(query)}`,
215
+ snippet: data.Abstract,
216
+ source: 'DuckDuckGo'
217
+ });
218
+ }
219
+ // Add related topics
220
+ if (data.RelatedTopics && data.RelatedTopics.length > 0) {
221
+ data.RelatedTopics.slice(0, 3).forEach(topic => {
222
+ if (topic.Text && topic.FirstURL) {
223
+ results.push({
224
+ title: topic.Text.split(' - ')[0] || topic.Text.substring(0, 60),
225
+ url: topic.FirstURL,
226
+ snippet: topic.Text,
227
+ source: 'DuckDuckGo'
228
+ });
229
+ }
230
+ });
231
+ }
232
+ return results;
233
+ } catch (error) {
234
+ console.error('DuckDuckGo API error:', error);
235
+ return [];
236
+ }
237
+ }
238
+ // Helper function to get trending news from Reddit directly
239
+ async function getTrendingNews() {
240
+ try {
241
+ const response = await fetch(`${API_CONFIG.REDDIT_TRENDING_ENDPOINT}?limit=5`);
242
+ if (!response.ok) {
243
+ console.error('Reddit trending error:', response.status);
244
+ return [];
245
+ }
246
+ const data = await response.json();
247
+ if (data?.data?.children) {
248
+ return data.data.children.filter(post => post.data.url && !post.data.is_self).map(post => ({
249
+ title: post.data.title,
250
+ url: post.data.url,
251
+ description: `Trending: ${post.data.title} (${post.data.score} upvotes, ${post.data.num_comments} comments)`,
252
+ publishedAt: new Date(post.data.created_utc * 1000).toISOString(),
253
+ source: {
254
+ name: 'r/news'
255
+ }
256
+ }));
257
+ }
258
+ } catch (error) {
259
+ console.error('Reddit trending error:', error);
260
+ }
261
+ return [];
262
+ }
263
+ // Direct MCP search function - no more server dependency
264
+ async function performDirectMCPSearch(query, includeNews = true, includeWeb = true) {
265
+ try {
266
+ console.log(`🔍 Performing direct MCP search for: "${query}" (news: ${includeNews}, web: ${includeWeb})`);
267
+ const promises = [];
268
+ // Fetch news if requested
269
+ if (includeNews) {
270
+ // Try multiple news sources
271
+ promises.push(fetchNewsFromNewsAPI(query), fetchAlternativeNews(query));
272
+ // For US news specifically, get trending
273
+ if (query.toLowerCase().includes('us news') || query.toLowerCase().includes('american news')) {
274
+ promises.push(getTrendingNews());
275
+ }
276
+ }
277
+ // Fetch web search if requested
278
+ if (includeWeb) {
279
+ promises.push(searchDuckDuckGo(query));
280
+ }
281
+ // Execute all searches concurrently
282
+ const results = await Promise.allSettled(promises);
283
+ // Combine all successful results
284
+ let searchResults = [];
285
+ let newsArticles = [];
286
+ results.forEach((result, index) => {
287
+ if (result.status === 'fulfilled' && Array.isArray(result.value)) {
288
+ if (includeWeb && index === results.length - 1) {
289
+ // Last promise is web search
290
+ searchResults = result.value;
291
+ } else if (includeNews) {
292
+ // Other promises are news sources
293
+ newsArticles = [...newsArticles, ...result.value];
294
+ }
295
+ }
296
+ });
297
+ // Remove duplicates and limit results
298
+ newsArticles = newsArticles.filter((article, index, self) => index === self.findIndex(a => a.title === article.title)).slice(0, 8);
299
+ searchResults = searchResults.slice(0, 5);
300
+ const response = {
301
+ searchResults: includeWeb ? searchResults : [],
302
+ newsArticles: includeNews ? newsArticles : [],
303
+ summary: `Found ${searchResults.length} web results and ${newsArticles.length} news articles for "${query}"`,
304
+ sources: [...(includeWeb ? ['DuckDuckGo'] : []), ...(includeNews ? ['NewsAPI', 'Reddit', 'Alternative Sources'] : [])].filter(Boolean),
305
+ searchTime: Date.now(),
306
+ realData: true // Flag to indicate this is real data
307
+ };
308
+ console.log(`✅ Direct MCP search completed: ${response.searchResults.length} web + ${response.newsArticles.length} news results`);
309
+ return response;
310
+ } catch (error) {
311
+ console.error('🚨 Direct MCP search error:', error);
312
+ throw error;
313
+ }
314
+ }
315
+ // Helper function to detect if a query needs multi-message response
316
+ function needsMultiMessageResponse(query) {
317
+ const multiMessageKeywords = ['explain step by step', 'break down', 'tutorial', 'guide', 'how to', 'teach me', 'walk me through', 'step-by-step', 'detailed explanation', 'in detail', 'comprehensive', 'thorough', 'complete guide', 'coding', 'programming', 'development', 'build', 'create', 'multiple', 'several', 'various', 'different ways'];
318
+ const lowerQuery = query.toLowerCase();
319
+ return multiMessageKeywords.some(keyword => lowerQuery.includes(keyword)) || query.length > 200; // Long queries often benefit from multi-message responses
320
+ }
321
+ // Helper function to detect if a query needs real-time data
322
+ function needsRealTimeData(query) {
323
+ const realTimeKeywords = ['latest', 'recent', 'news', 'current', 'today', 'yesterday', 'breaking', 'update', 'now', 'price', 'stock', 'weather', 'trending', 'popular', 'search', "what's happening", 'tell me about', 'find', 'look up', 'research'];
324
+ const lowerQuery = query.toLowerCase();
325
+ return realTimeKeywords.some(keyword => lowerQuery.includes(keyword));
326
+ }
327
+ // Helper function to format MCP data for the agent
328
+ function formatMCPDataForAgent(mcpData) {
329
+ let context = '';
330
+ if (mcpData.searchResults && mcpData.searchResults.length > 0) {
331
+ context += 'Current web search results:\n';
332
+ mcpData.searchResults.forEach((result, i) => {
333
+ context += `${i + 1}. **${result.title}**\n ${result.snippet}\n Source: ${result.url}\n\n`;
334
+ });
335
+ }
336
+ if (mcpData.newsArticles && mcpData.newsArticles.length > 0) {
337
+ context += 'Recent news articles:\n';
338
+ mcpData.newsArticles.forEach((article, i) => {
339
+ context += `${i + 1}. **${article.title}**\n ${article.description}\n Published: ${new Date(article.publishedAt).toLocaleDateString()}\n Source: ${article.source.name}\n\n`;
340
+ });
341
+ }
342
+ if (context) {
343
+ context = 'Here is the current information I have access to:\n\n' + context + '\nPlease use this information to provide an accurate, up-to-date response.';
344
+ }
345
+ return context;
346
+ }
347
+ // Helper function to get the appropriate system prompt based on provider
348
+ function getSystemPrompt(provider, includeMCP = false) {
349
+ const basePrompt = includeMCP ? 'You are a helpful AI assistant that can access real-time information through web search and news APIs. When provided with current information, use it to give accurate, up-to-date responses. Always cite your sources when referencing specific information from search results or news articles. You excel at providing comprehensive analysis and insights based on the latest data available.' : 'You are a helpful AI assistant that provides detailed, step-by-step responses. Focus on the specific aspect requested and provide practical, actionable information.';
350
+ if (provider === 'anthropic') {
351
+ return basePrompt;
352
+ } else if (provider === 'openai') {
353
+ return basePrompt;
354
+ }
355
+ return basePrompt;
356
+ }
357
+ // Helper function to get conversation context from regular messages
358
+ function getConversationContext(regularMessages) {
359
+ if (!regularMessages || regularMessages.length === 0) return '';
360
+ // Get the last few messages for context
361
+ const recentMessages = regularMessages.slice(-5);
362
+ let context = 'Recent conversation context:\n';
363
+ recentMessages.forEach((msg, index) => {
364
+ const author = msg.author?.username || msg.author?.givenName || 'User';
365
+ const content = msg.message?.substring(0, 200) || ''; // Limit content length
366
+ if (content.trim()) {
367
+ context += `${index + 1}. ${author}: ${content}\n`;
368
+ }
369
+ });
370
+ return context + '\n';
371
+ }
372
+ const aiAgentMachine = createMachine({
373
+ /** @xstate-layout N4IgpgJg5mDOIC5QEMCWBBGA7ALgOlQgBswBiAZQFEA5AEQH0BZS889AcUoG0AGAXUSgADgHtYqHKhFZBIAB6IA7ACZleAGwBWdYoAsmngA4AzAE5Fi4wBoQAT0S6AjKbzHHy06aO7Du3eoBfAJs0TDBcAmIyAElqAAUAVQAVegBhAAl0ak5eASQQUXFJaVkFBE1dF0dvXx49Q19NG3sEXUUXHz9lRydFA2dNIJCMbHxCElJUgBlKdAAleko5uYB5OdzZQokpGXyyzU1jPFN9ZXVdHmN9dUNmxGNfPB7NRUNnR0N1ZX0hkFDRvDILDIIi2ABeqCwUFIG3yW2Ku1AZXcykUGlMhk0hh4PEcenU5zurV0R16yiupkODV+-3C+CBIPBkOhXEceWEYm2JT2iBRaPUGKxOLx-kJdkQ33UeA8ZnUxiuulRuhpIzpeAAZmAcABjAAWzNoyBwyFIEGkYAIWAAbiIANYWzU63WMVJxQ3G2Ecoo7Uq87FS8lnE6KardInGc54TTKF48bQVE4VQbBP6qiKOvUGo0msAAJ1zIlzeCERCN6sLAFsNVq9S63dnPQVOQjfQgPjwA8Yg21Q44idc8J8LspcapHMYeMqU7SIkIC9q4OIoabzZabfa8Ng80awHM4KIsLAwI34T6eW3-dKuwKezww+LynLjoZVDxPKiu20VWFZ-PF8zSDzAsixLMtK03cJtxwXd92kI8T2bM8kT9Ooo0sN9HEwrpLiJN4nkMSxTEwgjFHUONFG-AEgMLUg5koJI5gATQQ71uWQhByU0KMfDOao3zfZRbgfFQpVqaNtAJTRiMotVqNzCgaAYZhWA4bh+E2RC2PkCVjC4ioX3UPivFMQSiW+HhjlI-xugFD4Xgo6c03wOTSFiRIUgyLIcnUuFNMRbTWmUIlDN0fDsUxPofCMYwZIiFzplmBYllWdYfK9Ll-LKTjuIMoyBKEloEw0KS3zImUzAclMsBECA4FkGccA01jMsQABadQiVarjPB63revaWKxiiJqMtbTQTjwfijH4vxxtMIkXhcF8JzIoi5XaGLHJ-elgVBCEoRGltz2qJxpUcc5elIyk5X7S5Bx0HE4yIypLEG6snSzY1DqQgKehfPBh3ld9cTjawHycQxJq+Ui3wjEy8U24ZtuLP9YCXKBvq0rK4wsr5DhDLwe10fsYyeO930Mkw9HMN65MxlqEEeO9qbleVun8RQiRDULox0GMYwjTFAiCAIgA */
374
+ id: 'aiAgent',
375
+ types: {},
376
+ initial: 'idle',
377
+ context: {
378
+ messages: [],
379
+ currentInput: '',
380
+ error: null,
381
+ isTyping: false,
382
+ multiMessageMode: false,
383
+ currentMultiStep: 0,
384
+ totalMultiSteps: 0,
385
+ multiMessagePlan: [],
386
+ mcpData: undefined,
387
+ regularMessages: [] // Add regular messages from query
388
+ },
389
+ states: {
390
+ idle: {
391
+ on: {
392
+ SEND_MESSAGE: {
393
+ target: 'analyzing',
394
+ guard: 'hasValidMessage',
395
+ actions: 'addUserMessage'
396
+ },
397
+ FORCE_MULTI_MESSAGE: {
398
+ target: 'analyzing',
399
+ guard: 'hasValidMessage',
400
+ actions: 'addUserMessage'
401
+ },
402
+ AUTO_RESPOND_TO_MESSAGE: {
403
+ target: 'processing',
404
+ guard: 'hasValidMessage',
405
+ actions: 'addAutoResponseMessage'
406
+ },
407
+ INPUT_CHANGE: {
408
+ actions: 'updateInput'
409
+ },
410
+ CLEAR_ERROR: {
411
+ actions: 'clearError'
412
+ },
413
+ UPDATE_REGULAR_MESSAGES: {
414
+ actions: 'updateRegularMessages'
415
+ },
416
+ ANALYZE_EXISTING_CONTEXT: {
417
+ target: 'analyzing',
418
+ guard: 'hasExistingContext',
419
+ actions: 'addContextAnalysisMessage'
420
+ },
421
+ CONTINUE_PROCESSING: {
422
+ // Just stay in idle state to trigger the useEffect again
423
+ actions: 'logContinueProcessing'
424
+ }
425
+ }
426
+ },
427
+ analyzing: {
428
+ entry: 'setTyping',
429
+ always: [{
430
+ target: 'planningMultiMessage',
431
+ guard: 'shouldUseMultiMessage'
432
+ }, {
433
+ target: 'fetchingData',
434
+ guard: 'queryNeedsRealTimeData'
435
+ }, {
436
+ target: 'processing'
437
+ }]
438
+ },
439
+ planningMultiMessage: {
440
+ entry: 'setMultiMessageMode',
441
+ invoke: {
442
+ id: 'generateMultiMessagePlan',
443
+ src: 'generateMultiMessagePlan',
444
+ input: ({
445
+ context
446
+ }) => ({
447
+ query: context.messages[context.messages.length - 1]?.content || '',
448
+ regularMessages: context.regularMessages
449
+ }),
450
+ onDone: {
451
+ target: 'multiProcessing',
452
+ actions: 'setMultiMessagePlan'
453
+ },
454
+ onError: {
455
+ target: 'processing' // Fall back to single message
456
+ }
457
+ }
458
+ },
459
+ multiProcessing: {
460
+ invoke: {
461
+ id: 'generateMultiMessage',
462
+ src: 'generateMultiMessage',
463
+ input: ({
464
+ context
465
+ }) => ({
466
+ messages: context.messages,
467
+ plan: context.multiMessagePlan,
468
+ currentStep: context.currentMultiStep,
469
+ mcpData: context.mcpData,
470
+ regularMessages: context.regularMessages
471
+ }),
472
+ onDone: [{
473
+ target: 'waitingBetweenMessages',
474
+ guard: 'hasMoreMultiMessages',
475
+ actions: ['addAIMessage', 'incrementMultiStep']
476
+ }, {
477
+ target: 'idle',
478
+ actions: ['addAIMessage', 'resetMultiMessage']
479
+ }],
480
+ onError: {
481
+ target: 'error',
482
+ actions: 'setError'
483
+ }
484
+ }
485
+ },
486
+ waitingBetweenMessages: {
487
+ entry: 'setTyping',
488
+ after: {
489
+ 1500: 'multiProcessing'
490
+ }
491
+ },
492
+ fetchingData: {
493
+ invoke: {
494
+ id: 'fetchMCPData',
495
+ src: 'fetchMCPData',
496
+ input: ({
497
+ context
498
+ }) => ({
499
+ query: context.messages[context.messages.length - 1]?.content || ''
500
+ }),
501
+ onDone: {
502
+ target: 'processing',
503
+ actions: 'setMCPData'
504
+ },
505
+ onError: {
506
+ target: 'processing'
507
+ }
508
+ }
509
+ },
510
+ processing: {
511
+ entry: () => {
512
+ console.log('🤖 Entering processing state');
513
+ },
514
+ invoke: {
515
+ id: 'generateResponse',
516
+ src: 'generateAIResponse',
517
+ input: ({
518
+ context
519
+ }) => {
520
+ console.log('🤖 generateAIResponse input:', {
521
+ messagesCount: context.messages.length,
522
+ hasMessageToRespondTo: !!context.messageToRespondTo,
523
+ messageToRespondTo: context.messageToRespondTo,
524
+ regularMessagesCount: context.regularMessages?.length || 0
525
+ });
526
+ return {
527
+ messages: context.messages,
528
+ mcpData: context.mcpData,
529
+ regularMessages: context.regularMessages,
530
+ messageToRespondTo: context.messageToRespondTo
531
+ };
532
+ },
533
+ onDone: {
534
+ target: 'idle',
535
+ actions: [assign(({
536
+ context,
537
+ event
538
+ }) => {
539
+ console.log('🤖 🎯 onDone transition triggered with event:', event);
540
+ console.log('🤖 🎯 Event type:', typeof event);
541
+ console.log('🤖 🎯 Event content:', event);
542
+ return context;
543
+ }), 'addAIMessage']
544
+ },
545
+ onError: {
546
+ target: 'error',
547
+ actions: 'setError'
548
+ }
549
+ }
550
+ },
551
+ error: {
552
+ on: {
553
+ RETRY: {
554
+ target: 'processing'
555
+ },
556
+ SEND_MESSAGE: {
557
+ target: 'analyzing',
558
+ guard: 'hasValidMessage',
559
+ actions: 'addUserMessage'
560
+ },
561
+ INPUT_CHANGE: {
562
+ actions: 'updateInput'
563
+ },
564
+ CLEAR_ERROR: {
565
+ target: 'idle',
566
+ actions: 'clearError'
567
+ },
568
+ UPDATE_REGULAR_MESSAGES: {
569
+ actions: 'updateRegularMessages'
570
+ }
571
+ }
572
+ }
573
+ }
574
+ }, {
575
+ guards: {
576
+ hasValidMessage: ({
577
+ event
578
+ }) => {
579
+ console.log('🔍 hasValidMessage guard called with event:', event);
580
+ if (event.type === 'AUTO_RESPOND_TO_MESSAGE') {
581
+ const isValid = event.message?.trim().length > 0;
582
+ console.log('🔍 AUTO_RESPOND_TO_MESSAGE guard result:', isValid, 'message:', event.message);
583
+ return isValid;
584
+ }
585
+ if (event.type === 'SEND_MESSAGE' || event.type === 'FORCE_MULTI_MESSAGE') {
586
+ const isValid = event.message?.trim().length > 0;
587
+ console.log('🔍 SEND_MESSAGE/FORCE_MULTI_MESSAGE guard result:', isValid, 'message:', event.message);
588
+ return isValid;
589
+ }
590
+ console.log('🔍 Unknown event type in hasValidMessage guard:', event.type);
591
+ return false;
592
+ },
593
+ shouldUseMultiMessage: ({
594
+ context,
595
+ event
596
+ }) => {
597
+ if (event.type === 'FORCE_MULTI_MESSAGE') return true;
598
+ const lastMessage = context.messages[context.messages.length - 1];
599
+ if (!lastMessage || lastMessage.sender !== 'user') return false;
600
+ const shouldUse = needsMultiMessageResponse(lastMessage.content);
601
+ console.log('🔄 Should use multi-message:', shouldUse, 'for:', lastMessage.content);
602
+ return shouldUse;
603
+ },
604
+ queryNeedsRealTimeData: ({
605
+ context
606
+ }) => {
607
+ const lastMessage = context.messages[context.messages.length - 1];
608
+ if (!lastMessage || lastMessage.sender !== 'user') return false;
609
+ const needs = needsRealTimeData(lastMessage.content);
610
+ console.log('🔍 Query needs real-time data:', needs, 'for:', lastMessage.content);
611
+ return needs;
612
+ },
613
+ hasMoreMultiMessages: ({
614
+ context
615
+ }) => {
616
+ return context.currentMultiStep < context.totalMultiSteps - 1;
617
+ },
618
+ hasExistingContext: ({
619
+ context
620
+ }) => {
621
+ return context.regularMessages && context.regularMessages.length > 0;
622
+ }
623
+ },
624
+ actions: {
625
+ addUserMessage: assign(({
626
+ context,
627
+ event
628
+ }) => {
629
+ if (event.type !== 'SEND_MESSAGE' && event.type !== 'FORCE_MULTI_MESSAGE') return context;
630
+ const newMessage = {
631
+ id: Date.now().toString(),
632
+ content: event.message,
633
+ sender: 'user',
634
+ timestamp: new Date()
635
+ };
636
+ return {
637
+ ...context,
638
+ messages: [...context.messages, newMessage],
639
+ currentInput: '',
640
+ error: null,
641
+ mcpData: undefined,
642
+ messageToRespondTo: undefined // Clear the message to respond to when adding new user message
643
+ };
644
+ }),
645
+ addAIMessage: assign(({
646
+ context,
647
+ event
648
+ }) => {
649
+ console.log('🤖 addAIMessage called with event:', event);
650
+ // Extract the AI response content from the event
651
+ let aiResponseContent = '';
652
+ // Handle different event formats
653
+ if (event && typeof event === 'object') {
654
+ if ('output' in event) {
655
+ aiResponseContent = event.output;
656
+ } else if ('data' in event) {
657
+ aiResponseContent = event.data;
658
+ } else if (typeof event === 'string') {
659
+ // Direct string response from generateAIResponse actor
660
+ aiResponseContent = event;
661
+ } else {
662
+ console.error('🤖 Could not extract AI response content from event:', event);
663
+ aiResponseContent = 'Sorry, I encountered an error generating the response.';
664
+ }
665
+ } else if (typeof event === 'string') {
666
+ // Direct string response from generateAIResponse actor
667
+ aiResponseContent = event;
668
+ } else {
669
+ console.error('🤖 Could not extract AI response content from event:', event);
670
+ aiResponseContent = 'Sorry, I encountered an error generating the response.';
671
+ }
672
+ console.log('🤖 AI response content:', aiResponseContent.substring(0, 100) + '...');
673
+ const newMessage = {
674
+ id: (Date.now() + 1).toString(),
675
+ content: aiResponseContent,
676
+ sender: 'ai',
677
+ timestamp: new Date()
678
+ };
679
+ console.log('🤖 Adding AI message to context:', newMessage);
680
+ return {
681
+ ...context,
682
+ messages: [...context.messages, newMessage],
683
+ isTyping: false,
684
+ error: null,
685
+ messageToRespondTo: undefined // Clear the message to respond to after processing
686
+ };
687
+ }),
688
+ updateInput: assign(({
689
+ context,
690
+ event
691
+ }) => {
692
+ if (event.type !== 'INPUT_CHANGE') return context;
693
+ return {
694
+ ...context,
695
+ currentInput: event.value
696
+ };
697
+ }),
698
+ updateRegularMessages: assign(({
699
+ context,
700
+ event
701
+ }) => {
702
+ if (event.type !== 'UPDATE_REGULAR_MESSAGES') return context;
703
+ return {
704
+ ...context,
705
+ regularMessages: event.messages || []
706
+ };
707
+ }),
708
+ setMultiMessageMode: assign(({
709
+ context
710
+ }) => ({
711
+ ...context,
712
+ multiMessageMode: true,
713
+ currentMultiStep: 0
714
+ })),
715
+ setMultiMessagePlan: assign(({
716
+ context,
717
+ event
718
+ }) => {
719
+ const plan = event.output;
720
+ console.log('📝 Multi-message plan created:', plan.totalSteps, 'steps');
721
+ return {
722
+ ...context,
723
+ multiMessagePlan: plan.plan,
724
+ totalMultiSteps: plan.totalSteps
725
+ };
726
+ }),
727
+ incrementMultiStep: assign(({
728
+ context
729
+ }) => ({
730
+ ...context,
731
+ currentMultiStep: context.currentMultiStep + 1
732
+ })),
733
+ logContinueProcessing: () => {
734
+ console.log('🤖 Continue processing triggered - machine will stay in idle state');
735
+ },
736
+ resetMultiMessage: assign(({
737
+ context
738
+ }) => ({
739
+ ...context,
740
+ multiMessageMode: false,
741
+ currentMultiStep: 0,
742
+ totalMultiSteps: 0,
743
+ multiMessagePlan: [],
744
+ isTyping: false
745
+ })),
746
+ setTyping: assign(({
747
+ context
748
+ }) => ({
749
+ ...context,
750
+ isTyping: true
751
+ })),
752
+ setMCPData: assign(({
753
+ context,
754
+ event
755
+ }) => {
756
+ console.log('📊 MCP data fetched successfully');
757
+ return {
758
+ ...context,
759
+ mcpData: event.output
760
+ };
761
+ }),
762
+ setError: assign(({
763
+ context,
764
+ event
765
+ }) => {
766
+ console.error('❌ AI processing error:', event);
767
+ let errorMessage = 'An unexpected error occurred';
768
+ const error = event.error;
769
+ if (error instanceof Error) {
770
+ errorMessage = error.message;
771
+ } else if (typeof error === 'string') {
772
+ errorMessage = error;
773
+ }
774
+ if (errorMessage.includes('API key')) {
775
+ errorMessage = 'API key not configured. Please add your API key in Model Settings.';
776
+ } else if (errorMessage.includes('rate limit')) {
777
+ errorMessage = 'Rate limit exceeded. Please try again in a moment.';
778
+ } else if (errorMessage.includes('network') || errorMessage.includes('fetch')) {
779
+ errorMessage = 'Network error. Please check your connection and try again.';
780
+ }
781
+ return {
782
+ ...context,
783
+ error: errorMessage,
784
+ isTyping: false
785
+ };
786
+ }),
787
+ clearError: assign(({
788
+ context
789
+ }) => ({
790
+ ...context,
791
+ error: null
792
+ })),
793
+ addContextAnalysisMessage: assign(({
794
+ context
795
+ }) => {
796
+ const newMessage = {
797
+ id: (Date.now() + 2).toString(),
798
+ content: 'Please analyze the existing conversation and provide insights, continue the discussion, or ask relevant follow-up questions based on the context.',
799
+ sender: 'user',
800
+ timestamp: new Date()
801
+ };
802
+ return {
803
+ ...context,
804
+ messages: [...context.messages, newMessage],
805
+ currentInput: '',
806
+ error: null
807
+ };
808
+ }),
809
+ addAutoResponseMessage: assign(({
810
+ context,
811
+ event
812
+ }) => {
813
+ if (event.type !== 'AUTO_RESPOND_TO_MESSAGE') return context;
814
+ console.log('🤖 addAutoResponseMessage called with event:', event);
815
+ console.log('🤖 Current context before update:', {
816
+ messagesCount: context.messages.length,
817
+ hasMessageToRespondTo: !!context.messageToRespondTo,
818
+ messageToRespondTo: context.messageToRespondTo
819
+ });
820
+ // For auto-responses, we store the message content for AI processing
821
+ // but don't add it as a new user message to avoid duplicates
822
+ const updatedContext = {
823
+ ...context,
824
+ currentInput: '',
825
+ error: null,
826
+ mcpData: undefined,
827
+ // Store the message to respond to without adding it to messages array
828
+ messageToRespondTo: event.message
829
+ };
830
+ console.log('🤖 Context updated with messageToRespondTo:', event.message);
831
+ console.log('🤖 Updated context:', {
832
+ messagesCount: updatedContext.messages.length,
833
+ hasMessageToRespondTo: !!updatedContext.messageToRespondTo,
834
+ messageToRespondTo: updatedContext.messageToRespondTo
835
+ });
836
+ return updatedContext;
837
+ })
838
+ },
839
+ actors: {
840
+ generateMultiMessagePlan: fromPromise(async ({
841
+ input
842
+ }) => {
843
+ try {
844
+ console.log('📋 Generating multi-message plan for:', input.query);
845
+ // Check if we have an available AI provider
846
+ if (!API_CONFIG.availableProvider) {
847
+ throw new Error('No AI API key configured. Please set VITE_ANTHROPIC_API_KEY or VITE_OPENAI_API_KEY in your environment.');
848
+ }
849
+ console.log(`🤖 Using ${API_CONFIG.availableProvider} provider for multi-message planning`);
850
+ // Add conversation context if available
851
+ let systemPrompt = `You are a planning assistant. Break down complex queries into 3-5 independent messages that can be sent sequentially.
852
+
853
+ Each message should be a complete, standalone response that builds upon the previous ones.
854
+
855
+ Return ONLY a JSON object in this exact format:
856
+ {
857
+ "plan": ["First message topic/focus", "Second message topic/focus", "Third message topic/focus"],
858
+ "totalSteps": 3
859
+ }
860
+
861
+ Keep each step concise but descriptive. Make sure the breakdown makes sense for step-by-step explanations.`;
862
+ if (input.regularMessages && input.regularMessages.length > 0) {
863
+ const conversationContext = getConversationContext(input.regularMessages);
864
+ systemPrompt = `${systemPrompt}\n\n${conversationContext}`;
865
+ }
866
+ const response = await makeApiCall(API_CONFIG.primaryEndpoint, {
867
+ method: 'POST',
868
+ headers: {
869
+ 'Content-Type': 'application/json'
870
+ },
871
+ body: JSON.stringify({
872
+ model: API_CONFIG.primaryModel,
873
+ max_tokens: 500,
874
+ system: systemPrompt,
875
+ messages: [{
876
+ role: 'user',
877
+ content: `Please create a multi-message plan for this query: "${input.query}"`
878
+ }]
879
+ })
880
+ });
881
+ const data = await response.json();
882
+ const planText = data.content[0]?.text || '';
883
+ // Parse the JSON response
884
+ try {
885
+ const plan = JSON.parse(planText);
886
+ console.log('✅ Multi-message plan created:', plan);
887
+ return plan;
888
+ } catch {
889
+ // Fallback plan if parsing fails
890
+ return {
891
+ plan: ['Introduction and overview', 'Detailed explanation with examples', 'Summary and next steps'],
892
+ totalSteps: 3
893
+ };
894
+ }
895
+ } catch (error) {
896
+ console.error('🚨 Multi-message planning error:', error);
897
+ throw error;
898
+ }
899
+ }),
900
+ generateMultiMessage: fromPromise(async ({
901
+ input
902
+ }) => {
903
+ console.log(`🔄 Generating multi-message ${input.currentStep + 1}/${input.plan?.length || 1}`);
904
+ try {
905
+ // Check if we have an available AI provider
906
+ if (!API_CONFIG.availableProvider) {
907
+ throw new Error('No AI API key configured. Please set VITE_ANTHROPIC_API_KEY or VITE_OPENAI_API_KEY in your environment.');
908
+ }
909
+ console.log(`🤖 Using ${API_CONFIG.availableProvider} provider for multi-message generation`);
910
+ const userMessages = input.messages.filter(msg => msg.sender === 'user');
911
+ const latestUserMessage = userMessages[userMessages.length - 1];
912
+ if (!latestUserMessage) {
913
+ throw new Error('No user message found');
914
+ }
915
+ const currentStepTopic = input.plan?.[input.currentStep] || 'General response';
916
+ const stepNumber = input.currentStep + 1;
917
+ const totalSteps = input.plan?.length || 1;
918
+ let prompt = `User's original question: "${latestUserMessage.content}"
919
+
920
+ This is message ${stepNumber} of ${totalSteps} in a multi-message response.
921
+ Focus specifically on: ${currentStepTopic}
922
+
923
+ Guidelines:
924
+ - Start with a clear indicator like "**Step ${stepNumber}/${totalSteps}: ${currentStepTopic}**"
925
+ - Provide a complete, standalone response for this specific aspect
926
+ - Keep it focused and detailed but not overwhelming
927
+ - Use examples, code snippets, or bullet points where helpful
928
+ - End with a brief transition to what's coming next (unless it's the final message)`;
929
+ // Add conversation context if available
930
+ if (input.regularMessages && input.regularMessages.length > 0) {
931
+ const conversationContext = getConversationContext(input.regularMessages);
932
+ prompt = `${conversationContext}${prompt}`;
933
+ }
934
+ // Add MCP context if available
935
+ if (input.mcpData) {
936
+ const mcpContext = formatMCPDataForAgent(input.mcpData);
937
+ if (mcpContext) {
938
+ prompt = `${mcpContext}\n\n${prompt}`;
939
+ }
940
+ }
941
+ const response = await makeApiCall(API_CONFIG.primaryEndpoint, {
942
+ method: 'POST',
943
+ headers: {
944
+ 'Content-Type': 'application/json'
945
+ },
946
+ body: JSON.stringify({
947
+ model: API_CONFIG.primaryModel,
948
+ max_tokens: 800,
949
+ system: getSystemPrompt(API_CONFIG.availableProvider || 'anthropic', false),
950
+ messages: [...input.messages.slice(-5).map(msg => ({
951
+ role: msg.sender === 'user' ? 'user' : 'assistant',
952
+ content: msg.content
953
+ })), {
954
+ role: 'user',
955
+ content: prompt
956
+ }]
957
+ })
958
+ });
959
+ const data = await response.json();
960
+ return data.content[0]?.text || "Sorry, I couldn't generate a response for this step.";
961
+ } catch (error) {
962
+ console.error('🚨 Multi-message generation error:', error);
963
+ throw error;
964
+ }
965
+ }),
966
+ fetchMCPData: fromPromise(async ({
967
+ input
968
+ }) => {
969
+ try {
970
+ console.log('🌐 Fetching MCP data for query:', input.query);
971
+ const response = await performDirectMCPSearch(input.query, true, true);
972
+ console.log('✅ MCP data fetched:', response.summary);
973
+ return response;
974
+ } catch (error) {
975
+ console.error('🚨 MCP fetch error:', error);
976
+ throw error;
977
+ }
978
+ }),
979
+ generateAIResponse: fromPromise(async ({
980
+ input
981
+ }) => {
982
+ console.log('🤖 Generating response using server-side AI proxy');
983
+ console.log('🤖 Input received:', {
984
+ messagesCount: input.messages.length,
985
+ hasMCPData: !!input.mcpData,
986
+ regularMessagesCount: input.regularMessages?.length || 0,
987
+ messageToRespondTo: input.messageToRespondTo
988
+ });
989
+ try {
990
+ // Check if we have an available AI provider
991
+ if (!API_CONFIG.availableProvider) {
992
+ throw new Error('No AI API key configured. Please set VITE_ANTHROPIC_API_KEY or VITE_OPENAI_API_KEY in your environment.');
993
+ }
994
+ console.log(`🤖 Using ${API_CONFIG.availableProvider} provider for AI response generation`);
995
+ // Get the latest user message or the message to respond to
996
+ let prompt;
997
+ let userMessages = input.messages.filter(msg => msg.sender === 'user');
998
+ if (input.messageToRespondTo) {
999
+ // Use the message to respond to for auto-responses
1000
+ prompt = input.messageToRespondTo;
1001
+ console.log('🤖 Auto-responding to message:', prompt.substring(0, 50) + '...');
1002
+ } else if (userMessages.length > 0) {
1003
+ const latestUserMessage = userMessages[userMessages.length - 1];
1004
+ prompt = latestUserMessage.content;
1005
+ } else {
1006
+ // If no user messages, this might be an auto-response
1007
+ prompt = 'Please provide a helpful response to the conversation context.';
1008
+ }
1009
+ // Add conversation context if available
1010
+ if (input.regularMessages && input.regularMessages.length > 0) {
1011
+ const conversationContext = getConversationContext(input.regularMessages);
1012
+ prompt = `${conversationContext}User question: ${prompt}`;
1013
+ console.log('🚀 Enhanced prompt with conversation context - Recent messages:', input.regularMessages.length);
1014
+ }
1015
+ // Add MCP context if available
1016
+ if (input.mcpData) {
1017
+ const mcpContext = formatMCPDataForAgent(input.mcpData);
1018
+ if (mcpContext) {
1019
+ prompt = `${mcpContext}\n\nUser question: ${prompt}`;
1020
+ console.log('🚀 Enhanced prompt with MCP data - Web results:', input.mcpData.searchResults?.length || 0, 'News articles:', input.mcpData.newsArticles?.length || 0);
1021
+ }
1022
+ }
1023
+ // Use Vite proxy for AI API calls (avoids CORS issues)
1024
+ const controller = new AbortController();
1025
+ const timeoutId = setTimeout(() => controller.abort(), 15000); // Increased to 15s timeout for better reliability
1026
+ try {
1027
+ const response = await makeApiCall(API_CONFIG.primaryEndpoint, {
1028
+ method: 'POST',
1029
+ headers: {
1030
+ 'Content-Type': 'application/json'
1031
+ },
1032
+ body: JSON.stringify({
1033
+ model: API_CONFIG.primaryModel,
1034
+ max_tokens: 300,
1035
+ // Further reduced for faster responses
1036
+ system: getSystemPrompt(API_CONFIG.availableProvider || 'anthropic', true),
1037
+ messages: [
1038
+ // Only include the last 2 messages for faster processing
1039
+ ...input.messages.slice(-2).map(msg => ({
1040
+ role: msg.sender === 'user' ? 'user' : 'assistant',
1041
+ content: msg.content
1042
+ })), {
1043
+ role: 'user',
1044
+ content: prompt
1045
+ }]
1046
+ }),
1047
+ signal: controller.signal
1048
+ });
1049
+ clearTimeout(timeoutId);
1050
+ const data = await response.json();
1051
+ console.log('🤖 AI API response received:', data);
1052
+ const aiResponseText = data.content[0]?.text || data.choices?.[0]?.message?.content || "Sorry, I couldn't generate a response.";
1053
+ console.log('🤖 Extracted AI response text:', aiResponseText.substring(0, 100) + '...');
1054
+ console.log('🤖 ✅ generateAIResponse actor completing successfully with text length:', aiResponseText.length);
1055
+ return aiResponseText;
1056
+ } catch (error) {
1057
+ clearTimeout(timeoutId);
1058
+ if (error.name === 'AbortError') {
1059
+ throw new Error('AI response generation timed out. Please try again.');
1060
+ }
1061
+ throw error;
1062
+ }
1063
+ } catch (error) {
1064
+ console.error('🚨 AI generation error:', error);
1065
+ if (error instanceof Error) {
1066
+ if (error.message.includes('API key')) {
1067
+ throw new Error('AI API key is not configured. Please set your API keys in the environment variables.');
1068
+ }
1069
+ if (error.message.includes('rate limit')) {
1070
+ throw new Error('Rate limit exceeded. Please try again in a moment.');
1071
+ }
1072
+ if (error.message.includes('network') || error.message.includes('fetch')) {
1073
+ throw new Error('Network error. Please check your connection and ensure your Vite dev server is running on localhost:3011.');
1074
+ }
1075
+ throw error; // Re-throw the Error instance
1076
+ }
1077
+ // If error is not an Error instance, create a proper Error with string message
1078
+ const errorMessage = typeof error === 'string' ? error : error && typeof error === 'object' && 'message' in error ? String(error.message) : 'An unexpected error occurred while generating the response';
1079
+ throw new Error(errorMessage);
1080
+ }
1081
+ })
1082
+ }
1083
+ });export{aiAgentMachine};//# sourceMappingURL=aiAgentMachine.js.map