@robota-sdk/agent-core 3.0.0-beta.14 → 3.0.0-beta.16

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 (486) hide show
  1. package/README.md +2 -0
  2. package/dist/abstracts/abstract-agent.d.ts.map +1 -1
  3. package/dist/abstracts/abstract-agent.js.map +1 -1
  4. package/dist/abstracts/abstract-ai-provider.d.ts +8 -7
  5. package/dist/abstracts/abstract-ai-provider.d.ts.map +1 -1
  6. package/dist/abstracts/abstract-ai-provider.js +21 -15
  7. package/dist/abstracts/abstract-ai-provider.js.map +1 -1
  8. package/dist/abstracts/abstract-executor.d.ts.map +1 -1
  9. package/dist/abstracts/abstract-executor.js +20 -12
  10. package/dist/abstracts/abstract-executor.js.map +1 -1
  11. package/dist/abstracts/abstract-manager.d.ts.map +1 -1
  12. package/dist/abstracts/abstract-manager.js.map +1 -1
  13. package/dist/abstracts/abstract-module-events.d.ts +77 -0
  14. package/dist/abstracts/abstract-module-events.d.ts.map +1 -0
  15. package/dist/abstracts/abstract-module-events.js +8 -0
  16. package/dist/abstracts/abstract-module-events.js.map +1 -0
  17. package/dist/abstracts/abstract-module-types.d.ts +110 -0
  18. package/dist/abstracts/abstract-module-types.d.ts.map +1 -0
  19. package/dist/abstracts/abstract-module-types.js +20 -0
  20. package/dist/abstracts/abstract-module-types.js.map +1 -0
  21. package/dist/abstracts/abstract-module.d.ts +13 -312
  22. package/dist/abstracts/abstract-module.d.ts.map +1 -1
  23. package/dist/abstracts/abstract-module.js +137 -302
  24. package/dist/abstracts/abstract-module.js.map +1 -1
  25. package/dist/abstracts/abstract-module.test.d.ts +2 -0
  26. package/dist/abstracts/abstract-module.test.d.ts.map +1 -0
  27. package/dist/abstracts/abstract-module.test.js +150 -0
  28. package/dist/abstracts/abstract-module.test.js.map +1 -0
  29. package/dist/abstracts/abstract-plugin-types.d.ts +152 -0
  30. package/dist/abstracts/abstract-plugin-types.d.ts.map +1 -0
  31. package/dist/abstracts/abstract-plugin-types.js +29 -0
  32. package/dist/abstracts/abstract-plugin-types.js.map +1 -0
  33. package/dist/abstracts/abstract-plugin.d.ts +15 -304
  34. package/dist/abstracts/abstract-plugin.d.ts.map +1 -1
  35. package/dist/abstracts/abstract-plugin.js +28 -144
  36. package/dist/abstracts/abstract-plugin.js.map +1 -1
  37. package/dist/abstracts/abstract-tool.d.ts +1 -1
  38. package/dist/abstracts/abstract-tool.d.ts.map +1 -1
  39. package/dist/abstracts/abstract-tool.js +2 -2
  40. package/dist/abstracts/abstract-tool.js.map +1 -1
  41. package/dist/abstracts/abstract-workflow-converter.d.ts.map +1 -1
  42. package/dist/abstracts/abstract-workflow-converter.js +29 -20
  43. package/dist/abstracts/abstract-workflow-converter.js.map +1 -1
  44. package/dist/abstracts/abstract-workflow-converter.test.d.ts +2 -0
  45. package/dist/abstracts/abstract-workflow-converter.test.d.ts.map +1 -0
  46. package/dist/abstracts/abstract-workflow-converter.test.js +144 -0
  47. package/dist/abstracts/abstract-workflow-converter.test.js.map +1 -0
  48. package/dist/abstracts/abstract-workflow-validator-helpers.d.ts +37 -0
  49. package/dist/abstracts/abstract-workflow-validator-helpers.d.ts.map +1 -0
  50. package/dist/abstracts/abstract-workflow-validator-helpers.js +147 -0
  51. package/dist/abstracts/abstract-workflow-validator-helpers.js.map +1 -0
  52. package/dist/abstracts/abstract-workflow-validator-helpers.test.d.ts +2 -0
  53. package/dist/abstracts/abstract-workflow-validator-helpers.test.d.ts.map +1 -0
  54. package/dist/abstracts/abstract-workflow-validator-helpers.test.js +157 -0
  55. package/dist/abstracts/abstract-workflow-validator-helpers.test.js.map +1 -0
  56. package/dist/abstracts/abstract-workflow-validator.d.ts +18 -130
  57. package/dist/abstracts/abstract-workflow-validator.d.ts.map +1 -1
  58. package/dist/abstracts/abstract-workflow-validator.js +58 -326
  59. package/dist/abstracts/abstract-workflow-validator.js.map +1 -1
  60. package/dist/abstracts/abstract-workflow-validator.test.d.ts +2 -0
  61. package/dist/abstracts/abstract-workflow-validator.test.d.ts.map +1 -0
  62. package/dist/abstracts/abstract-workflow-validator.test.js +142 -0
  63. package/dist/abstracts/abstract-workflow-validator.test.js.map +1 -0
  64. package/dist/abstracts/index.d.ts +1 -0
  65. package/dist/abstracts/index.d.ts.map +1 -1
  66. package/dist/abstracts/index.js +3 -2
  67. package/dist/abstracts/index.js.map +1 -1
  68. package/dist/agents/constants.d.ts +1 -1
  69. package/dist/agents/constants.d.ts.map +1 -1
  70. package/dist/agents/constants.js +1 -1
  71. package/dist/agents/constants.js.map +1 -1
  72. package/dist/agents/index.js +1 -1
  73. package/dist/agents/index.js.map +1 -1
  74. package/dist/agents/robota.test.js +36 -36
  75. package/dist/agents/robota.test.js.map +1 -1
  76. package/dist/browser/index.d.ts +28 -1
  77. package/dist/browser/index.js +5 -5
  78. package/dist/context/index.d.ts +4 -0
  79. package/dist/context/index.d.ts.map +1 -0
  80. package/dist/context/index.js +2 -0
  81. package/dist/context/index.js.map +1 -0
  82. package/dist/context/models.d.ts +27 -0
  83. package/dist/context/models.d.ts.map +1 -0
  84. package/dist/context/models.js +76 -0
  85. package/dist/context/models.js.map +1 -0
  86. package/dist/context/models.test.d.ts +2 -0
  87. package/dist/context/models.test.d.ts.map +1 -0
  88. package/dist/context/models.test.js +51 -0
  89. package/dist/context/models.test.js.map +1 -0
  90. package/dist/context/types.d.ts +25 -0
  91. package/dist/context/types.d.ts.map +1 -0
  92. package/dist/context/types.js +8 -0
  93. package/dist/context/types.js.map +1 -0
  94. package/dist/core/robota-config-manager.d.ts +78 -0
  95. package/dist/core/robota-config-manager.d.ts.map +1 -0
  96. package/dist/core/robota-config-manager.js +216 -0
  97. package/dist/core/robota-config-manager.js.map +1 -0
  98. package/dist/core/robota-execution.d.ts +23 -0
  99. package/dist/core/robota-execution.d.ts.map +1 -0
  100. package/dist/core/robota-execution.js +81 -0
  101. package/dist/core/robota-execution.js.map +1 -0
  102. package/dist/core/robota-initializer.d.ts +37 -0
  103. package/dist/core/robota-initializer.d.ts.map +1 -0
  104. package/dist/core/robota-initializer.js +77 -0
  105. package/dist/core/robota-initializer.js.map +1 -0
  106. package/dist/core/robota-lifecycle.d.ts +53 -0
  107. package/dist/core/robota-lifecycle.d.ts.map +1 -0
  108. package/dist/core/robota-lifecycle.js +73 -0
  109. package/dist/core/robota-lifecycle.js.map +1 -0
  110. package/dist/core/robota-module-manager.d.ts +78 -0
  111. package/dist/core/robota-module-manager.d.ts.map +1 -0
  112. package/dist/core/robota-module-manager.js +114 -0
  113. package/dist/core/robota-module-manager.js.map +1 -0
  114. package/dist/core/robota-plugin-manager.d.ts +40 -0
  115. package/dist/core/robota-plugin-manager.d.ts.map +1 -0
  116. package/dist/core/robota-plugin-manager.js +71 -0
  117. package/dist/core/robota-plugin-manager.js.map +1 -0
  118. package/dist/core/robota.d.ts +56 -606
  119. package/dist/core/robota.d.ts.map +1 -1
  120. package/dist/core/robota.js +210 -1152
  121. package/dist/core/robota.js.map +1 -1
  122. package/dist/core/robota.test.d.ts +2 -0
  123. package/dist/core/robota.test.d.ts.map +1 -0
  124. package/dist/core/robota.test.js +353 -0
  125. package/dist/core/robota.test.js.map +1 -0
  126. package/dist/event-service/event-service.d.ts +61 -0
  127. package/dist/event-service/event-service.d.ts.map +1 -0
  128. package/dist/event-service/event-service.js +120 -0
  129. package/dist/event-service/event-service.js.map +1 -0
  130. package/dist/event-service/index.d.ts +6 -0
  131. package/dist/event-service/index.d.ts.map +1 -0
  132. package/dist/event-service/index.js +4 -0
  133. package/dist/event-service/index.js.map +1 -0
  134. package/dist/event-service/interfaces.d.ts +98 -0
  135. package/dist/event-service/interfaces.d.ts.map +1 -0
  136. package/dist/event-service/interfaces.js +8 -0
  137. package/dist/event-service/interfaces.js.map +1 -0
  138. package/dist/event-service/task-events.d.ts +6 -0
  139. package/dist/event-service/task-events.d.ts.map +1 -0
  140. package/dist/event-service/task-events.js +6 -0
  141. package/dist/event-service/task-events.js.map +1 -0
  142. package/dist/event-service/user-events.d.ts +7 -0
  143. package/dist/event-service/user-events.d.ts.map +1 -0
  144. package/dist/event-service/user-events.js +6 -0
  145. package/dist/event-service/user-events.js.map +1 -0
  146. package/dist/executors/local-executor.d.ts +2 -2
  147. package/dist/executors/local-executor.d.ts.map +1 -1
  148. package/dist/executors/local-executor.js +7 -7
  149. package/dist/executors/local-executor.js.map +1 -1
  150. package/dist/executors/local-executor.test.js +16 -16
  151. package/dist/executors/local-executor.test.js.map +1 -1
  152. package/dist/hooks/hook-runner.d.ts +20 -0
  153. package/dist/hooks/hook-runner.d.ts.map +1 -0
  154. package/dist/hooks/hook-runner.js +95 -0
  155. package/dist/hooks/hook-runner.js.map +1 -0
  156. package/dist/hooks/index.d.ts +3 -0
  157. package/dist/hooks/index.d.ts.map +1 -0
  158. package/dist/hooks/index.js +3 -0
  159. package/dist/hooks/index.js.map +1 -0
  160. package/dist/hooks/types.d.ts +40 -0
  161. package/dist/hooks/types.d.ts.map +1 -0
  162. package/dist/hooks/types.js +5 -0
  163. package/dist/hooks/types.js.map +1 -0
  164. package/dist/index.d.ts +49 -75
  165. package/dist/index.d.ts.map +1 -1
  166. package/dist/index.js +26 -71
  167. package/dist/index.js.map +1 -1
  168. package/dist/interfaces/agent.d.ts +3 -2
  169. package/dist/interfaces/agent.d.ts.map +1 -1
  170. package/dist/interfaces/cache.d.ts +64 -0
  171. package/dist/interfaces/cache.d.ts.map +1 -0
  172. package/dist/interfaces/cache.js +2 -0
  173. package/dist/interfaces/cache.js.map +1 -0
  174. package/dist/interfaces/event-service.d.ts +4 -75
  175. package/dist/interfaces/event-service.d.ts.map +1 -1
  176. package/dist/interfaces/executor.d.ts.map +1 -1
  177. package/dist/interfaces/history-module.d.ts.map +1 -1
  178. package/dist/interfaces/index.d.ts +12 -9
  179. package/dist/interfaces/index.d.ts.map +1 -1
  180. package/dist/interfaces/index.js +2 -1
  181. package/dist/interfaces/index.js.map +1 -1
  182. package/dist/interfaces/manager.d.ts.map +1 -1
  183. package/dist/interfaces/media-provider.d.ts +86 -0
  184. package/dist/interfaces/media-provider.d.ts.map +1 -0
  185. package/dist/interfaces/media-provider.js +13 -0
  186. package/dist/interfaces/media-provider.js.map +1 -0
  187. package/dist/interfaces/messages.d.ts +23 -1
  188. package/dist/interfaces/messages.d.ts.map +1 -1
  189. package/dist/interfaces/messages.js.map +1 -1
  190. package/dist/interfaces/progress-reporting.d.ts.map +1 -1
  191. package/dist/interfaces/progress-reporting.js +1 -3
  192. package/dist/interfaces/progress-reporting.js.map +1 -1
  193. package/dist/interfaces/provider.d.ts +12 -1
  194. package/dist/interfaces/provider.d.ts.map +1 -1
  195. package/dist/interfaces/service.d.ts.map +1 -1
  196. package/dist/interfaces/tool.d.ts +1 -0
  197. package/dist/interfaces/tool.d.ts.map +1 -1
  198. package/dist/interfaces/types.d.ts.map +1 -1
  199. package/dist/interfaces/types.js +6 -6
  200. package/dist/interfaces/types.js.map +1 -1
  201. package/dist/interfaces/workflow-converter.d.ts.map +1 -1
  202. package/dist/interfaces/workflow-validator.d.ts.map +1 -1
  203. package/dist/interfaces/workflow-validator.js.map +1 -1
  204. package/dist/managers/agent-factory.d.ts.map +1 -1
  205. package/dist/managers/agent-factory.js +24 -16
  206. package/dist/managers/agent-factory.js.map +1 -1
  207. package/dist/managers/agent-factory.test.js +35 -25
  208. package/dist/managers/agent-factory.test.js.map +1 -1
  209. package/dist/managers/agent-templates.d.ts.map +1 -1
  210. package/dist/managers/agent-templates.js +22 -10
  211. package/dist/managers/agent-templates.js.map +1 -1
  212. package/dist/managers/agent-templates.test.d.ts +2 -0
  213. package/dist/managers/agent-templates.test.d.ts.map +1 -0
  214. package/dist/managers/agent-templates.test.js +175 -0
  215. package/dist/managers/agent-templates.test.js.map +1 -0
  216. package/dist/managers/ai-provider-manager.d.ts.map +1 -1
  217. package/dist/managers/ai-provider-manager.js +8 -10
  218. package/dist/managers/ai-provider-manager.js.map +1 -1
  219. package/dist/managers/ai-provider-manager.test.d.ts +2 -0
  220. package/dist/managers/ai-provider-manager.test.d.ts.map +1 -0
  221. package/dist/managers/ai-provider-manager.test.js +327 -0
  222. package/dist/managers/ai-provider-manager.test.js.map +1 -0
  223. package/dist/managers/conversation-history-manager.d.ts +13 -425
  224. package/dist/managers/conversation-history-manager.d.ts.map +1 -1
  225. package/dist/managers/conversation-history-manager.js +21 -537
  226. package/dist/managers/conversation-history-manager.js.map +1 -1
  227. package/dist/managers/conversation-history-manager.test.js +82 -43
  228. package/dist/managers/conversation-history-manager.test.js.map +1 -1
  229. package/dist/managers/conversation-message-factory.d.ts +40 -0
  230. package/dist/managers/conversation-message-factory.d.ts.map +1 -0
  231. package/dist/managers/conversation-message-factory.js +66 -0
  232. package/dist/managers/conversation-message-factory.js.map +1 -0
  233. package/dist/managers/conversation-message-factory.test.d.ts +2 -0
  234. package/dist/managers/conversation-message-factory.test.d.ts.map +1 -0
  235. package/dist/managers/conversation-message-factory.test.js +95 -0
  236. package/dist/managers/conversation-message-factory.test.js.map +1 -0
  237. package/dist/managers/conversation-session.d.ts +90 -0
  238. package/dist/managers/conversation-session.d.ts.map +1 -0
  239. package/dist/managers/conversation-session.js +177 -0
  240. package/dist/managers/conversation-session.js.map +1 -0
  241. package/dist/managers/index.d.ts +2 -2
  242. package/dist/managers/index.d.ts.map +1 -1
  243. package/dist/managers/index.js +1 -1
  244. package/dist/managers/index.js.map +1 -1
  245. package/dist/managers/module-registry-validation.d.ts +38 -0
  246. package/dist/managers/module-registry-validation.d.ts.map +1 -0
  247. package/dist/managers/module-registry-validation.js +100 -0
  248. package/dist/managers/module-registry-validation.js.map +1 -0
  249. package/dist/managers/module-registry-validation.test.d.ts +2 -0
  250. package/dist/managers/module-registry-validation.test.d.ts.map +1 -0
  251. package/dist/managers/module-registry-validation.test.js +144 -0
  252. package/dist/managers/module-registry-validation.test.js.map +1 -0
  253. package/dist/managers/module-registry.d.ts +13 -111
  254. package/dist/managers/module-registry.d.ts.map +1 -1
  255. package/dist/managers/module-registry.js +74 -344
  256. package/dist/managers/module-registry.js.map +1 -1
  257. package/dist/managers/module-type-registry-helpers.d.ts +34 -0
  258. package/dist/managers/module-type-registry-helpers.d.ts.map +1 -0
  259. package/dist/managers/module-type-registry-helpers.js +255 -0
  260. package/dist/managers/module-type-registry-helpers.js.map +1 -0
  261. package/dist/managers/module-type-registry.d.ts +10 -64
  262. package/dist/managers/module-type-registry.d.ts.map +1 -1
  263. package/dist/managers/module-type-registry.js +25 -373
  264. package/dist/managers/module-type-registry.js.map +1 -1
  265. package/dist/managers/plugins-helpers.d.ts +18 -0
  266. package/dist/managers/plugins-helpers.d.ts.map +1 -0
  267. package/dist/managers/plugins-helpers.js +118 -0
  268. package/dist/managers/plugins-helpers.js.map +1 -0
  269. package/dist/managers/plugins-helpers.test.d.ts +2 -0
  270. package/dist/managers/plugins-helpers.test.d.ts.map +1 -0
  271. package/dist/managers/plugins-helpers.test.js +68 -0
  272. package/dist/managers/plugins-helpers.test.js.map +1 -0
  273. package/dist/managers/plugins.d.ts +16 -109
  274. package/dist/managers/plugins.d.ts.map +1 -1
  275. package/dist/managers/plugins.js +29 -220
  276. package/dist/managers/plugins.js.map +1 -1
  277. package/dist/managers/plugins.test.d.ts +2 -0
  278. package/dist/managers/plugins.test.d.ts.map +1 -0
  279. package/dist/managers/plugins.test.js +160 -0
  280. package/dist/managers/plugins.test.js.map +1 -0
  281. package/dist/managers/tool-manager.d.ts +1 -1
  282. package/dist/managers/tool-manager.d.ts.map +1 -1
  283. package/dist/managers/tool-manager.js +15 -5
  284. package/dist/managers/tool-manager.js.map +1 -1
  285. package/dist/managers/tool-manager.test.js +32 -16
  286. package/dist/managers/tool-manager.test.js.map +1 -1
  287. package/dist/node/index.cjs +5 -5
  288. package/dist/node/index.d.cts +28 -1
  289. package/dist/node/index.d.ts +28 -1
  290. package/dist/node/index.js +5 -5
  291. package/dist/permissions/index.d.ts +7 -0
  292. package/dist/permissions/index.d.ts.map +1 -0
  293. package/dist/permissions/index.js +4 -0
  294. package/dist/permissions/index.js.map +1 -0
  295. package/dist/permissions/permission-gate.d.ts +38 -0
  296. package/dist/permissions/permission-gate.d.ts.map +1 -0
  297. package/dist/permissions/permission-gate.js +119 -0
  298. package/dist/permissions/permission-gate.js.map +1 -0
  299. package/dist/permissions/permission-mode.d.ts +25 -0
  300. package/dist/permissions/permission-mode.d.ts.map +1 -0
  301. package/dist/permissions/permission-mode.js +58 -0
  302. package/dist/permissions/permission-mode.js.map +1 -0
  303. package/dist/permissions/types.d.ts +27 -0
  304. package/dist/permissions/types.d.ts.map +1 -0
  305. package/dist/permissions/types.js +9 -0
  306. package/dist/permissions/types.js.map +1 -0
  307. package/dist/plugins/event-emitter/metrics.d.ts.map +1 -1
  308. package/dist/plugins/event-emitter/metrics.js +1 -1
  309. package/dist/plugins/event-emitter/metrics.js.map +1 -1
  310. package/dist/plugins/event-emitter/plugin-types.d.ts +88 -0
  311. package/dist/plugins/event-emitter/plugin-types.d.ts.map +1 -0
  312. package/dist/plugins/event-emitter/plugin-types.js +2 -0
  313. package/dist/plugins/event-emitter/plugin-types.js.map +1 -0
  314. package/dist/plugins/event-emitter/types.d.ts +3 -3
  315. package/dist/plugins/event-emitter/types.d.ts.map +1 -1
  316. package/dist/plugins/event-emitter/types.js +4 -4
  317. package/dist/plugins/event-emitter/types.js.map +1 -1
  318. package/dist/plugins/event-emitter-plugin.d.ts +9 -184
  319. package/dist/plugins/event-emitter-plugin.d.ts.map +1 -1
  320. package/dist/plugins/event-emitter-plugin.js +91 -235
  321. package/dist/plugins/event-emitter-plugin.js.map +1 -1
  322. package/dist/schemas/agent-template-schema.d.ts +12 -12
  323. package/dist/schemas/agent-template-schema.d.ts.map +1 -1
  324. package/dist/schemas/agent-template-schema.js +35 -33
  325. package/dist/schemas/agent-template-schema.js.map +1 -1
  326. package/dist/services/cache/cache-key-builder.d.ts +13 -0
  327. package/dist/services/cache/cache-key-builder.d.ts.map +1 -0
  328. package/dist/services/cache/cache-key-builder.js +30 -0
  329. package/dist/services/cache/cache-key-builder.js.map +1 -0
  330. package/dist/services/cache/cache-key-builder.test.d.ts +2 -0
  331. package/dist/services/cache/cache-key-builder.test.d.ts.map +1 -0
  332. package/dist/services/cache/cache-key-builder.test.js +56 -0
  333. package/dist/services/cache/cache-key-builder.test.js.map +1 -0
  334. package/dist/services/cache/execution-cache-service.d.ts +18 -0
  335. package/dist/services/cache/execution-cache-service.d.ts.map +1 -0
  336. package/dist/services/cache/execution-cache-service.js +26 -0
  337. package/dist/services/cache/execution-cache-service.js.map +1 -0
  338. package/dist/services/cache/execution-cache-service.test.d.ts +2 -0
  339. package/dist/services/cache/execution-cache-service.test.d.ts.map +1 -0
  340. package/dist/services/cache/execution-cache-service.test.js +59 -0
  341. package/dist/services/cache/execution-cache-service.test.js.map +1 -0
  342. package/dist/services/cache/index.d.ts +4 -0
  343. package/dist/services/cache/index.d.ts.map +1 -0
  344. package/dist/services/cache/index.js +4 -0
  345. package/dist/services/cache/index.js.map +1 -0
  346. package/dist/services/cache/memory-cache-storage.d.ts +25 -0
  347. package/dist/services/cache/memory-cache-storage.d.ts.map +1 -0
  348. package/dist/services/cache/memory-cache-storage.js +89 -0
  349. package/dist/services/cache/memory-cache-storage.js.map +1 -0
  350. package/dist/services/cache/memory-cache-storage.test.d.ts +2 -0
  351. package/dist/services/cache/memory-cache-storage.test.d.ts.map +1 -0
  352. package/dist/services/cache/memory-cache-storage.test.js +94 -0
  353. package/dist/services/cache/memory-cache-storage.test.js.map +1 -0
  354. package/dist/services/conversation-service/conversation-service.test.d.ts +2 -0
  355. package/dist/services/conversation-service/conversation-service.test.d.ts.map +1 -0
  356. package/dist/services/conversation-service/conversation-service.test.js +248 -0
  357. package/dist/services/conversation-service/conversation-service.test.js.map +1 -0
  358. package/dist/services/conversation-service/index.d.ts +10 -71
  359. package/dist/services/conversation-service/index.d.ts.map +1 -1
  360. package/dist/services/conversation-service/index.js +58 -355
  361. package/dist/services/conversation-service/index.js.map +1 -1
  362. package/dist/services/conversation-service/message-helpers.d.ts +47 -0
  363. package/dist/services/conversation-service/message-helpers.d.ts.map +1 -0
  364. package/dist/services/conversation-service/message-helpers.js +150 -0
  365. package/dist/services/conversation-service/message-helpers.js.map +1 -0
  366. package/dist/services/conversation-service/types.d.ts.map +1 -1
  367. package/dist/services/execution-constants.d.ts +16 -0
  368. package/dist/services/execution-constants.d.ts.map +1 -0
  369. package/dist/services/execution-constants.js +16 -0
  370. package/dist/services/execution-constants.js.map +1 -0
  371. package/dist/services/execution-event-emitter.d.ts +60 -0
  372. package/dist/services/execution-event-emitter.d.ts.map +1 -0
  373. package/dist/services/execution-event-emitter.js +323 -0
  374. package/dist/services/execution-event-emitter.js.map +1 -0
  375. package/dist/services/execution-round.d.ts +58 -0
  376. package/dist/services/execution-round.d.ts.map +1 -0
  377. package/dist/services/execution-round.js +323 -0
  378. package/dist/services/execution-round.js.map +1 -0
  379. package/dist/services/execution-round.test.d.ts +2 -0
  380. package/dist/services/execution-round.test.d.ts.map +1 -0
  381. package/dist/services/execution-round.test.js +188 -0
  382. package/dist/services/execution-round.test.js.map +1 -0
  383. package/dist/services/execution-service.d.ts +28 -125
  384. package/dist/services/execution-service.d.ts.map +1 -1
  385. package/dist/services/execution-service.js +222 -1134
  386. package/dist/services/execution-service.js.map +1 -1
  387. package/dist/services/execution-service.test.js +115 -72
  388. package/dist/services/execution-service.test.js.map +1 -1
  389. package/dist/services/execution-stream.d.ts +32 -0
  390. package/dist/services/execution-stream.d.ts.map +1 -0
  391. package/dist/services/execution-stream.js +268 -0
  392. package/dist/services/execution-stream.js.map +1 -0
  393. package/dist/services/execution-types.d.ts +122 -0
  394. package/dist/services/execution-types.d.ts.map +1 -0
  395. package/dist/services/execution-types.js +48 -0
  396. package/dist/services/execution-types.js.map +1 -0
  397. package/dist/services/history-module.d.ts.map +1 -1
  398. package/dist/services/history-module.js +1 -1
  399. package/dist/services/history-module.js.map +1 -1
  400. package/dist/services/history-module.test.d.ts +2 -0
  401. package/dist/services/history-module.test.d.ts.map +1 -0
  402. package/dist/services/history-module.test.js +137 -0
  403. package/dist/services/history-module.test.js.map +1 -0
  404. package/dist/services/in-memory-history-store.d.ts.map +1 -1
  405. package/dist/services/in-memory-history-store.js +1 -1
  406. package/dist/services/in-memory-history-store.js.map +1 -1
  407. package/dist/services/index.d.ts +0 -1
  408. package/dist/services/index.d.ts.map +1 -1
  409. package/dist/services/index.js +2 -3
  410. package/dist/services/index.js.map +1 -1
  411. package/dist/services/plugin-hook-dispatcher.d.ts +11 -0
  412. package/dist/services/plugin-hook-dispatcher.d.ts.map +1 -0
  413. package/dist/services/plugin-hook-dispatcher.js +68 -0
  414. package/dist/services/plugin-hook-dispatcher.js.map +1 -0
  415. package/dist/services/plugin-hook-dispatcher.test.d.ts +2 -0
  416. package/dist/services/plugin-hook-dispatcher.test.d.ts.map +1 -0
  417. package/dist/services/plugin-hook-dispatcher.test.js +93 -0
  418. package/dist/services/plugin-hook-dispatcher.test.js.map +1 -0
  419. package/dist/services/plugin-priority.test.d.ts +2 -0
  420. package/dist/services/plugin-priority.test.d.ts.map +1 -0
  421. package/dist/services/plugin-priority.test.js +119 -0
  422. package/dist/services/plugin-priority.test.js.map +1 -0
  423. package/dist/services/tool-execution-service.d.ts +1 -0
  424. package/dist/services/tool-execution-service.d.ts.map +1 -1
  425. package/dist/services/tool-execution-service.js +89 -46
  426. package/dist/services/tool-execution-service.js.map +1 -1
  427. package/dist/services/tool-execution-service.test.d.ts +2 -0
  428. package/dist/services/tool-execution-service.test.d.ts.map +1 -0
  429. package/dist/services/tool-execution-service.test.js +358 -0
  430. package/dist/services/tool-execution-service.test.js.map +1 -0
  431. package/dist/tool-registry/function-tool.d.ts +54 -0
  432. package/dist/tool-registry/function-tool.d.ts.map +1 -0
  433. package/dist/tool-registry/function-tool.js +190 -0
  434. package/dist/tool-registry/function-tool.js.map +1 -0
  435. package/dist/tool-registry/index.d.ts +3 -0
  436. package/dist/tool-registry/index.d.ts.map +1 -0
  437. package/dist/tool-registry/index.js +3 -0
  438. package/dist/tool-registry/index.js.map +1 -0
  439. package/dist/tool-registry/tool-registry.d.ts +54 -0
  440. package/dist/tool-registry/tool-registry.d.ts.map +1 -0
  441. package/dist/tool-registry/tool-registry.js +148 -0
  442. package/dist/tool-registry/tool-registry.js.map +1 -0
  443. package/dist/utils/errors.d.ts +11 -2
  444. package/dist/utils/errors.d.ts.map +1 -1
  445. package/dist/utils/errors.js +13 -2
  446. package/dist/utils/errors.js.map +1 -1
  447. package/dist/utils/errors.test.d.ts +2 -0
  448. package/dist/utils/errors.test.d.ts.map +1 -0
  449. package/dist/utils/errors.test.js +361 -0
  450. package/dist/utils/errors.test.js.map +1 -0
  451. package/dist/utils/execution-proxy.d.ts +7 -3
  452. package/dist/utils/execution-proxy.d.ts.map +1 -1
  453. package/dist/utils/execution-proxy.js +64 -42
  454. package/dist/utils/execution-proxy.js.map +1 -1
  455. package/dist/utils/execution-proxy.test.d.ts +2 -0
  456. package/dist/utils/execution-proxy.test.d.ts.map +1 -0
  457. package/dist/utils/execution-proxy.test.js +179 -0
  458. package/dist/utils/execution-proxy.test.js.map +1 -0
  459. package/dist/utils/logger.d.ts +3 -3
  460. package/dist/utils/logger.d.ts.map +1 -1
  461. package/dist/utils/logger.js +9 -5
  462. package/dist/utils/logger.js.map +1 -1
  463. package/dist/utils/message-converter.d.ts +1 -4
  464. package/dist/utils/message-converter.d.ts.map +1 -1
  465. package/dist/utils/message-converter.js +13 -12
  466. package/dist/utils/message-converter.js.map +1 -1
  467. package/dist/utils/message-converter.test.d.ts +2 -0
  468. package/dist/utils/message-converter.test.d.ts.map +1 -0
  469. package/dist/utils/message-converter.test.js +164 -0
  470. package/dist/utils/message-converter.test.js.map +1 -0
  471. package/dist/utils/periodic-task.d.ts +1 -1
  472. package/dist/utils/periodic-task.d.ts.map +1 -1
  473. package/dist/utils/periodic-task.js +1 -1
  474. package/dist/utils/periodic-task.js.map +1 -1
  475. package/dist/utils/periodic-task.test.d.ts +2 -0
  476. package/dist/utils/periodic-task.test.d.ts.map +1 -0
  477. package/dist/utils/periodic-task.test.js +87 -0
  478. package/dist/utils/periodic-task.test.js.map +1 -0
  479. package/dist/utils/validation.d.ts.map +1 -1
  480. package/dist/utils/validation.js +17 -11
  481. package/dist/utils/validation.js.map +1 -1
  482. package/dist/utils/validation.test.d.ts +2 -0
  483. package/dist/utils/validation.test.d.ts.map +1 -0
  484. package/dist/utils/validation.test.js +249 -0
  485. package/dist/utils/validation.test.js.map +1 -0
  486. package/package.json +1 -1
@@ -1,3 +1,15 @@
1
+ /**
2
+ * Core Robota agent class.
3
+ *
4
+ * Heavy logic is delegated to extracted helpers:
5
+ * - {@link RobotaModuleManager} — module lifecycle
6
+ * - {@link RobotaPluginManager} — plugin lifecycle
7
+ * - {@link RobotaConfigManager} — config/tool/model management
8
+ * - {@link performAsyncInitialization} — async boot sequence
9
+ * - {@link robotaRun}, {@link robotaRunStream} — execution turns
10
+ * - {@link buildAgentStats}, {@link destroyAgent} — stats and teardown
11
+ * @public
12
+ */
1
13
  import { AbstractAgent } from '../abstracts/abstract-agent';
2
14
  import { ModuleRegistry } from '../managers/module-registry';
3
15
  import { EventEmitterPlugin } from '../plugins/event-emitter-plugin';
@@ -6,213 +18,110 @@ import { AIProviders } from '../managers/ai-provider-manager';
6
18
  import { Tools } from '../managers/tool-manager';
7
19
  import { AgentFactory } from '../managers/agent-factory';
8
20
  import { ConversationHistory } from '../managers/conversation-history-manager';
9
- import { ExecutionService } from '../services/execution-service';
10
21
  import { AGENT_EVENTS, AGENT_EVENT_PREFIX } from '../agents/constants';
11
- import { DEFAULT_ABSTRACT_EVENT_SERVICE, isDefaultEventService, bindWithOwnerPath } from '../services/event-service';
12
- import { AbstractTool } from '../abstracts/abstract-tool';
22
+ import { DEFAULT_ABSTRACT_EVENT_SERVICE, isDefaultEventService, bindWithOwnerPath, } from '../event-service/index';
13
23
  import { createLogger, setGlobalLogLevel } from '../utils/logger';
14
- import { ConfigurationError } from '../utils/errors';
15
- /**
16
- * Configuration options for creating a Robota instance.
17
- * Extends AgentConfig with additional options specific to the Robota agent system.
18
- *
19
- * @public
20
- * @interface
21
- * @example
22
- * ```typescript
23
- * const config: AgentConfig = {
24
- * name: 'MyAgent',
25
- * aiProviders: [new OpenAIProvider()],
26
- * defaultModel: {
27
- * provider: 'openai',
28
- * model: 'gpt-4'
29
- * },
30
- * tools: [weatherTool, calculatorTool],
31
- * plugins: [new LoggingPlugin(), new UsagePlugin()],
32
- * logging: { level: 'info', enabled: true }
33
- * };
34
- * ```
35
- */
36
- // Robota uses AgentConfig directly
24
+ import { RobotaModuleManager } from './robota-module-manager';
25
+ import { RobotaPluginManager } from './robota-plugin-manager';
26
+ import { RobotaConfigManager, validateAgentConfig } from './robota-config-manager';
27
+ import { performAsyncInitialization } from './robota-initializer';
28
+ import { robotaRun, robotaRunStream } from './robota-execution';
29
+ import { buildAgentStats, destroyAgent } from './robota-lifecycle';
30
+ const ID_RADIX = 36;
31
+ const ID_RANDOM_LENGTH = 9;
37
32
  /**
38
- * Core AI agent implementation for the Robota SDK.
39
- *
40
- * Robota is a comprehensive AI agent that integrates multiple AI providers, tools, and plugins
41
- * into a unified conversational interface. Each instance is completely independent with its own
42
- * managers and services - NO GLOBAL SINGLETONS are used.
43
- *
44
- * Key Features:
45
- * - Multiple AI provider support (OpenAI, Anthropic, Google)
46
- * - Function/tool calling with Zod schema validation
47
- * - Plugin system for extensible functionality
48
- * - Streaming response support
49
- * - Conversation history management
50
- * - Instance-specific resource management
51
- *
33
+ * Core AI agent integrating multiple AI providers, tools, and plugins
34
+ * into a unified conversational interface.
52
35
  * @public
53
- * @class
54
- * @implements AgentInterface
55
- *
56
- * @example Basic Usage
57
- * ```typescript
58
- * import { Robota } from '@robota-sdk/agents';
59
- * import { OpenAIProvider } from '@robota-sdk/openai';
60
- *
61
- * const robota = new Robota({
62
- * name: 'MyAgent',
63
- * aiProviders: [new OpenAIProvider({ apiKey: 'sk-...' })],
64
- * defaultModel: {
65
- * provider: 'openai',
66
- * model: 'gpt-4'
67
- * }
68
- * });
69
- *
70
- * const response = await robota.run('Hello, how are you?');
71
- * console.log(response);
72
- * ```
73
- *
74
- * @example With Tools and Plugins
75
- * ```typescript
76
- * import { Robota, LoggingPlugin, UsagePlugin } from '@robota-sdk/agents';
77
- * import { weatherTool, calculatorTool } from './my-tools';
78
- *
79
- * const robota = new Robota({
80
- * name: 'AdvancedAgent',
81
- * aiProviders: [openaiProvider],
82
- * defaultModel: {
83
- * provider: 'openai',
84
- * model: 'gpt-4'
85
- * },
86
- * tools: [weatherTool, calculatorTool],
87
- * plugins: [
88
- * new LoggingPlugin({ level: 'info' }),
89
- * new UsagePlugin({ trackTokens: true })
90
- * ]
91
- * });
92
- *
93
- * const response = await robota.run('What\'s the weather in Tokyo?');
94
- * ```
95
- *
96
- * @example Streaming Response
97
- * ```typescript
98
- * for await (const chunk of robota.runStream('Tell me a story')) {
99
- * process.stdout.write(chunk);
100
- * }
101
- * ```
102
36
  */
103
37
  export class Robota extends AbstractAgent {
104
- /** The name of this agent instance */
105
38
  name;
106
- /** The version of the Robota agent implementation */
107
39
  version = '1.0.0';
108
- // Instance-specific managers (NO SINGLETONS)
109
40
  aiProviders;
110
41
  tools;
111
42
  agentFactory;
112
43
  conversationHistory;
113
- // Module system integration
114
44
  moduleRegistry;
115
45
  eventEmitter;
116
- // Core services
117
46
  executionService;
118
47
  eventService;
119
48
  agentEventService;
120
- // State management
121
49
  config;
122
50
  conversationId;
123
51
  logger;
124
52
  initializationPromise;
125
53
  isFullyInitialized = false;
126
54
  startTime;
127
- // Configuration update state
128
55
  configVersion = 1;
129
56
  configUpdatedAt = Date.now();
130
- /**
131
- * Creates a new Robota agent instance with the new aiProviders array design.
132
- *
133
- * The constructor performs synchronous initialization and validation.
134
- * Async initialization (AI provider setup, tool registration) is deferred
135
- * until the first run() call for optimal performance.
136
- *
137
- * @param config - Configuration options for the agent
138
- * @throws {ConfigurationError} When required configuration is missing or invalid
139
- * @throws {ValidationError} When configuration values are invalid
140
- *
141
- * @example
142
- * ```typescript
143
- * const robota = new Robota({
144
- * name: 'CustomerSupport',
145
- * aiProviders: [
146
- * new OpenAIProvider({ apiKey: process.env.OPENAI_API_KEY }),
147
- * new AnthropicProvider({ apiKey: process.env.ANTHROPIC_API_KEY })
148
- * ],
149
- * defaultModel: {
150
- * provider: 'openai',
151
- * model: 'gpt-4',
152
- * temperature: 0.7
153
- * },
154
- * tools: [emailTool, ticketTool],
155
- * plugins: [new LoggingPlugin(), new ErrorHandlingPlugin()]
156
- * });
157
- * ```
158
- */
57
+ moduleManager;
58
+ pluginManager;
59
+ configManager;
159
60
  constructor(config) {
160
61
  super();
161
62
  this.name = config.name;
162
63
  this.config = config;
163
- this.conversationId = config.conversationId || `conv_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
64
+ this.conversationId =
65
+ config.conversationId ||
66
+ `conv_${Date.now()}_${Math.random().toString(ID_RADIX).substr(2, ID_RANDOM_LENGTH)}`;
164
67
  this.logger = createLogger('Robota');
165
68
  this.startTime = Date.now();
166
- // Apply logging configuration
167
69
  if (config.logging) {
168
- if (config.logging.level) {
70
+ if (config.logging.level)
169
71
  setGlobalLogLevel(config.logging.level);
170
- }
171
- if (config.logging.enabled === false) {
72
+ if (config.logging.enabled === false)
172
73
  setGlobalLogLevel('silent');
173
- }
174
74
  }
175
- // Validate new configuration format
176
- this.validateNewConfig(config);
177
- // Create INSTANCE-SPECIFIC managers (NO SINGLETONS)
178
- this.aiProviders = this.createAIProvidersInstance();
179
- this.tools = this.createToolsInstance();
180
- this.agentFactory = this.createAgentFactoryInstance();
181
- this.conversationHistory = this.createConversationHistoryInstance();
182
- // Create module system components
183
- this.eventEmitter = this.createEventEmitterInstance();
184
- this.moduleRegistry = this.createModuleRegistryInstance();
185
- // Initialize base EventService (UNBOUND).
186
- // The agent must use an owner-bound instance for agent.* events,
187
- // while ExecutionService will use owner-bound instances for execution.* and tool.* events.
75
+ validateAgentConfig(config);
76
+ this.aiProviders = new AIProviders();
77
+ this.tools = new Tools();
78
+ this.agentFactory = new AgentFactory();
79
+ this.conversationHistory = new ConversationHistory();
80
+ this.eventEmitter = new EventEmitterPlugin({
81
+ enabled: true,
82
+ events: [
83
+ EVENT_EMITTER_EVENTS.MODULE_INITIALIZE_START,
84
+ EVENT_EMITTER_EVENTS.MODULE_INITIALIZE_COMPLETE,
85
+ EVENT_EMITTER_EVENTS.MODULE_INITIALIZE_ERROR,
86
+ EVENT_EMITTER_EVENTS.MODULE_EXECUTION_START,
87
+ EVENT_EMITTER_EVENTS.MODULE_EXECUTION_COMPLETE,
88
+ EVENT_EMITTER_EVENTS.MODULE_EXECUTION_ERROR,
89
+ EVENT_EMITTER_EVENTS.MODULE_DISPOSE_START,
90
+ EVENT_EMITTER_EVENTS.MODULE_DISPOSE_COMPLETE,
91
+ EVENT_EMITTER_EVENTS.MODULE_DISPOSE_ERROR,
92
+ ],
93
+ });
94
+ this.moduleRegistry = new ModuleRegistry(this.eventEmitter);
188
95
  this.eventService = config.eventService || DEFAULT_ABSTRACT_EVENT_SERVICE;
189
96
  this.agentEventService = bindWithOwnerPath(this.eventService, {
190
97
  ownerType: 'agent',
191
98
  ownerId: this.conversationId,
192
- ownerPath: this.buildOwnerPath(this.config.executionContext)
99
+ ownerPath: this.buildOwnerPath(this.config.executionContext),
193
100
  });
194
- // Store config for async initialization
195
- this.config = config;
196
- // ExecutionService will be initialized after async setup is complete
197
- this.logger.debug('Robota created with new aiProviders array design', {
198
- name: this.name,
199
- conversationId: this.conversationId,
200
- providersCount: config.aiProviders.length,
201
- toolsCount: config.tools?.length || 0,
202
- pluginsCount: config.plugins?.length || 0,
203
- defaultProvider: config.defaultModel.provider,
204
- defaultModel: config.defaultModel.model
101
+ this.initDelegates();
102
+ this.emitCreatedEvent();
103
+ }
104
+ initDelegates() {
105
+ this.moduleManager = new RobotaModuleManager(this.name, this.moduleRegistry, this.logger, () => this.isFullyInitialized, () => this.ensureFullyInitialized());
106
+ this.pluginManager = new RobotaPluginManager(this.logger, () => this.isFullyInitialized, () => this.executionService);
107
+ this.configManager = new RobotaConfigManager(this.logger, () => this.aiProviders, () => this.tools, () => this.eventService, () => this.isFullyInitialized, () => this.ensureFullyInitialized(), () => this.config, (c) => {
108
+ this.config = c;
109
+ }, () => this.configVersion, () => ++this.configVersion, () => this.configUpdatedAt, (t) => {
110
+ this.configUpdatedAt = t;
111
+ }, (eventType, data) => {
112
+ this.emitAgentEvent(eventType, data);
205
113
  });
206
- // Agent creation event
114
+ }
115
+ emitCreatedEvent() {
207
116
  const toolNames = Array.isArray(this.config.tools)
208
117
  ? this.config.tools
209
- .map(t => {
210
- const schemaName = t?.schema?.name;
211
- if (typeof schemaName === 'string' && schemaName.length > 0)
212
- return schemaName;
213
- const instanceName = t?.name;
214
- if (typeof instanceName === 'string' && instanceName.length > 0)
215
- return instanceName;
118
+ .map((t) => {
119
+ const sn = t?.schema?.name;
120
+ if (typeof sn === 'string' && sn.length > 0)
121
+ return sn;
122
+ const nm = t?.name;
123
+ if (typeof nm === 'string' && nm.length > 0)
124
+ return nm;
216
125
  return '';
217
126
  })
218
127
  .filter((n) => typeof n === 'string' && n.length > 0)
@@ -224,1054 +133,203 @@ export class Robota extends AbstractAgent {
224
133
  provider: this.config.defaultModel.provider,
225
134
  model: this.config.defaultModel.model,
226
135
  temperature: this.config.defaultModel.temperature,
227
- maxTokens: this.config.defaultModel.maxTokens
228
- }
229
- });
230
- }
231
- /**
232
- * Update tools for this agent instance.
233
- * Rebuilds the Tools registry atomically and emits CONFIG_UPDATED event.
234
- */
235
- async updateTools(next) {
236
- await this.ensureFullyInitialized();
237
- if (!Array.isArray(next)) {
238
- throw new ConfigurationError('updateTools: next must be an array of tools');
239
- }
240
- // Rebuild tool registry atomically
241
- const registry = this.tools.getRegistry();
242
- registry.clear();
243
- const toolNames = [];
244
- for (const tool of next) {
245
- // Inject EventService into AbstractTool if available
246
- if (this.eventService) {
247
- tool.setEventService(this.eventService);
248
- }
249
- // Adapter executor consistent with initialization
250
- const toolExecutor = async (parameters, context) => {
251
- if (!context) {
252
- throw new Error('[ROBOTA] Missing ToolExecutionContext for tool execution');
253
- }
254
- const result = await tool.execute(parameters, context);
255
- return result.data;
256
- };
257
- this.tools.addTool(tool.schema, toolExecutor);
258
- const nm = tool.schema.name;
259
- if (typeof nm === 'string' && nm.length > 0)
260
- toolNames.push(nm);
261
- }
262
- // Update config snapshot
263
- this.config.tools = next;
264
- this.configVersion += 1;
265
- this.configUpdatedAt = Date.now();
266
- // Emit agent.config_updated
267
- this.emitAgentEvent(AGENT_EVENTS.CONFIG_UPDATED, {
268
- parameters: {
269
- tools: toolNames,
270
- systemMessage: this.config.defaultModel.systemMessage,
271
- provider: this.config.defaultModel.provider,
272
- model: this.config.defaultModel.model,
273
- temperature: this.config.defaultModel.temperature,
274
- maxTokens: this.config.defaultModel.maxTokens
136
+ maxTokens: this.config.defaultModel.maxTokens,
275
137
  },
276
- metadata: {
277
- version: this.configVersion
278
- }
279
- });
280
- return { version: this.configVersion };
281
- }
282
- /**
283
- * Update configuration partially. Currently supports tools.
284
- */
285
- async updateConfiguration(patch) {
286
- if (patch.tools) {
287
- return this.updateTools(patch.tools);
288
- }
289
- // Extendable: merge other fields with validation in future
290
- throw new ConfigurationError('updateConfiguration: only tools patch is supported at this time');
291
- }
292
- /**
293
- * Read-only configuration overview for UI.
294
- */
295
- async getConfiguration() {
296
- await this.ensureFullyInitialized();
297
- const schemas = this.tools.getTools();
298
- const tools = schemas.map(s => ({
299
- name: s.name,
300
- parameters: (() => {
301
- const params = s.parameters;
302
- const props = params?.properties;
303
- return props && typeof props === 'object' ? Object.keys(props) : undefined;
304
- })()
305
- }));
306
- return {
307
- version: this.configVersion,
308
- tools,
309
- updatedAt: this.configUpdatedAt,
310
- metadata: undefined
311
- };
312
- }
313
- emitAgentEvent(eventType, data) {
314
- if (isDefaultEventService(this.agentEventService)) {
315
- return;
316
- }
317
- const payload = {
318
- timestamp: new Date(),
319
- ...data,
320
- };
321
- // Absolute ownerPath: pass the full path explicitly so downstream subscribers can derive `path` deterministically.
322
- this.agentEventService.emit(eventType, payload, {
323
- ownerType: AGENT_EVENT_PREFIX,
324
- ownerId: this.conversationId,
325
- ownerPath: this.buildOwnerPath(this.config.executionContext)
326
- });
327
- }
328
- buildOwnerPath(executionContext) {
329
- const base = executionContext?.ownerPath?.length
330
- ? executionContext.ownerPath.map(segment => ({ ...segment }))
331
- : [];
332
- return [...base, { type: 'agent', id: this.conversationId }];
333
- }
334
- /**
335
- * Create instance-specific AIProviders manager
336
- */
337
- createAIProvidersInstance() {
338
- return new AIProviders();
339
- }
340
- /**
341
- * Create instance-specific Tools manager
342
- */
343
- createToolsInstance() {
344
- return new Tools();
345
- }
346
- /**
347
- * Create instance-specific AgentFactory manager
348
- */
349
- createAgentFactoryInstance() {
350
- return new AgentFactory();
351
- }
352
- /**
353
- * Create instance-specific ConversationHistory manager
354
- */
355
- createConversationHistoryInstance() {
356
- return new ConversationHistory();
357
- }
358
- /**
359
- * Create instance-specific EventEmitter plugin
360
- */
361
- createEventEmitterInstance() {
362
- return new EventEmitterPlugin({
363
- enabled: true,
364
- events: [
365
- EVENT_EMITTER_EVENTS.MODULE_INITIALIZE_START,
366
- EVENT_EMITTER_EVENTS.MODULE_INITIALIZE_COMPLETE,
367
- EVENT_EMITTER_EVENTS.MODULE_INITIALIZE_ERROR,
368
- EVENT_EMITTER_EVENTS.MODULE_EXECUTION_START,
369
- EVENT_EMITTER_EVENTS.MODULE_EXECUTION_COMPLETE,
370
- EVENT_EMITTER_EVENTS.MODULE_EXECUTION_ERROR,
371
- EVENT_EMITTER_EVENTS.MODULE_DISPOSE_START,
372
- EVENT_EMITTER_EVENTS.MODULE_DISPOSE_COMPLETE,
373
- EVENT_EMITTER_EVENTS.MODULE_DISPOSE_ERROR
374
- ]
375
138
  });
376
139
  }
377
- /**
378
- * Create instance-specific ModuleRegistry
379
- */
380
- createModuleRegistryInstance() {
381
- return new ModuleRegistry(this.eventEmitter);
382
- }
383
- /**
384
- * Ensure full initialization has occurred
385
- */
386
- async ensureFullyInitialized() {
387
- if (this.isFullyInitialized) {
388
- return;
389
- }
390
- if (!this.initializationPromise) {
391
- this.initializationPromise = this.performAsyncInitialization();
392
- }
393
- await this.initializationPromise;
394
- }
395
- /**
396
- * Perform actual async initialization
397
- */
398
- async performAsyncInitialization() {
399
- this.logger.debug('Starting Robota initialization with independent managers');
400
- try {
401
- // Initialize all instance-specific managers
402
- await Promise.all([
403
- this.aiProviders.initialize(),
404
- this.tools.initialize(),
405
- this.agentFactory.initialize()
406
- ]);
407
- // Register AI providers after manager initialization
408
- if (this.config.aiProviders) {
409
- for (const provider of this.config.aiProviders) {
410
- this.aiProviders.addProvider(provider.name, provider);
411
- }
412
- }
413
- // Set current provider from defaultModel
414
- if (this.config.defaultModel) {
415
- this.aiProviders.setCurrentProvider(this.config.defaultModel.provider, this.config.defaultModel.model);
416
- }
417
- // Register modules if provided
418
- if (this.config.modules) {
419
- for (const module of this.config.modules) {
420
- await this.moduleRegistry.registerModule(module, {
421
- autoInitialize: true,
422
- validateDependencies: true
423
- });
424
- }
425
- this.logger.debug('Modules registered and initialized', {
426
- moduleCount: this.config.modules.length,
427
- moduleNames: this.config.modules.map(m => m.name)
428
- });
429
- }
430
- // Register tools
431
- if (this.config.tools) {
432
- for (const tool of this.config.tools) {
433
- // Inject EventService into AbstractTool if available
434
- if (tool instanceof AbstractTool && this.eventService) {
435
- tool.setEventService(this.eventService);
436
- }
437
- // Convert AbstractTool to ToolSchema and executor
438
- // Create an adapter to convert ToolResult to ToolExecutionData
439
- const toolExecutor = async (parameters, context) => {
440
- if (!context) {
441
- throw new Error('[ROBOTA] Missing ToolExecutionContext for tool execution');
442
- }
443
- const result = await tool.execute(parameters, context);
444
- return result.data;
445
- };
446
- this.tools.addTool(tool.schema, toolExecutor);
447
- this.logger.debug('Tool registered during initialization', { toolName: tool.schema.name });
448
- }
449
- }
450
- // NOW initialize ExecutionService after all managers are set up
451
- // 🎯 [CONTEXT-INJECTION] Extract execution context from config if available
452
- const executionContext = this.config.executionContext;
453
- this.executionService = new ExecutionService(this.aiProviders, this.tools, this.conversationHistory, this.eventService, executionContext // 🎯 [CONTEXT-INJECTION] Pass execution context to ExecutionService
454
- );
455
- // Register plugins with ExecutionService after it's created
456
- if (this.config.plugins) {
457
- for (const plugin of this.config.plugins) {
458
- this.executionService.registerPlugin(plugin);
459
- // Subscribe plugin to module events if it supports it
460
- if (plugin.subscribeToModuleEvents) {
461
- await plugin.subscribeToModuleEvents(this.eventEmitter);
462
- this.logger.debug('Plugin subscribed to module events', {
463
- pluginName: plugin.name
464
- });
465
- }
466
- }
467
- }
468
- this.isFullyInitialized = true;
469
- this.logger.debug('Robota initialization completed successfully with independent managers');
470
- }
471
- catch (error) {
472
- this.logger.error('Robota initialization failed', {
473
- error: error instanceof Error ? error.message : String(error)
474
- });
475
- throw error;
476
- }
477
- }
478
- /**
479
- * Initialize the agent if not already done
480
- *
481
- * Note: This is a protected lifecycle hook required by AbstractAgent.
482
- * Do not mark it as an internal tag, because DTS generation uses `stripInternal`
483
- * and would remove this method from the public type surface, breaking the
484
- * abstract contract in `.d.ts`.
485
- */
486
- async initialize() {
487
- await this.ensureFullyInitialized();
488
- }
489
- /**
490
- * Execute a conversation turn with the AI agent.
491
- *
492
- * This is the primary method for interacting with the agent. It processes user input,
493
- * manages conversation history, executes any required tools, and returns the AI response.
494
- * The method automatically initializes the agent on first use.
495
- *
496
- * @param input - The user's message or prompt to send to the AI
497
- * @param options - Optional configuration for this specific execution
498
- * @returns Promise that resolves to the AI's response as a string
499
- *
500
- * @throws {ConfigurationError} When the agent configuration is invalid
501
- * @throws {ProviderError} When the AI provider encounters an error
502
- * @throws {ToolExecutionError} When a tool execution fails
503
- *
504
- * @example Basic conversation
505
- * ```typescript
506
- * const response = await robota.run('Hello, how are you?');
507
- * console.log(response); // "Hello! I'm doing well, thank you for asking..."
508
- * ```
509
- *
510
- * @example With execution options
511
- * ```typescript
512
- * const response = await robota.run('Analyze this data', {
513
- * sessionId: 'user-123',
514
- * userId: 'john.doe',
515
- * metadata: { source: 'web-app', priority: 'high' }
516
- * });
517
- * ```
518
- *
519
- * @example Error handling
520
- * ```typescript
521
- * try {
522
- * const response = await robota.run('Complex request');
523
- * } catch (error) {
524
- * if (error instanceof ToolExecutionError) {
525
- * console.error('Tool failed:', error.toolName, error.message);
526
- * }
527
- * }
528
- * ```
529
- */
140
+ // --- Execution ---
530
141
  async run(input, options = {}) {
531
142
  await this.ensureFullyInitialized();
532
- try {
533
- // Emit agent execution start (agent-owned event)
534
- this.emitAgentEvent(AGENT_EVENTS.EXECUTION_START, {});
535
- this.logger.debug('Starting Robota execution', {
536
- inputLength: input.length,
537
- conversationId: this.conversationId,
538
- sessionId: options.sessionId || 'none',
539
- userId: options.userId || 'none',
540
- hasMetadata: !!options.metadata
541
- });
542
- // Get current conversation history from centralized manager
543
- const messages = this.getHistory();
544
- // Prepare execution config with current provider/model settings
545
- const executionConfig = {
546
- ...this.config
547
- };
548
- // Execute using execution service
549
- const result = await this.executionService.execute(input, messages, executionConfig, {
550
- conversationId: this.conversationId,
551
- ...(options.sessionId && { sessionId: options.sessionId }),
552
- ...(options.userId && { userId: options.userId }),
553
- ...(options.metadata && { metadata: options.metadata })
554
- });
555
- this.logger.debug('Robota execution completed', {
556
- success: result.success,
557
- duration: result.duration,
558
- tokensUsed: result.tokensUsed,
559
- toolsExecuted: result.toolsExecuted
560
- });
561
- if (!result.success && result.error) {
562
- throw result.error;
563
- }
564
- // Emit agent execution complete (agent-owned event)
565
- this.emitAgentEvent(AGENT_EVENTS.EXECUTION_COMPLETE, {});
566
- return result.response;
567
- }
568
- catch (error) {
569
- this.logger.error('Robota execution failed', {
570
- error: error instanceof Error ? error.message : String(error),
571
- conversationId: this.conversationId
572
- });
573
- // Emit agent execution error (agent-owned event)
574
- this.emitAgentEvent(AGENT_EVENTS.EXECUTION_ERROR, {
575
- error: error instanceof Error ? error.message : String(error)
576
- });
577
- throw error;
578
- }
143
+ return robotaRun(this.executionDeps(), input, options);
579
144
  }
580
- /**
581
- * Execute a conversation turn with streaming response.
582
- *
583
- * Similar to run() but returns an async generator that yields response chunks
584
- * as they arrive from the AI provider. This enables real-time streaming of
585
- * the AI's response for better user experience.
586
- *
587
- * @param input - The user's message or prompt to send to the AI
588
- * @param options - Optional configuration for this specific execution
589
- * @returns AsyncGenerator that yields string chunks of the AI response
590
- *
591
- * @throws {ConfigurationError} When the agent configuration is invalid
592
- * @throws {ProviderError} When the AI provider encounters an error
593
- * @throws {ToolExecutionError} When a tool execution fails
594
- *
595
- * @example Basic streaming
596
- * ```typescript
597
- * for await (const chunk of robota.runStream('Tell me a story')) {
598
- * process.stdout.write(chunk);
599
- * }
600
- * console.log('\n'); // New line after story
601
- * ```
602
- *
603
- * @example Collecting full response
604
- * ```typescript
605
- * let fullResponse = '';
606
- * for await (const chunk of robota.runStream('Explain quantum computing')) {
607
- * fullResponse += chunk;
608
- * updateUI(chunk); // Update UI in real-time
609
- * }
610
- * console.log('Complete response:', fullResponse);
611
- * ```
612
- *
613
- * @example Error handling in streams
614
- * ```typescript
615
- * try {
616
- * for await (const chunk of robota.runStream('Complex request')) {
617
- * handleChunk(chunk);
618
- * }
619
- * } catch (error) {
620
- * console.error('Streaming failed:', error.message);
621
- * }
622
- * ```
623
- */
624
145
  async *runStream(input, options = {}) {
625
146
  await this.ensureFullyInitialized();
626
- try {
627
- // Emit agent execution start (agent-owned event) for streaming
628
- this.emitAgentEvent(AGENT_EVENTS.EXECUTION_START, {});
629
- this.logger.debug('Starting Robota streaming execution', {
630
- inputLength: input.length,
631
- conversationId: this.conversationId,
632
- sessionId: options.sessionId || 'none',
633
- userId: options.userId || 'none',
634
- hasMetadata: !!options.metadata
635
- });
636
- // Get current conversation history from centralized manager
637
- const messages = this.getHistory();
638
- // Prepare execution config with current provider/model settings
639
- const executionConfig = {
640
- ...this.config
641
- };
642
- // Execute using execution service
643
- const stream = this.executionService.executeStream(input, messages, executionConfig, {
644
- conversationId: this.conversationId,
645
- ...(options.sessionId && { sessionId: options.sessionId }),
646
- ...(options.userId && { userId: options.userId }),
647
- ...(options.metadata && { metadata: options.metadata })
648
- });
649
- for await (const chunk of stream) {
650
- yield chunk.chunk;
651
- }
652
- }
653
- catch (error) {
654
- this.logger.error('Robota streaming execution failed', {
655
- error: error instanceof Error ? error.message : String(error),
656
- conversationId: this.conversationId
657
- });
658
- // Emit agent execution error (agent-owned event) for streaming
659
- this.emitAgentEvent(AGENT_EVENTS.EXECUTION_ERROR, {
660
- error: error instanceof Error ? error.message : String(error)
661
- });
662
- throw error;
663
- }
664
- finally {
665
- // Emit agent execution complete (agent-owned event) at end of streaming
666
- this.emitAgentEvent(AGENT_EVENTS.EXECUTION_COMPLETE, {});
667
- }
147
+ yield* robotaRunStream(this.executionDeps(), input, options);
148
+ }
149
+ executionDeps() {
150
+ return {
151
+ conversationId: this.conversationId,
152
+ config: this.config,
153
+ logger: this.logger,
154
+ getHistory: () => this.getHistory(),
155
+ getExecutionService: () => this.executionService,
156
+ emitAgentEvent: (t, d) => this.emitAgentEvent(t, d),
157
+ };
668
158
  }
669
- /**
670
- * Get the conversation history for this agent instance.
671
- *
672
- * Returns an array of messages representing the complete conversation history
673
- * for this agent's conversation session. The history includes user messages,
674
- * assistant responses, and tool call results.
675
- *
676
- * @returns Array of TUniversalMessage objects representing the conversation history
677
- *
678
- * @example
679
- * ```typescript
680
- * await robota.run('What is 2 + 2?');
681
- * await robota.run('What about 3 + 3?');
682
- *
683
- * const history = robota.getHistory();
684
- * console.log(history.length); // 4 (2 user messages, 2 assistant responses)
685
- * console.log(history[0].role); // 'user'
686
- * console.log(history[0].content); // 'What is 2 + 2?'
687
- * ```
688
- */
159
+ // --- History ---
689
160
  getHistory() {
690
- const conversationSession = this.conversationHistory.getConversationSession(this.conversationId);
691
- const universalMessages = conversationSession.getMessages();
692
- return universalMessages.map(msg => ({
161
+ const session = this.conversationHistory.getConversationSession(this.conversationId);
162
+ return session.getMessages().map((msg) => ({
693
163
  role: msg.role,
694
164
  content: msg.content,
695
165
  timestamp: msg.timestamp,
696
166
  metadata: msg.metadata,
697
167
  ...(msg.role === 'assistant' && 'toolCalls' in msg ? { toolCalls: msg.toolCalls } : {}),
698
- ...(msg.role === 'tool' && 'toolCallId' in msg ? { toolCallId: msg.toolCallId } : {})
168
+ ...(msg.role === 'tool' && 'toolCallId' in msg ? { toolCallId: msg.toolCallId } : {}),
699
169
  }));
700
170
  }
701
- /**
702
- * Clear the conversation history for this agent instance.
703
- *
704
- * Removes all messages from the conversation history, starting fresh.
705
- * This does not affect the agent's configuration or other state.
706
- *
707
- * @example
708
- * ```typescript
709
- * await robota.run('First message');
710
- * console.log(robota.getHistory().length); // 2 (user + assistant)
711
- *
712
- * robota.clearHistory();
713
- * console.log(robota.getHistory().length); // 0
714
- * ```
715
- */
716
171
  clearHistory() {
717
- const conversationSession = this.conversationHistory.getConversationSession(this.conversationId);
718
- conversationSession.clear();
719
- this.logger.debug('Conversation history cleared', { conversationId: this.conversationId });
172
+ this.conversationHistory.getConversationSession(this.conversationId).clear();
173
+ }
174
+ /** Inject a message into conversation history without triggering execution. */
175
+ injectMessage(role, content) {
176
+ const session = this.conversationHistory.getConversationSession(this.conversationId);
177
+ if (role === 'assistant') {
178
+ session.addAssistantMessage(content, []);
179
+ }
180
+ else if (role === 'system') {
181
+ session.addSystemMessage(content);
182
+ }
183
+ else {
184
+ session.addUserMessage(content);
185
+ }
186
+ }
187
+ // --- Config / Model / Tools (delegated) ---
188
+ async updateTools(next) {
189
+ return this.configManager.updateTools(next);
190
+ }
191
+ async updateConfiguration(patch) {
192
+ return this.configManager.updateConfiguration(patch);
193
+ }
194
+ async getConfiguration() {
195
+ return this.configManager.getConfiguration();
196
+ }
197
+ setModel(mc) {
198
+ this.configManager.setModel(mc);
199
+ }
200
+ getModel() {
201
+ return this.configManager.getModel();
202
+ }
203
+ registerTool(tool) {
204
+ this.configManager.registerTool(tool, this.tools);
205
+ }
206
+ unregisterTool(toolName) {
207
+ this.tools.removeTool(toolName);
208
+ }
209
+ getConfig() {
210
+ return { ...this.config };
720
211
  }
721
- /**
722
- * Add a plugin to the agent at runtime.
723
- *
724
- * Plugins provide extensible functionality through lifecycle hooks.
725
- * This method allows dynamic addition of plugins after agent creation.
726
- *
727
- * @param plugin - The plugin instance to add
728
- *
729
- * @example
730
- * ```typescript
731
- * import { UsagePlugin, PerformancePlugin } from '@robota-sdk/agents';
732
- *
733
- * const robota = new Robota(config);
734
- *
735
- * // Add plugins dynamically
736
- * robota.addPlugin(new UsagePlugin({ trackTokens: true }));
737
- * robota.addPlugin(new PerformancePlugin({ trackMemory: true }));
738
- * ```
739
- */
212
+ // --- Plugins (delegated) ---
740
213
  addPlugin(plugin) {
741
- this.executionService.registerPlugin(plugin);
742
- this.logger.debug('Plugin added', { pluginName: plugin.name });
214
+ this.pluginManager.addPlugin(plugin);
743
215
  }
744
- /**
745
- * Remove a plugin from the agent by name.
746
- *
747
- * @param pluginName - The name of the plugin to remove
748
- * @returns true if the plugin was found and removed, false otherwise
749
- *
750
- * @example
751
- * ```typescript
752
- * const removed = robota.removePlugin('usage-plugin');
753
- * if (removed) {
754
- * console.log('Plugin removed successfully');
755
- * } else {
756
- * console.log('Plugin not found');
757
- * }
758
- * ```
759
- */
760
216
  removePlugin(pluginName) {
761
- const removed = this.executionService.removePlugin(pluginName);
762
- if (removed) {
763
- this.logger.debug('Plugin removed', { pluginName });
764
- }
765
- return removed;
217
+ return this.pluginManager.removePlugin(pluginName);
766
218
  }
767
- /**
768
- * Get a specific plugin by name with type safety.
769
- *
770
- * @template T - The expected plugin type extending AbstractPlugin
771
- * @param pluginName - The name of the plugin to retrieve
772
- * @returns The plugin instance if found, null otherwise
773
- *
774
- * @example
775
- * ```typescript
776
- * import { UsagePlugin } from '@robota-sdk/agents';
777
- *
778
- * const usagePlugin = robota.getPlugin<UsagePlugin>('usage-plugin');
779
- * if (usagePlugin) {
780
- * const stats = usagePlugin.getUsageStats();
781
- * console.log('Token usage:', stats.totalTokens);
782
- * }
783
- * ```
784
- */
785
219
  getPlugin(pluginName) {
786
- return this.executionService.getPlugin(pluginName);
220
+ return this.pluginManager.getPlugin(pluginName);
787
221
  }
788
- /**
789
- * Get all registered plugins.
790
- *
791
- * @returns Array of all currently registered plugin instances
792
- *
793
- * @example
794
- * ```typescript
795
- * const plugins = robota.getPlugins();
796
- * console.log(`Agent has ${plugins.length} plugins registered`);
797
- * plugins.forEach(plugin => {
798
- * console.log(`- ${plugin.name} (${plugin.version})`);
799
- * });
800
- * ```
801
- */
802
222
  getPlugins() {
803
- return this.executionService.getPlugins();
223
+ return this.pluginManager.getPlugins();
804
224
  }
805
- /**
806
- * Get all registered plugin names
807
- */
808
225
  getPluginNames() {
809
- if (!this.isFullyInitialized || !this.executionService) {
810
- return [];
811
- }
812
- return this.executionService.getPlugins().map(plugin => plugin.name);
226
+ return this.pluginManager.getPluginNames();
813
227
  }
814
- // ========================================
815
- // Module Management Methods
816
- // ========================================
817
- /**
818
- * Register a new module with the agent
819
- * @param module - The module instance to register
820
- * @param options - Registration options
821
- */
228
+ // --- Modules (delegated) ---
822
229
  async registerModule(module, options) {
823
- await this.ensureFullyInitialized();
824
- await this.moduleRegistry.registerModule(module, {
825
- autoInitialize: options?.autoInitialize ?? true,
826
- validateDependencies: options?.validateDependencies ?? true
827
- });
828
- this.logger.info('Module registered', {
829
- moduleName: module.name,
830
- moduleType: module.getModuleType().type
831
- });
230
+ return this.moduleManager.registerModule(module, options);
832
231
  }
833
- /**
834
- * Unregister a module from the agent
835
- * @param moduleName - Name of the module to unregister
836
- * @returns True if module was unregistered, false if not found
837
- */
838
232
  async unregisterModule(moduleName) {
839
- if (!this.isFullyInitialized) {
840
- return false;
841
- }
842
- const result = await this.moduleRegistry.unregisterModule(moduleName);
843
- if (result) {
844
- this.logger.info('Module unregistered', { moduleName });
845
- }
846
- return result;
233
+ return this.moduleManager.unregisterModule(moduleName);
847
234
  }
848
- /**
849
- * Get a module by name with type safety
850
- * @param moduleName - Name of the module to retrieve
851
- * @returns The module instance or null if not found
852
- */
853
235
  getModule(moduleName) {
854
- if (!this.isFullyInitialized) {
855
- return null;
856
- }
857
- return this.moduleRegistry.getModule(moduleName);
236
+ return this.moduleManager.getModule(moduleName);
858
237
  }
859
- /**
860
- * Get modules by type
861
- * @param moduleType - Type of modules to retrieve
862
- * @returns Array of modules matching the type
863
- */
864
238
  getModulesByType(moduleType) {
865
- if (!this.isFullyInitialized) {
866
- return [];
867
- }
868
- return this.moduleRegistry.getModulesByType(moduleType);
239
+ return this.moduleManager.getModulesByType(moduleType);
869
240
  }
870
- /**
871
- * Get all registered modules
872
- * @returns Array of all registered modules
873
- */
874
241
  getModules() {
875
- if (!this.isFullyInitialized) {
876
- return [];
877
- }
878
- return this.moduleRegistry.getAllModules();
242
+ return this.moduleManager.getModules();
879
243
  }
880
- /**
881
- * Get all registered module names
882
- * @returns Array of module names
883
- */
884
244
  getModuleNames() {
885
- if (!this.isFullyInitialized) {
886
- return [];
887
- }
888
- return this.moduleRegistry.getModuleNames();
245
+ return this.moduleManager.getModuleNames();
889
246
  }
890
- /**
891
- * Check if a module is registered
892
- * @param moduleName - Name of the module to check
893
- * @returns True if module is registered
894
- */
895
247
  hasModule(moduleName) {
896
- if (!this.isFullyInitialized) {
897
- return false;
898
- }
899
- return this.moduleRegistry.hasModule(moduleName);
248
+ return this.moduleManager.hasModule(moduleName);
900
249
  }
901
- /**
902
- * Execute a module by name
903
- * @param moduleName - Name of the module to execute
904
- * @param context - Execution context
905
- * @returns Module execution result
906
- */
907
250
  async executeModule(moduleName, context) {
908
- await this.ensureFullyInitialized();
909
- const executionContext = {
910
- agentName: this.name,
911
- ...(context.executionId && { executionId: context.executionId }),
912
- ...(context.sessionId && { sessionId: context.sessionId }),
913
- ...(context.userId && { userId: context.userId }),
914
- ...(context.metadata && { metadata: context.metadata })
915
- };
916
- return await this.moduleRegistry.executeModule(moduleName, executionContext);
251
+ return this.moduleManager.executeModule(moduleName, context);
917
252
  }
918
- /**
919
- * Get module execution statistics
920
- * @param moduleName - Name of the module
921
- * @returns Module statistics or null if not found
922
- */
923
253
  getModuleStats(moduleName) {
924
- if (!this.isFullyInitialized) {
925
- return null;
926
- }
927
- return this.moduleRegistry.getModuleStats(moduleName);
254
+ return this.moduleManager.getModuleStats(moduleName);
928
255
  }
929
- /**
930
- * Register a new AI provider at runtime.
931
- *
932
- * Allows dynamic addition of AI providers after agent creation.
933
- * The provider can then be selected using switchProvider().
934
- *
935
- * @param name - Unique name for the provider
936
- * @param provider - The AI provider instance to register
937
- *
938
- * @example
939
- * ```typescript
940
- * import { AnthropicProvider } from '@robota-sdk/anthropic';
941
- *
942
- * const anthropicProvider = new AnthropicProvider({
943
- * apiKey: process.env.ANTHROPIC_API_KEY
944
- * });
945
- *
946
- * robota.registerProvider('anthropic', anthropicProvider);
947
- * robota.switchProvider('anthropic', 'claude-3-opus-20240229');
948
- * ```
949
- */
950
- /**
951
- * Set the current model configuration (complete replacement).
952
- *
953
- * Updates the current AI provider, model, and related settings. This completely
954
- * replaces the current model configuration with the new values.
955
- *
956
- * @param modelConfig - New model configuration
957
- *
958
- * @throws {ConfigurationError} When the provider is not available
959
- *
960
- * @example
961
- * ```typescript
962
- * // Switch to a different provider and model
963
- * robota.setModel({
964
- * provider: 'anthropic',
965
- * model: 'claude-3-opus',
966
- * temperature: 0.9,
967
- * maxTokens: 4000
968
- * });
969
- *
970
- * // Simple model change
971
- * robota.setModel({
972
- * provider: 'openai',
973
- * model: 'gpt-4-turbo'
974
- * });
975
- * ```
976
- */
977
- setModel(modelConfig) {
978
- // Validate required fields
979
- if (!modelConfig.provider || !modelConfig.model) {
980
- throw new ConfigurationError('Both provider and model are required', { component: 'Robota' });
981
- }
982
- // Ensure managers are initialized before using them
983
- if (!this.isFullyInitialized) {
984
- throw new ConfigurationError('Agent must be fully initialized before changing model configuration', { component: 'Robota' });
985
- }
986
- const availableProviders = this.aiProviders.getProviderNames();
987
- if (!availableProviders.includes(modelConfig.provider)) {
988
- throw new ConfigurationError(`AI Provider '${modelConfig.provider}' not found. ` +
989
- `Available: ${availableProviders.join(', ')}`, {
990
- component: 'Robota',
991
- provider: modelConfig.provider,
992
- availableProviders
993
- });
994
- }
995
- // Update provider and model
996
- this.aiProviders.setCurrentProvider(modelConfig.provider, modelConfig.model);
997
- // Update config with new defaultModel settings only
998
- this.config = {
999
- ...this.config,
1000
- defaultModel: {
1001
- ...this.config.defaultModel,
1002
- provider: modelConfig.provider,
1003
- model: modelConfig.model,
1004
- ...(modelConfig.temperature !== undefined && { temperature: modelConfig.temperature }),
1005
- ...(modelConfig.maxTokens !== undefined && { maxTokens: modelConfig.maxTokens }),
1006
- ...(modelConfig.topP !== undefined && { topP: modelConfig.topP }),
1007
- ...(modelConfig.systemMessage !== undefined && { systemMessage: modelConfig.systemMessage })
1008
- }
1009
- };
1010
- this.logger.debug('Model configuration updated', modelConfig);
1011
- }
1012
- /**
1013
- * Get the current model configuration.
1014
- *
1015
- * Returns the current AI provider, model, and related settings.
1016
- *
1017
- * @returns Current model configuration
1018
- *
1019
- * @example
1020
- * ```typescript
1021
- * const current = robota.getModel();
1022
- * console.log(`Current: ${current.provider}/${current.model}`);
1023
- * console.log(`Temperature: ${current.temperature}`);
1024
- * console.log(`Max tokens: ${current.maxTokens}`);
1025
- * ```
1026
- */
1027
- getModel() {
1028
- // Ensure managers are initialized before using them
1029
- if (!this.isFullyInitialized) {
1030
- throw new ConfigurationError('Agent must be fully initialized before getting model configuration', { component: 'Robota' });
1031
- }
1032
- const currentProviderInfo = this.aiProviders.getCurrentProvider();
1033
- if (!currentProviderInfo) {
1034
- throw new ConfigurationError('No provider is currently set', { component: 'Robota' });
1035
- }
1036
- const currentProvider = currentProviderInfo.provider;
1037
- const currentModel = currentProviderInfo.model;
1038
- const currentTemperature = this.config.defaultModel.temperature;
1039
- const currentMaxTokens = this.config.defaultModel.maxTokens;
1040
- const currentTopP = this.config.defaultModel.topP;
1041
- const currentSystemMessage = this.config.defaultModel.systemMessage;
1042
- return {
1043
- provider: currentProvider,
1044
- model: currentModel,
1045
- ...(currentTemperature !== undefined && { temperature: currentTemperature }),
1046
- ...(currentMaxTokens !== undefined && { maxTokens: currentMaxTokens }),
1047
- ...(currentTopP !== undefined && { topP: currentTopP }),
1048
- ...(currentSystemMessage !== undefined && { systemMessage: currentSystemMessage })
1049
- };
1050
- }
1051
- /**
1052
- * Register a new tool for function calling.
1053
- *
1054
- * Adds a tool that the AI can call during conversations. The tool's schema
1055
- * defines its name, description, and parameters for the AI to understand.
1056
- *
1057
- * @param tool - The tool instance to register
1058
- *
1059
- * @example
1060
- * ```typescript
1061
- * import { AbstractTool } from '@robota-sdk/agents';
1062
- *
1063
- * class WeatherTool extends AbstractTool {
1064
- * name = 'get_weather';
1065
- * description = 'Get current weather for a location';
1066
- *
1067
- * get schema() {
1068
- * return {
1069
- * name: this.name,
1070
- * description: this.description,
1071
- * parameters: {
1072
- * type: 'object',
1073
- * properties: {
1074
- * location: { type: 'string', description: 'City name' }
1075
- * },
1076
- * required: ['location']
1077
- * }
1078
- * };
1079
- * }
1080
- *
1081
- * async execute(params: { location: string }) {
1082
- * // Implementation here
1083
- * return { temperature: 22, condition: 'sunny' };
1084
- * }
1085
- * }
1086
- *
1087
- * robota.registerTool(new WeatherTool());
1088
- * ```
1089
- */
1090
- registerTool(tool) {
1091
- // Check if tool is already registered to prevent duplicates
1092
- if (this.tools.hasTool(tool.schema.name)) {
1093
- this.logger.warn('Tool already registered, skipping', { toolName: tool.schema.name });
1094
- return;
1095
- }
1096
- // Create an adapter to convert IToolResult.data (tool result payload) to the executor return type.
1097
- const toolExecutor = async (parameters, context) => {
1098
- if (!context) {
1099
- throw new Error('[ROBOTA] Missing ToolExecutionContext for tool execution');
1100
- }
1101
- const result = await tool.execute(parameters, context);
1102
- return result.data;
1103
- };
1104
- this.tools.addTool(tool.schema, toolExecutor);
1105
- this.logger.debug('Tool registered', { toolName: tool.schema.name });
1106
- }
1107
- /**
1108
- * Unregister a tool by name.
1109
- *
1110
- * Removes a previously registered tool, making it unavailable for future AI calls.
1111
- *
1112
- * @param toolName - Name of the tool to unregister
1113
- *
1114
- * @example
1115
- * ```typescript
1116
- * robota.unregisterTool('weather-tool');
1117
- *
1118
- * const stats = robota.getStats();
1119
- * console.log('Remaining tools:', stats.tools);
1120
- * ```
1121
- */
1122
- unregisterTool(toolName) {
1123
- this.tools.removeTool(toolName);
1124
- this.logger.debug('Tool unregistered', { toolName });
1125
- }
1126
- /**
1127
- * Get the current agent configuration.
1128
- *
1129
- * Returns a copy of the current configuration object. Modifications to the
1130
- * returned object do not affect the agent - use updateConfig() to make changes.
1131
- *
1132
- * @returns Copy of the current IAgentConfig
1133
- *
1134
- * @example
1135
- * ```typescript
1136
- * const config = robota.getConfig();
1137
- * console.log('Current model:', config.currentModel);
1138
- * console.log('Available providers:', Object.keys(config.aiProviders || {}));
1139
- * ```
1140
- */
1141
- getConfig() {
1142
- return { ...this.config };
1143
- }
1144
- /**
1145
- * Get comprehensive agent statistics including providers, tools, plugins, modules, and performance data.
1146
- *
1147
- * @returns Object containing all agent statistics and metadata
1148
- *
1149
- * @example
1150
- * ```typescript
1151
- * const stats = robota.getStats();
1152
- * console.log(`Agent: ${stats.name} v${stats.version}`);
1153
- * console.log(`Uptime: ${stats.uptime}ms`);
1154
- * console.log(`Providers: ${stats.providers.join(', ')}`);
1155
- * console.log(`Tools: ${stats.tools.join(', ')}`);
1156
- * console.log(`Plugins: ${stats.plugins.join(', ')}`);
1157
- * console.log(`Modules: ${stats.modules.join(', ')}`);
1158
- * console.log(`Messages: ${stats.historyLength}`);
1159
- * ```
1160
- */
256
+ // --- Stats & Lifecycle ---
1161
257
  getStats() {
1162
- const providers = this.isFullyInitialized ? this.aiProviders.getProviderNames() : [];
1163
- const currentProviderInfo = this.isFullyInitialized ? this.aiProviders.getCurrentProvider() : null;
1164
- const currentProvider = currentProviderInfo ? currentProviderInfo.provider : null;
1165
- const tools = this.isFullyInitialized ? this.tools.getTools().map(tool => tool.name) : [];
1166
- const plugins = this.getPluginNames();
1167
- const modules = this.getModuleNames();
1168
- const history = this.getHistory();
1169
- const uptime = Date.now() - this.startTime;
1170
- return {
258
+ return buildAgentStats({
1171
259
  name: this.name,
1172
260
  version: this.version,
1173
261
  conversationId: this.conversationId,
1174
- providers,
1175
- currentProvider,
1176
- tools,
1177
- plugins,
1178
- modules,
1179
- historyLength: history.length,
1180
- historyStats: {
1181
- userMessages: history.filter(m => m.role === 'user').length,
1182
- assistantMessages: history.filter(m => m.role === 'assistant').length,
1183
- systemMessages: history.filter(m => m.role === 'system').length,
1184
- toolMessages: history.filter(m => m.role === 'tool').length
262
+ startTime: this.startTime,
263
+ isFullyInitialized: this.isFullyInitialized,
264
+ aiProviders: this.aiProviders,
265
+ tools: this.tools,
266
+ getPluginNames: () => this.getPluginNames(),
267
+ getModuleNames: () => this.getModuleNames(),
268
+ getHistory: () => this.getHistory(),
269
+ });
270
+ }
271
+ async destroy() {
272
+ await destroyAgent({
273
+ name: this.name,
274
+ isFullyInitialized: this.isFullyInitialized,
275
+ moduleRegistry: this.moduleRegistry,
276
+ eventEmitter: this.eventEmitter,
277
+ executionService: this.executionService,
278
+ logger: this.logger,
279
+ resetState: () => {
280
+ this.isFullyInitialized = false;
281
+ this.initializationPromise = undefined;
1185
282
  },
1186
- uptime
1187
- };
283
+ });
1188
284
  }
1189
- /**
1190
- * Validate the new agent configuration format.
1191
- * @internal
1192
- */
1193
- validateNewConfig(config) {
1194
- if (!config.name) {
1195
- throw new ConfigurationError('Agent name is required', { component: 'Robota' });
1196
- }
1197
- if (!config.aiProviders || config.aiProviders.length === 0) {
1198
- throw new ConfigurationError('At least one AI provider is required', { component: 'Robota' });
1199
- }
1200
- if (!config.defaultModel) {
1201
- throw new ConfigurationError('Default model configuration is required', { component: 'Robota' });
1202
- }
1203
- if (!config.defaultModel.provider || !config.defaultModel.model) {
1204
- throw new ConfigurationError('Default model must specify both provider and model', { component: 'Robota' });
1205
- }
1206
- // Check for duplicate provider names
1207
- const providerNames = config.aiProviders.map(p => p.name);
1208
- const duplicates = providerNames.filter((name, index) => providerNames.indexOf(name) !== index);
1209
- if (duplicates.length > 0) {
1210
- throw new ConfigurationError(`Duplicate AI provider names: ${duplicates.join(', ')}`, { component: 'Robota', duplicates });
1211
- }
1212
- // Validate that default provider exists in providers list
1213
- if (!providerNames.includes(config.defaultModel.provider)) {
1214
- throw new ConfigurationError(`Default provider '${config.defaultModel.provider}' not found in AI providers list. ` +
1215
- `Available: ${providerNames.join(', ')}`, {
1216
- component: 'Robota',
1217
- defaultProvider: config.defaultModel.provider,
1218
- availableProviders: providerNames
1219
- });
1220
- }
285
+ // --- Initialization ---
286
+ async initialize() {
287
+ await this.ensureFullyInitialized();
1221
288
  }
1222
- /**
1223
- * Clean up and dispose of the agent instance.
1224
- *
1225
- * This method properly cleans up all resources, managers, and services
1226
- * to prevent memory leaks and ensure graceful shutdown.
1227
- *
1228
- * @example
1229
- * ```typescript
1230
- * // Clean shutdown
1231
- * await robota.destroy();
1232
- * console.log('Agent destroyed');
1233
- * ```
1234
- */
1235
- async destroy() {
1236
- this.logger.debug('Destroying Robota instance', { name: this.name });
289
+ async ensureFullyInitialized() {
290
+ if (this.isFullyInitialized)
291
+ return;
292
+ if (!this.initializationPromise)
293
+ this.initializationPromise = this.doAsyncInit();
294
+ await this.initializationPromise;
295
+ }
296
+ async doAsyncInit() {
1237
297
  try {
1238
- // Dispose all modules first (in reverse dependency order)
1239
- if (this.isFullyInitialized && this.moduleRegistry) {
1240
- await this.moduleRegistry.disposeAllModules();
1241
- this.logger.debug('All modules disposed');
1242
- }
1243
- // Cleanup execution service and plugins
1244
- if (this.executionService) {
1245
- // Unsubscribe plugins from module events
1246
- const plugins = this.executionService.getPlugins();
1247
- for (const plugin of plugins) {
1248
- if (plugin.unsubscribeFromModuleEvents && this.eventEmitter) {
1249
- await plugin.unsubscribeFromModuleEvents(this.eventEmitter);
1250
- }
1251
- }
1252
- this.logger.debug('ExecutionService plugins cleaned up');
1253
- }
1254
- // Clear module registry
1255
- if (this.moduleRegistry) {
1256
- this.moduleRegistry.clearAllModules();
1257
- this.logger.debug('ModuleRegistry cleared');
1258
- }
1259
- // Dispose EventEmitter
1260
- if (this.eventEmitter) {
1261
- await this.eventEmitter.destroy();
1262
- this.logger.debug('EventEmitter disposed');
1263
- }
1264
- // Reset state
1265
- this.isFullyInitialized = false;
1266
- this.initializationPromise = undefined;
1267
- this.logger.info('Robota instance destroyed successfully', { name: this.name });
298
+ this.executionService = await performAsyncInitialization({
299
+ config: this.config,
300
+ aiProviders: this.aiProviders,
301
+ tools: this.tools,
302
+ agentFactory: this.agentFactory,
303
+ conversationHistory: this.conversationHistory,
304
+ moduleRegistry: this.moduleRegistry,
305
+ eventEmitter: this.eventEmitter,
306
+ eventService: this.eventService,
307
+ logger: this.logger,
308
+ });
309
+ this.isFullyInitialized = true;
1268
310
  }
1269
311
  catch (error) {
1270
- this.logger.error('Error during Robota destruction', {
1271
- error: error instanceof Error ? error.message : String(error)
312
+ this.logger.error('Robota initialization failed', {
313
+ error: error instanceof Error ? error.message : String(error),
1272
314
  });
1273
315
  throw error;
1274
316
  }
1275
317
  }
318
+ // --- Internal helpers ---
319
+ emitAgentEvent(eventType, data) {
320
+ if (isDefaultEventService(this.agentEventService))
321
+ return;
322
+ this.agentEventService.emit(eventType, { timestamp: new Date(), ...data }, {
323
+ ownerType: AGENT_EVENT_PREFIX,
324
+ ownerId: this.conversationId,
325
+ ownerPath: this.buildOwnerPath(this.config.executionContext),
326
+ });
327
+ }
328
+ buildOwnerPath(executionContext) {
329
+ const base = executionContext?.ownerPath?.length
330
+ ? executionContext.ownerPath.map((segment) => ({ ...segment }))
331
+ : [];
332
+ return [...base, { type: 'agent', id: this.conversationId }];
333
+ }
1276
334
  }
1277
335
  //# sourceMappingURL=robota.js.map