@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
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Token counts, added up across a turn.
3
+ *
4
+ * Providers report per call; a text turn spends two, plus one per tool round,
5
+ * plus one if the history was compacted. The host bills the conversation, so
6
+ * the framework hands it one figure beside `llmCalls`.
7
+ */
8
+ import type { TokenUsage } from "../types/ai.js";
9
+ interface Counted {
10
+ promptTokens?: number;
11
+ completionTokens?: number;
12
+ cachedInputTokens?: number;
13
+ }
14
+ /** What a call's metadata says it cost, or nothing when the provider said nothing. */
15
+ export declare function readUsage(metadata: Counted | undefined): TokenUsage | undefined;
16
+ /** Adds two tallies. Nobody counting is not the same as counting zero. */
17
+ export declare function addUsage(a: TokenUsage | undefined, b: TokenUsage | undefined): TokenUsage | undefined;
18
+ export {};
19
+ //# sourceMappingURL=usage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usage.d.ts","sourceRoot":"","sources":["../../src/utils/usage.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAEjD,UAAU,OAAO;IACf,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,sFAAsF;AACtF,wBAAgB,SAAS,CAAC,QAAQ,EAAE,OAAO,GAAG,SAAS,GAAG,UAAU,GAAG,SAAS,CAS/E;AAED,0EAA0E;AAC1E,wBAAgB,QAAQ,CAAC,CAAC,EAAE,UAAU,GAAG,SAAS,EAAE,CAAC,EAAE,UAAU,GAAG,SAAS,GAAG,UAAU,GAAG,SAAS,CAOrG"}
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Token counts, added up across a turn.
3
+ *
4
+ * Providers report per call; a text turn spends two, plus one per tool round,
5
+ * plus one if the history was compacted. The host bills the conversation, so
6
+ * the framework hands it one figure beside `llmCalls`.
7
+ */
8
+ /** What a call's metadata says it cost, or nothing when the provider said nothing. */
9
+ export function readUsage(metadata) {
10
+ if (!metadata)
11
+ return undefined;
12
+ const { promptTokens, completionTokens, cachedInputTokens } = metadata;
13
+ if (promptTokens === undefined && completionTokens === undefined)
14
+ return undefined;
15
+ return {
16
+ promptTokens: promptTokens ?? 0,
17
+ completionTokens: completionTokens ?? 0,
18
+ cachedInputTokens: cachedInputTokens ?? 0,
19
+ };
20
+ }
21
+ /** Adds two tallies. Nobody counting is not the same as counting zero. */
22
+ export function addUsage(a, b) {
23
+ if (!a || !b)
24
+ return a ?? b;
25
+ return {
26
+ promptTokens: a.promptTokens + b.promptTokens,
27
+ completionTokens: a.completionTokens + b.completionTokens,
28
+ cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens,
29
+ };
30
+ }
31
+ //# sourceMappingURL=usage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usage.js","sourceRoot":"","sources":["../../src/utils/usage.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAUH,sFAAsF;AACtF,MAAM,UAAU,SAAS,CAAC,QAA6B;IACrD,IAAI,CAAC,QAAQ;QAAE,OAAO,SAAS,CAAC;IAChC,MAAM,EAAE,YAAY,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,GAAG,QAAQ,CAAC;IACvE,IAAI,YAAY,KAAK,SAAS,IAAI,gBAAgB,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IACnF,OAAO;QACL,YAAY,EAAE,YAAY,IAAI,CAAC;QAC/B,gBAAgB,EAAE,gBAAgB,IAAI,CAAC;QACvC,iBAAiB,EAAE,iBAAiB,IAAI,CAAC;KAC1C,CAAC;AACJ,CAAC;AAED,0EAA0E;AAC1E,MAAM,UAAU,QAAQ,CAAC,CAAyB,EAAE,CAAyB;IAC3E,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC;QAAE,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5B,OAAO;QACL,YAAY,EAAE,CAAC,CAAC,YAAY,GAAG,CAAC,CAAC,YAAY;QAC7C,gBAAgB,EAAE,CAAC,CAAC,gBAAgB,GAAG,CAAC,CAAC,gBAAgB;QACzD,iBAAiB,EAAE,CAAC,CAAC,iBAAiB,GAAG,CAAC,CAAC,iBAAiB;KAC7D,CAAC;AACJ,CAAC"}
package/docs/README.md CHANGED
@@ -1,40 +1,58 @@
1
1
  ---
2
- title: "Documentation"
3
- description: "Typed conversations where code stays in charge. Docs for @falai/agent."
2
+ title: "@falai/agent docs"
3
+ description: "The docs for @falai/agent 4.0: a five-page tutorial, one guide per task, the concepts behind a turn, and one reference page per public type."
4
4
  type: overview
5
5
  order: 0
6
6
  ---
7
7
 
8
- # Documentation
8
+ # @falai/agent docs
9
9
 
10
- **Typed conversations where code stays in charge.**
10
+ @falai/agent is a TypeScript library for building chat assistants. The AI understands what the customer wrote; your code decides what happens next. One `agent.turn()` takes a message, a timer, an event from your system or a manual start, and returns the messages to send and the timers to set. Your program, the host, sends and schedules them.
11
11
 
12
- Define flows, steps, and tools in TypeScript; the framework calls the LLM only for the parts that need language — routing, extraction, and generation.
12
+ ## Tutorial
13
13
 
14
- ## New here?
14
+ Five pages that build one agent from install to production. Start at [Install](./start/01-install.md).
15
15
 
16
- Walk through a five-step tutorial that builds a working agent end to end, from install to streaming responses in production.
16
+ 1. [Install](./start/01-install.md)
17
+ 2. [Your first agent](./start/02-first-agent.md)
18
+ 3. [Collect data](./start/03-collect-data.md)
19
+ 4. [Add tools](./start/04-add-tools.md)
20
+ 5. [Go to production](./start/05-go-to-production.md)
17
21
 
18
- [Start the tutorial](./start/01-install.md)
22
+ ## Guides
19
23
 
20
- ## Solving one task?
24
+ One page per task. Each shows the code you write and what the framework does with it. Open [Triggers](./guides/triggers.md) first, since every flow starts with one; the rest stand alone.
21
25
 
22
- Eight task-shaped recipes covering conditions, branching, flow control, instructions, persistence, streaming, errors, and compaction.
26
+ - [Triggers](./guides/triggers.md) — message, mention, silence, event, manual start
27
+ - [Conditions](./guides/conditions.md) — `when` (the model) versus `if` (your code)
28
+ - [Branching](./guides/branching.md) — forks while a step is asking
29
+ - [Flow control](./guides/flow-control.md) — `then`, `else`, `onEnd`, `while`, chaining flows
30
+ - [Actions and events](./guides/actions-and-events.md) — what your code does and what it reports
31
+ - [Instructions](./guides/instructions.md) — rules the model follows at agent, flow or step level
32
+ - [Error handling](./guides/error-handling.md) — what throws, what stays put and retries on a timer, what you replay
33
+ - [Persistence](./guides/persistence.md) — `Store`, the version check on save, the seven built-in stores
34
+ - [Streaming](./guides/streaming.md) — `turnStream` and its chunks
35
+ - [Compaction](./guides/compaction.md) — trimming long histories once per turn
36
+ - [Flows from JSON](./guides/flows-from-json.md) — `FlowSpec`, `fromSpec`, `validateFlow`
37
+ - [Testing](./guides/testing.md) — a fake clock, an in-memory store, a scripted provider
23
38
 
24
- [Browse the guides](./guides/conditions.md)
39
+ ## Concepts
25
40
 
26
- ## Want the why?
41
+ Four pages explain the design. Start with [Architecture](./concepts/architecture.md).
27
42
 
28
- Three concept pages that build the mental model: the seven primitives, the per-turn pipeline, and how directives steer a conversation.
43
+ - [Architecture](./concepts/architecture.md) — agent, flow, trigger, step, field, run, turn
44
+ - [Pipeline](./concepts/pipeline.md) — the eight phases of one turn and what each costs
45
+ - [Runs and waits](./concepts/runs-and-waits.md) — who is speaking (the floor), timers (wakes), keys and claims
46
+ - [Collection](./concepts/collection.md) — how fields get filled
29
47
 
30
- [Read about the architecture](./concepts/architecture.md)
48
+ ## Reference
31
49
 
32
- ## Looking up an API?
50
+ One page per public type, with every field, its type and its default, taken from the code. Start at [Agent](./reference/agent.md), which covers `falai()`, the agent options, `turn()` and its result.
33
51
 
34
- One page per public type. Signatures, field tables, errors, and short runnable examples for `createAgent`, `Flow`, `Step`, `Tool`, `Instruction`, `Directive`, signals, providers, adapters, and more.
35
-
36
- [Open the reference](./reference/create-agent.md)
52
+ - [Agent](./reference/agent.md) · [Flow](./reference/flow.md) · [Step](./reference/step.md) · [Trigger](./reference/trigger.md) · [Fields](./reference/fields.md) · [Branches](./reference/branches.md)
53
+ - [Actions, events, conditions](./reference/actions-events-conditions.md) · [Instruction](./reference/instruction.md) · [Tool](./reference/tool.md)
54
+ - [Session](./reference/session.md) · [Stores](./reference/stores.md) · [Flow spec](./reference/flow-spec.md) · [Outcomes](./reference/outcomes.md) · [Errors](./reference/errors.md) · [Providers](./reference/providers.md)
37
55
 
38
56
  ---
39
57
 
40
- Upgrading? See the [v2.3 → v2.4 migration guide](./migration/v2-3-to-v2-4.md) or, from `1.x`, the [v1 → v2 migration guide](./migration/v1-to-v2.md).
58
+ Upgrading from 3.x? v4 is a clean break: nothing old compiles. The [v3 → v4 migration guide](./migration/v3-to-v4.md) has the before and after for every change.
@@ -1,274 +1,152 @@
1
1
  ---
2
- title: "Architecture"
3
- description: "The six primitives of @falai/agent and how they fit together to keep language on the AI's side and decisions on the code's side."
2
+ title: "Agent architecture"
3
+ description: "The seven words the rest of the docs use, and the line between what the model decides and what the code decides."
4
4
  type: concept
5
5
  order: 1
6
6
  ---
7
7
 
8
- # Architecture
9
-
10
- > the AI understands, the code is in control
11
-
12
- Six types do all the work. Five are about declaration — what the agent looks like in source. One is about control — what tools and hooks return at runtime to redirect a turn. This page maps the ownership and reference relationships between them, explains the schema-first principle that makes pre-extraction work, and draws the line between what the AI does and what the code does.
13
-
14
- LLMs are good at language and unreliable at control flow. They paraphrase well; they do not maintain invariants. They infer intent well; they do not enforce completion gates. The framework's job is to keep the AI on the side of language — understanding intent, extracting structured data, generating prose — while keeping the code on the side of decisions: which flow runs, when a flow completes, what a tool actually does, what state survives a turn.
15
-
16
- This page explains the shape of that seam. It names the six primitives, says what each one is for, and shows how they reference each other. It does not teach syntax. Once the mental model is in place, the [reference](../reference/create-agent.md) pages document the contracts and the [tutorial](../start/01-install.md) walks through the code line by line.
17
-
18
- ## Core vocabulary
19
-
20
- Eight terms cover everything below. Every other term in the docs defines itself at first use — there is no separate glossary.
21
-
22
- | Term | What it means here |
23
- |------|--------------------|
24
- | **Agent** | The top-level object. Owns the schema, provider, flows, tools, signals, and persistence. |
25
- | **Flow** | A single conversational goal — an ordered sequence of steps with shared completion semantics. |
26
- | **Step** | One node inside a flow. Asks a question, collects fields, calls tools, runs hooks, or speaks a verbatim line. |
27
- | **Tool** | A typed function the AI can call. May redirect the conversation by emitting a directive. |
28
- | **Instruction** | A behavioral statement (`must` / `never` / `should`) that shapes how the agent talks at a given scope. |
29
- | **Directive** | A flat object any tool, hook, or branch returns to write state, change position, or speak verbatim. |
30
- | **Schema** | The single source of truth for `TData` — what the agent collects across the whole conversation. |
31
- | **Context** | Ambient app data of type `TContext` — user, env, services. Independent of `TData`. |
32
-
33
- These are the words the rest of the docs use without footnotes. They are also the words the type system uses — every name in the table maps directly to an exported symbol or a generic parameter.
34
-
35
- ## The six primitives
36
-
37
- Six types do all the work. The first five are about declaration — what the agent looks like in source. The last one is about control — what tools and hooks return at runtime to act on a turn. None of them is novel on its own. The shape of the framework is in how few there are and how cleanly they compose.
38
-
39
- A small illustrative sketch first, just to show the silhouette:
40
-
41
- ```typescript
42
- const agent = createAgent({
43
- name: "BookingBot",
44
- schema: { /* TData shape */ },
45
- provider: new GeminiProvider({ apiKey }),
46
- instructions: [
47
- { kind: "must", prompt: "Confirm dates before booking." },
48
- ],
49
- tools: [
50
- { id: "book_hotel", handler: async (ctx) => { /* ... */ } },
51
- ],
52
- flows: [
53
- {
54
- title: "Booking",
55
- requiredFields: ["city", "checkIn"],
56
- steps: [
57
- { id: "ask", prompt: "Collect city and date.", collect: ["city", "checkIn"] },
58
- { id: "confirm", prompt: "Confirm and call book_hotel.", requires: ["city", "checkIn"] },
59
- ],
60
- },
61
- ],
62
- });
8
+ # Agent architecture
9
+
10
+ The AI understands. The code is in control.
11
+
12
+ @falai/agent runs a conversation as a set of small programs called flows. The model has two jobs: read what the customer wrote, and phrase what the assistant says. Every other decision is code: which flow runs, which step comes next, which field is still missing, how long to wait, what to send and when.
13
+
14
+ ## The words
15
+
16
+ These seven words are the whole design. The rest of the docs use them without explaining them again.
17
+
18
+ | Word | What it is | Where it lives |
19
+ |---|---|---|
20
+ | **Agent** | The configuration: fields, flows, provider, registries. One instance serves every session. | `f.agent(options)` returns an `Agent` |
21
+ | **Flow** | A trigger plus an ordered list of steps. | `Flow`, built with `f.flow()` |
22
+ | **Trigger** | When a run of the flow starts: `message`, `mention`, `silence`, `event`, or none (the host starts it). | `Trigger`, in `flow.on[]` |
23
+ | **Step** | One thing the run does: the model talks (`prompt` / `collect`), a fixed text goes out (`say`), the host does something (`do`), the run parks (`wait`), the code forks (`if`). | `Step`, in `flow.steps[]` |
24
+ | **Field** | One piece of data to collect, authored once on the agent with its own `ask`. | `FieldDef`, in `falai().fields()` |
25
+ | **Run** | One live execution of a flow inside a session. A session holds many runs; at most one is asking. That run holds the floor: the next message is read as its answer. | `Run`, in `session.runs[]` |
26
+ | **Turn** | One call to `agent.turn(input)`: something happened, here is what to send and when to wake up. | `TurnInput` in, `TurnResult` out |
27
+
28
+ Four registries live on the agent. Instructions are written inline, wherever they apply. Flows name registry entries as strings, and the names are checked when the agent is built.
29
+
30
+ | On the agent | What it holds | Named from |
31
+ |---|---|---|
32
+ | `actions` | Host code a `do` step runs. Returns `{ ok }`, `{ skipped }`, `{ failed }` or `{ defer }`. | `do: 'notify'` |
33
+ | `events` | Host events a trigger or a `wait` may name, each with an optional `direction`. | `on: [{ event: 'stage_entered' }]`, `wait: { event: 'meeting_booked' }` |
34
+ | `conditions` | Host predicates a JSON `if` may name, with an argument. | `if: { tagsAny: ['vip'] }` |
35
+ | `tools` | Typed functions the model may call while it speaks. They return `{ value?, data? }`, never movement. | `tools: ['checkAvailability']` on a step or a flow |
36
+ | `instructions` | Rules the prompt carries while they apply: `must`, `never`, `should`. | Not named: written inline where they apply, on the agent, a flow, a step, or the idle speaker |
37
+
38
+ The **host** is your program: the one that receives a message from the channel, loads the session, calls `turn()`, saves, sends and schedules. The framework does none of those.
39
+
40
+ ## How they fit
41
+
42
+ ```text
43
+ Agent (immutable, one instance for every session)
44
+ ├── fields nome, empresa, confirmado, … authored once, typed
45
+ ├── flows[] Flow = on[] (triggers) + steps[]
46
+ │ step: talk | say | do | wait | if
47
+ │ movement: then / else → step id | 'end' | { step, clear } | { flow, input }
48
+ ├── actions do: 'notify' ┐
49
+ ├── events event: 'meeting_booked' │ host registries,
50
+ ├── conditions if: { inStage: 'x' } │ referenced by name
51
+ ├── tools the model may call these ┘
52
+ ├── instructions must / never / should
53
+ ├── idle speaks when no run holds the floor ('silent' mutes it)
54
+ └── provider talks to the model
55
+
56
+ Session (one per conversation; the host saves it)
57
+ ├── data the collected fields, in any order
58
+ ├── runs[] live runs: running | asking | waiting | suspended
59
+ ├── claims which flows already ran here, so repeat: 'once' and cooldowns hold
60
+ └── inputs the last 50 input ids, for replays
61
+
62
+ turn(input) ── message | wake | event | start ──▶ TurnResult
63
+ session, changed, messages[], schedule[], llmCalls, …
63
64
  ```
64
65
 
65
- Five of the six primitives appear by name in that block. The remaining one — `Directive` — surfaces only when control flow is on the line, returned from a tool or hook to redirect the conversation.
66
-
67
- ### Agent
68
-
69
- An `Agent<TContext, TData>` is the top-level handle. It binds the four ingredients of a conversational system: a **schema** (what to collect), a **provider** (which LLM to call), a set of **flows** (what goals to pursue), and an optional **persistence** adapter (where to keep sessions). Anything ambient — auth, feature flags, services — rides on `TContext`. Anything collected — names, dates, choices — lives in `TData`. Both type parameters are inferred once at the agent boundary and propagate through every flow, step, tool, and hook beneath it.
70
-
71
- The agent owns the registry. It assigns a deterministic id to every flow, step, and tool; it enforces a single `schema` at every `collect` site; it holds the chosen provider and the session lifecycle. It exposes `respond(params)` and `respondStream(params)` for handling user input, plus `dispatch(target, session)` for redirecting from outside a turn. One agent serves many concurrent conversations — a session id keys into the persistence adapter, and `respond` is otherwise stateless from the caller's perspective.
72
-
73
- ### Flow
66
+ ## The two model calls
74
67
 
75
- A `Flow<TContext, TData>` is one conversational goal — booking a hotel, escalating a complaint, onboarding a teammate. Each flow declares a `title`, a list of `steps`, optional `requiredFields` that gate completion, and conditions for activation: `when` for AI-evaluated strings, `if` for code predicates. The flow router selects exactly one flow per turn, so a flow is also the unit of attention — at any moment, the agent is either inside one flow or sitting idle between flows.
68
+ The model gets at most two calls per turn, and each has one job.
76
69
 
77
- A flow owns its steps in declaration order, its scoped instructions and tools, and its completion semantics. The top-level `onComplete: string` is sugar for chaining into another flow on completion; for dynamic logic, `hooks.onComplete` returns a `Directive`. The optional `reentrant` flag opts the flow into "do another?" loops — on re-entry, the engine clears every field declared in `requiredFields` and `optionalFields` so the flow starts fresh. A flow does not own session data — `TData` lives at the agent — but it does declare which fields it needs to be considered done.
70
+ - **The understand call** reads the customer's message. It scores the candidate flows from 0 to 100, says which things the customer brought up, answers the `when` questions of the asking step, and extracts any field values the message carries. It never moves a run.
71
+ - **The speak call** phrases the assistant's reply for one talk step (or for the idle speaker) and extracts the fields that step is still collecting. It may call tools in rounds. It never moves a run either.
78
72
 
79
- ### Step
73
+ Everything else is code, in `src/core/Runner.ts`: which flows are eligible, which run holds the floor, which fields are pending, which step comes next, how long a wait is, what key a message gets, when a claim (a record that this flow already ran) blocks a start, what the result says. Code behaves the same on a replay; the model does not. So nothing the model says is applied before code checks it: unknown fields are dropped, values are coerced to the field's type, `enum` membership is enforced.
80
74
 
81
- A `Step<TContext, TData>` is a single node inside a flow. Each step describes one moment in the conversation: ask a question, collect a few schema fields, call a tool, branch to another step, or speak a verbatim line. Steps are the smallest unit the engine can suspend on between user turns — when a step finishes, the engine checks for a directive, then for branches, then falls through to the linear successor. Steps are also the unit at which scoped tools and instructions attach, so a step can shadow an agent-level setting locally without modifying the agent.
75
+ Two things follow. A flow with no talk steps costs zero model calls. And every result carries `llmCalls`, so a test asserts the budget instead of trusting it. [The turn pipeline](./pipeline.md) walks the eight phases and what each one spends.
82
76
 
83
- A step comes in three mutually exclusive shapes. An **LLM step** has a `prompt` and the engine calls the model. An **auto step** sets `auto: true` — pure computation, no LLM call, only `onEnter`, `prepare`, and `branches` execute. A **reply step** sets `reply` — the engine renders the template and emits it verbatim, skipping the model entirely. Beyond shape, a step owns its `collect` set (which schema fields it extracts), its `requires` list (prerequisites that must be present before entry), its scoped tools and instructions, its `branches` for explicit forks, and the four lifecycle positions: `onEnter`, `prepare`, `finalize`, `onExit`. The combination of three shapes and four lifecycle positions is what lets a step be either a conversational moment or a pure pipeline node, with no third category in between.
77
+ ## One agent, every session
84
78
 
85
- ### Tool
79
+ An `Agent` is immutable configuration. Build it once and keep it for the life of the process. It holds no session, no context and no history of its own; those arrive on every `turn()`.
86
80
 
87
- A `Tool<TContext, TData, TResult>` is a function the AI can call during a turn. Every tool is a single interface — `id` is the sole identifier, every metadata field is optional, and the handler receives a `ToolContext` (a typed view of `data`, `context`, `history`, plus `dispatch` for mid-handler redirection). A tool can return a plain value, a `ToolResult` with state writes, or a `ToolResult` with an embedded `directive` that redirects the conversation when the result is delivered.
81
+ ```ts
82
+ import type { Agent } from "@falai/agent";
83
+ declare const agent: Agent;
88
84
 
89
- A tool owns its parameters schema (what arguments the LLM may pass), its handler (what actually runs), and the optional safety metadata that lets the executor reason about it: `isReadOnly`, `isConcurrencySafe`, `isDestructive`, `validateInput`, `checkPermissions`, `maxResultSizeChars`. Tools are scoped — defined on the agent (always available), on a flow (available only while that flow is active), or on a step (available only while that step is current). Resolution stacks scope-on-scope so a step can shadow an agent-level tool by id without removing it from the registry.
90
-
91
- ### Instruction
92
-
93
- An `Instruction<TContext, TData>` is a single behavioral statement that shapes how the agent talks. Every instruction carries a `kind` discriminator — `must` for absolute do, `never` for absolute don't, `should` for conditional nudge — alongside a `prompt` (the rendered text) and optional activation conditions (`when` for AI strings, `if` for code predicates). One shape covers every behavioral nudge in the system; the only thing that differs from one instruction to the next is its severity and its scope.
94
-
95
- An instruction owns its rendered position in the prompt. The composer renders each active instruction as a single bullet under the system prompt's `## Instructions` section, prefixed with its kind and a scope caption: `[Always]` for agent-level, `[In: <FlowTitle>]` for flow-level, `[Step: <stepId>]` for step-level. The set actually rendered on a turn is reported back as `appliedInstructions` on the response — observability is deterministic, derived from rendering, not self-reported by the model.
96
-
97
- ### Directive
98
-
99
- A `Directive<TContext, TData>` is a flat object literal — not a class, not a builder, not a discriminated union — that any tool, hook, or branch returns to act on the turn. Every field is optional. A directive carries up to four orthogonal payloads: at most **one position field** (`goTo`, `goToStep`, `complete`, `abort`, or `reset`), zero or one **verbatim reply**, optional **state writes** (`dataUpdate` / `contextUpdate`), and optional **pre-LLM augmentation** (`appendPrompt`, `injectTools`, `halt`) plus optional `reason` strings inside object forms for traceability. The flatness is intentional — earlier drafts modeled directives as a discriminated union, but a flat object composes more naturally when a single decision point needs to write state, change position, and speak verbatim in one return value.
100
-
101
- The directive is the single language the framework speaks for control flow. A tool that decides "this user is ineligible" returns `{ goTo: "denial", reply: "Sorry — you don't qualify." }`. A finalize hook that finishes a booking returns `{ complete: true, dataUpdate: { bookingId } }`. A prepare hook that detects a VIP returns `{ appendPrompt: ["This caller is VIP — confirm preferences first."] }`. All of these merge through one algorithm — position fields by precedence, state writes shallow-merged, `reply` last-wins — implemented as `flow.merge(a, b)` and applied uniformly across the turn pipeline.
102
-
103
- The three pre-LLM fields (`appendPrompt`, `injectTools`, `halt`) have a one-turn lifetime: they only take effect in pre-LLM hooks (`onEnter`, `prepare`). When emitted from post-LLM hooks or persisted to `session.pendingDirective`, they are ignored with a WARN log. This keeps one type for all emitters while the engine enforces the phase boundary at runtime.
104
-
105
- ## Supporting concepts
106
-
107
- The six primitives carry the weight. Four supporting pieces make them ergonomic.
108
-
109
- ### `flow` namespace
110
-
111
- `flow` is a small runtime helper namespace exported from the package root. There are no constructor builders here — directives are object literals everywhere they appear in source. The namespace exists for runtime work: validating a directive that arrived from outside the framework (an RPC payload, a queue message), merging two directives by hand when composing custom orchestration, or narrowing an `unknown` value to `Directive` in a type guard.
112
-
113
- ```typescript
114
- import { flow } from "@falai/agent";
115
-
116
- flow.isDirective(x); // type guard
117
- flow.merge(a, b); // Algorithm 4 merge of two directives
118
- flow.validate(d); // throws FlowConfigurationError on invalid shape
85
+ const r = await agent.turn({ sessionId: "demo", message: "oi" });
86
+ console.log(r.llmCalls); // 1: one flow, nothing to judge, one speak call
119
87
  ```
120
88
 
121
- `flow.merge` is the same algorithm the engine runs internally on the per-turn directive bus, exposed for callers that need to compose results before dispatching them. `flow.validate` enforces three invariants — at most one position field, no empty `goTo: {}`, no `reply` alongside `abort` — and throws a typed error otherwise. The pipeline calls it eagerly on every emitted directive, so downstream code can rely on shape.
89
+ Here is the agent that call ran against:
122
90
 
123
- ### `createAgent`
91
+ ```ts
92
+ import { falai } from "@falai/agent";
93
+ import type { AiProvider } from "@falai/agent";
124
94
 
125
- `createAgent(options)` is the level-1 entry point for constructing an agent. It is sugar over `new Agent(options)` and accepts the same `AgentOptions` shape, but reads more naturally for the common case: one options object, generic inference flowing from `schema` through every `flows[].steps[].collect` reference. The type of `session.data` and tool-handler arguments is derived once at the call site and propagates everywhere.
95
+ declare const provider: AiProvider;
126
96
 
127
- ```typescript
128
- const agent = createAgent({
129
- name: "BookingBot",
130
- provider: new GeminiProvider({ apiKey: process.env.GEMINI_API_KEY! }),
131
- schema: { /* ... */ },
132
- flows: [/* ... */],
97
+ const f = falai().fields({
98
+ nome: { type: "string", ask: "Pergunte o nome da pessoa, sem tom de formulário." },
133
99
  });
134
- ```
135
-
136
- The factory is the recommended construction path for application code. The class form (`new Agent(options)`) remains for power users who need to subclass — for example, to override `respond` for custom telemetry, or to add bespoke methods on top of the agent surface. Both share validation: misuse surfaces as `FlowConfigurationError` synchronously at construction, before any turn runs.
137
-
138
- ### `Agent.dispatch`
139
-
140
- `agent.dispatch(target, session)` is the imperative entry point for redirecting a session from outside a turn — typically from a webhook, a cron job, or a UI button that jumps the user into a different flow. It accepts either a string shorthand (`"Feedback"` desugars to `{ goTo: "Feedback" }`) or a full `Directive`. Internally, it writes `session.pendingDirective`; the directive is consumed at the start of the next `respond` call before any other resolution runs. With a persistence adapter configured (and `autoSave` on — the default), dispatch persists immediately, so the queued directive survives process boundaries; without an adapter it is memory-only, and with `autoSave: false` persisting before the next turn is the caller's job. Because the save compare-and-swaps on the session version, a dispatch from a stale copy throws `SessionConflictError` instead of clobbering another writer.
141
-
142
- ```typescript
143
- const updated = await agent.dispatch(
144
- { goTo: "Billing", reply: "Transferring you now." },
145
- session,
146
- );
147
- ```
148
-
149
- Inside a turn, the same effect is reached by returning or dispatching a directive from a tool or hook — the per-turn bus handles the merge. Outside a turn, `Agent.dispatch` is the sanctioned entry point for setting the next position. There is one way to express each thing, and this is the one for "the user just clicked the cancel button in the UI; their next message should land in the Cancellation flow."
150
100
 
151
- The two routes — in-turn (return a directive) and out-of-turn (`Agent.dispatch`) — converge on the same place: `session.pendingDirective`. The pipeline consumes that field at the very top of the next turn before signals or routing run, applies it via `applyDirective`, and clears it. Persistence sees the same shape regardless of where the directive came from, which means the persisted state is independent of how the redirection was issued.
152
-
153
- ### Branches
154
-
155
- A step's `branches` field declares an explicit, source-local fork: from this step, here are the next-step options and how each one is chosen. Branches sit between code and AI — `if` predicates evaluate for free, `when` strings call the LLM only when the predicate already passed. The first matching entry wins, and its `then` resolves to a step id (within the current flow), a flow id (sugar for `goTo`), or a full directive (for cross-flow steps and state-writing forks).
156
-
157
- Branches are the answer to "how do I fork without an LLM call when the choice is purely a function of `data`?" — combined with `auto: true`, an entire decision can run with zero tokens. They coexist with the implicit-fork pattern (multiple successor steps, each carrying its own `step.when`); when both are present on the same step, branches take precedence. Branch resolution sits between the post-LLM phase of the directive bus and the linear successor selection — it is one specific position in the [turn pipeline](./pipeline.md), not a parallel system.
158
-
159
- Branches are also the place where the AI/code split is most visible at the call site. A single `branches` array can mix entries: one entry that uses `if` only (free), one that uses `when` only (one LLM call), one that uses both (`if` short-circuits the `when` evaluation). The author chooses per branch, and the cost of that choice is local to one entry rather than buried in a flag elsewhere.
160
-
161
- ## How the primitives reference each other
162
-
163
- The diagram below maps the ownership and reference relationships between the six primitives and the two state surfaces. Solid arrows are ownership. Dashed lines are scoping or extension. The two state nodes (`Schema` and `Context`) are not primitives — they are the typed surfaces the primitives operate on, drawn at the bottom because everything else references them.
164
-
165
- ```mermaid
166
- graph TB
167
- Schema[(Schema<br/>TData)]
168
- Context[(Context<br/>TContext)]
169
-
170
- Agent --> Schema
171
- Agent --> Context
172
- Agent -->|owns| Flow
173
- Agent -->|owns| Tool
174
- Agent -->|owns| Instruction
175
-
176
- Flow -->|owns| Step
177
- Flow -->|requiredFields| Schema
178
- Flow -.scoped.- Tool
179
- Flow -.scoped.- Instruction
180
-
181
- Step -->|collect / requires| Schema
182
- Step -.scoped.- Tool
183
- Step -.scoped.- Instruction
184
- Step -->|branches| Step
185
- Step -->|onEnter / prepare| Directive
186
- Step -->|finalize| Directive
187
-
188
- Tool -->|ctx.dispatch| Directive
189
- Tool -->|ToolResult.directive| Directive
190
-
191
- Directive -.merged via.-> FlowNS[flow.merge]
101
+ const agent = f.agent({
102
+ name: "Ana",
103
+ provider,
104
+ flows: [
105
+ f.flow({
106
+ id: "boas-vindas",
107
+ name: "Boas-vindas",
108
+ on: [{ message: [] }],
109
+ steps: [{ id: "nome", collect: ["nome"] }],
110
+ }),
111
+ ],
112
+ });
192
113
 
193
- classDef primitive fill:#1e293b,stroke:#0ea5e9,color:#fff;
194
- classDef state fill:#0f172a,stroke:#64748b,color:#cbd5e1;
195
- class Agent,Flow,Step,Tool,Instruction,Directive primitive;
196
- class Schema,Context state;
114
+ export { agent };
197
115
  ```
198
116
 
199
- Read it top-down. The agent owns flows, tools, and instructions, and binds them to a single schema and a single context type. A flow owns steps and may scope its own instructions and tools. A step references the schema through `collect` and `requires`, may carry its own scoped instructions and tools, and may fork via `branches` into another step. Hooks and tools emit directives — pre-LLM hooks use the pre-LLM fields (`appendPrompt`, `injectTools`, `halt`), post-LLM hooks use position/state/reply fields. The `flow` namespace validates and merges them.
200
-
201
- The two state types — `Schema` for `TData`, `Context` for `TContext` — sit at the bottom because everything else points at them. They are not primitives in the same sense as the six types; they are the typed surfaces those primitives operate on, and they are owned by the agent.
202
-
203
- Two things are deliberately absent from this diagram. There is no separate "router" primitive — flow selection is an internal pipeline phase, not a user-facing type. There is no separate "session" primitive in the declaration model — sessions are runtime state, indexed by `sessionId`, persisted by adapters, but not something application code constructs as a building block. Both of those concerns live in the [turn pipeline](./pipeline.md), where they are explained as steps in the per-turn sequence rather than parts of the static structure.
204
-
205
- ## The schema-first principle
206
-
207
- `TData` is **agent-level**, not flow-level. One schema describes everything that can be collected across every flow. Flows declare which fields they need (`requiredFields`); steps declare which fields they extract (`collect`) and which they require (`requires`). This is what makes pre-extraction work: when the user message arrives, the engine extracts every collectable field it can in a single pass into `session.data`, then skips any step whose `collect` set is already satisfied.
208
-
209
- The agent owns the schema, so the same field can be collected by step A in flow X and used as a prerequisite by step B in flow Y. The contracts at every site are the same shape — `(keyof TData)[]` — and TypeScript verifies them at compile time. Move a field name once at the schema and the failures surface immediately at every call site that references it.
117
+ The constructor checks the configuration before any turn runs: duplicate flow ids; every field, action, event, condition, tool and step id a flow names; the `with` of each `do` step against the action's parameters; the idle speaker's tool names. A bad name throws `FlowConfigurationError` when the agent is built, not on the turn that first reaches it.
210
118
 
211
- A practical consequence: a single user message like "I want a hotel in Lisbon for two people next Friday" populates `city`, `guests`, and `checkIn` in one extraction pass. The booking flow's first three steps all skip — their `collect` sets are already satisfied — and the engine arrives at the confirmation step on the very first turn. The flow's `requiredFields` gate completion the same way regardless of whether fields were collected one per turn or three at once. The schema does not care which step did the work; it only cares that the data is there.
119
+ Per turn, the host passes what only it knows:
212
120
 
213
- ## What the AI does, what the code does
121
+ | Input | What it is |
122
+ |---|---|
123
+ | `sessionId`, `session?` | The session the host loaded, or nothing on a first turn. A wake never creates a session. |
124
+ | `context` | Your own data for this turn: the customer, the tenant, whatever your flows read. Typed by `falai<C>()`. Templates read it as `{{context.x}}`; predicates, actions and tools as `ctx.context`. |
125
+ | `history` | The conversation before this input. Pass it on every input kind, wakes included; both calls read it. Leave out the message this turn carries: both calls quote it on their own, so a history that ends with it is read twice. |
126
+ | `silenced?` | Why the assistant cannot speak right now. `do` steps still run, nothing is phrased, zero calls — unless you pass `{ reason, understand: true }`, which still spends the understand call. |
127
+ | `anchors?`, `claims?` | Host keys and claims from the customer's other sessions, for flows that run once per customer instead of once per session (see [Anchors](./runs-and-waits.md#anchors)). |
214
128
 
215
- Two halves divide the work, and the seven primitives are positioned on whichever half makes the decision cheap and correct.
129
+ Then one of four input kinds: `{ message, id?, at? }`, `{ wake }`, `{ event, payload?, key }` or `{ start: { flow, input?, key } }`. [Agent](../reference/agent.md) lists every field.
216
130
 
217
- The AI is responsible for **language**: routing scores (which flow does this message want?), pre-extraction (what fields can be lifted out of this message?), step prompts (what should the assistant say to advance this step?), and the `when` half of conditions (does this AI-readable description match the situation?). The model is good at these jobs, and the framework spends tokens on them deliberately.
131
+ ## Never sends, never sleeps, never saves
218
132
 
219
- The code is responsible for **decisions**: completion (are all required fields present?), branches (does the `if` predicate pass?), tool execution (run the function, get a result), directive merging (which position field wins?), persistence (write the session, atomically). The runtime is good at these jobs, and the framework keeps them on the deterministic side of the seam.
220
-
221
- A primitive sits on the side that owns its decision. A `Flow.when` is AI because intent classification is the AI's job. A `Step.if` is code because boolean checks against `data` are the code's job. A `Directive` is code because the merge algorithm is deterministic. An `Instruction` is rendered text the code controls; the model only chooses how to follow it. Pulling on either thread leads back to the same answer: language belongs to the AI, decisions belong to the code, and the framework is the seam.
222
-
223
- The `when` / `if` split is the smallest visible expression of this principle. The same activation slot — on a flow, on a step, on an instruction, on a branch entry — accepts both: a string for the AI to evaluate, a function for the code to evaluate. When both are set, code runs first and short-circuits the AI call when the predicate already disqualifies the option. There is no unified condition type that abstracts the difference, because the difference is the point. One side spends tokens; the other does not. Authors choose explicitly, every time.
224
-
225
- ## What stays out
226
-
227
- A few things are notably absent from the framework, and the absences are part of the architecture.
228
-
229
- There is no built-in router DSL. The flow router is a single internal phase that scores flows by their `when`/`if` activation, applies a margin against the currently active flow to avoid thrashing, and lands on exactly one flow per turn. It is not exposed for subclassing or composition because there is nothing usefully variable about it at the application layer.
230
-
231
- There is no per-flow schema. Every flow consumes the agent's `TData`. A flow that needs an extra structured field declares it on the agent schema and lists it in `requiredFields`. The "this flow has its own private state" pattern always becomes "this flow uses a subset of the shared schema."
232
-
233
- There is no implicit messaging. The framework never emits a message of its own. Completion is a pure state transition — the active flow ends, the session goes idle, and any prose at that boundary comes from a developer-defined `reply` step or from the next flow's first step. Nothing speaks unless a step or a directive says it.
234
-
235
- There is no glossary. Eight terms are defined in the callout at the top of this page, and every other term in the docs defines itself at first use on the page that introduces it. The framework's surface is small enough that a glossary would duplicate prose without adding clarity.
236
-
237
- ## Why six primitives
238
-
239
- The set of six is the result of a few specific cuts. Each one collapsed a category of duplication into a single shape, and each one is worth naming for its own sake — not for migration purposes (the [migration guide](../migration/v1-to-v2.md) covers that), but because the surface visible today is the result of those choices.
240
-
241
- **One word per concept.** The verb form `route()` is still the act of selecting a flow, and "routing" is still the gerund — but the noun for "a single conversational goal" is **Flow**. The system that selects one is the **FlowRouter**. There is no overlap between the noun and the verb, which keeps the surface readable when the two appear in the same sentence.
242
-
243
- **One Instruction with a kind discriminator.** A behavioral statement is an `Instruction` with `kind: 'must' | 'never' | 'should'`. The three values cover absolute do, absolute don't, and conditional nudge — every behavioral statement an author wants to make falls into one of those categories, and the severity is visible at the call site. The renderer treats all three identically: same prompt position, same scope caption, same `appliedInstructions` reporting. Severity is what the model sees, not what the framework branches on.
244
-
245
- **One Tool with optional metadata.** A `Tool` is a single interface. The simple case is `{ id, handler }`. The production case adds `validateInput`, `checkPermissions`, `isReadOnly`, `isConcurrencySafe`, `isDestructive`, and `maxResultSizeChars` — every one optional. There is no upgrade boundary mid-codebase: a tool that starts as a plain function adds metadata fields when it needs them, without changing type or import. The executor reads each field defensively (undefined falls back to safe defaults), so the same tool runs identically with two metadata fields or zero.
246
-
247
- The remaining four primitives — Agent, Step, Flow, Directive — were always single-shape concepts. The six-primitive count is what survives those three consolidations plus the three that stood on their own.
248
-
249
- ## Construction shape
250
-
251
- The level-1 entry point is `createAgent({ ... })` — one options object, generic inference flowing from `schema` through every `flows[].steps[].collect` reference. The class form `new Agent({ ... })` accepts the same options for power users who need to subclass.
252
-
253
- ```typescript
254
- import { createAgent, GeminiProvider } from "@falai/agent";
255
-
256
- const agent = createAgent({
257
- name: "BookingBot",
258
- provider: new GeminiProvider({ apiKey }),
259
- schema: { /* TData shape */ },
260
- flows: [/* FlowOptions[] */],
261
- tools: [/* Tool[] */],
262
- instructions: [/* Instruction[] */],
263
- });
264
- ```
133
+ `turn()` does no I/O except the provider, your `do` handlers and the tools the model calls. It does not send a message, set a timer, read a clock you did not give it, or touch a store. It returns a plan:
265
134
 
266
- The construction shape encodes the ownership tree: an agent owns flows, tools, and instructions; the schema is set once; the provider is bound. Generic inference does the rest. The first time a `collect: ["foo"]` references a key not in the schema, the type checker objects at the call site. The first time two flows declare the same id, the constructor throws `FlowConfigurationError` synchronously. The first time a tool returns a malformed directive, `flow.validate` throws at apply time. Every error has a typed class, a single format (`[<ErrorClass>] <what>: <why>. <how to fix>.`), and a place in the construction or runtime sequence where it consistently surfaces.
135
+ | Result | What the host does with it |
136
+ |---|---|
137
+ | `changed: false` | Nothing. Save nothing, send nothing. |
138
+ | `session` | Save it with the version you loaded: `store.save(session, loadedVersion)`. A stale version throws `SessionConflictError`; discard everything and replay the same input. |
139
+ | `messages[]` | Send each one, honouring `afterMs`, keyed by `key` so a retry never sends twice. |
140
+ | `schedule[]` | Enqueue each wake with the key in the payload and `encodeURIComponent(key)` as the job id: BullMQ refuses a `:` in a custom id. When it fires, call `turn({ wake: key })`. |
141
+ | `outcomes`, `started`, `ended`, `skipped` | Your execution log. |
267
142
 
268
- ## What's next
143
+ The order matters: save first, then send and schedule. A message that leaves before the save is sent twice when the save loses a race; a message that leaves after it is not. The one exception is `do` handlers and tool handlers: they run inside the turn, before the save, so they run at least once and must be idempotent on `ctx.key`. [Runs and waits](./runs-and-waits.md#five-rules-that-always-hold) lists the five rules it rests on.
269
144
 
270
- The next page walks through what happens when `agent.respond(params)` is called: the per-turn pipeline, resolution precedence (`pendingDirective` first, then signals + routing in parallel, then auto-step chains, then branches, then linear succession), the directive bus, and how `flow.merge` collapses simultaneous emissions into a single applied directive. After that, the [Directives](./directives.md) page goes deeper into the directive shape itself — why it is flat, how `SignalDirective` extends it for signals, and what each field does.
145
+ Time comes from `clock` on the agent (default: the system time), so a test passes `fakeClock()` and moves it by hand. Core code never reads `Date.now()`.
271
146
 
272
- If the goal right now is to write code, the [tutorial](../start/01-install.md) starts from a one-line install and arrives at a working agent in five short pages. If the goal is to look up an exact contract, every primitive on this page has a [reference](../reference/create-agent.md) page with the full TypeScript declaration, a fields table, two short examples, and the typed errors it can throw.
147
+ ## Where next
273
148
 
274
- **Next:** [Turn pipeline](./pipeline.md)
149
+ - [The turn pipeline](./pipeline.md): the eight phases and what each one costs.
150
+ - [Runs and waits](./runs-and-waits.md): the floor, waits, wakes, keys, claims.
151
+ - [Field collection](./collection.md): pending fields, `ask`, `extract`, `maxAsks`.
152
+ - [Your first agent](../start/02-first-agent.md): the same words, one file at a time.