@hashgraphonline/conversational-agent 0.2.216 → 0.2.218

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/cli/readme.md +181 -0
  2. package/dist/cjs/index.cjs +1 -1
  3. package/dist/cjs/index.cjs.map +1 -1
  4. package/dist/cjs/index.d.ts +1 -0
  5. package/dist/cjs/plugins/community/swarm/SwarmPlugin.d.ts +17 -0
  6. package/dist/cjs/plugins/community/swarm/__tests__/SwarmPlugin.mocks.d.ts +1 -0
  7. package/dist/cjs/plugins/community/swarm/__tests__/SwarmPlugin.test.d.ts +1 -0
  8. package/dist/cjs/plugins/community/swarm/__tests__/tools/CreatePostageStampTool.test.d.ts +1 -0
  9. package/dist/cjs/plugins/community/swarm/__tests__/tools/DownloadDataTool.test.d.ts +1 -0
  10. package/dist/cjs/plugins/community/swarm/__tests__/tools/DownloadFilesTool.test.d.ts +1 -0
  11. package/dist/cjs/plugins/community/swarm/__tests__/tools/ExtendPostageStampTool.test.d.ts +1 -0
  12. package/dist/cjs/plugins/community/swarm/__tests__/tools/GetPostageStampTool.test.d.ts +1 -0
  13. package/dist/cjs/plugins/community/swarm/__tests__/tools/ListPostageStampsTool.test.d.ts +1 -0
  14. package/dist/cjs/plugins/community/swarm/__tests__/tools/QueryUploadProgressTool.test.d.ts +1 -0
  15. package/dist/cjs/plugins/community/swarm/__tests__/tools/ReadFeedTool.test.d.ts +1 -0
  16. package/dist/cjs/plugins/community/swarm/__tests__/tools/SwarmTool.mocks.d.ts +14 -0
  17. package/dist/cjs/plugins/community/swarm/__tests__/tools/UpdateFeedTool.test.d.ts +1 -0
  18. package/dist/cjs/plugins/community/swarm/__tests__/tools/UploadDataTool.test.d.ts +1 -0
  19. package/dist/cjs/plugins/community/swarm/__tests__/tools/UploadFileTool.test.d.ts +1 -0
  20. package/dist/cjs/plugins/community/swarm/__tests__/tools/UploadFolderTool.test.d.ts +1 -0
  21. package/dist/cjs/plugins/community/swarm/config.d.ts +6 -0
  22. package/dist/cjs/plugins/community/swarm/constants.d.ts +8 -0
  23. package/dist/cjs/plugins/community/swarm/index.d.ts +2 -0
  24. package/dist/cjs/plugins/community/swarm/model.d.ts +23 -0
  25. package/dist/cjs/plugins/community/swarm/tools/CreatePostageStampTool.d.ts +47 -0
  26. package/dist/cjs/plugins/community/swarm/tools/DownloadDataTool.d.ts +35 -0
  27. package/dist/cjs/plugins/community/swarm/tools/DownloadFilesTool.d.ts +41 -0
  28. package/dist/cjs/plugins/community/swarm/tools/ExtendPostageStampTool.d.ts +47 -0
  29. package/dist/cjs/plugins/community/swarm/tools/GetPostageStampTool.d.ts +35 -0
  30. package/dist/cjs/plugins/community/swarm/tools/ListPostageStampsTool.d.ts +53 -0
  31. package/dist/cjs/plugins/community/swarm/tools/QueryUploadProgressTool.d.ts +35 -0
  32. package/dist/cjs/plugins/community/swarm/tools/ReadFeedTool.d.ts +41 -0
  33. package/dist/cjs/plugins/community/swarm/tools/UpdateFeedTool.d.ts +47 -0
  34. package/dist/cjs/plugins/community/swarm/tools/UploadDataTool.d.ts +47 -0
  35. package/dist/cjs/plugins/community/swarm/tools/UploadFileTool.d.ts +53 -0
  36. package/dist/cjs/plugins/community/swarm/tools/UploadFolderTool.d.ts +47 -0
  37. package/dist/cjs/plugins/community/swarm/utils.d.ts +22 -0
  38. package/dist/cjs/plugins/index.d.ts +1 -0
  39. package/dist/esm/index.js +33 -31
  40. package/dist/esm/index.js.map +1 -1
  41. package/dist/esm/index10.js +13 -677
  42. package/dist/esm/index10.js.map +1 -1
  43. package/dist/esm/index11.js +601 -234
  44. package/dist/esm/index11.js.map +1 -1
  45. package/dist/esm/index12.js +296 -136
  46. package/dist/esm/index12.js.map +1 -1
  47. package/dist/esm/index13.js +127 -235
  48. package/dist/esm/index13.js.map +1 -1
  49. package/dist/esm/index14.js +247 -84
  50. package/dist/esm/index14.js.map +1 -1
  51. package/dist/esm/index15.js +81 -159
  52. package/dist/esm/index15.js.map +1 -1
  53. package/dist/esm/index16.js +155 -229
  54. package/dist/esm/index16.js.map +1 -1
  55. package/dist/esm/index17.js +238 -140
  56. package/dist/esm/index17.js.map +1 -1
  57. package/dist/esm/index18.js +139 -493
  58. package/dist/esm/index18.js.map +1 -1
  59. package/dist/esm/index19.js +479 -91
  60. package/dist/esm/index19.js.map +1 -1
  61. package/dist/esm/index20.js +88 -147
  62. package/dist/esm/index20.js.map +1 -1
  63. package/dist/esm/index21.js +127 -666
  64. package/dist/esm/index21.js.map +1 -1
  65. package/dist/esm/index22.js +698 -44
  66. package/dist/esm/index22.js.map +1 -1
  67. package/dist/esm/index23.js +45 -304
  68. package/dist/esm/index23.js.map +1 -1
  69. package/dist/esm/index24.js +303 -153
  70. package/dist/esm/index24.js.map +1 -1
  71. package/dist/esm/index25.js +150 -117
  72. package/dist/esm/index25.js.map +1 -1
  73. package/dist/esm/index26.js +154 -18
  74. package/dist/esm/index26.js.map +1 -1
  75. package/dist/esm/index27.js +18 -22
  76. package/dist/esm/index27.js.map +1 -1
  77. package/dist/esm/index28.js +15 -74
  78. package/dist/esm/index28.js.map +1 -1
  79. package/dist/esm/index29.js +70 -295
  80. package/dist/esm/index29.js.map +1 -1
  81. package/dist/esm/index30.js +279 -100
  82. package/dist/esm/index30.js.map +1 -1
  83. package/dist/esm/index31.js +86 -922
  84. package/dist/esm/index31.js.map +1 -1
  85. package/dist/esm/index32.js +904 -189
  86. package/dist/esm/index32.js.map +1 -1
  87. package/dist/esm/index33.js +185 -1169
  88. package/dist/esm/index33.js.map +1 -1
  89. package/dist/esm/index34.js +1218 -112
  90. package/dist/esm/index34.js.map +1 -1
  91. package/dist/esm/index35.js +111 -99
  92. package/dist/esm/index35.js.map +1 -1
  93. package/dist/esm/index36.js +113 -8
  94. package/dist/esm/index36.js.map +1 -1
  95. package/dist/esm/index37.js +8 -45
  96. package/dist/esm/index37.js.map +1 -1
  97. package/dist/esm/index38.js +41 -102
  98. package/dist/esm/index38.js.map +1 -1
  99. package/dist/esm/index39.js +96 -55
  100. package/dist/esm/index39.js.map +1 -1
  101. package/dist/esm/index4.js +1 -1
  102. package/dist/esm/index40.js +58 -71
  103. package/dist/esm/index40.js.map +1 -1
  104. package/dist/esm/index41.js +79 -21
  105. package/dist/esm/index41.js.map +1 -1
  106. package/dist/esm/index42.js +21 -5
  107. package/dist/esm/index42.js.map +1 -1
  108. package/dist/esm/index43.js +26 -11
  109. package/dist/esm/index43.js.map +1 -1
  110. package/dist/esm/index44.js +12 -322
  111. package/dist/esm/index44.js.map +1 -1
  112. package/dist/esm/index45.js +66 -173
  113. package/dist/esm/index45.js.map +1 -1
  114. package/dist/esm/index46.js +69 -24
  115. package/dist/esm/index46.js.map +1 -1
  116. package/dist/esm/index47.js +47 -88
  117. package/dist/esm/index47.js.map +1 -1
  118. package/dist/esm/index48.js +100 -7
  119. package/dist/esm/index48.js.map +1 -1
  120. package/dist/esm/index49.js +79 -0
  121. package/dist/esm/index49.js.map +1 -0
  122. package/dist/esm/index5.js +2 -2
  123. package/dist/esm/index50.js +75 -0
  124. package/dist/esm/index50.js.map +1 -0
  125. package/dist/esm/index51.js +124 -0
  126. package/dist/esm/index51.js.map +1 -0
  127. package/dist/esm/index52.js +58 -0
  128. package/dist/esm/index52.js.map +1 -0
  129. package/dist/esm/index53.js +83 -0
  130. package/dist/esm/index53.js.map +1 -0
  131. package/dist/esm/index54.js +100 -0
  132. package/dist/esm/index54.js.map +1 -0
  133. package/dist/esm/index55.js +118 -0
  134. package/dist/esm/index55.js.map +1 -0
  135. package/dist/esm/index56.js +108 -0
  136. package/dist/esm/index56.js.map +1 -0
  137. package/dist/esm/index57.js +8 -0
  138. package/dist/esm/index57.js.map +1 -0
  139. package/dist/esm/index58.js +325 -0
  140. package/dist/esm/index58.js.map +1 -0
  141. package/dist/esm/index59.js +187 -0
  142. package/dist/esm/index59.js.map +1 -0
  143. package/dist/esm/index6.js +132 -833
  144. package/dist/esm/index6.js.map +1 -1
  145. package/dist/esm/index60.js +10 -0
  146. package/dist/esm/index60.js.map +1 -0
  147. package/dist/esm/index61.js +98 -0
  148. package/dist/esm/index61.js.map +1 -0
  149. package/dist/esm/index62.js +131 -0
  150. package/dist/esm/index62.js.map +1 -0
  151. package/dist/esm/index63.js +19 -0
  152. package/dist/esm/index63.js.map +1 -0
  153. package/dist/esm/index7.js +826 -75
  154. package/dist/esm/index7.js.map +1 -1
  155. package/dist/esm/index8.js +91 -13
  156. package/dist/esm/index8.js.map +1 -1
  157. package/dist/esm/index9.js +13 -17
  158. package/dist/esm/index9.js.map +1 -1
  159. package/dist/types/index.d.ts +1 -0
  160. package/dist/types/plugins/community/swarm/SwarmPlugin.d.ts +17 -0
  161. package/dist/types/plugins/community/swarm/__tests__/SwarmPlugin.mocks.d.ts +1 -0
  162. package/dist/types/plugins/community/swarm/__tests__/SwarmPlugin.test.d.ts +1 -0
  163. package/dist/types/plugins/community/swarm/__tests__/tools/CreatePostageStampTool.test.d.ts +1 -0
  164. package/dist/types/plugins/community/swarm/__tests__/tools/DownloadDataTool.test.d.ts +1 -0
  165. package/dist/types/plugins/community/swarm/__tests__/tools/DownloadFilesTool.test.d.ts +1 -0
  166. package/dist/types/plugins/community/swarm/__tests__/tools/ExtendPostageStampTool.test.d.ts +1 -0
  167. package/dist/types/plugins/community/swarm/__tests__/tools/GetPostageStampTool.test.d.ts +1 -0
  168. package/dist/types/plugins/community/swarm/__tests__/tools/ListPostageStampsTool.test.d.ts +1 -0
  169. package/dist/types/plugins/community/swarm/__tests__/tools/QueryUploadProgressTool.test.d.ts +1 -0
  170. package/dist/types/plugins/community/swarm/__tests__/tools/ReadFeedTool.test.d.ts +1 -0
  171. package/dist/types/plugins/community/swarm/__tests__/tools/SwarmTool.mocks.d.ts +14 -0
  172. package/dist/types/plugins/community/swarm/__tests__/tools/UpdateFeedTool.test.d.ts +1 -0
  173. package/dist/types/plugins/community/swarm/__tests__/tools/UploadDataTool.test.d.ts +1 -0
  174. package/dist/types/plugins/community/swarm/__tests__/tools/UploadFileTool.test.d.ts +1 -0
  175. package/dist/types/plugins/community/swarm/__tests__/tools/UploadFolderTool.test.d.ts +1 -0
  176. package/dist/types/plugins/community/swarm/config.d.ts +6 -0
  177. package/dist/types/plugins/community/swarm/constants.d.ts +8 -0
  178. package/dist/types/plugins/community/swarm/index.d.ts +2 -0
  179. package/dist/types/plugins/community/swarm/model.d.ts +23 -0
  180. package/dist/types/plugins/community/swarm/tools/CreatePostageStampTool.d.ts +47 -0
  181. package/dist/types/plugins/community/swarm/tools/DownloadDataTool.d.ts +35 -0
  182. package/dist/types/plugins/community/swarm/tools/DownloadFilesTool.d.ts +41 -0
  183. package/dist/types/plugins/community/swarm/tools/ExtendPostageStampTool.d.ts +47 -0
  184. package/dist/types/plugins/community/swarm/tools/GetPostageStampTool.d.ts +35 -0
  185. package/dist/types/plugins/community/swarm/tools/ListPostageStampsTool.d.ts +53 -0
  186. package/dist/types/plugins/community/swarm/tools/QueryUploadProgressTool.d.ts +35 -0
  187. package/dist/types/plugins/community/swarm/tools/ReadFeedTool.d.ts +41 -0
  188. package/dist/types/plugins/community/swarm/tools/UpdateFeedTool.d.ts +47 -0
  189. package/dist/types/plugins/community/swarm/tools/UploadDataTool.d.ts +47 -0
  190. package/dist/types/plugins/community/swarm/tools/UploadFileTool.d.ts +53 -0
  191. package/dist/types/plugins/community/swarm/tools/UploadFolderTool.d.ts +47 -0
  192. package/dist/types/plugins/community/swarm/utils.d.ts +22 -0
  193. package/dist/types/plugins/index.d.ts +1 -0
  194. package/package.json +37 -27
  195. package/src/index.ts +1 -0
  196. package/src/plugins/community/swarm/README.md +279 -0
  197. package/src/plugins/community/swarm/SwarmPlugin.ts +178 -0
  198. package/src/plugins/community/swarm/__tests__/SwarmPlugin.mocks.ts +105 -0
  199. package/src/plugins/community/swarm/__tests__/SwarmPlugin.test.ts +93 -0
  200. package/src/plugins/community/swarm/__tests__/tools/CreatePostageStampTool.test.ts +152 -0
  201. package/src/plugins/community/swarm/__tests__/tools/DownloadDataTool.test.ts +93 -0
  202. package/src/plugins/community/swarm/__tests__/tools/DownloadFilesTool.test.ts +163 -0
  203. package/src/plugins/community/swarm/__tests__/tools/ExtendPostageStampTool.test.ts +132 -0
  204. package/src/plugins/community/swarm/__tests__/tools/GetPostageStampTool.test.ts +83 -0
  205. package/src/plugins/community/swarm/__tests__/tools/ListPostageStampsTool.test.ts +219 -0
  206. package/src/plugins/community/swarm/__tests__/tools/QueryUploadProgressTool.test.ts +169 -0
  207. package/src/plugins/community/swarm/__tests__/tools/ReadFeedTool.test.ts +133 -0
  208. package/src/plugins/community/swarm/__tests__/tools/SwarmTool.mocks.ts +67 -0
  209. package/src/plugins/community/swarm/__tests__/tools/UpdateFeedTool.test.ts +148 -0
  210. package/src/plugins/community/swarm/__tests__/tools/UploadDataTool.test.ts +125 -0
  211. package/src/plugins/community/swarm/__tests__/tools/UploadFileTool.test.ts +194 -0
  212. package/src/plugins/community/swarm/__tests__/tools/UploadFolderTool.test.ts +118 -0
  213. package/src/plugins/community/swarm/config.ts +6 -0
  214. package/src/plugins/community/swarm/constants.ts +12 -0
  215. package/src/plugins/community/swarm/index.ts +2 -0
  216. package/src/plugins/community/swarm/model.ts +23 -0
  217. package/src/plugins/community/swarm/tools/CreatePostageStampTool.ts +137 -0
  218. package/src/plugins/community/swarm/tools/DownloadDataTool.ts +79 -0
  219. package/src/plugins/community/swarm/tools/DownloadFilesTool.ts +155 -0
  220. package/src/plugins/community/swarm/tools/ExtendPostageStampTool.ts +112 -0
  221. package/src/plugins/community/swarm/tools/GetPostageStampTool.ts +92 -0
  222. package/src/plugins/community/swarm/tools/ListPostageStampsTool.ts +124 -0
  223. package/src/plugins/community/swarm/tools/QueryUploadProgressTool.ts +109 -0
  224. package/src/plugins/community/swarm/tools/ReadFeedTool.ts +110 -0
  225. package/src/plugins/community/swarm/tools/UpdateFeedTool.ts +149 -0
  226. package/src/plugins/community/swarm/tools/UploadDataTool.ts +109 -0
  227. package/src/plugins/community/swarm/tools/UploadFileTool.ts +163 -0
  228. package/src/plugins/community/swarm/tools/UploadFolderTool.ts +150 -0
  229. package/src/plugins/community/swarm/utils.ts +172 -0
  230. package/src/plugins/index.ts +1 -0
  231. package/cli/dist/CLIApp.d.ts +0 -11
  232. package/cli/dist/CLIApp.d.ts.map +0 -1
  233. package/cli/dist/CLIApp.js +0 -128
  234. package/cli/dist/CLIApp.js.map +0 -1
  235. package/cli/dist/LocalConversationalAgent.d.ts +0 -37
  236. package/cli/dist/LocalConversationalAgent.js +0 -58
  237. package/cli/dist/app.d.ts +0 -18
  238. package/cli/dist/app.d.ts.map +0 -1
  239. package/cli/dist/app.js +0 -14
  240. package/cli/dist/app.js.map +0 -1
  241. package/cli/dist/cli.d.ts +0 -3
  242. package/cli/dist/cli.d.ts.map +0 -1
  243. package/cli/dist/cli.js +0 -87
  244. package/cli/dist/cli.js.map +0 -1
  245. package/cli/dist/components/AppContainer.d.ts +0 -16
  246. package/cli/dist/components/AppContainer.js +0 -24
  247. package/cli/dist/components/AppScreens.d.ts +0 -2
  248. package/cli/dist/components/AppScreens.js +0 -259
  249. package/cli/dist/components/ChatScreen.d.ts +0 -21
  250. package/cli/dist/components/ChatScreen.d.ts.map +0 -1
  251. package/cli/dist/components/ChatScreen.js +0 -40
  252. package/cli/dist/components/ChatScreen.js.map +0 -1
  253. package/cli/dist/components/DebugLoadingScreen.d.ts +0 -5
  254. package/cli/dist/components/DebugLoadingScreen.js +0 -31
  255. package/cli/dist/components/LoadingScreen.d.ts +0 -3
  256. package/cli/dist/components/LoadingScreen.d.ts.map +0 -1
  257. package/cli/dist/components/LoadingScreen.js +0 -17
  258. package/cli/dist/components/LoadingScreen.js.map +0 -1
  259. package/cli/dist/components/LoadingScreenDebug.d.ts +0 -5
  260. package/cli/dist/components/LoadingScreenDebug.js +0 -27
  261. package/cli/dist/components/MCPConfigScreen.d.ts +0 -28
  262. package/cli/dist/components/MCPConfigScreen.d.ts.map +0 -1
  263. package/cli/dist/components/MCPConfigScreen.js +0 -186
  264. package/cli/dist/components/MCPConfigScreen.js.map +0 -1
  265. package/cli/dist/components/ScreenRouter.d.ts +0 -13
  266. package/cli/dist/components/ScreenRouter.d.ts.map +0 -1
  267. package/cli/dist/components/ScreenRouter.js +0 -23
  268. package/cli/dist/components/ScreenRouter.js.map +0 -1
  269. package/cli/dist/components/SetupScreen.d.ts +0 -16
  270. package/cli/dist/components/SetupScreen.d.ts.map +0 -1
  271. package/cli/dist/components/SetupScreen.js +0 -67
  272. package/cli/dist/components/SetupScreen.js.map +0 -1
  273. package/cli/dist/components/SingleLoadingScreen.d.ts +0 -5
  274. package/cli/dist/components/SingleLoadingScreen.js +0 -27
  275. package/cli/dist/components/StatusBadge.d.ts +0 -10
  276. package/cli/dist/components/StatusBadge.d.ts.map +0 -1
  277. package/cli/dist/components/StatusBadge.js +0 -24
  278. package/cli/dist/components/StatusBadge.js.map +0 -1
  279. package/cli/dist/components/TerminalWindow.d.ts +0 -9
  280. package/cli/dist/components/TerminalWindow.d.ts.map +0 -1
  281. package/cli/dist/components/TerminalWindow.js +0 -19
  282. package/cli/dist/components/TerminalWindow.js.map +0 -1
  283. package/cli/dist/components/WelcomeScreen.d.ts +0 -12
  284. package/cli/dist/components/WelcomeScreen.d.ts.map +0 -1
  285. package/cli/dist/components/WelcomeScreen.js +0 -47
  286. package/cli/dist/components/WelcomeScreen.js.map +0 -1
  287. package/cli/dist/context/AppContext.d.ts +0 -68
  288. package/cli/dist/context/AppContext.js +0 -363
  289. package/cli/dist/headless-runner.d.ts +0 -17
  290. package/cli/dist/headless-runner.d.ts.map +0 -1
  291. package/cli/dist/headless-runner.js +0 -128
  292. package/cli/dist/headless-runner.js.map +0 -1
  293. package/cli/dist/hooks/useInitializeAgent.d.ts +0 -19
  294. package/cli/dist/hooks/useInitializeAgent.d.ts.map +0 -1
  295. package/cli/dist/hooks/useInitializeAgent.js +0 -29
  296. package/cli/dist/hooks/useInitializeAgent.js.map +0 -1
  297. package/cli/dist/hooks/useStableState.d.ts +0 -38
  298. package/cli/dist/hooks/useStableState.d.ts.map +0 -1
  299. package/cli/dist/hooks/useStableState.js +0 -69
  300. package/cli/dist/hooks/useStableState.js.map +0 -1
  301. package/cli/dist/managers/AgentManager.d.ts +0 -58
  302. package/cli/dist/managers/AgentManager.d.ts.map +0 -1
  303. package/cli/dist/managers/AgentManager.js +0 -121
  304. package/cli/dist/managers/AgentManager.js.map +0 -1
  305. package/cli/dist/managers/ConfigManager.d.ts +0 -54
  306. package/cli/dist/managers/ConfigManager.d.ts.map +0 -1
  307. package/cli/dist/managers/ConfigManager.js +0 -188
  308. package/cli/dist/managers/ConfigManager.js.map +0 -1
  309. package/cli/dist/types.d.ts +0 -52
  310. package/cli/dist/types.d.ts.map +0 -1
  311. package/cli/dist/types.js +0 -34
  312. package/cli/dist/types.js.map +0 -1
@@ -1,251 +1,966 @@
1
- import { StructuredTool } from "@langchain/core/tools";
2
- import { z } from "zod";
1
+ import { AgentExecutor } from "langchain/agents";
2
+ import { z, ZodError } from "zod";
3
+ import { FormGenerator } from "./index11.js";
4
+ import { FormEngine } from "./index12.js";
3
5
  import { Logger } from "@hashgraphonline/standards-sdk";
4
6
  import { isFormValidatable } from "@hashgraphonline/standards-agent-kit";
5
- class FormValidatingToolWrapper extends StructuredTool {
6
- constructor(originalTool, formGenerator, config = {}) {
7
- super();
8
- this.originalTool = originalTool;
9
- this.formGenerator = formGenerator;
10
- this.validationConfig = config;
11
- this.logger = new Logger({ module: "FormValidatingToolWrapper" });
12
- this.name = originalTool.name;
13
- this.description = originalTool.description;
14
- this.schema = originalTool.schema;
15
- this.logger.info(`🔧 FormValidatingToolWrapper created for tool: ${this.name}`, {
16
- originalToolName: originalTool.name,
17
- originalToolType: originalTool.constructor.name,
18
- wrapperType: this.constructor.name
7
+ import { ResponseFormatter } from "./index36.js";
8
+ const globalPendingForms = /* @__PURE__ */ new Map();
9
+ class FormAwareAgentExecutor extends AgentExecutor {
10
+ constructor(...args) {
11
+ super(...args);
12
+ this.pendingForms = /* @__PURE__ */ new Map();
13
+ this.formGenerator = new FormGenerator();
14
+ this.formEngine = new FormEngine(
15
+ new Logger({ module: "FormAwareAgentExecutor.FormEngine" })
16
+ );
17
+ this.formLogger = new Logger({ module: "FormAwareAgentExecutor" });
18
+ this.parameterPreprocessingCallback = void 0;
19
+ }
20
+ /**
21
+ * Type guard to check if a Zod type is a ZodObject
22
+ */
23
+ isZodObject(schema) {
24
+ return schema instanceof z.ZodObject;
25
+ }
26
+ /**
27
+ * Type guard to check if metadata has hashLinkBlock
28
+ */
29
+ hasHashLinkBlock(metadata) {
30
+ return typeof metadata === "object" && metadata !== null && "hashLinkBlock" in metadata && typeof metadata.hashLinkBlock === "object" && metadata.hashLinkBlock !== null;
31
+ }
32
+ /**
33
+ * Set parameter preprocessing callback
34
+ */
35
+ setParameterPreprocessingCallback(callback) {
36
+ this.parameterPreprocessingCallback = callback;
37
+ }
38
+ /**
39
+ * BULLETPROOF TOOL INTERCEPTION
40
+ * Override the single-step execution to intercept tool calls BEFORE LangChain processes them
41
+ */
42
+ async _takeNextStep(nameToolMap, inputs, intermediateSteps, runManager, config) {
43
+ this.formLogger.info("🛡️ BULLETPROOF INTERCEPTION: _takeNextStep called", {
44
+ availableTools: Object.keys(nameToolMap),
45
+ inputKeys: Object.keys(inputs)
46
+ });
47
+ const result = await this.agent.plan(
48
+ intermediateSteps,
49
+ inputs,
50
+ runManager?.getChild()
51
+ );
52
+ if ("returnValues" in result) {
53
+ this.formLogger.info("Agent returned finish action, passing through");
54
+ return result;
55
+ }
56
+ const action = result;
57
+ const toolName = action.tool;
58
+ const toolInput = action.toolInput;
59
+ this.formLogger.info(`🎯 INTERCEPTING TOOL CALL: ${toolName}`, {
60
+ toolInput,
61
+ hasInNameToolMap: toolName in nameToolMap,
62
+ toolInputKeys: Object.keys(toolInput || {})
19
63
  });
64
+ const tool = nameToolMap[toolName] || this.tools.find((t) => t.name === toolName);
65
+ if (!tool) {
66
+ this.formLogger.error(`Tool ${toolName} not found in registry`);
67
+ throw new Error(`Tool "${toolName}" not found`);
68
+ }
69
+ let shouldGenerateForm = false;
70
+ if (isFormValidatable(tool)) {
71
+ this.formLogger.info(
72
+ `🔍 Tool ${toolName} implements FormValidatable, checking shouldGenerateForm()`,
73
+ {
74
+ toolInput
75
+ }
76
+ );
77
+ try {
78
+ shouldGenerateForm = tool.shouldGenerateForm(toolInput);
79
+ this.formLogger.info(
80
+ `FormValidatable.shouldGenerateForm() result: ${shouldGenerateForm}`,
81
+ {
82
+ toolName,
83
+ toolInput
84
+ }
85
+ );
86
+ } catch (error) {
87
+ this.formLogger.error(
88
+ `Error calling shouldGenerateForm() on ${toolName}:`,
89
+ error
90
+ );
91
+ shouldGenerateForm = false;
92
+ }
93
+ }
94
+ if (shouldGenerateForm) {
95
+ this.formLogger.info(`🚨 FORM GENERATION TRIGGERED for ${toolName}`);
96
+ try {
97
+ let schemaToUse;
98
+ let isFocusedSchema = false;
99
+ if (isFormValidatable(tool)) {
100
+ this.formLogger.info(
101
+ `🎯 Tool ${toolName} is FormValidatable, attempting to get focused schema`
102
+ );
103
+ try {
104
+ const focusedSchema = tool.getFormSchema();
105
+ if (focusedSchema) {
106
+ schemaToUse = focusedSchema;
107
+ isFocusedSchema = true;
108
+ this.formLogger.info(
109
+ `✅ Successfully obtained focused schema for ${toolName}`
110
+ );
111
+ } else {
112
+ this.formLogger.warn(
113
+ `getFormSchema() returned null/undefined for ${toolName}, using default schema`
114
+ );
115
+ schemaToUse = tool.schema;
116
+ isFocusedSchema = false;
117
+ }
118
+ } catch (error) {
119
+ this.formLogger.error(
120
+ `Failed to get focused schema from ${toolName}:`,
121
+ error
122
+ );
123
+ this.formLogger.info(
124
+ `Falling back to default schema for ${toolName}`
125
+ );
126
+ schemaToUse = tool.schema;
127
+ isFocusedSchema = false;
128
+ }
129
+ } else {
130
+ this.formLogger.info(
131
+ `Tool ${toolName} is not FormValidatable, using default schema`
132
+ );
133
+ schemaToUse = tool.schema;
134
+ isFocusedSchema = false;
135
+ }
136
+ let schemaFieldCount = "unknown";
137
+ try {
138
+ if (this.isZodObject(schemaToUse)) {
139
+ const zodObject = schemaToUse;
140
+ const shape = zodObject.shape;
141
+ if (shape && typeof shape === "object") {
142
+ schemaFieldCount = Object.keys(shape).length.toString();
143
+ }
144
+ }
145
+ } catch {
146
+ }
147
+ this.formLogger.info(
148
+ `📋 Generating form with ${isFocusedSchema ? "FOCUSED" : "DEFAULT"} schema`,
149
+ {
150
+ toolName,
151
+ schemaType: schemaToUse?.constructor?.name,
152
+ estimatedFieldCount: schemaFieldCount,
153
+ isFocusedSchema
154
+ }
155
+ );
156
+ let missingFields;
157
+ if (isFocusedSchema) {
158
+ this.formLogger.info(
159
+ `⭐ Using focused schema - letting FormGenerator determine fields from schema`
160
+ );
161
+ missingFields = void 0;
162
+ } else {
163
+ missingFields = /* @__PURE__ */ new Set();
164
+ if (this.isZodObject(schemaToUse)) {
165
+ const zodObject = schemaToUse;
166
+ const shape = zodObject.shape || {};
167
+ for (const fieldName of Object.keys(shape)) {
168
+ const value = (toolInput || {})[fieldName];
169
+ const isEmpty = isFormValidatable(tool) && tool.isFieldEmpty ? tool.isFieldEmpty(fieldName, value) : value === void 0 || value === "" || value === null || Array.isArray(value) && value.length === 0;
170
+ const isRequired = this.isFieldRequired(schemaToUse, fieldName);
171
+ const isEssential = isFormValidatable(tool) && tool.getEssentialFields ? tool.getEssentialFields().includes(fieldName) : false;
172
+ this.formLogger.info(`🔍 Field analysis: ${fieldName}`, {
173
+ value,
174
+ isEmpty,
175
+ isRequired,
176
+ isEssential,
177
+ willAddToMissingFields: isEmpty && (isRequired || isEssential)
178
+ });
179
+ if (isEmpty && (isRequired || isEssential)) {
180
+ missingFields.add(fieldName);
181
+ }
182
+ }
183
+ }
184
+ this.formLogger.info(`📋 Missing fields analysis complete`, {
185
+ totalFields: this.isZodObject(schemaToUse) ? Object.keys(schemaToUse.shape).length : 0,
186
+ missingFieldsCount: missingFields.size,
187
+ missingFields: Array.from(missingFields)
188
+ });
189
+ }
190
+ const formMessage = await this.formGenerator.generateFormFromSchema(
191
+ schemaToUse,
192
+ toolInput,
193
+ {
194
+ toolName,
195
+ toolDescription: tool.description
196
+ },
197
+ missingFields
198
+ );
199
+ if (this.isZodObject(schemaToUse)) {
200
+ try {
201
+ const { jsonSchema, uiSchema } = this.formGenerator.generateJsonSchemaForm(
202
+ schemaToUse,
203
+ toolInput,
204
+ missingFields
205
+ );
206
+ formMessage.jsonSchema = jsonSchema;
207
+ formMessage.uiSchema = uiSchema;
208
+ } catch (error) {
209
+ this.formLogger.warn(
210
+ "Failed to generate JSON Schema for RJSF:",
211
+ error
212
+ );
213
+ }
214
+ }
215
+ formMessage.partialInput = toolInput;
216
+ const formData = {
217
+ toolName,
218
+ originalInput: inputs,
219
+ originalToolInput: toolInput,
220
+ schema: schemaToUse,
221
+ toolRef: tool,
222
+ originalToolRef: tool.originalTool
223
+ };
224
+ this.pendingForms.set(formMessage.id, formData);
225
+ globalPendingForms.set(formMessage.id, formData);
226
+ this.formLogger.info(`✅ FORM INTERCEPT SUCCESS for ${toolName}`);
227
+ const formResult = {
228
+ requiresForm: true,
229
+ formMessage
230
+ };
231
+ return [
232
+ {
233
+ action,
234
+ observation: JSON.stringify(formResult)
235
+ }
236
+ ];
237
+ } catch (error) {
238
+ this.formLogger.error(`Form generation failed for ${toolName}:`, error);
239
+ }
240
+ }
241
+ this.formLogger.info(
242
+ `⚪ Passing through to normal tool execution for ${toolName}`
243
+ );
244
+ if (this.parameterPreprocessingCallback && toolInput) {
245
+ this.formLogger.info(
246
+ `🔄 Applying parameter preprocessing for ${toolName}`
247
+ );
248
+ try {
249
+ const preprocessedInput = await this.parameterPreprocessingCallback(
250
+ toolName,
251
+ toolInput
252
+ );
253
+ if (preprocessedInput && typeof preprocessedInput === "object" && "__requestForm" in preprocessedInput) {
254
+ const rf = preprocessedInput.__requestForm;
255
+ const formId = rf.id || `form_${Date.now()}_${Math.random().toString(36).slice(2)}`;
256
+ const formMessage = {
257
+ type: "form",
258
+ id: formId,
259
+ originalPrompt: "Parameter validation required",
260
+ toolName,
261
+ formConfig: {
262
+ title: rf.title || "Complete required parameters",
263
+ description: rf.description || "One or more parameters require confirmation. Please review and submit.",
264
+ submitLabel: rf.submitLabel || "Continue",
265
+ fields: (rf.fields || []).map((f) => {
266
+ const allowedTypes = [
267
+ "text",
268
+ "number",
269
+ "select",
270
+ "checkbox",
271
+ "textarea"
272
+ ];
273
+ const resolvedType = allowedTypes.includes(
274
+ f.type
275
+ ) ? f.type : "text";
276
+ return {
277
+ name: f.name,
278
+ label: f.label,
279
+ type: resolvedType,
280
+ required: f.required ?? true,
281
+ options: f.options
282
+ };
283
+ })
284
+ }
285
+ };
286
+ const resolvedSchema = isFormValidatable(tool) ? (() => {
287
+ try {
288
+ const s = tool.getFormSchema();
289
+ return s || tool.schema;
290
+ } catch {
291
+ return tool.schema;
292
+ }
293
+ })() : tool.schema;
294
+ this.pendingForms.set(formId, {
295
+ toolName,
296
+ originalInput: inputs,
297
+ originalToolInput: toolInput,
298
+ schema: resolvedSchema,
299
+ toolRef: tool,
300
+ originalToolRef: tool.originalTool
301
+ });
302
+ globalPendingForms.set(formId, {
303
+ toolName,
304
+ originalInput: inputs,
305
+ originalToolInput: toolInput,
306
+ schema: resolvedSchema
307
+ });
308
+ return [
309
+ {
310
+ action,
311
+ observation: JSON.stringify({ requiresForm: true, formMessage })
312
+ }
313
+ ];
314
+ }
315
+ if (JSON.stringify(preprocessedInput) !== JSON.stringify(toolInput)) {
316
+ this.formLogger.info(`📝 Parameters preprocessed for ${toolName}:`, {
317
+ original: Object.keys(toolInput),
318
+ preprocessed: Object.keys(preprocessedInput),
319
+ hasChanges: true
320
+ });
321
+ try {
322
+ action.toolInput = preprocessedInput;
323
+ } catch {
324
+ }
325
+ } else {
326
+ this.formLogger.debug(`No parameter changes needed for ${toolName}`);
327
+ }
328
+ } catch (preprocessError) {
329
+ this.formLogger.warn(
330
+ `Parameter preprocessing failed for ${toolName}, using original parameters:`,
331
+ preprocessError
332
+ );
333
+ }
334
+ }
335
+ return super._takeNextStep(
336
+ nameToolMap,
337
+ inputs,
338
+ intermediateSteps,
339
+ runManager,
340
+ config
341
+ );
20
342
  }
21
343
  /**
22
- * Validate the input against the schema
344
+ * Helper to determine if a field is required in the schema
23
345
  */
24
- validateInput(input) {
346
+ isFieldRequired(schema, fieldPath) {
347
+ if (!schema || !fieldPath) {
348
+ return false;
349
+ }
25
350
  try {
26
- this.schema.parse(input);
27
- return { isValid: true };
28
- } catch (error) {
29
- if (error instanceof z.ZodError) {
30
- const errors = error.errors.filter((err) => {
31
- const fieldName = err.path[0];
32
- return !this.validationConfig.skipFields?.includes(fieldName);
33
- }).map((err) => `${err.path.join(".")}: ${err.message}`);
34
- return { isValid: false, errors };
351
+ const obj = schema;
352
+ const def = obj._def;
353
+ if (!def || def.typeName !== "ZodObject") {
354
+ return false;
355
+ }
356
+ const rawShape = typeof def.shape === "function" ? def.shape() : def.shape;
357
+ if (!rawShape || typeof rawShape !== "object") {
358
+ return false;
359
+ }
360
+ const shape = rawShape;
361
+ const fieldSchema = shape[fieldPath];
362
+ if (!fieldSchema) {
363
+ return false;
364
+ }
365
+ const unwrapOptional = (s) => {
366
+ const inner = s._def;
367
+ if (inner && inner.typeName === "ZodOptional" && inner.innerType) {
368
+ return inner.innerType;
369
+ }
370
+ return s;
371
+ };
372
+ const unwrapped = unwrapOptional(fieldSchema);
373
+ const fdef = unwrapped._def;
374
+ if (!fdef) {
375
+ return true;
376
+ }
377
+ if (fdef.typeName === "ZodOptional" || fdef.typeName === "ZodDefault") {
378
+ return false;
35
379
  }
36
- return { isValid: false, errors: ["Validation failed"] };
380
+ if (fdef.defaultValue !== void 0) {
381
+ return false;
382
+ }
383
+ return true;
384
+ } catch (error) {
385
+ this.formLogger.debug(
386
+ `Could not determine if field ${fieldPath} is required:`,
387
+ error
388
+ );
37
389
  }
390
+ return false;
38
391
  }
39
392
  /**
40
- * Gets the shape keys from the schema if it's a ZodObject
393
+ * Override _call to intercept Zod validation errors at the execution level
41
394
  */
42
- getSchemaShape() {
43
- if (this.isZodObject(this.schema)) {
44
- return Object.keys(this.schema.shape);
395
+ async _call(inputs) {
396
+ try {
397
+ const result = await super._call(inputs);
398
+ if (result.intermediateSteps && Array.isArray(result.intermediateSteps)) {
399
+ for (const step of result.intermediateSteps) {
400
+ if (step.observation) {
401
+ try {
402
+ const parsed = typeof step.observation === "string" ? JSON.parse(step.observation) : step.observation;
403
+ if (parsed.requiresForm && parsed.formMessage) {
404
+ this.formLogger.info("Tool requested form generation", {
405
+ toolName: step.action?.tool,
406
+ hasForm: true
407
+ });
408
+ const actionToolName = step.action?.tool || "unknown";
409
+ const toolInstance = this.tools.find(
410
+ (t) => t.name === actionToolName
411
+ );
412
+ const originalToolCandidate = toolInstance || {};
413
+ const pf = {
414
+ toolName: actionToolName,
415
+ originalInput: inputs,
416
+ originalToolInput: step.action?.toolInput,
417
+ schema: null,
418
+ toolRef: toolInstance,
419
+ originalToolRef: originalToolCandidate?.originalTool
420
+ };
421
+ this.pendingForms.set(parsed.formMessage.id, pf);
422
+ globalPendingForms.set(parsed.formMessage.id, pf);
423
+ return {
424
+ ...result,
425
+ requiresForm: true,
426
+ formMessage: parsed.formMessage,
427
+ output: parsed.message || "Please complete the form to continue."
428
+ };
429
+ }
430
+ if (parsed.hashLinkBlock || parsed.success && parsed.inscription && parsed.hashLinkBlock) {
431
+ this.formLogger.info("Tool returned HashLink blocks", {
432
+ toolName: step.action?.tool,
433
+ hasHashLink: true,
434
+ blockId: parsed.hashLinkBlock?.blockId
435
+ });
436
+ const hashLinkResponse = this.processHashLinkResponse(parsed);
437
+ return {
438
+ ...result,
439
+ hasHashLinkBlocks: true,
440
+ hashLinkBlock: hashLinkResponse.hashLinkBlock,
441
+ output: hashLinkResponse.message
442
+ };
443
+ }
444
+ } catch {
445
+ }
446
+ }
447
+ }
448
+ }
449
+ return result;
450
+ } catch (error) {
451
+ if (error instanceof ZodError) {
452
+ this.formLogger.info("Intercepted ZodError during agent execution");
453
+ return this.handleValidationError(error, inputs, []);
454
+ }
455
+ throw error;
45
456
  }
46
- return [];
47
457
  }
48
458
  /**
49
- * Executes the wrapped tool's original implementation directly, bypassing wrapper logic.
459
+ * Handles Zod validation errors by generating forms
50
460
  */
51
- async executeOriginal(input, runManager) {
52
- const tool = this.originalTool;
53
- if ("_call" in tool && typeof tool._call === "function") {
54
- return tool._call(input, runManager);
55
- }
56
- if ("call" in tool && typeof tool.call === "function") {
57
- return tool.call(input, runManager);
461
+ async handleValidationError(error, inputs, intermediateSteps) {
462
+ this.formLogger.info("Zod validation error detected, generating form", {
463
+ errorIssues: error.issues.length,
464
+ inputKeys: Object.keys(inputs)
465
+ });
466
+ let toolInfo = this.extractToolInfoFromError(
467
+ error,
468
+ inputs,
469
+ intermediateSteps
470
+ );
471
+ if (!toolInfo) {
472
+ this.formLogger.warn(
473
+ "Could not extract tool info from validation error, trying fallback detection"
474
+ );
475
+ const fallbackTool = this.detectToolFromErrorContext(error);
476
+ if (!fallbackTool) {
477
+ this.formLogger.error(
478
+ "No tool detected for form generation, rethrowing error"
479
+ );
480
+ throw error;
481
+ }
482
+ toolInfo = fallbackTool;
58
483
  }
59
- throw new Error("Original tool has no callable implementation");
484
+ this.formLogger.info("Generating form for tool:", {
485
+ toolName: toolInfo.toolName,
486
+ hasSchema: !!toolInfo.schema
487
+ });
488
+ const formMessage = this.formGenerator.generateFormFromError(
489
+ error,
490
+ toolInfo.schema,
491
+ toolInfo.toolName,
492
+ inputs.input || ""
493
+ );
494
+ this.pendingForms.set(formMessage.id, {
495
+ toolName: toolInfo.toolName,
496
+ originalInput: inputs,
497
+ schema: toolInfo.schema
498
+ });
499
+ globalPendingForms.set(formMessage.id, {
500
+ toolName: toolInfo.toolName,
501
+ originalInput: inputs,
502
+ schema: toolInfo.schema
503
+ });
504
+ return {
505
+ output: this.formatFormResponse(formMessage),
506
+ formMessage,
507
+ requiresForm: true,
508
+ intermediateSteps: intermediateSteps || []
509
+ };
60
510
  }
61
511
  /**
62
- * Provides access to the wrapped tool instance for executors that want to bypass the wrapper.
512
+ * Get a copy of pending forms for preservation during executor recreation
63
513
  */
64
- getOriginalTool() {
65
- return this.originalTool;
514
+ getPendingForms() {
515
+ return new Map(this.pendingForms);
66
516
  }
67
517
  /**
68
- * Checks if tool implements FormValidatable method
518
+ * Restore pending forms from a previous executor instance
69
519
  */
70
- hasFormValidatableMethod(tool, methodName) {
71
- return tool !== null && typeof tool === "object" && methodName in tool && typeof tool[methodName] === "function";
520
+ restorePendingForms(forms) {
521
+ for (const [formId, formData] of forms) {
522
+ this.pendingForms.set(formId, formData);
523
+ }
72
524
  }
73
525
  /**
74
- * Expose FormValidatable methods by delegating to the underlying tool when available.
526
+ * Processes form submission and continues tool execution
75
527
  */
76
- getFormSchema() {
77
- if (this.hasFormValidatableMethod(this.originalTool, "getFormSchema")) {
78
- return this.originalTool.getFormSchema();
528
+ async processFormSubmission(submission) {
529
+ this.formLogger.info(
530
+ "🚀 FormAwareAgentExecutor.processFormSubmission called!",
531
+ {
532
+ submissionFormId: submission.formId,
533
+ submissionToolName: submission.toolName
534
+ }
535
+ );
536
+ if (!submission) {
537
+ throw new Error("Form submission is null or undefined");
79
538
  }
80
- return this.schema;
81
- }
82
- getEssentialFields() {
83
- if (this.hasFormValidatableMethod(this.originalTool, "getEssentialFields")) {
84
- return this.originalTool.getEssentialFields();
539
+ if (!submission.formId) {
540
+ throw new Error("Form submission missing formId");
85
541
  }
86
- return [];
87
- }
88
- isFieldEmpty(fieldName, value) {
89
- if (this.hasFormValidatableMethod(this.originalTool, "isFieldEmpty")) {
90
- return this.originalTool.isFieldEmpty(fieldName, value);
542
+ if (!submission.parameters || submission.parameters === null || typeof submission.parameters !== "object" || Array.isArray(submission.parameters)) {
543
+ throw new Error(
544
+ `Form submission parameters are invalid: ${typeof submission.parameters}, isNull: ${submission.parameters === null}, isArray: ${Array.isArray(
545
+ submission.parameters
546
+ )}, parameters: ${JSON.stringify(submission.parameters)}`
547
+ );
91
548
  }
92
- if (value === void 0 || value === null || value === "") {
93
- return true;
549
+ this.formLogger.info("Processing form submission:", {
550
+ formId: submission.formId,
551
+ toolName: submission.toolName,
552
+ parameterKeys: Object.keys(submission.parameters),
553
+ parametersType: typeof submission.parameters,
554
+ parametersIsNull: submission.parameters === null,
555
+ parametersIsUndefined: submission.parameters === void 0,
556
+ hasContext: !!submission.context
557
+ });
558
+ let pendingForm = this.pendingForms.get(submission.formId);
559
+ if (!pendingForm) {
560
+ pendingForm = globalPendingForms.get(submission.formId);
561
+ if (!pendingForm) {
562
+ throw new Error(`No pending form found for ID: ${submission.formId}`);
563
+ }
94
564
  }
95
- if (Array.isArray(value) && value.length === 0) {
96
- return true;
565
+ this.pendingForms.delete(submission.formId);
566
+ globalPendingForms.delete(submission.formId);
567
+ const tool = pendingForm.toolRef || this.tools.find((t) => t.name === pendingForm.toolName);
568
+ if (!tool) {
569
+ throw new Error(
570
+ `Tool not found for form submission: ${pendingForm.toolName}`
571
+ );
97
572
  }
98
- return false;
99
- }
100
- /**
101
- * Calculates which fields are missing from the input
102
- */
103
- calculateMissingFields(input, isCustom) {
104
- const missingFields = /* @__PURE__ */ new Set();
105
- if (!isCustom) {
106
- return missingFields;
573
+ let baseToolInput = {};
574
+ try {
575
+ if (pendingForm.originalToolInput && typeof pendingForm.originalToolInput === "object") {
576
+ baseToolInput = {
577
+ ...pendingForm.originalToolInput
578
+ };
579
+ }
580
+ } catch (error) {
581
+ this.formLogger.warn(
582
+ "Failed to extract base tool input, using empty object:",
583
+ error
584
+ );
585
+ baseToolInput = {};
107
586
  }
108
- const essentialFields = this.getEssentialFields();
109
- for (const fieldName of essentialFields) {
110
- const value = input[fieldName];
111
- if (this.isFieldEmpty(fieldName, value)) {
112
- missingFields.add(fieldName);
587
+ let submissionData = {};
588
+ try {
589
+ if (submission.parameters && typeof submission.parameters === "object") {
590
+ submissionData = {
591
+ ...submission.parameters
592
+ };
593
+ }
594
+ } catch (error) {
595
+ this.formLogger.warn(
596
+ "Failed to extract submission parameters, using empty object:",
597
+ error
598
+ );
599
+ submissionData = {};
600
+ }
601
+ const mergedToolInput = {};
602
+ try {
603
+ Object.keys(baseToolInput).forEach((key) => {
604
+ const value = baseToolInput[key];
605
+ if (value !== void 0 && value !== null) {
606
+ mergedToolInput[key] = value;
607
+ }
608
+ });
609
+ Object.keys(submissionData).forEach((key) => {
610
+ const value = submissionData[key];
611
+ if (value !== void 0 && value !== null) {
612
+ mergedToolInput[key] = value;
613
+ }
614
+ });
615
+ mergedToolInput.renderForm = false;
616
+ mergedToolInput.__fromForm = true;
617
+ this.formLogger.info("Successfully merged tool input:", {
618
+ baseKeys: Object.keys(baseToolInput),
619
+ submissionKeys: Object.keys(submissionData),
620
+ mergedKeys: Object.keys(mergedToolInput)
621
+ });
622
+ } catch (error) {
623
+ this.formLogger.error("Failed to merge tool input data:", error);
624
+ throw new Error(
625
+ `Failed to merge tool input data: ${error instanceof Error ? error.message : "Unknown error"}`
626
+ );
627
+ }
628
+ try {
629
+ const maybeWrapper = tool;
630
+ let toolOutput;
631
+ if (typeof maybeWrapper.executeOriginal === "function") {
632
+ toolOutput = await maybeWrapper.executeOriginal(mergedToolInput);
633
+ } else if (typeof maybeWrapper.getOriginalTool === "function") {
634
+ const ot = maybeWrapper.getOriginalTool();
635
+ const otCall = ot;
636
+ if (ot && typeof otCall._call === "function") {
637
+ toolOutput = await otCall._call(mergedToolInput);
638
+ } else if (ot && typeof otCall.call === "function") {
639
+ toolOutput = await otCall.call(mergedToolInput);
640
+ } else {
641
+ const tcall = tool;
642
+ if (typeof tcall.call === "function") {
643
+ toolOutput = await tcall.call(mergedToolInput);
644
+ } else {
645
+ throw new Error(
646
+ "No callable tool implementation found for form submission"
647
+ );
648
+ }
649
+ }
650
+ } else if (maybeWrapper.originalTool && typeof maybeWrapper.originalTool._call === "function") {
651
+ toolOutput = await maybeWrapper.originalTool._call(mergedToolInput);
652
+ } else if (maybeWrapper.originalTool && typeof maybeWrapper.originalTool.call === "function") {
653
+ toolOutput = await maybeWrapper.originalTool.call(mergedToolInput);
654
+ } else if (typeof tool.call === "function") {
655
+ toolOutput = await tool.call(mergedToolInput);
656
+ } else {
657
+ throw new Error(
658
+ "No callable tool implementation found for form submission"
659
+ );
660
+ }
661
+ let responseMetadata = {};
662
+ let formattedOutput;
663
+ try {
664
+ const parsed = JSON.parse(toolOutput);
665
+ this.formLogger.info(
666
+ "✅ METADATA EXTRACTION: Successfully parsed JSON",
667
+ {
668
+ jsonKeys: Object.keys(parsed),
669
+ hasHashLinkBlock: !!parsed.hashLinkBlock
670
+ }
671
+ );
672
+ if (parsed && typeof parsed === "object") {
673
+ if (ResponseFormatter.isHashLinkResponse(parsed)) {
674
+ this.formLogger.info(
675
+ "🔗 HASHLINK DETECTED: Processing HashLink response separately to preserve metadata"
676
+ );
677
+ const parsedRecord = parsed;
678
+ responseMetadata = {
679
+ ...responseMetadata,
680
+ hashLinkBlock: parsedRecord.hashLinkBlock,
681
+ ...parsedRecord
682
+ };
683
+ formattedOutput = ResponseFormatter.formatHashLinkResponse(parsed);
684
+ this.formLogger.info(
685
+ "🔗 METADATA PRESERVED: HashLink metadata extracted for component rendering",
686
+ {
687
+ blockId: this.hasHashLinkBlock(responseMetadata) ? responseMetadata.hashLinkBlock.blockId : void 0,
688
+ hasTemplate: this.hasHashLinkBlock(responseMetadata) ? !!responseMetadata.hashLinkBlock.template : false
689
+ }
690
+ );
691
+ } else {
692
+ formattedOutput = ResponseFormatter.formatResponse(toolOutput);
693
+ responseMetadata = {
694
+ ...responseMetadata,
695
+ hashLinkBlock: parsed.hashLinkBlock,
696
+ ...parsed
697
+ };
698
+ }
699
+ } else {
700
+ formattedOutput = ResponseFormatter.formatResponse(toolOutput);
701
+ }
702
+ } catch (error) {
703
+ this.formLogger.warn(
704
+ "❌ METADATA EXTRACTION: Tool output is not JSON",
705
+ {
706
+ error: error instanceof Error ? error.message : "unknown error",
707
+ outputSample: typeof toolOutput === "string" ? toolOutput.substring(0, 200) : "not-string"
708
+ }
709
+ );
710
+ formattedOutput = ResponseFormatter.formatResponse(toolOutput);
711
+ }
712
+ return {
713
+ output: formattedOutput,
714
+ formCompleted: true,
715
+ originalFormId: submission.formId,
716
+ intermediateSteps: [],
717
+ metadata: responseMetadata,
718
+ rawToolOutput: toolOutput,
719
+ toolName: pendingForm.toolName
720
+ };
721
+ } catch (error) {
722
+ if (error instanceof ZodError) {
723
+ return this.handleValidationError(error, mergedToolInput, []);
113
724
  }
725
+ throw error;
114
726
  }
115
- return missingFields;
116
727
  }
117
728
  /**
118
- * Creates a form message with optional JSON schema
729
+ * Extracts tool information from the execution context
119
730
  */
120
- async createFormMessage(schema, input, missingFields) {
121
- let formMessage = await this.formGenerator.generateFormFromSchema(
122
- schema,
123
- input,
124
- {
125
- toolName: this.name,
126
- toolDescription: this.description
127
- },
128
- missingFields
129
- );
130
- if (this.isZodObject(schema)) {
131
- try {
132
- const { jsonSchema, uiSchema } = this.formGenerator.generateJsonSchemaForm(
133
- schema,
134
- input,
135
- missingFields
731
+ extractToolInfoFromError(error, inputs, intermediateSteps) {
732
+ try {
733
+ if (intermediateSteps.length > 0) {
734
+ const lastStep = intermediateSteps[intermediateSteps.length - 1];
735
+ if (lastStep.action && lastStep.action.tool) {
736
+ const tool = this.tools.find((t) => t.name === lastStep.action.tool);
737
+ if (tool && "schema" in tool) {
738
+ this.formLogger.info(
739
+ "Found tool from intermediate steps:",
740
+ lastStep.action.tool
741
+ );
742
+ return {
743
+ toolName: lastStep.action.tool,
744
+ schema: tool.schema
745
+ };
746
+ }
747
+ }
748
+ }
749
+ const inputSteps = inputs.intermediateSteps || [];
750
+ if (inputSteps.length > 0) {
751
+ const lastStep = inputSteps[inputSteps.length - 1];
752
+ let action;
753
+ if (Array.isArray(lastStep) && lastStep.length > 0) {
754
+ action = lastStep[0];
755
+ } else if (lastStep.action) {
756
+ action = lastStep.action;
757
+ } else {
758
+ action = lastStep;
759
+ }
760
+ if (action && action.tool) {
761
+ const tool = this.tools.find((t) => t.name === action.tool);
762
+ if (tool && "schema" in tool) {
763
+ this.formLogger.info("Found tool from input steps:", action.tool);
764
+ return {
765
+ toolName: action.tool,
766
+ schema: tool.schema
767
+ };
768
+ }
769
+ }
770
+ }
771
+ const toolFromContext = this.findToolFromContext(inputs);
772
+ if (toolFromContext) {
773
+ this.formLogger.info(
774
+ "Found tool from context:",
775
+ toolFromContext.toolName
136
776
  );
137
- formMessage = {
138
- ...formMessage,
139
- jsonSchema,
140
- uiSchema
141
- };
142
- } catch (error) {
143
- this.logger.warn("Failed to generate JSON Schema for RJSF:", error);
777
+ return toolFromContext;
144
778
  }
779
+ return null;
780
+ } catch (err) {
781
+ this.formLogger.error("Error extracting tool info:", err);
782
+ return null;
145
783
  }
146
- formMessage.partialInput = input;
147
- return formMessage;
148
784
  }
149
785
  /**
150
- * Type guard to check if a schema is a ZodObject
786
+ * Attempts to find tool from execution context
151
787
  */
152
- isZodObject(schema) {
153
- const def = schema._def;
154
- return !!(def && def.typeName === "ZodObject");
788
+ findToolFromContext(inputs) {
789
+ const inputText = inputs.input || "";
790
+ for (const tool of this.tools) {
791
+ const keywords = this.extractToolKeywords(tool.name);
792
+ if (keywords.some(
793
+ (keyword) => inputText.toLowerCase().includes(keyword.toLowerCase())
794
+ )) {
795
+ if ("schema" in tool) {
796
+ return {
797
+ toolName: tool.name,
798
+ schema: tool.schema
799
+ };
800
+ }
801
+ }
802
+ }
803
+ return null;
155
804
  }
156
805
  /**
157
- * Check if we should generate a form for this tool invocation
806
+ * Additional fallback to detect tool from error context
158
807
  */
159
- shouldGenerateForm(input) {
160
- this.logger.info(`shouldGenerateForm called for ${this.name}/${this.originalTool.name}`, {
161
- input,
162
- hasCustomValidation: !!this.validationConfig.customValidation
163
- });
164
- if (this.validationConfig.customValidation) {
165
- const result = !this.validationConfig.customValidation(input);
166
- this.logger.info(`Custom validation result: ${result}`);
167
- return result;
808
+ detectToolFromErrorContext(error) {
809
+ const errorPaths = error.issues.map((issue) => issue.path.join("."));
810
+ for (const tool of this.tools) {
811
+ if ("schema" in tool) {
812
+ const toolSchema = tool.schema;
813
+ if (this.schemaMatchesErrorPaths(toolSchema, errorPaths)) {
814
+ this.formLogger.info(
815
+ "Detected tool from error path analysis:",
816
+ tool.name
817
+ );
818
+ return {
819
+ toolName: tool.name,
820
+ schema: toolSchema
821
+ };
822
+ }
823
+ }
168
824
  }
169
- if (isFormValidatable(this.originalTool)) {
170
- this.logger.info(`Tool ${this.originalTool.name} implements FormValidatable, using custom logic`);
171
- return this.originalTool.shouldGenerateForm(input);
825
+ return null;
826
+ }
827
+ /**
828
+ * Checks if a schema structure matches error paths
829
+ */
830
+ schemaMatchesErrorPaths(schema, errorPaths) {
831
+ const schemaRecord = schema;
832
+ if (!schemaRecord || !schemaRecord._def) return false;
833
+ try {
834
+ const def = schemaRecord._def;
835
+ if (def.typeName === "ZodObject") {
836
+ const shape = def.shape;
837
+ const schemaKeys = Object.keys(shape || {});
838
+ return errorPaths.some((path) => {
839
+ const topLevelKey = path.split(".")[0];
840
+ return schemaKeys.includes(topLevelKey);
841
+ });
842
+ }
843
+ } catch (err) {
844
+ this.formLogger.debug("Error analyzing schema structure:", err);
172
845
  }
173
- this.logger.info(`Tool ${this.originalTool.name} using schema validation only`);
174
- const validation = this.validateInput(input);
175
- this.logger.info(`Schema validation for ${this.originalTool.name}:`, {
176
- isValid: validation.isValid,
177
- errors: validation.errors
178
- });
179
- return !validation.isValid;
846
+ return false;
180
847
  }
181
848
  /**
182
- * Checks if input has bypass flags that skip form generation
849
+ * Extracts keywords from tool name for matching
183
850
  */
184
- hasFormBypassFlags(input) {
185
- return input.__fromForm === true || input.renderForm === false;
851
+ extractToolKeywords(toolName) {
852
+ const words = toolName.replace(/([A-Z])/g, " $1").toLowerCase().split(/[\s_-]+/).filter((w) => w.length > 2);
853
+ return [...words, toolName.toLowerCase()];
186
854
  }
187
855
  /**
188
- * Override _call to intercept tool execution
856
+ * Formats the form message for display
189
857
  */
190
- async _call(input, runManager) {
191
- this.logger.info(`🚨🚨🚨 FormValidatingToolWrapper._call INTERCEPTING ${this.name} 🚨🚨🚨`, {
192
- input,
193
- inputKeys: Object.keys(input),
194
- schemaShape: this.getSchemaShape(),
195
- stackTrace: new Error().stack?.split("\n").slice(0, 5)
196
- });
197
- const inputRecord = input;
198
- if (this.hasFormBypassFlags(inputRecord)) {
199
- this.logger.info("Bypassing form generation and executing original tool due to submission flags");
200
- return this.executeOriginal(inputRecord, runManager);
201
- }
202
- const shouldGenerate = this.shouldGenerateForm(input);
203
- this.logger.info(`FormValidatingToolWrapper decision for ${this.name}:`, {
204
- shouldGenerateForm: shouldGenerate,
205
- toolName: this.name,
206
- originalToolName: this.originalTool.name
207
- });
208
- if (shouldGenerate) {
209
- this.logger.info(`Generating form for incomplete input in ${this.name}`);
210
- try {
211
- const isCustom = isFormValidatable(this.originalTool);
212
- const schemaToUse = isCustom ? this.getFormSchema() : this.schema;
213
- const missingFields = this.calculateMissingFields(
214
- input,
215
- isCustom
216
- );
217
- const schemaFields = this.isZodObject(schemaToUse) ? Object.keys(schemaToUse.shape) : [];
218
- this.logger.info(`Using ${isCustom ? "CUSTOM" : "DEFAULT"} schema for form generation`, {
219
- toolName: this.originalTool.name,
220
- schemaType: schemaToUse.constructor?.name,
221
- schemaFields,
222
- isCustomSchema: isCustom
223
- });
224
- const formMessage = await this.createFormMessage(
225
- schemaToUse,
226
- input,
227
- missingFields
858
+ formatFormResponse(formMessage) {
859
+ const fieldCount = formMessage.formConfig.fields.length;
860
+ const fieldList = formMessage.formConfig.fields.slice(0, 3).map((f) => `• ${f.label}`).join("\n");
861
+ return `I need some additional information to complete your request.
862
+
863
+ ${formMessage.formConfig.description}
864
+
865
+ Required fields:
866
+ ${fieldList}${fieldCount > 3 ? `
867
+ ... and ${fieldCount - 3} more` : ""}
868
+
869
+ Please fill out the form below to continue.`;
870
+ }
871
+ /**
872
+ * Check if there are pending forms
873
+ */
874
+ hasPendingForms() {
875
+ return this.pendingForms.size > 0;
876
+ }
877
+ /**
878
+ * Get information about pending forms
879
+ */
880
+ getPendingFormsInfo() {
881
+ return Array.from(this.pendingForms.entries()).map(([formId, info]) => ({
882
+ formId,
883
+ toolName: info.toolName
884
+ }));
885
+ }
886
+ /**
887
+ * Processes HashLink block responses from tools
888
+ */
889
+ processHashLinkResponse(toolResponse) {
890
+ try {
891
+ let hashLinkBlock;
892
+ if (toolResponse.hashLinkBlock) {
893
+ hashLinkBlock = toolResponse.hashLinkBlock;
894
+ } else if (toolResponse.success && toolResponse.hashLinkBlock) {
895
+ hashLinkBlock = toolResponse.hashLinkBlock;
896
+ }
897
+ if (!hashLinkBlock) {
898
+ throw new Error("HashLink block data not found in response");
899
+ }
900
+ if (!hashLinkBlock.blockId || !hashLinkBlock.hashLink || !hashLinkBlock.attributes) {
901
+ throw new Error(
902
+ "Invalid HashLink block structure - missing required fields"
228
903
  );
229
- const result = {
230
- requiresForm: true,
231
- formMessage,
232
- message: `Please complete the form to provide the required information for ${this.name}.`
233
- };
234
- this.logger.info(`FormValidatingToolWrapper returning form result for ${this.name}`);
235
- return JSON.stringify(result);
236
- } catch (error) {
237
- this.logger.error("Failed to generate form:", error);
238
904
  }
905
+ let message = "Content processed successfully!";
906
+ if (toolResponse.success && toolResponse.inscription) {
907
+ const inscription = toolResponse.inscription;
908
+ const metadata = toolResponse.metadata || {};
909
+ message = `✅ ${inscription.standard} Hashinal inscription completed!
910
+
911
+ `;
912
+ if (metadata.name) {
913
+ message += `**${metadata.name}**
914
+ `;
915
+ }
916
+ if (metadata.description) {
917
+ message += `${metadata.description}
918
+
919
+ `;
920
+ }
921
+ message += `📍 **Topic ID:** ${inscription.topicId}
922
+ `;
923
+ message += `🔗 **HRL:** ${inscription.hrl}
924
+ `;
925
+ if (inscription.cdnUrl) {
926
+ message += `🌐 **CDN URL:** ${inscription.cdnUrl}
927
+ `;
928
+ }
929
+ if (metadata.creator) {
930
+ message += `👤 **Creator:** ${metadata.creator}
931
+ `;
932
+ }
933
+ }
934
+ this.formLogger.info("Processed HashLink response", {
935
+ blockId: hashLinkBlock.blockId,
936
+ hashLink: hashLinkBlock.hashLink,
937
+ hasTemplate: !!hashLinkBlock.template,
938
+ attributeCount: Object.keys(hashLinkBlock.attributes || {}).length
939
+ });
940
+ return {
941
+ hasHashLinkBlocks: true,
942
+ hashLinkBlock,
943
+ message
944
+ };
945
+ } catch (error) {
946
+ this.formLogger.error("Error processing HashLink response:", error);
947
+ return {
948
+ hasHashLinkBlocks: false,
949
+ message: "Content processed, but interactive display is not available."
950
+ };
239
951
  }
240
- this.logger.info(`FormValidatingToolWrapper passing through to original tool ${this.name}`);
241
- return this.executeOriginal(input, runManager);
242
952
  }
243
- }
244
- function wrapToolWithFormValidation(tool, formGenerator, config = {}) {
245
- return new FormValidatingToolWrapper(tool, formGenerator, config);
953
+ /**
954
+ * Get FormEngine statistics for debugging
955
+ */
956
+ getFormEngineStatistics() {
957
+ return {
958
+ strategies: this.formEngine.getRegisteredStrategies(),
959
+ middleware: this.formEngine.getRegisteredMiddleware()
960
+ };
961
+ }
246
962
  }
247
963
  export {
248
- FormValidatingToolWrapper,
249
- wrapToolWithFormValidation
964
+ FormAwareAgentExecutor
250
965
  };
251
966
  //# sourceMappingURL=index32.js.map