@ai.ntellect/core 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (435) hide show
  1. package/.mocharc.json +6 -0
  2. package/AGENTS.md +50 -0
  3. package/ARCHITECTURE.md +58 -0
  4. package/BENCHMARK.md +38 -0
  5. package/CHANGELOG.md +224 -0
  6. package/README.md +411 -142
  7. package/agent/agent-workflow.ts +569 -0
  8. package/agent/agent.ts +183 -0
  9. package/agent/base/executor.ts +103 -0
  10. package/agent/base/index.ts +87 -0
  11. package/agent/entity-resolver/confidence.ts +54 -0
  12. package/agent/entity-resolver/entity-index.ts +241 -0
  13. package/agent/entity-resolver/explore-strategy.ts +82 -0
  14. package/agent/entity-resolver/index.ts +22 -0
  15. package/agent/entity-resolver/resolver.ts +193 -0
  16. package/agent/entity-resolver/scorer.ts +211 -0
  17. package/agent/entity-resolver/types.ts +98 -0
  18. package/agent/generic-executor.ts +713 -0
  19. package/agent/handlers/cognitive-handler.ts +197 -0
  20. package/agent/handlers/index.ts +1 -0
  21. package/agent/handoff.ts +58 -0
  22. package/agent/llm-factory.ts +343 -0
  23. package/agent/orchestrator.ts +45 -0
  24. package/agent/prompt-builder.ts +78 -0
  25. package/agent/registry.ts +64 -0
  26. package/agent/tools/file-system.ts +471 -0
  27. package/agent/tools/index.ts +23 -0
  28. package/agent/tools/logger.ts +105 -0
  29. package/agent/tools/tool-resolver.ts +104 -0
  30. package/benchmark/cortexflow-workflow.ts +182 -0
  31. package/benchmark/langgraph-workflow.ts +201 -0
  32. package/benchmark/llm-client.ts +76 -0
  33. package/benchmark/run-benchmark.ts +222 -0
  34. package/cli-dev.ts +419 -0
  35. package/dist/agent/agent-workflow.d.ts +41 -0
  36. package/dist/agent/agent-workflow.d.ts.map +1 -0
  37. package/dist/agent/agent-workflow.js +560 -0
  38. package/dist/agent/agent-workflow.js.map +1 -0
  39. package/dist/agent/agent.d.ts +38 -0
  40. package/dist/agent/agent.d.ts.map +1 -0
  41. package/dist/agent/agent.js +149 -0
  42. package/dist/agent/agent.js.map +1 -0
  43. package/dist/agent/base/executor.d.ts +51 -0
  44. package/dist/agent/base/executor.d.ts.map +1 -0
  45. package/dist/agent/base/executor.js +69 -0
  46. package/dist/agent/base/executor.js.map +1 -0
  47. package/dist/agent/base/index.d.ts +30 -0
  48. package/dist/agent/base/index.d.ts.map +1 -0
  49. package/dist/agent/base/index.js +88 -0
  50. package/dist/agent/base/index.js.map +1 -0
  51. package/dist/agent/entity-resolver/confidence.d.ts +4 -0
  52. package/dist/agent/entity-resolver/confidence.d.ts.map +1 -0
  53. package/dist/agent/entity-resolver/confidence.js +47 -0
  54. package/dist/agent/entity-resolver/confidence.js.map +1 -0
  55. package/dist/agent/entity-resolver/entity-index.d.ts +40 -0
  56. package/dist/agent/entity-resolver/entity-index.d.ts.map +1 -0
  57. package/dist/agent/entity-resolver/entity-index.js +244 -0
  58. package/dist/agent/entity-resolver/entity-index.js.map +1 -0
  59. package/dist/agent/entity-resolver/explore-strategy.d.ts +13 -0
  60. package/dist/agent/entity-resolver/explore-strategy.d.ts.map +1 -0
  61. package/dist/agent/entity-resolver/explore-strategy.js +109 -0
  62. package/dist/agent/entity-resolver/explore-strategy.js.map +1 -0
  63. package/dist/agent/entity-resolver/index.d.ts +8 -0
  64. package/dist/agent/entity-resolver/index.d.ts.map +1 -0
  65. package/dist/agent/entity-resolver/index.js +16 -0
  66. package/dist/agent/entity-resolver/index.js.map +1 -0
  67. package/dist/agent/entity-resolver/resolver.d.ts +18 -0
  68. package/dist/agent/entity-resolver/resolver.d.ts.map +1 -0
  69. package/dist/agent/entity-resolver/resolver.js +158 -0
  70. package/dist/agent/entity-resolver/resolver.js.map +1 -0
  71. package/dist/agent/entity-resolver/scorer.d.ts +3 -0
  72. package/dist/agent/entity-resolver/scorer.d.ts.map +1 -0
  73. package/dist/agent/entity-resolver/scorer.js +182 -0
  74. package/dist/agent/entity-resolver/scorer.js.map +1 -0
  75. package/dist/agent/entity-resolver/types.d.ts +89 -0
  76. package/dist/agent/entity-resolver/types.d.ts.map +1 -0
  77. package/dist/agent/entity-resolver/types.js +3 -0
  78. package/dist/agent/entity-resolver/types.js.map +1 -0
  79. package/dist/agent/generic-executor.d.ts +68 -0
  80. package/dist/agent/generic-executor.d.ts.map +1 -0
  81. package/dist/agent/generic-executor.js +620 -0
  82. package/dist/agent/generic-executor.js.map +1 -0
  83. package/dist/agent/handlers/cognitive-handler.d.ts +44 -0
  84. package/dist/agent/handlers/cognitive-handler.d.ts.map +1 -0
  85. package/dist/agent/handlers/cognitive-handler.js +172 -0
  86. package/dist/agent/handlers/cognitive-handler.js.map +1 -0
  87. package/dist/agent/handlers/index.d.ts +2 -0
  88. package/dist/agent/handlers/index.d.ts.map +1 -0
  89. package/dist/agent/handlers/index.js +7 -0
  90. package/dist/agent/handlers/index.js.map +1 -0
  91. package/dist/agent/handoff.d.ts +12 -0
  92. package/dist/agent/handoff.d.ts.map +1 -0
  93. package/dist/agent/handoff.js +62 -0
  94. package/dist/agent/handoff.js.map +1 -0
  95. package/dist/agent/llm-factory.d.ts +19 -0
  96. package/dist/agent/llm-factory.d.ts.map +1 -0
  97. package/dist/agent/llm-factory.js +297 -0
  98. package/dist/agent/llm-factory.js.map +1 -0
  99. package/dist/agent/orchestrator.d.ts +18 -0
  100. package/dist/agent/orchestrator.d.ts.map +1 -0
  101. package/dist/agent/orchestrator.js +44 -0
  102. package/dist/agent/orchestrator.js.map +1 -0
  103. package/dist/agent/prompt-builder.d.ts +35 -0
  104. package/dist/agent/prompt-builder.d.ts.map +1 -0
  105. package/dist/agent/prompt-builder.js +76 -0
  106. package/dist/agent/prompt-builder.js.map +1 -0
  107. package/dist/agent/registry.d.ts +19 -0
  108. package/dist/agent/registry.d.ts.map +1 -0
  109. package/dist/agent/registry.js +48 -0
  110. package/dist/agent/registry.js.map +1 -0
  111. package/dist/agent/tools/file-system.d.ts +11 -0
  112. package/dist/agent/tools/file-system.d.ts.map +1 -0
  113. package/dist/agent/tools/file-system.js +528 -0
  114. package/dist/agent/tools/file-system.js.map +1 -0
  115. package/dist/agent/tools/index.d.ts +4 -0
  116. package/dist/agent/tools/index.d.ts.map +1 -0
  117. package/dist/agent/tools/index.js +20 -0
  118. package/dist/agent/tools/index.js.map +1 -0
  119. package/dist/agent/tools/logger.d.ts +33 -0
  120. package/dist/agent/tools/logger.d.ts.map +1 -0
  121. package/dist/agent/tools/logger.js +86 -0
  122. package/dist/agent/tools/logger.js.map +1 -0
  123. package/dist/agent/tools/tool-resolver.d.ts +7 -0
  124. package/dist/agent/tools/tool-resolver.d.ts.map +1 -0
  125. package/dist/agent/tools/tool-resolver.js +122 -0
  126. package/dist/agent/tools/tool-resolver.js.map +1 -0
  127. package/dist/execution/adapters/in-memory-checkpoint.d.ts +11 -0
  128. package/dist/execution/adapters/in-memory-checkpoint.d.ts.map +1 -0
  129. package/dist/execution/adapters/in-memory-checkpoint.js +54 -0
  130. package/dist/execution/adapters/in-memory-checkpoint.js.map +1 -0
  131. package/dist/execution/compiler.d.ts +8 -0
  132. package/dist/execution/compiler.d.ts.map +1 -0
  133. package/dist/execution/compiler.js +50 -0
  134. package/dist/execution/compiler.js.map +1 -0
  135. package/dist/execution/controller.d.ts +30 -0
  136. package/dist/execution/controller.d.ts.map +1 -0
  137. package/dist/execution/controller.js +80 -0
  138. package/dist/execution/controller.js.map +1 -0
  139. package/dist/execution/event-manager.d.ts +29 -0
  140. package/dist/execution/event-manager.d.ts.map +1 -0
  141. package/dist/execution/event-manager.js +264 -0
  142. package/dist/execution/event-manager.js.map +1 -0
  143. package/dist/execution/index.d.ts +221 -0
  144. package/dist/execution/index.d.ts.map +1 -0
  145. package/dist/execution/index.js +638 -0
  146. package/dist/execution/index.js.map +1 -0
  147. package/dist/execution/logger.d.ts +46 -0
  148. package/dist/execution/logger.d.ts.map +1 -0
  149. package/dist/execution/logger.js +69 -0
  150. package/dist/execution/logger.js.map +1 -0
  151. package/dist/execution/node.d.ts +65 -0
  152. package/dist/execution/node.d.ts.map +1 -0
  153. package/dist/execution/node.js +250 -0
  154. package/dist/execution/node.js.map +1 -0
  155. package/dist/execution/observer.d.ts +38 -0
  156. package/dist/execution/observer.d.ts.map +1 -0
  157. package/dist/execution/observer.js +111 -0
  158. package/dist/execution/observer.js.map +1 -0
  159. package/dist/execution/planner.d.ts +14 -0
  160. package/dist/execution/planner.d.ts.map +1 -0
  161. package/dist/execution/planner.js +43 -0
  162. package/dist/execution/planner.js.map +1 -0
  163. package/dist/execution/reducer.d.ts +19 -0
  164. package/dist/execution/reducer.d.ts.map +1 -0
  165. package/dist/execution/reducer.js +61 -0
  166. package/dist/execution/reducer.js.map +1 -0
  167. package/dist/execution/registry.d.ts +38 -0
  168. package/dist/execution/registry.d.ts.map +1 -0
  169. package/dist/execution/registry.js +63 -0
  170. package/dist/execution/registry.js.map +1 -0
  171. package/dist/execution/send-api.d.ts +24 -0
  172. package/dist/execution/send-api.d.ts.map +1 -0
  173. package/dist/execution/send-api.js +52 -0
  174. package/dist/execution/send-api.js.map +1 -0
  175. package/dist/execution/types.parallel.d.ts +61 -0
  176. package/dist/execution/types.parallel.d.ts.map +1 -0
  177. package/dist/execution/types.parallel.js +3 -0
  178. package/dist/execution/types.parallel.js.map +1 -0
  179. package/dist/execution/visualizer.d.ts +35 -0
  180. package/dist/execution/visualizer.d.ts.map +1 -0
  181. package/dist/execution/visualizer.js +131 -0
  182. package/dist/execution/visualizer.js.map +1 -0
  183. package/dist/index.d.ts +47 -0
  184. package/dist/index.d.ts.map +1 -0
  185. package/dist/index.js +78 -0
  186. package/dist/index.js.map +1 -0
  187. package/dist/interfaces/index.d.ts +487 -0
  188. package/dist/interfaces/index.d.ts.map +1 -0
  189. package/dist/interfaces/index.js +75 -0
  190. package/dist/interfaces/index.js.map +1 -0
  191. package/dist/modules/agenda/adapters/node-cron/index.d.ts +17 -0
  192. package/dist/modules/agenda/adapters/node-cron/index.d.ts.map +1 -0
  193. package/dist/modules/agenda/adapters/node-cron/index.js +30 -0
  194. package/dist/modules/agenda/adapters/node-cron/index.js.map +1 -0
  195. package/dist/modules/agenda/index.d.ts +63 -0
  196. package/dist/modules/agenda/index.d.ts.map +1 -0
  197. package/dist/modules/agenda/index.js +141 -0
  198. package/dist/modules/agenda/index.js.map +1 -0
  199. package/dist/modules/cli/index.d.ts +13 -0
  200. package/dist/modules/cli/index.d.ts.map +1 -0
  201. package/dist/modules/cli/index.js +672 -0
  202. package/dist/modules/cli/index.js.map +1 -0
  203. package/dist/modules/embedding/adapters/ai/index.d.ts +29 -0
  204. package/dist/modules/embedding/adapters/ai/index.d.ts.map +1 -0
  205. package/dist/modules/embedding/adapters/ai/index.js +58 -0
  206. package/dist/modules/embedding/adapters/ai/index.js.map +1 -0
  207. package/dist/modules/embedding/index.d.ts +36 -0
  208. package/dist/modules/embedding/index.d.ts.map +1 -0
  209. package/dist/modules/embedding/index.js +60 -0
  210. package/dist/modules/embedding/index.js.map +1 -0
  211. package/dist/modules/nlp/engine.d.ts +126 -0
  212. package/dist/modules/nlp/engine.d.ts.map +1 -0
  213. package/dist/modules/nlp/engine.js +299 -0
  214. package/dist/modules/nlp/engine.js.map +1 -0
  215. package/dist/modules/nlp/index.d.ts +27 -0
  216. package/dist/modules/nlp/index.d.ts.map +1 -0
  217. package/dist/modules/nlp/index.js +56 -0
  218. package/dist/modules/nlp/index.js.map +1 -0
  219. package/dist/persistence/index.d.ts +12 -0
  220. package/dist/persistence/index.d.ts.map +1 -0
  221. package/dist/persistence/index.js +24 -0
  222. package/dist/persistence/index.js.map +1 -0
  223. package/dist/persistence/neo4j/driver.d.ts +26 -0
  224. package/dist/persistence/neo4j/driver.d.ts.map +1 -0
  225. package/dist/persistence/neo4j/driver.js +64 -0
  226. package/dist/persistence/neo4j/driver.js.map +1 -0
  227. package/dist/persistence/neo4j/entity-store.d.ts +15 -0
  228. package/dist/persistence/neo4j/entity-store.d.ts.map +1 -0
  229. package/dist/persistence/neo4j/entity-store.js +136 -0
  230. package/dist/persistence/neo4j/entity-store.js.map +1 -0
  231. package/dist/persistence/neo4j/execution-tracer.d.ts +19 -0
  232. package/dist/persistence/neo4j/execution-tracer.d.ts.map +1 -0
  233. package/dist/persistence/neo4j/execution-tracer.js +166 -0
  234. package/dist/persistence/neo4j/execution-tracer.js.map +1 -0
  235. package/dist/persistence/neo4j/memory-adapter.d.ts +35 -0
  236. package/dist/persistence/neo4j/memory-adapter.d.ts.map +1 -0
  237. package/dist/persistence/neo4j/memory-adapter.js +252 -0
  238. package/dist/persistence/neo4j/memory-adapter.js.map +1 -0
  239. package/dist/persistence/neo4j/petri-checkpoint-adapter.d.ts +22 -0
  240. package/dist/persistence/neo4j/petri-checkpoint-adapter.d.ts.map +1 -0
  241. package/dist/persistence/neo4j/petri-checkpoint-adapter.js +141 -0
  242. package/dist/persistence/neo4j/petri-checkpoint-adapter.js.map +1 -0
  243. package/dist/pipeline/agent-pipeline.d.ts +99 -0
  244. package/dist/pipeline/agent-pipeline.d.ts.map +1 -0
  245. package/dist/pipeline/agent-pipeline.js +356 -0
  246. package/dist/pipeline/agent-pipeline.js.map +1 -0
  247. package/dist/routing/checkpoint-adapter.d.ts +30 -0
  248. package/dist/routing/checkpoint-adapter.d.ts.map +1 -0
  249. package/dist/routing/checkpoint-adapter.js +83 -0
  250. package/dist/routing/checkpoint-adapter.js.map +1 -0
  251. package/dist/routing/documentation-generator.d.ts +47 -0
  252. package/dist/routing/documentation-generator.d.ts.map +1 -0
  253. package/dist/routing/documentation-generator.js +320 -0
  254. package/dist/routing/documentation-generator.js.map +1 -0
  255. package/dist/routing/index.d.ts +38 -0
  256. package/dist/routing/index.d.ts.map +1 -0
  257. package/dist/routing/index.js +375 -0
  258. package/dist/routing/index.js.map +1 -0
  259. package/dist/routing/intent-classifier.d.ts +206 -0
  260. package/dist/routing/intent-classifier.d.ts.map +1 -0
  261. package/dist/routing/intent-classifier.js +267 -0
  262. package/dist/routing/intent-classifier.js.map +1 -0
  263. package/dist/routing/matrix.d.ts +6 -0
  264. package/dist/routing/matrix.d.ts.map +1 -0
  265. package/dist/routing/matrix.js +131 -0
  266. package/dist/routing/matrix.js.map +1 -0
  267. package/dist/routing/orchestrator.d.ts +87 -0
  268. package/dist/routing/orchestrator.d.ts.map +1 -0
  269. package/dist/routing/orchestrator.js +425 -0
  270. package/dist/routing/orchestrator.js.map +1 -0
  271. package/dist/routing/postgres-checkpoint-adapter.d.ts +32 -0
  272. package/dist/routing/postgres-checkpoint-adapter.d.ts.map +1 -0
  273. package/dist/routing/postgres-checkpoint-adapter.js +167 -0
  274. package/dist/routing/postgres-checkpoint-adapter.js.map +1 -0
  275. package/dist/routing/redis-checkpoint-adapter.d.ts +34 -0
  276. package/dist/routing/redis-checkpoint-adapter.d.ts.map +1 -0
  277. package/dist/routing/redis-checkpoint-adapter.js +170 -0
  278. package/dist/routing/redis-checkpoint-adapter.js.map +1 -0
  279. package/dist/routing/types.d.ts +49 -0
  280. package/dist/routing/types.d.ts.map +1 -0
  281. package/dist/routing/types.js +3 -0
  282. package/dist/routing/types.js.map +1 -0
  283. package/dist/types/agent.d.ts +289 -0
  284. package/dist/types/agent.d.ts.map +1 -0
  285. package/dist/types/agent.js +78 -0
  286. package/dist/types/agent.js.map +1 -0
  287. package/dist/types/index.d.ts +343 -0
  288. package/dist/types/index.d.ts.map +1 -0
  289. package/dist/types/index.js +3 -0
  290. package/dist/types/index.js.map +1 -0
  291. package/dist/utils/generate-action-schema.d.ts +4 -0
  292. package/dist/utils/generate-action-schema.d.ts.map +1 -0
  293. package/dist/utils/generate-action-schema.js +46 -0
  294. package/dist/utils/generate-action-schema.js.map +1 -0
  295. package/dist/utils/header-builder.d.ts +12 -0
  296. package/dist/utils/header-builder.d.ts.map +1 -0
  297. package/dist/utils/header-builder.js +35 -0
  298. package/dist/utils/header-builder.js.map +1 -0
  299. package/dist/utils/logger.d.ts +27 -0
  300. package/dist/utils/logger.d.ts.map +1 -0
  301. package/dist/utils/logger.js +45 -0
  302. package/dist/utils/logger.js.map +1 -0
  303. package/docs/.gitbook/assets/image (1).png +0 -0
  304. package/docs/.gitbook/assets/image (2).png +0 -0
  305. package/docs/.gitbook/assets/image (3).png +0 -0
  306. package/docs/.gitbook/assets/image (4).png +0 -0
  307. package/docs/.gitbook/assets/image (5).png +0 -0
  308. package/docs/.gitbook/assets/image (6).png +0 -0
  309. package/docs/.gitbook/assets/image.png +0 -0
  310. package/docs/README.md +57 -0
  311. package/docs/SUMMARY.md +34 -0
  312. package/docs/cas-dusages.md +69 -0
  313. package/docs/cli/README.md +65 -0
  314. package/docs/concepts-cles.md +50 -0
  315. package/docs/core/architecture.md +87 -0
  316. package/docs/core/benchmark.md +59 -0
  317. package/docs/core/checkpoint.md +72 -0
  318. package/docs/core/documentation.md +55 -0
  319. package/docs/core/graphcontroller.md +63 -0
  320. package/docs/core/graphflow.md +137 -0
  321. package/docs/core/introduction.md +41 -0
  322. package/docs/core/les-evenements.md +95 -0
  323. package/docs/modules/agenda/README.md +63 -0
  324. package/docs/modules/agenda/interface-iagenda.md +170 -0
  325. package/docs/modules/agenda/les-adaptateurs/README.md +237 -0
  326. package/docs/modules/agenda/les-adaptateurs/nodecronadapter.md +91 -0
  327. package/docs/modules/introduction.md +55 -0
  328. package/docs/modules/les-adaptateurs.md +52 -0
  329. package/docs/modules/memoire/README.md +68 -0
  330. package/docs/modules/memoire/interface-imemory.md +183 -0
  331. package/docs/modules/memoire/les-adaptateurs/README.md +209 -0
  332. package/docs/modules/memoire/les-adaptateurs/inmemoryadapter.md +110 -0
  333. package/docs/modules/memoire/les-adaptateurs/meilisearchadapter.md +147 -0
  334. package/docs/modules/memoire/les-adaptateurs/redisadapter.md +212 -0
  335. package/docs/modules/nlp/README.md +44 -0
  336. package/docs/philosophie.md +51 -0
  337. package/docs/tutoriels/ajouter-des-conditions.md +150 -0
  338. package/docs/tutoriels/branching.md +194 -0
  339. package/docs/tutoriels/checkpoint-usage.md +99 -0
  340. package/docs/tutoriels/creer-agent-onchain.md +1041 -0
  341. package/docs/tutoriels/creer-un-agent.md +108 -0
  342. package/docs/tutoriels/creer-un-graphe-simple.md +92 -0
  343. package/docs/tutoriels/gerer-les-erreurs.md +124 -0
  344. package/docs/tutoriels/pour-commencer.md +73 -0
  345. package/docs/tutoriels/retry.md +166 -0
  346. package/execution/adapters/in-memory-checkpoint.ts +35 -0
  347. package/execution/compiler.ts +47 -0
  348. package/execution/controller.ts +84 -0
  349. package/execution/event-manager.ts +331 -0
  350. package/execution/index.ts +800 -0
  351. package/execution/logger.ts +70 -0
  352. package/execution/node.ts +315 -0
  353. package/execution/observer.ts +192 -0
  354. package/execution/planner.ts +40 -0
  355. package/execution/reducer.ts +73 -0
  356. package/execution/registry.ts +86 -0
  357. package/execution/send-api.ts +58 -0
  358. package/execution/types.parallel.ts +81 -0
  359. package/execution/visualizer.ts +158 -0
  360. package/index.ts +55 -465
  361. package/interfaces/index.ts +597 -0
  362. package/modules/agenda/adapters/node-cron/index.ts +25 -0
  363. package/modules/agenda/index.ts +146 -0
  364. package/modules/cli/index.ts +580 -0
  365. package/modules/embedding/adapters/ai/index.ts +42 -0
  366. package/modules/embedding/index.ts +45 -0
  367. package/modules/nlp/engine.ts +324 -0
  368. package/modules/nlp/index.ts +45 -0
  369. package/package.json +81 -9
  370. package/persistence/index.ts +27 -0
  371. package/persistence/neo4j/driver.ts +34 -0
  372. package/persistence/neo4j/entity-store.ts +141 -0
  373. package/persistence/neo4j/execution-tracer.ts +194 -0
  374. package/persistence/neo4j/memory-adapter.ts +281 -0
  375. package/persistence/neo4j/petri-checkpoint-adapter.ts +153 -0
  376. package/pipeline/agent-pipeline.ts +426 -0
  377. package/routing/checkpoint-adapter.ts +79 -0
  378. package/routing/documentation-generator.ts +358 -0
  379. package/routing/index.ts +459 -0
  380. package/routing/intent-classifier.ts +360 -0
  381. package/routing/matrix.ts +138 -0
  382. package/routing/orchestrator.ts +498 -0
  383. package/routing/patterns/data-extraction.json +79 -0
  384. package/routing/patterns/human-approval.json +64 -0
  385. package/routing/patterns/rag-search.json +68 -0
  386. package/routing/postgres-checkpoint-adapter.ts +172 -0
  387. package/routing/redis-checkpoint-adapter.ts +187 -0
  388. package/routing/types.ts +59 -0
  389. package/routing/web-server.ts +260 -0
  390. package/scripts/generate-petri-docs.ts +70 -0
  391. package/scripts/get-gmail-token.js +65 -0
  392. package/scripts/get-gmail-token.ts +65 -0
  393. package/test/agent/agent.test.ts +92 -0
  394. package/test/agent/clone.test.ts +143 -0
  395. package/test/agent/cognitive-handler.test.ts +78 -0
  396. package/test/agent/entity-store.test.ts +80 -0
  397. package/test/agent/generic-executor.test.ts +230 -0
  398. package/test/agent/handoff.test.ts +163 -0
  399. package/test/agent/llm-factory.test.ts +40 -0
  400. package/test/agent/orchestrator.test.ts +156 -0
  401. package/test/agent/registry.test.ts +97 -0
  402. package/test/agent/tools.test.ts +267 -0
  403. package/test/execution/checkpoint.test.ts +811 -0
  404. package/test/execution/controller.test.ts +236 -0
  405. package/test/execution/event-manager.test.ts +118 -0
  406. package/test/execution/index.test.ts +690 -0
  407. package/test/execution/node.test.ts +464 -0
  408. package/test/execution/observer.test.ts +393 -0
  409. package/test/execution/parallel.test.ts +135 -0
  410. package/test/execution/plan-llm-integration.test.ts +290 -0
  411. package/test/execution/plan-real-onchain.test.ts +226 -0
  412. package/test/execution/send-api.test.ts +121 -0
  413. package/test/modules/agenda/node-cron.test.ts +307 -0
  414. package/test/modules/cli/index.test.ts +125 -0
  415. package/test/persistence/neo4j-execution-tracer.test.ts +96 -0
  416. package/test/persistence/neo4j-memory-adapter.test.ts +107 -0
  417. package/test/persistence/neo4j-petri-checkpoint.test.ts +89 -0
  418. package/test/pipeline/agent-pipeline.test.ts +118 -0
  419. package/test/routing/checkpoint-persistence.test.ts +58 -0
  420. package/test/routing/documentation-generator.test.ts +76 -0
  421. package/test/routing/integration.test.ts +261 -0
  422. package/test/routing/intent-classifier.test.ts +102 -0
  423. package/test/routing/petri.test.ts +156 -0
  424. package/test/routing/real-llm.test.ts +260 -0
  425. package/test-petri-features.ts +218 -0
  426. package/test-pipeline-api.ts +163 -0
  427. package/tsconfig.json +30 -108
  428. package/types/agent.ts +296 -0
  429. package/types/index.ts +387 -0
  430. package/utils/generate-action-schema.ts +47 -0
  431. package/utils/header-builder.ts +40 -0
  432. package/utils/logger.ts +40 -0
  433. package/package copy.json +0 -21
  434. package/types.ts +0 -62
  435. package/utils/executor.ts +0 -42
@@ -0,0 +1,498 @@
1
+ import { PetriNet, TransitionResult, GuardLLMExecutor } from './index';
2
+ import { TransitionAction } from './types';
3
+ import { ToolRegistry } from '../execution/registry';
4
+ import { GraphFlow } from '../execution/index';
5
+ import { z } from 'zod';
6
+ import { compilePlan } from '../execution/compiler';
7
+ import logger from '../utils/logger';
8
+ import { IntentClassifier } from './intent-classifier';
9
+ import { IPetriCheckpointAdapter } from './checkpoint-adapter';
10
+
11
+ export interface Session {
12
+ id: string;
13
+ petriNet: PetriNet;
14
+ context: Record<string, any>;
15
+ history: string[];
16
+ createdAt: number;
17
+ traceId?: string;
18
+ clarificationQuestion?: string;
19
+ inFallbackMode?: boolean;
20
+ fallbackContext?: {
21
+ conversationHistory: string[];
22
+ lastFallbackResponse?: string;
23
+ };
24
+ }
25
+
26
+ export type FallbackLLM = (
27
+ message: string,
28
+ session: Session,
29
+ toolRegistry?: ToolRegistry
30
+ ) => Promise<{ response: string; shouldReenterPetri?: boolean; reinterpretMessage?: string }>;
31
+
32
+ export interface IntentResult {
33
+ intent: string;
34
+ confidence: number;
35
+ entities: Record<string, any>;
36
+ intents?: Array<{ intent: string; confidence: number; entities?: Record<string, any> }>;
37
+ }
38
+
39
+ export type IntentClassifierFn = (
40
+ message: string,
41
+ context?: { turnHistory?: string[] }
42
+ ) => Promise<IntentResult>;
43
+
44
+ export class CortexFlowOrchestrator {
45
+ private petriNet: PetriNet;
46
+ private toolRegistry: ToolRegistry;
47
+ private sessions: Map<string, Session> = new Map();
48
+ private intentClassifier?: IntentClassifierFn;
49
+ private intentClassifierInstance?: IntentClassifier;
50
+ private llmCall?: (prompt: string) => Promise<string>;
51
+ private petriCheckpointAdapter?: IPetriCheckpointAdapter;
52
+ private fallbackLLM?: FallbackLLM;
53
+ private confidenceThreshold: number = 0.6;
54
+
55
+ constructor(name: string, toolRegistry?: ToolRegistry) {
56
+ this.petriNet = new PetriNet(name);
57
+ this.toolRegistry = toolRegistry || new ToolRegistry();
58
+ }
59
+
60
+ setFallbackLLM(fn: FallbackLLM): void {
61
+ this.fallbackLLM = fn;
62
+ }
63
+
64
+ setConfidenceThreshold(threshold: number): void {
65
+ this.confidenceThreshold = threshold;
66
+ }
67
+
68
+ getConfidenceThreshold(): number {
69
+ return this.confidenceThreshold;
70
+ }
71
+
72
+ get petri(): PetriNet {
73
+ return this.petriNet;
74
+ }
75
+
76
+ setPetriCheckpointAdapter(adapter: IPetriCheckpointAdapter): void {
77
+ this.petriCheckpointAdapter = adapter;
78
+ }
79
+
80
+ async savePetriState(sessionId: string): Promise<string | null> {
81
+ const session = this.sessions.get(sessionId);
82
+ if (!session || !this.petriCheckpointAdapter) return null;
83
+ try {
84
+ const checkpointId = await this.petriCheckpointAdapter.save(session.petriNet, session);
85
+ logger.info({ sessionId, checkpointId }, 'Petri state saved');
86
+ return checkpointId;
87
+ } catch (error) {
88
+ logger.error({ sessionId, error }, 'Failed to save Petri state');
89
+ return null;
90
+ }
91
+ }
92
+
93
+ async restorePetriState(checkpointId: string): Promise<string | null> {
94
+ if (!this.petriCheckpointAdapter) return null;
95
+ try {
96
+ const result = await this.petriCheckpointAdapter.load(checkpointId);
97
+ if (!result) return null;
98
+ const { net, session: restoredSession } = result;
99
+ if (restoredSession) {
100
+ this.sessions.set(restoredSession.id, restoredSession);
101
+ return restoredSession.id;
102
+ }
103
+ const newSessionId = `session_${Date.now()}`;
104
+ const newSession: Session = {
105
+ id: newSessionId,
106
+ petriNet: net,
107
+ context: {},
108
+ history: [],
109
+ createdAt: Date.now(),
110
+ traceId: `trace_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
111
+ };
112
+ this.sessions.set(newSessionId, newSession);
113
+ return newSessionId;
114
+ } catch (error) {
115
+ logger.error({ checkpointId, error }, 'Failed to restore Petri state');
116
+ return null;
117
+ }
118
+ }
119
+
120
+ async listPetriCheckpoints() {
121
+ if (!this.petriCheckpointAdapter) return [];
122
+ return this.petriCheckpointAdapter.list();
123
+ }
124
+
125
+ setIntentClassifier(classifier: IntentClassifierFn, instance?: IntentClassifier): void {
126
+ this.intentClassifier = classifier;
127
+ this.intentClassifierInstance = instance;
128
+ }
129
+
130
+ setLLMCall(llmCall: (prompt: string) => Promise<string>): void {
131
+ this.llmCall = llmCall;
132
+ this.petriNet.setLLMExecutor(async (prompt, ctx) => {
133
+ const result = await llmCall(
134
+ `You are a guard evaluator. Context: ${JSON.stringify(ctx)}. ${prompt} Answer only 'yes' or 'no'.`
135
+ );
136
+ return result.toLowerCase().includes('yes');
137
+ });
138
+ }
139
+
140
+ async classifyIntent(message: string, sessionId?: string): Promise<IntentResult> {
141
+ if (!this.intentClassifier) {
142
+ return { intent: 'UNKNOWN', confidence: 0, entities: {} };
143
+ }
144
+ const session = sessionId ? this.sessions.get(sessionId) : undefined;
145
+ const turnHistory = session?.history || [];
146
+ return this.intentClassifier(message, { turnHistory });
147
+ }
148
+
149
+ startSession(sessionId?: string): string {
150
+ const id = sessionId || `session_${Date.now()}`;
151
+ const traceId = `trace_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
152
+ const net = new PetriNet(this.petriNet.name);
153
+ net.places = new Map(this.petriNet.places);
154
+ net.transitions = new Map(this.petriNet.transitions);
155
+ net.state = {
156
+ marking: new Map(
157
+ Array.from(this.petriNet.state.marking.entries()).map(([k, v]) => [
158
+ k,
159
+ v.map(t => ({ ...t })),
160
+ ])
161
+ ),
162
+ history: [],
163
+ };
164
+ this.sessions.set(id, {
165
+ id,
166
+ petriNet: net,
167
+ context: {},
168
+ history: [],
169
+ createdAt: Date.now(),
170
+ traceId,
171
+ });
172
+ logger.info({ sessionId: id, traceId }, 'Session started');
173
+ return id;
174
+ }
175
+
176
+ getSession(sessionId: string): Session | undefined {
177
+ return this.sessions.get(sessionId);
178
+ }
179
+
180
+ async fire(transitionId: string, sessionId: string, tokenData?: Record<string, any>): Promise<TransitionResult & { actionResult?: any }> {
181
+ const session = this.sessions.get(sessionId);
182
+ if (!session) throw new Error(`Session ${sessionId} not found`);
183
+ const log = logger.child({ sessionId, traceId: session.traceId });
184
+ const transition = session.petriNet.transitions.get(transitionId);
185
+ if (!transition) throw new Error(`Transition ${transitionId} not found`);
186
+ log.info({ transitionId }, 'Firing transition');
187
+ const result = await session.petriNet.fireTransition(transitionId, tokenData);
188
+ if (!result.success) {
189
+ log.warn({ transitionId, result }, 'Transition failed');
190
+ return result as any;
191
+ }
192
+ if (transition.action) {
193
+ try {
194
+ log.info({ transitionId, actionType: (transition as any).action?.type }, 'Executing action');
195
+ const actionResult = await this.executeAction(transition.action, tokenData || session.context, session);
196
+ log.info({ transitionId, actionResult }, 'Action completed');
197
+ return { ...result, actionResult };
198
+ } catch (error) {
199
+ log.error({ transitionId, error }, 'Action failed');
200
+ return { ...result, success: false, error: (error as Error).message, actionResult: undefined } as any;
201
+ }
202
+ }
203
+ return result as any;
204
+ }
205
+
206
+ private async executeAction(action: TransitionAction, context: Record<string, any>, session: Session): Promise<any> {
207
+ if (action.type === 'graphflow') return this.executeGraphFlowAction(action, context, session);
208
+ if (action.type === 'dynamic') return this.executeDynamicAction(action, context, session);
209
+ return undefined;
210
+ }
211
+
212
+ private async executeGraphFlowAction(action: TransitionAction, context: Record<string, any>, session: Session): Promise<any> {
213
+ if (!action.name) throw new Error('GraphFlow action missing tool name');
214
+ const tool = this.toolRegistry.get(action.name);
215
+ if (!tool) throw new Error(`Tool ${action.name} not registered`);
216
+ const flowContext = action.contextMapper ? action.contextMapper(context) : context;
217
+ const timeoutMs = (action as any).timeout || 30000;
218
+ const maxSteps = (action as any).maxSteps || 10;
219
+ let steps = 0;
220
+ const originalExecute = tool.graph.execute.bind(tool.graph);
221
+ const wrappedExecute = async (startNode: string, ctx: any) => {
222
+ steps++;
223
+ if (steps > maxSteps) throw new Error(`GraphFlow exceeded max steps: ${maxSteps}`);
224
+ return originalExecute(startNode, ctx);
225
+ };
226
+ const timeoutPromise = new Promise<never>((_, reject) => {
227
+ setTimeout(() => reject(new Error(`GraphFlow timeout after ${timeoutMs}ms`)), timeoutMs);
228
+ });
229
+ try {
230
+ const result = await Promise.race([wrappedExecute(tool.startNode, flowContext), timeoutPromise]);
231
+ session.context = { ...session.context, ...result };
232
+ return result;
233
+ } catch (error) {
234
+ session.context = { ...session.context, lastError: (error as Error).message };
235
+ throw error;
236
+ }
237
+ }
238
+
239
+ private async executeDynamicAction(action: TransitionAction, context: Record<string, any>, session: Session): Promise<any> {
240
+ if (!this.llmCall) throw new Error('LLM call not configured for dynamic action');
241
+ if (!action.prompt) throw new Error('Dynamic action missing prompt');
242
+ const maxSteps = action.maxSteps || 5;
243
+ const plan = await this.generateDynamicPlan(action.prompt, context, maxSteps, session.traceId);
244
+ const { graph, startNode } = this.compilePlan(plan);
245
+ const timeoutMs = (action as any).timeout || 30000;
246
+ let steps = 0;
247
+ const originalExecute = graph.execute.bind(graph);
248
+ const wrappedExecute = async (startNode: string, ctx: any) => {
249
+ steps++;
250
+ if (steps > maxSteps) throw new Error(`Dynamic plan exceeded max steps: ${maxSteps}`);
251
+ return originalExecute(startNode, ctx);
252
+ };
253
+ const timeoutPromise = new Promise<never>((_, reject) => {
254
+ setTimeout(() => reject(new Error(`Dynamic action timeout after ${timeoutMs}ms`)), timeoutMs);
255
+ });
256
+ try {
257
+ const result = await Promise.race([wrappedExecute(startNode, context), timeoutPromise]);
258
+ session.context = { ...session.context, ...result };
259
+ return result;
260
+ } catch (error) {
261
+ session.context = { ...session.context, lastError: (error as Error).message };
262
+ logger.warn({ traceId: session.traceId, error }, 'Dynamic action failed');
263
+ throw error;
264
+ }
265
+ }
266
+
267
+ private async generateDynamicPlan(prompt: string, context: Record<string, any>, maxSteps: number, traceId?: string): Promise<{ goal: string; steps: { node: string; params?: any }[] }> {
268
+ if (!this.llmCall) throw new Error('LLM call not configured');
269
+ const availableTools = this.toolRegistry.list();
270
+ const log = logger.child({ traceId });
271
+ const llmPrompt = `You are a workflow planner. Generate a structured plan as JSON with "goal" (string) and "steps" (array of { node: string, params?: Record<string, any> }).
272
+ Only use tools from the available list. Max ${maxSteps} steps.
273
+
274
+ Available tools:
275
+ ${availableTools.map(t => `- ${t.name}: ${t.description}`).join('\n')}
276
+
277
+ User intent: ${prompt}
278
+ Context: ${JSON.stringify(context)}
279
+
280
+ Respond with valid JSON only.`;
281
+ const response = await this.llmCall(llmPrompt);
282
+ const rawPlan = JSON.parse(response);
283
+ const PlanSchema = z.object({
284
+ goal: z.string(),
285
+ steps: z.array(
286
+ z.object({
287
+ node: z.string(),
288
+ params: z.record(z.string(), z.unknown()).optional(),
289
+ })
290
+ ),
291
+ });
292
+ try {
293
+ const plan = PlanSchema.parse(rawPlan);
294
+ if (plan.steps.length > maxSteps) throw new Error(`Plan exceeds max steps: ${plan.steps.length} > ${maxSteps}`);
295
+ log.info({ plan }, 'Dynamic plan validated successfully');
296
+ return { goal: plan.goal || prompt, steps: plan.steps };
297
+ } catch (error) {
298
+ log.warn({ rawPlan, error, prompt }, 'Dynamic plan rejected by Zod validation');
299
+ throw error;
300
+ }
301
+ }
302
+
303
+ private compilePlan(plan: { goal: string; steps: { node: string; params?: any }[] }): { graph: GraphFlow<any>; startNode: string } {
304
+ return compilePlan(plan, this.toolRegistry);
305
+ }
306
+
307
+ async orchestrate(message: string, sessionId?: string): Promise<{
308
+ intent: IntentResult;
309
+ transitionResult?: TransitionResult & { actionResult?: any };
310
+ sessionId: string;
311
+ needsClarification?: boolean;
312
+ clarificationQuestion?: string;
313
+ fallbackResponse?: string;
314
+ shouldReenterPetri?: boolean;
315
+ }> {
316
+ const session = sessionId ? this.sessions.get(sessionId) : undefined;
317
+ const resolvedSessionId = session ? session.id : this.startSession(sessionId);
318
+ const sessionObj = this.sessions.get(resolvedSessionId)!;
319
+ const log = logger.child({ sessionId: resolvedSessionId, traceId: sessionObj.traceId });
320
+ log.info({ message }, 'Orchestration started');
321
+
322
+ if (sessionObj.inFallbackMode && this.fallbackLLM) {
323
+ return this.handleFallbackMode(message, resolvedSessionId, sessionObj, log);
324
+ }
325
+
326
+ const intent = await this.classifyIntent(message, resolvedSessionId);
327
+ sessionObj.history.push(message);
328
+ log.info({ intent }, 'Intent classified');
329
+
330
+ const threshold = this.confidenceThreshold;
331
+ if (intent.confidence < threshold || intent.intent === 'UNKNOWN') {
332
+ log.warn({ intent, threshold }, 'Low confidence or UNKNOWN, entering fallback mode');
333
+
334
+ if (this.fallbackLLM) {
335
+ return this.enterFallbackMode(message, resolvedSessionId, sessionObj, intent, log);
336
+ }
337
+
338
+ let clarificationQuestion: string | undefined;
339
+ if (this.intentClassifierInstance) {
340
+ try {
341
+ clarificationQuestion = await this.intentClassifierInstance.generateClarification(message);
342
+ sessionObj.clarificationQuestion = clarificationQuestion;
343
+ } catch (error) {
344
+ log.warn({ error }, 'Failed to generate clarification question');
345
+ }
346
+ }
347
+ return { intent, sessionId: resolvedSessionId, needsClarification: true, clarificationQuestion };
348
+ }
349
+
350
+ let intentsToExecute = intent.intents && intent.intents.length > 0
351
+ ? [...intent.intents]
352
+ : [];
353
+
354
+ const mainIntent = { intent: intent.intent, confidence: intent.confidence, entities: intent.entities };
355
+ if (!intentsToExecute.some(i => i.intent === mainIntent.intent)) {
356
+ intentsToExecute.unshift(mainIntent);
357
+ }
358
+
359
+ const results: Array<TransitionResult & { actionResult?: any }> = [];
360
+
361
+ for (let i = 0; i < intentsToExecute.length; i++) {
362
+ const subIntent = intentsToExecute[i];
363
+
364
+ if (i > 0) {
365
+ log.info('Resetting Petri net for next sub-intent');
366
+ sessionObj.petriNet.state.marking.clear();
367
+ sessionObj.petriNet.state.marking.set('idle', [{
368
+ id: `reset_${Date.now()}`,
369
+ data: { resetForMultiIntent: true },
370
+ createdAt: Date.now(),
371
+ }]);
372
+ sessionObj.petriNet.state.history = [];
373
+ }
374
+
375
+ const enabledTransitions = sessionObj.petriNet.getEnabledTransitions({
376
+ intent: subIntent.intent,
377
+ confidence: subIntent.confidence,
378
+ ...(subIntent.entities || {}),
379
+ });
380
+
381
+ if (enabledTransitions.length === 0) {
382
+ log.warn({ subIntent }, 'No enabled transitions for sub-intent');
383
+
384
+ if (this.fallbackLLM && intentsToExecute.length === 1) {
385
+ return this.enterFallbackMode(message, resolvedSessionId, sessionObj, intent, log);
386
+ }
387
+
388
+ if (intentsToExecute.length === 1) {
389
+ let clarificationQuestion: string | undefined;
390
+ if (this.intentClassifierInstance) {
391
+ try {
392
+ clarificationQuestion = await this.intentClassifierInstance.generateClarification(message);
393
+ sessionObj.clarificationQuestion = clarificationQuestion;
394
+ } catch (error) {
395
+ log.warn({ error }, 'Failed to generate clarification question');
396
+ }
397
+ }
398
+ return { intent, sessionId: resolvedSessionId, needsClarification: true, clarificationQuestion };
399
+ }
400
+ continue;
401
+ }
402
+
403
+ const transitionId = enabledTransitions[0];
404
+ log.info({ transitionId, subIntent }, 'Firing enabled transition for sub-intent');
405
+ const result = await this.fire(transitionId, resolvedSessionId, {
406
+ intent: subIntent.intent,
407
+ ...(subIntent.entities || {}),
408
+ traceId: sessionObj.traceId,
409
+ });
410
+ results.push(result);
411
+ log.info({ result }, 'Sub-intent transition completed');
412
+ }
413
+
414
+ log.info({ results }, 'Orchestration completed');
415
+ return {
416
+ intent,
417
+ transitionResult: results.length > 0 ? results[results.length - 1] : undefined,
418
+ sessionId: resolvedSessionId,
419
+ needsClarification: false,
420
+ };
421
+ }
422
+
423
+ private async enterFallbackMode(
424
+ message: string,
425
+ sessionId: string,
426
+ sessionObj: Session,
427
+ intent: IntentResult,
428
+ log: any
429
+ ): Promise<{
430
+ intent: IntentResult;
431
+ sessionId: string;
432
+ fallbackResponse?: string;
433
+ needsClarification?: boolean;
434
+ shouldReenterPetri?: boolean;
435
+ }> {
436
+ sessionObj.inFallbackMode = true;
437
+ if (!sessionObj.fallbackContext) {
438
+ sessionObj.fallbackContext = {
439
+ conversationHistory: [...sessionObj.history],
440
+ };
441
+ }
442
+
443
+ const fallbackResult = await this.fallbackLLM!(message, sessionObj, this.toolRegistry);
444
+
445
+ sessionObj.fallbackContext.lastFallbackResponse = fallbackResult.response;
446
+ sessionObj.fallbackContext.conversationHistory.push(message, fallbackResult.response);
447
+
448
+ log.info({ fallbackResult }, 'Fallback LLM responded');
449
+
450
+ if (fallbackResult.shouldReenterPetri && fallbackResult.reinterpretMessage) {
451
+ log.info({ reinterpretMessage: fallbackResult.reinterpretMessage }, 'Reinterpreting message via fallback');
452
+ sessionObj.inFallbackMode = false;
453
+ return this.orchestrate(fallbackResult.reinterpretMessage, sessionId);
454
+ }
455
+
456
+ return {
457
+ intent,
458
+ sessionId,
459
+ fallbackResponse: fallbackResult.response,
460
+ shouldReenterPetri: false,
461
+ };
462
+ }
463
+
464
+ private async handleFallbackMode(
465
+ message: string,
466
+ sessionId: string,
467
+ sessionObj: Session,
468
+ log: any
469
+ ): Promise<{
470
+ intent: IntentResult;
471
+ sessionId: string;
472
+ fallbackResponse?: string;
473
+ needsClarification?: boolean;
474
+ shouldReenterPetri?: boolean;
475
+ }> {
476
+ const intent: IntentResult = { intent: 'UNKNOWN', confidence: 0, entities: {} };
477
+
478
+ const fallbackResult = await this.fallbackLLM!(message, sessionObj, this.toolRegistry);
479
+
480
+ sessionObj.fallbackContext!.lastFallbackResponse = fallbackResult.response;
481
+ sessionObj.fallbackContext!.conversationHistory.push(message, fallbackResult.response);
482
+
483
+ log.info({ fallbackResult }, 'Fallback LLM continued');
484
+
485
+ if (fallbackResult.shouldReenterPetri && fallbackResult.reinterpretMessage) {
486
+ log.info({ reinterpretMessage: fallbackResult.reinterpretMessage }, 'Reinterpreting message via fallback');
487
+ sessionObj.inFallbackMode = false;
488
+ return this.orchestrate(fallbackResult.reinterpretMessage, sessionId);
489
+ }
490
+
491
+ return {
492
+ intent,
493
+ sessionId,
494
+ fallbackResponse: fallbackResult.response,
495
+ shouldReenterPetri: false,
496
+ };
497
+ }
498
+ }
@@ -0,0 +1,79 @@
1
+ {
2
+ "name": "data_extraction_workflow",
3
+ "description": "Extract structured data from unstructured input. Useful for form filling, information extraction from emails, or document processing.",
4
+ "places": [
5
+ { "id": "idle", "type": "initial", "tokens": [{ "id": "start", "data": {} }] },
6
+ { "id": "text_analyzed", "type": "normal", "tokens": [] },
7
+ { "id": "data_extracted", "type": "normal", "tokens": [] },
8
+ { "id": "validating", "type": "normal", "tokens": [] },
9
+ { "id": "validation_passed", "type": "normal", "tokens": [] },
10
+ { "id": "validation_failed", "type": "normal", "tokens": [] },
11
+ { "id": "completed", "type": "final", "tokens": [] },
12
+ { "id": "needs_review", "type": "final", "tokens": [] }
13
+ ],
14
+ "transitions": [
15
+ {
16
+ "id": "analyze_text",
17
+ "from": ["idle"],
18
+ "to": "text_analyzed",
19
+ "action": {
20
+ "type": "dynamic",
21
+ "prompt": "Analyze the input text and identify key information to extract based on the required fields.",
22
+ "maxSteps": 2
23
+ }
24
+ },
25
+ {
26
+ "id": "extract_data",
27
+ "from": ["text_analyzed"],
28
+ "to": "data_extracted",
29
+ "action": {
30
+ "type": "graphflow",
31
+ "name": "extraction_tool",
32
+ "contextMapper": "ctx => ({ text: ctx.originalText || ctx.input, schema: ctx.extractionSchema })"
33
+ }
34
+ },
35
+ {
36
+ "id": "validate_data",
37
+ "from": ["data_extracted"],
38
+ "to": "validating",
39
+ "action": {
40
+ "type": "dynamic",
41
+ "prompt": "Validate the extracted data against the required schema. Check for missing fields, format errors, and consistency.",
42
+ "maxSteps": 3
43
+ }
44
+ },
45
+ {
46
+ "id": "validation_passed",
47
+ "from": ["validating"],
48
+ "to": "validation_passed",
49
+ "guard": {
50
+ "type": "deterministic",
51
+ "condition": "context.validationResult?.isValid === true"
52
+ }
53
+ },
54
+ {
55
+ "id": "validation_failed",
56
+ "from": ["validating"],
57
+ "to": "validation_failed",
58
+ "guard": {
59
+ "type": "deterministic",
60
+ "condition": "context.validationResult?.isValid === false"
61
+ }
62
+ },
63
+ {
64
+ "id": "complete",
65
+ "from": ["validation_passed"],
66
+ "to": "completed"
67
+ },
68
+ {
69
+ "id": "flag_for_review",
70
+ "from": ["validation_failed"],
71
+ "to": "needs_review",
72
+ "action": {
73
+ "type": "dynamic",
74
+ "prompt": "Flag the extraction for human review. Explain what validation errors occurred.",
75
+ "maxSteps": 2
76
+ }
77
+ }
78
+ ]
79
+ }
@@ -0,0 +1,64 @@
1
+ {
2
+ "name": "human_approval_workflow",
3
+ "description": "Workflow with human approval step. Use this pattern when actions need human validation before execution.",
4
+ "places": [
5
+ { "id": "idle", "type": "initial", "tokens": [{ "id": "start", "data": {} }] },
6
+ { "id": "awaiting_approval", "type": "normal", "tokens": [] },
7
+ { "id": "approved", "type": "normal", "tokens": [] },
8
+ { "id": "rejected", "type": "normal", "tokens": [] },
9
+ { "id": "executing", "type": "normal", "tokens": [] },
10
+ { "id": "completed", "type": "final", "tokens": [] },
11
+ { "id": "cancelled", "type": "final", "tokens": [] }
12
+ ],
13
+ "transitions": [
14
+ {
15
+ "id": "request_approval",
16
+ "from": ["idle"],
17
+ "to": "awaiting_approval",
18
+ "description": "Request human approval for the pending action",
19
+ "action": {
20
+ "type": "dynamic",
21
+ "prompt": "Present the action to the user for approval. Explain what will happen.",
22
+ "maxSteps": 2
23
+ }
24
+ },
25
+ {
26
+ "id": "approve",
27
+ "from": ["awaiting_approval"],
28
+ "to": "approved",
29
+ "guard": {
30
+ "type": "deterministic",
31
+ "condition": "context.approved === true"
32
+ }
33
+ },
34
+ {
35
+ "id": "reject",
36
+ "from": ["awaiting_approval"],
37
+ "to": "rejected",
38
+ "guard": {
39
+ "type": "deterministic",
40
+ "condition": "context.approved === false"
41
+ }
42
+ },
43
+ {
44
+ "id": "execute_action",
45
+ "from": ["approved"],
46
+ "to": "executing",
47
+ "action": {
48
+ "type": "graphflow",
49
+ "name": "main_action",
50
+ "contextMapper": "ctx => ({ ...ctx, approved: undefined })"
51
+ }
52
+ },
53
+ {
54
+ "id": "complete",
55
+ "from": ["executing"],
56
+ "to": "completed"
57
+ },
58
+ {
59
+ "id": "cancel",
60
+ "from": ["rejected"],
61
+ "to": "cancelled"
62
+ }
63
+ ]
64
+ }