@falai/agent 1.2.7 → 2.0.0

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 (508) hide show
  1. package/README.md +40 -886
  2. package/dist/adapters/MemoryAdapter.js +2 -2
  3. package/dist/adapters/MemoryAdapter.js.map +1 -1
  4. package/dist/adapters/MongoAdapter.js +2 -2
  5. package/dist/adapters/MongoAdapter.js.map +1 -1
  6. package/dist/adapters/OpenSearchAdapter.d.ts.map +1 -1
  7. package/dist/adapters/OpenSearchAdapter.js +9 -7
  8. package/dist/adapters/OpenSearchAdapter.js.map +1 -1
  9. package/dist/adapters/PostgreSQLAdapter.d.ts +14 -0
  10. package/dist/adapters/PostgreSQLAdapter.d.ts.map +1 -1
  11. package/dist/adapters/PostgreSQLAdapter.js +25 -9
  12. package/dist/adapters/PostgreSQLAdapter.js.map +1 -1
  13. package/dist/adapters/PrismaAdapter.js +5 -5
  14. package/dist/adapters/PrismaAdapter.js.map +1 -1
  15. package/dist/adapters/RedisAdapter.js +2 -2
  16. package/dist/adapters/RedisAdapter.js.map +1 -1
  17. package/dist/adapters/SQLiteAdapter.d.ts +17 -0
  18. package/dist/adapters/SQLiteAdapter.d.ts.map +1 -1
  19. package/dist/adapters/SQLiteAdapter.js +30 -11
  20. package/dist/adapters/SQLiteAdapter.js.map +1 -1
  21. package/dist/cjs/adapters/MemoryAdapter.js +2 -2
  22. package/dist/cjs/adapters/MemoryAdapter.js.map +1 -1
  23. package/dist/cjs/adapters/MongoAdapter.js +2 -2
  24. package/dist/cjs/adapters/MongoAdapter.js.map +1 -1
  25. package/dist/cjs/adapters/OpenSearchAdapter.d.ts.map +1 -1
  26. package/dist/cjs/adapters/OpenSearchAdapter.js +9 -7
  27. package/dist/cjs/adapters/OpenSearchAdapter.js.map +1 -1
  28. package/dist/cjs/adapters/PostgreSQLAdapter.d.ts +14 -0
  29. package/dist/cjs/adapters/PostgreSQLAdapter.d.ts.map +1 -1
  30. package/dist/cjs/adapters/PostgreSQLAdapter.js +25 -9
  31. package/dist/cjs/adapters/PostgreSQLAdapter.js.map +1 -1
  32. package/dist/cjs/adapters/PrismaAdapter.js +5 -5
  33. package/dist/cjs/adapters/PrismaAdapter.js.map +1 -1
  34. package/dist/cjs/adapters/RedisAdapter.js +2 -2
  35. package/dist/cjs/adapters/RedisAdapter.js.map +1 -1
  36. package/dist/cjs/adapters/SQLiteAdapter.d.ts +17 -0
  37. package/dist/cjs/adapters/SQLiteAdapter.d.ts.map +1 -1
  38. package/dist/cjs/adapters/SQLiteAdapter.js +30 -11
  39. package/dist/cjs/adapters/SQLiteAdapter.js.map +1 -1
  40. package/dist/cjs/constants/index.d.ts +0 -9
  41. package/dist/cjs/constants/index.d.ts.map +1 -1
  42. package/dist/cjs/constants/index.js +2 -11
  43. package/dist/cjs/constants/index.js.map +1 -1
  44. package/dist/cjs/core/Agent.d.ts +119 -153
  45. package/dist/cjs/core/Agent.d.ts.map +1 -1
  46. package/dist/cjs/core/Agent.js +471 -324
  47. package/dist/cjs/core/Agent.js.map +1 -1
  48. package/dist/cjs/core/AutoChainExecutor.d.ts +107 -0
  49. package/dist/cjs/core/AutoChainExecutor.d.ts.map +1 -0
  50. package/dist/cjs/core/AutoChainExecutor.js +297 -0
  51. package/dist/cjs/core/AutoChainExecutor.js.map +1 -0
  52. package/dist/cjs/core/BranchEvaluator.d.ts +54 -0
  53. package/dist/cjs/core/BranchEvaluator.d.ts.map +1 -0
  54. package/dist/cjs/core/BranchEvaluator.js +130 -0
  55. package/dist/cjs/core/BranchEvaluator.js.map +1 -0
  56. package/dist/cjs/core/DirectiveBus.d.ts +88 -0
  57. package/dist/cjs/core/DirectiveBus.d.ts.map +1 -0
  58. package/dist/cjs/core/DirectiveBus.js +196 -0
  59. package/dist/cjs/core/DirectiveBus.js.map +1 -0
  60. package/dist/cjs/core/DirectiveChainTracker.d.ts +49 -0
  61. package/dist/cjs/core/DirectiveChainTracker.d.ts.map +1 -0
  62. package/dist/cjs/core/DirectiveChainTracker.js +121 -0
  63. package/dist/cjs/core/DirectiveChainTracker.js.map +1 -0
  64. package/dist/cjs/core/Flow.d.ts +186 -0
  65. package/dist/cjs/core/Flow.d.ts.map +1 -0
  66. package/dist/cjs/core/Flow.js +550 -0
  67. package/dist/cjs/core/Flow.js.map +1 -0
  68. package/dist/cjs/core/FlowRouter.d.ts +182 -0
  69. package/dist/cjs/core/FlowRouter.d.ts.map +1 -0
  70. package/dist/cjs/core/{RoutingEngine.js → FlowRouter.js} +323 -306
  71. package/dist/cjs/core/FlowRouter.js.map +1 -0
  72. package/dist/cjs/core/PersistenceManager.d.ts +2 -2
  73. package/dist/cjs/core/PersistenceManager.d.ts.map +1 -1
  74. package/dist/cjs/core/PersistenceManager.js +7 -7
  75. package/dist/cjs/core/PersistenceManager.js.map +1 -1
  76. package/dist/cjs/core/PromptComposer.d.ts +21 -8
  77. package/dist/cjs/core/PromptComposer.d.ts.map +1 -1
  78. package/dist/cjs/core/PromptComposer.js +182 -105
  79. package/dist/cjs/core/PromptComposer.js.map +1 -1
  80. package/dist/cjs/core/PromptSectionCache.d.ts +1 -1
  81. package/dist/cjs/core/PromptSectionCache.js +1 -1
  82. package/dist/cjs/core/ResponseEngine.d.ts +18 -8
  83. package/dist/cjs/core/ResponseEngine.d.ts.map +1 -1
  84. package/dist/cjs/core/ResponseEngine.js +38 -36
  85. package/dist/cjs/core/ResponseEngine.js.map +1 -1
  86. package/dist/cjs/core/ResponseModal.d.ts +73 -56
  87. package/dist/cjs/core/ResponseModal.d.ts.map +1 -1
  88. package/dist/cjs/core/ResponseModal.js +1196 -1015
  89. package/dist/cjs/core/ResponseModal.js.map +1 -1
  90. package/dist/cjs/core/ResponsePipeline.d.ts +124 -26
  91. package/dist/cjs/core/ResponsePipeline.d.ts.map +1 -1
  92. package/dist/cjs/core/ResponsePipeline.js +524 -134
  93. package/dist/cjs/core/ResponsePipeline.js.map +1 -1
  94. package/dist/cjs/core/SignalEvaluator.d.ts +86 -0
  95. package/dist/cjs/core/SignalEvaluator.d.ts.map +1 -0
  96. package/dist/cjs/core/SignalEvaluator.js +333 -0
  97. package/dist/cjs/core/SignalEvaluator.js.map +1 -0
  98. package/dist/cjs/core/SignalProcessor.d.ts +152 -0
  99. package/dist/cjs/core/SignalProcessor.d.ts.map +1 -0
  100. package/dist/cjs/core/SignalProcessor.js +562 -0
  101. package/dist/cjs/core/SignalProcessor.js.map +1 -0
  102. package/dist/cjs/core/Step.d.ts +43 -32
  103. package/dist/cjs/core/Step.d.ts.map +1 -1
  104. package/dist/cjs/core/Step.js +221 -126
  105. package/dist/cjs/core/Step.js.map +1 -1
  106. package/dist/cjs/core/StreamingToolExecutor.d.ts +2 -2
  107. package/dist/cjs/core/StreamingToolExecutor.d.ts.map +1 -1
  108. package/dist/cjs/core/StreamingToolExecutor.js.map +1 -1
  109. package/dist/cjs/core/ToolManager.d.ts +44 -13
  110. package/dist/cjs/core/ToolManager.d.ts.map +1 -1
  111. package/dist/cjs/core/ToolManager.js +174 -91
  112. package/dist/cjs/core/ToolManager.js.map +1 -1
  113. package/dist/cjs/core/createAgent.d.ts +35 -0
  114. package/dist/cjs/core/createAgent.d.ts.map +1 -0
  115. package/dist/cjs/core/createAgent.js +39 -0
  116. package/dist/cjs/core/createAgent.js.map +1 -0
  117. package/dist/cjs/core/flow-namespace.d.ts +49 -0
  118. package/dist/cjs/core/flow-namespace.d.ts.map +1 -0
  119. package/dist/cjs/core/flow-namespace.js +171 -0
  120. package/dist/cjs/core/flow-namespace.js.map +1 -0
  121. package/dist/cjs/index.d.ts +11 -14
  122. package/dist/cjs/index.d.ts.map +1 -1
  123. package/dist/cjs/index.js +18 -22
  124. package/dist/cjs/index.js.map +1 -1
  125. package/dist/cjs/providers/GeminiProvider.d.ts +3 -3
  126. package/dist/cjs/providers/GeminiProvider.d.ts.map +1 -1
  127. package/dist/cjs/providers/GeminiProvider.js +16 -14
  128. package/dist/cjs/providers/GeminiProvider.js.map +1 -1
  129. package/dist/cjs/types/agent.d.ts +183 -54
  130. package/dist/cjs/types/agent.d.ts.map +1 -1
  131. package/dist/cjs/types/agent.js +0 -6
  132. package/dist/cjs/types/agent.js.map +1 -1
  133. package/dist/cjs/types/ai.d.ts +3 -3
  134. package/dist/cjs/types/ai.d.ts.map +1 -1
  135. package/dist/cjs/types/errors.d.ts +15 -0
  136. package/dist/cjs/types/errors.d.ts.map +1 -0
  137. package/dist/cjs/types/errors.js +22 -0
  138. package/dist/cjs/types/errors.js.map +1 -0
  139. package/dist/cjs/types/flow.d.ts +513 -0
  140. package/dist/cjs/types/flow.d.ts.map +1 -0
  141. package/dist/cjs/types/{route.js → flow.js} +2 -2
  142. package/dist/cjs/types/flow.js.map +1 -0
  143. package/dist/cjs/types/index.d.ts +7 -6
  144. package/dist/cjs/types/index.d.ts.map +1 -1
  145. package/dist/cjs/types/index.js +6 -2
  146. package/dist/cjs/types/index.js.map +1 -1
  147. package/dist/cjs/types/persistence.d.ts +11 -7
  148. package/dist/cjs/types/persistence.d.ts.map +1 -1
  149. package/dist/cjs/types/routing.d.ts +1 -1
  150. package/dist/cjs/types/routing.d.ts.map +1 -1
  151. package/dist/cjs/types/session.d.ts +24 -23
  152. package/dist/cjs/types/session.d.ts.map +1 -1
  153. package/dist/cjs/types/signals.d.ts +248 -0
  154. package/dist/cjs/types/signals.d.ts.map +1 -0
  155. package/dist/cjs/types/signals.js +11 -0
  156. package/dist/cjs/types/signals.js.map +1 -0
  157. package/dist/cjs/types/template.d.ts +2 -8
  158. package/dist/cjs/types/template.d.ts.map +1 -1
  159. package/dist/cjs/types/tool.d.ts +36 -29
  160. package/dist/cjs/types/tool.d.ts.map +1 -1
  161. package/dist/cjs/types/tool.js +1 -1
  162. package/dist/cjs/types/tool.js.map +1 -1
  163. package/dist/cjs/utils/condition.d.ts +7 -1
  164. package/dist/cjs/utils/condition.d.ts.map +1 -1
  165. package/dist/cjs/utils/condition.js.map +1 -1
  166. package/dist/cjs/utils/id.d.ts +13 -5
  167. package/dist/cjs/utils/id.d.ts.map +1 -1
  168. package/dist/cjs/utils/id.js +24 -10
  169. package/dist/cjs/utils/id.js.map +1 -1
  170. package/dist/cjs/utils/index.d.ts +2 -2
  171. package/dist/cjs/utils/index.d.ts.map +1 -1
  172. package/dist/cjs/utils/index.js +7 -3
  173. package/dist/cjs/utils/index.js.map +1 -1
  174. package/dist/cjs/utils/session.d.ts +44 -5
  175. package/dist/cjs/utils/session.d.ts.map +1 -1
  176. package/dist/cjs/utils/session.js +197 -38
  177. package/dist/cjs/utils/session.js.map +1 -1
  178. package/dist/constants/index.d.ts +0 -9
  179. package/dist/constants/index.d.ts.map +1 -1
  180. package/dist/constants/index.js +3 -9
  181. package/dist/constants/index.js.map +1 -1
  182. package/dist/core/Agent.d.ts +119 -153
  183. package/dist/core/Agent.d.ts.map +1 -1
  184. package/dist/core/Agent.js +472 -325
  185. package/dist/core/Agent.js.map +1 -1
  186. package/dist/core/AutoChainExecutor.d.ts +107 -0
  187. package/dist/core/AutoChainExecutor.d.ts.map +1 -0
  188. package/dist/core/AutoChainExecutor.js +293 -0
  189. package/dist/core/AutoChainExecutor.js.map +1 -0
  190. package/dist/core/BranchEvaluator.d.ts +54 -0
  191. package/dist/core/BranchEvaluator.d.ts.map +1 -0
  192. package/dist/core/BranchEvaluator.js +126 -0
  193. package/dist/core/BranchEvaluator.js.map +1 -0
  194. package/dist/core/DirectiveBus.d.ts +88 -0
  195. package/dist/core/DirectiveBus.d.ts.map +1 -0
  196. package/dist/core/DirectiveBus.js +192 -0
  197. package/dist/core/DirectiveBus.js.map +1 -0
  198. package/dist/core/DirectiveChainTracker.d.ts +49 -0
  199. package/dist/core/DirectiveChainTracker.d.ts.map +1 -0
  200. package/dist/core/DirectiveChainTracker.js +117 -0
  201. package/dist/core/DirectiveChainTracker.js.map +1 -0
  202. package/dist/core/Flow.d.ts +186 -0
  203. package/dist/core/Flow.d.ts.map +1 -0
  204. package/dist/core/Flow.js +546 -0
  205. package/dist/core/Flow.js.map +1 -0
  206. package/dist/core/FlowRouter.d.ts +182 -0
  207. package/dist/core/FlowRouter.d.ts.map +1 -0
  208. package/dist/core/{RoutingEngine.js → FlowRouter.js} +322 -305
  209. package/dist/core/FlowRouter.js.map +1 -0
  210. package/dist/core/PersistenceManager.d.ts +2 -2
  211. package/dist/core/PersistenceManager.d.ts.map +1 -1
  212. package/dist/core/PersistenceManager.js +7 -7
  213. package/dist/core/PersistenceManager.js.map +1 -1
  214. package/dist/core/PromptComposer.d.ts +21 -8
  215. package/dist/core/PromptComposer.d.ts.map +1 -1
  216. package/dist/core/PromptComposer.js +183 -106
  217. package/dist/core/PromptComposer.js.map +1 -1
  218. package/dist/core/PromptSectionCache.d.ts +1 -1
  219. package/dist/core/PromptSectionCache.js +1 -1
  220. package/dist/core/ResponseEngine.d.ts +18 -8
  221. package/dist/core/ResponseEngine.d.ts.map +1 -1
  222. package/dist/core/ResponseEngine.js +38 -36
  223. package/dist/core/ResponseEngine.js.map +1 -1
  224. package/dist/core/ResponseModal.d.ts +73 -56
  225. package/dist/core/ResponseModal.d.ts.map +1 -1
  226. package/dist/core/ResponseModal.js +1198 -1017
  227. package/dist/core/ResponseModal.js.map +1 -1
  228. package/dist/core/ResponsePipeline.d.ts +124 -26
  229. package/dist/core/ResponsePipeline.d.ts.map +1 -1
  230. package/dist/core/ResponsePipeline.js +524 -135
  231. package/dist/core/ResponsePipeline.js.map +1 -1
  232. package/dist/core/SignalEvaluator.d.ts +86 -0
  233. package/dist/core/SignalEvaluator.d.ts.map +1 -0
  234. package/dist/core/SignalEvaluator.js +326 -0
  235. package/dist/core/SignalEvaluator.js.map +1 -0
  236. package/dist/core/SignalProcessor.d.ts +152 -0
  237. package/dist/core/SignalProcessor.d.ts.map +1 -0
  238. package/dist/core/SignalProcessor.js +555 -0
  239. package/dist/core/SignalProcessor.js.map +1 -0
  240. package/dist/core/Step.d.ts +43 -32
  241. package/dist/core/Step.d.ts.map +1 -1
  242. package/dist/core/Step.js +220 -126
  243. package/dist/core/Step.js.map +1 -1
  244. package/dist/core/StreamingToolExecutor.d.ts +2 -2
  245. package/dist/core/StreamingToolExecutor.d.ts.map +1 -1
  246. package/dist/core/StreamingToolExecutor.js.map +1 -1
  247. package/dist/core/ToolManager.d.ts +44 -13
  248. package/dist/core/ToolManager.d.ts.map +1 -1
  249. package/dist/core/ToolManager.js +174 -91
  250. package/dist/core/ToolManager.js.map +1 -1
  251. package/dist/core/createAgent.d.ts +35 -0
  252. package/dist/core/createAgent.d.ts.map +1 -0
  253. package/dist/core/createAgent.js +36 -0
  254. package/dist/core/createAgent.js.map +1 -0
  255. package/dist/core/flow-namespace.d.ts +49 -0
  256. package/dist/core/flow-namespace.d.ts.map +1 -0
  257. package/dist/core/flow-namespace.js +168 -0
  258. package/dist/core/flow-namespace.js.map +1 -0
  259. package/dist/index.d.ts +11 -14
  260. package/dist/index.d.ts.map +1 -1
  261. package/dist/index.js +9 -12
  262. package/dist/index.js.map +1 -1
  263. package/dist/providers/GeminiProvider.d.ts +3 -3
  264. package/dist/providers/GeminiProvider.d.ts.map +1 -1
  265. package/dist/providers/GeminiProvider.js +16 -14
  266. package/dist/providers/GeminiProvider.js.map +1 -1
  267. package/dist/types/agent.d.ts +183 -54
  268. package/dist/types/agent.d.ts.map +1 -1
  269. package/dist/types/agent.js +0 -6
  270. package/dist/types/agent.js.map +1 -1
  271. package/dist/types/ai.d.ts +3 -3
  272. package/dist/types/ai.d.ts.map +1 -1
  273. package/dist/types/errors.d.ts +15 -0
  274. package/dist/types/errors.d.ts.map +1 -0
  275. package/dist/types/errors.js +18 -0
  276. package/dist/types/errors.js.map +1 -0
  277. package/dist/types/flow.d.ts +513 -0
  278. package/dist/types/flow.d.ts.map +1 -0
  279. package/dist/types/flow.js +5 -0
  280. package/dist/types/flow.js.map +1 -0
  281. package/dist/types/index.d.ts +7 -6
  282. package/dist/types/index.d.ts.map +1 -1
  283. package/dist/types/index.js +4 -1
  284. package/dist/types/index.js.map +1 -1
  285. package/dist/types/persistence.d.ts +11 -7
  286. package/dist/types/persistence.d.ts.map +1 -1
  287. package/dist/types/routing.d.ts +1 -1
  288. package/dist/types/routing.d.ts.map +1 -1
  289. package/dist/types/session.d.ts +24 -23
  290. package/dist/types/session.d.ts.map +1 -1
  291. package/dist/types/signals.d.ts +248 -0
  292. package/dist/types/signals.d.ts.map +1 -0
  293. package/dist/types/signals.js +10 -0
  294. package/dist/types/signals.js.map +1 -0
  295. package/dist/types/template.d.ts +2 -8
  296. package/dist/types/template.d.ts.map +1 -1
  297. package/dist/types/tool.d.ts +36 -29
  298. package/dist/types/tool.d.ts.map +1 -1
  299. package/dist/types/tool.js +1 -1
  300. package/dist/types/tool.js.map +1 -1
  301. package/dist/utils/condition.d.ts +7 -1
  302. package/dist/utils/condition.d.ts.map +1 -1
  303. package/dist/utils/condition.js.map +1 -1
  304. package/dist/utils/id.d.ts +13 -5
  305. package/dist/utils/id.d.ts.map +1 -1
  306. package/dist/utils/id.js +22 -9
  307. package/dist/utils/id.js.map +1 -1
  308. package/dist/utils/index.d.ts +2 -2
  309. package/dist/utils/index.d.ts.map +1 -1
  310. package/dist/utils/index.js +2 -2
  311. package/dist/utils/index.js.map +1 -1
  312. package/dist/utils/session.d.ts +44 -5
  313. package/dist/utils/session.d.ts.map +1 -1
  314. package/dist/utils/session.js +193 -37
  315. package/dist/utils/session.js.map +1 -1
  316. package/docs/README.md +15 -202
  317. package/docs/concepts/architecture.md +281 -0
  318. package/docs/concepts/directives.md +400 -0
  319. package/docs/concepts/pipeline.md +399 -0
  320. package/docs/guides/branching.md +263 -0
  321. package/docs/guides/compaction.md +163 -0
  322. package/docs/guides/conditions.md +167 -0
  323. package/docs/guides/error-handling.md +176 -0
  324. package/docs/guides/flow-control.md +409 -0
  325. package/docs/guides/instructions.md +210 -0
  326. package/docs/guides/persistence.md +182 -0
  327. package/docs/guides/streaming.md +137 -0
  328. package/docs/migration/README.md +15 -0
  329. package/docs/migration/route-to-flow.md +560 -0
  330. package/docs/migration/v1-to-v2.md +909 -0
  331. package/docs/reference/adapters.md +481 -0
  332. package/docs/reference/branches.md +241 -0
  333. package/docs/reference/create-agent.md +186 -0
  334. package/docs/reference/directive.md +243 -0
  335. package/docs/reference/errors.md +122 -0
  336. package/docs/reference/flow.md +238 -0
  337. package/docs/reference/instruction.md +177 -0
  338. package/docs/reference/pre-directive.md +131 -0
  339. package/docs/reference/providers.md +227 -0
  340. package/docs/reference/signals.md +356 -0
  341. package/docs/reference/step.md +339 -0
  342. package/docs/reference/tool.md +269 -0
  343. package/docs/start/01-install.md +81 -0
  344. package/docs/start/02-first-agent.md +196 -0
  345. package/docs/start/03-collect-data.md +222 -0
  346. package/docs/start/04-add-tools.md +276 -0
  347. package/docs/start/05-go-to-production.md +216 -0
  348. package/examples/01-quickstart.ts +20 -0
  349. package/examples/02-data-extraction.ts +90 -0
  350. package/examples/03-tools.ts +136 -0
  351. package/examples/04-instructions.ts +100 -0
  352. package/examples/05-branching.ts +140 -0
  353. package/examples/06-flow-control.ts +103 -0
  354. package/examples/07-streaming.ts +69 -0
  355. package/examples/08-persistence.ts +98 -0
  356. package/examples/09-signals.ts +144 -0
  357. package/examples/tsconfig.json +30 -0
  358. package/package.json +2 -1
  359. package/src/adapters/MemoryAdapter.ts +3 -3
  360. package/src/adapters/MongoAdapter.ts +3 -3
  361. package/src/adapters/OpenSearchAdapter.ts +10 -8
  362. package/src/adapters/PostgreSQLAdapter.ts +26 -10
  363. package/src/adapters/PrismaAdapter.ts +6 -6
  364. package/src/adapters/RedisAdapter.ts +3 -3
  365. package/src/adapters/SQLiteAdapter.ts +31 -12
  366. package/src/constants/index.ts +2 -10
  367. package/src/core/Agent.ts +585 -374
  368. package/src/core/AutoChainExecutor.ts +440 -0
  369. package/src/core/BranchEvaluator.ts +167 -0
  370. package/src/core/DirectiveBus.ts +248 -0
  371. package/src/core/DirectiveChainTracker.ts +144 -0
  372. package/src/core/Flow.ts +666 -0
  373. package/src/core/{RoutingEngine.ts → FlowRouter.ts} +385 -365
  374. package/src/core/PersistenceManager.ts +8 -8
  375. package/src/core/PromptComposer.ts +209 -140
  376. package/src/core/PromptSectionCache.ts +1 -1
  377. package/src/core/ResponseEngine.ts +61 -46
  378. package/src/core/ResponseModal.ts +1458 -1241
  379. package/src/core/ResponsePipeline.ts +675 -173
  380. package/src/core/SignalEvaluator.ts +420 -0
  381. package/src/core/SignalProcessor.ts +723 -0
  382. package/src/core/Step.ts +279 -176
  383. package/src/core/StreamingToolExecutor.ts +4 -4
  384. package/src/core/ToolManager.ts +200 -97
  385. package/src/core/createAgent.ts +40 -0
  386. package/src/core/flow-namespace.ts +219 -0
  387. package/src/index.ts +42 -36
  388. package/src/providers/GeminiProvider.ts +17 -15
  389. package/src/types/agent.ts +182 -53
  390. package/src/types/ai.ts +3 -3
  391. package/src/types/errors.ts +18 -0
  392. package/src/types/flow.ts +590 -0
  393. package/src/types/index.ts +43 -16
  394. package/src/types/persistence.ts +12 -8
  395. package/src/types/routing.ts +1 -1
  396. package/src/types/session.ts +26 -23
  397. package/src/types/signals.ts +321 -0
  398. package/src/types/template.ts +3 -11
  399. package/src/types/tool.ts +50 -42
  400. package/src/utils/condition.ts +13 -4
  401. package/src/utils/id.ts +27 -9
  402. package/src/utils/index.ts +6 -2
  403. package/src/utils/session.ts +238 -42
  404. package/dist/cjs/core/BatchExecutor.d.ts +0 -359
  405. package/dist/cjs/core/BatchExecutor.d.ts.map +0 -1
  406. package/dist/cjs/core/BatchExecutor.js +0 -861
  407. package/dist/cjs/core/BatchExecutor.js.map +0 -1
  408. package/dist/cjs/core/BatchPromptBuilder.d.ts +0 -89
  409. package/dist/cjs/core/BatchPromptBuilder.d.ts.map +0 -1
  410. package/dist/cjs/core/BatchPromptBuilder.js +0 -223
  411. package/dist/cjs/core/BatchPromptBuilder.js.map +0 -1
  412. package/dist/cjs/core/Route.d.ts +0 -180
  413. package/dist/cjs/core/Route.d.ts.map +0 -1
  414. package/dist/cjs/core/Route.js +0 -542
  415. package/dist/cjs/core/Route.js.map +0 -1
  416. package/dist/cjs/core/RoutingEngine.d.ts +0 -185
  417. package/dist/cjs/core/RoutingEngine.d.ts.map +0 -1
  418. package/dist/cjs/core/RoutingEngine.js.map +0 -1
  419. package/dist/cjs/types/route.d.ts +0 -336
  420. package/dist/cjs/types/route.d.ts.map +0 -1
  421. package/dist/cjs/types/route.js.map +0 -1
  422. package/dist/core/BatchExecutor.d.ts +0 -359
  423. package/dist/core/BatchExecutor.d.ts.map +0 -1
  424. package/dist/core/BatchExecutor.js +0 -856
  425. package/dist/core/BatchExecutor.js.map +0 -1
  426. package/dist/core/BatchPromptBuilder.d.ts +0 -89
  427. package/dist/core/BatchPromptBuilder.d.ts.map +0 -1
  428. package/dist/core/BatchPromptBuilder.js +0 -219
  429. package/dist/core/BatchPromptBuilder.js.map +0 -1
  430. package/dist/core/Route.d.ts +0 -180
  431. package/dist/core/Route.d.ts.map +0 -1
  432. package/dist/core/Route.js +0 -538
  433. package/dist/core/Route.js.map +0 -1
  434. package/dist/core/RoutingEngine.d.ts +0 -185
  435. package/dist/core/RoutingEngine.d.ts.map +0 -1
  436. package/dist/core/RoutingEngine.js.map +0 -1
  437. package/dist/types/route.d.ts +0 -336
  438. package/dist/types/route.d.ts.map +0 -1
  439. package/dist/types/route.js +0 -5
  440. package/dist/types/route.js.map +0 -1
  441. package/docs/CONTRIBUTING.md +0 -521
  442. package/docs/api/README.md +0 -3299
  443. package/docs/api/overview.md +0 -1410
  444. package/docs/architecture/data-extraction-flow.md +0 -360
  445. package/docs/architecture/multi-step-execution.md +0 -277
  446. package/docs/core/agent/README.md +0 -938
  447. package/docs/core/agent/context-management.md +0 -796
  448. package/docs/core/agent/rules-and-prohibitions.md +0 -113
  449. package/docs/core/agent/session-management.md +0 -693
  450. package/docs/core/ai-integration/prompt-composition.md +0 -355
  451. package/docs/core/ai-integration/providers.md +0 -515
  452. package/docs/core/ai-integration/response-processing.md +0 -433
  453. package/docs/core/conversation-flows/data-collection.md +0 -772
  454. package/docs/core/conversation-flows/route-dsl.md +0 -509
  455. package/docs/core/conversation-flows/routes.md +0 -249
  456. package/docs/core/conversation-flows/step-transitions.md +0 -731
  457. package/docs/core/conversation-flows/steps.md +0 -268
  458. package/docs/core/error-handling.md +0 -830
  459. package/docs/core/persistence/adapters.md +0 -255
  460. package/docs/core/persistence/session-storage.md +0 -656
  461. package/docs/core/routing/intelligent-routing.md +0 -470
  462. package/docs/core/tools/enhanced-tool.md +0 -186
  463. package/docs/core/tools/streaming-execution.md +0 -161
  464. package/docs/core/tools/tool-definition.md +0 -970
  465. package/docs/core/tools/tool-scoping.md +0 -819
  466. package/docs/guides/advanced-patterns/publishing.md +0 -186
  467. package/docs/guides/context-compaction.md +0 -96
  468. package/docs/guides/error-handling-patterns.md +0 -578
  469. package/docs/guides/getting-started/README.md +0 -795
  470. package/docs/guides/migration/README.md +0 -101
  471. package/docs/guides/migration/flexible-routing-conditions.md +0 -375
  472. package/docs/guides/migration/multi-step-execution.md +0 -393
  473. package/docs/guides/migration/response-modal-refactor.md +0 -518
  474. package/docs/guides/prompt-optimization.md +0 -164
  475. package/examples/advanced-patterns/context-compaction.ts +0 -223
  476. package/examples/advanced-patterns/knowledge-based-agent.ts +0 -735
  477. package/examples/advanced-patterns/persistent-onboarding.ts +0 -728
  478. package/examples/advanced-patterns/route-lifecycle-hooks.ts +0 -556
  479. package/examples/advanced-patterns/streaming-responses.ts +0 -656
  480. package/examples/ai-providers/anthropic-integration.ts +0 -388
  481. package/examples/ai-providers/openai-integration.ts +0 -228
  482. package/examples/condition-patterns/function-only-conditions.ts +0 -365
  483. package/examples/condition-patterns/mixed-array-conditions.ts +0 -477
  484. package/examples/condition-patterns/route-skipif-patterns.ts +0 -468
  485. package/examples/condition-patterns/step-skipif-patterns.ts +0 -0
  486. package/examples/condition-patterns/string-only-conditions.ts +0 -296
  487. package/examples/conversation-flows/completion-transitions.ts +0 -318
  488. package/examples/core-concepts/basic-agent.ts +0 -503
  489. package/examples/core-concepts/modern-streaming-api.ts +0 -309
  490. package/examples/core-concepts/schema-driven-extraction.ts +0 -332
  491. package/examples/core-concepts/session-management.ts +0 -494
  492. package/examples/integrations/database-integration.ts +0 -631
  493. package/examples/integrations/healthcare-integration.ts +0 -595
  494. package/examples/integrations/search-integration.ts +0 -530
  495. package/examples/integrations/server-session-management.ts +0 -307
  496. package/examples/persistence/custom-adapter.ts +0 -526
  497. package/examples/persistence/database-persistence.ts +0 -583
  498. package/examples/persistence/memory-sessions.ts +0 -495
  499. package/examples/persistence/prisma-schema.example.prisma +0 -74
  500. package/examples/persistence/redis-persistence.ts +0 -488
  501. package/examples/tools/basic-tools.ts +0 -765
  502. package/examples/tools/data-enrichment-tools.ts +0 -593
  503. package/examples/tools/enhanced-tool-metadata.ts +0 -268
  504. package/examples/tools/streaming-tool-execution.ts +0 -283
  505. package/src/core/BatchExecutor.ts +0 -1187
  506. package/src/core/BatchPromptBuilder.ts +0 -299
  507. package/src/core/Route.ts +0 -678
  508. package/src/types/route.ts +0 -392
@@ -1,593 +0,0 @@
1
- /**
2
- * Example: Modifying Collected data with Tools and Hooks using ToolManager
3
- *
4
- * This demonstrates:
5
- * 1. Schema-first data extraction with JSON Schema
6
- * 2. Simplified tools that modify collected data (validation, enrichment)
7
- * 3. Lifecycle hooks for data validation and business logic
8
- * 4. Data-driven step flows with code-based logic (skipIf, requires)
9
- * 5. Three-phase pipeline: PREPARATION → ROUTING → RESPONSE
10
- * 6. NEW: ToolManager pattern helpers for common data operations
11
- */
12
-
13
- import {
14
- Agent,
15
- END_ROUTE,
16
- OpenAIProvider,
17
- Tool,
18
- ToolContext,
19
- ValidationError,
20
- } from "../../src";
21
-
22
- // ==============================================================================
23
- // CONTEXT & COLLECTED DATA TYPES
24
- // ==============================================================================
25
-
26
- interface FlightBookingContext {
27
- availableFlights?: Array<{
28
- flightNumber: string;
29
- price: number;
30
- departure: string;
31
- arrival: string;
32
- }>;
33
- airportCodes?: Record<string, string>;
34
- }
35
-
36
- interface FlightData {
37
- destination: string;
38
- destinationCode?: string; // Enriched by tool
39
- departureDate: string;
40
- departureDateParsed?: string; // Enriched by tool
41
- passengers: number;
42
- cabinClass: "economy" | "business" | "first";
43
- shouldSearchFlights?: boolean; // Trigger flag
44
- }
45
-
46
- // ==============================================================================
47
- // TOOLS: Data Enrichment (PREPARATION Phase)
48
- // ==============================================================================
49
-
50
- // Tool 1: Convert city names to airport codes using ToolManager pattern helper
51
- const enrichDestinationConfig = {
52
- id: "enrich_destination",
53
- name: "Destination Code Lookup",
54
- description: "Convert city names to IATA airport codes",
55
- fields: ["destination"] as const,
56
- enricher: async (context: FlightBookingContext, data: Pick<FlightData, "destination">) => {
57
- const destination = data.destination;
58
-
59
- if (!destination) {
60
- return {};
61
- }
62
-
63
- // Simulate airport code lookup
64
- const airportCodes: Record<string, string> = {
65
- Paris: "CDG",
66
- London: "LHR",
67
- "New York": "JFK",
68
- Tokyo: "NRT",
69
- "Los Angeles": "LAX",
70
- };
71
-
72
- const destinationCode = airportCodes[destination];
73
-
74
- console.log(`[Tool] Enriched: ${destination} → ${destinationCode}`);
75
-
76
- return {
77
- destinationCode,
78
- } as Partial<FlightData>;
79
- },
80
- };
81
-
82
- // Tool 2: Parse and validate dates using ToolManager pattern helper
83
- const validateDateConfig = {
84
- id: "validate_date",
85
- name: "Date Parser & Validator",
86
- description: "Parse relative dates (today, tomorrow) to ISO format and validate",
87
- fields: ["departureDate"] as const,
88
- enricher: async (context: FlightBookingContext, data: Pick<FlightData, "departureDate">) => {
89
- const departureDate = data.departureDate;
90
-
91
- if (!departureDate) {
92
- return {};
93
- }
94
-
95
- let parsedDate: string;
96
- const today = new Date();
97
-
98
- // Parse relative dates
99
- if (departureDate.toLowerCase() === "today") {
100
- parsedDate = today.toISOString().split("T")[0];
101
- } else if (departureDate.toLowerCase() === "tomorrow") {
102
- const tomorrow = new Date(today);
103
- tomorrow.setDate(tomorrow.getDate() + 1);
104
- parsedDate = tomorrow.toISOString().split("T")[0];
105
- } else if (departureDate.toLowerCase().startsWith("next ")) {
106
- // Handle "next week", "next month", etc.
107
- const nextWeek = new Date(today);
108
- nextWeek.setDate(nextWeek.getDate() + 7);
109
- parsedDate = nextWeek.toISOString().split("T")[0];
110
- } else {
111
- // Assume it's already in a proper format
112
- parsedDate = departureDate;
113
- }
114
-
115
- // Validate that date isn't in the past
116
- const parsedDateObj = new Date(parsedDate);
117
- if (parsedDateObj < today) {
118
- console.warn(`[Tool] Warning: Date ${parsedDate} is in the past`);
119
- // You could throw an error here or set a flag
120
- }
121
-
122
- console.log(`[Tool] Parsed date: ${departureDate} → ${parsedDate}`);
123
-
124
- return {
125
- departureDateParsed: parsedDate,
126
- } as Partial<FlightData>;
127
- },
128
- };
129
-
130
- // Tool 3: Search for flights (triggered by flag) using unified Tool interface
131
- const searchFlightsTool: Tool<FlightBookingContext, FlightData> = {
132
- id: "search_flights",
133
- name: "Flight Availability Search",
134
- description: "Search for available flights based on collected data",
135
- parameters: {
136
- type: "object",
137
- properties: {},
138
- },
139
- handler: async (toolContext, args) => {
140
- const flightData = toolContext.data;
141
-
142
- if (!flightData?.destinationCode || !flightData?.departureDateParsed) {
143
- console.log("[Tool] Cannot search flights: missing required data");
144
- return { data: "Missing required data for flight search" };
145
- }
146
-
147
- // Simulate flight search API call
148
- const flights = [
149
- {
150
- flightNumber: "UA123",
151
- price: 450,
152
- departure: "08:00",
153
- arrival: "14:30",
154
- },
155
- {
156
- flightNumber: "DL456",
157
- price: 520,
158
- departure: "10:30",
159
- arrival: "16:45",
160
- },
161
- ];
162
-
163
- console.log(
164
- `[Tool] Found ${flights.length} flights to ${flightData.destinationCode}`
165
- );
166
-
167
- return {
168
- data: `Found ${flights.length} available flights`,
169
- contextUpdate: {
170
- availableFlights: flights,
171
- },
172
- dataUpdate: {
173
- shouldSearchFlights: false,
174
- },
175
- };
176
- },
177
- };
178
-
179
- // Tool 4: Book the flight using unified Tool interface
180
- const bookFlightTool: Tool<FlightBookingContext, FlightData> = {
181
- id: "book_flight",
182
- name: "Flight Booking Processor",
183
- description: "Finalize the flight booking",
184
- parameters: {
185
- type: "object",
186
- properties: {},
187
- },
188
- handler: async (toolContext, args) => {
189
- const flightData = toolContext.data;
190
- console.log("[Tool] Booking flight with data:", flightData);
191
- // Simulate booking API call
192
- return { data: "Flight booking confirmed!" };
193
- },
194
- };
195
-
196
- // ==============================================================================
197
- // LIFECYCLE HOOKS: Data Validation & Business Logic (RESPONSE Phase)
198
- // ==============================================================================
199
-
200
- function onDataUpdate(
201
- data: Record<string, unknown>,
202
- previousData: Record<string, unknown>
203
- ): Record<string, unknown> {
204
- console.log("[Hook] onDataUpdate called");
205
- console.log(" Previous:", previousData);
206
- console.log(" New:", data);
207
-
208
- // Example: Validate passenger count
209
- const passengers = data.passengers as number | undefined;
210
- if (typeof passengers === "number") {
211
- if (passengers < 1) {
212
- console.warn("[Hook] Invalid passengers count, setting to 1");
213
- data.passengers = 1;
214
- }
215
- if (passengers > 9) {
216
- console.warn("[Hook] Too many passengers, capping at 9");
217
- data.passengers = 9;
218
- }
219
- }
220
-
221
- // Example: Normalize cabin class
222
- const cabinClass = data.cabinClass as string | undefined;
223
- if (typeof cabinClass === "string") {
224
- data.cabinClass = cabinClass.toLowerCase();
225
- }
226
-
227
- // Example: Auto-trigger flight search when we have enough data
228
- const hasDestination = data.destinationCode || data.destination;
229
- const hasDate = data.departureDateParsed || data.departureDate;
230
- const hasPassengers = typeof passengers === "number";
231
-
232
- if (hasDestination && hasDate && hasPassengers && !data.shouldSearchFlights) {
233
- console.log("[Hook] All required data collected, triggering flight search");
234
- data.shouldSearchFlights = true;
235
- }
236
-
237
- return data;
238
- }
239
-
240
- // ==============================================================================
241
- // AGENT SETUP
242
- // ==============================================================================
243
-
244
- // Define flight booking schema
245
- const flightBookingSchema = {
246
- type: "object",
247
- properties: {
248
- destination: {
249
- type: "string",
250
- description: "City or airport the user wants to fly to",
251
- },
252
- destinationCode: {
253
- type: "string",
254
- description: "IATA airport code (enriched by tool)",
255
- },
256
- departureDate: {
257
- type: "string",
258
- description: "When the user wants to depart",
259
- },
260
- departureDateParsed: {
261
- type: "string",
262
- description: "Parsed ISO date (enriched by tool)",
263
- },
264
- passengers: {
265
- type: "number",
266
- minimum: 1,
267
- maximum: 9,
268
- },
269
- cabinClass: {
270
- type: "string",
271
- enum: ["economy", "business", "first"],
272
- default: "economy",
273
- },
274
- shouldSearchFlights: {
275
- type: "boolean",
276
- description: "Flag to trigger flight search",
277
- },
278
- },
279
- required: ["destination", "departureDate", "passengers"],
280
- };
281
-
282
- const agent = new Agent<FlightBookingContext, FlightData>({
283
- name: "Flight Booking Agent",
284
- goal: "Help users book flights efficiently",
285
- description: "I help you find and book flights",
286
- provider: new OpenAIProvider({
287
- apiKey: process.env.OPENAI_API_KEY || "your-api-key-here",
288
- model: "gpt-4o-mini",
289
- }),
290
- context: {},
291
- // NEW: Agent-level schema
292
- schema: flightBookingSchema,
293
- hooks: {
294
- onDataUpdate, // Validation & enrichment hook
295
- },
296
- });
297
-
298
- // Pattern 1: Using the enrichDestinationConfig with inline tool creation
299
- const enrichDestinationTool = {
300
- id: "enrich_destination",
301
- name: "Destination Code Lookup",
302
- description: "Convert city names to IATA airport codes",
303
- parameters: {
304
- type: "object",
305
- properties: {},
306
- },
307
- handler: async (context: ToolContext<FlightBookingContext, FlightData>, args?: Record<string, unknown>) => {
308
- const destination = context.data.destination;
309
-
310
- if (!destination) {
311
- return { data: "No destination to enrich" };
312
- }
313
-
314
- // Use the original enricher function from the config
315
- const result = await enrichDestinationConfig.enricher(context.context, { destination });
316
-
317
- console.log(`[Tool] Enriched: ${destination} → ${result.destinationCode}`);
318
-
319
- return {
320
- data: `Destination code: ${result.destinationCode}`,
321
- dataUpdate: result,
322
- };
323
- },
324
- };
325
-
326
- // Pattern 2: Using the validateDateConfig with typed tool interface
327
- const validateDateTool: Tool<FlightBookingContext, FlightData> = {
328
- id: "validate_date",
329
- name: "Date Parser & Validator",
330
- description: "Parse relative dates (today, tomorrow) to ISO format and validate",
331
- parameters: {
332
- type: "object",
333
- properties: {},
334
- },
335
- handler: async (context, args) => {
336
- const departureDate = context.data.departureDate;
337
-
338
- if (!departureDate) {
339
- return { data: "No departure date to validate" };
340
- }
341
-
342
- // Use the original enricher function from the config
343
- const result = await validateDateConfig.enricher(context.context, { departureDate });
344
-
345
- console.log(`[Tool] Parsed date: ${departureDate} → ${result.departureDateParsed}`);
346
-
347
- return {
348
- data: `Parsed date: ${result.departureDateParsed}`,
349
- dataUpdate: result,
350
- };
351
- },
352
- };
353
-
354
- // Demonstrate different registration methods for data enrichment tools
355
-
356
- // Method 1: Register enrichment tools for ID-based reference
357
- agent.tool.register(enrichDestinationTool);
358
- agent.tool.register(validateDateTool);
359
-
360
- // Method 2: Use registerMany for multiple tools
361
- agent.tool.registerMany([searchFlightsTool, bookFlightTool]);
362
-
363
- // Method 3: Create specialized data enrichment tools using the helper
364
- const passengerEnrichmentTool = agent.tool.createDataEnrichment({
365
- id: "enrich_passenger_info",
366
- fields: ["passengers"] as const,
367
- enricher: async (context, data) => {
368
- // Add passenger type classification - return fields that exist in FlightData
369
- const cabinClass = data.passengers === 1 ? "business" : data.passengers <= 4 ? "economy" : "economy";
370
- return {
371
- cabinClass, // This matches the cabinClass field in FlightData
372
- };
373
- },
374
- });
375
-
376
- // Method 4: Create validation tool using the helper
377
- const flightDataValidator = agent.tool.createValidation({
378
- id: "validate_flight_data",
379
- fields: ["destination", "departureDate", "passengers"] as const,
380
- validator: async (context, data) => {
381
- const errors: ValidationError[] = [];
382
- if (!data.destination) errors.push({
383
- field: "destination",
384
- value: data.destination,
385
- message: "Destination is required",
386
- schemaPath: "destination"
387
- });
388
- if (!data.departureDate) errors.push({
389
- field: "departureDate",
390
- value: data.departureDate,
391
- message: "Departure date is required",
392
- schemaPath: "departureDate"
393
- });
394
- if (!data.passengers || data.passengers < 1) errors.push({
395
- field: "passengers",
396
- value: data.passengers,
397
- message: "At least 1 passenger required",
398
- schemaPath: "passengers"
399
- });
400
-
401
- return {
402
- valid: errors.length === 0,
403
- errors,
404
- warnings: [],
405
- };
406
- },
407
- });
408
-
409
- // Define route with data extraction
410
- const bookingRoute = agent.createRoute({
411
- title: "Book Flight",
412
- description: "Help user book a flight",
413
- when: [
414
- "User wants to book a flight",
415
- "User mentions flying, traveling, or booking",
416
- ],
417
- // NEW: Required fields for route completion
418
- requiredFields: ["destination", "departureDate", "passengers"],
419
- // NEW: Optional fields that enhance the experience
420
- optionalFields: ["destinationCode", "departureDateParsed", "cabinClass", "shouldSearchFlights"],
421
- });
422
-
423
- // Method 5: Add route-scoped tools (only available in this route)
424
- bookingRoute.addTool({
425
- id: "route_specific_tool",
426
- description: "Tool only available in booking route",
427
- handler: () => "This tool is scoped to the booking route only",
428
- });
429
-
430
- // Step 1: Collect destination
431
- const collectDestination = bookingRoute.initialStep.nextStep({
432
- prompt: "Ask where they want to fly",
433
- collect: ["destination"],
434
- skipIf: (ctx) => !!ctx.data?.destination,
435
- });
436
-
437
- // Step 2: Enrich destination (tool execution)
438
- const enrichDestination = collectDestination.nextStep({
439
- tools: ["enrich_destination"], // Reference by ID
440
- requires: ["destination"],
441
- });
442
-
443
- // Step 3: Collect date
444
- const collectDate = enrichDestination.nextStep({
445
- prompt: "Ask when they want to depart",
446
- collect: ["departureDate"],
447
- skipIf: (ctx) => !!ctx.data?.departureDate,
448
- });
449
-
450
- // Step 4: Validate/parse date (tool execution)
451
- const validateDate = collectDate.nextStep({
452
- tools: ["validate_date"], // Reference by ID
453
- requires: ["departureDate"],
454
- });
455
-
456
- // Step 5: Collect passengers
457
- const collectPassengers = validateDate.nextStep({
458
- prompt: "Ask how many passengers",
459
- collect: ["passengers"],
460
- skipIf: (ctx) => !!ctx.data?.passengers,
461
- });
462
-
463
- // Step 6: Search flights (triggered by hook setting shouldSearchFlights)
464
- const searchFlights = collectPassengers.nextStep({
465
- tools: ["search_flights"], // Reference by ID
466
- // This step is entered when shouldSearchFlights is true
467
- // The hook automatically sets this flag when all data is collected
468
- });
469
-
470
- // Step 7: Present results
471
- const presentResults = searchFlights.nextStep({
472
- prompt: "Present available flights to the user",
473
- });
474
-
475
- // Step 8: Confirm booking
476
- const confirmBooking = presentResults.nextStep({
477
- prompt: "Ask user to confirm the booking",
478
- requires: ["destinationCode", "departureDateParsed", "passengers"],
479
- });
480
-
481
- // Method 6: Step-scoped tools can be added via the step's tools array
482
- // Note: Step-scoped tools are typically defined inline in the step configuration
483
-
484
- // Step 9: Finalize booking
485
- const finalizeBooking = confirmBooking.nextStep({
486
- tools: ["book_flight"], // Reference by ID
487
- when: "User confirms the booking",
488
- });
489
-
490
- // Step 10: End of conversation
491
- finalizeBooking.nextStep({ step: END_ROUTE });
492
-
493
- // ==============================================================================
494
- // USAGE EXAMPLE: Three-Phase Pipeline Demonstration
495
- // ==============================================================================
496
-
497
- async function main() {
498
- // Session is automatically managed by the agent
499
- console.log("✨ Session ready:", agent.session.id);
500
-
501
- // Turn 1: User provides everything at once
502
- await agent.session.addMessage("user", "I want to fly to Paris tomorrow with 2 passengers");
503
-
504
- const response = await agent.respond({
505
- history: agent.session.getHistory()
506
- });
507
-
508
- console.log("\n=== RESPONSE ===");
509
- console.log("Message:", response.message);
510
- console.log("Data:", agent.session.getData());
511
- console.log("Context:", agent["context"]);
512
-
513
- await agent.session.addMessage("assistant", response.message);
514
-
515
- if (response.isRouteComplete) {
516
- console.log("\n✅ Flight booking complete!");
517
- await sendBookingConfirmation(agent.session.getData());
518
- }
519
-
520
- /*
521
- * Expected flow:
522
- * 1. AI extracts: { destination: "Paris", departureDate: "tomorrow", passengers: 2 }
523
- * 2. Hook validates passengers ✓
524
- * 3. Hook detects all data present, sets shouldSearchFlights: true
525
- * 4. Step machine:
526
- * - Skips collectDestination (has destination)
527
- * - Runs enrichDestination tool → adds destinationCode: "CDG"
528
- * - Skips collectDate (has departureDate)
529
- * - Runs validateDate tool → adds departureDateParsed: "2025-10-16"
530
- * - Skips collectPassengers (has passengers)
531
- * - Runs searchFlights tool → updates context with flights, clears flag
532
- * - Enters presentResults step
533
- * 5. AI generates response with flight options
534
- */
535
- }
536
-
537
- /**
538
- * Mock function to send a booking confirmation.
539
- * @param data - The flight booking data.
540
- */
541
- async function sendBookingConfirmation(data: Partial<FlightData> | undefined) {
542
- console.log("\n" + "=".repeat(60));
543
- console.log("🚀 Sending Booking Confirmation...");
544
- console.log("=".repeat(60));
545
- console.log("Booking Details:", JSON.stringify(data, null, 2));
546
- console.log(
547
- ` - Sending confirmation for flight to ${data?.destinationCode} on ${
548
- data?.departureDateParsed ?? ""
549
- }.`
550
- );
551
- await new Promise((resolve) => setTimeout(resolve, 1000));
552
- console.log("✨ Confirmation sent!");
553
- }
554
-
555
- // ==============================================================================
556
- // KEY TAKEAWAYS: Architecture Principles Demonstrated
557
- // ==============================================================================
558
-
559
- /*
560
- * 1. SCHEMA-FIRST DATA EXTRACTION
561
- * - Define data contracts upfront with JSON Schema
562
- * - Type-safe extraction throughout the conversation
563
- * - Predictable data structure every time
564
- *
565
- * 2. CODE-BASED STEP LOGIC
566
- * - Use TypeScript functions (skipIf, requires) instead of LLM conditions
567
- * - Deterministic flow based on collected data
568
- * - No fuzzy LLM interpretation of step logic
569
- *
570
- * 3. TOOLS ENRICH COLLECTED DATA (PREPARATION Phase)
571
- * - Tools modify collected data via `dataUpdate`
572
- * - Great for: validation, enrichment, normalization, computed fields
573
- * - Execute before AI sees the conversation
574
- *
575
- * 4. LIFECYCLE HOOKS (RESPONSE Phase)
576
- * - onDataUpdate runs after each data extraction
577
- * - Cross-cutting logic: validation, business rules, auto-triggering
578
- * - Return modified collected data
579
- *
580
- * 5. THREE-PHASE PIPELINE
581
- * - PREPARATION: Tools execute and enrich context/data
582
- * - ROUTING: AI scores routes based on current step
583
- * - RESPONSE: AI generates message with schema-enforced extraction
584
- *
585
- * 6. SESSION STEP MANAGEMENT
586
- * - Collected data persists across conversation turns
587
- * - Always-on routing respects user intent changes
588
- * - Step recovery enables conversation resumption
589
- */
590
-
591
- if (require.main === module) {
592
- main().catch(console.error);
593
- }