@falai/agent 3.4.5 → 4.0.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (856) hide show
  1. package/README.md +41 -34
  2. package/dist/cjs/core/Agent.d.ts +22 -378
  3. package/dist/cjs/core/Agent.d.ts.map +1 -1
  4. package/dist/cjs/core/Agent.js +104 -1178
  5. package/dist/cjs/core/Agent.js.map +1 -1
  6. package/dist/cjs/core/CompactionEngine.d.ts.map +1 -1
  7. package/dist/cjs/core/CompactionEngine.js +5 -3
  8. package/dist/cjs/core/CompactionEngine.js.map +1 -1
  9. package/dist/cjs/core/FlowSpec.d.ts +136 -0
  10. package/dist/cjs/core/FlowSpec.d.ts.map +1 -0
  11. package/dist/cjs/core/FlowSpec.js +522 -0
  12. package/dist/cjs/core/FlowSpec.js.map +1 -0
  13. package/dist/cjs/core/Migrate.d.ts +38 -0
  14. package/dist/cjs/core/Migrate.d.ts.map +1 -0
  15. package/dist/cjs/core/Migrate.js +270 -0
  16. package/dist/cjs/core/Migrate.js.map +1 -0
  17. package/dist/cjs/core/Prompt.d.ts +54 -0
  18. package/dist/cjs/core/Prompt.d.ts.map +1 -0
  19. package/dist/cjs/core/Prompt.js +143 -0
  20. package/dist/cjs/core/Prompt.js.map +1 -0
  21. package/dist/cjs/core/Runner.d.ts +160 -0
  22. package/dist/cjs/core/Runner.d.ts.map +1 -0
  23. package/dist/cjs/core/Runner.js +1131 -0
  24. package/dist/cjs/core/Runner.js.map +1 -0
  25. package/dist/cjs/core/Speak.d.ts +37 -0
  26. package/dist/cjs/core/Speak.d.ts.map +1 -0
  27. package/dist/cjs/core/Speak.js +364 -0
  28. package/dist/cjs/core/Speak.js.map +1 -0
  29. package/dist/cjs/core/Understand.d.ts +28 -0
  30. package/dist/cjs/core/Understand.d.ts.map +1 -0
  31. package/dist/cjs/core/Understand.js +353 -0
  32. package/dist/cjs/core/Understand.js.map +1 -0
  33. package/dist/cjs/core/contracts.d.ts +122 -0
  34. package/dist/cjs/core/contracts.d.ts.map +1 -0
  35. package/dist/cjs/core/contracts.js +11 -0
  36. package/dist/cjs/core/contracts.js.map +1 -0
  37. package/dist/cjs/core/falai.d.ts +57 -0
  38. package/dist/cjs/core/falai.d.ts.map +1 -0
  39. package/dist/cjs/core/falai.js +43 -0
  40. package/dist/cjs/core/falai.js.map +1 -0
  41. package/dist/cjs/core/predicate.d.ts +9 -0
  42. package/dist/cjs/core/predicate.d.ts.map +1 -0
  43. package/dist/cjs/core/predicate.js +58 -0
  44. package/dist/cjs/core/predicate.js.map +1 -0
  45. package/dist/cjs/index.d.ts +26 -31
  46. package/dist/cjs/index.d.ts.map +1 -1
  47. package/dist/cjs/index.js +46 -68
  48. package/dist/cjs/index.js.map +1 -1
  49. package/dist/cjs/persistence/MemoryStore.d.ts +15 -0
  50. package/dist/cjs/persistence/MemoryStore.d.ts.map +1 -0
  51. package/dist/cjs/persistence/MemoryStore.js +39 -0
  52. package/dist/cjs/persistence/MemoryStore.js.map +1 -0
  53. package/dist/cjs/persistence/MongoStore.d.ts +42 -0
  54. package/dist/cjs/persistence/MongoStore.d.ts.map +1 -0
  55. package/dist/cjs/persistence/MongoStore.js +60 -0
  56. package/dist/cjs/persistence/MongoStore.js.map +1 -0
  57. package/dist/cjs/persistence/OpenSearchStore.d.ts +86 -0
  58. package/dist/cjs/persistence/OpenSearchStore.d.ts.map +1 -0
  59. package/dist/cjs/persistence/OpenSearchStore.js +120 -0
  60. package/dist/cjs/persistence/OpenSearchStore.js.map +1 -0
  61. package/dist/cjs/persistence/PostgresStore.d.ts +41 -0
  62. package/dist/cjs/persistence/PostgresStore.d.ts.map +1 -0
  63. package/dist/cjs/persistence/PostgresStore.js +58 -0
  64. package/dist/cjs/persistence/PostgresStore.js.map +1 -0
  65. package/dist/cjs/persistence/PrismaStore.d.ts +65 -0
  66. package/dist/cjs/persistence/PrismaStore.d.ts.map +1 -0
  67. package/dist/cjs/persistence/PrismaStore.js +95 -0
  68. package/dist/cjs/persistence/PrismaStore.js.map +1 -0
  69. package/dist/cjs/persistence/RedisStore.d.ts +34 -0
  70. package/dist/cjs/persistence/RedisStore.d.ts.map +1 -0
  71. package/dist/cjs/persistence/RedisStore.js +61 -0
  72. package/dist/cjs/persistence/RedisStore.js.map +1 -0
  73. package/dist/cjs/persistence/SQLiteStore.d.ts +45 -0
  74. package/dist/cjs/persistence/SQLiteStore.d.ts.map +1 -0
  75. package/dist/cjs/persistence/SQLiteStore.js +74 -0
  76. package/dist/cjs/persistence/SQLiteStore.js.map +1 -0
  77. package/dist/cjs/persistence/sessionRow.d.ts +14 -0
  78. package/dist/cjs/persistence/sessionRow.d.ts.map +1 -0
  79. package/dist/cjs/persistence/sessionRow.js +50 -0
  80. package/dist/cjs/persistence/sessionRow.js.map +1 -0
  81. package/dist/cjs/providers/DeepSeekProvider.d.ts.map +1 -1
  82. package/dist/cjs/providers/DeepSeekProvider.js +8 -3
  83. package/dist/cjs/providers/DeepSeekProvider.js.map +1 -1
  84. package/dist/cjs/providers/GeminiProvider.d.ts +4 -3
  85. package/dist/cjs/providers/GeminiProvider.d.ts.map +1 -1
  86. package/dist/cjs/providers/GeminiProvider.js +4 -3
  87. package/dist/cjs/providers/GeminiProvider.js.map +1 -1
  88. package/dist/cjs/providers/OpenAICompatibleProvider.d.ts +4 -0
  89. package/dist/cjs/providers/OpenAICompatibleProvider.d.ts.map +1 -1
  90. package/dist/cjs/providers/OpenAICompatibleProvider.js +2 -0
  91. package/dist/cjs/providers/OpenAICompatibleProvider.js.map +1 -1
  92. package/dist/cjs/providers/OpenRouterProvider.d.ts.map +1 -1
  93. package/dist/cjs/providers/OpenRouterProvider.js +2 -4
  94. package/dist/cjs/providers/OpenRouterProvider.js.map +1 -1
  95. package/dist/cjs/providers/ProviderAdapter.d.ts +11 -6
  96. package/dist/cjs/providers/ProviderAdapter.d.ts.map +1 -1
  97. package/dist/cjs/providers/ProviderAdapter.js +33 -10
  98. package/dist/cjs/providers/ProviderAdapter.js.map +1 -1
  99. package/dist/cjs/providers/ZaiProvider.d.ts +6 -4
  100. package/dist/cjs/providers/ZaiProvider.d.ts.map +1 -1
  101. package/dist/cjs/providers/ZaiProvider.js +6 -4
  102. package/dist/cjs/providers/ZaiProvider.js.map +1 -1
  103. package/dist/cjs/types/agent.d.ts +153 -383
  104. package/dist/cjs/types/agent.d.ts.map +1 -1
  105. package/dist/cjs/types/agent.js +1 -1
  106. package/dist/cjs/types/ai.d.ts +32 -1
  107. package/dist/cjs/types/ai.d.ts.map +1 -1
  108. package/dist/cjs/types/compaction.d.ts +3 -1
  109. package/dist/cjs/types/compaction.d.ts.map +1 -1
  110. package/dist/cjs/types/errors.d.ts +9 -12
  111. package/dist/cjs/types/errors.d.ts.map +1 -1
  112. package/dist/cjs/types/errors.js +14 -17
  113. package/dist/cjs/types/errors.js.map +1 -1
  114. package/dist/cjs/types/flow.d.ts +265 -513
  115. package/dist/cjs/types/flow.d.ts.map +1 -1
  116. package/dist/cjs/types/flow.js +7 -1
  117. package/dist/cjs/types/flow.js.map +1 -1
  118. package/dist/cjs/types/history.d.ts +7 -18
  119. package/dist/cjs/types/history.d.ts.map +1 -1
  120. package/dist/cjs/types/history.js.map +1 -1
  121. package/dist/cjs/types/index.d.ts +9 -15
  122. package/dist/cjs/types/index.d.ts.map +1 -1
  123. package/dist/cjs/types/index.js +4 -14
  124. package/dist/cjs/types/index.js.map +1 -1
  125. package/dist/cjs/types/session.d.ts +94 -64
  126. package/dist/cjs/types/session.d.ts.map +1 -1
  127. package/dist/cjs/types/session.js +5 -1
  128. package/dist/cjs/types/session.js.map +1 -1
  129. package/dist/cjs/types/tool.d.ts +37 -207
  130. package/dist/cjs/types/tool.d.ts.map +1 -1
  131. package/dist/cjs/types/tool.js +5 -14
  132. package/dist/cjs/types/tool.js.map +1 -1
  133. package/dist/cjs/utils/clock.d.ts +28 -0
  134. package/dist/cjs/utils/clock.d.ts.map +1 -0
  135. package/dist/cjs/utils/clock.js +64 -0
  136. package/dist/cjs/utils/clock.js.map +1 -0
  137. package/dist/cjs/utils/duration.d.ts +11 -0
  138. package/dist/cjs/utils/duration.d.ts.map +1 -0
  139. package/dist/cjs/utils/duration.js +31 -0
  140. package/dist/cjs/utils/duration.js.map +1 -0
  141. package/dist/cjs/utils/history.d.ts +4 -1
  142. package/dist/cjs/utils/history.d.ts.map +1 -1
  143. package/dist/cjs/utils/history.js +2 -2
  144. package/dist/cjs/utils/history.js.map +1 -1
  145. package/dist/cjs/utils/index.d.ts +4 -10
  146. package/dist/cjs/utils/index.d.ts.map +1 -1
  147. package/dist/cjs/utils/index.js +14 -61
  148. package/dist/cjs/utils/index.js.map +1 -1
  149. package/dist/cjs/utils/json.d.ts +2 -0
  150. package/dist/cjs/utils/json.d.ts.map +1 -1
  151. package/dist/cjs/utils/json.js +5 -0
  152. package/dist/cjs/utils/json.js.map +1 -1
  153. package/dist/cjs/utils/outcomes.d.ts +48 -0
  154. package/dist/cjs/utils/outcomes.d.ts.map +1 -0
  155. package/dist/cjs/utils/outcomes.js +51 -0
  156. package/dist/cjs/utils/outcomes.js.map +1 -0
  157. package/dist/cjs/utils/schema.d.ts +50 -0
  158. package/dist/cjs/utils/schema.d.ts.map +1 -0
  159. package/dist/cjs/utils/schema.js +138 -0
  160. package/dist/cjs/utils/schema.js.map +1 -0
  161. package/dist/cjs/utils/streamingMessage.d.ts +3 -2
  162. package/dist/cjs/utils/streamingMessage.d.ts.map +1 -1
  163. package/dist/cjs/utils/streamingMessage.js +38 -4
  164. package/dist/cjs/utils/streamingMessage.js.map +1 -1
  165. package/dist/cjs/utils/template.d.ts +13 -149
  166. package/dist/cjs/utils/template.d.ts.map +1 -1
  167. package/dist/cjs/utils/template.js +31 -363
  168. package/dist/cjs/utils/template.js.map +1 -1
  169. package/dist/cjs/utils/usage.d.ts +19 -0
  170. package/dist/cjs/utils/usage.d.ts.map +1 -0
  171. package/dist/cjs/utils/usage.js +35 -0
  172. package/dist/cjs/utils/usage.js.map +1 -0
  173. package/dist/core/Agent.d.ts +22 -378
  174. package/dist/core/Agent.d.ts.map +1 -1
  175. package/dist/core/Agent.js +107 -1181
  176. package/dist/core/Agent.js.map +1 -1
  177. package/dist/core/CompactionEngine.d.ts.map +1 -1
  178. package/dist/core/CompactionEngine.js +5 -3
  179. package/dist/core/CompactionEngine.js.map +1 -1
  180. package/dist/core/FlowSpec.d.ts +136 -0
  181. package/dist/core/FlowSpec.d.ts.map +1 -0
  182. package/dist/core/FlowSpec.js +516 -0
  183. package/dist/core/FlowSpec.js.map +1 -0
  184. package/dist/core/Migrate.d.ts +38 -0
  185. package/dist/core/Migrate.d.ts.map +1 -0
  186. package/dist/core/Migrate.js +264 -0
  187. package/dist/core/Migrate.js.map +1 -0
  188. package/dist/core/Prompt.d.ts +54 -0
  189. package/dist/core/Prompt.d.ts.map +1 -0
  190. package/dist/core/Prompt.js +133 -0
  191. package/dist/core/Prompt.js.map +1 -0
  192. package/dist/core/Runner.d.ts +160 -0
  193. package/dist/core/Runner.d.ts.map +1 -0
  194. package/dist/core/Runner.js +1127 -0
  195. package/dist/core/Runner.js.map +1 -0
  196. package/dist/core/Speak.d.ts +37 -0
  197. package/dist/core/Speak.d.ts.map +1 -0
  198. package/dist/core/Speak.js +360 -0
  199. package/dist/core/Speak.js.map +1 -0
  200. package/dist/core/Understand.d.ts +28 -0
  201. package/dist/core/Understand.d.ts.map +1 -0
  202. package/dist/core/Understand.js +349 -0
  203. package/dist/core/Understand.js.map +1 -0
  204. package/dist/core/contracts.d.ts +122 -0
  205. package/dist/core/contracts.d.ts.map +1 -0
  206. package/dist/core/contracts.js +10 -0
  207. package/dist/core/contracts.js.map +1 -0
  208. package/dist/core/falai.d.ts +57 -0
  209. package/dist/core/falai.d.ts.map +1 -0
  210. package/dist/core/falai.js +40 -0
  211. package/dist/core/falai.js.map +1 -0
  212. package/dist/core/predicate.d.ts +9 -0
  213. package/dist/core/predicate.d.ts.map +1 -0
  214. package/dist/core/predicate.js +54 -0
  215. package/dist/core/predicate.js.map +1 -0
  216. package/dist/index.d.ts +26 -31
  217. package/dist/index.d.ts.map +1 -1
  218. package/dist/index.js +19 -24
  219. package/dist/index.js.map +1 -1
  220. package/dist/persistence/MemoryStore.d.ts +15 -0
  221. package/dist/persistence/MemoryStore.d.ts.map +1 -0
  222. package/dist/persistence/MemoryStore.js +35 -0
  223. package/dist/persistence/MemoryStore.js.map +1 -0
  224. package/dist/persistence/MongoStore.d.ts +42 -0
  225. package/dist/persistence/MongoStore.d.ts.map +1 -0
  226. package/dist/persistence/MongoStore.js +56 -0
  227. package/dist/persistence/MongoStore.js.map +1 -0
  228. package/dist/persistence/OpenSearchStore.d.ts +86 -0
  229. package/dist/persistence/OpenSearchStore.d.ts.map +1 -0
  230. package/dist/persistence/OpenSearchStore.js +116 -0
  231. package/dist/persistence/OpenSearchStore.js.map +1 -0
  232. package/dist/persistence/PostgresStore.d.ts +41 -0
  233. package/dist/persistence/PostgresStore.d.ts.map +1 -0
  234. package/dist/persistence/PostgresStore.js +54 -0
  235. package/dist/persistence/PostgresStore.js.map +1 -0
  236. package/dist/persistence/PrismaStore.d.ts +65 -0
  237. package/dist/persistence/PrismaStore.d.ts.map +1 -0
  238. package/dist/persistence/PrismaStore.js +91 -0
  239. package/dist/persistence/PrismaStore.js.map +1 -0
  240. package/dist/persistence/RedisStore.d.ts +34 -0
  241. package/dist/persistence/RedisStore.d.ts.map +1 -0
  242. package/dist/persistence/RedisStore.js +57 -0
  243. package/dist/persistence/RedisStore.js.map +1 -0
  244. package/dist/persistence/SQLiteStore.d.ts +45 -0
  245. package/dist/persistence/SQLiteStore.d.ts.map +1 -0
  246. package/dist/persistence/SQLiteStore.js +70 -0
  247. package/dist/persistence/SQLiteStore.js.map +1 -0
  248. package/dist/persistence/sessionRow.d.ts +14 -0
  249. package/dist/persistence/sessionRow.d.ts.map +1 -0
  250. package/dist/persistence/sessionRow.js +45 -0
  251. package/dist/persistence/sessionRow.js.map +1 -0
  252. package/dist/providers/DeepSeekProvider.d.ts.map +1 -1
  253. package/dist/providers/DeepSeekProvider.js +8 -3
  254. package/dist/providers/DeepSeekProvider.js.map +1 -1
  255. package/dist/providers/GeminiProvider.d.ts +4 -3
  256. package/dist/providers/GeminiProvider.d.ts.map +1 -1
  257. package/dist/providers/GeminiProvider.js +4 -3
  258. package/dist/providers/GeminiProvider.js.map +1 -1
  259. package/dist/providers/OpenAICompatibleProvider.d.ts +4 -0
  260. package/dist/providers/OpenAICompatibleProvider.d.ts.map +1 -1
  261. package/dist/providers/OpenAICompatibleProvider.js +2 -0
  262. package/dist/providers/OpenAICompatibleProvider.js.map +1 -1
  263. package/dist/providers/OpenRouterProvider.d.ts.map +1 -1
  264. package/dist/providers/OpenRouterProvider.js +2 -4
  265. package/dist/providers/OpenRouterProvider.js.map +1 -1
  266. package/dist/providers/ProviderAdapter.d.ts +11 -6
  267. package/dist/providers/ProviderAdapter.d.ts.map +1 -1
  268. package/dist/providers/ProviderAdapter.js +34 -11
  269. package/dist/providers/ProviderAdapter.js.map +1 -1
  270. package/dist/providers/ZaiProvider.d.ts +6 -4
  271. package/dist/providers/ZaiProvider.d.ts.map +1 -1
  272. package/dist/providers/ZaiProvider.js +6 -4
  273. package/dist/providers/ZaiProvider.js.map +1 -1
  274. package/dist/types/agent.d.ts +153 -383
  275. package/dist/types/agent.d.ts.map +1 -1
  276. package/dist/types/agent.js +1 -1
  277. package/dist/types/ai.d.ts +32 -1
  278. package/dist/types/ai.d.ts.map +1 -1
  279. package/dist/types/compaction.d.ts +3 -1
  280. package/dist/types/compaction.d.ts.map +1 -1
  281. package/dist/types/errors.d.ts +9 -12
  282. package/dist/types/errors.d.ts.map +1 -1
  283. package/dist/types/errors.js +12 -15
  284. package/dist/types/errors.js.map +1 -1
  285. package/dist/types/flow.d.ts +265 -513
  286. package/dist/types/flow.d.ts.map +1 -1
  287. package/dist/types/flow.js +7 -1
  288. package/dist/types/flow.js.map +1 -1
  289. package/dist/types/history.d.ts +7 -18
  290. package/dist/types/history.d.ts.map +1 -1
  291. package/dist/types/history.js.map +1 -1
  292. package/dist/types/index.d.ts +9 -15
  293. package/dist/types/index.d.ts.map +1 -1
  294. package/dist/types/index.js +2 -7
  295. package/dist/types/index.js.map +1 -1
  296. package/dist/types/session.d.ts +94 -64
  297. package/dist/types/session.d.ts.map +1 -1
  298. package/dist/types/session.js +5 -1
  299. package/dist/types/session.js.map +1 -1
  300. package/dist/types/tool.d.ts +37 -207
  301. package/dist/types/tool.d.ts.map +1 -1
  302. package/dist/types/tool.js +6 -13
  303. package/dist/types/tool.js.map +1 -1
  304. package/dist/utils/clock.d.ts +28 -0
  305. package/dist/utils/clock.d.ts.map +1 -0
  306. package/dist/utils/clock.js +59 -0
  307. package/dist/utils/clock.js.map +1 -0
  308. package/dist/utils/duration.d.ts +11 -0
  309. package/dist/utils/duration.d.ts.map +1 -0
  310. package/dist/utils/duration.js +26 -0
  311. package/dist/utils/duration.js.map +1 -0
  312. package/dist/utils/history.d.ts +4 -1
  313. package/dist/utils/history.d.ts.map +1 -1
  314. package/dist/utils/history.js +2 -2
  315. package/dist/utils/history.js.map +1 -1
  316. package/dist/utils/index.d.ts +4 -10
  317. package/dist/utils/index.d.ts.map +1 -1
  318. package/dist/utils/index.js +4 -21
  319. package/dist/utils/index.js.map +1 -1
  320. package/dist/utils/json.d.ts +2 -0
  321. package/dist/utils/json.d.ts.map +1 -1
  322. package/dist/utils/json.js +4 -0
  323. package/dist/utils/json.js.map +1 -1
  324. package/dist/utils/outcomes.d.ts +48 -0
  325. package/dist/utils/outcomes.d.ts.map +1 -0
  326. package/dist/utils/outcomes.js +48 -0
  327. package/dist/utils/outcomes.js.map +1 -0
  328. package/dist/utils/schema.d.ts +50 -0
  329. package/dist/utils/schema.d.ts.map +1 -0
  330. package/dist/utils/schema.js +129 -0
  331. package/dist/utils/schema.js.map +1 -0
  332. package/dist/utils/streamingMessage.d.ts +3 -2
  333. package/dist/utils/streamingMessage.d.ts.map +1 -1
  334. package/dist/utils/streamingMessage.js +38 -4
  335. package/dist/utils/streamingMessage.js.map +1 -1
  336. package/dist/utils/template.d.ts +13 -149
  337. package/dist/utils/template.d.ts.map +1 -1
  338. package/dist/utils/template.js +28 -355
  339. package/dist/utils/template.js.map +1 -1
  340. package/dist/utils/usage.d.ts +19 -0
  341. package/dist/utils/usage.d.ts.map +1 -0
  342. package/dist/utils/usage.js +31 -0
  343. package/dist/utils/usage.js.map +1 -0
  344. package/docs/README.md +37 -19
  345. package/docs/concepts/architecture.md +117 -239
  346. package/docs/concepts/collection.md +170 -0
  347. package/docs/concepts/pipeline.md +132 -378
  348. package/docs/concepts/runs-and-waits.md +192 -0
  349. package/docs/guides/actions-and-events.md +276 -0
  350. package/docs/guides/branching.md +119 -208
  351. package/docs/guides/compaction.md +63 -158
  352. package/docs/guides/conditions.md +164 -128
  353. package/docs/guides/error-handling.md +168 -164
  354. package/docs/guides/flow-control.md +210 -349
  355. package/docs/guides/flows-from-json.md +224 -0
  356. package/docs/guides/instructions.md +125 -161
  357. package/docs/guides/persistence.md +182 -206
  358. package/docs/guides/streaming.md +50 -114
  359. package/docs/guides/testing.md +284 -0
  360. package/docs/guides/triggers.md +401 -0
  361. package/docs/migration/README.md +8 -15
  362. package/docs/migration/v1-to-v2.md +1 -1
  363. package/docs/migration/v2-3-to-v2-4.md +2 -2
  364. package/docs/migration/v2-6-to-v2-7.md +4 -4
  365. package/docs/migration/v3-to-v4.md +452 -0
  366. package/docs/reference/actions-events-conditions.md +396 -0
  367. package/docs/reference/agent.md +244 -0
  368. package/docs/reference/branches.md +75 -203
  369. package/docs/reference/errors.md +188 -144
  370. package/docs/reference/fields.md +125 -0
  371. package/docs/reference/flow-spec.md +248 -0
  372. package/docs/reference/flow.md +104 -192
  373. package/docs/reference/instruction.md +83 -137
  374. package/docs/reference/outcomes.md +273 -0
  375. package/docs/reference/providers.md +525 -302
  376. package/docs/reference/session.md +210 -0
  377. package/docs/reference/step.md +194 -312
  378. package/docs/reference/stores.md +496 -0
  379. package/docs/reference/tool.md +162 -231
  380. package/docs/reference/trigger.md +180 -0
  381. package/docs/rfc/v4-one-flow.md +477 -0
  382. package/docs/start/01-install.md +59 -44
  383. package/docs/start/02-first-agent.md +97 -147
  384. package/docs/start/03-collect-data.md +78 -183
  385. package/docs/start/04-add-tools.md +159 -227
  386. package/docs/start/05-go-to-production.md +167 -164
  387. package/examples/01-quickstart.ts +26 -16
  388. package/examples/02-fields.ts +75 -0
  389. package/examples/03-tools.ts +79 -119
  390. package/examples/04-instructions.ts +60 -87
  391. package/examples/05-branches.ts +78 -0
  392. package/examples/06-triggers-and-waits.ts +148 -0
  393. package/examples/07-streaming.ts +34 -60
  394. package/examples/08-store-and-migration.ts +97 -0
  395. package/examples/09-flows-from-json.ts +107 -0
  396. package/package.json +9 -6
  397. package/src/core/Agent.ts +116 -1512
  398. package/src/core/CompactionEngine.ts +7 -4
  399. package/src/core/FlowSpec.ts +712 -0
  400. package/src/core/Migrate.ts +256 -0
  401. package/src/core/Prompt.ts +156 -0
  402. package/src/core/Runner.ts +1181 -0
  403. package/src/core/Speak.ts +451 -0
  404. package/src/core/Understand.ts +422 -0
  405. package/src/core/contracts.ts +111 -0
  406. package/src/core/falai.ts +86 -0
  407. package/src/core/predicate.ts +56 -0
  408. package/src/index.ts +119 -147
  409. package/src/persistence/MemoryStore.ts +37 -0
  410. package/src/persistence/MongoStore.ts +89 -0
  411. package/src/persistence/OpenSearchStore.ts +153 -0
  412. package/src/persistence/PostgresStore.ts +89 -0
  413. package/src/persistence/PrismaStore.ts +127 -0
  414. package/src/persistence/RedisStore.ts +90 -0
  415. package/src/persistence/SQLiteStore.ts +103 -0
  416. package/src/persistence/sessionRow.ts +45 -0
  417. package/src/providers/DeepSeekProvider.ts +8 -3
  418. package/src/providers/GeminiProvider.ts +4 -3
  419. package/src/providers/OpenAICompatibleProvider.ts +6 -0
  420. package/src/providers/OpenRouterProvider.ts +2 -4
  421. package/src/providers/ProviderAdapter.ts +46 -13
  422. package/src/providers/ZaiProvider.ts +6 -4
  423. package/src/types/agent.ts +124 -397
  424. package/src/types/ai.ts +33 -1
  425. package/src/types/compaction.ts +3 -1
  426. package/src/types/errors.ts +13 -16
  427. package/src/types/flow.ts +249 -550
  428. package/src/types/history.ts +7 -20
  429. package/src/types/index.ts +87 -139
  430. package/src/types/session.ts +135 -70
  431. package/src/types/tool.ts +42 -267
  432. package/src/utils/clock.ts +70 -0
  433. package/src/utils/duration.ts +33 -0
  434. package/src/utils/history.ts +3 -2
  435. package/src/utils/index.ts +8 -66
  436. package/src/utils/json.ts +5 -0
  437. package/src/utils/outcomes.ts +56 -0
  438. package/src/utils/schema.ts +145 -0
  439. package/src/utils/streamingMessage.ts +34 -4
  440. package/src/utils/template.ts +32 -423
  441. package/src/utils/usage.ts +37 -0
  442. package/dist/adapters/MemoryAdapter.d.ts +0 -47
  443. package/dist/adapters/MemoryAdapter.d.ts.map +0 -1
  444. package/dist/adapters/MemoryAdapter.js +0 -204
  445. package/dist/adapters/MemoryAdapter.js.map +0 -1
  446. package/dist/adapters/MongoAdapter.d.ts +0 -97
  447. package/dist/adapters/MongoAdapter.d.ts.map +0 -1
  448. package/dist/adapters/MongoAdapter.js +0 -196
  449. package/dist/adapters/MongoAdapter.js.map +0 -1
  450. package/dist/adapters/OpenSearchAdapter.d.ts +0 -169
  451. package/dist/adapters/OpenSearchAdapter.d.ts.map +0 -1
  452. package/dist/adapters/OpenSearchAdapter.js +0 -471
  453. package/dist/adapters/OpenSearchAdapter.js.map +0 -1
  454. package/dist/adapters/PostgreSQLAdapter.d.ts +0 -85
  455. package/dist/adapters/PostgreSQLAdapter.d.ts.map +0 -1
  456. package/dist/adapters/PostgreSQLAdapter.js +0 -308
  457. package/dist/adapters/PostgreSQLAdapter.js.map +0 -1
  458. package/dist/adapters/PrismaAdapter.d.ts +0 -115
  459. package/dist/adapters/PrismaAdapter.d.ts.map +0 -1
  460. package/dist/adapters/PrismaAdapter.js +0 -406
  461. package/dist/adapters/PrismaAdapter.js.map +0 -1
  462. package/dist/adapters/RedisAdapter.d.ts +0 -72
  463. package/dist/adapters/RedisAdapter.d.ts.map +0 -1
  464. package/dist/adapters/RedisAdapter.js +0 -286
  465. package/dist/adapters/RedisAdapter.js.map +0 -1
  466. package/dist/adapters/SQLiteAdapter.d.ts +0 -86
  467. package/dist/adapters/SQLiteAdapter.d.ts.map +0 -1
  468. package/dist/adapters/SQLiteAdapter.js +0 -337
  469. package/dist/adapters/SQLiteAdapter.js.map +0 -1
  470. package/dist/adapters/index.d.ts +0 -17
  471. package/dist/adapters/index.d.ts.map +0 -1
  472. package/dist/adapters/index.js +0 -11
  473. package/dist/adapters/index.js.map +0 -1
  474. package/dist/adapters/sessionRow.d.ts +0 -22
  475. package/dist/adapters/sessionRow.d.ts.map +0 -1
  476. package/dist/adapters/sessionRow.js +0 -48
  477. package/dist/adapters/sessionRow.js.map +0 -1
  478. package/dist/cjs/adapters/MemoryAdapter.d.ts +0 -47
  479. package/dist/cjs/adapters/MemoryAdapter.d.ts.map +0 -1
  480. package/dist/cjs/adapters/MemoryAdapter.js +0 -208
  481. package/dist/cjs/adapters/MemoryAdapter.js.map +0 -1
  482. package/dist/cjs/adapters/MongoAdapter.d.ts +0 -97
  483. package/dist/cjs/adapters/MongoAdapter.d.ts.map +0 -1
  484. package/dist/cjs/adapters/MongoAdapter.js +0 -200
  485. package/dist/cjs/adapters/MongoAdapter.js.map +0 -1
  486. package/dist/cjs/adapters/OpenSearchAdapter.d.ts +0 -169
  487. package/dist/cjs/adapters/OpenSearchAdapter.d.ts.map +0 -1
  488. package/dist/cjs/adapters/OpenSearchAdapter.js +0 -475
  489. package/dist/cjs/adapters/OpenSearchAdapter.js.map +0 -1
  490. package/dist/cjs/adapters/PostgreSQLAdapter.d.ts +0 -85
  491. package/dist/cjs/adapters/PostgreSQLAdapter.d.ts.map +0 -1
  492. package/dist/cjs/adapters/PostgreSQLAdapter.js +0 -312
  493. package/dist/cjs/adapters/PostgreSQLAdapter.js.map +0 -1
  494. package/dist/cjs/adapters/PrismaAdapter.d.ts +0 -115
  495. package/dist/cjs/adapters/PrismaAdapter.d.ts.map +0 -1
  496. package/dist/cjs/adapters/PrismaAdapter.js +0 -410
  497. package/dist/cjs/adapters/PrismaAdapter.js.map +0 -1
  498. package/dist/cjs/adapters/RedisAdapter.d.ts +0 -72
  499. package/dist/cjs/adapters/RedisAdapter.d.ts.map +0 -1
  500. package/dist/cjs/adapters/RedisAdapter.js +0 -290
  501. package/dist/cjs/adapters/RedisAdapter.js.map +0 -1
  502. package/dist/cjs/adapters/SQLiteAdapter.d.ts +0 -86
  503. package/dist/cjs/adapters/SQLiteAdapter.d.ts.map +0 -1
  504. package/dist/cjs/adapters/SQLiteAdapter.js +0 -341
  505. package/dist/cjs/adapters/SQLiteAdapter.js.map +0 -1
  506. package/dist/cjs/adapters/index.d.ts +0 -17
  507. package/dist/cjs/adapters/index.d.ts.map +0 -1
  508. package/dist/cjs/adapters/index.js +0 -21
  509. package/dist/cjs/adapters/index.js.map +0 -1
  510. package/dist/cjs/adapters/sessionRow.d.ts +0 -22
  511. package/dist/cjs/adapters/sessionRow.d.ts.map +0 -1
  512. package/dist/cjs/adapters/sessionRow.js +0 -52
  513. package/dist/cjs/adapters/sessionRow.js.map +0 -1
  514. package/dist/cjs/constants/index.d.ts +0 -1
  515. package/dist/cjs/constants/index.d.ts.map +0 -1
  516. package/dist/cjs/constants/index.js +0 -4
  517. package/dist/cjs/constants/index.js.map +0 -1
  518. package/dist/cjs/core/AutoChainExecutor.d.ts +0 -97
  519. package/dist/cjs/core/AutoChainExecutor.d.ts.map +0 -1
  520. package/dist/cjs/core/AutoChainExecutor.js +0 -288
  521. package/dist/cjs/core/AutoChainExecutor.js.map +0 -1
  522. package/dist/cjs/core/BranchEvaluator.d.ts +0 -55
  523. package/dist/cjs/core/BranchEvaluator.d.ts.map +0 -1
  524. package/dist/cjs/core/BranchEvaluator.js +0 -125
  525. package/dist/cjs/core/BranchEvaluator.js.map +0 -1
  526. package/dist/cjs/core/DirectiveChainTracker.d.ts +0 -49
  527. package/dist/cjs/core/DirectiveChainTracker.d.ts.map +0 -1
  528. package/dist/cjs/core/DirectiveChainTracker.js +0 -121
  529. package/dist/cjs/core/DirectiveChainTracker.js.map +0 -1
  530. package/dist/cjs/core/Events.d.ts +0 -26
  531. package/dist/cjs/core/Events.d.ts.map +0 -1
  532. package/dist/cjs/core/Events.js +0 -144
  533. package/dist/cjs/core/Events.js.map +0 -1
  534. package/dist/cjs/core/Flow.d.ts +0 -183
  535. package/dist/cjs/core/Flow.d.ts.map +0 -1
  536. package/dist/cjs/core/Flow.js +0 -551
  537. package/dist/cjs/core/Flow.js.map +0 -1
  538. package/dist/cjs/core/FlowRouter.d.ts +0 -183
  539. package/dist/cjs/core/FlowRouter.d.ts.map +0 -1
  540. package/dist/cjs/core/FlowRouter.js +0 -1047
  541. package/dist/cjs/core/FlowRouter.js.map +0 -1
  542. package/dist/cjs/core/PersistenceManager.d.ts +0 -114
  543. package/dist/cjs/core/PersistenceManager.d.ts.map +0 -1
  544. package/dist/cjs/core/PersistenceManager.js +0 -336
  545. package/dist/cjs/core/PersistenceManager.js.map +0 -1
  546. package/dist/cjs/core/PromptComposer.d.ts +0 -47
  547. package/dist/cjs/core/PromptComposer.d.ts.map +0 -1
  548. package/dist/cjs/core/PromptComposer.js +0 -397
  549. package/dist/cjs/core/PromptComposer.js.map +0 -1
  550. package/dist/cjs/core/PromptSectionCache.d.ts +0 -48
  551. package/dist/cjs/core/PromptSectionCache.d.ts.map +0 -1
  552. package/dist/cjs/core/PromptSectionCache.js +0 -108
  553. package/dist/cjs/core/PromptSectionCache.js.map +0 -1
  554. package/dist/cjs/core/ResponseEngine.d.ts +0 -43
  555. package/dist/cjs/core/ResponseEngine.d.ts.map +0 -1
  556. package/dist/cjs/core/ResponseEngine.js +0 -235
  557. package/dist/cjs/core/ResponseEngine.js.map +0 -1
  558. package/dist/cjs/core/ResponseGenerationError.d.ts +0 -30
  559. package/dist/cjs/core/ResponseGenerationError.d.ts.map +0 -1
  560. package/dist/cjs/core/ResponseGenerationError.js +0 -35
  561. package/dist/cjs/core/ResponseGenerationError.js.map +0 -1
  562. package/dist/cjs/core/ResponseModal.d.ts +0 -305
  563. package/dist/cjs/core/ResponseModal.d.ts.map +0 -1
  564. package/dist/cjs/core/ResponseModal.js +0 -1414
  565. package/dist/cjs/core/ResponseModal.js.map +0 -1
  566. package/dist/cjs/core/ResponsePipeline.d.ts +0 -220
  567. package/dist/cjs/core/ResponsePipeline.d.ts.map +0 -1
  568. package/dist/cjs/core/ResponsePipeline.js +0 -1040
  569. package/dist/cjs/core/ResponsePipeline.js.map +0 -1
  570. package/dist/cjs/core/SessionFinalizer.d.ts +0 -34
  571. package/dist/cjs/core/SessionFinalizer.d.ts.map +0 -1
  572. package/dist/cjs/core/SessionFinalizer.js +0 -88
  573. package/dist/cjs/core/SessionFinalizer.js.map +0 -1
  574. package/dist/cjs/core/SessionManager.d.ts +0 -112
  575. package/dist/cjs/core/SessionManager.d.ts.map +0 -1
  576. package/dist/cjs/core/SessionManager.js +0 -308
  577. package/dist/cjs/core/SessionManager.js.map +0 -1
  578. package/dist/cjs/core/SignalCoordinator.d.ts +0 -103
  579. package/dist/cjs/core/SignalCoordinator.d.ts.map +0 -1
  580. package/dist/cjs/core/SignalCoordinator.js +0 -207
  581. package/dist/cjs/core/SignalCoordinator.js.map +0 -1
  582. package/dist/cjs/core/SignalEvaluator.d.ts +0 -86
  583. package/dist/cjs/core/SignalEvaluator.d.ts.map +0 -1
  584. package/dist/cjs/core/SignalEvaluator.js +0 -319
  585. package/dist/cjs/core/SignalEvaluator.js.map +0 -1
  586. package/dist/cjs/core/SignalProcessor.d.ts +0 -152
  587. package/dist/cjs/core/SignalProcessor.d.ts.map +0 -1
  588. package/dist/cjs/core/SignalProcessor.js +0 -505
  589. package/dist/cjs/core/SignalProcessor.js.map +0 -1
  590. package/dist/cjs/core/Step.d.ts +0 -184
  591. package/dist/cjs/core/Step.d.ts.map +0 -1
  592. package/dist/cjs/core/Step.js +0 -599
  593. package/dist/cjs/core/Step.js.map +0 -1
  594. package/dist/cjs/core/StepLifecycle.d.ts +0 -43
  595. package/dist/cjs/core/StepLifecycle.d.ts.map +0 -1
  596. package/dist/cjs/core/StepLifecycle.js +0 -180
  597. package/dist/cjs/core/StepLifecycle.js.map +0 -1
  598. package/dist/cjs/core/StreamingToolExecutor.d.ts +0 -142
  599. package/dist/cjs/core/StreamingToolExecutor.d.ts.map +0 -1
  600. package/dist/cjs/core/StreamingToolExecutor.js +0 -490
  601. package/dist/cjs/core/StreamingToolExecutor.js.map +0 -1
  602. package/dist/cjs/core/ToolLoopExecutor.d.ts +0 -133
  603. package/dist/cjs/core/ToolLoopExecutor.d.ts.map +0 -1
  604. package/dist/cjs/core/ToolLoopExecutor.js +0 -568
  605. package/dist/cjs/core/ToolLoopExecutor.js.map +0 -1
  606. package/dist/cjs/core/ToolManager.d.ts +0 -250
  607. package/dist/cjs/core/ToolManager.d.ts.map +0 -1
  608. package/dist/cjs/core/ToolManager.js +0 -1104
  609. package/dist/cjs/core/ToolManager.js.map +0 -1
  610. package/dist/cjs/core/createAgent.d.ts +0 -35
  611. package/dist/cjs/core/createAgent.d.ts.map +0 -1
  612. package/dist/cjs/core/createAgent.js +0 -39
  613. package/dist/cjs/core/createAgent.js.map +0 -1
  614. package/dist/cjs/core/flow-namespace.d.ts +0 -64
  615. package/dist/cjs/core/flow-namespace.d.ts.map +0 -1
  616. package/dist/cjs/core/flow-namespace.js +0 -182
  617. package/dist/cjs/core/flow-namespace.js.map +0 -1
  618. package/dist/cjs/core/toolGates.d.ts +0 -24
  619. package/dist/cjs/core/toolGates.d.ts.map +0 -1
  620. package/dist/cjs/core/toolGates.js +0 -52
  621. package/dist/cjs/core/toolGates.js.map +0 -1
  622. package/dist/cjs/types/persistence.d.ts +0 -254
  623. package/dist/cjs/types/persistence.d.ts.map +0 -1
  624. package/dist/cjs/types/persistence.js +0 -7
  625. package/dist/cjs/types/persistence.js.map +0 -1
  626. package/dist/cjs/types/prompt-cache.d.ts +0 -15
  627. package/dist/cjs/types/prompt-cache.d.ts.map +0 -1
  628. package/dist/cjs/types/prompt-cache.js +0 -6
  629. package/dist/cjs/types/prompt-cache.js.map +0 -1
  630. package/dist/cjs/types/signals.d.ts +0 -263
  631. package/dist/cjs/types/signals.d.ts.map +0 -1
  632. package/dist/cjs/types/signals.js +0 -11
  633. package/dist/cjs/types/signals.js.map +0 -1
  634. package/dist/cjs/types/template.d.ts +0 -84
  635. package/dist/cjs/types/template.d.ts.map +0 -1
  636. package/dist/cjs/types/template.js +0 -3
  637. package/dist/cjs/types/template.js.map +0 -1
  638. package/dist/cjs/utils/condition.d.ts +0 -63
  639. package/dist/cjs/utils/condition.d.ts.map +0 -1
  640. package/dist/cjs/utils/condition.js +0 -239
  641. package/dist/cjs/utils/condition.js.map +0 -1
  642. package/dist/cjs/utils/event.d.ts +0 -6
  643. package/dist/cjs/utils/event.d.ts.map +0 -1
  644. package/dist/cjs/utils/event.js +0 -20
  645. package/dist/cjs/utils/event.js.map +0 -1
  646. package/dist/cjs/utils/id.d.ts +0 -33
  647. package/dist/cjs/utils/id.d.ts.map +0 -1
  648. package/dist/cjs/utils/id.js +0 -84
  649. package/dist/cjs/utils/id.js.map +0 -1
  650. package/dist/cjs/utils/serialize.d.ts +0 -36
  651. package/dist/cjs/utils/serialize.d.ts.map +0 -1
  652. package/dist/cjs/utils/serialize.js +0 -77
  653. package/dist/cjs/utils/serialize.js.map +0 -1
  654. package/dist/cjs/utils/session.d.ts +0 -124
  655. package/dist/cjs/utils/session.d.ts.map +0 -1
  656. package/dist/cjs/utils/session.js +0 -396
  657. package/dist/cjs/utils/session.js.map +0 -1
  658. package/dist/constants/index.d.ts +0 -2
  659. package/dist/constants/index.d.ts.map +0 -1
  660. package/dist/constants/index.js +0 -4
  661. package/dist/constants/index.js.map +0 -1
  662. package/dist/core/AutoChainExecutor.d.ts +0 -97
  663. package/dist/core/AutoChainExecutor.d.ts.map +0 -1
  664. package/dist/core/AutoChainExecutor.js +0 -284
  665. package/dist/core/AutoChainExecutor.js.map +0 -1
  666. package/dist/core/BranchEvaluator.d.ts +0 -55
  667. package/dist/core/BranchEvaluator.d.ts.map +0 -1
  668. package/dist/core/BranchEvaluator.js +0 -121
  669. package/dist/core/BranchEvaluator.js.map +0 -1
  670. package/dist/core/DirectiveChainTracker.d.ts +0 -49
  671. package/dist/core/DirectiveChainTracker.d.ts.map +0 -1
  672. package/dist/core/DirectiveChainTracker.js +0 -117
  673. package/dist/core/DirectiveChainTracker.js.map +0 -1
  674. package/dist/core/Events.d.ts +0 -26
  675. package/dist/core/Events.d.ts.map +0 -1
  676. package/dist/core/Events.js +0 -137
  677. package/dist/core/Events.js.map +0 -1
  678. package/dist/core/Flow.d.ts +0 -183
  679. package/dist/core/Flow.d.ts.map +0 -1
  680. package/dist/core/Flow.js +0 -547
  681. package/dist/core/Flow.js.map +0 -1
  682. package/dist/core/FlowRouter.d.ts +0 -183
  683. package/dist/core/FlowRouter.d.ts.map +0 -1
  684. package/dist/core/FlowRouter.js +0 -1043
  685. package/dist/core/FlowRouter.js.map +0 -1
  686. package/dist/core/PersistenceManager.d.ts +0 -114
  687. package/dist/core/PersistenceManager.d.ts.map +0 -1
  688. package/dist/core/PersistenceManager.js +0 -332
  689. package/dist/core/PersistenceManager.js.map +0 -1
  690. package/dist/core/PromptComposer.d.ts +0 -47
  691. package/dist/core/PromptComposer.d.ts.map +0 -1
  692. package/dist/core/PromptComposer.js +0 -393
  693. package/dist/core/PromptComposer.js.map +0 -1
  694. package/dist/core/PromptSectionCache.d.ts +0 -48
  695. package/dist/core/PromptSectionCache.d.ts.map +0 -1
  696. package/dist/core/PromptSectionCache.js +0 -104
  697. package/dist/core/PromptSectionCache.js.map +0 -1
  698. package/dist/core/ResponseEngine.d.ts +0 -43
  699. package/dist/core/ResponseEngine.d.ts.map +0 -1
  700. package/dist/core/ResponseEngine.js +0 -231
  701. package/dist/core/ResponseEngine.js.map +0 -1
  702. package/dist/core/ResponseGenerationError.d.ts +0 -30
  703. package/dist/core/ResponseGenerationError.d.ts.map +0 -1
  704. package/dist/core/ResponseGenerationError.js +0 -31
  705. package/dist/core/ResponseGenerationError.js.map +0 -1
  706. package/dist/core/ResponseModal.d.ts +0 -305
  707. package/dist/core/ResponseModal.d.ts.map +0 -1
  708. package/dist/core/ResponseModal.js +0 -1410
  709. package/dist/core/ResponseModal.js.map +0 -1
  710. package/dist/core/ResponsePipeline.d.ts +0 -220
  711. package/dist/core/ResponsePipeline.d.ts.map +0 -1
  712. package/dist/core/ResponsePipeline.js +0 -1035
  713. package/dist/core/ResponsePipeline.js.map +0 -1
  714. package/dist/core/SessionFinalizer.d.ts +0 -34
  715. package/dist/core/SessionFinalizer.d.ts.map +0 -1
  716. package/dist/core/SessionFinalizer.js +0 -84
  717. package/dist/core/SessionFinalizer.js.map +0 -1
  718. package/dist/core/SessionManager.d.ts +0 -112
  719. package/dist/core/SessionManager.d.ts.map +0 -1
  720. package/dist/core/SessionManager.js +0 -301
  721. package/dist/core/SessionManager.js.map +0 -1
  722. package/dist/core/SignalCoordinator.d.ts +0 -103
  723. package/dist/core/SignalCoordinator.d.ts.map +0 -1
  724. package/dist/core/SignalCoordinator.js +0 -203
  725. package/dist/core/SignalCoordinator.js.map +0 -1
  726. package/dist/core/SignalEvaluator.d.ts +0 -86
  727. package/dist/core/SignalEvaluator.d.ts.map +0 -1
  728. package/dist/core/SignalEvaluator.js +0 -312
  729. package/dist/core/SignalEvaluator.js.map +0 -1
  730. package/dist/core/SignalProcessor.d.ts +0 -152
  731. package/dist/core/SignalProcessor.d.ts.map +0 -1
  732. package/dist/core/SignalProcessor.js +0 -498
  733. package/dist/core/SignalProcessor.js.map +0 -1
  734. package/dist/core/Step.d.ts +0 -184
  735. package/dist/core/Step.d.ts.map +0 -1
  736. package/dist/core/Step.js +0 -594
  737. package/dist/core/Step.js.map +0 -1
  738. package/dist/core/StepLifecycle.d.ts +0 -43
  739. package/dist/core/StepLifecycle.d.ts.map +0 -1
  740. package/dist/core/StepLifecycle.js +0 -176
  741. package/dist/core/StepLifecycle.js.map +0 -1
  742. package/dist/core/StreamingToolExecutor.d.ts +0 -142
  743. package/dist/core/StreamingToolExecutor.d.ts.map +0 -1
  744. package/dist/core/StreamingToolExecutor.js +0 -483
  745. package/dist/core/StreamingToolExecutor.js.map +0 -1
  746. package/dist/core/ToolLoopExecutor.d.ts +0 -133
  747. package/dist/core/ToolLoopExecutor.d.ts.map +0 -1
  748. package/dist/core/ToolLoopExecutor.js +0 -564
  749. package/dist/core/ToolLoopExecutor.js.map +0 -1
  750. package/dist/core/ToolManager.d.ts +0 -250
  751. package/dist/core/ToolManager.d.ts.map +0 -1
  752. package/dist/core/ToolManager.js +0 -1098
  753. package/dist/core/ToolManager.js.map +0 -1
  754. package/dist/core/createAgent.d.ts +0 -35
  755. package/dist/core/createAgent.d.ts.map +0 -1
  756. package/dist/core/createAgent.js +0 -36
  757. package/dist/core/createAgent.js.map +0 -1
  758. package/dist/core/flow-namespace.d.ts +0 -64
  759. package/dist/core/flow-namespace.d.ts.map +0 -1
  760. package/dist/core/flow-namespace.js +0 -179
  761. package/dist/core/flow-namespace.js.map +0 -1
  762. package/dist/core/toolGates.d.ts +0 -24
  763. package/dist/core/toolGates.d.ts.map +0 -1
  764. package/dist/core/toolGates.js +0 -49
  765. package/dist/core/toolGates.js.map +0 -1
  766. package/dist/types/persistence.d.ts +0 -254
  767. package/dist/types/persistence.d.ts.map +0 -1
  768. package/dist/types/persistence.js +0 -6
  769. package/dist/types/persistence.js.map +0 -1
  770. package/dist/types/prompt-cache.d.ts +0 -15
  771. package/dist/types/prompt-cache.d.ts.map +0 -1
  772. package/dist/types/prompt-cache.js +0 -5
  773. package/dist/types/prompt-cache.js.map +0 -1
  774. package/dist/types/signals.d.ts +0 -263
  775. package/dist/types/signals.d.ts.map +0 -1
  776. package/dist/types/signals.js +0 -10
  777. package/dist/types/signals.js.map +0 -1
  778. package/dist/types/template.d.ts +0 -84
  779. package/dist/types/template.d.ts.map +0 -1
  780. package/dist/types/template.js +0 -2
  781. package/dist/types/template.js.map +0 -1
  782. package/dist/utils/condition.d.ts +0 -63
  783. package/dist/utils/condition.d.ts.map +0 -1
  784. package/dist/utils/condition.js +0 -230
  785. package/dist/utils/condition.js.map +0 -1
  786. package/dist/utils/event.d.ts +0 -6
  787. package/dist/utils/event.d.ts.map +0 -1
  788. package/dist/utils/event.js +0 -17
  789. package/dist/utils/event.js.map +0 -1
  790. package/dist/utils/id.d.ts +0 -33
  791. package/dist/utils/id.d.ts.map +0 -1
  792. package/dist/utils/id.js +0 -77
  793. package/dist/utils/id.js.map +0 -1
  794. package/dist/utils/serialize.d.ts +0 -36
  795. package/dist/utils/serialize.d.ts.map +0 -1
  796. package/dist/utils/serialize.js +0 -72
  797. package/dist/utils/serialize.js.map +0 -1
  798. package/dist/utils/session.d.ts +0 -124
  799. package/dist/utils/session.d.ts.map +0 -1
  800. package/dist/utils/session.js +0 -379
  801. package/dist/utils/session.js.map +0 -1
  802. package/docs/concepts/directives.md +0 -369
  803. package/docs/reference/adapters.md +0 -543
  804. package/docs/reference/create-agent.md +0 -216
  805. package/docs/reference/directive.md +0 -242
  806. package/docs/reference/signals.md +0 -368
  807. package/examples/02-data-extraction.ts +0 -90
  808. package/examples/05-branching.ts +0 -140
  809. package/examples/06-flow-control.ts +0 -103
  810. package/examples/08-persistence.ts +0 -98
  811. package/examples/09-signals.ts +0 -144
  812. package/src/adapters/MemoryAdapter.ts +0 -281
  813. package/src/adapters/MongoAdapter.ts +0 -341
  814. package/src/adapters/OpenSearchAdapter.ts +0 -693
  815. package/src/adapters/PostgreSQLAdapter.ts +0 -487
  816. package/src/adapters/PrismaAdapter.ts +0 -617
  817. package/src/adapters/RedisAdapter.ts +0 -439
  818. package/src/adapters/SQLiteAdapter.ts +0 -496
  819. package/src/adapters/index.ts +0 -43
  820. package/src/adapters/sessionRow.ts +0 -57
  821. package/src/constants/index.ts +0 -2
  822. package/src/core/AutoChainExecutor.ts +0 -397
  823. package/src/core/BranchEvaluator.ts +0 -161
  824. package/src/core/DirectiveChainTracker.ts +0 -144
  825. package/src/core/Events.ts +0 -164
  826. package/src/core/Flow.ts +0 -665
  827. package/src/core/FlowRouter.ts +0 -1540
  828. package/src/core/PersistenceManager.ts +0 -446
  829. package/src/core/PromptComposer.ts +0 -448
  830. package/src/core/PromptSectionCache.ts +0 -125
  831. package/src/core/ResponseEngine.ts +0 -338
  832. package/src/core/ResponseGenerationError.ts +0 -53
  833. package/src/core/ResponseModal.ts +0 -1902
  834. package/src/core/ResponsePipeline.ts +0 -1404
  835. package/src/core/SessionFinalizer.ts +0 -108
  836. package/src/core/SessionManager.ts +0 -372
  837. package/src/core/SignalCoordinator.ts +0 -263
  838. package/src/core/SignalEvaluator.ts +0 -404
  839. package/src/core/SignalProcessor.ts +0 -663
  840. package/src/core/Step.ts +0 -782
  841. package/src/core/StepLifecycle.ts +0 -242
  842. package/src/core/StreamingToolExecutor.ts +0 -609
  843. package/src/core/ToolLoopExecutor.ts +0 -749
  844. package/src/core/ToolManager.ts +0 -1379
  845. package/src/core/createAgent.ts +0 -40
  846. package/src/core/flow-namespace.ts +0 -227
  847. package/src/core/toolGates.ts +0 -72
  848. package/src/types/persistence.ts +0 -303
  849. package/src/types/prompt-cache.ts +0 -17
  850. package/src/types/signals.ts +0 -338
  851. package/src/types/template.ts +0 -98
  852. package/src/utils/condition.ts +0 -296
  853. package/src/utils/event.ts +0 -16
  854. package/src/utils/id.ts +0 -91
  855. package/src/utils/serialize.ts +0 -86
  856. package/src/utils/session.ts +0 -501
@@ -0,0 +1,422 @@
1
+ /**
2
+ * Understand: the one call that judges the lead's message (design §4.3).
3
+ *
4
+ * Runner decides who is eligible and what is pending; this module turns that
5
+ * into one prompt, one envelope schema and at most one provider call, then
6
+ * hands back raw values keyed by their real ids. It never writes session
7
+ * data: Runner validates, coerces and applies.
8
+ *
9
+ * Two shortcuts cost zero calls: a single eligible message flow with nothing
10
+ * else to judge starts outright, and a turn with nothing AI-conditioned
11
+ * returns an empty Understanding.
12
+ *
13
+ * The envelope is built for two kinds of provider at once. Gemini enforces
14
+ * the schema, so every section is a closed object with every property
15
+ * required and nullable. GLM follows it by prompt only, so the prompt
16
+ * restates the shape with a skeleton and the parser tolerates missing keys,
17
+ * wrong scalar types and stray text around the JSON.
18
+ */
19
+
20
+ import type { AgentOptions } from "../types/agent.js";
21
+ import type { GenerateMessageOutput, TokenUsage } from "../types/ai.js";
22
+ import type { FieldDef, FieldDefs, Flow, ParamDef, ParamDefs } from "../types/flow.js";
23
+ import type { StructuredSchema } from "../types/schema.js";
24
+ import { extractEmbeddedJSONObject, isRecord } from "../utils/json.js";
25
+ import { logger } from "../utils/logger.js";
26
+ import { coerceField, isKnown, pendingFields, toWireSchema } from "../utils/schema.js";
27
+ import { render, type TemplateScope } from "../utils/template.js";
28
+ import { readUsage } from "../utils/usage.js";
29
+ import type { UnderstandRequest, Understanding } from "./contracts.js";
30
+ import { describeField, factsSection, joinSections, stablePrefix } from "./Prompt.js";
31
+
32
+ export const UNDERSTAND_SCHEMA_NAME = "understand";
33
+
34
+ const SECTIONS = ["flows", "mentions", "extract", "branches", "fields"] as const;
35
+
36
+ /** Gemini rejects any other character in a property name. */
37
+ const SAFE_KEY = /^[a-zA-Z0-9_-]+$/;
38
+
39
+ export class Understand<C = unknown, D = unknown> {
40
+ constructor(private readonly options: AgentOptions<C, D>) {}
41
+
42
+ async run(req: UnderstandRequest<C, D>): Promise<Understanding> {
43
+ const candidates = candidateFlows(req);
44
+ const onlyRouting =
45
+ req.mentionFlows.length === 0 && req.branches.length === 0 && Object.keys(req.fields).length === 0;
46
+ if (onlyRouting && candidates.length <= 1) {
47
+ // One eligible flow and nobody on the floor: it starts, no scoring.
48
+ // Otherwise there is nothing to compare or extract.
49
+ const only = candidates[0];
50
+ return only && !req.floor ? { ...empty(0), flows: { [only.id]: 100 } } : empty(0);
51
+ }
52
+
53
+ const aliases = new Aliases();
54
+ const jsonSchema = buildEnvelope(req, candidates, aliases);
55
+ const { system, turn: prompt } = this.buildPrompt(req, candidates, aliases, jsonSchema);
56
+
57
+ // Provider failures propagate: in this phase the turn throws and the host retries the input.
58
+ const out = await this.options.provider.generateMessage<C, unknown>({
59
+ prompt,
60
+ ...(system ? { system } : {}),
61
+ history: req.history,
62
+ context: req.context,
63
+ parameters: { jsonSchema, schemaName: UNDERSTAND_SCHEMA_NAME },
64
+ });
65
+
66
+ const reply = usable(out.structured) ? out.structured : extractEmbeddedJSONObject(out.message);
67
+ if (!usable(reply)) {
68
+ logger.warn(
69
+ `[Understand] The reply had no usable structure, so nothing was judged this turn. ` +
70
+ `Reply started with: ${out.message.slice(0, 200)}`,
71
+ );
72
+ return empty(1, readUsage(out.metadata));
73
+ }
74
+ return { ...parseReply(reply, aliases), ...usageOf(out.metadata) };
75
+ }
76
+
77
+ private buildPrompt(
78
+ req: UnderstandRequest<C, D>,
79
+ candidates: Flow<C, D>[],
80
+ aliases: Aliases,
81
+ schema: StructuredSchema,
82
+ ): { system: string | null; turn: string } {
83
+ const scope: TemplateScope = { data: req.data, context: req.context };
84
+ const t = (text: string): string => render(text, scope);
85
+ const data = isRecord(req.data) ? req.data : {};
86
+ const { system, inline } = stablePrefix(this.options, scope);
87
+ return {
88
+ system,
89
+ turn: joinSections(
90
+ inline,
91
+ taskSection(),
92
+ floorSection(req, this.options.fields, data, t),
93
+ factsSection(this.options.fields, data),
94
+ flowsSection(candidates, aliases, t),
95
+ mentionsSection(req.mentionFlows, aliases, t),
96
+ branchesSection(req.branches, aliases, t),
97
+ fieldsSection(req.fields, aliases),
98
+ messageSection(req.text),
99
+ outputSection(schema),
100
+ ),
101
+ };
102
+ }
103
+ }
104
+
105
+ // ── Candidates and keys ─────────────────────────────────────────────────
106
+
107
+ /** The floor's flow first, then the eligible message flows, each id once. */
108
+ function candidateFlows<C, D>(req: UnderstandRequest<C, D>): Flow<C, D>[] {
109
+ const seen = new Map<string, Flow<C, D>>();
110
+ for (const flow of [...(req.floor ? [req.floor.flow] : []), ...req.messageFlows]) {
111
+ if (!seen.has(flow.id)) seen.set(flow.id, flow);
112
+ }
113
+ return [...seen.values()];
114
+ }
115
+
116
+ /**
117
+ * Envelope property names for ids the schema cannot carry. A safe id keeps
118
+ * its own name; anything else (run ids carry `#`, `:` and `/`) gets a short
119
+ * alias, mapped back when the reply is parsed.
120
+ */
121
+ class Aliases {
122
+ private readonly byReal = new Map<string, string>();
123
+ private readonly byAlias = new Map<string, string>();
124
+ private n = 0;
125
+
126
+ of(real: string, prefix = "k"): string {
127
+ const seen = this.byReal.get(real);
128
+ if (seen) return seen;
129
+ const alias = SAFE_KEY.test(real) && !this.byAlias.has(real) ? real : this.fresh(prefix);
130
+ this.byAlias.set(alias, real);
131
+ this.byReal.set(real, alias);
132
+ return alias;
133
+ }
134
+
135
+ /** Unknown aliases come back as they are; Runner drops keys it does not know. */
136
+ real(alias: string): string {
137
+ return this.byAlias.get(alias) ?? alias;
138
+ }
139
+
140
+ private fresh(prefix: string): string {
141
+ let alias: string;
142
+ do alias = `${prefix}${++this.n}`;
143
+ while (this.byAlias.has(alias));
144
+ return alias;
145
+ }
146
+ }
147
+
148
+ function branchKey(branch: { runId: string; stepId: string; index: number }): string {
149
+ return `${branch.runId}/${branch.stepId}/${branch.index}`;
150
+ }
151
+
152
+ // ── Envelope ────────────────────────────────────────────────────────────
153
+
154
+ function buildEnvelope<C, D>(req: UnderstandRequest<C, D>, candidates: Flow<C, D>[], aliases: Aliases): StructuredSchema {
155
+ const properties: Record<string, StructuredSchema> = {};
156
+
157
+ if (candidates.length) {
158
+ properties.flows = toWireSchema(
159
+ keyed(candidates.map((f) => aliases.of(f.id, "f")), { type: "integer", description: "0-100 fit of the message to this flow" }),
160
+ { nullable: true },
161
+ );
162
+ }
163
+ if (req.mentionFlows.length) {
164
+ properties.mentions = toWireSchema(
165
+ keyed(req.mentionFlows.map((f) => aliases.of(f.id, "f")), { type: "boolean", description: "The customer brought this up" }),
166
+ { nullable: true },
167
+ );
168
+ const extract: Record<string, StructuredSchema> = {};
169
+ for (const flow of req.mentionFlows) {
170
+ const defs = extractDefs(flow);
171
+ if (defs) extract[aliases.of(flow.id, "f")] = toWireSchema(defs, { nullable: true });
172
+ }
173
+ if (Object.keys(extract).length) {
174
+ properties.extract = { type: "object", properties: extract, required: Object.keys(extract), additionalProperties: false };
175
+ }
176
+ }
177
+ if (req.branches.length) {
178
+ properties.branches = toWireSchema(
179
+ keyed(req.branches.map((b) => aliases.of(branchKey(b), "q")), { type: "boolean", description: "The answer to this question" }),
180
+ { nullable: true },
181
+ );
182
+ }
183
+ if (Object.keys(req.fields).length) {
184
+ const defs: FieldDefs = {};
185
+ for (const [slug, def] of Object.entries(req.fields)) defs[aliases.of(slug, "d")] = def;
186
+ properties.fields = toWireSchema(defs, { nullable: true });
187
+ }
188
+
189
+ return { type: "object", properties, required: Object.keys(properties), additionalProperties: false };
190
+ }
191
+
192
+ function keyed(keys: string[], def: FieldDef): FieldDefs {
193
+ return Object.fromEntries(keys.map((key) => [key, def]));
194
+ }
195
+
196
+ /** The mention trigger's `extract` definitions, when the flow has any. */
197
+ function extractDefs<C, D>(flow: Flow<C, D>): ParamDefs | undefined {
198
+ for (const trigger of flow.on ?? []) {
199
+ if ("mention" in trigger && trigger.extract && Object.keys(trigger.extract).length) return trigger.extract;
200
+ }
201
+ return undefined;
202
+ }
203
+
204
+ // ── Prompt sections ─────────────────────────────────────────────────────
205
+
206
+ function taskSection(): string {
207
+ return [
208
+ "## Task",
209
+ "Judge the customer's latest message, quoted below, against the conversation so far. " +
210
+ "Only the customer's own words count as evidence: never treat the assistant's questions or guesses as something the customer said. " +
211
+ 'Answer with one JSON object in the shape given under "Output".',
212
+ ].join("\n");
213
+ }
214
+
215
+ function floorSection<C, D>(
216
+ req: UnderstandRequest<C, D>,
217
+ fields: FieldDefs,
218
+ data: Record<string, unknown>,
219
+ t: (text: string) => string,
220
+ ): string | null {
221
+ if (!req.floor) return null;
222
+ const { run, flow } = req.floor;
223
+ const lines = [
224
+ "## Current flow",
225
+ `The customer is mid-conversation in "${flow.name}" (${flow.id})${flow.description ? `: ${t(flow.description)}` : "."}`,
226
+ ];
227
+ const step = flow.steps.find((s) => s.id === run.stepId);
228
+ if (step && ("collect" in step || "prompt" in step)) {
229
+ lines.push(`Current step: ${step.id}${step.prompt ? ` — ${t(step.prompt)}` : ""}`);
230
+ const pending = pendingFields(step, data, run.asked);
231
+ if (pending.length) {
232
+ lines.push("This step is waiting for:");
233
+ lines.push(...pending.map((slug) => `- ${fields[slug] ? describeField(slug, fields[slug]) : slug}`));
234
+ }
235
+ }
236
+ lines.push("The customer may continue here or switch to something else. Score the current flow below like any other.");
237
+ return lines.join("\n");
238
+ }
239
+
240
+ function flowsSection<C, D>(candidates: Flow<C, D>[], aliases: Aliases, t: (text: string) => string): string | null {
241
+ if (candidates.length === 0) return null;
242
+ const lines = [
243
+ "## Flows the customer may want",
244
+ "Score every flow from 0 to 100 by how well the message fits it. Score all of them, the current flow included.",
245
+ ];
246
+ candidates.forEach((flow, i) => {
247
+ lines.push(`${i + 1}. ${aliases.of(flow.id, "f")} — ${flow.name}${flow.description ? `: ${t(flow.description)}` : ""}`);
248
+ const phrases = triggerPhrases(flow, "message");
249
+ if (phrases.length) lines.push(` The customer: ${phrases.map(t).join("; ")}`);
250
+ });
251
+ lines.push(
252
+ "",
253
+ "Scoring rules:",
254
+ "- 90-100: explicit keywords + clear intent",
255
+ "- 70-89: strong contextual evidence + relevant keywords",
256
+ "- 50-69: moderate relevance",
257
+ "- 30-49: weak connection or ambiguous",
258
+ "- 0-29: minimal/none",
259
+ );
260
+ return lines.join("\n");
261
+ }
262
+
263
+ function mentionsSection<C, D>(flows: Flow<C, D>[], aliases: Aliases, t: (text: string) => string): string | null {
264
+ if (flows.length === 0) return null;
265
+ const lines = [
266
+ "## Things the customer may mention",
267
+ "For each item, answer true when the customer's message clearly brings it up, false otherwise. " +
268
+ "Be conservative: true needs clear, explicit evidence in the message. The phrases under an item are alternatives; one match is enough.",
269
+ ];
270
+ for (const flow of flows) {
271
+ lines.push(`- ${aliases.of(flow.id, "f")} — ${flow.name}${flow.description ? `: ${t(flow.description)}` : ""}`);
272
+ const phrases = triggerPhrases(flow, "mention");
273
+ if (phrases.length) lines.push(` Counts when: ${phrases.map(t).join("; ")}`);
274
+ const defs = extractDefs(flow);
275
+ if (defs) {
276
+ lines.push(" When true, also extract:");
277
+ lines.push(...Object.entries(defs).map(([name, def]) => ` - ${describeParam(name, def)}`));
278
+ }
279
+ }
280
+ return lines.join("\n");
281
+ }
282
+
283
+ function branchesSection(
284
+ branches: UnderstandRequest["branches"],
285
+ aliases: Aliases,
286
+ t: (text: string) => string,
287
+ ): string | null {
288
+ if (branches.length === 0) return null;
289
+ return [
290
+ "## Questions about this message",
291
+ "Answer each question with true or false, judging the customer's message in the context of the conversation.",
292
+ ...branches.map((b) => `- ${aliases.of(branchKey(b), "q")}: ${t(b.when)}`),
293
+ ].join("\n");
294
+ }
295
+
296
+ function fieldsSection(fields: Record<string, FieldDef>, aliases: Aliases): string | null {
297
+ const entries = Object.entries(fields);
298
+ if (entries.length === 0) return null;
299
+ return [
300
+ "## Details the customer may have given",
301
+ "Report a value only when the customer actually gave it in this message. " +
302
+ "Never guess and never infer it from the assistant's words. Use null when the customer did not give it.",
303
+ ...entries.map(([slug, def]) => `- ${describeField(aliases.of(slug, "d"), def)}`),
304
+ ].join("\n");
305
+ }
306
+
307
+ function messageSection(text: string): string {
308
+ return ["## Customer's latest message", '"""', text, '"""'].join("\n");
309
+ }
310
+
311
+ type Section = (typeof SECTIONS)[number];
312
+
313
+ const OUTPUT_LINES: Record<Section, string> = {
314
+ flows: "- flows: one integer from 0 to 100 per flow id listed above",
315
+ mentions: "- mentions: true or false per item id",
316
+ extract: "- extract: per item id, an object with the values pulled from the message; null values when the item was not brought up",
317
+ branches: "- branches: true or false per question id",
318
+ fields: "- fields: one value per detail, null when the customer did not give it",
319
+ };
320
+
321
+ /**
322
+ * What the skeleton shows in each section: a score of 0, a "no" answer, and
323
+ * null for anything extracted, so a prompt-only model never reads a
324
+ * placeholder as a default value.
325
+ */
326
+ const PLACEHOLDER: Record<Section, unknown> = { flows: 0, mentions: false, extract: null, branches: false, fields: null };
327
+
328
+ function outputSection(schema: StructuredSchema): string {
329
+ const present = SECTIONS.filter((s) => schema.properties?.[s] !== undefined);
330
+ const skeleton = Object.fromEntries(present.map((s) => [s, fill(schema.properties?.[s] ?? {}, PLACEHOLDER[s])]));
331
+ return [
332
+ "## Output",
333
+ "Return exactly one JSON object and nothing else: no prose before or after, no code fence. " +
334
+ "Every key below is required; use null where you have nothing to report.",
335
+ ...present.map((s) => OUTPUT_LINES[s]),
336
+ "Shape, with placeholder values:",
337
+ JSON.stringify(skeleton),
338
+ ].join("\n");
339
+ }
340
+
341
+ /** The schema's shape with one placeholder at every leaf. */
342
+ function fill(schema: StructuredSchema, placeholder: unknown): unknown {
343
+ const type = Array.isArray(schema.type) ? schema.type[0] : schema.type;
344
+ if (type !== "object") return placeholder;
345
+ return Object.fromEntries(Object.entries(schema.properties ?? {}).map(([k, v]) => [k, fill(v, placeholder)]));
346
+ }
347
+
348
+ function triggerPhrases<C, D>(flow: Flow<C, D>, kind: "message" | "mention"): string[] {
349
+ const phrases: string[] = [];
350
+ for (const trigger of flow.on ?? []) {
351
+ if (kind === "message" && "message" in trigger) phrases.push(...trigger.message);
352
+ if (kind === "mention" && "mention" in trigger) phrases.push(...trigger.mention);
353
+ }
354
+ return phrases;
355
+ }
356
+
357
+ function describeParam(name: string, def: ParamDef): string {
358
+ if (def.type === "array") return `${name} (list of ${def.items.type})${def.description ? `: ${def.description}` : ""}`;
359
+ return describeField(name, def);
360
+ }
361
+
362
+ // ── Reply parsing ───────────────────────────────────────────────────────
363
+
364
+ function empty(llmCalls: number, usage?: TokenUsage): Understanding {
365
+ return { flows: {}, mentions: {}, extract: {}, branches: {}, fields: {}, llmCalls, ...(usage ? { usage } : {}) };
366
+ }
367
+
368
+ /** `{ usage }` when the provider counted, `{}` when it did not — `exactOptionalPropertyTypes`. */
369
+ function usageOf(metadata: GenerateMessageOutput["metadata"]): { usage?: TokenUsage } {
370
+ const usage = readUsage(metadata);
371
+ return usage ? { usage } : {};
372
+ }
373
+
374
+ /** A reply is usable when it is an object carrying at least one envelope section. */
375
+ function usable(value: unknown): value is Record<string, unknown> {
376
+ return isRecord(value) && SECTIONS.some((s) => s in value);
377
+ }
378
+
379
+ function entries(value: unknown): [string, unknown][] {
380
+ return isRecord(value) ? Object.entries(value) : [];
381
+ }
382
+
383
+ function parseReply(reply: Record<string, unknown>, aliases: Aliases): Understanding {
384
+ const flows: Record<string, number> = {};
385
+ for (const [key, raw] of entries(reply.flows)) {
386
+ const n = score(raw);
387
+ if (n !== undefined) flows[aliases.real(key)] = n;
388
+ }
389
+ const extract: Record<string, Record<string, unknown>> = {};
390
+ for (const [key, raw] of entries(reply.extract)) {
391
+ if (isRecord(raw)) extract[aliases.real(key)] = given(raw);
392
+ }
393
+ return {
394
+ flows,
395
+ mentions: booleans(reply.mentions, aliases),
396
+ extract,
397
+ branches: booleans(reply.branches, aliases),
398
+ fields: given(Object.fromEntries(entries(reply.fields).map(([k, v]) => [aliases.real(k), v]))),
399
+ llmCalls: 1,
400
+ };
401
+ }
402
+
403
+ /** A finite number, or a numeric string, clamped to 0-100. Anything else is dropped. */
404
+ function score(raw: unknown): number | undefined {
405
+ const n = typeof raw === "number" ? raw : typeof raw === "string" ? Number(raw.trim()) : NaN;
406
+ return Number.isFinite(n) ? Math.min(100, Math.max(0, n)) : undefined;
407
+ }
408
+
409
+ /** Booleans, with `sim`/`yes`/`true` strings accepted through the shared coercion table. */
410
+ function booleans(value: unknown, aliases: Aliases): Record<string, boolean> {
411
+ const out: Record<string, boolean> = {};
412
+ for (const [key, raw] of entries(value)) {
413
+ const coerced = coerceField({ type: "boolean" }, raw);
414
+ if (coerced.ok && typeof coerced.value === "boolean") out[aliases.real(key)] = coerced.value;
415
+ }
416
+ return out;
417
+ }
418
+
419
+ /** Raw values the customer gave: `null`, `undefined` and `''` mean nothing was given. */
420
+ function given(value: Record<string, unknown>): Record<string, unknown> {
421
+ return Object.fromEntries(Object.entries(value).filter(([, v]) => isKnown(v)));
422
+ }
@@ -0,0 +1,111 @@
1
+ /**
2
+ * The seams between the turn's phases. Runner decides who is eligible and
3
+ * what is pending; Understand and Speak turn that into at most one provider
4
+ * call each and hand back plain data for Runner to apply.
5
+ *
6
+ * Runner (code) ──UnderstandRequest──▶ Understand (≤1 call) ──Understanding──▶ Runner
7
+ * Runner (code) ──SpeakRequest──────▶ Speak (≤1 call + tools) ──SpeakOutcome──▶ Runner
8
+ */
9
+
10
+ import type { TokenUsage } from "../types/ai.js";
11
+ import type { Idle } from "../types/agent.js";
12
+ import type { FieldDef, Flow, Instruction, StepBase, TalkStep } from "../types/flow.js";
13
+ import type { History } from "../types/history.js";
14
+ import type { Run, StepOutcomeCode } from "../types/session.js";
15
+ import type { Tool } from "../types/tool.js";
16
+
17
+ export type InputKind = "message" | "wake" | "event" | "start";
18
+
19
+ // ── Understand ──────────────────────────────────────────────────────────
20
+
21
+ /** Everything the understand call may judge this turn. Runner filters by `if` and `repeat` first. */
22
+ export interface UnderstandRequest<C = unknown, D = unknown> {
23
+ text: string;
24
+ history: History;
25
+ context: C;
26
+ data: Partial<D>;
27
+ /** The run holding the floor, always a candidate whatever its trigger. */
28
+ floor?: { run: Run; flow: Flow<C, D> };
29
+ /** Eligible `message` flows, in flow order. `[]` triggers (catch-alls) are excluded. */
30
+ messageFlows: Flow<C, D>[];
31
+ /** Eligible `mention` flows with a non-empty `mention[]`, in flow order. */
32
+ mentionFlows: Flow<C, D>[];
33
+ /** `when` branches of the asking step. */
34
+ branches: Array<{ runId: string; stepId: string; index: number; when: string }>;
35
+ /** Pending fields harvestable from any text (`extract: 'anywhere'`). */
36
+ fields: Record<string, FieldDef>;
37
+ }
38
+
39
+ /** The judged result. Raw values: Runner validates and writes them. */
40
+ export interface Understanding {
41
+ /** flowId → 0–100 fit of the lead's message to the flow. */
42
+ flows: Record<string, number>;
43
+ /** flowId → the lead mentioned it. */
44
+ mentions: Record<string, boolean>;
45
+ /** flowId → values extracted for a mention trigger's `extract` schema. */
46
+ extract: Record<string, Record<string, unknown>>;
47
+ /** `${runId}/${stepId}/${index}` → the branch condition holds. */
48
+ branches: Record<string, boolean>;
49
+ /** field → raw value the lead gave, or nothing. */
50
+ fields: Record<string, unknown>;
51
+ llmCalls: number;
52
+ usage?: TokenUsage;
53
+ }
54
+
55
+ // ── Speak ───────────────────────────────────────────────────────────────
56
+
57
+ /** A talk step queued to speak, with its pending fields already computed. */
58
+ export interface TalkRequest<C = unknown, D = unknown> {
59
+ run: Run;
60
+ flow: Flow<C, D>;
61
+ step: StepBase<D> & TalkStep<C, D>;
62
+ /** `step.collect` minus known minus at `maxAsks`, in order. */
63
+ pending: string[];
64
+ }
65
+
66
+ /** No run holds the floor; the idle speaker answers. */
67
+ export interface IdleRequest<C = unknown, D = unknown> {
68
+ idle: Exclude<Idle<C, D>, "silent">;
69
+ }
70
+
71
+ export interface SpeakRequest<C = unknown, D = unknown> {
72
+ talk: TalkRequest<C, D> | IdleRequest<C, D>;
73
+ /** What started this turn. A wake has no text: the assistant speaks first. */
74
+ input: { kind: InputKind; text?: string };
75
+ context: C;
76
+ data: Partial<D>;
77
+ history: History;
78
+ now: Date;
79
+ /** Already filtered by their `if`; `when` stays for the prompt. */
80
+ instructions: Instruction<C, D>[];
81
+ tools: Tool<C, D>[];
82
+ }
83
+
84
+ export interface Spoken {
85
+ message: string;
86
+ /** Raw envelope values for the pending fields. Runner validates and writes them. */
87
+ fields: Record<string, unknown>;
88
+ /** Data patches returned by tools, merged in call order. */
89
+ data: Record<string, unknown>;
90
+ toolCalls: Array<{ toolName: string; arguments: Record<string, unknown> }>;
91
+ llmCalls: number;
92
+ usage?: TokenUsage;
93
+ }
94
+
95
+ /**
96
+ * Why a speak call failed, and whether a later wake could still fix it. A kind
97
+ * no wake can fix — wrong key, a prompt past the context window, a spent
98
+ * balance with no stated reset — ends the step instead of re-running two model
99
+ * calls against the same wall every fifteen minutes.
100
+ */
101
+ export interface Deferral {
102
+ code: StepOutcomeCode;
103
+ retryable: boolean;
104
+ /** When the provider said its limit reopens. Beats the backoff ladder. */
105
+ resetAtMs?: number;
106
+ }
107
+
108
+ /** `deferred` is the provider failing; Runner re-parks the step under a retry wake, or ends it. */
109
+ export type SpeakOutcome = { spoken: Spoken } | { deferred: Deferral; llmCalls: number; usage?: TokenUsage };
110
+
111
+ export type SpeakStreamChunk = { delta: string } | { done: true; outcome: SpeakOutcome };
@@ -0,0 +1,86 @@
1
+ /**
2
+ * `falai()` carries the one explicit generic an app writes: its context type.
3
+ * Everything else is inferred from values.
4
+ *
5
+ * ```ts
6
+ * const f = falai<LeadContext>().fields({
7
+ * nome: { type: 'string', ask: 'Pergunte o nome de um jeito leve.' },
8
+ * });
9
+ * const agent = f.agent({ name: 'Ana', provider, flows: [f.flow({ ... })] });
10
+ * const r = await agent.turn({ sessionId: 'demo', context, message: 'oi' });
11
+ * ```
12
+ *
13
+ * `f.fields(...)` binds the collected-data type, so every `collect`, `ask`,
14
+ * `clearOnStart` and action `ctx.set` downstream is checked against the
15
+ * field slugs. Action, event and condition names inside flows stay strings:
16
+ * they are checked when the agent is built, the same way JSON specs are.
17
+ */
18
+
19
+ import type { AgentOptions } from "../types/agent.js";
20
+ import type {
21
+ Action,
22
+ ActionCtx,
23
+ ActionResult,
24
+ Condition,
25
+ EventDef,
26
+ FieldDefs,
27
+ Flow,
28
+ InferData,
29
+ InferParams,
30
+ ParamDefs,
31
+ PredCtx,
32
+ } from "../types/flow.js";
33
+ import { Agent } from "./Agent.js";
34
+ import { type FlowSpec, fromSpec } from "./FlowSpec.js";
35
+
36
+ /** The toolkit once fields are bound. `D` is the collected-data type. */
37
+ export interface Falai<C, D, F extends FieldDefs> {
38
+ /** The field definitions, as given. */
39
+ readonly fields: F;
40
+ /** A host action; `params` is typed from `parameters`. */
41
+ action<const P extends ParamDefs>(def: {
42
+ description?: string;
43
+ parameters: P;
44
+ run: (params: InferParams<P>, ctx: ActionCtx<C, D>) => ActionResult | Promise<ActionResult>;
45
+ }): Action<C, D, InferParams<P>>;
46
+ /** A host event; `P` is its payload type. */
47
+ event<P = undefined>(def?: { direction?: "inbound" | "outbound" }): EventDef<P>;
48
+ /** A host condition JSON predicates may name. */
49
+ condition<Arg>(check: (ctx: PredCtx<C, D>, arg: Arg) => boolean): Condition<C, D, Arg>;
50
+ /** A flow; returns it unchanged, typed. */
51
+ flow(def: Flow<C, D>): Flow<C, D>;
52
+ /** A stored flow (JSON) as a typed flow. The agent validates it when built. */
53
+ fromSpec(spec: FlowSpec): Flow<C, D>;
54
+ /** The agent; `fields` come from the toolkit. */
55
+ agent(options: Omit<AgentOptions<C, D>, "fields">): Agent<C, D>;
56
+ }
57
+
58
+ /** The toolkit before fields are bound: loose data, plus `fields()` to bind them. */
59
+ export interface FalaiRoot<C> extends Omit<Falai<C, InferData<FieldDefs>, FieldDefs>, "fields"> {
60
+ fields<const F extends FieldDefs>(defs: F): Falai<C, InferData<F>, F>;
61
+ }
62
+
63
+ /** The collected-data type of a bound toolkit: `type Data = DataOf<typeof f>`. */
64
+ export type DataOf<T extends { fields: FieldDefs }> = InferData<T["fields"]>;
65
+
66
+ function toolkit<C, D, F extends FieldDefs>(fields: F): Falai<C, D, F> {
67
+ return {
68
+ fields,
69
+ action: (def) => def,
70
+ event: (def = {}) => def,
71
+ condition: (check) => ({ check }),
72
+ flow: (def) => def,
73
+ fromSpec: (spec) => fromSpec<C, D>(spec),
74
+ agent: (options) => new Agent<C, D>({ ...options, fields }),
75
+ };
76
+ }
77
+
78
+ /**
79
+ * Start here. Pass the host context type; `falai()` alone means no context.
80
+ */
81
+ export function falai<C = undefined>(): FalaiRoot<C> {
82
+ return {
83
+ ...toolkit<C, InferData<FieldDefs>, FieldDefs>({}),
84
+ fields: (defs) => toolkit(defs),
85
+ };
86
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Code predicates: a function runs as is; a `ConditionSpec` is AND over its
3
+ * keys, with `equals`, `known` and `silenced` built in and every other key
4
+ * looked up in the agent's conditions.
5
+ */
6
+
7
+ import { FlowConfigurationError } from "../types/errors.js";
8
+ import type { ConditionMap, Pred, PredCtx } from "../types/flow.js";
9
+ import { isKnown } from "../utils/schema.js";
10
+
11
+ export function evaluate<C, D, P>(
12
+ pred: Pred<C, D, P>,
13
+ ctx: PredCtx<C, D, P>,
14
+ conditions: ConditionMap<C, D>,
15
+ ): boolean {
16
+ if (typeof pred === "function") return pred(ctx);
17
+ const data: Record<string, unknown> = ctx.data;
18
+ for (const [name, arg] of Object.entries(pred)) {
19
+ if (arg === undefined) continue;
20
+ let holds: boolean;
21
+ switch (name) {
22
+ case "equals":
23
+ holds = Object.entries(arg as Record<string, unknown>).every(([field, value]) => deepEqual(data[field], value));
24
+ break;
25
+ case "known":
26
+ holds = (arg as string[]).every((field) => isKnown(data[field]));
27
+ break;
28
+ case "silenced":
29
+ holds = (ctx.silenced !== undefined) === Boolean(arg);
30
+ break;
31
+ default: {
32
+ const condition = conditions[name];
33
+ if (!condition) {
34
+ throw new FlowConfigurationError(
35
+ `[FlowConfigurationError] unknown condition "${name}": it is not one of the agent's conditions. ` +
36
+ `Register it under \`conditions\` or fix the name.`,
37
+ );
38
+ }
39
+ holds = condition.check(ctx, arg);
40
+ }
41
+ }
42
+ if (!holds) return false;
43
+ }
44
+ return true;
45
+ }
46
+
47
+ export function deepEqual(a: unknown, b: unknown): boolean {
48
+ if (a === b) return true;
49
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
50
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
51
+ const ka = Object.keys(a);
52
+ const kb = Object.keys(b);
53
+ if (ka.length !== kb.length) return false;
54
+ const bRecord = b as Record<string, unknown>;
55
+ return ka.every((k) => k in bRecord && deepEqual((a as Record<string, unknown>)[k], bRecord[k]));
56
+ }