@buoy-gg/ask-buoy 7.0.36 → 7.0.38

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