@falai/agent 3.4.5 → 4.0.0-alpha.2

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 (856) hide show
  1. package/README.md +41 -34
  2. package/dist/cjs/core/Agent.d.ts +22 -378
  3. package/dist/cjs/core/Agent.d.ts.map +1 -1
  4. package/dist/cjs/core/Agent.js +104 -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 +522 -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 +143 -0
  20. package/dist/cjs/core/Prompt.js.map +1 -0
  21. package/dist/cjs/core/Runner.d.ts +160 -0
  22. package/dist/cjs/core/Runner.d.ts.map +1 -0
  23. package/dist/cjs/core/Runner.js +1131 -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 +364 -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 +353 -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 +153 -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/schema.d.ts +50 -0
  158. package/dist/cjs/utils/schema.d.ts.map +1 -0
  159. package/dist/cjs/utils/schema.js +138 -0
  160. package/dist/cjs/utils/schema.js.map +1 -0
  161. package/dist/cjs/utils/streamingMessage.d.ts +3 -2
  162. package/dist/cjs/utils/streamingMessage.d.ts.map +1 -1
  163. package/dist/cjs/utils/streamingMessage.js +38 -4
  164. package/dist/cjs/utils/streamingMessage.js.map +1 -1
  165. package/dist/cjs/utils/template.d.ts +13 -149
  166. package/dist/cjs/utils/template.d.ts.map +1 -1
  167. package/dist/cjs/utils/template.js +31 -363
  168. package/dist/cjs/utils/template.js.map +1 -1
  169. package/dist/cjs/utils/usage.d.ts +19 -0
  170. package/dist/cjs/utils/usage.d.ts.map +1 -0
  171. package/dist/cjs/utils/usage.js +35 -0
  172. package/dist/cjs/utils/usage.js.map +1 -0
  173. package/dist/core/Agent.d.ts +22 -378
  174. package/dist/core/Agent.d.ts.map +1 -1
  175. package/dist/core/Agent.js +107 -1181
  176. package/dist/core/Agent.js.map +1 -1
  177. package/dist/core/CompactionEngine.d.ts.map +1 -1
  178. package/dist/core/CompactionEngine.js +5 -3
  179. package/dist/core/CompactionEngine.js.map +1 -1
  180. package/dist/core/FlowSpec.d.ts +136 -0
  181. package/dist/core/FlowSpec.d.ts.map +1 -0
  182. package/dist/core/FlowSpec.js +516 -0
  183. package/dist/core/FlowSpec.js.map +1 -0
  184. package/dist/core/Migrate.d.ts +38 -0
  185. package/dist/core/Migrate.d.ts.map +1 -0
  186. package/dist/core/Migrate.js +264 -0
  187. package/dist/core/Migrate.js.map +1 -0
  188. package/dist/core/Prompt.d.ts +54 -0
  189. package/dist/core/Prompt.d.ts.map +1 -0
  190. package/dist/core/Prompt.js +133 -0
  191. package/dist/core/Prompt.js.map +1 -0
  192. package/dist/core/Runner.d.ts +160 -0
  193. package/dist/core/Runner.d.ts.map +1 -0
  194. package/dist/core/Runner.js +1127 -0
  195. package/dist/core/Runner.js.map +1 -0
  196. package/dist/core/Speak.d.ts +37 -0
  197. package/dist/core/Speak.d.ts.map +1 -0
  198. package/dist/core/Speak.js +360 -0
  199. package/dist/core/Speak.js.map +1 -0
  200. package/dist/core/Understand.d.ts +28 -0
  201. package/dist/core/Understand.d.ts.map +1 -0
  202. package/dist/core/Understand.js +349 -0
  203. package/dist/core/Understand.js.map +1 -0
  204. package/dist/core/contracts.d.ts +122 -0
  205. package/dist/core/contracts.d.ts.map +1 -0
  206. package/dist/core/contracts.js +10 -0
  207. package/dist/core/contracts.js.map +1 -0
  208. package/dist/core/falai.d.ts +57 -0
  209. package/dist/core/falai.d.ts.map +1 -0
  210. package/dist/core/falai.js +40 -0
  211. package/dist/core/falai.js.map +1 -0
  212. package/dist/core/predicate.d.ts +9 -0
  213. package/dist/core/predicate.d.ts.map +1 -0
  214. package/dist/core/predicate.js +54 -0
  215. package/dist/core/predicate.js.map +1 -0
  216. package/dist/index.d.ts +26 -31
  217. package/dist/index.d.ts.map +1 -1
  218. package/dist/index.js +19 -24
  219. package/dist/index.js.map +1 -1
  220. package/dist/persistence/MemoryStore.d.ts +15 -0
  221. package/dist/persistence/MemoryStore.d.ts.map +1 -0
  222. package/dist/persistence/MemoryStore.js +35 -0
  223. package/dist/persistence/MemoryStore.js.map +1 -0
  224. package/dist/persistence/MongoStore.d.ts +42 -0
  225. package/dist/persistence/MongoStore.d.ts.map +1 -0
  226. package/dist/persistence/MongoStore.js +56 -0
  227. package/dist/persistence/MongoStore.js.map +1 -0
  228. package/dist/persistence/OpenSearchStore.d.ts +86 -0
  229. package/dist/persistence/OpenSearchStore.d.ts.map +1 -0
  230. package/dist/persistence/OpenSearchStore.js +116 -0
  231. package/dist/persistence/OpenSearchStore.js.map +1 -0
  232. package/dist/persistence/PostgresStore.d.ts +41 -0
  233. package/dist/persistence/PostgresStore.d.ts.map +1 -0
  234. package/dist/persistence/PostgresStore.js +54 -0
  235. package/dist/persistence/PostgresStore.js.map +1 -0
  236. package/dist/persistence/PrismaStore.d.ts +65 -0
  237. package/dist/persistence/PrismaStore.d.ts.map +1 -0
  238. package/dist/persistence/PrismaStore.js +91 -0
  239. package/dist/persistence/PrismaStore.js.map +1 -0
  240. package/dist/persistence/RedisStore.d.ts +34 -0
  241. package/dist/persistence/RedisStore.d.ts.map +1 -0
  242. package/dist/persistence/RedisStore.js +57 -0
  243. package/dist/persistence/RedisStore.js.map +1 -0
  244. package/dist/persistence/SQLiteStore.d.ts +45 -0
  245. package/dist/persistence/SQLiteStore.d.ts.map +1 -0
  246. package/dist/persistence/SQLiteStore.js +70 -0
  247. package/dist/persistence/SQLiteStore.js.map +1 -0
  248. package/dist/persistence/sessionRow.d.ts +14 -0
  249. package/dist/persistence/sessionRow.d.ts.map +1 -0
  250. package/dist/persistence/sessionRow.js +45 -0
  251. package/dist/persistence/sessionRow.js.map +1 -0
  252. package/dist/providers/DeepSeekProvider.d.ts.map +1 -1
  253. package/dist/providers/DeepSeekProvider.js +8 -3
  254. package/dist/providers/DeepSeekProvider.js.map +1 -1
  255. package/dist/providers/GeminiProvider.d.ts +4 -3
  256. package/dist/providers/GeminiProvider.d.ts.map +1 -1
  257. package/dist/providers/GeminiProvider.js +4 -3
  258. package/dist/providers/GeminiProvider.js.map +1 -1
  259. package/dist/providers/OpenAICompatibleProvider.d.ts +4 -0
  260. package/dist/providers/OpenAICompatibleProvider.d.ts.map +1 -1
  261. package/dist/providers/OpenAICompatibleProvider.js +2 -0
  262. package/dist/providers/OpenAICompatibleProvider.js.map +1 -1
  263. package/dist/providers/OpenRouterProvider.d.ts.map +1 -1
  264. package/dist/providers/OpenRouterProvider.js +2 -4
  265. package/dist/providers/OpenRouterProvider.js.map +1 -1
  266. package/dist/providers/ProviderAdapter.d.ts +11 -6
  267. package/dist/providers/ProviderAdapter.d.ts.map +1 -1
  268. package/dist/providers/ProviderAdapter.js +34 -11
  269. package/dist/providers/ProviderAdapter.js.map +1 -1
  270. package/dist/providers/ZaiProvider.d.ts +6 -4
  271. package/dist/providers/ZaiProvider.d.ts.map +1 -1
  272. package/dist/providers/ZaiProvider.js +6 -4
  273. package/dist/providers/ZaiProvider.js.map +1 -1
  274. package/dist/types/agent.d.ts +153 -383
  275. package/dist/types/agent.d.ts.map +1 -1
  276. package/dist/types/agent.js +1 -1
  277. package/dist/types/ai.d.ts +32 -1
  278. package/dist/types/ai.d.ts.map +1 -1
  279. package/dist/types/compaction.d.ts +3 -1
  280. package/dist/types/compaction.d.ts.map +1 -1
  281. package/dist/types/errors.d.ts +9 -12
  282. package/dist/types/errors.d.ts.map +1 -1
  283. package/dist/types/errors.js +12 -15
  284. package/dist/types/errors.js.map +1 -1
  285. package/dist/types/flow.d.ts +265 -513
  286. package/dist/types/flow.d.ts.map +1 -1
  287. package/dist/types/flow.js +7 -1
  288. package/dist/types/flow.js.map +1 -1
  289. package/dist/types/history.d.ts +7 -18
  290. package/dist/types/history.d.ts.map +1 -1
  291. package/dist/types/history.js.map +1 -1
  292. package/dist/types/index.d.ts +9 -15
  293. package/dist/types/index.d.ts.map +1 -1
  294. package/dist/types/index.js +2 -7
  295. package/dist/types/index.js.map +1 -1
  296. package/dist/types/session.d.ts +94 -64
  297. package/dist/types/session.d.ts.map +1 -1
  298. package/dist/types/session.js +5 -1
  299. package/dist/types/session.js.map +1 -1
  300. package/dist/types/tool.d.ts +37 -207
  301. package/dist/types/tool.d.ts.map +1 -1
  302. package/dist/types/tool.js +6 -13
  303. package/dist/types/tool.js.map +1 -1
  304. package/dist/utils/clock.d.ts +28 -0
  305. package/dist/utils/clock.d.ts.map +1 -0
  306. package/dist/utils/clock.js +59 -0
  307. package/dist/utils/clock.js.map +1 -0
  308. package/dist/utils/duration.d.ts +11 -0
  309. package/dist/utils/duration.d.ts.map +1 -0
  310. package/dist/utils/duration.js +26 -0
  311. package/dist/utils/duration.js.map +1 -0
  312. package/dist/utils/history.d.ts +4 -1
  313. package/dist/utils/history.d.ts.map +1 -1
  314. package/dist/utils/history.js +2 -2
  315. package/dist/utils/history.js.map +1 -1
  316. package/dist/utils/index.d.ts +4 -10
  317. package/dist/utils/index.d.ts.map +1 -1
  318. package/dist/utils/index.js +4 -21
  319. package/dist/utils/index.js.map +1 -1
  320. package/dist/utils/json.d.ts +2 -0
  321. package/dist/utils/json.d.ts.map +1 -1
  322. package/dist/utils/json.js +4 -0
  323. package/dist/utils/json.js.map +1 -1
  324. package/dist/utils/outcomes.d.ts +48 -0
  325. package/dist/utils/outcomes.d.ts.map +1 -0
  326. package/dist/utils/outcomes.js +48 -0
  327. package/dist/utils/outcomes.js.map +1 -0
  328. package/dist/utils/schema.d.ts +50 -0
  329. package/dist/utils/schema.d.ts.map +1 -0
  330. package/dist/utils/schema.js +129 -0
  331. package/dist/utils/schema.js.map +1 -0
  332. package/dist/utils/streamingMessage.d.ts +3 -2
  333. package/dist/utils/streamingMessage.d.ts.map +1 -1
  334. package/dist/utils/streamingMessage.js +38 -4
  335. package/dist/utils/streamingMessage.js.map +1 -1
  336. package/dist/utils/template.d.ts +13 -149
  337. package/dist/utils/template.d.ts.map +1 -1
  338. package/dist/utils/template.js +28 -355
  339. package/dist/utils/template.js.map +1 -1
  340. package/dist/utils/usage.d.ts +19 -0
  341. package/dist/utils/usage.d.ts.map +1 -0
  342. package/dist/utils/usage.js +31 -0
  343. package/dist/utils/usage.js.map +1 -0
  344. package/docs/README.md +37 -19
  345. package/docs/concepts/architecture.md +117 -239
  346. package/docs/concepts/collection.md +170 -0
  347. package/docs/concepts/pipeline.md +132 -378
  348. package/docs/concepts/runs-and-waits.md +192 -0
  349. package/docs/guides/actions-and-events.md +276 -0
  350. package/docs/guides/branching.md +119 -208
  351. package/docs/guides/compaction.md +63 -158
  352. package/docs/guides/conditions.md +164 -128
  353. package/docs/guides/error-handling.md +168 -164
  354. package/docs/guides/flow-control.md +210 -349
  355. package/docs/guides/flows-from-json.md +224 -0
  356. package/docs/guides/instructions.md +125 -161
  357. package/docs/guides/persistence.md +182 -206
  358. package/docs/guides/streaming.md +50 -114
  359. package/docs/guides/testing.md +284 -0
  360. package/docs/guides/triggers.md +401 -0
  361. package/docs/migration/README.md +8 -15
  362. package/docs/migration/v1-to-v2.md +1 -1
  363. package/docs/migration/v2-3-to-v2-4.md +2 -2
  364. package/docs/migration/v2-6-to-v2-7.md +4 -4
  365. package/docs/migration/v3-to-v4.md +452 -0
  366. package/docs/reference/actions-events-conditions.md +396 -0
  367. package/docs/reference/agent.md +244 -0
  368. package/docs/reference/branches.md +75 -203
  369. package/docs/reference/errors.md +188 -144
  370. package/docs/reference/fields.md +125 -0
  371. package/docs/reference/flow-spec.md +248 -0
  372. package/docs/reference/flow.md +104 -192
  373. package/docs/reference/instruction.md +83 -137
  374. package/docs/reference/outcomes.md +273 -0
  375. package/docs/reference/providers.md +525 -302
  376. package/docs/reference/session.md +210 -0
  377. package/docs/reference/step.md +194 -312
  378. package/docs/reference/stores.md +496 -0
  379. package/docs/reference/tool.md +162 -231
  380. package/docs/reference/trigger.md +180 -0
  381. package/docs/rfc/v4-one-flow.md +477 -0
  382. package/docs/start/01-install.md +59 -44
  383. package/docs/start/02-first-agent.md +97 -147
  384. package/docs/start/03-collect-data.md +78 -183
  385. package/docs/start/04-add-tools.md +159 -227
  386. package/docs/start/05-go-to-production.md +167 -164
  387. package/examples/01-quickstart.ts +26 -16
  388. package/examples/02-fields.ts +75 -0
  389. package/examples/03-tools.ts +79 -119
  390. package/examples/04-instructions.ts +60 -87
  391. package/examples/05-branches.ts +78 -0
  392. package/examples/06-triggers-and-waits.ts +148 -0
  393. package/examples/07-streaming.ts +34 -60
  394. package/examples/08-store-and-migration.ts +97 -0
  395. package/examples/09-flows-from-json.ts +107 -0
  396. package/package.json +9 -6
  397. package/src/core/Agent.ts +116 -1512
  398. package/src/core/CompactionEngine.ts +7 -4
  399. package/src/core/FlowSpec.ts +712 -0
  400. package/src/core/Migrate.ts +256 -0
  401. package/src/core/Prompt.ts +156 -0
  402. package/src/core/Runner.ts +1181 -0
  403. package/src/core/Speak.ts +451 -0
  404. package/src/core/Understand.ts +422 -0
  405. package/src/core/contracts.ts +111 -0
  406. package/src/core/falai.ts +86 -0
  407. package/src/core/predicate.ts +56 -0
  408. package/src/index.ts +119 -147
  409. package/src/persistence/MemoryStore.ts +37 -0
  410. package/src/persistence/MongoStore.ts +89 -0
  411. package/src/persistence/OpenSearchStore.ts +153 -0
  412. package/src/persistence/PostgresStore.ts +89 -0
  413. package/src/persistence/PrismaStore.ts +127 -0
  414. package/src/persistence/RedisStore.ts +90 -0
  415. package/src/persistence/SQLiteStore.ts +103 -0
  416. package/src/persistence/sessionRow.ts +45 -0
  417. package/src/providers/DeepSeekProvider.ts +8 -3
  418. package/src/providers/GeminiProvider.ts +4 -3
  419. package/src/providers/OpenAICompatibleProvider.ts +6 -0
  420. package/src/providers/OpenRouterProvider.ts +2 -4
  421. package/src/providers/ProviderAdapter.ts +46 -13
  422. package/src/providers/ZaiProvider.ts +6 -4
  423. package/src/types/agent.ts +124 -397
  424. package/src/types/ai.ts +33 -1
  425. package/src/types/compaction.ts +3 -1
  426. package/src/types/errors.ts +13 -16
  427. package/src/types/flow.ts +249 -550
  428. package/src/types/history.ts +7 -20
  429. package/src/types/index.ts +87 -139
  430. package/src/types/session.ts +135 -70
  431. package/src/types/tool.ts +42 -267
  432. package/src/utils/clock.ts +70 -0
  433. package/src/utils/duration.ts +33 -0
  434. package/src/utils/history.ts +3 -2
  435. package/src/utils/index.ts +8 -66
  436. package/src/utils/json.ts +5 -0
  437. package/src/utils/outcomes.ts +56 -0
  438. package/src/utils/schema.ts +145 -0
  439. package/src/utils/streamingMessage.ts +34 -4
  440. package/src/utils/template.ts +32 -423
  441. package/src/utils/usage.ts +37 -0
  442. package/dist/adapters/MemoryAdapter.d.ts +0 -47
  443. package/dist/adapters/MemoryAdapter.d.ts.map +0 -1
  444. package/dist/adapters/MemoryAdapter.js +0 -204
  445. package/dist/adapters/MemoryAdapter.js.map +0 -1
  446. package/dist/adapters/MongoAdapter.d.ts +0 -97
  447. package/dist/adapters/MongoAdapter.d.ts.map +0 -1
  448. package/dist/adapters/MongoAdapter.js +0 -196
  449. package/dist/adapters/MongoAdapter.js.map +0 -1
  450. package/dist/adapters/OpenSearchAdapter.d.ts +0 -169
  451. package/dist/adapters/OpenSearchAdapter.d.ts.map +0 -1
  452. package/dist/adapters/OpenSearchAdapter.js +0 -471
  453. package/dist/adapters/OpenSearchAdapter.js.map +0 -1
  454. package/dist/adapters/PostgreSQLAdapter.d.ts +0 -85
  455. package/dist/adapters/PostgreSQLAdapter.d.ts.map +0 -1
  456. package/dist/adapters/PostgreSQLAdapter.js +0 -308
  457. package/dist/adapters/PostgreSQLAdapter.js.map +0 -1
  458. package/dist/adapters/PrismaAdapter.d.ts +0 -115
  459. package/dist/adapters/PrismaAdapter.d.ts.map +0 -1
  460. package/dist/adapters/PrismaAdapter.js +0 -406
  461. package/dist/adapters/PrismaAdapter.js.map +0 -1
  462. package/dist/adapters/RedisAdapter.d.ts +0 -72
  463. package/dist/adapters/RedisAdapter.d.ts.map +0 -1
  464. package/dist/adapters/RedisAdapter.js +0 -286
  465. package/dist/adapters/RedisAdapter.js.map +0 -1
  466. package/dist/adapters/SQLiteAdapter.d.ts +0 -86
  467. package/dist/adapters/SQLiteAdapter.d.ts.map +0 -1
  468. package/dist/adapters/SQLiteAdapter.js +0 -337
  469. package/dist/adapters/SQLiteAdapter.js.map +0 -1
  470. package/dist/adapters/index.d.ts +0 -17
  471. package/dist/adapters/index.d.ts.map +0 -1
  472. package/dist/adapters/index.js +0 -11
  473. package/dist/adapters/index.js.map +0 -1
  474. package/dist/adapters/sessionRow.d.ts +0 -22
  475. package/dist/adapters/sessionRow.d.ts.map +0 -1
  476. package/dist/adapters/sessionRow.js +0 -48
  477. package/dist/adapters/sessionRow.js.map +0 -1
  478. package/dist/cjs/adapters/MemoryAdapter.d.ts +0 -47
  479. package/dist/cjs/adapters/MemoryAdapter.d.ts.map +0 -1
  480. package/dist/cjs/adapters/MemoryAdapter.js +0 -208
  481. package/dist/cjs/adapters/MemoryAdapter.js.map +0 -1
  482. package/dist/cjs/adapters/MongoAdapter.d.ts +0 -97
  483. package/dist/cjs/adapters/MongoAdapter.d.ts.map +0 -1
  484. package/dist/cjs/adapters/MongoAdapter.js +0 -200
  485. package/dist/cjs/adapters/MongoAdapter.js.map +0 -1
  486. package/dist/cjs/adapters/OpenSearchAdapter.d.ts +0 -169
  487. package/dist/cjs/adapters/OpenSearchAdapter.d.ts.map +0 -1
  488. package/dist/cjs/adapters/OpenSearchAdapter.js +0 -475
  489. package/dist/cjs/adapters/OpenSearchAdapter.js.map +0 -1
  490. package/dist/cjs/adapters/PostgreSQLAdapter.d.ts +0 -85
  491. package/dist/cjs/adapters/PostgreSQLAdapter.d.ts.map +0 -1
  492. package/dist/cjs/adapters/PostgreSQLAdapter.js +0 -312
  493. package/dist/cjs/adapters/PostgreSQLAdapter.js.map +0 -1
  494. package/dist/cjs/adapters/PrismaAdapter.d.ts +0 -115
  495. package/dist/cjs/adapters/PrismaAdapter.d.ts.map +0 -1
  496. package/dist/cjs/adapters/PrismaAdapter.js +0 -410
  497. package/dist/cjs/adapters/PrismaAdapter.js.map +0 -1
  498. package/dist/cjs/adapters/RedisAdapter.d.ts +0 -72
  499. package/dist/cjs/adapters/RedisAdapter.d.ts.map +0 -1
  500. package/dist/cjs/adapters/RedisAdapter.js +0 -290
  501. package/dist/cjs/adapters/RedisAdapter.js.map +0 -1
  502. package/dist/cjs/adapters/SQLiteAdapter.d.ts +0 -86
  503. package/dist/cjs/adapters/SQLiteAdapter.d.ts.map +0 -1
  504. package/dist/cjs/adapters/SQLiteAdapter.js +0 -341
  505. package/dist/cjs/adapters/SQLiteAdapter.js.map +0 -1
  506. package/dist/cjs/adapters/index.d.ts +0 -17
  507. package/dist/cjs/adapters/index.d.ts.map +0 -1
  508. package/dist/cjs/adapters/index.js +0 -21
  509. package/dist/cjs/adapters/index.js.map +0 -1
  510. package/dist/cjs/adapters/sessionRow.d.ts +0 -22
  511. package/dist/cjs/adapters/sessionRow.d.ts.map +0 -1
  512. package/dist/cjs/adapters/sessionRow.js +0 -52
  513. package/dist/cjs/adapters/sessionRow.js.map +0 -1
  514. package/dist/cjs/constants/index.d.ts +0 -1
  515. package/dist/cjs/constants/index.d.ts.map +0 -1
  516. package/dist/cjs/constants/index.js +0 -4
  517. package/dist/cjs/constants/index.js.map +0 -1
  518. package/dist/cjs/core/AutoChainExecutor.d.ts +0 -97
  519. package/dist/cjs/core/AutoChainExecutor.d.ts.map +0 -1
  520. package/dist/cjs/core/AutoChainExecutor.js +0 -288
  521. package/dist/cjs/core/AutoChainExecutor.js.map +0 -1
  522. package/dist/cjs/core/BranchEvaluator.d.ts +0 -55
  523. package/dist/cjs/core/BranchEvaluator.d.ts.map +0 -1
  524. package/dist/cjs/core/BranchEvaluator.js +0 -125
  525. package/dist/cjs/core/BranchEvaluator.js.map +0 -1
  526. package/dist/cjs/core/DirectiveChainTracker.d.ts +0 -49
  527. package/dist/cjs/core/DirectiveChainTracker.d.ts.map +0 -1
  528. package/dist/cjs/core/DirectiveChainTracker.js +0 -121
  529. package/dist/cjs/core/DirectiveChainTracker.js.map +0 -1
  530. package/dist/cjs/core/Events.d.ts +0 -26
  531. package/dist/cjs/core/Events.d.ts.map +0 -1
  532. package/dist/cjs/core/Events.js +0 -144
  533. package/dist/cjs/core/Events.js.map +0 -1
  534. package/dist/cjs/core/Flow.d.ts +0 -183
  535. package/dist/cjs/core/Flow.d.ts.map +0 -1
  536. package/dist/cjs/core/Flow.js +0 -551
  537. package/dist/cjs/core/Flow.js.map +0 -1
  538. package/dist/cjs/core/FlowRouter.d.ts +0 -183
  539. package/dist/cjs/core/FlowRouter.d.ts.map +0 -1
  540. package/dist/cjs/core/FlowRouter.js +0 -1047
  541. package/dist/cjs/core/FlowRouter.js.map +0 -1
  542. package/dist/cjs/core/PersistenceManager.d.ts +0 -114
  543. package/dist/cjs/core/PersistenceManager.d.ts.map +0 -1
  544. package/dist/cjs/core/PersistenceManager.js +0 -336
  545. package/dist/cjs/core/PersistenceManager.js.map +0 -1
  546. package/dist/cjs/core/PromptComposer.d.ts +0 -47
  547. package/dist/cjs/core/PromptComposer.d.ts.map +0 -1
  548. package/dist/cjs/core/PromptComposer.js +0 -397
  549. package/dist/cjs/core/PromptComposer.js.map +0 -1
  550. package/dist/cjs/core/PromptSectionCache.d.ts +0 -48
  551. package/dist/cjs/core/PromptSectionCache.d.ts.map +0 -1
  552. package/dist/cjs/core/PromptSectionCache.js +0 -108
  553. package/dist/cjs/core/PromptSectionCache.js.map +0 -1
  554. package/dist/cjs/core/ResponseEngine.d.ts +0 -43
  555. package/dist/cjs/core/ResponseEngine.d.ts.map +0 -1
  556. package/dist/cjs/core/ResponseEngine.js +0 -235
  557. package/dist/cjs/core/ResponseEngine.js.map +0 -1
  558. package/dist/cjs/core/ResponseGenerationError.d.ts +0 -30
  559. package/dist/cjs/core/ResponseGenerationError.d.ts.map +0 -1
  560. package/dist/cjs/core/ResponseGenerationError.js +0 -35
  561. package/dist/cjs/core/ResponseGenerationError.js.map +0 -1
  562. package/dist/cjs/core/ResponseModal.d.ts +0 -305
  563. package/dist/cjs/core/ResponseModal.d.ts.map +0 -1
  564. package/dist/cjs/core/ResponseModal.js +0 -1414
  565. package/dist/cjs/core/ResponseModal.js.map +0 -1
  566. package/dist/cjs/core/ResponsePipeline.d.ts +0 -220
  567. package/dist/cjs/core/ResponsePipeline.d.ts.map +0 -1
  568. package/dist/cjs/core/ResponsePipeline.js +0 -1040
  569. package/dist/cjs/core/ResponsePipeline.js.map +0 -1
  570. package/dist/cjs/core/SessionFinalizer.d.ts +0 -34
  571. package/dist/cjs/core/SessionFinalizer.d.ts.map +0 -1
  572. package/dist/cjs/core/SessionFinalizer.js +0 -88
  573. package/dist/cjs/core/SessionFinalizer.js.map +0 -1
  574. package/dist/cjs/core/SessionManager.d.ts +0 -112
  575. package/dist/cjs/core/SessionManager.d.ts.map +0 -1
  576. package/dist/cjs/core/SessionManager.js +0 -308
  577. package/dist/cjs/core/SessionManager.js.map +0 -1
  578. package/dist/cjs/core/SignalCoordinator.d.ts +0 -103
  579. package/dist/cjs/core/SignalCoordinator.d.ts.map +0 -1
  580. package/dist/cjs/core/SignalCoordinator.js +0 -207
  581. package/dist/cjs/core/SignalCoordinator.js.map +0 -1
  582. package/dist/cjs/core/SignalEvaluator.d.ts +0 -86
  583. package/dist/cjs/core/SignalEvaluator.d.ts.map +0 -1
  584. package/dist/cjs/core/SignalEvaluator.js +0 -319
  585. package/dist/cjs/core/SignalEvaluator.js.map +0 -1
  586. package/dist/cjs/core/SignalProcessor.d.ts +0 -152
  587. package/dist/cjs/core/SignalProcessor.d.ts.map +0 -1
  588. package/dist/cjs/core/SignalProcessor.js +0 -505
  589. package/dist/cjs/core/SignalProcessor.js.map +0 -1
  590. package/dist/cjs/core/Step.d.ts +0 -184
  591. package/dist/cjs/core/Step.d.ts.map +0 -1
  592. package/dist/cjs/core/Step.js +0 -599
  593. package/dist/cjs/core/Step.js.map +0 -1
  594. package/dist/cjs/core/StepLifecycle.d.ts +0 -43
  595. package/dist/cjs/core/StepLifecycle.d.ts.map +0 -1
  596. package/dist/cjs/core/StepLifecycle.js +0 -180
  597. package/dist/cjs/core/StepLifecycle.js.map +0 -1
  598. package/dist/cjs/core/StreamingToolExecutor.d.ts +0 -142
  599. package/dist/cjs/core/StreamingToolExecutor.d.ts.map +0 -1
  600. package/dist/cjs/core/StreamingToolExecutor.js +0 -490
  601. package/dist/cjs/core/StreamingToolExecutor.js.map +0 -1
  602. package/dist/cjs/core/ToolLoopExecutor.d.ts +0 -133
  603. package/dist/cjs/core/ToolLoopExecutor.d.ts.map +0 -1
  604. package/dist/cjs/core/ToolLoopExecutor.js +0 -568
  605. package/dist/cjs/core/ToolLoopExecutor.js.map +0 -1
  606. package/dist/cjs/core/ToolManager.d.ts +0 -250
  607. package/dist/cjs/core/ToolManager.d.ts.map +0 -1
  608. package/dist/cjs/core/ToolManager.js +0 -1104
  609. package/dist/cjs/core/ToolManager.js.map +0 -1
  610. package/dist/cjs/core/createAgent.d.ts +0 -35
  611. package/dist/cjs/core/createAgent.d.ts.map +0 -1
  612. package/dist/cjs/core/createAgent.js +0 -39
  613. package/dist/cjs/core/createAgent.js.map +0 -1
  614. package/dist/cjs/core/flow-namespace.d.ts +0 -64
  615. package/dist/cjs/core/flow-namespace.d.ts.map +0 -1
  616. package/dist/cjs/core/flow-namespace.js +0 -182
  617. package/dist/cjs/core/flow-namespace.js.map +0 -1
  618. package/dist/cjs/core/toolGates.d.ts +0 -24
  619. package/dist/cjs/core/toolGates.d.ts.map +0 -1
  620. package/dist/cjs/core/toolGates.js +0 -52
  621. package/dist/cjs/core/toolGates.js.map +0 -1
  622. package/dist/cjs/types/persistence.d.ts +0 -254
  623. package/dist/cjs/types/persistence.d.ts.map +0 -1
  624. package/dist/cjs/types/persistence.js +0 -7
  625. package/dist/cjs/types/persistence.js.map +0 -1
  626. package/dist/cjs/types/prompt-cache.d.ts +0 -15
  627. package/dist/cjs/types/prompt-cache.d.ts.map +0 -1
  628. package/dist/cjs/types/prompt-cache.js +0 -6
  629. package/dist/cjs/types/prompt-cache.js.map +0 -1
  630. package/dist/cjs/types/signals.d.ts +0 -263
  631. package/dist/cjs/types/signals.d.ts.map +0 -1
  632. package/dist/cjs/types/signals.js +0 -11
  633. package/dist/cjs/types/signals.js.map +0 -1
  634. package/dist/cjs/types/template.d.ts +0 -84
  635. package/dist/cjs/types/template.d.ts.map +0 -1
  636. package/dist/cjs/types/template.js +0 -3
  637. package/dist/cjs/types/template.js.map +0 -1
  638. package/dist/cjs/utils/condition.d.ts +0 -63
  639. package/dist/cjs/utils/condition.d.ts.map +0 -1
  640. package/dist/cjs/utils/condition.js +0 -239
  641. package/dist/cjs/utils/condition.js.map +0 -1
  642. package/dist/cjs/utils/event.d.ts +0 -6
  643. package/dist/cjs/utils/event.d.ts.map +0 -1
  644. package/dist/cjs/utils/event.js +0 -20
  645. package/dist/cjs/utils/event.js.map +0 -1
  646. package/dist/cjs/utils/id.d.ts +0 -33
  647. package/dist/cjs/utils/id.d.ts.map +0 -1
  648. package/dist/cjs/utils/id.js +0 -84
  649. package/dist/cjs/utils/id.js.map +0 -1
  650. package/dist/cjs/utils/serialize.d.ts +0 -36
  651. package/dist/cjs/utils/serialize.d.ts.map +0 -1
  652. package/dist/cjs/utils/serialize.js +0 -77
  653. package/dist/cjs/utils/serialize.js.map +0 -1
  654. package/dist/cjs/utils/session.d.ts +0 -124
  655. package/dist/cjs/utils/session.d.ts.map +0 -1
  656. package/dist/cjs/utils/session.js +0 -396
  657. package/dist/cjs/utils/session.js.map +0 -1
  658. package/dist/constants/index.d.ts +0 -2
  659. package/dist/constants/index.d.ts.map +0 -1
  660. package/dist/constants/index.js +0 -4
  661. package/dist/constants/index.js.map +0 -1
  662. package/dist/core/AutoChainExecutor.d.ts +0 -97
  663. package/dist/core/AutoChainExecutor.d.ts.map +0 -1
  664. package/dist/core/AutoChainExecutor.js +0 -284
  665. package/dist/core/AutoChainExecutor.js.map +0 -1
  666. package/dist/core/BranchEvaluator.d.ts +0 -55
  667. package/dist/core/BranchEvaluator.d.ts.map +0 -1
  668. package/dist/core/BranchEvaluator.js +0 -121
  669. package/dist/core/BranchEvaluator.js.map +0 -1
  670. package/dist/core/DirectiveChainTracker.d.ts +0 -49
  671. package/dist/core/DirectiveChainTracker.d.ts.map +0 -1
  672. package/dist/core/DirectiveChainTracker.js +0 -117
  673. package/dist/core/DirectiveChainTracker.js.map +0 -1
  674. package/dist/core/Events.d.ts +0 -26
  675. package/dist/core/Events.d.ts.map +0 -1
  676. package/dist/core/Events.js +0 -137
  677. package/dist/core/Events.js.map +0 -1
  678. package/dist/core/Flow.d.ts +0 -183
  679. package/dist/core/Flow.d.ts.map +0 -1
  680. package/dist/core/Flow.js +0 -547
  681. package/dist/core/Flow.js.map +0 -1
  682. package/dist/core/FlowRouter.d.ts +0 -183
  683. package/dist/core/FlowRouter.d.ts.map +0 -1
  684. package/dist/core/FlowRouter.js +0 -1043
  685. package/dist/core/FlowRouter.js.map +0 -1
  686. package/dist/core/PersistenceManager.d.ts +0 -114
  687. package/dist/core/PersistenceManager.d.ts.map +0 -1
  688. package/dist/core/PersistenceManager.js +0 -332
  689. package/dist/core/PersistenceManager.js.map +0 -1
  690. package/dist/core/PromptComposer.d.ts +0 -47
  691. package/dist/core/PromptComposer.d.ts.map +0 -1
  692. package/dist/core/PromptComposer.js +0 -393
  693. package/dist/core/PromptComposer.js.map +0 -1
  694. package/dist/core/PromptSectionCache.d.ts +0 -48
  695. package/dist/core/PromptSectionCache.d.ts.map +0 -1
  696. package/dist/core/PromptSectionCache.js +0 -104
  697. package/dist/core/PromptSectionCache.js.map +0 -1
  698. package/dist/core/ResponseEngine.d.ts +0 -43
  699. package/dist/core/ResponseEngine.d.ts.map +0 -1
  700. package/dist/core/ResponseEngine.js +0 -231
  701. package/dist/core/ResponseEngine.js.map +0 -1
  702. package/dist/core/ResponseGenerationError.d.ts +0 -30
  703. package/dist/core/ResponseGenerationError.d.ts.map +0 -1
  704. package/dist/core/ResponseGenerationError.js +0 -31
  705. package/dist/core/ResponseGenerationError.js.map +0 -1
  706. package/dist/core/ResponseModal.d.ts +0 -305
  707. package/dist/core/ResponseModal.d.ts.map +0 -1
  708. package/dist/core/ResponseModal.js +0 -1410
  709. package/dist/core/ResponseModal.js.map +0 -1
  710. package/dist/core/ResponsePipeline.d.ts +0 -220
  711. package/dist/core/ResponsePipeline.d.ts.map +0 -1
  712. package/dist/core/ResponsePipeline.js +0 -1035
  713. package/dist/core/ResponsePipeline.js.map +0 -1
  714. package/dist/core/SessionFinalizer.d.ts +0 -34
  715. package/dist/core/SessionFinalizer.d.ts.map +0 -1
  716. package/dist/core/SessionFinalizer.js +0 -84
  717. package/dist/core/SessionFinalizer.js.map +0 -1
  718. package/dist/core/SessionManager.d.ts +0 -112
  719. package/dist/core/SessionManager.d.ts.map +0 -1
  720. package/dist/core/SessionManager.js +0 -301
  721. package/dist/core/SessionManager.js.map +0 -1
  722. package/dist/core/SignalCoordinator.d.ts +0 -103
  723. package/dist/core/SignalCoordinator.d.ts.map +0 -1
  724. package/dist/core/SignalCoordinator.js +0 -203
  725. package/dist/core/SignalCoordinator.js.map +0 -1
  726. package/dist/core/SignalEvaluator.d.ts +0 -86
  727. package/dist/core/SignalEvaluator.d.ts.map +0 -1
  728. package/dist/core/SignalEvaluator.js +0 -312
  729. package/dist/core/SignalEvaluator.js.map +0 -1
  730. package/dist/core/SignalProcessor.d.ts +0 -152
  731. package/dist/core/SignalProcessor.d.ts.map +0 -1
  732. package/dist/core/SignalProcessor.js +0 -498
  733. package/dist/core/SignalProcessor.js.map +0 -1
  734. package/dist/core/Step.d.ts +0 -184
  735. package/dist/core/Step.d.ts.map +0 -1
  736. package/dist/core/Step.js +0 -594
  737. package/dist/core/Step.js.map +0 -1
  738. package/dist/core/StepLifecycle.d.ts +0 -43
  739. package/dist/core/StepLifecycle.d.ts.map +0 -1
  740. package/dist/core/StepLifecycle.js +0 -176
  741. package/dist/core/StepLifecycle.js.map +0 -1
  742. package/dist/core/StreamingToolExecutor.d.ts +0 -142
  743. package/dist/core/StreamingToolExecutor.d.ts.map +0 -1
  744. package/dist/core/StreamingToolExecutor.js +0 -483
  745. package/dist/core/StreamingToolExecutor.js.map +0 -1
  746. package/dist/core/ToolLoopExecutor.d.ts +0 -133
  747. package/dist/core/ToolLoopExecutor.d.ts.map +0 -1
  748. package/dist/core/ToolLoopExecutor.js +0 -564
  749. package/dist/core/ToolLoopExecutor.js.map +0 -1
  750. package/dist/core/ToolManager.d.ts +0 -250
  751. package/dist/core/ToolManager.d.ts.map +0 -1
  752. package/dist/core/ToolManager.js +0 -1098
  753. package/dist/core/ToolManager.js.map +0 -1
  754. package/dist/core/createAgent.d.ts +0 -35
  755. package/dist/core/createAgent.d.ts.map +0 -1
  756. package/dist/core/createAgent.js +0 -36
  757. package/dist/core/createAgent.js.map +0 -1
  758. package/dist/core/flow-namespace.d.ts +0 -64
  759. package/dist/core/flow-namespace.d.ts.map +0 -1
  760. package/dist/core/flow-namespace.js +0 -179
  761. package/dist/core/flow-namespace.js.map +0 -1
  762. package/dist/core/toolGates.d.ts +0 -24
  763. package/dist/core/toolGates.d.ts.map +0 -1
  764. package/dist/core/toolGates.js +0 -49
  765. package/dist/core/toolGates.js.map +0 -1
  766. package/dist/types/persistence.d.ts +0 -254
  767. package/dist/types/persistence.d.ts.map +0 -1
  768. package/dist/types/persistence.js +0 -6
  769. package/dist/types/persistence.js.map +0 -1
  770. package/dist/types/prompt-cache.d.ts +0 -15
  771. package/dist/types/prompt-cache.d.ts.map +0 -1
  772. package/dist/types/prompt-cache.js +0 -5
  773. package/dist/types/prompt-cache.js.map +0 -1
  774. package/dist/types/signals.d.ts +0 -263
  775. package/dist/types/signals.d.ts.map +0 -1
  776. package/dist/types/signals.js +0 -10
  777. package/dist/types/signals.js.map +0 -1
  778. package/dist/types/template.d.ts +0 -84
  779. package/dist/types/template.d.ts.map +0 -1
  780. package/dist/types/template.js +0 -2
  781. package/dist/types/template.js.map +0 -1
  782. package/dist/utils/condition.d.ts +0 -63
  783. package/dist/utils/condition.d.ts.map +0 -1
  784. package/dist/utils/condition.js +0 -230
  785. package/dist/utils/condition.js.map +0 -1
  786. package/dist/utils/event.d.ts +0 -6
  787. package/dist/utils/event.d.ts.map +0 -1
  788. package/dist/utils/event.js +0 -17
  789. package/dist/utils/event.js.map +0 -1
  790. package/dist/utils/id.d.ts +0 -33
  791. package/dist/utils/id.d.ts.map +0 -1
  792. package/dist/utils/id.js +0 -77
  793. package/dist/utils/id.js.map +0 -1
  794. package/dist/utils/serialize.d.ts +0 -36
  795. package/dist/utils/serialize.d.ts.map +0 -1
  796. package/dist/utils/serialize.js +0 -72
  797. package/dist/utils/serialize.js.map +0 -1
  798. package/dist/utils/session.d.ts +0 -124
  799. package/dist/utils/session.d.ts.map +0 -1
  800. package/dist/utils/session.js +0 -379
  801. package/dist/utils/session.js.map +0 -1
  802. package/docs/concepts/directives.md +0 -369
  803. package/docs/reference/adapters.md +0 -543
  804. package/docs/reference/create-agent.md +0 -216
  805. package/docs/reference/directive.md +0 -242
  806. package/docs/reference/signals.md +0 -368
  807. package/examples/02-data-extraction.ts +0 -90
  808. package/examples/05-branching.ts +0 -140
  809. package/examples/06-flow-control.ts +0 -103
  810. package/examples/08-persistence.ts +0 -98
  811. package/examples/09-signals.ts +0 -144
  812. package/src/adapters/MemoryAdapter.ts +0 -281
  813. package/src/adapters/MongoAdapter.ts +0 -341
  814. package/src/adapters/OpenSearchAdapter.ts +0 -693
  815. package/src/adapters/PostgreSQLAdapter.ts +0 -487
  816. package/src/adapters/PrismaAdapter.ts +0 -617
  817. package/src/adapters/RedisAdapter.ts +0 -439
  818. package/src/adapters/SQLiteAdapter.ts +0 -496
  819. package/src/adapters/index.ts +0 -43
  820. package/src/adapters/sessionRow.ts +0 -57
  821. package/src/constants/index.ts +0 -2
  822. package/src/core/AutoChainExecutor.ts +0 -397
  823. package/src/core/BranchEvaluator.ts +0 -161
  824. package/src/core/DirectiveChainTracker.ts +0 -144
  825. package/src/core/Events.ts +0 -164
  826. package/src/core/Flow.ts +0 -665
  827. package/src/core/FlowRouter.ts +0 -1540
  828. package/src/core/PersistenceManager.ts +0 -446
  829. package/src/core/PromptComposer.ts +0 -448
  830. package/src/core/PromptSectionCache.ts +0 -125
  831. package/src/core/ResponseEngine.ts +0 -338
  832. package/src/core/ResponseGenerationError.ts +0 -53
  833. package/src/core/ResponseModal.ts +0 -1902
  834. package/src/core/ResponsePipeline.ts +0 -1404
  835. package/src/core/SessionFinalizer.ts +0 -108
  836. package/src/core/SessionManager.ts +0 -372
  837. package/src/core/SignalCoordinator.ts +0 -263
  838. package/src/core/SignalEvaluator.ts +0 -404
  839. package/src/core/SignalProcessor.ts +0 -663
  840. package/src/core/Step.ts +0 -782
  841. package/src/core/StepLifecycle.ts +0 -242
  842. package/src/core/StreamingToolExecutor.ts +0 -609
  843. package/src/core/ToolLoopExecutor.ts +0 -749
  844. package/src/core/ToolManager.ts +0 -1379
  845. package/src/core/createAgent.ts +0 -40
  846. package/src/core/flow-namespace.ts +0 -227
  847. package/src/core/toolGates.ts +0 -72
  848. package/src/types/persistence.ts +0 -303
  849. package/src/types/prompt-cache.ts +0 -17
  850. package/src/types/signals.ts +0 -338
  851. package/src/types/template.ts +0 -98
  852. package/src/utils/condition.ts +0 -296
  853. package/src/utils/event.ts +0 -16
  854. package/src/utils/id.ts +0 -91
  855. package/src/utils/serialize.ts +0 -86
  856. package/src/utils/session.ts +0 -501
@@ -1,170 +1,75 @@
1
1
  ---
2
2
  title: "Compaction"
3
- description: "Keep prompts within token limits across long sessions by layering tool-result budgeting, micro-compaction, and LLM summarization in cost order."
3
+ description: "Keep a long history inside the model's window: three layers in cost order, applied once per turn to what both calls see."
4
4
  type: guide
5
- order: 8
5
+ order: 10
6
6
  ---
7
7
 
8
8
  # Compaction
9
9
 
10
- > **Where this is introduced:** [Errors](./error-handling.md)
11
-
12
- Long-running sessions accumulate history. Tool calls return verbose
13
- JSON, turns pile up, and at some point the next provider call runs
14
- out of token budget. Compaction is the framework's answer: a layered
15
- strategy that trims and summarizes `session.history` before each turn
16
- so the prompt fits without dropping anything load-bearing. Layers run
17
- in cost order — character-level truncation first, an LLM summarization
18
- call only when nothing cheaper closes the gap.
19
-
20
- This guide is task-shaped: enable compaction, choose a budget, and
21
- understand which layer fires when.
22
-
23
- ## Enable compaction
24
-
25
- Compaction is opt-in. Set `AgentOptions.compaction` and the agent
26
- validates the config at construction time, then runs the engine
27
- deterministically at end-of-turn finalize on every `respond()` /
28
- `chat()` / `stream()` call — and additionally whenever a message is
29
- appended via `session.addMessage()`. Since v2.4 the finalize run is
30
- guaranteed, so respond-only integrations that never call
31
- `addMessage()` get bounded history too (previously compaction only
32
- ran inside `addMessage()`).
33
-
34
- ```typescript
35
- import { createAgent, GeminiProvider } from "@falai/agent";
36
-
37
- const agent = createAgent({
38
- name: "Concierge",
39
- provider: new GeminiProvider({ apiKey: process.env.GEMINI_API_KEY! }),
40
- schema: { /* ... */ },
41
- flows: [/* ... */],
42
-
43
- compaction: {
44
- maxTokens: 32_000, // total token budget for the prompt
45
- compactionThreshold: 0.8, // fire when history hits 80% of maxTokens (default)
46
- preserveRecentCount: 4, // never touch the last 4 history items (default)
47
- maxToolResultChars: 5_000, // global cap per tool message (default)
48
- // enabled: true, // default true when `compaction` is provided
49
- },
10
+ A long conversation grows a long history. `compaction` trims the copy the model reads once the history passes a token budget you set.
11
+
12
+ ```ts
13
+ import { falai, GeminiProvider } from "@falai/agent";
14
+
15
+ const f = falai().fields({});
16
+
17
+ const agent = f.agent({
18
+ name: "Ana",
19
+ provider: new GeminiProvider({ apiKey: process.env.GEMINI_API_KEY ?? "", model: "gemini-2.5-flash" }),
20
+ idle: { prompt: "Responda pela empresa." },
21
+ compaction: { maxTokens: 2000 },
50
22
  });
51
- ```
52
23
 
53
- The four knobs map onto the
54
- [`AgentCompactionConfig`](../reference/create-agent.md) interface.
55
- `maxTokens` is the only required field; the rest fall back to the
56
- defaults shown above. The agent calls `validateOptions` synchronously
57
- at construction, so misvalued thresholds (`compactionThreshold` outside
58
- `[0.5, 0.95]`, `preserveRecentCount < 2`, `maxToolResultChars <= 0`)
59
- throw immediately rather than silently no-oping at runtime.
60
-
61
- A second knob lives on every `Tool`: `maxResultSizeChars`. That value
62
- is enforced by the tool executor the moment a tool returns, before the
63
- result enters history at all. It and the agent-level `maxToolResultChars`
64
- work together — per-tool first, global later.
65
-
66
- ## How a turn checks the budget
67
-
68
- At the end of every turn (and on each `session.addMessage()`), the
69
- engine runs
70
- `CompactionEngine.checkAndCompact(session.history, options)`. The
71
- compacted history is what gets persisted and carried into the next
72
- turn's prompt. The engine estimates the current token count using a
73
- character-based heuristic (~4 characters per token), compares against
74
- `maxTokens * compactionThreshold`, and applies the cheapest layer that
75
- brings history below the threshold. If even the most expensive layer
76
- cannot, an aggressive truncation fallback removes the oldest items
77
- until the budget fits.
78
-
79
- `preserveRecentCount` is honored by every layer. The trailing N items
80
- of `session.history` are never modified, summarized, or removed —
81
- recent turns are the one piece of context the engine refuses to spend.
82
-
83
- ## Layer 1 — tool-result budgeting
84
-
85
- `tool_result_budget` is the cheapest layer. It walks history, finds
86
- items with `role: "tool"`, and truncates any whose stringified content
87
- exceeds `maxToolResultChars`. Truncated items get a deterministic
88
- notice appended:
89
-
90
- ```text
91
- [Truncated: 12834 chars total, showing first 5000]
24
+ const history = Array.from({ length: 400 }, (_, i) => ({ role: "user" as const, content: `mensagem antiga número ${i}` }));
25
+ const r = await agent.turn({ sessionId: "demo", history, message: "oi" });
26
+ console.log(r.llmCalls); // 2: one call to summarize the old messages, one to reply
92
27
  ```
93
28
 
94
- Character-level and synchronous — no LLM call, no network. It fires
95
- whenever history crosses the threshold and at least one tool message
96
- is oversized. For agents that orchestrate verbose APIs (search, SQL,
97
- web fetches) this layer alone usually keeps the prompt in budget.
98
-
99
- The per-tool counterpart is `Tool.maxResultSizeChars`. Set it on
100
- high-volume tools to truncate at execution time, before the result
101
- ever lands in history. Combine the two: a tight per-tool cap on a
102
- known-chatty tool, plus a global ceiling at the agent level.
103
-
104
- ## Layer 2 — micro-compaction
105
-
106
- If `tool_result_budget` is not enough, `micro_compact` runs over the
107
- already-budgeted history. It compresses verbose tool outputs inline
108
- by collapsing whitespace runs to a single space and trimming the
109
- edges. Tool results are the only target — user, assistant, and system
110
- messages pass through unchanged.
111
-
112
- Still LLM-free and deterministic. Most effective on tool results that
113
- contain pretty-printed JSON or multiline text where formatting is
114
- whitespace-heavy. The recent-N tail (`preserveRecentCount`) is
115
- preserved verbatim during this pass; the cutoff is `history.length -
116
- preserveRecentCount`, and only items before that cutoff are
117
- compressed.
118
-
119
- ## Layer 3 — LLM summarization
120
-
121
- When neither character-level layer brings the prompt under threshold,
122
- `auto_compact` dispatches a single `provider.generateMessage` call
123
- asking the agent's own LLM to summarize the older portion. The result
124
- becomes one synthetic system message:
125
-
126
- ```text
127
- [Conversation Summary]
128
- <summary text from the provider>
129
- ```
29
+ With `maxTokens: 2000` the turn compacts when the history is estimated at 1600 tokens or more (80% of 2000). These 400 short messages estimate at close to 3000, so the oldest ones are summarized before the reply is phrased, and that summary is one model call. Below the threshold nothing happens and nothing is spent.
30
+
31
+ ## The option
32
+
33
+ `AgentCompactionConfig`, from `src/types/agent.ts`; the defaults are applied in `src/core/Agent.ts`:
34
+
35
+ | Field | Meaning | Default |
36
+ |---|---|---|
37
+ | `maxTokens` | the token budget for the history | required |
38
+ | `compactionThreshold` | compact when the estimate reaches this share of `maxTokens`; between 0.5 and 0.95 | `0.8` |
39
+ | `preserveRecentCount` | the newest messages are never changed or removed; at least 2 | `4` |
40
+ | `maxToolResultChars` | characters kept of a tool result before it is cut; more than 0 | `5000` |
41
+ | `enabled` | `false` turns compaction off without removing the config | `true` when the config is present |
42
+
43
+ A value out of range throws at construction, as a plain `Error`: `compactionThreshold must be between 0.5 and 0.95, got 2`, `preserveRecentCount must be >= 2, got 1`, `maxToolResultChars must be > 0, got 0`.
44
+
45
+ ## When it runs
46
+
47
+ Once per turn, before the understand call and before the speak call, so both read the same trimmed history. The framework reads `input.history`, or `session.history` when the host passes none, and only acts when there is one. The trimmed copy lives for that turn: your stored history is never rewritten by the framework. The next turn compacts again from whatever you pass.
48
+
49
+ Tokens are estimated, not counted: the characters of every message's content, plus its `name` when it has one (a tool result always does), plus 4 per message for its role, divided by 4 and rounded up. The estimate is deterministic, so the same history compacts the same way every time.
50
+
51
+ ## The three layers, cheapest first
52
+
53
+ The engine tries each layer in order and stops at the first one that brings the estimate under the threshold. Under the threshold it runs none of them and reports `none`. The newest `preserveRecentCount` messages stay untouched through all three.
54
+
55
+ | Strategy | What it does | Model calls |
56
+ |---|---|---|
57
+ | `tool_result_budget` | cuts every tool result longer than `maxToolResultChars`, appending `[Truncated: N chars total, showing first M]` | 0 |
58
+ | `micro_compact` | collapses runs of whitespace inside older tool results | 0 |
59
+ | `auto_compact` | asks the model to summarize every message older than the preserved window, and replaces them with one `system` item that starts with `[Conversation Summary]` | 1 |
60
+
61
+ The first two layers touch tool results only, because that is where a history gets long without saying much. A conversation of plain user and assistant text goes straight to `auto_compact` when it passes the threshold.
62
+
63
+ `auto_compact` is one model call and adds one to `result.llmCalls`. It is the only call in a turn that is neither understand nor speak; the summary prompt is sent with no `schemaName`. When that call fails, the engine drops the oldest messages instead until the rest fit, without another call; the turn goes on and the failed call still counts.
64
+
65
+ The preserved window is a target, not a hard cut: its left edge moves left when it would otherwise open on a tool result whose calling assistant message was cut away, because providers reject such a history at the next request.
66
+
67
+ ## Turning it off
68
+
69
+ Leave `compaction` out, or set `enabled: false`. Either way the model sees the full history you pass, and the `context` kind of `ProviderError` is what tells you the window overflowed; see [error handling](./error-handling.md).
70
+
71
+ ## What compaction is not
72
+
73
+ It is not memory. The collected fields live in `session.data` and are never compacted; the model is told what is already known on every call a talk step makes (the idle speaker's prompt does not restate them). It is not persistence: what you store is up to you, and the summary the engine writes is not kept anywhere unless you keep the trimmed history yourself.
130
74
 
131
- That synthetic item replaces every history item before the
132
- `preserveRecentCount` tail. The recent tail is appended unchanged. If
133
- the provider call fails — quota, network, any caught exception — the
134
- engine falls back to `aggressiveTruncate`: walk older messages newest
135
- to oldest, keep as many as fit under `maxTokens * compactionThreshold`,
136
- drop the rest. The strategy field on the result still reads
137
- `"auto_compact"` so callers can see that summarization was attempted.
138
-
139
- This layer costs a real provider round-trip. It only fires when
140
- character-level layers cannot close the gap — in practice, sessions
141
- with hundreds of long turns or tools that return narrative prose
142
- rather than structured data.
143
-
144
- ## When each layer fires
145
-
146
- The `compactionThreshold` ratio is the gate for all three layers. Below
147
- threshold, `checkAndCompact` returns `strategy: "none"` and history
148
- passes through untouched. At or above threshold, the engine attempts
149
- each layer in order and stops as soon as the result drops below the
150
- threshold:
151
-
152
- | Estimated tokens | Strategy that fires |
153
- |------------------|---------------------|
154
- | `< maxTokens * compactionThreshold` | `none` |
155
- | `≥ threshold`, oversized tool messages exist | `tool_result_budget` |
156
- | `≥ threshold` after budgeting | `micro_compact` |
157
- | `≥ threshold` after micro-compaction | `auto_compact` (LLM call) |
158
- | LLM call failed | `auto_compact` (truncation fallback) |
159
-
160
- The result's `messagesCompacted` count and optional `summary` field
161
- are logged at `info` level so production logs show which layer fired
162
- on which turn.
163
-
164
- A practical defaults sketch: set `maxTokens` to ~80% of the model's
165
- context window, leave `compactionThreshold` at the 0.8 default, and
166
- put a tight per-tool `maxResultSizeChars` on any tool that talks to
167
- a search API or a database. Pick the budget, set the caps, let the
168
- layers absorb the noise.
169
-
170
- **Next:** [Architecture](../concepts/architecture.md)
75
+ See [the pipeline](../concepts/pipeline.md) for where the compaction step sits among the eight phases.
@@ -1,181 +1,217 @@
1
1
  ---
2
- title: "When and if"
3
- description: "Pick between AI-evaluated `when` strings and code-evaluated `if` predicates, and combine them to save tokens."
2
+ title: "Conditions"
3
+ description: "if is a question your code answers for free; when is a question the model answers inside a model call."
4
4
  type: guide
5
- order: 1
5
+ order: 2
6
6
  ---
7
7
 
8
- # When and if
8
+ # Conditions
9
9
 
10
- Conditions decide whether a flow activates, a step runs, an instruction applies, or a branch fires. v2 splits them into two distinct fields with different evaluators:
10
+ Two words, two judges. `if` is a question your code answers. `when` is a question the model answers from what the customer just said.
11
11
 
12
- - `when` — strings the LLM evaluates against intent and the conversation. Costs tokens.
13
- - `if` — TypeScript predicates the engine evaluates locally. Free.
12
+ The smallest condition is an `if` step:
14
13
 
15
- The split is the same everywhere: `Flow`, `Step`, `Instruction`, and `BranchEntry` all expose `when?` and `if?` with identical semantics. This guide shows how to pick between them, how arrays combine, and what happens when both are set. If you are migrating from v1, the [v1 → v2 migration guide](../migration/v1-to-v2.md) covers the renamed condition fields.
14
+ ```ts
15
+ import { falai, GeminiProvider } from "@falai/agent";
16
16
 
17
- ## Pick the right field
17
+ interface Ctx {
18
+ lead: { tags: string[] };
19
+ }
18
20
 
19
- Reach for `if` first. It's free, deterministic, and reads clearly in code review.
21
+ const f = falai<Ctx>().fields({});
22
+
23
+ const agent = f.agent({
24
+ name: "Ana",
25
+ // Set GEMINI_API_KEY in your environment before running this.
26
+ provider: new GeminiProvider({ apiKey: process.env.GEMINI_API_KEY ?? "", model: "gemini-2.5-flash" }),
27
+ flows: [
28
+ f.flow({
29
+ id: "boas-vindas",
30
+ name: "Boas-vindas",
31
+ steps: [
32
+ { id: "vip", if: ({ context }) => context.lead.tags.includes("vip"), then: "tapete", else: "oi" },
33
+ { id: "tapete", say: "Bem-vindo de volta. Já avisei seu gerente de conta.", then: "end" },
34
+ { id: "oi", say: "Oi. Posso ajudar em algo?" },
35
+ ],
36
+ }),
37
+ ],
38
+ });
20
39
 
21
- | Question to answer | Use |
22
- | --------------------------------------------------------------- | -------- |
23
- | Is this user authenticated? Is `data.tier === 'pro'`? | `if` |
24
- | Is the feature flag on? Is the order older than 90 days? | `if` |
25
- | Did the user ask about pricing? Are they expressing frustration? | `when` |
26
- | Is the user describing a refund scenario in their own words? | `when` |
40
+ const r = await agent.turn({ sessionId: "s1", context: { lead: { tags: ["vip"] } }, start: { flow: "boas-vindas", key: "signup:1" } });
41
+ console.log(r.messages[0]?.text); // "Bem-vindo de volta. Já avisei seu gerente de conta."
42
+ console.log(r.llmCalls); // 0
43
+ ```
27
44
 
28
- If the answer lives in `data`, `context`, or `session`, it's `if`. If the answer requires reading the user's intent from natural language, it's `when`.
45
+ Code answered the question, so the turn cost no model call.
29
46
 
30
- ## `when` — AI strings
47
+ ## `if`: code, free
31
48
 
32
- `when` accepts a string or an array of strings. Functions are rejected at construction time with `FlowConfigurationError`.
49
+ An `if` is a `Pred`: a function that returns a boolean, or the same thing written as JSON (a `ConditionSpec`). Both see the same context.
33
50
 
34
- ```typescript
35
- {
36
- title: "Refund",
37
- when: "the user is requesting a refund",
38
- }
39
- ```
51
+ | `PredCtx` field | What it is |
52
+ |---|---|
53
+ | `context` | the host context passed to this `turn()` |
54
+ | `data` | the collected fields so far, `Partial<D>` |
55
+ | `input` | the run's input: an event payload, a start input, a mention's extract; `unknown` |
56
+ | `run` | the run being judged; absent only for an agent-level instruction while the idle speaker answers |
57
+ | `silenced` | the host's reason the assistant cannot speak now; absent when it can |
58
+ | `now` | the agent's clock |
40
59
 
41
- Multiple non-`!` strings combine with **OR** semantics — any clause may pass for the condition to match. Use the array form for alternative natural-language expressions of the same intent:
60
+ ### As a function
42
61
 
43
- ```typescript
44
- {
45
- title: "Address",
46
- when: [
47
- "the user asked about the address",
48
- "the user asked where we are located",
49
- ],
50
- }
62
+ ```ts fragment
63
+ if: ({ context, data, now }) => context.lead.owner === "ai" && data.nome !== undefined && now.getHours() < 18
51
64
  ```
52
65
 
53
- Prefix a string with `!` to make it an exclusion. Exclusions also combine with OR semantics: if any exclusion matches, the condition is inhibited. A negative-only `when` means "active unless this exclusion matches."
66
+ A function is the most direct form. It cannot be stored: `toSpec` refuses a flow that carries one with a `FlowConfigurationError`. For a flow that lives in a database, write the JSON form.
54
67
 
55
- ```typescript
56
- {
57
- title: "Checkout",
58
- when: [
59
- "the user is ready to buy",
60
- "!the user is asking for support",
61
- ],
62
- }
63
- ```
68
+ ### As JSON
64
69
 
65
- The strings are sent to the LLM as part of the routing or activation prompt. For instructions, the string is appended to the instruction bullet so the response model can apply the instruction conditionally. Keep conditions short, intent-shaped, and free of code-style boolean expressions — `"the user wants to cancel"` lands; `"data.cancelRequested === true"` does not.
70
+ A `ConditionSpec` is an object whose keys are conditions. Every listed key must hold. Three are built in:
66
71
 
67
- ## `if` — code predicates
72
+ | Key | Holds when | Example |
73
+ |---|---|---|
74
+ | `equals` | each listed field equals the given value | `{ equals: { confirmado: true } }` |
75
+ | `known` | each listed field has a value (not `undefined`, `null` or `''`) | `{ known: ['nome', 'empresa'] }` |
76
+ | `silenced` | `true`: the host said the assistant cannot speak; `false`: it can | `{ silenced: true }` |
68
77
 
69
- `if` accepts a function or an array of functions. Each predicate receives a `TemplateContext`-shaped argument (`{ context, data, session, history, helpers }`) and returns `boolean | Promise<boolean>`.
78
+ Any other key names one of the agent's `conditions` and carries its argument:
70
79
 
71
- ```typescript
72
- {
73
- title: "Enterprise",
74
- if: ({ context }) => context.tier === "enterprise",
75
- }
76
- ```
80
+ ```ts
81
+ import { falai, GeminiProvider } from "@falai/agent";
77
82
 
78
- Arrays combine with **AND** semantics — every predicate must return truthy.
83
+ interface Ctx {
84
+ lead: { tags: string[] };
85
+ }
79
86
 
80
- ```typescript
81
- {
82
- if: [
83
- ({ context }) => context.authenticated,
84
- ({ data }) => (data.cartTotal ?? 0) > 100,
87
+ const f = falai<Ctx>().fields({
88
+ nome: { type: "string", ask: "Pergunte o nome." },
89
+ confirmado: { type: "boolean", ask: "Resuma o que anotou e pergunte se está certo." },
90
+ });
91
+
92
+ const agent = f.agent({
93
+ name: "Ana",
94
+ provider: new GeminiProvider({ apiKey: process.env.GEMINI_API_KEY ?? "", model: "gemini-2.5-flash" }),
95
+ conditions: {
96
+ // Used by name in JSON: { tagsAny: ["vip", "parceiro"] }. The argument comes from JSON unchecked, so test it.
97
+ tagsAny: f.condition((ctx, tags: string[]) => Array.isArray(tags) && tags.some((t) => ctx.context.lead.tags.includes(t))),
98
+ },
99
+ flows: [
100
+ f.flow({
101
+ id: "fechamento",
102
+ name: "Fechamento",
103
+ on: [{ message: ["quer fechar o contrato"], if: { tagsAny: ["vip", "parceiro"] } }],
104
+ steps: [
105
+ { id: "quem", collect: ["nome"] },
106
+ { id: "confirma", collect: ["confirmado"] },
107
+ { id: "ok", if: { equals: { confirmado: true } }, else: { step: "quem", clear: ["confirmado", "nome"] } },
108
+ { id: "tchau", prompt: "Agradeça e diga que um vendedor continua daqui." },
109
+ ],
110
+ }),
85
111
  ],
86
- }
112
+ });
87
113
  ```
88
114
 
89
- Predicates that throw or reject are caught, logged, and treated as `false` for that evaluation. They never corrupt the session — the worst case is the condition fails to match.
115
+ `f.condition` gives the check its argument type; the JSON side stays a plain object. When the agent is built, `validateFlow` checks every JSON condition and throws `FlowConfigurationError` on the first problem:
90
116
 
91
- ### What's in the predicate context
117
+ - `equals` must be an object; each key must be a field; each value must have the field's exact type (`"3"` is not a number, nothing is coerced) and be in its `enum` unless it is a template such as `"{{context.plano}}"`.
118
+ - `known` must be a list of field slugs.
119
+ - `silenced` must be a boolean.
120
+ - Any other key must be a registered condition, or the error names it: `unknown condition "tagsAny"`.
92
121
 
93
- Predicates receive a context object with the same shape used everywhere templates and conditions evaluate. The fields you'll reach for most:
122
+ Keys with an `undefined` value are skipped. An empty object `{}` always holds.
94
123
 
95
- | Field | Type | Notes |
96
- | ---------- | ------------------------ | ---------------------------------------------------------------- |
97
- | `data` | `Partial<TData>` | Collected schema fields. Null-check anything not in `requires`. |
98
- | `context` | `TContext` | Agent-level ambient context (user, env, services). |
99
- | `session` | `SessionState<TData>` | Current flow id, current step id, full history. |
100
- | `history` | `Event[]` | Read-only conversation history. |
124
+ ## `when`: judged by the model
101
125
 
102
- Predicates can be `async`. Awaiting a database lookup or feature-flag service is supported, but remember: every predicate runs every time its host primitive is evaluated. Keep them cheap, or memoize the work in a hook upstream.
126
+ A `when` is a sentence about the customer's latest message. It appears in two places:
103
127
 
104
- ```typescript
105
- {
106
- if: async ({ context, data }) =>
107
- await context.flags.isEnabled("v2_pricing", data.userId),
108
- }
109
- ```
128
+ - **A branch on a talk step.** The understand call answers it true or false while the step is asking. The first branch that holds moves the run. See [Branching](branching.md).
129
+ - **An instruction.** The sentence is rendered into the speak prompt for the model to apply itself: "when the customer is upset, apologise once". It is guidance, not a gate; code never evaluates it.
110
130
 
111
- ## When both are set
131
+ ```ts
132
+ import { falai } from "@falai/agent";
112
133
 
113
- Setting both `when` and `if` on the same primitive runs `if` **first**, free. `when` is only sent to the LLM when every `if` predicate passes. The order is deliberate: predicates short-circuit the LLM call when the answer is already disqualified.
134
+ const f = falai().fields({
135
+ pedido: { type: "string", ask: "Pergunte o número do pedido." },
136
+ });
114
137
 
115
- ```typescript
116
- {
117
- title: "US Pricing",
118
- if: ({ context }) => context.country === "US" && context.flags.usPricing,
119
- when: "the user is asking about pricing",
120
- }
138
+ const suporte = f.flow({
139
+ id: "suporte",
140
+ name: "Suporte a pedidos",
141
+ on: [{ message: ["problema com um pedido"] }],
142
+ instructions: [{ kind: "must", when: "o cliente está irritado", prompt: "Peça desculpa uma vez e vá direto à solução." }],
143
+ steps: [
144
+ {
145
+ id: "dados",
146
+ collect: ["pedido"],
147
+ branches: [{ when: "a pessoa pede para falar com um humano", then: { flow: "humano" } }],
148
+ },
149
+ { id: "resolve", prompt: "Explique o próximo passo para o pedido {{data.pedido}}." },
150
+ ],
151
+ });
121
152
  ```
122
153
 
123
- In the snippet above, non-US users skip the AI evaluation entirely. The `when` string costs tokens only when the predicate already says "this user is in scope, ask the AI whether they're asking about pricing."
154
+ What a `when` costs: the understand call happens at most once per turn, and every `when` branch rides in it. When that call would not happen otherwise (a single message flow, nothing to extract, no mention flows), a `when` branch alone makes the turn spend it. An instruction's `when` costs nothing extra: it is text inside the speak prompt.
124
155
 
125
- This pattern is the recommended shape any time a condition has both a cheap precondition and an intent classification. Lead with `if` to gate. Use `when` to interpret.
156
+ A `when` only makes sense where there is fresh customer text. Branches on a `wait` step are judged when the customer replies, by code only: an `if` branch there works, a `when` branch is listed by the type but never asked.
126
157
 
127
- ## Where the split lives
158
+ ## Where each is allowed
128
159
 
129
- The same `when` / `if` shape attaches to four primitives. Semantics are identical in each location:
160
+ | Place | `if` | `when` |
161
+ |---|---|---|
162
+ | Trigger (`on[].if`) | yes: the run starts only if it holds; also the flow's default `while` | no: the phrases in `message` and `mention` are the model's part |
163
+ | Flow `while` | yes: re-checked whenever the run moves | no |
164
+ | Branch on a talk step | yes, code | yes, the understand call |
165
+ | Branch on a `wait` step | yes, when the customer replies | never judged |
166
+ | `if` step | yes, required | no |
167
+ | Instruction (agent, flow or step) | yes: the instruction is dropped from the prompt when it fails | yes: rendered into the prompt |
130
168
 
131
- | Primitive | Field path | What it gates |
132
- | --------------- | ----------------------- | -------------------------------------------------- |
133
- | Flow | `FlowOptions.when/if` | Whether the router selects this flow this turn |
134
- | Step | `StepOptions.when/if` | Whether the step is reachable in the current flow |
135
- | Instruction | `Instruction.when/if` | Whether the instruction applies to the response |
136
- | BranchEntry | `BranchEntry.when/if` | Whether this branch entry matches inside `step.branches` |
169
+ ## Which one to write
137
170
 
138
- ```typescript
139
- // Flow scope — gate flow selection
140
- { title: "Refund", when: "user wants a refund", if: ({ context }) => context.authenticated }
171
+ Ask where the answer already is.
141
172
 
142
- // Step scope — gate step reachability
143
- { id: "verify_payment", when: "user is confirming the order", if: ({ data }) => !!data.cardToken }
173
+ - In `context`, `data` or the input: `if`. It is free and deterministic.
174
+ - In what the customer just said, and you need code to act on it: a `when` branch.
175
+ - In what the customer just said, and it is a yes or no you will keep: collect a boolean field with `extract: 'asked'` and gate on it with an `if` step. The speak envelope of that step fills the field; there is no extra call. The confirmation pattern in [Collection](../concepts/collection.md) is this.
176
+ - Both: a `when` branch on the step and an `if` on the flow. Each is judged by its own judge.
144
177
 
145
- // Instruction scope — render only when relevant
146
- { kind: "should", when: "user mentions a discount code", prompt: "Validate the code before applying it." }
178
+ ## JSON flows
147
179
 
148
- // Branch scope — pick a successor
149
- branches: [
150
- { if: ({ data }) => data.tier === "enterprise", when: "user wants pricing", then: "enterprise_pricing" },
151
- { then: "default_pricing" },
152
- ]
153
- ```
154
-
155
- ## `step.skip` is the OR companion
180
+ A stored flow carries only the JSON form. `f.fromSpec` types it, and the agent checks the names when it is built:
156
181
 
157
- One adjacent field rounds out the picture. `step.skip` is **function-only** with **OR** semantics — when any predicate returns truthy, the step is bypassed. Use it for "skip when this field already exists" cases:
182
+ ```ts
183
+ import { falai, GeminiProvider } from "@falai/agent";
184
+ import type { FlowSpec } from "@falai/agent";
158
185
 
159
- ```typescript
160
- {
161
- id: "ask_email",
162
- collect: ["email"],
163
- skip: ({ data }) => !!data.email,
186
+ interface Ctx {
187
+ lead: { stageId: string };
164
188
  }
165
- ```
166
189
 
167
- `skip` does not accept strings. There is no AI counterpart — skipping is a code decision by design.
168
-
169
- ## Quick reference
190
+ const f = falai<Ctx>().fields({});
191
+
192
+ const spec: FlowSpec = {
193
+ id: "proposta",
194
+ name: "Acompanhar proposta",
195
+ on: [{ event: "stage_entered", after: "1h", if: { inStage: "proposta" } }],
196
+ while: { inStage: "proposta" },
197
+ steps: [{ id: "p", kind: "prompt", prompt: "Pergunte se a proposta chegou bem e se há dúvidas." }],
198
+ };
199
+
200
+ const agent = f.agent({
201
+ name: "Ana",
202
+ provider: new GeminiProvider({ apiKey: process.env.GEMINI_API_KEY ?? "", model: "gemini-2.5-flash" }),
203
+ events: { stage_entered: f.event<{ stageId: string }>() },
204
+ conditions: {
205
+ inStage: f.condition((ctx, stageId: string) => ctx.context.lead.stageId === stageId),
206
+ },
207
+ flows: [f.fromSpec(spec)],
208
+ });
209
+ ```
170
210
 
171
- A short checklist before shipping a condition:
211
+ Remove `inStage` from `conditions` and `f.agent` throws `[FlowConfigurationError] flow "proposta": unknown condition "inStage" in while. Register it in conditions or use equals, known, silenced.` The flow's `while` is checked before its triggers, so that is the line you see first. More in [Flows from JSON](flows-from-json.md).
172
212
 
173
- - Does it read a field, flag, or context value? Use `if`.
174
- - Does it interpret natural language? Use `when`.
175
- - Multiple natural-language alternatives where any may match? Put them in `when` — non-`!` entries use OR.
176
- - Need an AI-evaluated exclusion? Prefix that `when` entry with `!`.
177
- - Multiple code predicates that must all pass? Put them in `if` — arrays use AND.
178
- - Need to skip when a value is already collected? `step.skip` (OR semantics).
179
- - Both fields set? `if` runs first, free; `when` only fires if `if` passes.
213
+ ## Read next
180
214
 
181
- **Next:** [Branching](./branching.md)
215
+ - [Branching](branching.md): `when` and `if` branches, the `if` step, `clear`.
216
+ - [Flow control](flow-control.md): `while` and the premise check.
217
+ - [Actions, events and conditions reference](../reference/actions-events-conditions.md): `Condition`, `ConditionSpec`, `PredCtx`.