@falai/agent 3.4.5 → 4.0.0-alpha.10

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 (865) hide show
  1. package/README.md +41 -34
  2. package/dist/cjs/core/Agent.d.ts +29 -378
  3. package/dist/cjs/core/Agent.d.ts.map +1 -1
  4. package/dist/cjs/core/Agent.js +113 -1178
  5. package/dist/cjs/core/Agent.js.map +1 -1
  6. package/dist/cjs/core/CompactionEngine.d.ts.map +1 -1
  7. package/dist/cjs/core/CompactionEngine.js +5 -3
  8. package/dist/cjs/core/CompactionEngine.js.map +1 -1
  9. package/dist/cjs/core/FlowSpec.d.ts +136 -0
  10. package/dist/cjs/core/FlowSpec.d.ts.map +1 -0
  11. package/dist/cjs/core/FlowSpec.js +573 -0
  12. package/dist/cjs/core/FlowSpec.js.map +1 -0
  13. package/dist/cjs/core/Migrate.d.ts +38 -0
  14. package/dist/cjs/core/Migrate.d.ts.map +1 -0
  15. package/dist/cjs/core/Migrate.js +270 -0
  16. package/dist/cjs/core/Migrate.js.map +1 -0
  17. package/dist/cjs/core/Prompt.d.ts +54 -0
  18. package/dist/cjs/core/Prompt.d.ts.map +1 -0
  19. package/dist/cjs/core/Prompt.js +149 -0
  20. package/dist/cjs/core/Prompt.js.map +1 -0
  21. package/dist/cjs/core/Runner.d.ts +171 -0
  22. package/dist/cjs/core/Runner.d.ts.map +1 -0
  23. package/dist/cjs/core/Runner.js +1158 -0
  24. package/dist/cjs/core/Runner.js.map +1 -0
  25. package/dist/cjs/core/Speak.d.ts +37 -0
  26. package/dist/cjs/core/Speak.d.ts.map +1 -0
  27. package/dist/cjs/core/Speak.js +373 -0
  28. package/dist/cjs/core/Speak.js.map +1 -0
  29. package/dist/cjs/core/Understand.d.ts +28 -0
  30. package/dist/cjs/core/Understand.d.ts.map +1 -0
  31. package/dist/cjs/core/Understand.js +357 -0
  32. package/dist/cjs/core/Understand.js.map +1 -0
  33. package/dist/cjs/core/contracts.d.ts +122 -0
  34. package/dist/cjs/core/contracts.d.ts.map +1 -0
  35. package/dist/cjs/core/contracts.js +11 -0
  36. package/dist/cjs/core/contracts.js.map +1 -0
  37. package/dist/cjs/core/falai.d.ts +57 -0
  38. package/dist/cjs/core/falai.d.ts.map +1 -0
  39. package/dist/cjs/core/falai.js +43 -0
  40. package/dist/cjs/core/falai.js.map +1 -0
  41. package/dist/cjs/core/predicate.d.ts +9 -0
  42. package/dist/cjs/core/predicate.d.ts.map +1 -0
  43. package/dist/cjs/core/predicate.js +58 -0
  44. package/dist/cjs/core/predicate.js.map +1 -0
  45. package/dist/cjs/index.d.ts +26 -31
  46. package/dist/cjs/index.d.ts.map +1 -1
  47. package/dist/cjs/index.js +46 -68
  48. package/dist/cjs/index.js.map +1 -1
  49. package/dist/cjs/persistence/MemoryStore.d.ts +15 -0
  50. package/dist/cjs/persistence/MemoryStore.d.ts.map +1 -0
  51. package/dist/cjs/persistence/MemoryStore.js +39 -0
  52. package/dist/cjs/persistence/MemoryStore.js.map +1 -0
  53. package/dist/cjs/persistence/MongoStore.d.ts +42 -0
  54. package/dist/cjs/persistence/MongoStore.d.ts.map +1 -0
  55. package/dist/cjs/persistence/MongoStore.js +60 -0
  56. package/dist/cjs/persistence/MongoStore.js.map +1 -0
  57. package/dist/cjs/persistence/OpenSearchStore.d.ts +86 -0
  58. package/dist/cjs/persistence/OpenSearchStore.d.ts.map +1 -0
  59. package/dist/cjs/persistence/OpenSearchStore.js +120 -0
  60. package/dist/cjs/persistence/OpenSearchStore.js.map +1 -0
  61. package/dist/cjs/persistence/PostgresStore.d.ts +41 -0
  62. package/dist/cjs/persistence/PostgresStore.d.ts.map +1 -0
  63. package/dist/cjs/persistence/PostgresStore.js +58 -0
  64. package/dist/cjs/persistence/PostgresStore.js.map +1 -0
  65. package/dist/cjs/persistence/PrismaStore.d.ts +65 -0
  66. package/dist/cjs/persistence/PrismaStore.d.ts.map +1 -0
  67. package/dist/cjs/persistence/PrismaStore.js +95 -0
  68. package/dist/cjs/persistence/PrismaStore.js.map +1 -0
  69. package/dist/cjs/persistence/RedisStore.d.ts +34 -0
  70. package/dist/cjs/persistence/RedisStore.d.ts.map +1 -0
  71. package/dist/cjs/persistence/RedisStore.js +61 -0
  72. package/dist/cjs/persistence/RedisStore.js.map +1 -0
  73. package/dist/cjs/persistence/SQLiteStore.d.ts +45 -0
  74. package/dist/cjs/persistence/SQLiteStore.d.ts.map +1 -0
  75. package/dist/cjs/persistence/SQLiteStore.js +74 -0
  76. package/dist/cjs/persistence/SQLiteStore.js.map +1 -0
  77. package/dist/cjs/persistence/sessionRow.d.ts +14 -0
  78. package/dist/cjs/persistence/sessionRow.d.ts.map +1 -0
  79. package/dist/cjs/persistence/sessionRow.js +50 -0
  80. package/dist/cjs/persistence/sessionRow.js.map +1 -0
  81. package/dist/cjs/providers/DeepSeekProvider.d.ts.map +1 -1
  82. package/dist/cjs/providers/DeepSeekProvider.js +8 -3
  83. package/dist/cjs/providers/DeepSeekProvider.js.map +1 -1
  84. package/dist/cjs/providers/GeminiProvider.d.ts +4 -3
  85. package/dist/cjs/providers/GeminiProvider.d.ts.map +1 -1
  86. package/dist/cjs/providers/GeminiProvider.js +4 -3
  87. package/dist/cjs/providers/GeminiProvider.js.map +1 -1
  88. package/dist/cjs/providers/OpenAICompatibleProvider.d.ts +4 -0
  89. package/dist/cjs/providers/OpenAICompatibleProvider.d.ts.map +1 -1
  90. package/dist/cjs/providers/OpenAICompatibleProvider.js +2 -0
  91. package/dist/cjs/providers/OpenAICompatibleProvider.js.map +1 -1
  92. package/dist/cjs/providers/OpenRouterProvider.d.ts.map +1 -1
  93. package/dist/cjs/providers/OpenRouterProvider.js +2 -4
  94. package/dist/cjs/providers/OpenRouterProvider.js.map +1 -1
  95. package/dist/cjs/providers/ProviderAdapter.d.ts +11 -6
  96. package/dist/cjs/providers/ProviderAdapter.d.ts.map +1 -1
  97. package/dist/cjs/providers/ProviderAdapter.js +33 -10
  98. package/dist/cjs/providers/ProviderAdapter.js.map +1 -1
  99. package/dist/cjs/providers/ZaiProvider.d.ts +6 -4
  100. package/dist/cjs/providers/ZaiProvider.d.ts.map +1 -1
  101. package/dist/cjs/providers/ZaiProvider.js +6 -4
  102. package/dist/cjs/providers/ZaiProvider.js.map +1 -1
  103. package/dist/cjs/types/agent.d.ts +163 -383
  104. package/dist/cjs/types/agent.d.ts.map +1 -1
  105. package/dist/cjs/types/agent.js +1 -1
  106. package/dist/cjs/types/ai.d.ts +32 -1
  107. package/dist/cjs/types/ai.d.ts.map +1 -1
  108. package/dist/cjs/types/compaction.d.ts +3 -1
  109. package/dist/cjs/types/compaction.d.ts.map +1 -1
  110. package/dist/cjs/types/errors.d.ts +9 -12
  111. package/dist/cjs/types/errors.d.ts.map +1 -1
  112. package/dist/cjs/types/errors.js +14 -17
  113. package/dist/cjs/types/errors.js.map +1 -1
  114. package/dist/cjs/types/flow.d.ts +265 -513
  115. package/dist/cjs/types/flow.d.ts.map +1 -1
  116. package/dist/cjs/types/flow.js +7 -1
  117. package/dist/cjs/types/flow.js.map +1 -1
  118. package/dist/cjs/types/history.d.ts +7 -18
  119. package/dist/cjs/types/history.d.ts.map +1 -1
  120. package/dist/cjs/types/history.js.map +1 -1
  121. package/dist/cjs/types/index.d.ts +9 -15
  122. package/dist/cjs/types/index.d.ts.map +1 -1
  123. package/dist/cjs/types/index.js +4 -14
  124. package/dist/cjs/types/index.js.map +1 -1
  125. package/dist/cjs/types/session.d.ts +94 -64
  126. package/dist/cjs/types/session.d.ts.map +1 -1
  127. package/dist/cjs/types/session.js +5 -1
  128. package/dist/cjs/types/session.js.map +1 -1
  129. package/dist/cjs/types/tool.d.ts +37 -207
  130. package/dist/cjs/types/tool.d.ts.map +1 -1
  131. package/dist/cjs/types/tool.js +5 -14
  132. package/dist/cjs/types/tool.js.map +1 -1
  133. package/dist/cjs/utils/clock.d.ts +28 -0
  134. package/dist/cjs/utils/clock.d.ts.map +1 -0
  135. package/dist/cjs/utils/clock.js +64 -0
  136. package/dist/cjs/utils/clock.js.map +1 -0
  137. package/dist/cjs/utils/duration.d.ts +11 -0
  138. package/dist/cjs/utils/duration.d.ts.map +1 -0
  139. package/dist/cjs/utils/duration.js +31 -0
  140. package/dist/cjs/utils/duration.js.map +1 -0
  141. package/dist/cjs/utils/history.d.ts +4 -1
  142. package/dist/cjs/utils/history.d.ts.map +1 -1
  143. package/dist/cjs/utils/history.js +2 -2
  144. package/dist/cjs/utils/history.js.map +1 -1
  145. package/dist/cjs/utils/index.d.ts +4 -10
  146. package/dist/cjs/utils/index.d.ts.map +1 -1
  147. package/dist/cjs/utils/index.js +14 -61
  148. package/dist/cjs/utils/index.js.map +1 -1
  149. package/dist/cjs/utils/json.d.ts +2 -0
  150. package/dist/cjs/utils/json.d.ts.map +1 -1
  151. package/dist/cjs/utils/json.js +5 -0
  152. package/dist/cjs/utils/json.js.map +1 -1
  153. package/dist/cjs/utils/outcomes.d.ts +48 -0
  154. package/dist/cjs/utils/outcomes.d.ts.map +1 -0
  155. package/dist/cjs/utils/outcomes.js +51 -0
  156. package/dist/cjs/utils/outcomes.js.map +1 -0
  157. package/dist/cjs/utils/phrases.d.ts +25 -0
  158. package/dist/cjs/utils/phrases.d.ts.map +1 -0
  159. package/dist/cjs/utils/phrases.js +38 -0
  160. package/dist/cjs/utils/phrases.js.map +1 -0
  161. package/dist/cjs/utils/schema.d.ts +50 -0
  162. package/dist/cjs/utils/schema.d.ts.map +1 -0
  163. package/dist/cjs/utils/schema.js +138 -0
  164. package/dist/cjs/utils/schema.js.map +1 -0
  165. package/dist/cjs/utils/streamingMessage.d.ts +3 -2
  166. package/dist/cjs/utils/streamingMessage.d.ts.map +1 -1
  167. package/dist/cjs/utils/streamingMessage.js +38 -4
  168. package/dist/cjs/utils/streamingMessage.js.map +1 -1
  169. package/dist/cjs/utils/template.d.ts +22 -150
  170. package/dist/cjs/utils/template.d.ts.map +1 -1
  171. package/dist/cjs/utils/template.js +64 -359
  172. package/dist/cjs/utils/template.js.map +1 -1
  173. package/dist/cjs/utils/usage.d.ts +19 -0
  174. package/dist/cjs/utils/usage.d.ts.map +1 -0
  175. package/dist/cjs/utils/usage.js +35 -0
  176. package/dist/cjs/utils/usage.js.map +1 -0
  177. package/dist/core/Agent.d.ts +29 -378
  178. package/dist/core/Agent.d.ts.map +1 -1
  179. package/dist/core/Agent.js +116 -1181
  180. package/dist/core/Agent.js.map +1 -1
  181. package/dist/core/CompactionEngine.d.ts.map +1 -1
  182. package/dist/core/CompactionEngine.js +5 -3
  183. package/dist/core/CompactionEngine.js.map +1 -1
  184. package/dist/core/FlowSpec.d.ts +136 -0
  185. package/dist/core/FlowSpec.d.ts.map +1 -0
  186. package/dist/core/FlowSpec.js +567 -0
  187. package/dist/core/FlowSpec.js.map +1 -0
  188. package/dist/core/Migrate.d.ts +38 -0
  189. package/dist/core/Migrate.d.ts.map +1 -0
  190. package/dist/core/Migrate.js +264 -0
  191. package/dist/core/Migrate.js.map +1 -0
  192. package/dist/core/Prompt.d.ts +54 -0
  193. package/dist/core/Prompt.d.ts.map +1 -0
  194. package/dist/core/Prompt.js +139 -0
  195. package/dist/core/Prompt.js.map +1 -0
  196. package/dist/core/Runner.d.ts +171 -0
  197. package/dist/core/Runner.d.ts.map +1 -0
  198. package/dist/core/Runner.js +1154 -0
  199. package/dist/core/Runner.js.map +1 -0
  200. package/dist/core/Speak.d.ts +37 -0
  201. package/dist/core/Speak.d.ts.map +1 -0
  202. package/dist/core/Speak.js +369 -0
  203. package/dist/core/Speak.js.map +1 -0
  204. package/dist/core/Understand.d.ts +28 -0
  205. package/dist/core/Understand.d.ts.map +1 -0
  206. package/dist/core/Understand.js +353 -0
  207. package/dist/core/Understand.js.map +1 -0
  208. package/dist/core/contracts.d.ts +122 -0
  209. package/dist/core/contracts.d.ts.map +1 -0
  210. package/dist/core/contracts.js +10 -0
  211. package/dist/core/contracts.js.map +1 -0
  212. package/dist/core/falai.d.ts +57 -0
  213. package/dist/core/falai.d.ts.map +1 -0
  214. package/dist/core/falai.js +40 -0
  215. package/dist/core/falai.js.map +1 -0
  216. package/dist/core/predicate.d.ts +9 -0
  217. package/dist/core/predicate.d.ts.map +1 -0
  218. package/dist/core/predicate.js +54 -0
  219. package/dist/core/predicate.js.map +1 -0
  220. package/dist/index.d.ts +26 -31
  221. package/dist/index.d.ts.map +1 -1
  222. package/dist/index.js +19 -24
  223. package/dist/index.js.map +1 -1
  224. package/dist/persistence/MemoryStore.d.ts +15 -0
  225. package/dist/persistence/MemoryStore.d.ts.map +1 -0
  226. package/dist/persistence/MemoryStore.js +35 -0
  227. package/dist/persistence/MemoryStore.js.map +1 -0
  228. package/dist/persistence/MongoStore.d.ts +42 -0
  229. package/dist/persistence/MongoStore.d.ts.map +1 -0
  230. package/dist/persistence/MongoStore.js +56 -0
  231. package/dist/persistence/MongoStore.js.map +1 -0
  232. package/dist/persistence/OpenSearchStore.d.ts +86 -0
  233. package/dist/persistence/OpenSearchStore.d.ts.map +1 -0
  234. package/dist/persistence/OpenSearchStore.js +116 -0
  235. package/dist/persistence/OpenSearchStore.js.map +1 -0
  236. package/dist/persistence/PostgresStore.d.ts +41 -0
  237. package/dist/persistence/PostgresStore.d.ts.map +1 -0
  238. package/dist/persistence/PostgresStore.js +54 -0
  239. package/dist/persistence/PostgresStore.js.map +1 -0
  240. package/dist/persistence/PrismaStore.d.ts +65 -0
  241. package/dist/persistence/PrismaStore.d.ts.map +1 -0
  242. package/dist/persistence/PrismaStore.js +91 -0
  243. package/dist/persistence/PrismaStore.js.map +1 -0
  244. package/dist/persistence/RedisStore.d.ts +34 -0
  245. package/dist/persistence/RedisStore.d.ts.map +1 -0
  246. package/dist/persistence/RedisStore.js +57 -0
  247. package/dist/persistence/RedisStore.js.map +1 -0
  248. package/dist/persistence/SQLiteStore.d.ts +45 -0
  249. package/dist/persistence/SQLiteStore.d.ts.map +1 -0
  250. package/dist/persistence/SQLiteStore.js +70 -0
  251. package/dist/persistence/SQLiteStore.js.map +1 -0
  252. package/dist/persistence/sessionRow.d.ts +14 -0
  253. package/dist/persistence/sessionRow.d.ts.map +1 -0
  254. package/dist/persistence/sessionRow.js +45 -0
  255. package/dist/persistence/sessionRow.js.map +1 -0
  256. package/dist/providers/DeepSeekProvider.d.ts.map +1 -1
  257. package/dist/providers/DeepSeekProvider.js +8 -3
  258. package/dist/providers/DeepSeekProvider.js.map +1 -1
  259. package/dist/providers/GeminiProvider.d.ts +4 -3
  260. package/dist/providers/GeminiProvider.d.ts.map +1 -1
  261. package/dist/providers/GeminiProvider.js +4 -3
  262. package/dist/providers/GeminiProvider.js.map +1 -1
  263. package/dist/providers/OpenAICompatibleProvider.d.ts +4 -0
  264. package/dist/providers/OpenAICompatibleProvider.d.ts.map +1 -1
  265. package/dist/providers/OpenAICompatibleProvider.js +2 -0
  266. package/dist/providers/OpenAICompatibleProvider.js.map +1 -1
  267. package/dist/providers/OpenRouterProvider.d.ts.map +1 -1
  268. package/dist/providers/OpenRouterProvider.js +2 -4
  269. package/dist/providers/OpenRouterProvider.js.map +1 -1
  270. package/dist/providers/ProviderAdapter.d.ts +11 -6
  271. package/dist/providers/ProviderAdapter.d.ts.map +1 -1
  272. package/dist/providers/ProviderAdapter.js +34 -11
  273. package/dist/providers/ProviderAdapter.js.map +1 -1
  274. package/dist/providers/ZaiProvider.d.ts +6 -4
  275. package/dist/providers/ZaiProvider.d.ts.map +1 -1
  276. package/dist/providers/ZaiProvider.js +6 -4
  277. package/dist/providers/ZaiProvider.js.map +1 -1
  278. package/dist/types/agent.d.ts +163 -383
  279. package/dist/types/agent.d.ts.map +1 -1
  280. package/dist/types/agent.js +1 -1
  281. package/dist/types/ai.d.ts +32 -1
  282. package/dist/types/ai.d.ts.map +1 -1
  283. package/dist/types/compaction.d.ts +3 -1
  284. package/dist/types/compaction.d.ts.map +1 -1
  285. package/dist/types/errors.d.ts +9 -12
  286. package/dist/types/errors.d.ts.map +1 -1
  287. package/dist/types/errors.js +12 -15
  288. package/dist/types/errors.js.map +1 -1
  289. package/dist/types/flow.d.ts +265 -513
  290. package/dist/types/flow.d.ts.map +1 -1
  291. package/dist/types/flow.js +7 -1
  292. package/dist/types/flow.js.map +1 -1
  293. package/dist/types/history.d.ts +7 -18
  294. package/dist/types/history.d.ts.map +1 -1
  295. package/dist/types/history.js.map +1 -1
  296. package/dist/types/index.d.ts +9 -15
  297. package/dist/types/index.d.ts.map +1 -1
  298. package/dist/types/index.js +2 -7
  299. package/dist/types/index.js.map +1 -1
  300. package/dist/types/session.d.ts +94 -64
  301. package/dist/types/session.d.ts.map +1 -1
  302. package/dist/types/session.js +5 -1
  303. package/dist/types/session.js.map +1 -1
  304. package/dist/types/tool.d.ts +37 -207
  305. package/dist/types/tool.d.ts.map +1 -1
  306. package/dist/types/tool.js +6 -13
  307. package/dist/types/tool.js.map +1 -1
  308. package/dist/utils/clock.d.ts +28 -0
  309. package/dist/utils/clock.d.ts.map +1 -0
  310. package/dist/utils/clock.js +59 -0
  311. package/dist/utils/clock.js.map +1 -0
  312. package/dist/utils/duration.d.ts +11 -0
  313. package/dist/utils/duration.d.ts.map +1 -0
  314. package/dist/utils/duration.js +26 -0
  315. package/dist/utils/duration.js.map +1 -0
  316. package/dist/utils/history.d.ts +4 -1
  317. package/dist/utils/history.d.ts.map +1 -1
  318. package/dist/utils/history.js +2 -2
  319. package/dist/utils/history.js.map +1 -1
  320. package/dist/utils/index.d.ts +4 -10
  321. package/dist/utils/index.d.ts.map +1 -1
  322. package/dist/utils/index.js +4 -21
  323. package/dist/utils/index.js.map +1 -1
  324. package/dist/utils/json.d.ts +2 -0
  325. package/dist/utils/json.d.ts.map +1 -1
  326. package/dist/utils/json.js +4 -0
  327. package/dist/utils/json.js.map +1 -1
  328. package/dist/utils/outcomes.d.ts +48 -0
  329. package/dist/utils/outcomes.d.ts.map +1 -0
  330. package/dist/utils/outcomes.js +48 -0
  331. package/dist/utils/outcomes.js.map +1 -0
  332. package/dist/utils/phrases.d.ts +25 -0
  333. package/dist/utils/phrases.d.ts.map +1 -0
  334. package/dist/utils/phrases.js +35 -0
  335. package/dist/utils/phrases.js.map +1 -0
  336. package/dist/utils/schema.d.ts +50 -0
  337. package/dist/utils/schema.d.ts.map +1 -0
  338. package/dist/utils/schema.js +129 -0
  339. package/dist/utils/schema.js.map +1 -0
  340. package/dist/utils/streamingMessage.d.ts +3 -2
  341. package/dist/utils/streamingMessage.d.ts.map +1 -1
  342. package/dist/utils/streamingMessage.js +38 -4
  343. package/dist/utils/streamingMessage.js.map +1 -1
  344. package/dist/utils/template.d.ts +22 -150
  345. package/dist/utils/template.d.ts.map +1 -1
  346. package/dist/utils/template.js +61 -351
  347. package/dist/utils/template.js.map +1 -1
  348. package/dist/utils/usage.d.ts +19 -0
  349. package/dist/utils/usage.d.ts.map +1 -0
  350. package/dist/utils/usage.js +31 -0
  351. package/dist/utils/usage.js.map +1 -0
  352. package/docs/README.md +37 -19
  353. package/docs/concepts/architecture.md +117 -239
  354. package/docs/concepts/collection.md +170 -0
  355. package/docs/concepts/pipeline.md +132 -378
  356. package/docs/concepts/runs-and-waits.md +192 -0
  357. package/docs/guides/actions-and-events.md +276 -0
  358. package/docs/guides/branching.md +119 -208
  359. package/docs/guides/compaction.md +63 -158
  360. package/docs/guides/conditions.md +164 -128
  361. package/docs/guides/error-handling.md +170 -164
  362. package/docs/guides/flow-control.md +210 -349
  363. package/docs/guides/flows-from-json.md +224 -0
  364. package/docs/guides/instructions.md +125 -161
  365. package/docs/guides/persistence.md +182 -206
  366. package/docs/guides/streaming.md +50 -114
  367. package/docs/guides/testing.md +284 -0
  368. package/docs/guides/triggers.md +401 -0
  369. package/docs/migration/README.md +8 -15
  370. package/docs/migration/v1-to-v2.md +1 -1
  371. package/docs/migration/v2-3-to-v2-4.md +2 -2
  372. package/docs/migration/v2-6-to-v2-7.md +4 -4
  373. package/docs/migration/v3-to-v4.md +457 -0
  374. package/docs/reference/actions-events-conditions.md +396 -0
  375. package/docs/reference/agent.md +248 -0
  376. package/docs/reference/branches.md +75 -203
  377. package/docs/reference/errors.md +188 -144
  378. package/docs/reference/fields.md +125 -0
  379. package/docs/reference/flow-spec.md +248 -0
  380. package/docs/reference/flow.md +104 -192
  381. package/docs/reference/instruction.md +83 -137
  382. package/docs/reference/outcomes.md +273 -0
  383. package/docs/reference/providers.md +525 -302
  384. package/docs/reference/session.md +210 -0
  385. package/docs/reference/step.md +194 -312
  386. package/docs/reference/stores.md +496 -0
  387. package/docs/reference/tool.md +162 -231
  388. package/docs/reference/trigger.md +200 -0
  389. package/docs/rfc/v4-one-flow.md +477 -0
  390. package/docs/start/01-install.md +59 -44
  391. package/docs/start/02-first-agent.md +97 -147
  392. package/docs/start/03-collect-data.md +78 -183
  393. package/docs/start/04-add-tools.md +159 -227
  394. package/docs/start/05-go-to-production.md +181 -163
  395. package/examples/01-quickstart.ts +26 -16
  396. package/examples/02-fields.ts +75 -0
  397. package/examples/03-tools.ts +79 -119
  398. package/examples/04-instructions.ts +60 -87
  399. package/examples/05-branches.ts +78 -0
  400. package/examples/06-triggers-and-waits.ts +149 -0
  401. package/examples/07-streaming.ts +34 -60
  402. package/examples/08-store-and-migration.ts +97 -0
  403. package/examples/09-flows-from-json.ts +107 -0
  404. package/package.json +11 -6
  405. package/src/core/Agent.ts +126 -1512
  406. package/src/core/CompactionEngine.ts +7 -4
  407. package/src/core/FlowSpec.ts +778 -0
  408. package/src/core/Migrate.ts +256 -0
  409. package/src/core/Prompt.ts +162 -0
  410. package/src/core/Runner.ts +1214 -0
  411. package/src/core/Speak.ts +460 -0
  412. package/src/core/Understand.ts +423 -0
  413. package/src/core/contracts.ts +111 -0
  414. package/src/core/falai.ts +86 -0
  415. package/src/core/predicate.ts +56 -0
  416. package/src/index.ts +120 -147
  417. package/src/persistence/MemoryStore.ts +37 -0
  418. package/src/persistence/MongoStore.ts +89 -0
  419. package/src/persistence/OpenSearchStore.ts +153 -0
  420. package/src/persistence/PostgresStore.ts +89 -0
  421. package/src/persistence/PrismaStore.ts +127 -0
  422. package/src/persistence/RedisStore.ts +90 -0
  423. package/src/persistence/SQLiteStore.ts +103 -0
  424. package/src/persistence/sessionRow.ts +45 -0
  425. package/src/providers/DeepSeekProvider.ts +8 -3
  426. package/src/providers/GeminiProvider.ts +4 -3
  427. package/src/providers/OpenAICompatibleProvider.ts +6 -0
  428. package/src/providers/OpenRouterProvider.ts +2 -4
  429. package/src/providers/ProviderAdapter.ts +46 -13
  430. package/src/providers/ZaiProvider.ts +6 -4
  431. package/src/types/agent.ts +135 -397
  432. package/src/types/ai.ts +33 -1
  433. package/src/types/compaction.ts +3 -1
  434. package/src/types/errors.ts +13 -16
  435. package/src/types/flow.ts +249 -550
  436. package/src/types/history.ts +7 -20
  437. package/src/types/index.ts +88 -139
  438. package/src/types/session.ts +135 -70
  439. package/src/types/tool.ts +42 -267
  440. package/src/utils/clock.ts +70 -0
  441. package/src/utils/duration.ts +33 -0
  442. package/src/utils/history.ts +3 -2
  443. package/src/utils/index.ts +8 -66
  444. package/src/utils/json.ts +5 -0
  445. package/src/utils/outcomes.ts +56 -0
  446. package/src/utils/phrases.ts +40 -0
  447. package/src/utils/schema.ts +145 -0
  448. package/src/utils/streamingMessage.ts +34 -4
  449. package/src/utils/template.ts +63 -418
  450. package/src/utils/usage.ts +37 -0
  451. package/dist/adapters/MemoryAdapter.d.ts +0 -47
  452. package/dist/adapters/MemoryAdapter.d.ts.map +0 -1
  453. package/dist/adapters/MemoryAdapter.js +0 -204
  454. package/dist/adapters/MemoryAdapter.js.map +0 -1
  455. package/dist/adapters/MongoAdapter.d.ts +0 -97
  456. package/dist/adapters/MongoAdapter.d.ts.map +0 -1
  457. package/dist/adapters/MongoAdapter.js +0 -196
  458. package/dist/adapters/MongoAdapter.js.map +0 -1
  459. package/dist/adapters/OpenSearchAdapter.d.ts +0 -169
  460. package/dist/adapters/OpenSearchAdapter.d.ts.map +0 -1
  461. package/dist/adapters/OpenSearchAdapter.js +0 -471
  462. package/dist/adapters/OpenSearchAdapter.js.map +0 -1
  463. package/dist/adapters/PostgreSQLAdapter.d.ts +0 -85
  464. package/dist/adapters/PostgreSQLAdapter.d.ts.map +0 -1
  465. package/dist/adapters/PostgreSQLAdapter.js +0 -308
  466. package/dist/adapters/PostgreSQLAdapter.js.map +0 -1
  467. package/dist/adapters/PrismaAdapter.d.ts +0 -115
  468. package/dist/adapters/PrismaAdapter.d.ts.map +0 -1
  469. package/dist/adapters/PrismaAdapter.js +0 -406
  470. package/dist/adapters/PrismaAdapter.js.map +0 -1
  471. package/dist/adapters/RedisAdapter.d.ts +0 -72
  472. package/dist/adapters/RedisAdapter.d.ts.map +0 -1
  473. package/dist/adapters/RedisAdapter.js +0 -286
  474. package/dist/adapters/RedisAdapter.js.map +0 -1
  475. package/dist/adapters/SQLiteAdapter.d.ts +0 -86
  476. package/dist/adapters/SQLiteAdapter.d.ts.map +0 -1
  477. package/dist/adapters/SQLiteAdapter.js +0 -337
  478. package/dist/adapters/SQLiteAdapter.js.map +0 -1
  479. package/dist/adapters/index.d.ts +0 -17
  480. package/dist/adapters/index.d.ts.map +0 -1
  481. package/dist/adapters/index.js +0 -11
  482. package/dist/adapters/index.js.map +0 -1
  483. package/dist/adapters/sessionRow.d.ts +0 -22
  484. package/dist/adapters/sessionRow.d.ts.map +0 -1
  485. package/dist/adapters/sessionRow.js +0 -48
  486. package/dist/adapters/sessionRow.js.map +0 -1
  487. package/dist/cjs/adapters/MemoryAdapter.d.ts +0 -47
  488. package/dist/cjs/adapters/MemoryAdapter.d.ts.map +0 -1
  489. package/dist/cjs/adapters/MemoryAdapter.js +0 -208
  490. package/dist/cjs/adapters/MemoryAdapter.js.map +0 -1
  491. package/dist/cjs/adapters/MongoAdapter.d.ts +0 -97
  492. package/dist/cjs/adapters/MongoAdapter.d.ts.map +0 -1
  493. package/dist/cjs/adapters/MongoAdapter.js +0 -200
  494. package/dist/cjs/adapters/MongoAdapter.js.map +0 -1
  495. package/dist/cjs/adapters/OpenSearchAdapter.d.ts +0 -169
  496. package/dist/cjs/adapters/OpenSearchAdapter.d.ts.map +0 -1
  497. package/dist/cjs/adapters/OpenSearchAdapter.js +0 -475
  498. package/dist/cjs/adapters/OpenSearchAdapter.js.map +0 -1
  499. package/dist/cjs/adapters/PostgreSQLAdapter.d.ts +0 -85
  500. package/dist/cjs/adapters/PostgreSQLAdapter.d.ts.map +0 -1
  501. package/dist/cjs/adapters/PostgreSQLAdapter.js +0 -312
  502. package/dist/cjs/adapters/PostgreSQLAdapter.js.map +0 -1
  503. package/dist/cjs/adapters/PrismaAdapter.d.ts +0 -115
  504. package/dist/cjs/adapters/PrismaAdapter.d.ts.map +0 -1
  505. package/dist/cjs/adapters/PrismaAdapter.js +0 -410
  506. package/dist/cjs/adapters/PrismaAdapter.js.map +0 -1
  507. package/dist/cjs/adapters/RedisAdapter.d.ts +0 -72
  508. package/dist/cjs/adapters/RedisAdapter.d.ts.map +0 -1
  509. package/dist/cjs/adapters/RedisAdapter.js +0 -290
  510. package/dist/cjs/adapters/RedisAdapter.js.map +0 -1
  511. package/dist/cjs/adapters/SQLiteAdapter.d.ts +0 -86
  512. package/dist/cjs/adapters/SQLiteAdapter.d.ts.map +0 -1
  513. package/dist/cjs/adapters/SQLiteAdapter.js +0 -341
  514. package/dist/cjs/adapters/SQLiteAdapter.js.map +0 -1
  515. package/dist/cjs/adapters/index.d.ts +0 -17
  516. package/dist/cjs/adapters/index.d.ts.map +0 -1
  517. package/dist/cjs/adapters/index.js +0 -21
  518. package/dist/cjs/adapters/index.js.map +0 -1
  519. package/dist/cjs/adapters/sessionRow.d.ts +0 -22
  520. package/dist/cjs/adapters/sessionRow.d.ts.map +0 -1
  521. package/dist/cjs/adapters/sessionRow.js +0 -52
  522. package/dist/cjs/adapters/sessionRow.js.map +0 -1
  523. package/dist/cjs/constants/index.d.ts +0 -1
  524. package/dist/cjs/constants/index.d.ts.map +0 -1
  525. package/dist/cjs/constants/index.js +0 -4
  526. package/dist/cjs/constants/index.js.map +0 -1
  527. package/dist/cjs/core/AutoChainExecutor.d.ts +0 -97
  528. package/dist/cjs/core/AutoChainExecutor.d.ts.map +0 -1
  529. package/dist/cjs/core/AutoChainExecutor.js +0 -288
  530. package/dist/cjs/core/AutoChainExecutor.js.map +0 -1
  531. package/dist/cjs/core/BranchEvaluator.d.ts +0 -55
  532. package/dist/cjs/core/BranchEvaluator.d.ts.map +0 -1
  533. package/dist/cjs/core/BranchEvaluator.js +0 -125
  534. package/dist/cjs/core/BranchEvaluator.js.map +0 -1
  535. package/dist/cjs/core/DirectiveChainTracker.d.ts +0 -49
  536. package/dist/cjs/core/DirectiveChainTracker.d.ts.map +0 -1
  537. package/dist/cjs/core/DirectiveChainTracker.js +0 -121
  538. package/dist/cjs/core/DirectiveChainTracker.js.map +0 -1
  539. package/dist/cjs/core/Events.d.ts +0 -26
  540. package/dist/cjs/core/Events.d.ts.map +0 -1
  541. package/dist/cjs/core/Events.js +0 -144
  542. package/dist/cjs/core/Events.js.map +0 -1
  543. package/dist/cjs/core/Flow.d.ts +0 -183
  544. package/dist/cjs/core/Flow.d.ts.map +0 -1
  545. package/dist/cjs/core/Flow.js +0 -551
  546. package/dist/cjs/core/Flow.js.map +0 -1
  547. package/dist/cjs/core/FlowRouter.d.ts +0 -183
  548. package/dist/cjs/core/FlowRouter.d.ts.map +0 -1
  549. package/dist/cjs/core/FlowRouter.js +0 -1047
  550. package/dist/cjs/core/FlowRouter.js.map +0 -1
  551. package/dist/cjs/core/PersistenceManager.d.ts +0 -114
  552. package/dist/cjs/core/PersistenceManager.d.ts.map +0 -1
  553. package/dist/cjs/core/PersistenceManager.js +0 -336
  554. package/dist/cjs/core/PersistenceManager.js.map +0 -1
  555. package/dist/cjs/core/PromptComposer.d.ts +0 -47
  556. package/dist/cjs/core/PromptComposer.d.ts.map +0 -1
  557. package/dist/cjs/core/PromptComposer.js +0 -397
  558. package/dist/cjs/core/PromptComposer.js.map +0 -1
  559. package/dist/cjs/core/PromptSectionCache.d.ts +0 -48
  560. package/dist/cjs/core/PromptSectionCache.d.ts.map +0 -1
  561. package/dist/cjs/core/PromptSectionCache.js +0 -108
  562. package/dist/cjs/core/PromptSectionCache.js.map +0 -1
  563. package/dist/cjs/core/ResponseEngine.d.ts +0 -43
  564. package/dist/cjs/core/ResponseEngine.d.ts.map +0 -1
  565. package/dist/cjs/core/ResponseEngine.js +0 -235
  566. package/dist/cjs/core/ResponseEngine.js.map +0 -1
  567. package/dist/cjs/core/ResponseGenerationError.d.ts +0 -30
  568. package/dist/cjs/core/ResponseGenerationError.d.ts.map +0 -1
  569. package/dist/cjs/core/ResponseGenerationError.js +0 -35
  570. package/dist/cjs/core/ResponseGenerationError.js.map +0 -1
  571. package/dist/cjs/core/ResponseModal.d.ts +0 -305
  572. package/dist/cjs/core/ResponseModal.d.ts.map +0 -1
  573. package/dist/cjs/core/ResponseModal.js +0 -1414
  574. package/dist/cjs/core/ResponseModal.js.map +0 -1
  575. package/dist/cjs/core/ResponsePipeline.d.ts +0 -220
  576. package/dist/cjs/core/ResponsePipeline.d.ts.map +0 -1
  577. package/dist/cjs/core/ResponsePipeline.js +0 -1040
  578. package/dist/cjs/core/ResponsePipeline.js.map +0 -1
  579. package/dist/cjs/core/SessionFinalizer.d.ts +0 -34
  580. package/dist/cjs/core/SessionFinalizer.d.ts.map +0 -1
  581. package/dist/cjs/core/SessionFinalizer.js +0 -88
  582. package/dist/cjs/core/SessionFinalizer.js.map +0 -1
  583. package/dist/cjs/core/SessionManager.d.ts +0 -112
  584. package/dist/cjs/core/SessionManager.d.ts.map +0 -1
  585. package/dist/cjs/core/SessionManager.js +0 -308
  586. package/dist/cjs/core/SessionManager.js.map +0 -1
  587. package/dist/cjs/core/SignalCoordinator.d.ts +0 -103
  588. package/dist/cjs/core/SignalCoordinator.d.ts.map +0 -1
  589. package/dist/cjs/core/SignalCoordinator.js +0 -207
  590. package/dist/cjs/core/SignalCoordinator.js.map +0 -1
  591. package/dist/cjs/core/SignalEvaluator.d.ts +0 -86
  592. package/dist/cjs/core/SignalEvaluator.d.ts.map +0 -1
  593. package/dist/cjs/core/SignalEvaluator.js +0 -319
  594. package/dist/cjs/core/SignalEvaluator.js.map +0 -1
  595. package/dist/cjs/core/SignalProcessor.d.ts +0 -152
  596. package/dist/cjs/core/SignalProcessor.d.ts.map +0 -1
  597. package/dist/cjs/core/SignalProcessor.js +0 -505
  598. package/dist/cjs/core/SignalProcessor.js.map +0 -1
  599. package/dist/cjs/core/Step.d.ts +0 -184
  600. package/dist/cjs/core/Step.d.ts.map +0 -1
  601. package/dist/cjs/core/Step.js +0 -599
  602. package/dist/cjs/core/Step.js.map +0 -1
  603. package/dist/cjs/core/StepLifecycle.d.ts +0 -43
  604. package/dist/cjs/core/StepLifecycle.d.ts.map +0 -1
  605. package/dist/cjs/core/StepLifecycle.js +0 -180
  606. package/dist/cjs/core/StepLifecycle.js.map +0 -1
  607. package/dist/cjs/core/StreamingToolExecutor.d.ts +0 -142
  608. package/dist/cjs/core/StreamingToolExecutor.d.ts.map +0 -1
  609. package/dist/cjs/core/StreamingToolExecutor.js +0 -490
  610. package/dist/cjs/core/StreamingToolExecutor.js.map +0 -1
  611. package/dist/cjs/core/ToolLoopExecutor.d.ts +0 -133
  612. package/dist/cjs/core/ToolLoopExecutor.d.ts.map +0 -1
  613. package/dist/cjs/core/ToolLoopExecutor.js +0 -568
  614. package/dist/cjs/core/ToolLoopExecutor.js.map +0 -1
  615. package/dist/cjs/core/ToolManager.d.ts +0 -250
  616. package/dist/cjs/core/ToolManager.d.ts.map +0 -1
  617. package/dist/cjs/core/ToolManager.js +0 -1104
  618. package/dist/cjs/core/ToolManager.js.map +0 -1
  619. package/dist/cjs/core/createAgent.d.ts +0 -35
  620. package/dist/cjs/core/createAgent.d.ts.map +0 -1
  621. package/dist/cjs/core/createAgent.js +0 -39
  622. package/dist/cjs/core/createAgent.js.map +0 -1
  623. package/dist/cjs/core/flow-namespace.d.ts +0 -64
  624. package/dist/cjs/core/flow-namespace.d.ts.map +0 -1
  625. package/dist/cjs/core/flow-namespace.js +0 -182
  626. package/dist/cjs/core/flow-namespace.js.map +0 -1
  627. package/dist/cjs/core/toolGates.d.ts +0 -24
  628. package/dist/cjs/core/toolGates.d.ts.map +0 -1
  629. package/dist/cjs/core/toolGates.js +0 -52
  630. package/dist/cjs/core/toolGates.js.map +0 -1
  631. package/dist/cjs/types/persistence.d.ts +0 -254
  632. package/dist/cjs/types/persistence.d.ts.map +0 -1
  633. package/dist/cjs/types/persistence.js +0 -7
  634. package/dist/cjs/types/persistence.js.map +0 -1
  635. package/dist/cjs/types/prompt-cache.d.ts +0 -15
  636. package/dist/cjs/types/prompt-cache.d.ts.map +0 -1
  637. package/dist/cjs/types/prompt-cache.js +0 -6
  638. package/dist/cjs/types/prompt-cache.js.map +0 -1
  639. package/dist/cjs/types/signals.d.ts +0 -263
  640. package/dist/cjs/types/signals.d.ts.map +0 -1
  641. package/dist/cjs/types/signals.js +0 -11
  642. package/dist/cjs/types/signals.js.map +0 -1
  643. package/dist/cjs/types/template.d.ts +0 -84
  644. package/dist/cjs/types/template.d.ts.map +0 -1
  645. package/dist/cjs/types/template.js +0 -3
  646. package/dist/cjs/types/template.js.map +0 -1
  647. package/dist/cjs/utils/condition.d.ts +0 -63
  648. package/dist/cjs/utils/condition.d.ts.map +0 -1
  649. package/dist/cjs/utils/condition.js +0 -239
  650. package/dist/cjs/utils/condition.js.map +0 -1
  651. package/dist/cjs/utils/event.d.ts +0 -6
  652. package/dist/cjs/utils/event.d.ts.map +0 -1
  653. package/dist/cjs/utils/event.js +0 -20
  654. package/dist/cjs/utils/event.js.map +0 -1
  655. package/dist/cjs/utils/id.d.ts +0 -33
  656. package/dist/cjs/utils/id.d.ts.map +0 -1
  657. package/dist/cjs/utils/id.js +0 -84
  658. package/dist/cjs/utils/id.js.map +0 -1
  659. package/dist/cjs/utils/serialize.d.ts +0 -36
  660. package/dist/cjs/utils/serialize.d.ts.map +0 -1
  661. package/dist/cjs/utils/serialize.js +0 -77
  662. package/dist/cjs/utils/serialize.js.map +0 -1
  663. package/dist/cjs/utils/session.d.ts +0 -124
  664. package/dist/cjs/utils/session.d.ts.map +0 -1
  665. package/dist/cjs/utils/session.js +0 -396
  666. package/dist/cjs/utils/session.js.map +0 -1
  667. package/dist/constants/index.d.ts +0 -2
  668. package/dist/constants/index.d.ts.map +0 -1
  669. package/dist/constants/index.js +0 -4
  670. package/dist/constants/index.js.map +0 -1
  671. package/dist/core/AutoChainExecutor.d.ts +0 -97
  672. package/dist/core/AutoChainExecutor.d.ts.map +0 -1
  673. package/dist/core/AutoChainExecutor.js +0 -284
  674. package/dist/core/AutoChainExecutor.js.map +0 -1
  675. package/dist/core/BranchEvaluator.d.ts +0 -55
  676. package/dist/core/BranchEvaluator.d.ts.map +0 -1
  677. package/dist/core/BranchEvaluator.js +0 -121
  678. package/dist/core/BranchEvaluator.js.map +0 -1
  679. package/dist/core/DirectiveChainTracker.d.ts +0 -49
  680. package/dist/core/DirectiveChainTracker.d.ts.map +0 -1
  681. package/dist/core/DirectiveChainTracker.js +0 -117
  682. package/dist/core/DirectiveChainTracker.js.map +0 -1
  683. package/dist/core/Events.d.ts +0 -26
  684. package/dist/core/Events.d.ts.map +0 -1
  685. package/dist/core/Events.js +0 -137
  686. package/dist/core/Events.js.map +0 -1
  687. package/dist/core/Flow.d.ts +0 -183
  688. package/dist/core/Flow.d.ts.map +0 -1
  689. package/dist/core/Flow.js +0 -547
  690. package/dist/core/Flow.js.map +0 -1
  691. package/dist/core/FlowRouter.d.ts +0 -183
  692. package/dist/core/FlowRouter.d.ts.map +0 -1
  693. package/dist/core/FlowRouter.js +0 -1043
  694. package/dist/core/FlowRouter.js.map +0 -1
  695. package/dist/core/PersistenceManager.d.ts +0 -114
  696. package/dist/core/PersistenceManager.d.ts.map +0 -1
  697. package/dist/core/PersistenceManager.js +0 -332
  698. package/dist/core/PersistenceManager.js.map +0 -1
  699. package/dist/core/PromptComposer.d.ts +0 -47
  700. package/dist/core/PromptComposer.d.ts.map +0 -1
  701. package/dist/core/PromptComposer.js +0 -393
  702. package/dist/core/PromptComposer.js.map +0 -1
  703. package/dist/core/PromptSectionCache.d.ts +0 -48
  704. package/dist/core/PromptSectionCache.d.ts.map +0 -1
  705. package/dist/core/PromptSectionCache.js +0 -104
  706. package/dist/core/PromptSectionCache.js.map +0 -1
  707. package/dist/core/ResponseEngine.d.ts +0 -43
  708. package/dist/core/ResponseEngine.d.ts.map +0 -1
  709. package/dist/core/ResponseEngine.js +0 -231
  710. package/dist/core/ResponseEngine.js.map +0 -1
  711. package/dist/core/ResponseGenerationError.d.ts +0 -30
  712. package/dist/core/ResponseGenerationError.d.ts.map +0 -1
  713. package/dist/core/ResponseGenerationError.js +0 -31
  714. package/dist/core/ResponseGenerationError.js.map +0 -1
  715. package/dist/core/ResponseModal.d.ts +0 -305
  716. package/dist/core/ResponseModal.d.ts.map +0 -1
  717. package/dist/core/ResponseModal.js +0 -1410
  718. package/dist/core/ResponseModal.js.map +0 -1
  719. package/dist/core/ResponsePipeline.d.ts +0 -220
  720. package/dist/core/ResponsePipeline.d.ts.map +0 -1
  721. package/dist/core/ResponsePipeline.js +0 -1035
  722. package/dist/core/ResponsePipeline.js.map +0 -1
  723. package/dist/core/SessionFinalizer.d.ts +0 -34
  724. package/dist/core/SessionFinalizer.d.ts.map +0 -1
  725. package/dist/core/SessionFinalizer.js +0 -84
  726. package/dist/core/SessionFinalizer.js.map +0 -1
  727. package/dist/core/SessionManager.d.ts +0 -112
  728. package/dist/core/SessionManager.d.ts.map +0 -1
  729. package/dist/core/SessionManager.js +0 -301
  730. package/dist/core/SessionManager.js.map +0 -1
  731. package/dist/core/SignalCoordinator.d.ts +0 -103
  732. package/dist/core/SignalCoordinator.d.ts.map +0 -1
  733. package/dist/core/SignalCoordinator.js +0 -203
  734. package/dist/core/SignalCoordinator.js.map +0 -1
  735. package/dist/core/SignalEvaluator.d.ts +0 -86
  736. package/dist/core/SignalEvaluator.d.ts.map +0 -1
  737. package/dist/core/SignalEvaluator.js +0 -312
  738. package/dist/core/SignalEvaluator.js.map +0 -1
  739. package/dist/core/SignalProcessor.d.ts +0 -152
  740. package/dist/core/SignalProcessor.d.ts.map +0 -1
  741. package/dist/core/SignalProcessor.js +0 -498
  742. package/dist/core/SignalProcessor.js.map +0 -1
  743. package/dist/core/Step.d.ts +0 -184
  744. package/dist/core/Step.d.ts.map +0 -1
  745. package/dist/core/Step.js +0 -594
  746. package/dist/core/Step.js.map +0 -1
  747. package/dist/core/StepLifecycle.d.ts +0 -43
  748. package/dist/core/StepLifecycle.d.ts.map +0 -1
  749. package/dist/core/StepLifecycle.js +0 -176
  750. package/dist/core/StepLifecycle.js.map +0 -1
  751. package/dist/core/StreamingToolExecutor.d.ts +0 -142
  752. package/dist/core/StreamingToolExecutor.d.ts.map +0 -1
  753. package/dist/core/StreamingToolExecutor.js +0 -483
  754. package/dist/core/StreamingToolExecutor.js.map +0 -1
  755. package/dist/core/ToolLoopExecutor.d.ts +0 -133
  756. package/dist/core/ToolLoopExecutor.d.ts.map +0 -1
  757. package/dist/core/ToolLoopExecutor.js +0 -564
  758. package/dist/core/ToolLoopExecutor.js.map +0 -1
  759. package/dist/core/ToolManager.d.ts +0 -250
  760. package/dist/core/ToolManager.d.ts.map +0 -1
  761. package/dist/core/ToolManager.js +0 -1098
  762. package/dist/core/ToolManager.js.map +0 -1
  763. package/dist/core/createAgent.d.ts +0 -35
  764. package/dist/core/createAgent.d.ts.map +0 -1
  765. package/dist/core/createAgent.js +0 -36
  766. package/dist/core/createAgent.js.map +0 -1
  767. package/dist/core/flow-namespace.d.ts +0 -64
  768. package/dist/core/flow-namespace.d.ts.map +0 -1
  769. package/dist/core/flow-namespace.js +0 -179
  770. package/dist/core/flow-namespace.js.map +0 -1
  771. package/dist/core/toolGates.d.ts +0 -24
  772. package/dist/core/toolGates.d.ts.map +0 -1
  773. package/dist/core/toolGates.js +0 -49
  774. package/dist/core/toolGates.js.map +0 -1
  775. package/dist/types/persistence.d.ts +0 -254
  776. package/dist/types/persistence.d.ts.map +0 -1
  777. package/dist/types/persistence.js +0 -6
  778. package/dist/types/persistence.js.map +0 -1
  779. package/dist/types/prompt-cache.d.ts +0 -15
  780. package/dist/types/prompt-cache.d.ts.map +0 -1
  781. package/dist/types/prompt-cache.js +0 -5
  782. package/dist/types/prompt-cache.js.map +0 -1
  783. package/dist/types/signals.d.ts +0 -263
  784. package/dist/types/signals.d.ts.map +0 -1
  785. package/dist/types/signals.js +0 -10
  786. package/dist/types/signals.js.map +0 -1
  787. package/dist/types/template.d.ts +0 -84
  788. package/dist/types/template.d.ts.map +0 -1
  789. package/dist/types/template.js +0 -2
  790. package/dist/types/template.js.map +0 -1
  791. package/dist/utils/condition.d.ts +0 -63
  792. package/dist/utils/condition.d.ts.map +0 -1
  793. package/dist/utils/condition.js +0 -230
  794. package/dist/utils/condition.js.map +0 -1
  795. package/dist/utils/event.d.ts +0 -6
  796. package/dist/utils/event.d.ts.map +0 -1
  797. package/dist/utils/event.js +0 -17
  798. package/dist/utils/event.js.map +0 -1
  799. package/dist/utils/id.d.ts +0 -33
  800. package/dist/utils/id.d.ts.map +0 -1
  801. package/dist/utils/id.js +0 -77
  802. package/dist/utils/id.js.map +0 -1
  803. package/dist/utils/serialize.d.ts +0 -36
  804. package/dist/utils/serialize.d.ts.map +0 -1
  805. package/dist/utils/serialize.js +0 -72
  806. package/dist/utils/serialize.js.map +0 -1
  807. package/dist/utils/session.d.ts +0 -124
  808. package/dist/utils/session.d.ts.map +0 -1
  809. package/dist/utils/session.js +0 -379
  810. package/dist/utils/session.js.map +0 -1
  811. package/docs/concepts/directives.md +0 -369
  812. package/docs/reference/adapters.md +0 -543
  813. package/docs/reference/create-agent.md +0 -216
  814. package/docs/reference/directive.md +0 -242
  815. package/docs/reference/signals.md +0 -368
  816. package/examples/02-data-extraction.ts +0 -90
  817. package/examples/05-branching.ts +0 -140
  818. package/examples/06-flow-control.ts +0 -103
  819. package/examples/08-persistence.ts +0 -98
  820. package/examples/09-signals.ts +0 -144
  821. package/src/adapters/MemoryAdapter.ts +0 -281
  822. package/src/adapters/MongoAdapter.ts +0 -341
  823. package/src/adapters/OpenSearchAdapter.ts +0 -693
  824. package/src/adapters/PostgreSQLAdapter.ts +0 -487
  825. package/src/adapters/PrismaAdapter.ts +0 -617
  826. package/src/adapters/RedisAdapter.ts +0 -439
  827. package/src/adapters/SQLiteAdapter.ts +0 -496
  828. package/src/adapters/index.ts +0 -43
  829. package/src/adapters/sessionRow.ts +0 -57
  830. package/src/constants/index.ts +0 -2
  831. package/src/core/AutoChainExecutor.ts +0 -397
  832. package/src/core/BranchEvaluator.ts +0 -161
  833. package/src/core/DirectiveChainTracker.ts +0 -144
  834. package/src/core/Events.ts +0 -164
  835. package/src/core/Flow.ts +0 -665
  836. package/src/core/FlowRouter.ts +0 -1540
  837. package/src/core/PersistenceManager.ts +0 -446
  838. package/src/core/PromptComposer.ts +0 -448
  839. package/src/core/PromptSectionCache.ts +0 -125
  840. package/src/core/ResponseEngine.ts +0 -338
  841. package/src/core/ResponseGenerationError.ts +0 -53
  842. package/src/core/ResponseModal.ts +0 -1902
  843. package/src/core/ResponsePipeline.ts +0 -1404
  844. package/src/core/SessionFinalizer.ts +0 -108
  845. package/src/core/SessionManager.ts +0 -372
  846. package/src/core/SignalCoordinator.ts +0 -263
  847. package/src/core/SignalEvaluator.ts +0 -404
  848. package/src/core/SignalProcessor.ts +0 -663
  849. package/src/core/Step.ts +0 -782
  850. package/src/core/StepLifecycle.ts +0 -242
  851. package/src/core/StreamingToolExecutor.ts +0 -609
  852. package/src/core/ToolLoopExecutor.ts +0 -749
  853. package/src/core/ToolManager.ts +0 -1379
  854. package/src/core/createAgent.ts +0 -40
  855. package/src/core/flow-namespace.ts +0 -227
  856. package/src/core/toolGates.ts +0 -72
  857. package/src/types/persistence.ts +0 -303
  858. package/src/types/prompt-cache.ts +0 -17
  859. package/src/types/signals.ts +0 -338
  860. package/src/types/template.ts +0 -98
  861. package/src/utils/condition.ts +0 -296
  862. package/src/utils/event.ts +0 -16
  863. package/src/utils/id.ts +0 -91
  864. package/src/utils/serialize.ts +0 -86
  865. package/src/utils/session.ts +0 -501
@@ -1,1379 +0,0 @@
1
- /**
2
- * ToolManager - Centralized tool management with simplified creation APIs
3
- */
4
-
5
- import type {
6
- Tool,
7
- ToolResult,
8
- ToolExecutionResult,
9
- DataEnrichmentConfig,
10
- ValidationConfig,
11
- ValidationResult,
12
- ApiCallConfig,
13
- ComputationConfig,
14
- ToolContext,
15
- ToolCallRequest,
16
- ToolExecutionUpdate,
17
- Event,
18
- } from "../types/index.js";
19
- import type { Directive } from "../types/flow.js";
20
- import { ToolScope } from "../types/index.js";
21
- import { logger, isToolResultLike, extractResultDirectives } from "../utils/index.js";
22
- // Type-only import: ToolManager must not create a runtime cycle with Agent
23
- import type { Agent } from "./Agent.js";
24
- import { Flow } from "./Flow.js";
25
- import { Step } from "./Step.js";
26
- import { StreamingToolExecutor } from "./StreamingToolExecutor.js";
27
- import { evaluateToolGates } from "./toolGates.js";
28
-
29
- /**
30
- * Error thrown when tool creation fails
31
- */
32
- export class ToolCreationError extends Error {
33
- constructor(
34
- message: string,
35
- public readonly toolId: string,
36
- public readonly cause?: Error
37
- ) {
38
- super(message);
39
- this.name = 'ToolCreationError';
40
- }
41
- }
42
-
43
- /**
44
- * Error thrown when tool execution fails
45
- */
46
- export class ToolExecutionError extends Error {
47
- constructor(
48
- message: string,
49
- public readonly toolId: string,
50
- public readonly executionContext?: Record<string, unknown>,
51
- public readonly cause?: Error
52
- ) {
53
- super(message);
54
- this.name = 'ToolExecutionError';
55
- }
56
- }
57
-
58
-
59
-
60
- /**
61
- * ToolManager - Centralized tool management with simplified APIs
62
- */
63
- export class ToolManager<TContext = unknown, TData = unknown> {
64
- private toolRegistry: Map<string, Tool<TContext, TData>>;
65
-
66
- /**
67
- * Per-turn transient tool layer populated from Directive.injectTools.
68
- * Resolution order: transient → step → flow → agent.
69
- * Drained at end of turn via try/finally guard.
70
- *
71
- * Tools are deduplicated by `id` with last-definition-wins when
72
- * multiple pre-LLM emitters contribute tools in the same turn.
73
- */
74
- private transientTools: Map<string, Tool<TContext, TData>> = new Map();
75
-
76
- constructor(private agent: Agent<TContext, TData>) {
77
- this.toolRegistry = new Map();
78
- }
79
-
80
- /**
81
- * Set the transient tool layer for the current turn.
82
- *
83
- * Accepts the merged `injectTools` array from pre-LLM emitters
84
- * (concatenated in outer-to-inner order).
85
- * Deduplicates by tool `id` with last-definition-wins.
86
- *
87
- * Must be paired with `clearTransientTools()` in a try/finally guard
88
- * so the layer is drained even on abnormal termination.
89
- */
90
- setTransientTools(tools: Tool<TContext, TData>[]): void {
91
- this.transientTools.clear();
92
- for (const tool of tools) {
93
- this.transientTools.set(tool.id, tool);
94
- }
95
- if (this.transientTools.size > 0) {
96
- logger.debug(
97
- `[ToolManager] Set transient tools for turn: ${Array.from(this.transientTools.keys()).join(', ')}`
98
- );
99
- }
100
- }
101
-
102
- /**
103
- * Clear the transient tool layer. Called at end of turn via try/finally
104
- * guard so tools do not leak into subsequent turns.
105
- */
106
- clearTransientTools(): void {
107
- if (this.transientTools.size > 0) {
108
- logger.debug(
109
- `[ToolManager] Cleared transient tools: ${Array.from(this.transientTools.keys()).join(', ')}`
110
- );
111
- }
112
- this.transientTools.clear();
113
- }
114
-
115
- /**
116
- * Check whether the transient layer currently has any tools.
117
- * Useful for testing and debugging.
118
- */
119
- hasTransientTools(): boolean {
120
- return this.transientTools.size > 0;
121
- }
122
-
123
- /**
124
- * Validate a tool definition for completeness and correctness
125
- */
126
- private validateToolDefinition(
127
- definition: Tool<TContext, TData>
128
- ): void {
129
- const errors: string[] = [];
130
-
131
- // Required fields validation
132
- if (!definition.id || typeof definition.id !== 'string') {
133
- errors.push('Tool ID is required and must be a non-empty string');
134
- } else if (definition.id.trim() === '') {
135
- errors.push('Tool ID cannot be empty or whitespace only');
136
- } else if (!/^[a-zA-Z0-9_-]+$/.test(definition.id)) {
137
- errors.push('Tool ID must contain only alphanumeric characters, underscores, and hyphens');
138
- }
139
-
140
- if (!definition.handler || typeof definition.handler !== 'function') {
141
- errors.push('Tool handler is required and must be a function');
142
- }
143
-
144
- if (definition.description !== undefined && (typeof definition.description !== 'string' || definition.description.trim() === '')) {
145
- errors.push('Tool description must be a non-empty string if provided');
146
- }
147
-
148
- // Parameters validation (basic JSON schema check)
149
- if (definition.parameters !== undefined) {
150
- try {
151
- if (typeof definition.parameters === 'object' && definition.parameters !== null) {
152
- // Basic validation for JSON schema structure
153
- const params = definition.parameters as Record<string, unknown>;
154
- if ('type' in params && params.type && typeof params.type !== 'string') {
155
- errors.push('Tool parameters type must be a string if specified');
156
- }
157
- if ('properties' in params && params.properties && typeof params.properties !== 'object') {
158
- errors.push('Tool parameters properties must be an object if specified');
159
- }
160
- } else if (typeof definition.parameters !== 'string') {
161
- errors.push('Tool parameters must be an object (JSON schema) or string if provided');
162
- }
163
- } catch {
164
- errors.push('Tool parameters must be valid JSON schema or string');
165
- }
166
- }
167
-
168
- if (errors.length > 0) {
169
- throw new ToolCreationError(
170
- `[ToolCreationError] Tool definition validation failed for "${definition.id || 'unknown'}": ${errors.join('; ')}. ` +
171
- `Fix the tool definition to meet the required schema.`,
172
- definition.id || 'unknown'
173
- );
174
- }
175
- }
176
-
177
- /**
178
- * Validate data enrichment configuration
179
- */
180
- private validateDataEnrichmentConfig<TFields extends keyof TData>(
181
- config: DataEnrichmentConfig<TContext, TData, TFields>
182
- ): void {
183
- const errors: string[] = [];
184
-
185
- if (!config.fields || !Array.isArray(config.fields) || config.fields.length === 0) {
186
- errors.push('Data enrichment fields must be a non-empty array');
187
- }
188
-
189
- if (!config.enricher || typeof config.enricher !== 'function') {
190
- errors.push('Data enrichment enricher must be a function');
191
- }
192
-
193
- if (errors.length > 0) {
194
- throw new ToolCreationError(
195
- `[ToolCreationError] Data enrichment config validation failed for "${config.id || 'unknown'}": ${errors.join('; ')}. ` +
196
- `Fix the enrichment config to satisfy the required fields.`,
197
- config.id || 'unknown'
198
- );
199
- }
200
- }
201
-
202
- /**
203
- * Validate validation configuration
204
- */
205
- private validateValidationConfig<TFields extends keyof TData>(
206
- config: ValidationConfig<TContext, TData, TFields>
207
- ): void {
208
- const errors: string[] = [];
209
-
210
- if (!config.fields || !Array.isArray(config.fields) || config.fields.length === 0) {
211
- errors.push('Validation fields must be a non-empty array');
212
- }
213
-
214
- if (!config.validator || typeof config.validator !== 'function') {
215
- errors.push('Validation validator must be a function');
216
- }
217
-
218
- if (errors.length > 0) {
219
- throw new ToolCreationError(
220
- `[ToolCreationError] Validation config validation failed for "${config.id || 'unknown'}": ${errors.join('; ')}. ` +
221
- `Fix the validation config to satisfy the required fields.`,
222
- config.id || 'unknown'
223
- );
224
- }
225
- }
226
-
227
- /**
228
- * Validate API call configuration
229
- */
230
- private validateApiCallConfig<TResult = unknown>(
231
- config: ApiCallConfig<TContext, TData, TResult>
232
- ): void {
233
- const errors: string[] = [];
234
-
235
- if (!config.endpoint) {
236
- errors.push('API call endpoint is required');
237
- } else if (typeof config.endpoint !== 'string' && typeof config.endpoint !== 'function') {
238
- errors.push('API call endpoint must be a string or function');
239
- }
240
-
241
- if (config.method && !['GET', 'POST', 'PUT', 'DELETE'].includes(config.method)) {
242
- errors.push('API call method must be one of: GET, POST, PUT, DELETE');
243
- }
244
-
245
- if (config.headers && typeof config.headers !== 'object' && typeof config.headers !== 'function') {
246
- errors.push('API call headers must be an object or function');
247
- }
248
-
249
- if (config.body && typeof config.body !== 'function') {
250
- errors.push('API call body must be a function');
251
- }
252
-
253
- if (config.transform && typeof config.transform !== 'function') {
254
- errors.push('API call transform must be a function');
255
- }
256
-
257
- if (errors.length > 0) {
258
- throw new ToolCreationError(
259
- `[ToolCreationError] API call config validation failed for "${config.id || 'unknown'}": ${errors.join('; ')}. ` +
260
- `Fix the API call config to satisfy the required fields.`,
261
- config.id || 'unknown'
262
- );
263
- }
264
- }
265
-
266
- /**
267
- * Validate computation configuration
268
- */
269
- private validateComputationConfig<TResult = unknown>(
270
- config: ComputationConfig<TContext, TData, TResult>
271
- ): void {
272
- const errors: string[] = [];
273
-
274
- if (!config.inputs || !Array.isArray(config.inputs) || config.inputs.length === 0) {
275
- errors.push('Computation inputs must be a non-empty array');
276
- }
277
-
278
- if (!config.compute || typeof config.compute !== 'function') {
279
- errors.push('Computation compute function is required');
280
- }
281
-
282
- if (errors.length > 0) {
283
- throw new ToolCreationError(
284
- `[ToolCreationError] Computation config validation failed for "${config.id || 'unknown'}": ${errors.join('; ')}. ` +
285
- `Fix the computation config to satisfy the required fields.`,
286
- config.id || 'unknown'
287
- );
288
- }
289
- }
290
-
291
- /**
292
- * Create a tool instance with type inference from parent Agent
293
- * Does not register the tool anywhere - just creates it
294
- */
295
- create(
296
- definition: Tool<TContext, TData>
297
- ): Tool<TContext, TData> {
298
- try {
299
- // Validate the tool definition first
300
- this.validateToolDefinition(definition);
301
-
302
- logger.debug(`[ToolManager] Created tool: ${definition.id}`);
303
- return definition;
304
- } catch (error) {
305
- throw new ToolCreationError(
306
- `[ToolCreationError] Failed to create tool "${definition.id}": ${error instanceof Error ? error.message : String(error)}. ` +
307
- `Ensure the tool definition passes validation.`,
308
- definition.id,
309
- error instanceof Error ? error : undefined
310
- );
311
- }
312
- }
313
-
314
- /**
315
- * Register a tool in the registry for later reference by ID
316
- * Can accept a tool instance
317
- */
318
- register(
319
- tool: Tool<TContext, TData>
320
- ): Tool<TContext, TData> {
321
- try {
322
- if (!tool) {
323
- throw new ToolCreationError(
324
- '[ToolCreationError] Tool registration failed: no tool provided. Pass a valid tool object with id and handler.',
325
- 'unknown'
326
- );
327
- }
328
-
329
- if (!('handler' in tool) || typeof tool.handler !== 'function') {
330
- throw new ToolCreationError(
331
- `[ToolCreationError] Invalid tool for registration: tool "${tool?.id || 'unknown'}" must have a handler function. Add a handler property.`,
332
- tool?.id || 'unknown'
333
- );
334
- }
335
-
336
- // Validate the tool
337
- if (!tool.id || typeof tool.id !== 'string' || tool.id.trim() === '') {
338
- throw new ToolCreationError(
339
- '[ToolCreationError] Tool ID missing: tool ID is required and must be a non-empty string. Provide a unique string id.',
340
- tool.id || 'unknown'
341
- );
342
- }
343
-
344
- // Check for ID conflicts and provide better error context
345
- if (this.toolRegistry.has(tool.id)) {
346
- const existingTool = this.toolRegistry.get(tool.id);
347
- logger.warn(`[ToolManager] Overwriting existing registered tool: ${tool.id} (previous: ${existingTool?.id || 'unnamed'})`);
348
- }
349
-
350
- this.toolRegistry.set(tool.id, tool);
351
- logger.debug(`[ToolManager] Registered tool: ${tool.id} (${tool.id || 'unnamed'})`);
352
-
353
- return tool;
354
- } catch (error) {
355
- if (error instanceof ToolCreationError) {
356
- throw error;
357
- }
358
-
359
- const toolId = tool?.id || 'unknown';
360
- throw new ToolCreationError(
361
- `[ToolCreationError] Failed to register tool "${toolId}": ${error instanceof Error ? error.message : String(error)}. ` +
362
- `Ensure the tool object is valid and has id + handler.`,
363
- toolId,
364
- error instanceof Error ? error : undefined
365
- );
366
- }
367
- }
368
-
369
- /**
370
- * Register multiple tools at once
371
- */
372
- registerMany(
373
- tools: Array<Tool<TContext, TData>>
374
- ): Tool<TContext, TData>[] {
375
- return tools.map(tool => this.register(tool));
376
- }
377
-
378
- /**
379
- * Get a registered tool by ID
380
- */
381
- getRegisteredTool(toolId: string): Tool<TContext, TData> | undefined {
382
- return this.toolRegistry.get(toolId);
383
- }
384
-
385
- /**
386
- * Get all registered tools
387
- */
388
- getAllRegistered(): Map<string, Tool<TContext, TData>> {
389
- return new Map(this.toolRegistry);
390
- }
391
-
392
- /**
393
- * Check if a tool is registered
394
- */
395
- isRegistered(toolId: string): boolean {
396
- return this.toolRegistry.has(toolId);
397
- }
398
-
399
- /**
400
- * Get all registered tool IDs
401
- */
402
- getRegisteredIds(): string[] {
403
- return Array.from(this.toolRegistry.keys());
404
- }
405
-
406
- /**
407
- * Get tool by ID from a specific scope
408
- */
409
- getFromScope(toolId: string, scope: ToolScope, step?: Step<TContext, TData>, flow?: Flow<TContext, TData>): Tool<TContext, TData> | undefined {
410
- return this.find(toolId, scope, step, flow);
411
- }
412
-
413
- /**
414
- * Check if a tool exists in any scope
415
- */
416
- exists(toolId: string, step?: Step<TContext, TData>, flow?: Flow<TContext, TData>): boolean {
417
- return this.find(toolId, ToolScope.ALL, step, flow) !== undefined;
418
- }
419
-
420
- /**
421
- * Get tool count by scope
422
- */
423
- getToolCount(scope?: ToolScope, step?: Step<TContext, TData>, flow?: Flow<TContext, TData>): number {
424
- return this.getAvailable(scope, step, flow).length;
425
- }
426
-
427
- /**
428
- * Clear all registered tools
429
- */
430
- clearRegistry(): void {
431
- this.toolRegistry.clear();
432
- logger.debug('[ToolManager] Cleared tool registry');
433
- }
434
-
435
- /**
436
- * Remove a tool from registry
437
- */
438
- unregister(toolId: string): boolean {
439
- const existed = this.toolRegistry.has(toolId);
440
- this.toolRegistry.delete(toolId);
441
- if (existed) {
442
- logger.debug(`[ToolManager] Unregistered tool: ${toolId}`);
443
- }
444
- return existed;
445
- }
446
-
447
- /**
448
- * Add a tool to the agent scope (creates and adds in one operation)
449
- */
450
- addToAgent(
451
- tool: Tool<TContext, TData>
452
- ): Tool<TContext, TData> {
453
- // Validate tool before adding
454
- if (!tool || !tool.id || !tool.handler) {
455
- throw new ToolCreationError(
456
- `[ToolCreationError] Invalid tool for addToAgent: tool must have id and handler properties. ` +
457
- `Provide a complete tool object with { id, handler, ... }.`,
458
- tool?.id || 'unknown'
459
- );
460
- }
461
-
462
- // Add to agent's tools array using the unified interface
463
- if (this.agent) {
464
- this.agent.addTool(tool);
465
- } else {
466
- logger.warn(`[ToolManager] No agent available, tool not added to agent scope: ${tool.id}`);
467
- }
468
-
469
- logger.debug(`[ToolManager] Added tool to agent scope: ${tool.id}`);
470
- return tool;
471
- }
472
-
473
- /**
474
- * Add a tool to a specific flow scope (creates and adds in one operation)
475
- */
476
- addToFlow(
477
- flow: Flow<TContext, TData>,
478
- tool: Tool<TContext, TData>
479
- ): Tool<TContext, TData> {
480
- // Add to flow's tools array using the existing createTool method
481
- if (flow && typeof flow.createTool === 'function') {
482
- flow.createTool(tool);
483
- } else {
484
- logger.warn(`[ToolManager] Flow does not support createTool method, tool not added to flow scope: ${tool.id}`);
485
- }
486
-
487
- logger.debug(`[ToolManager] Added tool to flow scope: ${tool.id}`);
488
- return tool;
489
- }
490
-
491
- /**
492
- * Find a tool by ID across different scopes with enhanced resolution logic
493
- * Priority: transient → step → flow → agent → registry
494
- * Supports both ID and name matching for better compatibility
495
- */
496
- find(toolId: string, scope?: ToolScope, step?: Step<TContext, TData>, flow?: Flow<TContext, TData>): Tool<TContext, TData> | undefined {
497
- logger.debug(`[ToolManager] Finding tool: ${toolId} with scope: ${scope || 'ALL'}`);
498
-
499
- // Check transient tools first (highest priority — per-turn injectTools)
500
- if (!scope || scope === ToolScope.ALL) {
501
- const transientTool = this.transientTools.get(toolId);
502
- if (transientTool) {
503
- logger.debug(`[ToolManager] Found tool in transient scope: ${toolId}`);
504
- return transientTool;
505
- }
506
- }
507
-
508
- // Check step-level tools (if step provided and scope allows)
509
- if (step && (!scope || scope === ToolScope.STEP || scope === ToolScope.ALL)) {
510
- if (step.tools) {
511
- for (const toolRef of step.tools) {
512
- if (typeof toolRef !== 'string') {
513
- // Inline tool object - check both id and name
514
- if (toolRef.id === toolId) {
515
- logger.debug(`[ToolManager] Found tool in step scope: ${toolId}`);
516
- return toolRef;
517
- }
518
- } else {
519
- // String reference - check if it matches and resolve from registry
520
- if (toolRef === toolId) {
521
- const registeredTool = this.toolRegistry.get(toolId);
522
- if (registeredTool) {
523
- logger.debug(`[ToolManager] Found tool reference in step, resolved from registry: ${toolId}`);
524
- return registeredTool;
525
- }
526
- }
527
- }
528
- }
529
- }
530
- }
531
-
532
- // Check flow-level tools (if route provided and scope allows)
533
- if (flow && (!scope || scope === ToolScope.FLOW || scope === ToolScope.ALL)) {
534
- if (flow.tools) {
535
- const flowTool = flow.tools.find((t) => t.id === toolId);
536
- if (flowTool) {
537
- logger.debug(`[ToolManager] Found tool in flow scope: ${toolId}`);
538
- return flowTool;
539
- }
540
- }
541
- }
542
-
543
- // Check agent-level tools (if scope allows)
544
- if (!scope || scope === ToolScope.AGENT || scope === ToolScope.ALL) {
545
- if (this.agent) {
546
- const agentTools = this.agent.getTools();
547
- const agentTool = agentTools.find((t) => t.id === toolId);
548
- if (agentTool) {
549
- logger.debug(`[ToolManager] Found tool in agent scope: ${toolId}`);
550
- return agentTool;
551
- }
552
- }
553
- }
554
-
555
- // Check registry (if scope allows)
556
- if (!scope || scope === ToolScope.REGISTERED || scope === ToolScope.ALL) {
557
- const registeredTool = this.toolRegistry.get(toolId);
558
- if (registeredTool) {
559
- logger.debug(`[ToolManager] Found tool in registry: ${toolId}`);
560
- return registeredTool;
561
- }
562
-
563
- // Also check by name in registry
564
- for (const [id, tool] of Array.from(this.toolRegistry.entries())) {
565
- if (tool.id === toolId) {
566
- logger.debug(`[ToolManager] Found tool in registry by name: ${toolId} (id: ${id})`);
567
- return tool;
568
- }
569
- }
570
- }
571
-
572
- logger.debug(`[ToolManager] Tool not found: ${toolId}`);
573
- return undefined;
574
- }
575
-
576
- /**
577
- * Get available tools for current context with enhanced resolution and deduplication
578
- * Returns tools in priority order with higher-priority scopes taking precedence
579
- * Resolution order: transient → step → flow → agent → registry
580
- */
581
- getAvailable(scope?: ToolScope, step?: Step<TContext, TData>, flow?: Flow<TContext, TData>): Tool<TContext, TData>[] {
582
- const toolMap = new Map<string, Tool<TContext, TData>>();
583
- const resolvedTools: Tool<TContext, TData>[] = [];
584
-
585
- logger.debug(`[ToolManager] Getting available tools with scope: ${scope || 'ALL'}`);
586
-
587
- // Add registered tools first (lowest priority)
588
- if (!scope || scope === ToolScope.REGISTERED || scope === ToolScope.ALL) {
589
- for (const [id, tool] of Array.from(this.toolRegistry.entries())) {
590
- toolMap.set(id, tool);
591
- }
592
- logger.debug(`[ToolManager] Added ${this.toolRegistry.size} registered tools`);
593
- }
594
-
595
- // Add agent-level tools (override registered tools with same ID)
596
- if (!scope || scope === ToolScope.AGENT || scope === ToolScope.ALL) {
597
- if (this.agent) {
598
- const agentTools = this.agent.getTools();
599
- for (const tool of agentTools) {
600
- toolMap.set(tool.id, tool);
601
- }
602
- logger.debug(`[ToolManager] Added ${agentTools.length} agent tools`);
603
- }
604
- }
605
-
606
- // Add route-level tools (override agent and registered tools with same ID)
607
- if (flow && (!scope || scope === ToolScope.FLOW || scope === ToolScope.ALL)) {
608
- if (flow.tools) {
609
- for (const tool of flow.tools) {
610
- toolMap.set(tool.id, tool);
611
- }
612
- logger.debug(`[ToolManager] Added ${flow.tools.length} flow.tools`);
613
- }
614
- }
615
-
616
- // Add step-level tools (override flow/agent/registry with same ID)
617
- if (step && (!scope || scope === ToolScope.STEP || scope === ToolScope.ALL)) {
618
- if (step.tools) {
619
- for (const toolRef of step.tools) {
620
- if (typeof toolRef !== 'string') {
621
- // Inline tool object - add directly
622
- toolMap.set(toolRef.id, toolRef);
623
- resolvedTools.push(toolRef);
624
- } else {
625
- // String reference - resolve from registry and add if found
626
- const registeredTool = this.toolRegistry.get(toolRef);
627
- if (registeredTool) {
628
- toolMap.set(registeredTool.id, registeredTool);
629
- resolvedTools.push(registeredTool);
630
- } else {
631
- logger.warn(`[ToolExecutionError] Step references unknown tool: "${toolRef}" is not registered. Skipping. Register the tool or remove the reference.`);
632
- }
633
- }
634
- }
635
- logger.debug(`[ToolManager] Added ${step.tools.length} step tools (${resolvedTools.length} resolved)`);
636
- }
637
- }
638
-
639
- // Add transient tools (highest priority — override everything with same ID)
640
- if (!scope || scope === ToolScope.ALL) {
641
- if (this.transientTools.size > 0) {
642
- for (const [id, tool] of this.transientTools) {
643
- toolMap.set(id, tool);
644
- }
645
- logger.debug(`[ToolManager] Added ${this.transientTools.size} transient tools`);
646
- }
647
- }
648
-
649
- // Convert map to array, preserving priority order
650
- const allTools = Array.from(toolMap.values());
651
-
652
- // If we have step-specific tools, prioritize them in the ordering
653
- // (but transient tools that override step tools via same ID are already in the map)
654
- if (resolvedTools.length > 0) {
655
- // Add resolved step tools first, then other tools not already included
656
- const stepToolIds = new Set(resolvedTools.map(t => t.id));
657
- const otherTools = allTools.filter(t => !stepToolIds.has(t.id));
658
- // For step tools, use the map version (which may be overridden by transient)
659
- const finalStepTools = resolvedTools.map(t => toolMap.get(t.id) || t);
660
- return [...finalStepTools, ...otherTools];
661
- }
662
-
663
- logger.debug(`[ToolManager] Returning ${allTools.length} available tools`);
664
- return allTools;
665
- }
666
-
667
- /**
668
- * Execute a single tool with context and collected data.
669
- */
670
- async executeTool(params: {
671
- tool: Tool<TContext, TData>;
672
- context: TContext;
673
- updateContext: (updates: Partial<TContext>) => Promise<void>;
674
- updateData: (updates: Partial<TData>) => Promise<void>;
675
- history: Event[];
676
- data?: Partial<TData>;
677
- toolArguments?: Record<string, unknown>;
678
- }): Promise<ToolExecutionResult> {
679
- const { tool, context, updateContext, updateData, history, data, toolArguments } = params;
680
- const startTime = Date.now();
681
- const executionTimeout = 30000; // 30 seconds default timeout
682
-
683
- try {
684
- // Validate tool before execution
685
- if (!tool || !tool.handler || typeof tool.handler !== 'function') {
686
- return {
687
- success: false,
688
- error: `Invalid tool: ${tool?.id || 'unknown'} - missing or invalid handler`,
689
- metadata: { toolId: tool?.id, executionTime: 0 }
690
- };
691
- }
692
-
693
- // Build tool context with complete agent data
694
- const collectedDirectives: Directive<TContext, TData>[] = [];
695
-
696
- const toolContext: ToolContext<TContext, TData> = {
697
- context,
698
- updateContext,
699
- updateData,
700
- history,
701
- data: data || {},
702
- getField: <K extends keyof TData>(key: K): TData[K] | undefined => {
703
- return data?.[key];
704
- },
705
- setField: async <K extends keyof TData>(key: K, value: TData[K]): Promise<void> => {
706
- const update = {} as Partial<TData>;
707
- update[key] = value;
708
- await updateData(update);
709
- },
710
- hasField: <K extends keyof TData>(key: K): boolean => {
711
- return data != null && key in data;
712
- },
713
- dispatch: (directive: Directive<TContext, TData>): void => {
714
- collectedDirectives.push(directive);
715
- }
716
- };
717
-
718
- logger.debug(`[ToolManager] Executing tool: ${tool.id} with args:`, toolArguments);
719
-
720
- // Pre-execution gates (validateInput → checkPermissions). Shared with the
721
- // streaming executor (StreamingToolExecutor) so authorization/validation
722
- // behave identically on every transport. When a gate denies, the handler
723
- // is NOT invoked.
724
- const gateDenial = await evaluateToolGates(tool, toolArguments, toolContext, startTime);
725
- if (gateDenial) {
726
- return gateDenial;
727
- }
728
-
729
- // Execute tool with timeout protection. The timer is cleared when the
730
- // race settles AND unref'd so a pending timer never delays process
731
- // shutdown; a handler that loses the race keeps running detached (its
732
- // result is discarded), which we surface in a warn.
733
- let timeoutTimer: ReturnType<typeof setTimeout> | undefined;
734
- const timeoutPromise = new Promise<never>((_, reject) => {
735
- timeoutTimer = setTimeout(
736
- () => reject(new Error(`Tool execution timeout after ${executionTimeout}ms`)),
737
- executionTimeout
738
- );
739
- timeoutTimer.unref?.();
740
- });
741
-
742
- let result: unknown;
743
- try {
744
- // Attach a no-op catch to the losing handler promise so a post-timeout
745
- // rejection can't surface as an unhandled rejection and crash the process.
746
- const handlerPromise = Promise.resolve(tool.handler(toolContext, toolArguments));
747
- handlerPromise.catch(() => undefined);
748
- result = await Promise.race([handlerPromise, timeoutPromise]);
749
- } finally {
750
- clearTimeout(timeoutTimer);
751
- }
752
-
753
- const executionTime = Date.now() - startTime;
754
- logger.debug(`[ToolManager] Tool ${tool.id} completed in ${executionTime}ms`);
755
-
756
- // Handle different result types. Only SEMANTIC markers identify a
757
- // ToolResult — bare `{data}` / `{error}` shapes are indistinguishable
758
- // from ordinary business payloads (e.g. upstream API envelopes) and are
759
- // wrapped as raw results instead.
760
- let toolResult: ToolResult<unknown, TContext, TData>;
761
-
762
- if (isToolResultLike(result)) {
763
- // It's already a ToolResult-like object
764
- toolResult = result as ToolResult<unknown, TContext, TData>;
765
- } else {
766
- // It's a raw result - wrap it
767
- toolResult = {
768
- data: result,
769
- success: true
770
- };
771
- }
772
-
773
- // Collect directives from the result — singular and plural forms both
774
- // count, ordered identically to the concurrent executor.
775
- collectedDirectives.push(...extractResultDirectives(toolResult));
776
-
777
- // Apply data updates from tool result with validation
778
- if (toolResult.dataUpdate) {
779
- try {
780
- if (typeof toolResult.dataUpdate === 'object' && toolResult.dataUpdate !== null) {
781
- await updateData(toolResult.dataUpdate);
782
- } else {
783
- logger.warn(`[DataValidationError] Tool "${tool.id}" returned invalid dataUpdate: expected object, got ${typeof toolResult.dataUpdate}. Fix the tool handler to return a valid dataUpdate object.`);
784
- }
785
- } catch (updateError) {
786
- logger.error(`[ToolManager] Failed to apply data update from tool ${tool.id}:`, updateError);
787
- return {
788
- success: false,
789
- error: `Failed to apply data update: ${updateError instanceof Error ? updateError.message : String(updateError)}`,
790
- metadata: { toolId: tool.id, executionTime, updateError: updateError instanceof Error ? updateError.message : String(updateError) }
791
- };
792
- }
793
- }
794
-
795
- // Apply context updates from tool result with validation
796
- if (toolResult.contextUpdate) {
797
- try {
798
- if (typeof toolResult.contextUpdate === 'object' && toolResult.contextUpdate !== null) {
799
- await updateContext(toolResult.contextUpdate);
800
- } else {
801
- logger.warn(`[DataValidationError] Tool "${tool.id}" returned invalid contextUpdate: expected object, got ${typeof toolResult.contextUpdate}. Fix the tool handler to return a valid contextUpdate object.`);
802
- }
803
- } catch (updateError) {
804
- logger.error(`[ToolManager] Failed to apply context update from tool ${tool.id}:`, updateError);
805
- return {
806
- success: false,
807
- error: `Failed to apply context update: ${updateError instanceof Error ? updateError.message : String(updateError)}`,
808
- metadata: { toolId: tool.id, executionTime, updateError: updateError instanceof Error ? updateError.message : String(updateError) }
809
- };
810
- }
811
- }
812
-
813
- // Return execution result with metadata
814
- return {
815
- success: toolResult.success !== false, // Default to true unless explicitly false
816
- data: toolResult.data,
817
- contextUpdate: toolResult.contextUpdate,
818
- dataUpdate: toolResult.dataUpdate,
819
- error: toolResult.error,
820
- directives: collectedDirectives.length > 0 ? collectedDirectives : undefined,
821
- metadata: {
822
- toolId: tool.id,
823
- toolName: tool.id,
824
- executionTime,
825
- ...(toolResult.meta || {})
826
- }
827
- };
828
- } catch (error) {
829
- const executionTime = Date.now() - startTime;
830
-
831
- logger.error(`[ToolManager] Tool execution error for ${tool.id} after ${executionTime}ms:`, error);
832
- if (error instanceof Error && error.message.includes("Tool execution timeout")) {
833
- // The losing handler may still be running with captured callbacks.
834
- // Its writes are NOT rolled back here — tools should stay idempotent
835
- // or accept their own cancellation via interruptBehavior/abort.
836
- logger.warn(
837
- `[ToolManager] Handler for "${tool.id}" exceeded ${executionTimeout}ms and was abandoned while still running. ` +
838
- `Its eventual side effects are not cancelled or rolled back.`
839
- );
840
- }
841
-
842
- // Re-throw the error so callers can handle it
843
- throw error;
844
- }
845
- }
846
-
847
- /**
848
- * Execute tool calls with concurrency control using StreamingToolExecutor.
849
- * Creates a StreamingToolExecutor, resolves tools, queues them, and yields
850
- * ToolExecutionUpdate results in original request order.
851
- *
852
- * Concurrency-safe tools run in parallel; non-safe tools run serially.
853
- * Progress messages are yielded immediately.
854
- */
855
- async *executeWithConcurrency(params: {
856
- toolCalls: ToolCallRequest[];
857
- context: TContext;
858
- data?: Partial<TData>;
859
- history?: Event[];
860
- signal?: AbortSignal;
861
- flow?: Flow<TContext, TData>;
862
- step?: Step<TContext, TData>;
863
- }): AsyncGenerator<ToolExecutionUpdate<TData>> {
864
- const { toolCalls, context, data, history, signal, flow, step } = params;
865
-
866
- if (toolCalls.length === 0) {
867
- return;
868
- }
869
-
870
- // Build a ToolContext for the executor
871
- const toolContext: ToolContext<TContext, TData> = {
872
- context,
873
- data: data || {} as Partial<TData>,
874
- history: history || [],
875
- step: step ? { id: step.id, flowId: flow?.id || '' } : undefined,
876
- updateContext: (updates: Partial<TContext>): Promise<void> => {
877
- Object.assign(context as Record<string, unknown>, updates);
878
- return Promise.resolve();
879
- },
880
- updateData: (updates: Partial<TData>): Promise<void> => {
881
- if (data) {
882
- Object.assign(data as Record<string, unknown>, updates);
883
- }
884
- return Promise.resolve();
885
- },
886
- getField: <K extends keyof TData>(key: K): TData[K] | undefined => {
887
- return data?.[key];
888
- },
889
- setField: <K extends keyof TData>(key: K, value: TData[K]): Promise<void> => {
890
- if (data) {
891
- (data as TData)[key] = value;
892
- }
893
- return Promise.resolve();
894
- },
895
- hasField: <K extends keyof TData>(key: K): boolean => {
896
- return data != null && key in (data as Record<string, unknown>);
897
- },
898
- dispatch: (_directive: Directive<TContext, TData>): void => {
899
- // Handlers never see THIS context — StreamingToolExecutor.executeTool
900
- // wraps each call in a per-call context whose dispatch attributes the
901
- // directive to that tool. Reaching here means a gate or future caller
902
- // dispatched outside a tool execution; surface it instead of dropping.
903
- logger.warn("[ToolManager] ctx.dispatch called outside tool execution has no turn to attach to; directive dropped.");
904
- },
905
- };
906
-
907
- const executor = new StreamingToolExecutor<TContext, TData>(toolContext, {
908
- signal,
909
- });
910
-
911
- // Resolve and queue each tool call
912
- for (const toolCall of toolCalls) {
913
- const tool = this.find(toolCall.toolName, undefined, step, flow);
914
- if (!tool) {
915
- logger.warn(`[ToolExecutionError] Tool not found for concurrent execution: "${toolCall.toolName}" is not registered in any scope. Skipping. Register the tool or check the tool name.`);
916
- continue;
917
- }
918
- // Tool carries all metadata fields directly — no cast needed
919
- executor.addTool(toolCall, tool);
920
- }
921
-
922
- // Yield all results in order
923
- yield* executor.getRemainingResults();
924
- }
925
-
926
- /**
927
- * Create a data enrichment tool that modifies collected data
928
- * Returns a tool instance that can be registered or added to scope
929
- */
930
- createDataEnrichment<TFields extends keyof TData>(
931
- config: DataEnrichmentConfig<TContext, TData, TFields>
932
- ): Tool<TContext, TData, void> {
933
- // Validate configuration first
934
- this.validateDataEnrichmentConfig(config);
935
-
936
- const tool: Tool<TContext, TData, void> = {
937
- id: config.id,
938
- description: config.description || `Enriches data fields: ${config.fields.join(', ')}`,
939
- parameters: {
940
- type: 'object',
941
- properties: {
942
- fields: {
943
- type: 'array',
944
- items: { type: 'string' },
945
- description: `Fields to enrich: ${config.fields.join(', ')}`
946
- }
947
- }
948
- },
949
- handler: async (context: ToolContext<TContext, TData>) => {
950
- try {
951
- // Extract the specified fields from current data
952
- const fieldData = {} as Pick<TData, TFields>;
953
- for (const field of config.fields) {
954
- if (context.hasField(field)) {
955
- const value = context.getField(field);
956
- if (value !== undefined) {
957
- (fieldData as Record<string, unknown>)[field as string] = value;
958
- }
959
- }
960
- }
961
-
962
- // Call the enricher function
963
- const enrichedData = await config.enricher(context.context, fieldData);
964
-
965
- // Update the data with enriched values
966
- if (enrichedData && typeof enrichedData === 'object') {
967
- await context.updateData(enrichedData);
968
- }
969
-
970
- logger.debug(`[ToolManager] Data enrichment completed for tool: ${config.id}`);
971
-
972
- return {
973
- success: true,
974
- dataUpdate: enrichedData
975
- };
976
- } catch (error) {
977
- const errorMessage = error instanceof Error ? error.message : String(error);
978
- logger.error(`[ToolManager] Data enrichment failed for ${config.id}: ${errorMessage}`);
979
- throw new ToolExecutionError(
980
- `[ToolExecutionError] Data enrichment failed for tool "${config.id}": ${errorMessage}. ` +
981
- `Check the enrichment handler and field references.`,
982
- config.id,
983
- { fields: config.fields },
984
- error instanceof Error ? error : undefined
985
- );
986
- }
987
- }
988
- };
989
-
990
- return tool;
991
- }
992
-
993
- /**
994
- * Create a validation tool that validates data fields
995
- * Returns a tool instance that can be registered or added to scope
996
- */
997
- createValidation<TFields extends keyof TData>(
998
- config: ValidationConfig<TContext, TData, TFields>
999
- ): Tool<TContext, TData, ValidationResult> {
1000
- // Validate configuration first
1001
- this.validateValidationConfig(config);
1002
-
1003
- const tool: Tool<TContext, TData, ValidationResult> = {
1004
- id: config.id,
1005
- description: config.description || `Validates data fields: ${config.fields.join(', ')}`,
1006
- parameters: {
1007
- type: 'object',
1008
- properties: {
1009
- fields: {
1010
- type: 'array',
1011
- items: { type: 'string' },
1012
- description: `Fields to validate: ${config.fields.join(', ')}`
1013
- }
1014
- }
1015
- },
1016
- handler: async (context: ToolContext<TContext, TData>): Promise<ValidationResult> => {
1017
- try {
1018
- // Extract the specified fields from current data
1019
- const fieldData = {} as Pick<TData, TFields>;
1020
- for (const field of config.fields) {
1021
- if (context.hasField(field)) {
1022
- const value = context.getField(field);
1023
- if (value !== undefined) {
1024
- (fieldData as Record<string, unknown>)[field as string] = value;
1025
- }
1026
- }
1027
- }
1028
-
1029
- // Call the validator function
1030
- const result = await config.validator(context.context, fieldData);
1031
-
1032
- logger.debug(`[ToolManager] Validation completed for tool: ${config.id}, valid: ${result.valid}`);
1033
- return result;
1034
- } catch (error) {
1035
- const errorMessage = error instanceof Error ? error.message : String(error);
1036
- logger.error(`[ToolManager] Validation failed for ${config.id}: ${errorMessage}`);
1037
-
1038
- // Return validation failure result instead of throwing
1039
- return {
1040
- valid: false,
1041
- errors: [{
1042
- field: 'validation',
1043
- message: `Validation error: ${errorMessage}`,
1044
- value: undefined,
1045
- schemaPath: config.id
1046
- }],
1047
- warnings: []
1048
- };
1049
- }
1050
- }
1051
- };
1052
-
1053
- return tool;
1054
- }
1055
-
1056
- /**
1057
- * Create an API call tool that makes external HTTP requests
1058
- * Returns a tool instance that can be registered or added to scope
1059
- */
1060
- createApiCall<TResult = unknown>(
1061
- config: ApiCallConfig<TContext, TData, TResult>
1062
- ): Tool<TContext, TData, TResult> {
1063
- // Validate configuration first
1064
- this.validateApiCallConfig(config);
1065
-
1066
- const tool: Tool<TContext, TData, TResult> = {
1067
- id: config.id,
1068
- description: config.description || `Makes API call to external service`,
1069
- parameters: {
1070
- type: 'object',
1071
- properties: {
1072
- endpoint: {
1073
- type: 'string',
1074
- description: 'API endpoint URL'
1075
- },
1076
- method: {
1077
- type: 'string',
1078
- enum: ['GET', 'POST', 'PUT', 'DELETE'],
1079
- description: 'HTTP method'
1080
- }
1081
- }
1082
- },
1083
- handler: async (context: ToolContext<TContext, TData>, args?: Record<string, unknown>): Promise<TResult> => {
1084
- try {
1085
- // Resolve endpoint URL
1086
- const endpoint = typeof config.endpoint === 'function'
1087
- ? config.endpoint(context.context, context.data)
1088
- : config.endpoint;
1089
-
1090
- // Resolve headers
1091
- const headers = typeof config.headers === 'function'
1092
- ? config.headers(context.context)
1093
- : config.headers || {};
1094
-
1095
- // Prepare request options
1096
- const requestOptions: RequestInit = {
1097
- method: config.method || 'GET',
1098
- headers: {
1099
- 'Content-Type': 'application/json',
1100
- ...headers
1101
- }
1102
- };
1103
-
1104
- // Add body for non-GET requests
1105
- if (config.body && (config.method === 'POST' || config.method === 'PUT')) {
1106
- const bodyData = config.body(context.context, context.data, args);
1107
- requestOptions.body = JSON.stringify(bodyData);
1108
- }
1109
-
1110
- // Make the API call
1111
- const response = await fetch(endpoint, requestOptions);
1112
-
1113
- if (!response.ok) {
1114
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
1115
- }
1116
-
1117
- // Parse response
1118
- let responseData: unknown;
1119
- const contentType = response.headers.get('content-type');
1120
- if (contentType && contentType.includes('application/json')) {
1121
- responseData = await response.json();
1122
- } else {
1123
- responseData = await response.text();
1124
- }
1125
-
1126
- // Transform response if transformer provided
1127
- const result = config.transform ? config.transform(responseData) : responseData as TResult;
1128
-
1129
- logger.debug(`[ToolManager] API call completed for tool: ${config.id}`);
1130
- return result;
1131
- } catch (error) {
1132
- const errorMessage = error instanceof Error ? error.message : String(error);
1133
- logger.error(`[ToolManager] API call failed for ${config.id}: ${errorMessage}`);
1134
-
1135
- throw new ToolExecutionError(
1136
- `[ToolExecutionError] API call failed for tool "${config.id}": ${errorMessage}. ` +
1137
- `Check the endpoint URL, method, and network connectivity.`,
1138
- config.id,
1139
- { endpoint: config.endpoint, method: config.method, args },
1140
- error instanceof Error ? error : undefined
1141
- );
1142
- }
1143
- }
1144
- };
1145
-
1146
- return tool;
1147
- }
1148
-
1149
- /**
1150
- * Create a computation tool that performs calculations on input data
1151
- * Returns a tool instance that can be registered or added to scope
1152
- */
1153
- createComputation<TResult = unknown>(
1154
- config: ComputationConfig<TContext, TData, TResult>
1155
- ): Tool<TContext, TData, TResult> {
1156
- // Validate configuration first
1157
- this.validateComputationConfig(config);
1158
-
1159
- const tool: Tool<TContext, TData, TResult> = {
1160
- id: config.id,
1161
- description: config.description || `Performs computation on inputs: ${config.inputs.join(', ')}`,
1162
- parameters: {
1163
- type: 'object',
1164
- properties: {
1165
- inputs: {
1166
- type: 'array',
1167
- items: { type: 'string' },
1168
- description: `Input fields: ${config.inputs.join(', ')}`
1169
- }
1170
- }
1171
- },
1172
- handler: async (context: ToolContext<TContext, TData>, args?: Record<string, unknown>): Promise<TResult> => {
1173
- try {
1174
- // Extract the specified input fields from current data
1175
- const inputData = {} as Partial<TData>;
1176
- for (const input of config.inputs) {
1177
- if (context.hasField(input)) {
1178
- const value = context.getField(input);
1179
- if (value !== undefined) {
1180
- (inputData as Record<string, unknown>)[input as string] = value;
1181
- }
1182
- }
1183
- }
1184
-
1185
- // Call the compute function
1186
- const result = await config.compute(context.context, inputData, args);
1187
-
1188
- logger.debug(`[ToolManager] Computation completed for tool: ${config.id}`);
1189
- return result;
1190
- } catch (error) {
1191
- const errorMessage = error instanceof Error ? error.message : String(error);
1192
- logger.error(`[ToolManager] Computation failed for ${config.id}: ${errorMessage}`);
1193
-
1194
- throw new ToolExecutionError(
1195
- `[ToolExecutionError] Computation failed for tool "${config.id}": ${errorMessage}. ` +
1196
- `Check the compute function and input field references.`,
1197
- config.id,
1198
- { inputs: config.inputs, args },
1199
- error instanceof Error ? error : undefined
1200
- );
1201
- }
1202
- }
1203
- };
1204
-
1205
- return tool;
1206
- }
1207
-
1208
- /**
1209
- * Get detailed information about a tool for debugging
1210
- */
1211
- getToolInfo(toolId: string, scope?: ToolScope, step?: Step<TContext, TData>, flow?: Flow<TContext, TData>): {
1212
- found: boolean;
1213
- tool?: Tool<TContext, TData>;
1214
- scope?: string;
1215
- metadata?: Record<string, unknown>;
1216
- } {
1217
- const tool = this.find(toolId, scope, step, flow);
1218
-
1219
- if (!tool) {
1220
- return { found: false };
1221
- }
1222
-
1223
- // Determine which scope the tool was found in
1224
- let foundScope = 'unknown';
1225
-
1226
- // Check step scope
1227
- if (step?.tools) {
1228
- const stepTool = step.tools.find((t) =>
1229
- (typeof t === 'string' && t === toolId) ||
1230
- (typeof t === 'object' && (t.id === toolId))
1231
- );
1232
- if (stepTool) foundScope = 'step';
1233
- }
1234
-
1235
- // Check route scope
1236
- if (foundScope === 'unknown' && flow?.tools) {
1237
- const flowTool = flow.tools.find((t) => t.id === toolId);
1238
- if (flowTool) foundScope = 'flow';
1239
- }
1240
-
1241
- // Check agent scope
1242
- if (foundScope === 'unknown' && this.agent) {
1243
- const agentTools = this.agent.tools;
1244
- const agentTool = agentTools.find((t) => t.id === toolId);
1245
- if (agentTool) foundScope = 'agent';
1246
- }
1247
-
1248
- // Check registry
1249
- if (foundScope === 'unknown' && this.toolRegistry.has(toolId)) {
1250
- foundScope = 'registry';
1251
- }
1252
-
1253
- return {
1254
- found: true,
1255
- tool,
1256
- scope: foundScope,
1257
- metadata: {
1258
- id: tool.id,
1259
- hasDescription: !!tool.description,
1260
- hasParameters: !!tool.parameters,
1261
- handlerLength: tool.handler.length
1262
- }
1263
- };
1264
- }
1265
-
1266
- /**
1267
- * Validate that all tools in a list exist and are accessible
1268
- */
1269
- validateToolReferences(toolIds: string[], step?: Step<TContext, TData>, flow?: Flow<TContext, TData>): {
1270
- valid: boolean;
1271
- missing: string[];
1272
- found: string[];
1273
- details: Array<{ id: string; found: boolean; scope?: string; }>;
1274
- } {
1275
- const missing: string[] = [];
1276
- const found: string[] = [];
1277
- const details: Array<{ id: string; found: boolean; scope?: string; }> = [];
1278
-
1279
- for (const toolId of toolIds) {
1280
- const info = this.getToolInfo(toolId, ToolScope.ALL, step, flow);
1281
-
1282
- if (info.found) {
1283
- found.push(toolId);
1284
- details.push({ id: toolId, found: true, scope: info.scope });
1285
- } else {
1286
- missing.push(toolId);
1287
- details.push({ id: toolId, found: false });
1288
- }
1289
- }
1290
-
1291
- return {
1292
- valid: missing.length === 0,
1293
- missing,
1294
- found,
1295
- details
1296
- };
1297
- }
1298
-
1299
- /**
1300
- * Get comprehensive statistics about the tool system
1301
- */
1302
- getStatistics(): {
1303
- registeredTools: number;
1304
- agentTools: number;
1305
- totalAvailable: number;
1306
- registeredToolIds: string[];
1307
- duplicateIds: string[];
1308
- } {
1309
- const registeredToolIds = Array.from(this.toolRegistry.keys());
1310
- const agentTools = this.agent ? this.agent.getTools() : [];
1311
- const agentToolIds = agentTools.map((t) => t.id);
1312
-
1313
- // Find duplicate IDs between registry and agent
1314
- const duplicateIds = registeredToolIds.filter(id => agentToolIds.includes(id));
1315
-
1316
- const allAvailable = this.getAvailable();
1317
-
1318
- return {
1319
- registeredTools: this.toolRegistry.size,
1320
- agentTools: agentTools.length,
1321
- totalAvailable: allAvailable.length,
1322
- registeredToolIds,
1323
- duplicateIds
1324
- };
1325
- }
1326
-
1327
- /**
1328
- * Perform health check on the tool system
1329
- */
1330
- healthCheck(): {
1331
- healthy: boolean;
1332
- issues: string[];
1333
- warnings: string[];
1334
- statistics: {
1335
- registeredTools: number;
1336
- agentTools: number;
1337
- totalAvailable: number;
1338
- registeredToolIds: string[];
1339
- duplicateIds: string[];
1340
- };
1341
- } {
1342
- const issues: string[] = [];
1343
- const warnings: string[] = [];
1344
- const stats = this.getStatistics();
1345
-
1346
- // Check for duplicate tool IDs
1347
- if (stats.duplicateIds.length > 0) {
1348
- warnings.push(`Duplicate tool IDs found between registry and agent: ${stats.duplicateIds.join(', ')}`);
1349
- }
1350
-
1351
- // Check for tools with missing handlers
1352
- for (const [id, tool] of Array.from(this.toolRegistry.entries())) {
1353
- if (!tool.handler || typeof tool.handler !== 'function') {
1354
- issues.push(`Tool '${id}' has invalid or missing handler`);
1355
- }
1356
-
1357
- if (!tool.id || tool.id.trim() === '') {
1358
- issues.push(`Tool has empty or invalid ID: ${JSON.stringify(tool)}`);
1359
- }
1360
- }
1361
-
1362
- // Check agent tools if available
1363
- if (this.agent) {
1364
- const agentTools = this.agent.getTools();
1365
- for (const tool of agentTools) {
1366
- if (!tool.handler || typeof tool.handler !== 'function') {
1367
- issues.push(`Agent tool '${tool.id}' has invalid or missing handler`);
1368
- }
1369
- }
1370
- }
1371
-
1372
- return {
1373
- healthy: issues.length === 0,
1374
- issues,
1375
- warnings,
1376
- statistics: stats
1377
- };
1378
- }
1379
- }