@dcyfr/ai 1.0.4 → 2.1.1

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 (411) hide show
  1. package/CHANGELOG.md +116 -0
  2. package/README.md +381 -9
  3. package/dist/ai/agents/agent-loader.d.ts +12 -0
  4. package/dist/ai/agents/agent-loader.d.ts.map +1 -1
  5. package/dist/ai/agents/agent-loader.js +74 -65
  6. package/dist/ai/agents/agent-loader.js.map +1 -1
  7. package/dist/ai/agents/agent-registry.d.ts +2 -0
  8. package/dist/ai/agents/agent-registry.d.ts.map +1 -1
  9. package/dist/ai/agents/agent-registry.js +15 -14
  10. package/dist/ai/agents/agent-registry.js.map +1 -1
  11. package/dist/ai/agents/agent-router.d.ts +20 -5
  12. package/dist/ai/agents/agent-router.d.ts.map +1 -1
  13. package/dist/ai/agents/agent-router.js +89 -43
  14. package/dist/ai/agents/agent-router.js.map +1 -1
  15. package/dist/ai/agents/index.d.ts +6 -1
  16. package/dist/ai/agents/index.d.ts.map +1 -1
  17. package/dist/ai/agents/index.js +9 -3
  18. package/dist/ai/agents/index.js.map +1 -1
  19. package/dist/ai/agents/instruction-template.d.ts +45 -0
  20. package/dist/ai/agents/instruction-template.d.ts.map +1 -0
  21. package/dist/ai/agents/instruction-template.js +197 -0
  22. package/dist/ai/agents/instruction-template.js.map +1 -0
  23. package/dist/ai/agents/persona-resolver.d.ts +90 -0
  24. package/dist/ai/agents/persona-resolver.d.ts.map +1 -0
  25. package/dist/ai/agents/persona-resolver.js +121 -0
  26. package/dist/ai/agents/persona-resolver.js.map +1 -0
  27. package/dist/ai/agents/schema.d.ts +166 -0
  28. package/dist/ai/agents/schema.d.ts.map +1 -0
  29. package/dist/ai/agents/schema.js +94 -0
  30. package/dist/ai/agents/schema.js.map +1 -0
  31. package/dist/ai/agents/types.d.ts +102 -0
  32. package/dist/ai/agents/types.d.ts.map +1 -1
  33. package/dist/ai/agents-builtin/architecture/index.js +3 -3
  34. package/dist/ai/agents-builtin/content/index.js +1 -1
  35. package/dist/ai/agents-builtin/data/index.js +1 -1
  36. package/dist/ai/agents-builtin/development/index.js +4 -4
  37. package/dist/ai/agents-builtin/devops/index.js +1 -1
  38. package/dist/ai/agents-builtin/index.js +33 -33
  39. package/dist/ai/agents-builtin/performance/index.js +1 -1
  40. package/dist/ai/agents-builtin/research/index.js +1 -1
  41. package/dist/ai/agents-builtin/security/index.js +1 -1
  42. package/dist/ai/agents-builtin/testing/index.js +2 -2
  43. package/dist/ai/config/loader.d.ts.map +1 -1
  44. package/dist/ai/config/loader.js +6 -3
  45. package/dist/ai/config/loader.js.map +1 -1
  46. package/dist/ai/config/schema.d.ts +242 -1156
  47. package/dist/ai/config/schema.d.ts.map +1 -1
  48. package/dist/ai/config/schema.js +69 -20
  49. package/dist/ai/config/schema.js.map +1 -1
  50. package/dist/ai/core/provider-registry.d.ts +32 -0
  51. package/dist/ai/core/provider-registry.d.ts.map +1 -1
  52. package/dist/ai/core/provider-registry.js +189 -14
  53. package/dist/ai/core/provider-registry.js.map +1 -1
  54. package/dist/ai/core/telemetry-engine.d.ts +26 -0
  55. package/dist/ai/core/telemetry-engine.d.ts.map +1 -1
  56. package/dist/ai/core/telemetry-engine.js +81 -1
  57. package/dist/ai/core/telemetry-engine.js.map +1 -1
  58. package/dist/ai/delegation/agent-registry.d.ts +143 -0
  59. package/dist/ai/delegation/agent-registry.d.ts.map +1 -0
  60. package/dist/ai/delegation/agent-registry.js +231 -0
  61. package/dist/ai/delegation/agent-registry.js.map +1 -0
  62. package/dist/ai/delegation/blast-radius-tracker.d.ts +65 -0
  63. package/dist/ai/delegation/blast-radius-tracker.d.ts.map +1 -0
  64. package/dist/ai/delegation/blast-radius-tracker.js +81 -0
  65. package/dist/ai/delegation/blast-radius-tracker.js.map +1 -0
  66. package/dist/ai/delegation/capability-bootstrap.d.ts +40 -0
  67. package/dist/ai/delegation/capability-bootstrap.d.ts.map +1 -0
  68. package/dist/ai/delegation/capability-bootstrap.js +431 -0
  69. package/dist/ai/delegation/capability-bootstrap.js.map +1 -0
  70. package/dist/ai/delegation/capability-registry.d.ts +81 -0
  71. package/dist/ai/delegation/capability-registry.d.ts.map +1 -0
  72. package/dist/ai/delegation/capability-registry.js +339 -0
  73. package/dist/ai/delegation/capability-registry.js.map +1 -0
  74. package/dist/ai/delegation/chain-tracker.d.ts +152 -0
  75. package/dist/ai/delegation/chain-tracker.d.ts.map +1 -0
  76. package/dist/ai/delegation/chain-tracker.js +336 -0
  77. package/dist/ai/delegation/chain-tracker.js.map +1 -0
  78. package/dist/ai/delegation/circuit-breaker.d.ts +59 -0
  79. package/dist/ai/delegation/circuit-breaker.d.ts.map +1 -0
  80. package/dist/ai/delegation/circuit-breaker.js +153 -0
  81. package/dist/ai/delegation/circuit-breaker.js.map +1 -0
  82. package/dist/ai/delegation/contract-manager.d.ts +415 -0
  83. package/dist/ai/delegation/contract-manager.d.ts.map +1 -0
  84. package/dist/ai/delegation/contract-manager.js +1258 -0
  85. package/dist/ai/delegation/contract-manager.js.map +1 -0
  86. package/dist/ai/delegation/delegation-manager.d.ts +505 -0
  87. package/dist/ai/delegation/delegation-manager.d.ts.map +1 -0
  88. package/dist/ai/delegation/delegation-manager.js +773 -0
  89. package/dist/ai/delegation/delegation-manager.js.map +1 -0
  90. package/dist/ai/delegation/event-schemas.d.ts +101 -0
  91. package/dist/ai/delegation/event-schemas.d.ts.map +1 -0
  92. package/dist/ai/delegation/event-schemas.js +59 -0
  93. package/dist/ai/delegation/event-schemas.js.map +1 -0
  94. package/dist/ai/delegation/execution-mode-dashboard.d.ts +109 -0
  95. package/dist/ai/delegation/execution-mode-dashboard.d.ts.map +1 -0
  96. package/dist/ai/delegation/execution-mode-dashboard.js +167 -0
  97. package/dist/ai/delegation/execution-mode-dashboard.js.map +1 -0
  98. package/dist/ai/delegation/feature-flags.d.ts +191 -0
  99. package/dist/ai/delegation/feature-flags.d.ts.map +1 -0
  100. package/dist/ai/delegation/feature-flags.js +332 -0
  101. package/dist/ai/delegation/feature-flags.js.map +1 -0
  102. package/dist/ai/delegation/index.d.ts +51 -0
  103. package/dist/ai/delegation/index.d.ts.map +1 -0
  104. package/dist/ai/delegation/index.js +39 -0
  105. package/dist/ai/delegation/index.js.map +1 -0
  106. package/dist/ai/delegation/middleware/chain-depth-middleware.d.ts +39 -0
  107. package/dist/ai/delegation/middleware/chain-depth-middleware.d.ts.map +1 -0
  108. package/dist/ai/delegation/middleware/chain-depth-middleware.js +77 -0
  109. package/dist/ai/delegation/middleware/chain-depth-middleware.js.map +1 -0
  110. package/dist/ai/delegation/middleware/chain-tracker-middleware.d.ts +46 -0
  111. package/dist/ai/delegation/middleware/chain-tracker-middleware.d.ts.map +1 -0
  112. package/dist/ai/delegation/middleware/chain-tracker-middleware.js +89 -0
  113. package/dist/ai/delegation/middleware/chain-tracker-middleware.js.map +1 -0
  114. package/dist/ai/delegation/middleware/content-policy-middleware.d.ts +31 -0
  115. package/dist/ai/delegation/middleware/content-policy-middleware.d.ts.map +1 -0
  116. package/dist/ai/delegation/middleware/content-policy-middleware.js +82 -0
  117. package/dist/ai/delegation/middleware/content-policy-middleware.js.map +1 -0
  118. package/dist/ai/delegation/middleware/feature-flag-middleware.d.ts +46 -0
  119. package/dist/ai/delegation/middleware/feature-flag-middleware.d.ts.map +1 -0
  120. package/dist/ai/delegation/middleware/feature-flag-middleware.js +59 -0
  121. package/dist/ai/delegation/middleware/feature-flag-middleware.js.map +1 -0
  122. package/dist/ai/delegation/middleware/identity-middleware.d.ts +23 -0
  123. package/dist/ai/delegation/middleware/identity-middleware.d.ts.map +1 -0
  124. package/dist/ai/delegation/middleware/identity-middleware.js +64 -0
  125. package/dist/ai/delegation/middleware/identity-middleware.js.map +1 -0
  126. package/dist/ai/delegation/middleware/permissions-middleware.d.ts +48 -0
  127. package/dist/ai/delegation/middleware/permissions-middleware.d.ts.map +1 -0
  128. package/dist/ai/delegation/middleware/permissions-middleware.js +107 -0
  129. package/dist/ai/delegation/middleware/permissions-middleware.js.map +1 -0
  130. package/dist/ai/delegation/middleware/rate-limiter-middleware.d.ts +38 -0
  131. package/dist/ai/delegation/middleware/rate-limiter-middleware.d.ts.map +1 -0
  132. package/dist/ai/delegation/middleware/rate-limiter-middleware.js +65 -0
  133. package/dist/ai/delegation/middleware/rate-limiter-middleware.js.map +1 -0
  134. package/dist/ai/delegation/middleware/reputation-middleware.d.ts +39 -0
  135. package/dist/ai/delegation/middleware/reputation-middleware.d.ts.map +1 -0
  136. package/dist/ai/delegation/middleware/reputation-middleware.js +75 -0
  137. package/dist/ai/delegation/middleware/reputation-middleware.js.map +1 -0
  138. package/dist/ai/delegation/middleware/resource-limiter-middleware.d.ts +52 -0
  139. package/dist/ai/delegation/middleware/resource-limiter-middleware.d.ts.map +1 -0
  140. package/dist/ai/delegation/middleware/resource-limiter-middleware.js +112 -0
  141. package/dist/ai/delegation/middleware/resource-limiter-middleware.js.map +1 -0
  142. package/dist/ai/delegation/middleware/threat-validator-middleware.d.ts +23 -0
  143. package/dist/ai/delegation/middleware/threat-validator-middleware.d.ts.map +1 -0
  144. package/dist/ai/delegation/middleware/threat-validator-middleware.js +83 -0
  145. package/dist/ai/delegation/middleware/threat-validator-middleware.js.map +1 -0
  146. package/dist/ai/delegation/middleware/tlp-middleware.d.ts +23 -0
  147. package/dist/ai/delegation/middleware/tlp-middleware.d.ts.map +1 -0
  148. package/dist/ai/delegation/middleware/tlp-middleware.js +59 -0
  149. package/dist/ai/delegation/middleware/tlp-middleware.js.map +1 -0
  150. package/dist/ai/delegation/monitoring.d.ts +298 -0
  151. package/dist/ai/delegation/monitoring.d.ts.map +1 -0
  152. package/dist/ai/delegation/monitoring.js +584 -0
  153. package/dist/ai/delegation/monitoring.js.map +1 -0
  154. package/dist/ai/delegation/security-middleware-chain.d.ts +71 -0
  155. package/dist/ai/delegation/security-middleware-chain.d.ts.map +1 -0
  156. package/dist/ai/delegation/security-middleware-chain.js +163 -0
  157. package/dist/ai/delegation/security-middleware-chain.js.map +1 -0
  158. package/dist/ai/delegation/session-checkpoint.d.ts +77 -0
  159. package/dist/ai/delegation/session-checkpoint.d.ts.map +1 -0
  160. package/dist/ai/delegation/session-checkpoint.js +131 -0
  161. package/dist/ai/delegation/session-checkpoint.js.map +1 -0
  162. package/dist/ai/delegation/session-manager.d.ts +131 -0
  163. package/dist/ai/delegation/session-manager.d.ts.map +1 -0
  164. package/dist/ai/delegation/session-manager.js +243 -0
  165. package/dist/ai/delegation/session-manager.js.map +1 -0
  166. package/dist/ai/delegation/session-queue.d.ts +95 -0
  167. package/dist/ai/delegation/session-queue.d.ts.map +1 -0
  168. package/dist/ai/delegation/session-queue.js +136 -0
  169. package/dist/ai/delegation/session-queue.js.map +1 -0
  170. package/dist/ai/delegation/timeout-watchdog.d.ts +60 -0
  171. package/dist/ai/delegation/timeout-watchdog.d.ts.map +1 -0
  172. package/dist/ai/delegation/timeout-watchdog.js +100 -0
  173. package/dist/ai/delegation/timeout-watchdog.js.map +1 -0
  174. package/dist/ai/examples/integration-demo.d.ts +27 -0
  175. package/dist/ai/examples/integration-demo.d.ts.map +1 -0
  176. package/dist/ai/examples/integration-demo.js +536 -0
  177. package/dist/ai/examples/integration-demo.js.map +1 -0
  178. package/dist/ai/index.d.ts +25 -0
  179. package/dist/ai/index.d.ts.map +1 -1
  180. package/dist/ai/index.js +34 -11
  181. package/dist/ai/index.js.map +1 -1
  182. package/dist/ai/mcp/servers/analytics/index.js +67 -11
  183. package/dist/ai/mcp/servers/analytics/index.js.map +1 -1
  184. package/dist/ai/mcp/servers/content-manager/index.d.ts.map +1 -1
  185. package/dist/ai/mcp/servers/content-manager/index.js +50 -4
  186. package/dist/ai/mcp/servers/content-manager/index.js.map +1 -1
  187. package/dist/ai/mcp/servers/delegation-monitor/index.d.ts +36 -0
  188. package/dist/ai/mcp/servers/delegation-monitor/index.d.ts.map +1 -0
  189. package/dist/ai/mcp/servers/delegation-monitor/index.js +757 -0
  190. package/dist/ai/mcp/servers/delegation-monitor/index.js.map +1 -0
  191. package/dist/ai/mcp/servers/design-tokens/index.d.ts.map +1 -1
  192. package/dist/ai/mcp/servers/design-tokens/index.js +62 -39
  193. package/dist/ai/mcp/servers/design-tokens/index.js.map +1 -1
  194. package/dist/ai/mcp/servers/promptintel/index.js +15 -3
  195. package/dist/ai/mcp/servers/promptintel/index.js.map +1 -1
  196. package/dist/ai/mcp/servers/shared/rate-limiter.d.ts.map +1 -1
  197. package/dist/ai/mcp/servers/shared/rate-limiter.js +3 -1
  198. package/dist/ai/mcp/servers/shared/rate-limiter.js.map +1 -1
  199. package/dist/ai/mcp/servers/shared/redis-client.d.ts.map +1 -1
  200. package/dist/ai/mcp/servers/shared/redis-client.js +54 -47
  201. package/dist/ai/mcp/servers/shared/redis-client.js.map +1 -1
  202. package/dist/ai/mcp/servers/shared/types.d.ts +9 -0
  203. package/dist/ai/mcp/servers/shared/types.d.ts.map +1 -1
  204. package/dist/ai/mcp/servers/shared/utils.d.ts +9 -1
  205. package/dist/ai/mcp/servers/shared/utils.d.ts.map +1 -1
  206. package/dist/ai/mcp/servers/shared/utils.js +52 -2
  207. package/dist/ai/mcp/servers/shared/utils.js.map +1 -1
  208. package/dist/ai/memory/config.d.ts +18 -3
  209. package/dist/ai/memory/config.d.ts.map +1 -1
  210. package/dist/ai/memory/config.js +61 -15
  211. package/dist/ai/memory/config.js.map +1 -1
  212. package/dist/ai/memory/dcyfr-memory.d.ts +4 -0
  213. package/dist/ai/memory/dcyfr-memory.d.ts.map +1 -1
  214. package/dist/ai/memory/dcyfr-memory.js +44 -6
  215. package/dist/ai/memory/dcyfr-memory.js.map +1 -1
  216. package/dist/ai/memory/mem0-client.d.ts.map +1 -1
  217. package/dist/ai/memory/mem0-client.js +53 -14
  218. package/dist/ai/memory/mem0-client.js.map +1 -1
  219. package/dist/ai/permissions/attenuation-engine.d.ts +159 -0
  220. package/dist/ai/permissions/attenuation-engine.d.ts.map +1 -0
  221. package/dist/ai/permissions/attenuation-engine.js +511 -0
  222. package/dist/ai/permissions/attenuation-engine.js.map +1 -0
  223. package/dist/ai/plugins/plugin-loader.d.ts +4 -0
  224. package/dist/ai/plugins/plugin-loader.d.ts.map +1 -1
  225. package/dist/ai/plugins/plugin-loader.js +28 -28
  226. package/dist/ai/plugins/plugin-loader.js.map +1 -1
  227. package/dist/ai/reputation/execution-mode-reputation.d.ts +104 -0
  228. package/dist/ai/reputation/execution-mode-reputation.d.ts.map +1 -0
  229. package/dist/ai/reputation/execution-mode-reputation.js +142 -0
  230. package/dist/ai/reputation/execution-mode-reputation.js.map +1 -0
  231. package/dist/ai/reputation/reputation-engine.d.ts +204 -0
  232. package/dist/ai/reputation/reputation-engine.d.ts.map +1 -0
  233. package/dist/ai/reputation/reputation-engine.js +426 -0
  234. package/dist/ai/reputation/reputation-engine.js.map +1 -0
  235. package/dist/ai/runtime/agent-runtime.d.ts +193 -0
  236. package/dist/ai/runtime/agent-runtime.d.ts.map +1 -0
  237. package/dist/ai/runtime/agent-runtime.js +1009 -0
  238. package/dist/ai/runtime/agent-runtime.js.map +1 -0
  239. package/dist/ai/runtime/index.d.ts +11 -0
  240. package/dist/ai/runtime/index.d.ts.map +1 -0
  241. package/dist/ai/runtime/index.js +9 -0
  242. package/dist/ai/runtime/index.js.map +1 -0
  243. package/dist/ai/runtime/telemetry-schema.d.ts +192 -0
  244. package/dist/ai/runtime/telemetry-schema.d.ts.map +1 -0
  245. package/dist/ai/runtime/telemetry-schema.js +200 -0
  246. package/dist/ai/runtime/telemetry-schema.js.map +1 -0
  247. package/dist/ai/runtime/types.d.ts +236 -0
  248. package/dist/ai/runtime/types.d.ts.map +1 -0
  249. package/dist/ai/runtime/types.js +10 -0
  250. package/dist/ai/runtime/types.js.map +1 -0
  251. package/dist/ai/src/batch-processor.d.ts +298 -0
  252. package/dist/ai/src/batch-processor.d.ts.map +1 -0
  253. package/dist/ai/src/batch-processor.js +520 -0
  254. package/dist/ai/src/batch-processor.js.map +1 -0
  255. package/dist/ai/src/capability-bootstrap.d.ts +222 -0
  256. package/dist/ai/src/capability-bootstrap.d.ts.map +1 -0
  257. package/dist/ai/src/capability-bootstrap.js +421 -0
  258. package/dist/ai/src/capability-bootstrap.js.map +1 -0
  259. package/dist/ai/src/capability-manifest-generator.d.ts +61 -0
  260. package/dist/ai/src/capability-manifest-generator.d.ts.map +1 -0
  261. package/dist/ai/src/capability-manifest-generator.js +700 -0
  262. package/dist/ai/src/capability-manifest-generator.js.map +1 -0
  263. package/dist/ai/src/capability-registry.d.ts +157 -0
  264. package/dist/ai/src/capability-registry.d.ts.map +1 -0
  265. package/dist/ai/src/capability-registry.js +577 -0
  266. package/dist/ai/src/capability-registry.js.map +1 -0
  267. package/dist/ai/src/cli/telemetry-dashboard.d.ts +132 -0
  268. package/dist/ai/src/cli/telemetry-dashboard.d.ts.map +1 -0
  269. package/dist/ai/src/cli/telemetry-dashboard.js +565 -0
  270. package/dist/ai/src/cli/telemetry-dashboard.js.map +1 -0
  271. package/dist/ai/src/delegation/feature-flags.d.ts +213 -0
  272. package/dist/ai/src/delegation/feature-flags.d.ts.map +1 -0
  273. package/dist/ai/src/delegation/feature-flags.js +395 -0
  274. package/dist/ai/src/delegation/feature-flags.js.map +1 -0
  275. package/dist/ai/src/delegation/liability-firebreak.d.ts +303 -0
  276. package/dist/ai/src/delegation/liability-firebreak.d.ts.map +1 -0
  277. package/dist/ai/src/delegation/liability-firebreak.js +643 -0
  278. package/dist/ai/src/delegation/liability-firebreak.js.map +1 -0
  279. package/dist/ai/src/delegation/security-threat-model.d.ts +171 -0
  280. package/dist/ai/src/delegation/security-threat-model.d.ts.map +1 -0
  281. package/dist/ai/src/delegation/security-threat-model.js +723 -0
  282. package/dist/ai/src/delegation/security-threat-model.js.map +1 -0
  283. package/dist/ai/src/delegation/tlp-enforcement.d.ts +146 -0
  284. package/dist/ai/src/delegation/tlp-enforcement.d.ts.map +1 -0
  285. package/dist/ai/src/delegation/tlp-enforcement.js +382 -0
  286. package/dist/ai/src/delegation/tlp-enforcement.js.map +1 -0
  287. package/dist/ai/src/delegation-capability-integration.d.ts +154 -0
  288. package/dist/ai/src/delegation-capability-integration.d.ts.map +1 -0
  289. package/dist/ai/src/delegation-capability-integration.js +351 -0
  290. package/dist/ai/src/delegation-capability-integration.js.map +1 -0
  291. package/dist/ai/src/end-to-end-workflow-orchestrator.d.ts +325 -0
  292. package/dist/ai/src/end-to-end-workflow-orchestrator.d.ts.map +1 -0
  293. package/dist/ai/src/end-to-end-workflow-orchestrator.js +801 -0
  294. package/dist/ai/src/end-to-end-workflow-orchestrator.js.map +1 -0
  295. package/dist/ai/src/enhanced-capability-detection.d.ts +237 -0
  296. package/dist/ai/src/enhanced-capability-detection.d.ts.map +1 -0
  297. package/dist/ai/src/enhanced-capability-detection.js +448 -0
  298. package/dist/ai/src/enhanced-capability-detection.js.map +1 -0
  299. package/dist/ai/src/intelligent-cache-manager.d.ts +327 -0
  300. package/dist/ai/src/intelligent-cache-manager.d.ts.map +1 -0
  301. package/dist/ai/src/intelligent-cache-manager.js +634 -0
  302. package/dist/ai/src/intelligent-cache-manager.js.map +1 -0
  303. package/dist/ai/src/mcp-auto-configuration.d.ts +232 -0
  304. package/dist/ai/src/mcp-auto-configuration.d.ts.map +1 -0
  305. package/dist/ai/src/mcp-auto-configuration.js +445 -0
  306. package/dist/ai/src/mcp-auto-configuration.js.map +1 -0
  307. package/dist/ai/src/performance-profiler.d.ts +351 -0
  308. package/dist/ai/src/performance-profiler.d.ts.map +1 -0
  309. package/dist/ai/src/performance-profiler.js +475 -0
  310. package/dist/ai/src/performance-profiler.js.map +1 -0
  311. package/dist/ai/src/personas/hooks/before-llm-call.d.ts +96 -0
  312. package/dist/ai/src/personas/hooks/before-llm-call.d.ts.map +1 -0
  313. package/dist/ai/src/personas/hooks/before-llm-call.js +83 -0
  314. package/dist/ai/src/personas/hooks/before-llm-call.js.map +1 -0
  315. package/dist/ai/src/personas/index.d.ts +10 -0
  316. package/dist/ai/src/personas/index.d.ts.map +1 -0
  317. package/dist/ai/src/personas/index.js +10 -0
  318. package/dist/ai/src/personas/index.js.map +1 -0
  319. package/dist/ai/src/personas/persona-loader.d.ts +42 -0
  320. package/dist/ai/src/personas/persona-loader.d.ts.map +1 -0
  321. package/dist/ai/src/personas/persona-loader.js +162 -0
  322. package/dist/ai/src/personas/persona-loader.js.map +1 -0
  323. package/dist/ai/src/personas/types.d.ts +199 -0
  324. package/dist/ai/src/personas/types.d.ts.map +1 -0
  325. package/dist/ai/src/personas/types.js +7 -0
  326. package/dist/ai/src/personas/types.js.map +1 -0
  327. package/dist/ai/src/personas/voice-resolver.d.ts +40 -0
  328. package/dist/ai/src/personas/voice-resolver.d.ts.map +1 -0
  329. package/dist/ai/src/personas/voice-resolver.js +201 -0
  330. package/dist/ai/src/personas/voice-resolver.js.map +1 -0
  331. package/dist/ai/src/resource-monitor.d.ts +311 -0
  332. package/dist/ai/src/resource-monitor.d.ts.map +1 -0
  333. package/dist/ai/src/resource-monitor.js +475 -0
  334. package/dist/ai/src/resource-monitor.js.map +1 -0
  335. package/dist/ai/src/runtime/agent-runtime.d.ts +340 -0
  336. package/dist/ai/src/runtime/agent-runtime.d.ts.map +1 -0
  337. package/dist/ai/src/runtime/agent-runtime.js +1084 -0
  338. package/dist/ai/src/runtime/agent-runtime.js.map +1 -0
  339. package/dist/ai/src/telemetry/delegation-telemetry.d.ts +287 -0
  340. package/dist/ai/src/telemetry/delegation-telemetry.d.ts.map +1 -0
  341. package/dist/ai/src/telemetry/delegation-telemetry.js +389 -0
  342. package/dist/ai/src/telemetry/delegation-telemetry.js.map +1 -0
  343. package/dist/ai/src/telemetry/index.d.ts +48 -0
  344. package/dist/ai/src/telemetry/index.d.ts.map +1 -0
  345. package/dist/ai/src/telemetry/index.js +48 -0
  346. package/dist/ai/src/telemetry/index.js.map +1 -0
  347. package/dist/ai/src/telemetry/runtime-telemetry-integration.d.ts +67 -0
  348. package/dist/ai/src/telemetry/runtime-telemetry-integration.d.ts.map +1 -0
  349. package/dist/ai/src/telemetry/runtime-telemetry-integration.js +415 -0
  350. package/dist/ai/src/telemetry/runtime-telemetry-integration.js.map +1 -0
  351. package/dist/ai/src/telemetry/telemetry-utils.d.ts +119 -0
  352. package/dist/ai/src/telemetry/telemetry-utils.d.ts.map +1 -0
  353. package/dist/ai/src/telemetry/telemetry-utils.js +250 -0
  354. package/dist/ai/src/telemetry/telemetry-utils.js.map +1 -0
  355. package/dist/ai/src/types/agent-capabilities.d.ts +227 -0
  356. package/dist/ai/src/types/agent-capabilities.d.ts.map +1 -0
  357. package/dist/ai/src/types/agent-capabilities.js +11 -0
  358. package/dist/ai/src/types/agent-capabilities.js.map +1 -0
  359. package/dist/ai/src/types/context-verification.d.ts +158 -0
  360. package/dist/ai/src/types/context-verification.d.ts.map +1 -0
  361. package/dist/ai/src/types/context-verification.js +73 -0
  362. package/dist/ai/src/types/context-verification.js.map +1 -0
  363. package/dist/ai/src/types/delegation-contracts.d.ts +296 -0
  364. package/dist/ai/src/types/delegation-contracts.d.ts.map +1 -0
  365. package/dist/ai/src/types/delegation-contracts.js +17 -0
  366. package/dist/ai/src/types/delegation-contracts.js.map +1 -0
  367. package/dist/ai/src/validation-pipeline-integration.d.ts +266 -0
  368. package/dist/ai/src/validation-pipeline-integration.d.ts.map +1 -0
  369. package/dist/ai/src/validation-pipeline-integration.js +695 -0
  370. package/dist/ai/src/validation-pipeline-integration.js.map +1 -0
  371. package/dist/ai/src/verification/multi-modal-formatters.d.ts +57 -0
  372. package/dist/ai/src/verification/multi-modal-formatters.d.ts.map +1 -0
  373. package/dist/ai/src/verification/multi-modal-formatters.js +655 -0
  374. package/dist/ai/src/verification/multi-modal-formatters.js.map +1 -0
  375. package/dist/ai/src/verification/output-formatter.d.ts +186 -0
  376. package/dist/ai/src/verification/output-formatter.d.ts.map +1 -0
  377. package/dist/ai/src/verification/output-formatter.js +296 -0
  378. package/dist/ai/src/verification/output-formatter.js.map +1 -0
  379. package/dist/ai/src/verification/parser-integration.d.ts +137 -0
  380. package/dist/ai/src/verification/parser-integration.d.ts.map +1 -0
  381. package/dist/ai/src/verification/parser-integration.js +273 -0
  382. package/dist/ai/src/verification/parser-integration.js.map +1 -0
  383. package/dist/ai/types/agent-capabilities.d.ts +387 -0
  384. package/dist/ai/types/agent-capabilities.d.ts.map +1 -0
  385. package/dist/ai/types/agent-capabilities.js +32 -0
  386. package/dist/ai/types/agent-capabilities.js.map +1 -0
  387. package/dist/ai/types/delegation-contracts.d.ts +291 -0
  388. package/dist/ai/types/delegation-contracts.d.ts.map +1 -0
  389. package/dist/ai/types/delegation-contracts.js +14 -0
  390. package/dist/ai/types/delegation-contracts.js.map +1 -0
  391. package/dist/ai/types/index.d.ts +4 -1
  392. package/dist/ai/types/index.d.ts.map +1 -1
  393. package/dist/ai/types/index.js +4 -1
  394. package/dist/ai/types/index.js.map +1 -1
  395. package/dist/ai/types/permission-tokens.d.ts +365 -0
  396. package/dist/ai/types/permission-tokens.d.ts.map +1 -0
  397. package/dist/ai/types/permission-tokens.js +13 -0
  398. package/dist/ai/types/permission-tokens.js.map +1 -0
  399. package/dist/ai/types/security-middleware.d.ts +130 -0
  400. package/dist/ai/types/security-middleware.d.ts.map +1 -0
  401. package/dist/ai/types/security-middleware.js +13 -0
  402. package/dist/ai/types/security-middleware.js.map +1 -0
  403. package/dist/ai/utils/storage.d.ts.map +1 -1
  404. package/dist/ai/utils/storage.js +6 -3
  405. package/dist/ai/utils/storage.js.map +1 -1
  406. package/dist/ai/validation/validation-framework.js +1 -1
  407. package/dist/ai/verification/policy-framework.d.ts +161 -0
  408. package/dist/ai/verification/policy-framework.d.ts.map +1 -0
  409. package/dist/ai/verification/policy-framework.js +436 -0
  410. package/dist/ai/verification/policy-framework.js.map +1 -0
  411. package/package.json +36 -8
@@ -0,0 +1,1009 @@
1
+ import { PermissionDeniedError } from './types.js';
2
+ function parseVersion(version) {
3
+ const parts = version.replace(/^[^\d]*/, '').split('.').map(Number);
4
+ return {
5
+ major: parts[0] || 0,
6
+ minor: parts[1] || 0,
7
+ patch: parts[2] || 0,
8
+ };
9
+ }
10
+ function checkVersionCompatibility(runtimeVersion, agentsVersion) {
11
+ // Current @dcyfr/ai version
12
+ const runtime = parseVersion(runtimeVersion);
13
+ if (!agentsVersion) {
14
+ console.warn('[AgentRuntime] Warning: Unable to detect @dcyfr/ai-agents version. ' +
15
+ 'Ensure versions are compatible. Current runtime: v' + runtimeVersion);
16
+ return;
17
+ }
18
+ const agents = parseVersion(agentsVersion);
19
+ // Version compatibility rules:
20
+ // - Major version must match (1.x.x with 1.x.x)
21
+ // - Runtime can be newer minor version than agents
22
+ // - Agents should not be more than 1 major version ahead
23
+ if (runtime.major !== agents.major) {
24
+ console.warn('[AgentRuntime] Version Mismatch Warning: ' +
25
+ `Runtime v${runtimeVersion} (major ${runtime.major}) ` +
26
+ `with Agents v${agentsVersion} (major ${agents.major}). ` +
27
+ 'Different major versions may cause compatibility issues. ' +
28
+ 'Consider upgrading to matching versions.');
29
+ }
30
+ else if (agents.minor > runtime.minor + 2) {
31
+ console.warn('[AgentRuntime] Version Skew Warning: ' +
32
+ `Agents v${agentsVersion} is significantly ahead of runtime v${runtimeVersion}. ` +
33
+ 'Consider upgrading @dcyfr/ai for latest features and compatibility.');
34
+ }
35
+ }
36
+ /**
37
+ * AgentRuntime - Executes multi-step tasks with LLM integration
38
+ *
39
+ * Bridges agent execution loop with LLM providers, memory, and telemetry.
40
+ * Supports tool execution, observation recording, and multi-iteration reasoning.
41
+ *
42
+ * @example
43
+ * ```typescript
44
+ * const runtime = new AgentRuntime(
45
+ * 'code-reviewer',
46
+ * providerRegistry,
47
+ * memory,
48
+ * telemetry
49
+ * );
50
+ *
51
+ * const result = await runtime.execute({
52
+ * task: 'Review the authentication logic in auth.ts',
53
+ * userId: 'user-123',
54
+ * sessionId: 'session-456',
55
+ * tools: [fileSearchTool, readFileTool]
56
+ * });
57
+ * ```
58
+ */
59
+ export class AgentRuntime {
60
+ agentName;
61
+ providerRegistry;
62
+ memory;
63
+ telemetry;
64
+ config;
65
+ beforeExecuteHooks = [];
66
+ afterExecuteHooks = [];
67
+ constructor(agentName, providerRegistry, memory, telemetry, config) {
68
+ // Version compatibility check
69
+ this.performVersionCheck();
70
+ this.agentName = agentName;
71
+ this.providerRegistry = providerRegistry;
72
+ this.memory = memory;
73
+ this.telemetry = telemetry;
74
+ // Apply default configuration
75
+ this.config = {
76
+ maxIterations: config?.maxIterations ?? 10,
77
+ timeout: config?.timeout ?? 120000, // 2 minutes
78
+ memoryEnabled: config?.memoryEnabled ?? true,
79
+ memoryTimeout: config?.memoryTimeout ?? 3000,
80
+ memoryRelevanceThreshold: config?.memoryRelevanceThreshold ?? 0.7,
81
+ summarizationEnabled: config?.summarizationEnabled ?? true,
82
+ summarizationInterval: config?.summarizationInterval ?? 5,
83
+ workingMemoryEnabled: config?.workingMemoryEnabled ?? true,
84
+ persistWorkingMemory: config?.persistWorkingMemory ?? false,
85
+ debugWorkingMemory: config?.debugWorkingMemory ?? false,
86
+ systemPrompt: config?.systemPrompt ?? this.getDefaultSystemPrompt(),
87
+ };
88
+ }
89
+ /**
90
+ * Check version compatibility between @dcyfr/ai and @dcyfr/ai-agents
91
+ * Logs warnings if version mismatches could cause issues
92
+ */
93
+ performVersionCheck() {
94
+ try {
95
+ // Get current runtime version from package.json
96
+ const runtimeVersion = '1.0.4'; // This should be dynamically imported in production
97
+ // Try to detect agents package version
98
+ let agentsVersion;
99
+ try {
100
+ // This is a best-effort detection - in practice, the calling package
101
+ // would need to provide this information
102
+ const process = globalThis.process;
103
+ if (process?.versions) {
104
+ // Check environment for version info
105
+ agentsVersion = process.env.DCYFR_AGENTS_VERSION;
106
+ }
107
+ }
108
+ catch {
109
+ // Ignore errors in version detection
110
+ }
111
+ checkVersionCompatibility(runtimeVersion, agentsVersion);
112
+ }
113
+ catch (error) {
114
+ // Don't fail initialization due to version checking issues
115
+ console.warn('[AgentRuntime] Version check failed:', error);
116
+ }
117
+ }
118
+ /**
119
+ * Register a before-execution hook
120
+ *
121
+ * Hooks are called before task execution begins.
122
+ * A hook can reject execution by throwing PermissionDeniedError.
123
+ *
124
+ * @param hook - Function to call before execution
125
+ *
126
+ * @example
127
+ * ```typescript
128
+ * runtime.beforeExecute(async (context) => {
129
+ * if (!hasPermission(context.userId, 'execute')) {
130
+ * throw new PermissionDeniedError('User lacks execute permission');
131
+ * }
132
+ * });
133
+ * ```
134
+ */
135
+ beforeExecute(hook) {
136
+ this.beforeExecuteHooks.push(hook);
137
+ }
138
+ /**
139
+ * Register an after-execution hook
140
+ *
141
+ * Hooks are called after task execution completes (success or failure).
142
+ * Useful for logging, auditing, or cleanup operations.
143
+ *
144
+ * @param hook - Function to call after execution
145
+ *
146
+ * @example
147
+ * ```typescript
148
+ * runtime.afterExecute(async (context, result) => {
149
+ * await auditLog.record({
150
+ * agent: context.agentName,
151
+ * task: context.task,
152
+ * success: result.success,
153
+ * cost: result.cost,
154
+ * });
155
+ * });
156
+ * ```
157
+ */
158
+ afterExecute(hook) {
159
+ this.afterExecuteHooks.push(hook);
160
+ }
161
+ /**
162
+ * Execute a task from start to completion
163
+ *
164
+ * @param context - Task context with description, tools, and metadata
165
+ * @returns Execution result with output, cost, and telemetry data
166
+ */
167
+ async handlePermissionDenied(error, hookContext, startTime) {
168
+ const executionTime = Date.now() - startTime;
169
+ const result = {
170
+ success: false,
171
+ error: error.message,
172
+ outcome: 'error',
173
+ executionTime,
174
+ cost: 0,
175
+ iterations: 0,
176
+ };
177
+ await this.runAfterExecuteHooks(hookContext, result);
178
+ return result;
179
+ }
180
+ async runBeforeExecuteHooks(hookContext, startTime) {
181
+ for (const hook of this.beforeExecuteHooks) {
182
+ try {
183
+ await hook(hookContext);
184
+ }
185
+ catch (error) {
186
+ if (error instanceof PermissionDeniedError) {
187
+ return this.handlePermissionDenied(error, hookContext, startTime);
188
+ }
189
+ const hookError = error instanceof Error ? error : new Error(String(error));
190
+ Object.assign(hookError, { isHookError: true });
191
+ throw hookError;
192
+ }
193
+ }
194
+ return null;
195
+ }
196
+ async execute(context) {
197
+ const startTime = Date.now();
198
+ let sessionManager;
199
+ let sessionId;
200
+ let memoryWriteFailed = false;
201
+ try {
202
+ // Create hook context
203
+ const hookContext = {
204
+ agentName: this.agentName,
205
+ task: context.task,
206
+ userId: context.userId,
207
+ sessionId: context.sessionId,
208
+ timestamp: Date.now(),
209
+ };
210
+ // Run before-execution hooks
211
+ const earlyResult = await this.runBeforeExecuteHooks(hookContext, startTime);
212
+ if (earlyResult !== null)
213
+ return earlyResult;
214
+ // Create telemetry session
215
+ // Note: startSession expects AgentType, but we have agentName as string
216
+ // For now, we'll use 'claude' as default - this should be configurable
217
+ sessionManager = this.telemetry.startSession('claude', // TODO: Make agentType configurable
218
+ {
219
+ taskType: 'feature',
220
+ description: context.task,
221
+ });
222
+ sessionId = sessionManager.getSession().sessionId;
223
+ // Emit start event
224
+ this.emitEvent({
225
+ type: 'start',
226
+ agentName: this.agentName,
227
+ task: context.task,
228
+ timestamp: Date.now(),
229
+ });
230
+ // Initialize state
231
+ const state = await this.initializeState(context);
232
+ // Execute with timeout
233
+ const result = await this.executeWithTimeout(state, context, startTime);
234
+ return await this.handleSuccessfulExecution(state, result, sessionManager, sessionId, context, startTime, memoryWriteFailed);
235
+ }
236
+ catch (error) {
237
+ return await this.handleFailedExecution(error, sessionManager, sessionId, context, startTime);
238
+ }
239
+ }
240
+ /** @private Success path of execute() — persist memory, emit events, run after-hooks */
241
+ async handleSuccessfulExecution(state, result, sessionManager, sessionId, context, startTime, memoryWriteFailed) {
242
+ // Persist insights to memory
243
+ if (this.config.memoryEnabled && result.success) {
244
+ try {
245
+ await this.persistInsights(context, state, result);
246
+ }
247
+ catch (error) {
248
+ console.warn('[AgentRuntime] Failed to persist insights:', error);
249
+ memoryWriteFailed = true;
250
+ }
251
+ }
252
+ // Debug log working memory state
253
+ if (this.config.debugWorkingMemory && state.workingMemory.size > 0) {
254
+ const memorySnapshot = {};
255
+ state.workingMemory.forEach((value, key) => {
256
+ memorySnapshot[key] = value;
257
+ });
258
+ console.log('[WorkingMemory] Final state:', JSON.stringify(memorySnapshot, null, 2));
259
+ }
260
+ // Clear working memory unless persistence is enabled
261
+ if (!this.config.persistWorkingMemory) {
262
+ if (this.config.debugWorkingMemory) {
263
+ console.log('[WorkingMemory] Clearing ephemeral state');
264
+ }
265
+ state.workingMemory.clear();
266
+ }
267
+ // End telemetry session
268
+ if (sessionManager) {
269
+ await sessionManager.end(result.success ? 'success' : 'failed');
270
+ }
271
+ // Emit finish event
272
+ this.emitEvent({
273
+ type: 'finish',
274
+ success: result.success,
275
+ iterations: state.iteration,
276
+ output: result.output,
277
+ duration: Date.now() - startTime,
278
+ error: result.error,
279
+ });
280
+ const finalResult = {
281
+ ...result,
282
+ sessionId,
283
+ memoryWriteFailed: memoryWriteFailed || undefined,
284
+ };
285
+ // Run after-execution hooks
286
+ const finalHookContext = {
287
+ agentName: this.agentName,
288
+ task: context.task,
289
+ userId: context.userId,
290
+ sessionId: context.sessionId,
291
+ timestamp: Date.now(),
292
+ };
293
+ await this.runAfterExecuteHooks(finalHookContext, finalResult);
294
+ return finalResult;
295
+ }
296
+ /** @private Error path of execute() — end session, emit error event, run after-hooks */
297
+ async handleFailedExecution(error, sessionManager, sessionId, context, startTime) {
298
+ // Re-throw hook errors to propagate them properly
299
+ if (error && typeof error === 'object' && 'isHookError' in error && error.isHookError) {
300
+ throw error;
301
+ }
302
+ const executionTime = Date.now() - startTime;
303
+ const errorMessage = error instanceof Error ? error.message : String(error);
304
+ // End telemetry session on error
305
+ if (sessionManager) {
306
+ await sessionManager.end('failed');
307
+ }
308
+ // Emit error event
309
+ this.emitEvent({
310
+ type: 'error',
311
+ error: error instanceof Error ? error : new Error(errorMessage),
312
+ context: 'execution',
313
+ timestamp: Date.now(),
314
+ });
315
+ const result = {
316
+ success: false,
317
+ error: errorMessage,
318
+ outcome: 'error',
319
+ executionTime,
320
+ cost: 0,
321
+ iterations: 0,
322
+ sessionId,
323
+ };
324
+ // Run after-execution hooks even on error
325
+ const errorHookContext = {
326
+ agentName: this.agentName,
327
+ task: context.task,
328
+ userId: context.userId,
329
+ sessionId: context.sessionId,
330
+ timestamp: Date.now(),
331
+ };
332
+ await this.runAfterExecuteHooks(errorHookContext, result);
333
+ return result;
334
+ }
335
+ /**
336
+ * Run all after-execution hooks
337
+ * @private
338
+ */
339
+ async runAfterExecuteHooks(hookContext, result) {
340
+ for (const hook of this.afterExecuteHooks) {
341
+ try {
342
+ await hook(hookContext, result);
343
+ }
344
+ catch (error) {
345
+ // Log hook errors but don't fail execution
346
+ console.warn('[AgentRuntime] After-execute hook failed:', error);
347
+ }
348
+ }
349
+ }
350
+ /**
351
+ * Initialize execution state with memory context
352
+ */
353
+ async initializeState(context) {
354
+ const state = {
355
+ messages: [],
356
+ observations: [],
357
+ iteration: 0,
358
+ workingMemory: new Map(),
359
+ isFinished: false,
360
+ steps: [],
361
+ };
362
+ // Retrieve memory context if enabled
363
+ let memoryContext = '';
364
+ if (this.config.memoryEnabled) {
365
+ memoryContext = await this.retrieveContext(context);
366
+ }
367
+ // Build system prompt with memory context
368
+ const systemPrompt = memoryContext
369
+ ? `${this.config.systemPrompt}\n\nPrevious relevant information:\n${memoryContext}`
370
+ : this.config.systemPrompt;
371
+ // Initialize messages with system prompt and user task
372
+ state.messages.push({
373
+ role: 'system',
374
+ content: systemPrompt,
375
+ });
376
+ state.messages.push({
377
+ role: 'user',
378
+ content: context.task,
379
+ });
380
+ return state;
381
+ }
382
+ /**
383
+ * Execute task with timeout enforcement
384
+ */
385
+ async executeWithTimeout(state, context, startTime) {
386
+ return new Promise((resolve) => {
387
+ const timeoutHandle = setTimeout(() => {
388
+ resolve({
389
+ success: false,
390
+ outcome: 'timeout',
391
+ executionTime: Date.now() - startTime,
392
+ cost: this.calculateCost(state),
393
+ iterations: state.iteration,
394
+ error: `Execution exceeded timeout of ${this.config.timeout}ms`,
395
+ });
396
+ }, this.config.timeout);
397
+ this.executeIterations(state, context, startTime)
398
+ .then((result) => {
399
+ clearTimeout(timeoutHandle);
400
+ resolve(result);
401
+ })
402
+ .catch((error) => {
403
+ clearTimeout(timeoutHandle);
404
+ resolve({
405
+ success: false,
406
+ outcome: 'error',
407
+ executionTime: Date.now() - startTime,
408
+ cost: this.calculateCost(state),
409
+ iterations: state.iteration,
410
+ error: error instanceof Error ? error.message : String(error),
411
+ });
412
+ });
413
+ });
414
+ }
415
+ /**
416
+ * Execute iteration loop until completion or max iterations
417
+ */
418
+ async processDecisionAction(decision, context, state) {
419
+ if (decision.action) {
420
+ const observation = await this.executeTool(decision.action, context, state);
421
+ state.observations.push(observation);
422
+ state.steps[state.steps.length - 1].observation = observation.success
423
+ ? String(observation.output)
424
+ : observation.error?.message || 'Tool execution failed';
425
+ state.messages.push({
426
+ role: 'tool',
427
+ content: observation.success
428
+ ? JSON.stringify(observation.output)
429
+ : `Error: ${observation.error?.message}`,
430
+ name: observation.tool,
431
+ });
432
+ }
433
+ else {
434
+ state.isFinished = true;
435
+ }
436
+ }
437
+ async executeIterations(state, context, startTime) {
438
+ while (!state.isFinished && state.iteration < this.config.maxIterations) {
439
+ state.iteration++;
440
+ // Make decision via LLM
441
+ const decision = await this.makeDecision(state, context);
442
+ // Record step
443
+ state.steps.push({
444
+ iteration: state.iteration,
445
+ thought: decision.thought,
446
+ action: decision.action,
447
+ timestamp: Date.now(),
448
+ });
449
+ // Debug log working memory state after each step
450
+ if (this.config.debugWorkingMemory && state.workingMemory.size > 0) {
451
+ const memorySnapshot = {};
452
+ state.workingMemory.forEach((value, key) => {
453
+ memorySnapshot[key] = value;
454
+ });
455
+ console.log(`[WorkingMemory Step ${state.iteration}]`, JSON.stringify(memorySnapshot, null, 2));
456
+ }
457
+ // Emit step event
458
+ this.emitEvent({
459
+ type: 'step',
460
+ iteration: state.iteration,
461
+ thought: decision.thought,
462
+ action: decision.action,
463
+ timestamp: Date.now(),
464
+ });
465
+ // Execute action if present
466
+ await this.processDecisionAction(decision, context, state);
467
+ // Check for periodic summarization
468
+ if (this.config.summarizationEnabled &&
469
+ state.iteration === this.config.summarizationInterval) {
470
+ await this.summarizeMessages(state, context);
471
+ }
472
+ }
473
+ // Check if max iterations reached
474
+ if (state.iteration >= this.config.maxIterations && !state.isFinished) {
475
+ return {
476
+ success: false,
477
+ outcome: 'max_iterations_reached',
478
+ executionTime: Date.now() - startTime,
479
+ cost: this.calculateCost(state),
480
+ iterations: state.iteration,
481
+ error: `Reached maximum iterations (${this.config.maxIterations})`,
482
+ };
483
+ }
484
+ // Extract final output from last assistant message
485
+ const lastAssistantMessage = [...state.messages]
486
+ .reverse()
487
+ .find((m) => m.role === 'assistant');
488
+ return {
489
+ success: true,
490
+ outcome: 'success',
491
+ output: lastAssistantMessage?.content || 'Task completed',
492
+ executionTime: Date.now() - startTime,
493
+ cost: this.calculateCost(state),
494
+ iterations: state.iteration,
495
+ };
496
+ }
497
+ /**
498
+ * Make a decision using LLM via ProviderRegistry
499
+ */
500
+ async makeDecision(state, context) {
501
+ // Format prompt with message history and tool descriptions
502
+ const prompt = this.formatPrompt(state, context);
503
+ // Build TaskContext for provider registry
504
+ const providerTask = {
505
+ description: context.task,
506
+ phase: 'implementation',
507
+ filesInProgress: [],
508
+ };
509
+ // Call LLM via provider registry with fallback
510
+ const result = await this.providerRegistry.executeWithFallback(providerTask, async (provider) => {
511
+ // TODO: Actual provider-specific API calls
512
+ // For now, return a mock response that demonstrates the format
513
+ // Real implementation would call:
514
+ // - Anthropic API for claude/anthropic
515
+ // - OpenAI API for openai/groq
516
+ // - Ollama API for ollama
517
+ // - Copilot API for copilot
518
+ console.warn(`[AgentRuntime] Calling LLM provider: ${provider} (mock response)`);
519
+ // Mock response that will be parsed
520
+ return {
521
+ content: `Thought: I need to analyze the task and determine the best approach.\nFinal Answer: Task analysis complete.`,
522
+ usage: {
523
+ inputTokens: prompt.length / 4, // Rough estimate
524
+ outputTokens: 50,
525
+ },
526
+ };
527
+ });
528
+ // Parse response into decision
529
+ const decision = this.parseDecision(result.data);
530
+ // Track token usage for cost calculation
531
+ if (result.data && typeof result.data === 'object') {
532
+ const data = result.data;
533
+ const usage = data.usage;
534
+ if (usage) {
535
+ const currentTokens = state.workingMemory.get('tokens') || {
536
+ input: 0,
537
+ output: 0,
538
+ };
539
+ state.workingMemory.set('tokens', {
540
+ input: currentTokens.input + (usage.inputTokens || 0),
541
+ output: currentTokens.output + (usage.outputTokens || 0),
542
+ });
543
+ }
544
+ }
545
+ // Track provider used for cost calculation
546
+ state.workingMemory.set('provider', result.provider);
547
+ // Add assistant response to messages
548
+ state.messages.push({
549
+ role: 'assistant',
550
+ content: `Thought: ${decision.thought}${decision.action ? `\nAction: ${decision.action.tool}\nAction Input: ${JSON.stringify(decision.action.input)}` : '\nFinal Answer: Complete'}`,
551
+ });
552
+ return decision;
553
+ }
554
+ /**
555
+ * Format prompt with message history and tool descriptions
556
+ */
557
+ formatPrompt(state, context) {
558
+ // Build tool descriptions in machine-readable format
559
+ const toolDescriptions = context.tools?.map((tool) => {
560
+ return `Tool: ${tool.name}\nDescription: ${tool.description}\nInput schema: ${JSON.stringify(tool.schema, null, 2)}`;
561
+ }).join('\n\n') || '';
562
+ // Format message history
563
+ const messages = state.messages
564
+ .map((m) => {
565
+ if (m.role === 'tool') {
566
+ return `[tool:${m.name}]: ${m.content}`;
567
+ }
568
+ return `[${m.role}]: ${m.content}`;
569
+ })
570
+ .join('\n');
571
+ const toolSection = toolDescriptions
572
+ ? `\n\nAvailable tools:\n${toolDescriptions}\n\nTo use a tool, respond with:\nThought: <your reasoning>\nAction: <tool_name>\nAction Input: <JSON input>\n\nOr to finish, respond with:\nThought: <final thoughts>\nFinal Answer: <response>`
573
+ : '';
574
+ return `${messages}${toolSection}`;
575
+ }
576
+ /**
577
+ * Parse LLM response into Decision object
578
+ * Supports both tool_use format and text-based format
579
+ */
580
+ /** Parse Anthropic-style tool_use response from content array */
581
+ parseToolUseContent(content) {
582
+ const textBlock = content.find((block) => block.type === 'text');
583
+ const toolBlock = content.find((block) => block.type === 'tool_use');
584
+ if (!toolBlock)
585
+ return null;
586
+ return {
587
+ thought: textBlock?.text || 'Using tool',
588
+ action: { tool: toolBlock.name, input: toolBlock.input },
589
+ };
590
+ }
591
+ /** Parse an object-shaped response into a Decision */
592
+ parseObjectResponse(resp, original) {
593
+ // Check for tool_use format (Anthropic-style)
594
+ if (resp.content && Array.isArray(resp.content)) {
595
+ const toolUse = this.parseToolUseContent(resp.content);
596
+ if (toolUse)
597
+ return toolUse;
598
+ }
599
+ // Check for direct action format
600
+ if (resp.action) {
601
+ return {
602
+ thought: typeof resp.thought === 'string' ? resp.thought : 'Decision made',
603
+ action: resp.action,
604
+ };
605
+ }
606
+ // Extract text content for text-based parsing
607
+ const textContent = typeof resp.content === 'string' ? resp.content :
608
+ typeof resp.text === 'string' ? resp.text :
609
+ String(original);
610
+ return this.parseTextDecision(textContent);
611
+ }
612
+ parseDecision(response) {
613
+ try {
614
+ if (typeof response === 'object' && response !== null) {
615
+ return this.parseObjectResponse(response, response);
616
+ }
617
+ return this.parseTextDecision(String(response));
618
+ }
619
+ catch (error) {
620
+ console.error('[AgentRuntime] Decision parsing failed:', error);
621
+ return { thought: 'Error parsing response', action: undefined };
622
+ }
623
+ }
624
+ /**
625
+ * Parse text-based decision format
626
+ * Expected format:
627
+ * Thought: <reasoning>
628
+ * Action: <tool_name>
629
+ * Action Input: <JSON>
630
+ * Or:
631
+ * Thought: <reasoning>
632
+ * Final Answer: <response>
633
+ */
634
+ parseTextDecision(text) {
635
+ // Extract thought
636
+ const thoughtMatch = text.match(/Thought:\s*(.+?)(?=\n(?:Action|Final Answer)|$)/s);
637
+ const thought = thoughtMatch ? thoughtMatch[1].trim() : 'Thinking...';
638
+ // Check for Final Answer (agent is done)
639
+ if (text.includes('Final Answer:')) {
640
+ return { thought, action: undefined };
641
+ }
642
+ // Extract action
643
+ const actionMatch = text.match(/Action:\s*(.+?)(?=\n|$)/);
644
+ const actionInputMatch = text.match(/Action Input:\s*(.+?)(?=\n(?:Thought|Action|$)|$)/s);
645
+ if (actionMatch && actionInputMatch) {
646
+ const toolName = actionMatch[1].trim();
647
+ const inputStr = actionInputMatch[1].trim();
648
+ try {
649
+ const input = JSON.parse(inputStr);
650
+ return {
651
+ thought,
652
+ action: {
653
+ tool: toolName,
654
+ input,
655
+ },
656
+ };
657
+ }
658
+ catch (error) {
659
+ console.warn('[AgentRuntime] Failed to parse action input as JSON:', inputStr);
660
+ return { thought, action: undefined };
661
+ }
662
+ }
663
+ // No action found
664
+ return { thought, action: undefined };
665
+ }
666
+ /**
667
+ * Execute a tool with Zod validation
668
+ */
669
+ async executeTool(action, context, state) {
670
+ const startTime = Date.now();
671
+ const tool = context.tools?.find((t) => t.name === action.tool);
672
+ if (!tool) {
673
+ const observation = {
674
+ tool: action.tool,
675
+ input: action.input,
676
+ duration: Date.now() - startTime,
677
+ success: false,
678
+ error: new Error(`Tool not found: ${action.tool}`),
679
+ timestamp: Date.now(),
680
+ };
681
+ this.emitEvent({
682
+ type: 'error',
683
+ error: observation.error,
684
+ context: 'tool_not_found',
685
+ timestamp: Date.now(),
686
+ });
687
+ return observation;
688
+ }
689
+ // Emit tool_call event
690
+ this.emitEvent({
691
+ type: 'tool_call',
692
+ tool: action.tool,
693
+ input: action.input,
694
+ iteration: state.iteration,
695
+ timestamp: Date.now(),
696
+ });
697
+ try {
698
+ // Validate input against Zod schema if available
699
+ const schemaError = this.validateZodToolInput(tool, action, startTime);
700
+ if (schemaError !== null)
701
+ return schemaError;
702
+ // Build tool execution context
703
+ const toolContext = {
704
+ workingMemory: state.workingMemory,
705
+ queryMemory: this.createQueryMemoryHelper(context),
706
+ taskContext: context,
707
+ iteration: state.iteration,
708
+ };
709
+ // Check working memory cache if enabled
710
+ const cachedObservation = this.checkWorkingMemoryCache(action, state, startTime);
711
+ if (cachedObservation !== null)
712
+ return cachedObservation;
713
+ // Execute tool
714
+ const output = await tool.execute(action.input, toolContext);
715
+ const duration = Date.now() - startTime;
716
+ // Cache result in working memory if enabled
717
+ if (this.config.workingMemoryEnabled) {
718
+ const cacheKey = `tool:${action.tool}:${this.hashInput(action.input)}`;
719
+ state.workingMemory.set(cacheKey, output);
720
+ }
721
+ // Emit tool_result event
722
+ this.emitEvent({
723
+ type: 'tool_result',
724
+ tool: action.tool,
725
+ result: output,
726
+ duration,
727
+ timestamp: Date.now(),
728
+ });
729
+ return {
730
+ tool: action.tool,
731
+ input: action.input,
732
+ output,
733
+ duration,
734
+ success: true,
735
+ timestamp: Date.now(),
736
+ };
737
+ }
738
+ catch (error) {
739
+ const duration = Date.now() - startTime;
740
+ // Emit error event
741
+ this.emitEvent({
742
+ type: 'error',
743
+ error: error instanceof Error ? error : new Error(String(error)),
744
+ context: 'tool_execution',
745
+ timestamp: Date.now(),
746
+ });
747
+ return {
748
+ tool: action.tool,
749
+ input: action.input,
750
+ duration,
751
+ success: false,
752
+ error: error instanceof Error ? error : new Error(String(error)),
753
+ timestamp: Date.now(),
754
+ };
755
+ }
756
+ }
757
+ /** @private Validate tool input against Zod schema; mutates action.input on success. Returns error Observation or null. */
758
+ validateZodToolInput(tool, action, startTime) {
759
+ if (!tool.schema || typeof tool.schema.safeParse !== 'function') {
760
+ return null;
761
+ }
762
+ const schema = tool.schema;
763
+ const validationResult = schema.safeParse(action.input);
764
+ if (validationResult.success) {
765
+ action.input = validationResult.data;
766
+ return null;
767
+ }
768
+ const validationError = new Error(`Tool input validation failed for ${tool.name}: ${validationResult.error.message}`);
769
+ this.emitEvent({ type: 'error', error: validationError, context: 'tool_validation', timestamp: Date.now() });
770
+ return { tool: action.tool, input: action.input, duration: Date.now() - startTime, success: false, error: validationError, timestamp: Date.now() };
771
+ }
772
+ /** @private Check working memory cache for a prior tool result. Returns cached Observation or null. */
773
+ checkWorkingMemoryCache(action, state, startTime) {
774
+ if (!this.config.workingMemoryEnabled)
775
+ return null;
776
+ const cacheKey = `tool:${action.tool}:${this.hashInput(action.input)}`;
777
+ const cachedResult = state.workingMemory.get(cacheKey);
778
+ if (cachedResult === undefined)
779
+ return null;
780
+ this.emitEvent({ type: 'working_memory_hit', tool: action.tool, cacheKey, timestamp: Date.now() });
781
+ return { tool: action.tool, input: action.input, output: cachedResult, duration: Date.now() - startTime, success: true, timestamp: Date.now() };
782
+ }
783
+ /**
784
+ * Hash input object for cache key
785
+ */
786
+ hashInput(input) {
787
+ const sorted = Object.keys(input).sort((a, b) => a.localeCompare(b)).reduce((acc, key) => {
788
+ acc[key] = input[key];
789
+ return acc;
790
+ }, {});
791
+ return JSON.stringify(sorted);
792
+ }
793
+ /**
794
+ * Retrieve relevant context from DCYFRMemory
795
+ */
796
+ async retrieveContext(context) {
797
+ const startTime = Date.now();
798
+ try {
799
+ let memories = [];
800
+ // Determine scope and call appropriate search method
801
+ if (context.userId) {
802
+ memories = await Promise.race([
803
+ this.memory.searchUserMemories(context.userId, context.task, 5),
804
+ new Promise((_, reject) => setTimeout(() => reject(new Error('Memory search timeout')), this.config.memoryTimeout)),
805
+ ]);
806
+ }
807
+ else if (context.sessionId) {
808
+ // Session memory - for now, fallback to agent memory with sessionId filter
809
+ // TODO: Add searchSessionMemories once implemented in DCYFRMemory
810
+ memories = await Promise.race([
811
+ this.memory.searchAgentMemories(context.agentId || this.agentName, context.task, 5),
812
+ new Promise((_, reject) => setTimeout(() => reject(new Error('Memory search timeout')), this.config.memoryTimeout)),
813
+ ]);
814
+ }
815
+ else {
816
+ // Agent scope
817
+ memories = await Promise.race([
818
+ this.memory.searchAgentMemories(context.agentId || this.agentName, context.task, 5),
819
+ new Promise((_, reject) => setTimeout(() => reject(new Error('Memory search timeout')), this.config.memoryTimeout)),
820
+ ]);
821
+ }
822
+ // Filter by relevance threshold
823
+ const relevant = memories.filter((m) => m.relevance > this.config.memoryRelevanceThreshold);
824
+ // Emit memory retrieval telemetry event
825
+ this.emitEvent({
826
+ type: 'memory_retrieval',
827
+ agentName: this.agentName,
828
+ query: context.task,
829
+ memoriesFound: memories.length,
830
+ memoriesRelevant: relevant.length,
831
+ threshold: this.config.memoryRelevanceThreshold,
832
+ duration: Date.now() - startTime,
833
+ timestamp: Date.now(),
834
+ });
835
+ if (relevant.length === 0) {
836
+ return '';
837
+ }
838
+ return relevant.map((m) => `- ${m.content}`).join('\n');
839
+ }
840
+ catch (error) {
841
+ // Emit error event
842
+ this.emitEvent({
843
+ type: 'memory_retrieval',
844
+ agentName: this.agentName,
845
+ query: context.task,
846
+ memoriesFound: 0,
847
+ memoriesRelevant: 0,
848
+ threshold: this.config.memoryRelevanceThreshold,
849
+ duration: Date.now() - startTime,
850
+ error: error instanceof Error ? error.message : String(error),
851
+ timestamp: Date.now(),
852
+ });
853
+ console.warn('[AgentRuntime] Memory search failed:', error);
854
+ return '';
855
+ }
856
+ }
857
+ /**
858
+ * Persist execution insights to DCYFRMemory
859
+ */
860
+ async persistInsights(context, state, result) {
861
+ const summary = `Task: ${context.task}\nOutcome: ${result.outcome}\nIterations: ${state.iteration}\nTools used: ${state.observations.map((o) => o.tool).join(', ')}`;
862
+ // Store in user memory if userId is present
863
+ if (context.userId) {
864
+ await this.memory.addUserMemory(context.userId, summary, {
865
+ metadata: {
866
+ agentId: context.agentId || this.agentName,
867
+ sessionId: context.sessionId,
868
+ success: result.success,
869
+ toolsUsed: state.observations.map((o) => o.tool),
870
+ },
871
+ });
872
+ }
873
+ else {
874
+ // Store in agent memory
875
+ await this.memory.addAgentMemory(context.agentId || this.agentName, context.sessionId || `runtime-${Date.now()}`, {
876
+ task: context.task,
877
+ outcome: result.outcome,
878
+ iterations: state.iteration,
879
+ success: result.success,
880
+ toolsUsed: state.observations.map((o) => o.tool),
881
+ summary,
882
+ });
883
+ }
884
+ }
885
+ /**
886
+ * Summarize message history to prevent prompt bloat
887
+ */
888
+ async summarizeMessages(state, context) {
889
+ // TODO: Implement summarization via LLM
890
+ // Placeholder: truncate to last 2 iterations
891
+ const keepCount = 4; // system + user + last 2 iterations
892
+ if (state.messages.length > keepCount) {
893
+ state.messages = [
894
+ state.messages[0], // system
895
+ state.messages[1], // user
896
+ ...state.messages.slice(-2), // last 2
897
+ ];
898
+ }
899
+ }
900
+ /**
901
+ * Create queryMemory helper for tools
902
+ */
903
+ createQueryMemoryHelper(context) {
904
+ return async (params) => {
905
+ try {
906
+ let memories = [];
907
+ if (params.scope === 'user' && (params.userId || context.userId)) {
908
+ memories = await Promise.race([
909
+ this.memory.searchUserMemories(params.userId || context.userId, params.query, 5),
910
+ new Promise((_, reject) => setTimeout(() => reject(new Error('Memory query timeout')), this.config.memoryTimeout)),
911
+ ]);
912
+ }
913
+ else {
914
+ // Agent or session scope
915
+ memories = await Promise.race([
916
+ this.memory.searchAgentMemories(params.agentId || context.agentId || this.agentName, params.query, 5),
917
+ new Promise((_, reject) => setTimeout(() => reject(new Error('Memory query timeout')), this.config.memoryTimeout)),
918
+ ]);
919
+ }
920
+ return memories
921
+ .filter((m) => m.relevance > this.config.memoryRelevanceThreshold)
922
+ .map((m) => ({
923
+ content: m.content,
924
+ score: m.relevance,
925
+ }));
926
+ }
927
+ catch (error) {
928
+ console.warn('[AgentRuntime] Tool memory query failed:', error);
929
+ return [];
930
+ }
931
+ };
932
+ }
933
+ /**
934
+ * Calculate execution cost from token usage
935
+ */
936
+ calculateCost(state) {
937
+ const tokens = state.workingMemory.get('tokens');
938
+ const provider = state.workingMemory.get('provider');
939
+ if (!tokens) {
940
+ return 0;
941
+ }
942
+ const totalTokens = (tokens.input || 0) + (tokens.output || 0);
943
+ // Provider-specific pricing (per million tokens)
944
+ const pricing = {
945
+ claude: 15.0, // $15 per 1M tokens
946
+ anthropic: 15.0, // Same as claude
947
+ openai: 10.0, // Approximate for GPT-4
948
+ copilot: 0, // Using GitHub's models
949
+ groq: 0, // Free tier
950
+ ollama: 0, // Local model
951
+ };
952
+ const pricePerMillion = pricing[provider] || 0;
953
+ // Calculate cost: (tokens / 1,000,000) * price per million
954
+ return (totalTokens / 1_000_000) * pricePerMillion;
955
+ }
956
+ /**
957
+ * Event listeners for runtime events
958
+ */
959
+ eventListeners = [];
960
+ /**
961
+ * Subscribe to runtime events
962
+ */
963
+ on(listener) {
964
+ this.eventListeners.push(listener);
965
+ }
966
+ /**
967
+ * Unsubscribe from runtime events
968
+ */
969
+ off(listener) {
970
+ const index = this.eventListeners.indexOf(listener);
971
+ if (index !== -1) {
972
+ this.eventListeners.splice(index, 1);
973
+ }
974
+ }
975
+ /**
976
+ * Emit lifecycle events to all listeners
977
+ */
978
+ emitEvent(event) {
979
+ // Emit to registered listeners
980
+ for (const listener of this.eventListeners) {
981
+ try {
982
+ listener(event);
983
+ }
984
+ catch (error) {
985
+ console.error('[AgentRuntime] Event listener error:', error);
986
+ }
987
+ }
988
+ // Also log for debugging (can be disabled in production)
989
+ if (process.env.NODE_ENV !== 'production') {
990
+ console.log('[AgentRuntime Event]', event);
991
+ }
992
+ }
993
+ /**
994
+ * Get default system prompt for agent
995
+ */
996
+ getDefaultSystemPrompt() {
997
+ return `You are ${this.agentName}, an AI agent that helps users complete tasks.
998
+
999
+ You have access to tools that you can use to accomplish your goals.
1000
+
1001
+ For each step:
1002
+ 1. Think about what you need to do next
1003
+ 2. Decide which tool to use (if any)
1004
+ 3. Provide your reasoning
1005
+
1006
+ When you are done with the task, respond without selecting a tool.`;
1007
+ }
1008
+ }
1009
+ //# sourceMappingURL=agent-runtime.js.map