@buoy-gg/ask-buoy 7.0.38 → 7.0.40

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 (306) hide show
  1. package/lib/commonjs/blocks/AskBlocks.js +338 -1
  2. package/lib/commonjs/blocks/AskBlocks.js.map +1 -0
  3. package/lib/commonjs/blocks/BlockRenderer.js +262 -1
  4. package/lib/commonjs/blocks/BlockRenderer.js.map +1 -0
  5. package/lib/commonjs/blocks/ChromePrototypes.js +514 -1
  6. package/lib/commonjs/blocks/ChromePrototypes.js.map +1 -0
  7. package/lib/commonjs/blocks/DataBlocks.js +781 -1
  8. package/lib/commonjs/blocks/DataBlocks.js.map +1 -0
  9. package/lib/commonjs/blocks/ExtraBlocks.js +1860 -1
  10. package/lib/commonjs/blocks/ExtraBlocks.js.map +1 -0
  11. package/lib/commonjs/blocks/MediaBlocks.js +156 -1
  12. package/lib/commonjs/blocks/MediaBlocks.js.map +1 -0
  13. package/lib/commonjs/blocks/ReceiptBlocks.js +586 -1
  14. package/lib/commonjs/blocks/ReceiptBlocks.js.map +1 -0
  15. package/lib/commonjs/blocks/blockText.js +60 -1
  16. package/lib/commonjs/blocks/blockText.js.map +1 -0
  17. package/lib/commonjs/blocks/blockText.test.js +53 -1
  18. package/lib/commonjs/blocks/blockText.test.js.map +1 -0
  19. package/lib/commonjs/blocks/context.js +42 -1
  20. package/lib/commonjs/blocks/context.js.map +1 -0
  21. package/lib/commonjs/blocks/icons.js +96 -1
  22. package/lib/commonjs/blocks/icons.js.map +1 -0
  23. package/lib/commonjs/blocks/index.js +95 -1
  24. package/lib/commonjs/blocks/index.js.map +1 -0
  25. package/lib/commonjs/blocks/listRow.test.js +55 -1
  26. package/lib/commonjs/blocks/listRow.test.js.map +1 -0
  27. package/lib/commonjs/blocks/pageState.js +34 -1
  28. package/lib/commonjs/blocks/pageState.js.map +1 -0
  29. package/lib/commonjs/blocks/pageState.test.js +57 -1
  30. package/lib/commonjs/blocks/pageState.test.js.map +1 -0
  31. package/lib/commonjs/blocks/primitives.js +457 -1
  32. package/lib/commonjs/blocks/primitives.js.map +1 -0
  33. package/lib/commonjs/blocks/primitivesIndex.js +62 -1
  34. package/lib/commonjs/blocks/primitivesIndex.js.map +1 -0
  35. package/lib/commonjs/components/ApprovalCard.js +297 -1
  36. package/lib/commonjs/components/ApprovalCard.js.map +1 -0
  37. package/lib/commonjs/components/AskBuoyHeader.js +196 -1
  38. package/lib/commonjs/components/AskBuoyHeader.js.map +1 -0
  39. package/lib/commonjs/components/AskBuoyIcon.js +19 -1
  40. package/lib/commonjs/components/AskBuoyIcon.js.map +1 -0
  41. package/lib/commonjs/components/AskBuoyModal.js +479 -1
  42. package/lib/commonjs/components/AskBuoyModal.js.map +1 -0
  43. package/lib/commonjs/components/AskBuoySettings.js +181 -1
  44. package/lib/commonjs/components/AskBuoySettings.js.map +1 -0
  45. package/lib/commonjs/components/ChangesBar.js +211 -1
  46. package/lib/commonjs/components/ChangesBar.js.map +1 -0
  47. package/lib/commonjs/components/Composer.js +255 -1
  48. package/lib/commonjs/components/Composer.js.map +1 -0
  49. package/lib/commonjs/components/EmptyState.js +161 -1
  50. package/lib/commonjs/components/EmptyState.js.map +1 -0
  51. package/lib/commonjs/components/KeyboardPad.js +80 -1
  52. package/lib/commonjs/components/KeyboardPad.js.map +1 -0
  53. package/lib/commonjs/components/Markdown.js +310 -1
  54. package/lib/commonjs/components/Markdown.js.map +1 -0
  55. package/lib/commonjs/components/MessageList.js +970 -1
  56. package/lib/commonjs/components/MessageList.js.map +1 -0
  57. package/lib/commonjs/components/QueuedMessages.js +145 -1
  58. package/lib/commonjs/components/QueuedMessages.js.map +1 -0
  59. package/lib/commonjs/components/ThinkingStrip.js +223 -1
  60. package/lib/commonjs/components/ThinkingStrip.js.map +1 -0
  61. package/lib/commonjs/components/TypingDots.js +63 -1
  62. package/lib/commonjs/components/TypingDots.js.map +1 -0
  63. package/lib/commonjs/components/markdownParse.js +131 -1
  64. package/lib/commonjs/components/markdownParse.js.map +1 -0
  65. package/lib/commonjs/components/markdownParse.test.js +99 -1
  66. package/lib/commonjs/components/markdownParse.test.js.map +1 -0
  67. package/lib/commonjs/components/useCopyAction.js +50 -1
  68. package/lib/commonjs/components/useCopyAction.js.map +1 -0
  69. package/lib/commonjs/index.js +252 -1
  70. package/lib/commonjs/index.js.map +1 -0
  71. package/lib/commonjs/preset.js +91 -1
  72. package/lib/commonjs/preset.js.map +1 -0
  73. package/lib/commonjs/store/activityGroups.js +110 -1
  74. package/lib/commonjs/store/activityGroups.js.map +1 -0
  75. package/lib/commonjs/store/activityGroups.test.js +78 -1
  76. package/lib/commonjs/store/activityGroups.test.js.map +1 -0
  77. package/lib/commonjs/store/askBuoySettings.js +72 -1
  78. package/lib/commonjs/store/askBuoySettings.js.map +1 -0
  79. package/lib/commonjs/store/askBuoyStore.js +589 -1
  80. package/lib/commonjs/store/askBuoyStore.js.map +1 -0
  81. package/lib/commonjs/store/blockPlacement.js +64 -1
  82. package/lib/commonjs/store/blockPlacement.js.map +1 -0
  83. package/lib/commonjs/store/blockPlacement.test.js +123 -1
  84. package/lib/commonjs/store/blockPlacement.test.js.map +1 -0
  85. package/lib/commonjs/store/queue.test.js +150 -1
  86. package/lib/commonjs/store/queue.test.js.map +1 -0
  87. package/lib/commonjs/store/resetConversation.js +77 -1
  88. package/lib/commonjs/store/resetConversation.js.map +1 -0
  89. package/lib/commonjs/store/restorePending.test.js +63 -1
  90. package/lib/commonjs/store/restorePending.test.js.map +1 -0
  91. package/lib/commonjs/store/restoredIds.test.js +47 -1
  92. package/lib/commonjs/store/restoredIds.test.js.map +1 -0
  93. package/lib/commonjs/store/suggestions.js +54 -1
  94. package/lib/commonjs/store/suggestions.js.map +1 -0
  95. package/lib/commonjs/store/suggestions.test.js +58 -1
  96. package/lib/commonjs/store/suggestions.test.js.map +1 -0
  97. package/lib/commonjs/store/systemLine.test.js +77 -1
  98. package/lib/commonjs/store/systemLine.test.js.map +1 -0
  99. package/lib/commonjs/store/ticketPrompt.js +17 -1
  100. package/lib/commonjs/store/ticketPrompt.js.map +1 -0
  101. package/lib/commonjs/store/traceText.js +81 -1
  102. package/lib/commonjs/store/traceText.js.map +1 -0
  103. package/lib/commonjs/store/traceText.test.js +112 -1
  104. package/lib/commonjs/store/traceText.test.js.map +1 -0
  105. package/lib/commonjs/store/transcriptPersistence.js +297 -1
  106. package/lib/commonjs/store/transcriptPersistence.js.map +1 -0
  107. package/lib/commonjs/store/transcriptPersistence.test.js +333 -1
  108. package/lib/commonjs/store/transcriptPersistence.test.js.map +1 -0
  109. package/lib/commonjs/store/turnRendering.test.js +151 -1
  110. package/lib/commonjs/store/turnRendering.test.js.map +1 -0
  111. package/lib/commonjs/store/useAskBuoy.js +651 -1
  112. package/lib/commonjs/store/useAskBuoy.js.map +1 -0
  113. package/lib/commonjs/store/useAskBuoySettings.js +14 -1
  114. package/lib/commonjs/store/useAskBuoySettings.js.map +1 -0
  115. package/lib/commonjs/sync/askBuoySyncAdapter.js +153 -1
  116. package/lib/commonjs/sync/askBuoySyncAdapter.js.map +1 -0
  117. package/lib/commonjs/sync/askBuoySyncAdapter.test.js +141 -1
  118. package/lib/commonjs/sync/askBuoySyncAdapter.test.js.map +1 -0
  119. package/lib/commonjs/sync/wire.js +58 -1
  120. package/lib/commonjs/sync/wire.js.map +1 -0
  121. package/lib/commonjs/types.js +6 -1
  122. package/lib/commonjs/types.js.map +1 -0
  123. package/lib/module/blocks/AskBlocks.js +331 -1
  124. package/lib/module/blocks/AskBlocks.js.map +1 -0
  125. package/lib/module/blocks/BlockRenderer.js +257 -1
  126. package/lib/module/blocks/BlockRenderer.js.map +1 -0
  127. package/lib/module/blocks/ChromePrototypes.js +503 -1
  128. package/lib/module/blocks/ChromePrototypes.js.map +1 -0
  129. package/lib/module/blocks/DataBlocks.js +767 -1
  130. package/lib/module/blocks/DataBlocks.js.map +1 -0
  131. package/lib/module/blocks/ExtraBlocks.js +1833 -1
  132. package/lib/module/blocks/ExtraBlocks.js.map +1 -0
  133. package/lib/module/blocks/MediaBlocks.js +151 -1
  134. package/lib/module/blocks/MediaBlocks.js.map +1 -0
  135. package/lib/module/blocks/ReceiptBlocks.js +574 -1
  136. package/lib/module/blocks/ReceiptBlocks.js.map +1 -0
  137. package/lib/module/blocks/blockText.js +55 -1
  138. package/lib/module/blocks/blockText.js.map +1 -0
  139. package/lib/module/blocks/blockText.test.js +53 -1
  140. package/lib/module/blocks/blockText.test.js.map +1 -0
  141. package/lib/module/blocks/context.js +35 -1
  142. package/lib/module/blocks/context.js.map +1 -0
  143. package/lib/module/blocks/icons.js +91 -1
  144. package/lib/module/blocks/icons.js.map +1 -0
  145. package/lib/module/blocks/index.js +8 -1
  146. package/lib/module/blocks/index.js.map +1 -0
  147. package/lib/module/blocks/listRow.test.js +56 -1
  148. package/lib/module/blocks/listRow.test.js.map +1 -0
  149. package/lib/module/blocks/pageState.js +30 -1
  150. package/lib/module/blocks/pageState.js.map +1 -0
  151. package/lib/module/blocks/pageState.test.js +56 -1
  152. package/lib/module/blocks/pageState.test.js.map +1 -0
  153. package/lib/module/blocks/primitives.js +445 -1
  154. package/lib/module/blocks/primitives.js.map +1 -0
  155. package/lib/module/blocks/primitivesIndex.js +5 -1
  156. package/lib/module/blocks/primitivesIndex.js.map +1 -0
  157. package/lib/module/components/ApprovalCard.js +292 -1
  158. package/lib/module/components/ApprovalCard.js.map +1 -0
  159. package/lib/module/components/AskBuoyHeader.js +193 -1
  160. package/lib/module/components/AskBuoyHeader.js.map +1 -0
  161. package/lib/module/components/AskBuoyIcon.js +8 -1
  162. package/lib/module/components/AskBuoyIcon.js.map +1 -0
  163. package/lib/module/components/AskBuoyModal.js +474 -1
  164. package/lib/module/components/AskBuoyModal.js.map +1 -0
  165. package/lib/module/components/AskBuoySettings.js +176 -1
  166. package/lib/module/components/AskBuoySettings.js.map +1 -0
  167. package/lib/module/components/ChangesBar.js +206 -1
  168. package/lib/module/components/ChangesBar.js.map +1 -0
  169. package/lib/module/components/Composer.js +250 -1
  170. package/lib/module/components/Composer.js.map +1 -0
  171. package/lib/module/components/EmptyState.js +156 -1
  172. package/lib/module/components/EmptyState.js.map +1 -0
  173. package/lib/module/components/KeyboardPad.js +75 -1
  174. package/lib/module/components/KeyboardPad.js.map +1 -0
  175. package/lib/module/components/Markdown.js +305 -1
  176. package/lib/module/components/Markdown.js.map +1 -0
  177. package/lib/module/components/MessageList.js +964 -1
  178. package/lib/module/components/MessageList.js.map +1 -0
  179. package/lib/module/components/QueuedMessages.js +140 -1
  180. package/lib/module/components/QueuedMessages.js.map +1 -0
  181. package/lib/module/components/ThinkingStrip.js +218 -1
  182. package/lib/module/components/ThinkingStrip.js.map +1 -0
  183. package/lib/module/components/TypingDots.js +58 -1
  184. package/lib/module/components/TypingDots.js.map +1 -0
  185. package/lib/module/components/markdownParse.js +125 -1
  186. package/lib/module/components/markdownParse.js.map +1 -0
  187. package/lib/module/components/markdownParse.test.js +98 -1
  188. package/lib/module/components/markdownParse.test.js.map +1 -0
  189. package/lib/module/components/useCopyAction.js +46 -1
  190. package/lib/module/components/useCopyAction.js.map +1 -0
  191. package/lib/module/index.js +34 -1
  192. package/lib/module/index.js.map +1 -0
  193. package/lib/module/preset.js +74 -1
  194. package/lib/module/preset.js.map +1 -0
  195. package/lib/module/store/activityGroups.js +103 -1
  196. package/lib/module/store/activityGroups.js.map +1 -0
  197. package/lib/module/store/activityGroups.test.js +77 -1
  198. package/lib/module/store/activityGroups.test.js.map +1 -0
  199. package/lib/module/store/askBuoySettings.js +67 -1
  200. package/lib/module/store/askBuoySettings.js.map +1 -0
  201. package/lib/module/store/askBuoyStore.js +583 -1
  202. package/lib/module/store/askBuoyStore.js.map +1 -0
  203. package/lib/module/store/blockPlacement.js +59 -1
  204. package/lib/module/store/blockPlacement.js.map +1 -0
  205. package/lib/module/store/blockPlacement.test.js +122 -1
  206. package/lib/module/store/blockPlacement.test.js.map +1 -0
  207. package/lib/module/store/queue.test.js +149 -1
  208. package/lib/module/store/queue.test.js.map +1 -0
  209. package/lib/module/store/resetConversation.js +72 -1
  210. package/lib/module/store/resetConversation.js.map +1 -0
  211. package/lib/module/store/restorePending.test.js +62 -1
  212. package/lib/module/store/restorePending.test.js.map +1 -0
  213. package/lib/module/store/restoredIds.test.js +46 -1
  214. package/lib/module/store/restoredIds.test.js.map +1 -0
  215. package/lib/module/store/suggestions.js +49 -1
  216. package/lib/module/store/suggestions.js.map +1 -0
  217. package/lib/module/store/suggestions.test.js +57 -1
  218. package/lib/module/store/suggestions.test.js.map +1 -0
  219. package/lib/module/store/systemLine.test.js +76 -1
  220. package/lib/module/store/systemLine.test.js.map +1 -0
  221. package/lib/module/store/ticketPrompt.js +13 -1
  222. package/lib/module/store/ticketPrompt.js.map +1 -0
  223. package/lib/module/store/traceText.js +75 -1
  224. package/lib/module/store/traceText.js.map +1 -0
  225. package/lib/module/store/traceText.test.js +111 -1
  226. package/lib/module/store/traceText.test.js.map +1 -0
  227. package/lib/module/store/transcriptPersistence.js +287 -1
  228. package/lib/module/store/transcriptPersistence.js.map +1 -0
  229. package/lib/module/store/transcriptPersistence.test.js +332 -1
  230. package/lib/module/store/transcriptPersistence.test.js.map +1 -0
  231. package/lib/module/store/turnRendering.test.js +150 -1
  232. package/lib/module/store/turnRendering.test.js.map +1 -0
  233. package/lib/module/store/useAskBuoy.js +646 -1
  234. package/lib/module/store/useAskBuoy.js.map +1 -0
  235. package/lib/module/store/useAskBuoySettings.js +9 -1
  236. package/lib/module/store/useAskBuoySettings.js.map +1 -0
  237. package/lib/module/sync/askBuoySyncAdapter.js +148 -1
  238. package/lib/module/sync/askBuoySyncAdapter.js.map +1 -0
  239. package/lib/module/sync/askBuoySyncAdapter.test.js +140 -1
  240. package/lib/module/sync/askBuoySyncAdapter.test.js.map +1 -0
  241. package/lib/module/sync/wire.js +47 -1
  242. package/lib/module/sync/wire.js.map +1 -0
  243. package/lib/module/types.js +4 -1
  244. package/lib/module/types.js.map +1 -0
  245. package/lib/typescript/blocks/AskBlocks.d.ts.map +1 -0
  246. package/lib/typescript/blocks/BlockRenderer.d.ts.map +1 -0
  247. package/lib/typescript/blocks/ChromePrototypes.d.ts.map +1 -0
  248. package/lib/typescript/blocks/DataBlocks.d.ts.map +1 -0
  249. package/lib/typescript/blocks/ExtraBlocks.d.ts.map +1 -0
  250. package/lib/typescript/blocks/MediaBlocks.d.ts.map +1 -0
  251. package/lib/typescript/blocks/ReceiptBlocks.d.ts.map +1 -0
  252. package/lib/typescript/blocks/blockText.d.ts.map +1 -0
  253. package/lib/typescript/blocks/blockText.test.d.ts.map +1 -0
  254. package/lib/typescript/blocks/context.d.ts.map +1 -0
  255. package/lib/typescript/blocks/icons.d.ts.map +1 -0
  256. package/lib/typescript/blocks/index.d.ts.map +1 -0
  257. package/lib/typescript/blocks/listRow.test.d.ts.map +1 -0
  258. package/lib/typescript/blocks/pageState.d.ts.map +1 -0
  259. package/lib/typescript/blocks/pageState.test.d.ts.map +1 -0
  260. package/lib/typescript/blocks/primitives.d.ts.map +1 -0
  261. package/lib/typescript/blocks/primitivesIndex.d.ts.map +1 -0
  262. package/lib/typescript/components/ApprovalCard.d.ts.map +1 -0
  263. package/lib/typescript/components/AskBuoyHeader.d.ts.map +1 -0
  264. package/lib/typescript/components/AskBuoyIcon.d.ts.map +1 -0
  265. package/lib/typescript/components/AskBuoyModal.d.ts.map +1 -0
  266. package/lib/typescript/components/AskBuoySettings.d.ts.map +1 -0
  267. package/lib/typescript/components/ChangesBar.d.ts.map +1 -0
  268. package/lib/typescript/components/Composer.d.ts.map +1 -0
  269. package/lib/typescript/components/EmptyState.d.ts.map +1 -0
  270. package/lib/typescript/components/KeyboardPad.d.ts.map +1 -0
  271. package/lib/typescript/components/Markdown.d.ts.map +1 -0
  272. package/lib/typescript/components/MessageList.d.ts.map +1 -0
  273. package/lib/typescript/components/QueuedMessages.d.ts.map +1 -0
  274. package/lib/typescript/components/ThinkingStrip.d.ts.map +1 -0
  275. package/lib/typescript/components/TypingDots.d.ts.map +1 -0
  276. package/lib/typescript/components/markdownParse.d.ts.map +1 -0
  277. package/lib/typescript/components/markdownParse.test.d.ts.map +1 -0
  278. package/lib/typescript/components/useCopyAction.d.ts.map +1 -0
  279. package/lib/typescript/index.d.ts.map +1 -0
  280. package/lib/typescript/preset.d.ts.map +1 -0
  281. package/lib/typescript/store/activityGroups.d.ts.map +1 -0
  282. package/lib/typescript/store/activityGroups.test.d.ts.map +1 -0
  283. package/lib/typescript/store/askBuoySettings.d.ts.map +1 -0
  284. package/lib/typescript/store/askBuoyStore.d.ts.map +1 -0
  285. package/lib/typescript/store/blockPlacement.d.ts.map +1 -0
  286. package/lib/typescript/store/blockPlacement.test.d.ts.map +1 -0
  287. package/lib/typescript/store/queue.test.d.ts.map +1 -0
  288. package/lib/typescript/store/resetConversation.d.ts.map +1 -0
  289. package/lib/typescript/store/restorePending.test.d.ts.map +1 -0
  290. package/lib/typescript/store/restoredIds.test.d.ts.map +1 -0
  291. package/lib/typescript/store/suggestions.d.ts.map +1 -0
  292. package/lib/typescript/store/suggestions.test.d.ts.map +1 -0
  293. package/lib/typescript/store/systemLine.test.d.ts.map +1 -0
  294. package/lib/typescript/store/ticketPrompt.d.ts.map +1 -0
  295. package/lib/typescript/store/traceText.d.ts.map +1 -0
  296. package/lib/typescript/store/traceText.test.d.ts.map +1 -0
  297. package/lib/typescript/store/transcriptPersistence.d.ts.map +1 -0
  298. package/lib/typescript/store/transcriptPersistence.test.d.ts.map +1 -0
  299. package/lib/typescript/store/turnRendering.test.d.ts.map +1 -0
  300. package/lib/typescript/store/useAskBuoy.d.ts.map +1 -0
  301. package/lib/typescript/store/useAskBuoySettings.d.ts.map +1 -0
  302. package/lib/typescript/sync/askBuoySyncAdapter.d.ts.map +1 -0
  303. package/lib/typescript/sync/askBuoySyncAdapter.test.d.ts.map +1 -0
  304. package/lib/typescript/sync/wire.d.ts.map +1 -0
  305. package/lib/typescript/types.d.ts.map +1 -0
  306. package/package.json +8 -8
@@ -1 +1,651 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.useAskBuoy=useAskBuoy,exports.useAskBuoyState=useAskBuoyState;var _sharedUi=require("@buoy-gg/shared-ui"),_react=require("react"),_reactNative=require("react-native"),_agentCore=require("@buoy-gg/agent-core"),_askBuoyStore=require("./askBuoyStore"),_resetConversation=require("./resetConversation"),_transcriptPersistence=require("./transcriptPersistence"),_useAskBuoySettings=require("./useAskBuoySettings");const isRelease="undefined"!=typeof __DEV__&&!__DEV__;function questionBehind(e){for(const t of _askBuoyStore.askBuoyStore.getState().messages)if(t.restored)for(const o of t.blocks){const t=o.block;if(t?.id!==e)continue;const s=t.question??t.label??t.title;return"string"==typeof s&&s.trim()?s.trim():void 0}}function readAvailableActions(){try{const e=(0,_sharedUi.listToolActions)();for(const t of(0,_sharedUi.listSnapshotToolIds)())e[t]||(e[t]=[]),e[t].includes(_agentCore.SNAPSHOT_ACTION)||(e[t]=[_agentCore.SNAPSHOT_ACTION,...e[t]]);return e}catch{return{}}}const SAVE_DEBOUNCE_MS=600;function useAskBuoyState(){return(0,_react.useSyncExternalStore)(_askBuoyStore.askBuoyStore.subscribe,_askBuoyStore.askBuoyStore.getState,_askBuoyStore.askBuoyStore.getState)}function useAskBuoy(e){const t=useAskBuoyState(),o=(0,_sharedUi.getUseIsPro)()(),s=(0,_react.useRef)(o);s.current=o;const r=(0,_react.useCallback)((...e)=>(0,_sharedUi.hasAccountAccess)()&&s.current?(0,_sharedUi.dispatchToolAction)(...e):Promise.reject(new Error("Ask Buoy requires Pro access.")),[]),a=(0,_react.useRef)(null),n=(0,_react.useRef)(!1),u=(0,_react.useRef)(null),i=(0,_react.useRef)(e);i.current=e;const c=!!e?.endpoint&&!!e?.model,l=!1!==e?.persistTranscript,{bypassApprovals:d,readOnly:y}=(0,_useAskBuoySettings.useAskBuoySettings)(),k=(0,_react.useRef)(d);k.current=d;const p=(0,_react.useRef)(y);p.current=y;const S=(0,_react.useCallback)(()=>p.current?{...e?.policy??{},readOnly:!0}:e?.policy??{},[e]),[_,B]=(0,_react.useState)(0);(0,_react.useEffect)(()=>{let e=!1;return(0,_sharedUi.waitForToolRegistry)().then(()=>{e||B(e=>e+1)}),()=>{e=!0}},[]);const g=(0,_react.useMemo)(()=>readAvailableActions(),[_]),h=Object.keys(g).sort().join(",");(0,_react.useEffect)(()=>{if(_askBuoyStore.askBuoyStore.setConfigured(c),_askBuoyStore.askBuoyStore.setMeta({model:e?.model,protocol:e?.protocol??(e?"anthropic":void 0),appName:e?.appName,platform:_reactNative.Platform.OS,build:isRelease?"release":"development"}),!c||!e)return a.current=null,void _askBuoyStore.askBuoyStore.setNotice("Ask Buoy isn't set up in this app yet. A developer needs to point it at your team's AI endpoint.");const t=e.protocol??"anthropic";isRelease&&e.apiKey?_askBuoyStore.askBuoyStore.setNotice("This build carries a plaintext apiKey — that's dev-only and it ships to every install. Use the headers callback with your own gateway for distributed builds."):"anthropic"===t&&/^https?:\/\/api\.openai\.com\//i.test(e.endpoint)?_askBuoyStore.askBuoyStore.setNotice('This endpoint is api.openai.com but the protocol is "anthropic". Set protocol: "openai" in the askBuoy config.'):"openai"===t&&/^https?:\/\/api\.anthropic\.com\//i.test(e.endpoint)?_askBuoyStore.askBuoyStore.setNotice('This endpoint is api.anthropic.com but the protocol is "openai". Remove protocol or set it to "anthropic".'):_askBuoyStore.askBuoyStore.setNotice(null);const o=[e.endpoint,e.protocol??"anthropic",e.model].join("|"),s=_askBuoyStore.askBuoyStore.getHeldSession();if(s&&s.signature===o)return a.current=s.session,s.session.setAvailableActions(g),s.session.setApprovalBypass(k.current),s.session.setReadOnly(p.current),void _askBuoyStore.askBuoyStore.setLedger(s.session.ledger);const u=(0,_agentCore.createAskBuoySession)({endpoint:e.endpoint,protocol:e.protocol??"anthropic",model:e.model,headers:e.headers,apiKey:e.apiKey,maxTokens:e.maxTokens,anthropicVersion:e.anthropicVersion,requestOverrides:e.requestOverrides,catalog:e.tools?.length?[..._agentCore.CATALOG,...e.tools]:void 0,dispatch:r,readSnapshot:_sharedUi.readToolSnapshot,availableActions:g,policy:e.policy,context:e.context,isRelease:isRelease,appName:e.appName,platform:_reactNative.Platform.OS,requestApproval:e=>_askBuoyStore.askBuoyStore.askApproval(e)});a.current=u,u.setApprovalBypass(k.current),u.setReadOnly(p.current),_askBuoyStore.askBuoyStore.holdSession(u,o),_askBuoyStore.askBuoyStore.setLedger(u.ledger);let i=!1;return(0,_sharedUi.waitForToolRegistry)().then(e=>{e&&!i&&u.prime()}),l&&!n.current&&(n.current=!0,(0,_transcriptPersistence.readTranscript)().then(e=>{e&&_askBuoyStore.askBuoyStore.hydrate({messages:e.messages,answers:e.answers,usage:e.usage,queued:e.queued})&&(a.current?.restore(e.history),e.ledger?.length&&a.current?.ledger.restore(e.ledger),e.pending&&_askBuoyStore.askBuoyStore.restorePending(e.pending))})),()=>{i=!0}},[c,e,g,h,l]),(0,_react.useEffect)(()=>{a.current?.setApprovalBypass(d)},[d]),(0,_react.useEffect)(()=>{a.current?.setReadOnly(y)},[y]);const f=t.messages,A=t.answers,b=t.usage,v=t.busy,m=t.pending,C=t.queued;(0,_react.useEffect)(()=>{if(!l)return;if(0===f.length)return;const e=()=>{(0,_transcriptPersistence.writeTranscript)((0,_transcriptPersistence.buildPayload)({messages:f,history:a.current?.messages??[],answers:A,usage:b,pending:m,ledger:_askBuoyStore.askBuoyStore.getLedger()?.list(),queued:C}))};if(!v)return void e();const t=setTimeout(e,SAVE_DEBOUNCE_MS);return()=>clearTimeout(t)},[l,v,f,A,b,m,C]);const w=(0,_react.useCallback)(e=>{if(!(0,_sharedUi.hasAccountAccess)()||!s.current)return;const t=a.current;if(!t)return;_askBuoyStore.askBuoyStore.beginTurn();const o=_askBuoyStore.askBuoyStore.startAssistant(),r=new AbortController;u.current=r,t.setAvailableActions(readAvailableActions());const n=i.current?.onEvent;(async()=>{try{for await(const s of t.send(e,r.signal))if(_askBuoyStore.askBuoyStore.applyEvent(o,s),n)try{n(s)}catch{}}catch(e){r.signal.aborted||_askBuoyStore.askBuoyStore.applyEvent(o,{type:"error",message:e instanceof Error?e.message:"Something went wrong talking to your AI endpoint."})}finally{r.signal.aborted&&_askBuoyStore.askBuoyStore.markStopped(o),_askBuoyStore.askBuoyStore.finishAssistant(o),u.current=null}})()},[]),T=(0,_react.useCallback)(e=>{if(!(0,_sharedUi.hasAccountAccess)()||!s.current)return;const t=e.trim();if(!a.current||!t)return;if(_askBuoyStore.askBuoyStore.getState().busy)return void _askBuoyStore.askBuoyStore.enqueue(t);const o=_askBuoyStore.askBuoyStore.getState().awaitingBlockId;o&&_askBuoyStore.askBuoyStore.recordAnswer({blockId:o,kind:"skipped"}),_askBuoyStore.askBuoyStore.addUser(t),w(t)},[w]),N=(0,_react.useCallback)(()=>{const{messages:e,busy:t}=_askBuoyStore.askBuoyStore.getState();if(t||!a.current)return;const o=[...e].reverse().find(e=>"user"===e.role);o&&w(o.text)},[w]),q=(0,_react.useCallback)(()=>{_askBuoyStore.askBuoyStore.requestStop(),_askBuoyStore.askBuoyStore.getState().pending&&_askBuoyStore.askBuoyStore.answerApproval(!1),u.current?.abort(),u.current=null},[]);(0,_react.useEffect)(()=>{const e=(0,_sharedUi.subscribeAccountAccess)(()=>{(0,_sharedUi.hasAccountAccess)()||q()});return()=>{e(),q()}},[q]),(0,_react.useEffect)(()=>{o||q()},[o,q]),(0,_react.useEffect)(()=>{if(0===t.queued.length)return;if("idle"!==(0,_askBuoyStore.turnPhaseOf)(t))return;if(null!==(0,_askBuoyStore.queuePauseReason)(t))return;const e=_askBuoyStore.askBuoyStore.shiftQueued();e&&T(e.text)},[t,T]);const R=(0,_react.useCallback)(e=>_askBuoyStore.askBuoyStore.takeQueuedToDraft(e),[]),O=(0,_react.useCallback)(e=>_askBuoyStore.askBuoyStore.removeQueued(e),[]),E=(0,_react.useCallback)(()=>{u.current?.abort(),u.current=null,(0,_resetConversation.clearConversation)()},[]),U=(0,_react.useCallback)(()=>(0,_resetConversation.resetConversation)({dispatch:_sharedUi.dispatchToolAction,undoFirst:!0}),[]),P=(0,_react.useCallback)(async t=>{const o=_askBuoyStore.askBuoyStore.getLedger();if(!o)return void _askBuoyStore.askBuoyStore.setNotice(`${t.label} couldn't run — no active Ask Buoy session.`);const s=e?.tools?.length?[..._agentCore.CATALOG,...e.tools]:void 0;if(t.targetDigest){const e=await(0,_agentCore.readTargetDigest)({toolId:t.toolId,action:t.action,params:t.params??{},dispatch:r,catalog:s});if(void 0!==e&&e!==t.targetDigest)return void _askBuoyStore.askBuoyStore.addNote(`“${t.label}” wasn't applied — what it would change has moved on since the app restarted. Nothing was written. Ask again if you still want it.`)}const a=await(0,_agentCore.runGatedAction)({toolId:t.toolId,action:t.action,params:t.params??{},dispatch:r,ledger:o,policy:S(),isRelease:isRelease,catalog:s});a.ok?_askBuoyStore.askBuoyStore.addNote(`Applied “${t.label}”, which was still waiting when the app restarted. Whatever else that answer was going to do is gone — ask again if there was more to it.`):_askBuoyStore.askBuoyStore.setNotice(`${t.label} failed — ${a.error}`)},[e,S]),I=(0,_react.useCallback)(e=>{const t=_askBuoyStore.askBuoyStore.getState().pending,o="boolean"==typeof e?e:e.approved;_askBuoyStore.askBuoyStore.answerApproval(e),t?.restored&&(o?P(t):_askBuoyStore.askBuoyStore.addNote(`Skipped “${t.label}”. Nothing was changed.`))},[P]),x=(0,_react.useCallback)(e=>{_askBuoyStore.askBuoyStore.recordAnswer(e);const t=questionBehind(e.blockId);T(t?`${t} — ${(0,_agentCore.answerToText)(e)}`:(0,_agentCore.answerToText)(e))},[T]),$=(0,_react.useCallback)(async(t,o)=>{if(!(0,_sharedUi.hasAccountAccess)()||!s.current)return void _askBuoyStore.askBuoyStore.setNotice("Ask Buoy requires Pro access.");if(t.send)return void T(t.send);if(!t.dispatch)return;const a=`${o}:${t.label}`,n=_askBuoyStore.askBuoyStore.getLedger();if(!n)return void _askBuoyStore.askBuoyStore.setNotice(`${t.label} failed — no active Ask Buoy session.`);_askBuoyStore.askBuoyStore.setActionState(a,"running");const u=await(0,_agentCore.runGatedAction)({toolId:t.dispatch.toolId,action:t.dispatch.action,params:t.dispatch.params??{},dispatch:r,ledger:n,policy:S(),isRelease:isRelease,catalog:e?.tools?.length?[..._agentCore.CATALOG,...e.tools]:void 0});u.ok?_askBuoyStore.askBuoyStore.setActionState(a,"done"):(_askBuoyStore.askBuoyStore.setActionState(a,"failed"),_askBuoyStore.askBuoyStore.setNotice(`${t.label} failed — ${u.error}`))},[T,e,S]);return{state:t,send:T,stop:q,reset:E,undoThenReset:U,approve:I,retry:N,answer:x,runAction:$,editQueued:R,removeQueued:O,configured:c,toolCount:Object.keys(g).length,availableToolIds:Object.keys(g)}}
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.useAskBuoy = useAskBuoy;
7
+ exports.useAskBuoyState = useAskBuoyState;
8
+ var _sharedUi = require("@buoy-gg/shared-ui");
9
+ var _react = require("react");
10
+ var _reactNative = require("react-native");
11
+ var _agentCore = require("@buoy-gg/agent-core");
12
+ var _askBuoyStore = require("./askBuoyStore");
13
+ var _resetConversation = require("./resetConversation");
14
+ var _transcriptPersistence = require("./transcriptPersistence");
15
+ var _useAskBuoySettings = require("./useAskBuoySettings");
16
+ /**
17
+ * Wire the sheet to the agent.
18
+ *
19
+ * Two things here are load-bearing:
20
+ *
21
+ * 1. DISPATCH GOES THROUGH `dispatchToolAction`, the same on-device seam a
22
+ * Scenario step and a desktop click use. No second adapter map, nothing
23
+ * that can drift from what the broker sees.
24
+ * 2. THE SESSION IS REBUILT WHEN THE TOOL LIST CHANGES. The adapter map is a
25
+ * memo whose contents depend on which packages resolved and whether a
26
+ * QueryClientProvider is above FloatingDevTools — it is per-app and per
27
+ * render, never a constant. A session that cached the tool list at open
28
+ * would offer the model tools that are no longer there.
29
+ */
30
+
31
+ const isRelease = typeof __DEV__ !== "undefined" && !__DEV__;
32
+
33
+ /**
34
+ * What this device can dispatch, right now.
35
+ *
36
+ * `getSnapshot` is folded in because half of Buoy's read surface is not an
37
+ * action at all — console entries, network events, routes and env live only in
38
+ * the adapter's snapshot. Without it the model is offered a console tool whose
39
+ * sole action wipes the logs, and no way to read them.
40
+ *
41
+ * READ FRESH, never cached. Packages register over the first frames, and some
42
+ * only once the thing they wrap exists — route-events publishes its actions
43
+ * when the navigation container is up, long after this hook first runs. A
44
+ * snapshot taken at mount froze that: the agent was handed a route tool that
45
+ * could only `getSnapshot`, so asked to navigate it guessed three tool names
46
+ * that do not exist, spent 41 seconds, and told the user this build cannot
47
+ * move between screens. It can.
48
+ */
49
+ /**
50
+ * The question a block asked, but ONLY when the model can no longer remember
51
+ * asking it — i.e. the bubble came back from disk. In a live conversation the
52
+ * model has the question in its own history and repeating it would put the
53
+ * words in the user's mouth twice.
54
+ *
55
+ * The wording field differs by block kind: `question` on choice and
56
+ * multiSelect, `label` on input / select / slider / dateTime, `title` on
57
+ * confirm and form.
58
+ */
59
+ function questionBehind(blockId) {
60
+ for (const m of _askBuoyStore.askBuoyStore.getState().messages) {
61
+ if (!m.restored) continue;
62
+ for (const placed of m.blocks) {
63
+ const b = placed.block;
64
+ if (b?.id !== blockId) continue;
65
+ const asked = b.question ?? b.label ?? b.title;
66
+ return typeof asked === "string" && asked.trim() ? asked.trim() : undefined;
67
+ }
68
+ }
69
+ return undefined;
70
+ }
71
+ function readAvailableActions() {
72
+ try {
73
+ const actions = (0, _sharedUi.listToolActions)();
74
+ for (const toolId of (0, _sharedUi.listSnapshotToolIds)()) {
75
+ if (!actions[toolId]) actions[toolId] = [];
76
+ if (!actions[toolId].includes(_agentCore.SNAPSHOT_ACTION)) {
77
+ actions[toolId] = [_agentCore.SNAPSHOT_ACTION, ...actions[toolId]];
78
+ }
79
+ }
80
+ return actions;
81
+ } catch {
82
+ return {};
83
+ }
84
+ }
85
+
86
+ /** Long enough to coalesce a streaming answer's deltas, short enough to beat a crash. */
87
+ const SAVE_DEBOUNCE_MS = 600;
88
+ function useAskBuoyState() {
89
+ return (0, _react.useSyncExternalStore)(_askBuoyStore.askBuoyStore.subscribe, _askBuoyStore.askBuoyStore.getState, _askBuoyStore.askBuoyStore.getState);
90
+ }
91
+ function useAskBuoy(config) {
92
+ const state = useAskBuoyState();
93
+ const hasProAccess = (0, _sharedUi.getUseIsPro)()();
94
+ const proAccessRef = (0, _react.useRef)(hasProAccess);
95
+ proAccessRef.current = hasProAccess;
96
+ const dispatchAgentAction = (0, _react.useCallback)((...args) => {
97
+ if (!(0, _sharedUi.hasAccountAccess)() || !proAccessRef.current) return Promise.reject(new Error("Ask Buoy requires Pro access."));
98
+ return (0, _sharedUi.dispatchToolAction)(...args);
99
+ }, []);
100
+ const sessionRef = (0, _react.useRef)(null);
101
+ /** One restore attempt per mount — see the note at the read. */
102
+ const restoredRef = (0, _react.useRef)(false);
103
+ const abortRef = (0, _react.useRef)(null);
104
+ // Read through a ref where a stable callback needs the LATEST config (the
105
+ // onEvent tap) without re-creating the callback per render.
106
+ const configRef = (0, _react.useRef)(config);
107
+ configRef.current = config;
108
+ const configured = !!config?.endpoint && !!config?.model;
109
+ /**
110
+ * On by default. The conversation surviving a reload is what makes the tool
111
+ * usable while iterating, and it is the only thing that survives a crash —
112
+ * but it puts the chat on disk, so a host handling regulated data can say no.
113
+ */
114
+ const persist = config?.persistTranscript !== false;
115
+ /**
116
+ * The device's "don't ask me" toggle, read here rather than only in the
117
+ * settings view so it is loaded off disk before the first turn — a
118
+ * preference that only took effect once you had opened Settings would ask
119
+ * once, every launch, which is the thing it exists to stop.
120
+ */
121
+ const {
122
+ bypassApprovals,
123
+ readOnly
124
+ } = (0, _useAskBuoySettings.useAskBuoySettings)();
125
+ // Through refs where the session is BUILT: the flags are not session
126
+ // identity, and putting them in that effect's deps would rebuild the
127
+ // conversation on a toggle. The effects below push changes instead.
128
+ const bypassRef = (0, _react.useRef)(bypassApprovals);
129
+ bypassRef.current = bypassApprovals;
130
+ const readOnlyRef = (0, _react.useRef)(readOnly);
131
+ readOnlyRef.current = readOnly;
132
+
133
+ /**
134
+ * The policy a human-initiated dispatch runs under — block buttons and a
135
+ * restored approval. The session applies the device toggles itself; these
136
+ * two paths take `config.policy` directly, so without this the Read only
137
+ * toggle governed the model's calls and not the buttons the model drew.
138
+ * App OR device: the toggle narrows, never widens.
139
+ */
140
+ const effectivePolicy = (0, _react.useCallback)(() => readOnlyRef.current ? {
141
+ ...(config?.policy ?? {}),
142
+ readOnly: true
143
+ } : config?.policy ?? {}, [config]);
144
+
145
+ /**
146
+ * Re-read once the registry says it is up. This is what the surrounding code
147
+ * has always assumed happens — the session effect's note about `toolKey`
148
+ * changing "a frame or two after open" was describing a recomputation that,
149
+ * with an empty dependency list, never actually ran.
150
+ */
151
+ const [registryTick, setRegistryTick] = (0, _react.useState)(0);
152
+ (0, _react.useEffect)(() => {
153
+ let cancelled = false;
154
+ void (0, _sharedUi.waitForToolRegistry)().then(() => {
155
+ if (!cancelled) setRegistryTick(n => n + 1);
156
+ });
157
+ return () => {
158
+ cancelled = true;
159
+ };
160
+ }, []);
161
+ const availableActions = (0, _react.useMemo)(() => readAvailableActions(), [registryTick]);
162
+ const toolKey = Object.keys(availableActions).sort().join(",");
163
+ (0, _react.useEffect)(() => {
164
+ _askBuoyStore.askBuoyStore.setConfigured(configured);
165
+ // Stamped on the store so an exported run says what it ran against.
166
+ _askBuoyStore.askBuoyStore.setMeta({
167
+ model: config?.model,
168
+ protocol: config?.protocol ?? (config ? "anthropic" : undefined),
169
+ appName: config?.appName,
170
+ platform: _reactNative.Platform.OS,
171
+ build: isRelease ? "release" : "development"
172
+ });
173
+ if (!configured || !config) {
174
+ sessionRef.current = null;
175
+ _askBuoyStore.askBuoyStore.setNotice("Ask Buoy isn't set up in this app yet. A developer needs to point it at your team's AI endpoint.");
176
+ return;
177
+ }
178
+ // The classic first-run mistake, caught statically: a provider's own URL
179
+ // with the wrong protocol fails with a raw error that says nothing about
180
+ // the one-line fix. ONLY the canonical provider hosts are checked — a
181
+ // gateway may legitimately speak either protocol on any path (our own dev
182
+ // gateway serves OpenAI framing on /v1/messages, and a path-based version
183
+ // of this check flagged it on the first device run).
184
+ const protocol = config.protocol ?? "anthropic";
185
+ if (isRelease && config.apiKey) {
186
+ _askBuoyStore.askBuoyStore.setNotice("This build carries a plaintext apiKey — that's dev-only and it ships to every install. Use the headers callback with your own gateway for distributed builds.");
187
+ } else if (protocol === "anthropic" && /^https?:\/\/api\.openai\.com\//i.test(config.endpoint)) {
188
+ _askBuoyStore.askBuoyStore.setNotice('This endpoint is api.openai.com but the protocol is "anthropic". Set protocol: "openai" in the askBuoy config.');
189
+ } else if (protocol === "openai" && /^https?:\/\/api\.anthropic\.com\//i.test(config.endpoint)) {
190
+ _askBuoyStore.askBuoyStore.setNotice('This endpoint is api.anthropic.com but the protocol is "openai". Remove protocol or set it to "anthropic".');
191
+ } else {
192
+ _askBuoyStore.askBuoyStore.setNotice(null);
193
+ }
194
+
195
+ // Reuse the held session while nothing material changed. The transcript
196
+ // already survives close/reopen in the module store; without this the
197
+ // session and ledger did not — reopening the sheet swapped in an empty
198
+ // ledger (undo bar gone, agent changes still live in the app) and a blank
199
+ // model memory behind a transcript that still showed the conversation.
200
+ // The tool list is deliberately NOT part of this signature. Packages
201
+ // register a frame or two apart, so `toolKey` legitimately changes right
202
+ // after open — and keying on it silently rebuilt the session mid-chat,
203
+ // throwing away the conversation, the model's memory and the undo ledger
204
+ // while the transcript (a separate store) kept rendering as if nothing
205
+ // happened. Verified on device: a destructive change went unrecorded
206
+ // because it landed in a ledger that had just been replaced.
207
+ const signature = [config.endpoint, config.protocol ?? "anthropic", config.model].join("|");
208
+ const held = _askBuoyStore.askBuoyStore.getHeldSession();
209
+ if (held && held.signature === signature) {
210
+ sessionRef.current = held.session;
211
+ held.session.setAvailableActions(availableActions);
212
+ held.session.setApprovalBypass(bypassRef.current);
213
+ held.session.setReadOnly(readOnlyRef.current);
214
+ _askBuoyStore.askBuoyStore.setLedger(held.session.ledger);
215
+ return;
216
+ }
217
+ const session = (0, _agentCore.createAskBuoySession)({
218
+ endpoint: config.endpoint,
219
+ protocol: config.protocol ?? "anthropic",
220
+ model: config.model,
221
+ headers: config.headers,
222
+ apiKey: config.apiKey,
223
+ maxTokens: config.maxTokens,
224
+ anthropicVersion: config.anthropicVersion,
225
+ requestOverrides: config.requestOverrides,
226
+ // Host-declared custom tools join the built-in catalog. toProviderTools
227
+ // still filters against the live registry, so a descriptor whose
228
+ // `custom:<id>` adapter never registered is simply not offered.
229
+ catalog: config.tools?.length ? [..._agentCore.CATALOG, ...config.tools] : undefined,
230
+ dispatch: dispatchAgentAction,
231
+ readSnapshot: _sharedUi.readToolSnapshot,
232
+ availableActions,
233
+ policy: config.policy,
234
+ context: config.context,
235
+ isRelease,
236
+ appName: config.appName,
237
+ platform: _reactNative.Platform.OS,
238
+ requestApproval: input => _askBuoyStore.askBuoyStore.askApproval(input)
239
+ });
240
+ sessionRef.current = session;
241
+ session.setApprovalBypass(bypassRef.current);
242
+ session.setReadOnly(readOnlyRef.current);
243
+ _askBuoyStore.askBuoyStore.holdSession(session, signature);
244
+ _askBuoyStore.askBuoyStore.setLedger(session.ledger);
245
+
246
+ /**
247
+ * Bring the last conversation back — both halves of it.
248
+ *
249
+ * The transcript and the model's memory are separate things (the store and
250
+ * the session), and restoring only the first is worse than restoring
251
+ * neither: the user reads a conversation the agent has no recollection of,
252
+ * and "undo that" or "now do the same for Pikachu" lands on an empty
253
+ * history. So the session is restored in the same pass, and only into a
254
+ * session this effect just built.
255
+ */
256
+ // The registry publishes on mount, a frame or two after first paint. Warm
257
+ // the grounding once it is there so the first question does not pay for it.
258
+ let cancelled = false;
259
+ void (0, _sharedUi.waitForToolRegistry)().then(ready => {
260
+ if (ready && !cancelled) void session.prime();
261
+ });
262
+
263
+ /**
264
+ * NOT gated on `cancelled`, and once per mount.
265
+ *
266
+ * The disk read races the tool registry, and it was losing about half the
267
+ * time. `availableActions` legitimately changes a frame or two after open
268
+ * (see the note above) — that re-runs this effect, whose cleanup sets
269
+ * `cancelled`, and the in-flight restore then threw its result away. The
270
+ * second pass takes the held-session branch and returns early, so nothing
271
+ * ever retried: the conversation was on disk, read correctly, and dropped
272
+ * on the floor. Caught by the e2e, where one test restored and the next
273
+ * did not, with no difference between them.
274
+ *
275
+ * Safe to leave running: `hydrate` refuses if anything has been said since,
276
+ * and `restore` refuses a session that already has history. Resolved
277
+ * against `sessionRef.current` rather than the captured `session` so a
278
+ * genuine reconfiguration mid-read restores into the session in use.
279
+ */
280
+ if (persist && !restoredRef.current) {
281
+ restoredRef.current = true;
282
+ void (0, _transcriptPersistence.readTranscript)().then(saved => {
283
+ if (!saved) return;
284
+ const hydrated = _askBuoyStore.askBuoyStore.hydrate({
285
+ messages: saved.messages,
286
+ answers: saved.answers,
287
+ usage: saved.usage,
288
+ queued: saved.queued
289
+ });
290
+ if (!hydrated) return;
291
+ sessionRef.current?.restore(saved.history);
292
+ // The undo bar, back with the transcript that promised it.
293
+ if (saved.ledger?.length) sessionRef.current?.ledger.restore(saved.ledger);
294
+ // A question the user never answered comes back with the conversation.
295
+ // Losing it silently reads as consent they never gave: nothing was
296
+ // tapped, so the change is still waiting as far as they know.
297
+ if (saved.pending) _askBuoyStore.askBuoyStore.restorePending(saved.pending);
298
+ });
299
+ }
300
+ return () => {
301
+ cancelled = true;
302
+ };
303
+ }, [configured, config, availableActions, toolKey, persist]);
304
+
305
+ /**
306
+ * Push a toggle made mid-conversation. Declared after the effect that builds
307
+ * the session, so on mount it lands on a session that already exists, and on
308
+ * a later flip it reaches the held one without disturbing the transcript.
309
+ */
310
+ (0, _react.useEffect)(() => {
311
+ sessionRef.current?.setApprovalBypass(bypassApprovals);
312
+ }, [bypassApprovals]);
313
+ (0, _react.useEffect)(() => {
314
+ sessionRef.current?.setReadOnly(readOnly);
315
+ }, [readOnly]);
316
+
317
+ /**
318
+ * Save on change: coalesced while a turn streams, immediate the moment it ends.
319
+ *
320
+ * The debounce exists because a streaming answer changes the store on every
321
+ * delta, and writing a whole transcript per token would cost more than the
322
+ * turn does. But applying it to the END of a turn as well left a window
323
+ * where the finished answer was on screen and not yet on disk — a crash or a
324
+ * fast reload inside it lost the whole turn, which is precisely the case
325
+ * this feature exists for. An e2e that relaunched as soon as the answer
326
+ * rendered lost it every time, and that is a real user doing a fast reload,
327
+ * not a harness artefact.
328
+ *
329
+ * Saving still happens DURING a turn as well, which is what lets a bubble
330
+ * the app died in come back marked interrupted rather than blank.
331
+ */
332
+ const messages = state.messages;
333
+ const answers = state.answers;
334
+ const usage = state.usage;
335
+ const busy = state.busy;
336
+ /**
337
+ * In the deps because an approval is the one thing that changes nothing
338
+ * else. `approval-required` adds no bubble and no tool row — the engine
339
+ * yields it and then parks — so without this the save that carries the card
340
+ * to disk never fires, and the reload it is meant to survive loses it.
341
+ */
342
+ const pending = state.pending;
343
+ const queued = state.queued;
344
+ (0, _react.useEffect)(() => {
345
+ if (!persist) return;
346
+ if (messages.length === 0) return;
347
+ const write = () => {
348
+ void (0, _transcriptPersistence.writeTranscript)((0, _transcriptPersistence.buildPayload)({
349
+ messages,
350
+ history: sessionRef.current?.messages ?? [],
351
+ answers,
352
+ usage,
353
+ pending,
354
+ ledger: _askBuoyStore.askBuoyStore.getLedger()?.list(),
355
+ queued
356
+ }));
357
+ };
358
+ if (!busy) {
359
+ write();
360
+ return;
361
+ }
362
+ const timer = setTimeout(write, SAVE_DEBOUNCE_MS);
363
+ return () => clearTimeout(timer);
364
+ }, [persist, busy, messages, answers, usage, pending, queued]);
365
+
366
+ /** Stream one turn into a fresh assistant bubble. Callers set up the user side. */
367
+ const runTurn = (0, _react.useCallback)(text => {
368
+ if (!(0, _sharedUi.hasAccountAccess)() || !proAccessRef.current) return;
369
+ const session = sessionRef.current;
370
+ if (!session) return;
371
+ _askBuoyStore.askBuoyStore.beginTurn();
372
+ const messageId = _askBuoyStore.askBuoyStore.startAssistant();
373
+ const controller = new AbortController();
374
+ abortRef.current = controller;
375
+
376
+ // The truth about this device, re-read at the top of every turn. A tool
377
+ // that registered since the sheet opened is dispatchable NOW, and the
378
+ // model is only offered what this list says it has.
379
+ session.setAvailableActions(readAvailableActions());
380
+ const onEvent = configRef.current?.onEvent;
381
+ void (async () => {
382
+ try {
383
+ for await (const ev of session.send(text, controller.signal)) {
384
+ _askBuoyStore.askBuoyStore.applyEvent(messageId, ev);
385
+ if (onEvent) {
386
+ try {
387
+ onEvent(ev);
388
+ } catch {
389
+ // The audit tap must never take the chat down.
390
+ }
391
+ }
392
+ }
393
+ } catch (err) {
394
+ // Stop is not a failure. The abort comes back as a cancelled fetch,
395
+ // and reporting that as an error told the user "couldn't reach your AI
396
+ // endpoint, check the connection" about the thing they had just asked
397
+ // for — with `FetchRequestCanceledException` printed underneath.
398
+ if (!controller.signal.aborted) {
399
+ _askBuoyStore.askBuoyStore.applyEvent(messageId, {
400
+ type: "error",
401
+ message: err instanceof Error ? err.message : "Something went wrong talking to your AI endpoint."
402
+ });
403
+ }
404
+ } finally {
405
+ // Marked HERE, not only in the catch. The engine now reads the abort
406
+ // between calls and returns cleanly, so most stops never throw — and
407
+ // a turn that ended because the user pressed Stop must say so either
408
+ // way, or the bubble just trails off as if the model ran out of words.
409
+ if (controller.signal.aborted) _askBuoyStore.askBuoyStore.markStopped(messageId);
410
+ _askBuoyStore.askBuoyStore.finishAssistant(messageId);
411
+ abortRef.current = null;
412
+ }
413
+ })();
414
+ }, []);
415
+ const send = (0, _react.useCallback)(text => {
416
+ if (!(0, _sharedUi.hasAccountAccess)() || !proAccessRef.current) return;
417
+ const trimmed = text.trim();
418
+ if (!sessionRef.current || !trimmed) return;
419
+
420
+ // Typed mid-turn: park it behind whatever is already parked. The
421
+ // composer already cleared the field, and silently dropping the words
422
+ // was the worst of all outcomes — the single slot this replaced did
423
+ // exactly that to every message but the last.
424
+ if (_askBuoyStore.askBuoyStore.getState().busy) {
425
+ _askBuoyStore.askBuoyStore.enqueue(trimmed);
426
+ return;
427
+ }
428
+
429
+ // Typing past an Ask block IS an answer: the block is skipped and locks.
430
+ // Without this the composer stayed on "Pick an option above…" forever and
431
+ // a stale choice sat tappable in the history.
432
+ const awaiting = _askBuoyStore.askBuoyStore.getState().awaitingBlockId;
433
+ if (awaiting) _askBuoyStore.askBuoyStore.recordAnswer({
434
+ blockId: awaiting,
435
+ kind: "skipped"
436
+ });
437
+ _askBuoyStore.askBuoyStore.addUser(trimmed);
438
+ runTurn(trimmed);
439
+ }, [runTurn]);
440
+ const retry = (0, _react.useCallback)(() => {
441
+ const {
442
+ messages,
443
+ busy
444
+ } = _askBuoyStore.askBuoyStore.getState();
445
+ if (busy || !sessionRef.current) return;
446
+ const lastUser = [...messages].reverse().find(m => m.role === "user");
447
+ if (!lastUser) return;
448
+ // The failed bubble is kept — see the note on `retry` in the interface.
449
+ runTurn(lastUser.text);
450
+ }, [runTurn]);
451
+ const stop = (0, _react.useCallback)(() => {
452
+ _askBuoyStore.askBuoyStore.requestStop();
453
+ // A pending approval parks an unresolved promise inside the engine; the
454
+ // abort signal is only read between calls, so Stop must also answer the
455
+ // approval (as declined) or the generator hangs forever.
456
+ if (_askBuoyStore.askBuoyStore.getState().pending) _askBuoyStore.askBuoyStore.answerApproval(false);
457
+ // Parked messages stay parked. The queue holds after a stop (see
458
+ // `queuePauseReason`), so ending the turn no longer flushes them — and
459
+ // they are not dumped into the composer either: three 4,000-character
460
+ // requests concatenated into one input lose their boundaries.
461
+ abortRef.current?.abort();
462
+ abortRef.current = null;
463
+ }, []);
464
+ (0, _react.useEffect)(() => {
465
+ const off = (0, _sharedUi.subscribeAccountAccess)(() => {
466
+ if (!(0, _sharedUi.hasAccountAccess)()) stop();
467
+ });
468
+ return () => {
469
+ off();
470
+ stop();
471
+ };
472
+ }, [stop]);
473
+
474
+ // Paid expiry and Weekend Pass ending keep the Free account admitted, but
475
+ // must still abort a paid-only turn that was already streaming.
476
+ (0, _react.useEffect)(() => {
477
+ if (!hasProAccess) stop();
478
+ }, [hasProAccess, stop]);
479
+
480
+ /**
481
+ * Deliver the next parked message — only when the chat is genuinely idle.
482
+ *
483
+ * `turnPhaseOf` + `queuePauseReason` decide, not `!busy`: the old check
484
+ * fired after an error (into the same dead connection), after Stop, and into
485
+ * an open Ask block as the answer to a question. See the store for the
486
+ * rules; this effect just obeys them.
487
+ */
488
+ (0, _react.useEffect)(() => {
489
+ if (state.queued.length === 0) return;
490
+ if ((0, _askBuoyStore.turnPhaseOf)(state) !== "idle") return;
491
+ if ((0, _askBuoyStore.queuePauseReason)(state) !== null) return;
492
+ const next = _askBuoyStore.askBuoyStore.shiftQueued();
493
+ if (next) send(next.text);
494
+ }, [state, send]);
495
+ const editQueued = (0, _react.useCallback)(id => _askBuoyStore.askBuoyStore.takeQueuedToDraft(id), []);
496
+ const removeQueued = (0, _react.useCallback)(id => _askBuoyStore.askBuoyStore.removeQueued(id), []);
497
+ const reset = (0, _react.useCallback)(() => {
498
+ abortRef.current?.abort();
499
+ abortRef.current = null;
500
+ // "New conversation" means gone, not hidden. Leaving the last chat on disk
501
+ // after the user asked for a clean one is the opposite of what they said.
502
+ (0, _resetConversation.clearConversation)();
503
+ }, []);
504
+ const undoThenReset = (0, _react.useCallback)(() => (0, _resetConversation.resetConversation)({
505
+ dispatch: _sharedUi.dispatchToolAction,
506
+ undoFirst: true
507
+ }), []);
508
+
509
+ /**
510
+ * Run a call whose approval outlived its turn.
511
+ *
512
+ * Through `runGatedAction` — the same gate a block button uses, where the
513
+ * human's tap IS the approval — rather than `dispatchToolAction` raw, so the
514
+ * deny list, read-only mode, the release refusals and the effect ledger all
515
+ * still apply to a change made this way. Undo works on it afterwards for
516
+ * exactly the same reason.
517
+ */
518
+ const applyRestoredApproval = (0, _react.useCallback)(async pending => {
519
+ const ledger = _askBuoyStore.askBuoyStore.getLedger();
520
+ if (!ledger) {
521
+ _askBuoyStore.askBuoyStore.setNotice(`${pending.label} couldn't run — no active Ask Buoy session.`);
522
+ return;
523
+ }
524
+ const catalog = config?.tools?.length ? [..._agentCore.CATALOG, ...config.tools] : undefined;
525
+ // Freshness before action. The card was asked in a run of the app that
526
+ // no longer exists; if what it would overwrite has moved since, writing
527
+ // the saved params is a change nobody approved. Re-read, compare, refuse.
528
+ if (pending.targetDigest) {
529
+ const now = await (0, _agentCore.readTargetDigest)({
530
+ toolId: pending.toolId,
531
+ action: pending.action,
532
+ params: pending.params ?? {},
533
+ dispatch: dispatchAgentAction,
534
+ catalog
535
+ });
536
+ if (now !== undefined && now !== pending.targetDigest) {
537
+ _askBuoyStore.askBuoyStore.addNote(`“${pending.label}” wasn't applied — what it would change has moved on since the app restarted. Nothing was written. Ask again if you still want it.`);
538
+ return;
539
+ }
540
+ }
541
+ const outcome = await (0, _agentCore.runGatedAction)({
542
+ toolId: pending.toolId,
543
+ action: pending.action,
544
+ params: pending.params ?? {},
545
+ dispatch: dispatchAgentAction,
546
+ ledger,
547
+ policy: effectivePolicy(),
548
+ isRelease,
549
+ catalog
550
+ });
551
+ if (outcome.ok) {
552
+ _askBuoyStore.askBuoyStore.addNote(`Applied “${pending.label}”, which was still waiting when the app restarted. Whatever else that answer was going to do is gone — ask again if there was more to it.`);
553
+ } else {
554
+ _askBuoyStore.askBuoyStore.setNotice(`${pending.label} failed — ${outcome.error}`);
555
+ }
556
+ }, [config, effectivePolicy]);
557
+ const approve = (0, _react.useCallback)(answer => {
558
+ const pending = _askBuoyStore.askBuoyStore.getState().pending;
559
+ const approved = typeof answer === "boolean" ? answer : answer.approved;
560
+ // Clear the card first either way: the tap is answered, and the dispatch
561
+ // below is slow enough to leave it sitting there looking unanswered.
562
+ _askBuoyStore.askBuoyStore.answerApproval(answer);
563
+ // A live card resolves the promise the engine is parked on, and the turn
564
+ // carries on from there. A RESTORED one has no turn behind it — that
565
+ // generator died with the process — so Allow has to run the call itself.
566
+ if (!pending?.restored) return;
567
+ if (!approved) {
568
+ _askBuoyStore.askBuoyStore.addNote(`Skipped “${pending.label}”. Nothing was changed.`);
569
+ return;
570
+ }
571
+ void applyRestoredApproval(pending);
572
+ }, [applyRestoredApproval]);
573
+ const answer = (0, _react.useCallback)(a => {
574
+ _askBuoyStore.askBuoyStore.recordAnswer(a);
575
+ // Plain words to the model, never JSON: "Business checkout", "Yes, go ahead."
576
+ //
577
+ // Unless the question came back from disk. A restored history is rewound
578
+ // to the last COMPLETE round, and an Ask block ends its turn with a
579
+ // `buoy_ui` call — so the turn that asked is always rewound out of the
580
+ // model's memory while its buttons stay tappable. A bare "Quantity" then
581
+ // arrives with nothing behind it, and the model answers "that could mean
582
+ // a couple of different things". Carry the question with the answer.
583
+ const asked = questionBehind(a.blockId);
584
+ send(asked ? `${asked} — ${(0, _agentCore.answerToText)(a)}` : (0, _agentCore.answerToText)(a));
585
+ }, [send]);
586
+
587
+ /**
588
+ * Block buttons. `send` is a chat reply; `dispatch` runs the action through
589
+ * `runGatedAction` — the SAME validation, policy and ledger path a model
590
+ * call takes, minus the model. The first version called `dispatchToolAction`
591
+ * raw, which made a model-authored button an invisible, ungoverned,
592
+ * unundoable mutation while the `buoy_ui` schema promised the opposite.
593
+ * The human's tap satisfies `requireApproval`; deny lists, read-only mode
594
+ * and release refusals still stand. Button state is tracked so a tap shows
595
+ * running → done and can't double-fire.
596
+ * (`minimize` / `openTool` are the sheet's to handle; see AskBuoyModal.)
597
+ */
598
+ const runAction = (0, _react.useCallback)(async (action, blockId) => {
599
+ if (!(0, _sharedUi.hasAccountAccess)() || !proAccessRef.current) {
600
+ _askBuoyStore.askBuoyStore.setNotice("Ask Buoy requires Pro access.");
601
+ return;
602
+ }
603
+ if (action.send) {
604
+ send(action.send);
605
+ return;
606
+ }
607
+ if (!action.dispatch) return;
608
+ const key = `${blockId}:${action.label}`;
609
+ const ledger = _askBuoyStore.askBuoyStore.getLedger();
610
+ if (!ledger) {
611
+ _askBuoyStore.askBuoyStore.setNotice(`${action.label} failed — no active Ask Buoy session.`);
612
+ return;
613
+ }
614
+ _askBuoyStore.askBuoyStore.setActionState(key, "running");
615
+ const outcome = await (0, _agentCore.runGatedAction)({
616
+ toolId: action.dispatch.toolId,
617
+ action: action.dispatch.action,
618
+ params: action.dispatch.params ?? {},
619
+ dispatch: dispatchAgentAction,
620
+ ledger,
621
+ policy: effectivePolicy(),
622
+ isRelease,
623
+ // Same merged catalog the session offers, so a button on a custom
624
+ // tool's block is not refused as unknown.
625
+ catalog: config?.tools?.length ? [..._agentCore.CATALOG, ...config.tools] : undefined
626
+ });
627
+ if (outcome.ok) {
628
+ _askBuoyStore.askBuoyStore.setActionState(key, "done");
629
+ } else {
630
+ _askBuoyStore.askBuoyStore.setActionState(key, "failed");
631
+ _askBuoyStore.askBuoyStore.setNotice(`${action.label} failed — ${outcome.error}`);
632
+ }
633
+ }, [send, config, effectivePolicy]);
634
+ return {
635
+ state,
636
+ send,
637
+ stop,
638
+ reset,
639
+ undoThenReset,
640
+ approve,
641
+ retry,
642
+ answer,
643
+ runAction,
644
+ editQueued,
645
+ removeQueued,
646
+ configured,
647
+ toolCount: Object.keys(availableActions).length,
648
+ availableToolIds: Object.keys(availableActions)
649
+ };
650
+ }
651
+ //# sourceMappingURL=useAskBuoy.js.map