@dcyfr/ai 1.0.4 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (411) hide show
  1. package/CHANGELOG.md +106 -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 +31 -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 +52 -0
  260. package/dist/ai/src/capability-manifest-generator.d.ts.map +1 -0
  261. package/dist/ai/src/capability-manifest-generator.js +691 -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 +35 -7
@@ -0,0 +1,1084 @@
1
+ /**
2
+ * DCYFR Agent Runtime with Delegation Support
3
+ * TLP:AMBER - Internal Use Only
4
+ *
5
+ * Agent runtime engine supporting delegation contract execution, capability
6
+ * self-assessment, and confidence tracking. Integrates with DCYFR delegation
7
+ * framework for intelligent task assignment and verification.
8
+ *
9
+ * @module runtime/agent-runtime
10
+ * @version 1.0.0
11
+ * @date 2026-02-13
12
+ */
13
+ import { EventEmitter } from 'events';
14
+ import { randomUUID } from 'crypto';
15
+ import { RuntimeTelemetryIntegration, createDefaultTelemetryIntegration, } from '../telemetry/index.js';
16
+ import { VerificationIntegration, } from '../verification/parser-integration.js';
17
+ /**
18
+ * DCYFR Agent Runtime
19
+ *
20
+ * Core runtime for AI agents with delegation support, capability tracking,
21
+ * and intelligent task execution.
22
+ */
23
+ export class AgentRuntime extends EventEmitter {
24
+ config;
25
+ currentTasks = new Map();
26
+ taskHistory = [];
27
+ capabilityAssessments = new Map();
28
+ confidenceHistory = new Map();
29
+ telemetryIntegration;
30
+ verificationIntegration;
31
+ constructor(config) {
32
+ super();
33
+ this.config = {
34
+ max_concurrent_tasks: 5,
35
+ default_timeout_ms: 300000, // 5 minutes default
36
+ enable_telemetry: true,
37
+ enable_verification_formatting: true,
38
+ verification_auto_formats: ['json', 'markdown'],
39
+ max_verification_output_bytes: 1024 * 1024, // 1MB default
40
+ debug: false,
41
+ ...config,
42
+ };
43
+ // Initialize capability tracking
44
+ this.initializeCapabilityTracking();
45
+ // Initialize telemetry integration if enabled
46
+ this.initializeTelemetry();
47
+ // Initialize verification integration if enabled
48
+ this.initializeVerificationIntegration();
49
+ if (this.config.debug) {
50
+ console.log(`[AgentRuntime] Initialized agent: ${this.config.agent_id}`);
51
+ }
52
+ }
53
+ /**
54
+ * Get agent information
55
+ */
56
+ getAgentInfo() {
57
+ return {
58
+ agent_id: this.config.agent_id,
59
+ agent_name: this.config.agent_name,
60
+ version: this.config.version,
61
+ capabilities: this.config.capabilities?.capabilities || [],
62
+ reputation_score: this.calculateCurrentReputation(),
63
+ current_workload: this.currentTasks.size,
64
+ max_concurrent_tasks: this.config.max_concurrent_tasks || 5,
65
+ };
66
+ }
67
+ /**
68
+ * Execute a task with optional delegation context
69
+ */
70
+ async executeTask(taskDescription, taskParameters, delegationContract) {
71
+ // Check concurrent task limit
72
+ if (this.currentTasks.size >= (this.config.max_concurrent_tasks || 5)) {
73
+ throw new Error('Maximum concurrent task limit reached');
74
+ }
75
+ // Create execution context
76
+ const context = {
77
+ execution_id: randomUUID(),
78
+ task: {
79
+ description: taskDescription,
80
+ parameters: taskParameters,
81
+ priority: delegationContract?.priority || 5,
82
+ },
83
+ delegation_contract: delegationContract,
84
+ metadata: {
85
+ started_at: new Date().toISOString(),
86
+ status: 'pending',
87
+ progress: 0,
88
+ },
89
+ };
90
+ // Add timeout from delegation contract or default
91
+ const timeout = delegationContract?.timeout_ms || this.config.default_timeout_ms || 300000;
92
+ context.metadata.estimated_completion_ms = timeout;
93
+ this.currentTasks.set(context.execution_id, context);
94
+ this.emit('task:started', context);
95
+ if (delegationContract) {
96
+ this.emit('delegation:contract:received', delegationContract);
97
+ }
98
+ try {
99
+ // Validate delegation contract constraints
100
+ if (delegationContract) {
101
+ await this.validateDelegationContract(delegationContract);
102
+ this.emit('delegation:contract:accepted', delegationContract);
103
+ }
104
+ // Execute the task with retry support
105
+ const result = await this.performTaskExecutionWithRetry(context, timeout, delegationContract?.retry_policy);
106
+ // Verify result if required
107
+ if (delegationContract?.verification_policy) {
108
+ result.verification = await this.performVerification(result, delegationContract);
109
+ }
110
+ // Update task history and capabilities
111
+ this.taskHistory.push(result);
112
+ this.updateCapabilitiesFromExecution(result);
113
+ this.currentTasks.delete(context.execution_id);
114
+ this.emit('task:completed', result);
115
+ if (this.config.debug) {
116
+ console.log(`[AgentRuntime] Task completed: ${context.execution_id}`);
117
+ }
118
+ return result;
119
+ }
120
+ catch (error) {
121
+ const errorMessage = error instanceof Error ? error.message : String(error);
122
+ const errorType = error instanceof Error ? error.constructor.name : typeof error;
123
+ const errorStack = error instanceof Error ? error.stack : undefined;
124
+ const result = {
125
+ context: { ...context, metadata: { ...context.metadata, status: 'failed' } },
126
+ success: false,
127
+ error: {
128
+ type: errorType,
129
+ message: errorMessage,
130
+ stack: errorStack,
131
+ },
132
+ metrics: {
133
+ execution_time_ms: Date.now() - new Date(context.metadata.started_at).getTime(),
134
+ },
135
+ completed_at: new Date().toISOString(),
136
+ };
137
+ this.taskHistory.push(result);
138
+ this.currentTasks.delete(context.execution_id);
139
+ this.emit('task:failed', result);
140
+ if (this.config.debug) {
141
+ console.error(`[AgentRuntime] Task failed: ${context.execution_id}`, error);
142
+ }
143
+ throw error;
144
+ }
145
+ }
146
+ /**
147
+ * Perform capability self-assessment
148
+ */
149
+ async performCapabilitySelfAssessment(capabilityId) {
150
+ const capabilities = this.config.capabilities?.capabilities || [];
151
+ const assessments = [];
152
+ const capabilitiesToAssess = capabilityId
153
+ ? capabilities.filter(c => c.capability_id === capabilityId)
154
+ : capabilities;
155
+ for (const capability of capabilitiesToAssess) {
156
+ const assessment = await this.assessCapability(capability);
157
+ assessments.push(assessment);
158
+ // Store assessment
159
+ const history = this.capabilityAssessments.get(capability.capability_id) || [];
160
+ history.push(assessment);
161
+ this.capabilityAssessments.set(capability.capability_id, history);
162
+ // Update confidence if significantly different
163
+ const confidenceDiff = Math.abs(assessment.confidence_level - capability.confidence_level);
164
+ if (confidenceDiff > 0.1) { // 10% threshold
165
+ const oldConfidence = capability.confidence_level;
166
+ capability.confidence_level = assessment.confidence_level;
167
+ this.updateConfidenceHistory(capability.capability_id, assessment.confidence_level);
168
+ this.emit('confidence:updated', capability.capability_id, oldConfidence, assessment.confidence_level);
169
+ }
170
+ this.emit('capability:assessed', assessment);
171
+ }
172
+ return assessments;
173
+ }
174
+ /**
175
+ * Get current task status
176
+ */
177
+ getCurrentTasks() {
178
+ return Array.from(this.currentTasks.values());
179
+ }
180
+ /**
181
+ * Get task execution history
182
+ */
183
+ getTaskHistory(limit) {
184
+ return limit ? this.taskHistory.slice(-limit) : [...this.taskHistory];
185
+ }
186
+ /**
187
+ * Get capability confidence history
188
+ */
189
+ getConfidenceHistory(capabilityId) {
190
+ return this.confidenceHistory.get(capabilityId) || [];
191
+ }
192
+ /**
193
+ * Get current capability manifest
194
+ */
195
+ getCapabilityManifest() {
196
+ return this.config.capabilities;
197
+ }
198
+ /**
199
+ * Update capability manifest
200
+ */
201
+ updateCapabilityManifest(manifest) {
202
+ this.config.capabilities = manifest;
203
+ if (this.config.debug) {
204
+ console.log(`[AgentRuntime] Updated capability manifest for ${this.config.agent_id}`);
205
+ }
206
+ }
207
+ /**
208
+ * Generate verification outputs for a task execution result
209
+ *
210
+ * @param result Task execution result to generate verification outputs for
211
+ * @param contract Delegation contract with verification requirements
212
+ * @param formats Optional additional output formats to generate
213
+ * @returns Parsed verification result with multi-modal outputs
214
+ */
215
+ async generateVerificationOutputs(result, contract, formats) {
216
+ if (!this.verificationIntegration) {
217
+ if (this.config.debug) {
218
+ console.warn('[AgentRuntime] Verification integration not initialized');
219
+ }
220
+ return null;
221
+ }
222
+ try {
223
+ const verificationResult = await this.verificationIntegration.processTaskResult(result, contract, { formats, validate_strict: true });
224
+ return verificationResult.parsedResult;
225
+ }
226
+ catch (error) {
227
+ console.error('[AgentRuntime] Failed to generate verification outputs:', error);
228
+ return null;
229
+ }
230
+ }
231
+ /**
232
+ * Generate multi-modal verification report for a task execution result
233
+ *
234
+ * @param result Task execution result to generate report for
235
+ * @param contract Delegation contract with verification requirements
236
+ * @param formats Optional output formats to include
237
+ * @returns Multi-modal verification report
238
+ */
239
+ async generateVerificationReport(result, contract, formats) {
240
+ if (!this.verificationIntegration) {
241
+ if (this.config.debug) {
242
+ console.warn('[AgentRuntime] Verification integration not initialized');
243
+ }
244
+ return null;
245
+ }
246
+ try {
247
+ const verificationResult = await this.verificationIntegration.processTaskResult(result, contract, { formats, validate_strict: true });
248
+ return verificationResult.multiModalReport;
249
+ }
250
+ catch (error) {
251
+ console.error('[AgentRuntime] Failed to generate verification report:', error);
252
+ return null;
253
+ }
254
+ }
255
+ /**
256
+ * Get supported verification output formats
257
+ *
258
+ * @returns Array of supported verification output formats
259
+ */
260
+ getSupportedVerificationFormats() {
261
+ return this.verificationIntegration?.getAvailableFormats() || [];
262
+ }
263
+ /**
264
+ * Check if verification output formatting is enabled
265
+ *
266
+ * @returns True if verification integration is initialized and enabled
267
+ */
268
+ isVerificationFormattingEnabled() {
269
+ return !!this.verificationIntegration && !!this.config.enable_verification_formatting;
270
+ }
271
+ /** Validate capability and timeout feasibility for a delegation contract */
272
+ checkCapabilityAndTimeout(contract, assessment) {
273
+ const updatedAssessment = { ...assessment };
274
+ if (contract.required_capabilities && contract.required_capabilities.length > 0) {
275
+ const capabilityIds = contract.required_capabilities.map(cap => typeof cap === 'string' ? cap : cap.capability_id);
276
+ const capabilityCheck = this.checkCapabilityRequirements(capabilityIds);
277
+ if (!capabilityCheck.canMeet) {
278
+ return { can_accept: false, reason: `Capability mismatch: ${capabilityCheck.reason}`, updated_assessment: updatedAssessment };
279
+ }
280
+ updatedAssessment.capability_match = capabilityCheck.match_score || 1;
281
+ }
282
+ else {
283
+ updatedAssessment.capability_match = 0.8;
284
+ }
285
+ const estimatedTime = this.estimateTaskTime(contract.task_description || contract.metadata?.task_categories?.join(' ') || '');
286
+ if (contract.timeout_ms && estimatedTime > contract.timeout_ms) {
287
+ return {
288
+ can_accept: false,
289
+ reason: `Task may exceed timeout (estimated: ${estimatedTime}ms, limit: ${contract.timeout_ms}ms)`,
290
+ updated_assessment: updatedAssessment
291
+ };
292
+ }
293
+ return { can_accept: true, updated_assessment: updatedAssessment };
294
+ }
295
+ /** Check reputation/permission requirements; mutates assessment.reputation_compliance and returns rejection or null */
296
+ checkReputationAndPermission(contract, assessment) {
297
+ if (contract.reputation_requirements) {
298
+ const check = this.checkReputationRequirements(contract.reputation_requirements);
299
+ if (!check.meets_requirements) {
300
+ return { can_accept: false, reason: `Reputation requirements not met: ${check.reason}`, confidence: 0, assessment: { ...assessment, reputation_compliance: false } };
301
+ }
302
+ }
303
+ assessment.reputation_compliance = true;
304
+ if (contract.permission_token) {
305
+ const check = this.validatePermissionToken(contract.permission_token);
306
+ if (!check.valid) {
307
+ return { can_accept: false, reason: `Permission validation failed: ${check.reason}`, confidence: 0, assessment };
308
+ }
309
+ }
310
+ return null;
311
+ }
312
+ /** Check firebreak constraints; mutates assessment.firebreak_compliance and returns rejection or null */
313
+ checkFirebreakConstraints(contract, assessment) {
314
+ if (!contract.firebreaks?.length) {
315
+ assessment.firebreak_compliance = true;
316
+ return null;
317
+ }
318
+ const check = this.validateFirebreaks(contract.firebreaks, contract);
319
+ if (!check.compliant) {
320
+ return { can_accept: false, reason: `Firebreak violation: ${check.reason}`, confidence: 0, assessment: { ...assessment, firebreak_compliance: false } };
321
+ }
322
+ assessment.firebreak_compliance = true;
323
+ return null;
324
+ }
325
+ /**
326
+ * Check if agent can accept delegation contract with comprehensive validation
327
+ */
328
+ async canAcceptDelegationContract(contract) {
329
+ let assessment = {
330
+ capability_match: 0, resource_availability: 0, workload_capacity: 0,
331
+ reputation_compliance: false, firebreak_compliance: false,
332
+ };
333
+ if (this.currentTasks.size >= (this.config.max_concurrent_tasks || 5)) {
334
+ return { can_accept: false, reason: 'Maximum concurrent tasks reached', confidence: 0, assessment };
335
+ }
336
+ assessment.workload_capacity = 1 - (this.currentTasks.size / (this.config.max_concurrent_tasks || 5));
337
+ const reputationRejection = this.checkReputationAndPermission(contract, assessment);
338
+ if (reputationRejection)
339
+ return reputationRejection;
340
+ const firebreakRejection = this.checkFirebreakConstraints(contract, assessment);
341
+ if (firebreakRejection)
342
+ return firebreakRejection;
343
+ if (contract.resource_requirements) {
344
+ const resourceCheck = this.checkResourceRequirements(contract.resource_requirements);
345
+ if (!resourceCheck.canMeet) {
346
+ return { can_accept: false, reason: `Insufficient resources: ${resourceCheck.reason}`, confidence: 0, assessment };
347
+ }
348
+ assessment.resource_availability = resourceCheck.availability_score || 1;
349
+ }
350
+ else {
351
+ assessment.resource_availability = 1;
352
+ }
353
+ const { can_accept, reason, updated_assessment } = this.checkCapabilityAndTimeout(contract, assessment);
354
+ assessment = updated_assessment;
355
+ if (!can_accept) {
356
+ return { can_accept: false, reason, confidence: 0, assessment };
357
+ }
358
+ const estimatedTime = this.estimateTaskTime(contract.task_description || contract.metadata?.task_categories?.join(' ') || '');
359
+ const confidence = this.calculateAcceptanceConfidence(assessment, contract);
360
+ return { can_accept: true, confidence, estimated_completion_ms: estimatedTime, assessment };
361
+ }
362
+ // Private methods
363
+ initializeCapabilityTracking() {
364
+ if (this.config.capabilities?.capabilities) {
365
+ for (const capability of this.config.capabilities.capabilities) {
366
+ this.updateConfidenceHistory(capability.capability_id, capability.confidence_level);
367
+ }
368
+ }
369
+ }
370
+ async validateDelegationContract(contract) {
371
+ const legacyContract = contract;
372
+ const hasExplicitTaskIdField = Object.prototype.hasOwnProperty.call(legacyContract, 'task_id');
373
+ const taskId = contract.task_id || contract.contract_id || legacyContract?.task?.id;
374
+ const delegatorAgentId = contract.delegator_agent_id || legacyContract?.delegator_agent || contract.delegator?.agent_id;
375
+ const delegateeAgentId = contract.delegatee_agent_id || legacyContract?.delegatee_agent || contract.delegatee?.agent_id;
376
+ // Validate contract format (support legacy aliases)
377
+ if ((hasExplicitTaskIdField && !contract.task_id) || !taskId || !delegatorAgentId || !delegateeAgentId) {
378
+ throw new Error('Invalid delegation contract: missing required fields');
379
+ }
380
+ // Check if we're the correct delegatee
381
+ const enforceDelegateeMatch = !!(contract.delegatee_agent_id || contract.delegatee?.agent_id);
382
+ if (enforceDelegateeMatch && delegateeAgentId !== this.config.agent_id) {
383
+ throw new Error(`Contract delegated to ${delegateeAgentId} but runtime is ${this.config.agent_id}`);
384
+ }
385
+ // Validate verification policy
386
+ const policyAliases = {
387
+ automated: 'direct_inspection',
388
+ manual: 'human_required',
389
+ capability_match: 'direct_inspection',
390
+ };
391
+ const rawPolicy = typeof contract.verification_policy === 'string'
392
+ ? contract.verification_policy
393
+ : legacyContract?.verification_policy?.verification_method;
394
+ const normalizedPolicy = policyAliases[rawPolicy] || rawPolicy;
395
+ const validPolicies = ['direct_inspection', 'third_party_audit', 'cryptographic_proof', 'human_required', 'none'];
396
+ if (!normalizedPolicy || !validPolicies.includes(String(normalizedPolicy))) {
397
+ throw new Error(`Invalid verification policy: ${rawPolicy}`);
398
+ }
399
+ // TLP Classification Enforcement
400
+ const { tlpEnforcement } = await import('../delegation/tlp-enforcement.js');
401
+ try {
402
+ tlpEnforcement.validateDelegationContract(contract);
403
+ }
404
+ catch (error) {
405
+ throw new Error(`TLP Security Violation: ${error instanceof Error ? error.message : 'Unknown error'}`);
406
+ }
407
+ }
408
+ async performTaskExecution(context, timeout) {
409
+ const startTime = Date.now();
410
+ context.metadata.status = 'running';
411
+ return new Promise((resolve, reject) => {
412
+ const timeoutHandle = setTimeout(() => {
413
+ context.metadata.status = 'timeout';
414
+ reject(new Error(`Task execution timeout after ${timeout}ms`));
415
+ }, timeout);
416
+ // Simulate task execution (in real implementation, this would call actual task logic)
417
+ this.simulateTaskExecution(context)
418
+ .then(output => {
419
+ clearTimeout(timeoutHandle);
420
+ const endTime = Date.now();
421
+ const result = {
422
+ context: { ...context, metadata: { ...context.metadata, status: 'completed', progress: 1 } },
423
+ success: true,
424
+ output,
425
+ metrics: {
426
+ execution_time_ms: endTime - startTime,
427
+ peak_memory_mb: this.getCurrentMemoryUsage(),
428
+ cpu_time_ms: endTime - startTime, // Simplified
429
+ },
430
+ completed_at: new Date().toISOString(),
431
+ };
432
+ resolve(result);
433
+ })
434
+ .catch(error => {
435
+ clearTimeout(timeoutHandle);
436
+ reject(error);
437
+ });
438
+ });
439
+ }
440
+ /** Apply retry delay and emit retry events for a given attempt */
441
+ async applyRetryDelay(context, attempt, retryPolicy) {
442
+ const delay = this.calculateRetryDelay(attempt, retryPolicy);
443
+ if (delay > 0) {
444
+ this.emit('task:retry:delay', context, attempt, delay);
445
+ await new Promise(resolve => setTimeout(resolve, delay));
446
+ }
447
+ this.emit('task:retry:attempt', context, attempt);
448
+ if (this.config.debug) {
449
+ const max = retryPolicy?.max_retries || 0;
450
+ console.log(`[AgentRuntime] Retry attempt ${attempt}/${max} for task ${context.execution_id}`);
451
+ }
452
+ }
453
+ /** Handle retry catch: emits events, returns true if loop should continue, false if error should be thrown */
454
+ handleRetryAttemptError(error, context, attempt, maxRetries, retryPolicy) {
455
+ if (attempt < maxRetries && this.shouldRetryError(error, retryPolicy)) {
456
+ this.emit('task:retry:error', context, attempt, error);
457
+ return true;
458
+ }
459
+ if (attempt > 0)
460
+ this.emit('task:retry:exhausted', context, attempt);
461
+ return false;
462
+ }
463
+ async performTaskExecutionWithRetry(context, timeout, retryPolicy) {
464
+ const maxRetries = retryPolicy?.max_retries || 0;
465
+ let lastError = null;
466
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
467
+ try {
468
+ if (attempt > 0)
469
+ await this.applyRetryDelay(context, attempt, retryPolicy);
470
+ const result = await this.performTaskExecution(context, timeout);
471
+ if (attempt > 0)
472
+ this.emit('task:retry:success', context, attempt);
473
+ return result;
474
+ }
475
+ catch (error) {
476
+ lastError = error;
477
+ if (this.handleRetryAttemptError(error, context, attempt, maxRetries, retryPolicy))
478
+ continue;
479
+ throw error;
480
+ }
481
+ }
482
+ throw lastError || new Error('Unknown retry error');
483
+ }
484
+ calculateRetryDelay(attempt, retryPolicy) {
485
+ if (!retryPolicy)
486
+ return 0;
487
+ const baseDelay = retryPolicy.initial_delay_ms || 1000;
488
+ const maxDelay = retryPolicy.max_delay_ms || 30000;
489
+ let delay;
490
+ switch (retryPolicy.backoff_strategy) {
491
+ case 'linear':
492
+ delay = baseDelay * attempt;
493
+ break;
494
+ case 'exponential':
495
+ delay = baseDelay * Math.pow(2, attempt - 1);
496
+ break;
497
+ case 'none':
498
+ default:
499
+ delay = baseDelay;
500
+ break;
501
+ }
502
+ return Math.min(delay, maxDelay);
503
+ }
504
+ shouldRetryError(error, retryPolicy) {
505
+ if (!retryPolicy || !retryPolicy.retry_conditions) {
506
+ // Default: retry on timeout and network errors
507
+ return error.message.includes('timeout') ||
508
+ error.message.includes('network') ||
509
+ error.message.includes('ECONNRESET') ||
510
+ error.message.includes('ENOTFOUND');
511
+ }
512
+ const conditions = retryPolicy.retry_conditions;
513
+ for (const condition of conditions) {
514
+ switch (condition) {
515
+ case 'timeout':
516
+ if (error.message.includes('timeout'))
517
+ return true;
518
+ break;
519
+ case 'network_error':
520
+ if (error.message.includes('network') ||
521
+ error.message.includes('ECONNRESET') ||
522
+ error.message.includes('ENOTFOUND'))
523
+ return true;
524
+ break;
525
+ case 'resource_unavailable':
526
+ if (error.message.includes('resource') ||
527
+ error.message.includes('limit') ||
528
+ error.message.includes('capacity'))
529
+ return true;
530
+ break;
531
+ }
532
+ }
533
+ return false;
534
+ }
535
+ async simulateTaskExecution(context) {
536
+ // Simulate progressive task execution with progress updates
537
+ const steps = 5;
538
+ for (let i = 1; i <= steps; i++) {
539
+ await new Promise(resolve => setTimeout(resolve, 100)); // Simulate work
540
+ context.metadata.progress = i / steps;
541
+ this.emit('task:progress', context, context.metadata.progress);
542
+ }
543
+ // Return simulated output based on task description
544
+ return {
545
+ task_id: context.task.description,
546
+ result: `Task completed: ${context.task.description}`,
547
+ execution_id: context.execution_id,
548
+ timestamp: new Date().toISOString(),
549
+ };
550
+ }
551
+ /** Apply verification integration outputs to result and update verificationResult accordingly */
552
+ async applyVerificationIntegration(result, contract, verificationResult) {
553
+ if (!this.verificationIntegration)
554
+ return;
555
+ try {
556
+ const verificationOutputResult = await this.verificationIntegration.processTaskResult(result, contract, { formats: this.config.verification_auto_formats, validate_strict: true });
557
+ result.verification_outputs = verificationOutputResult.parsedResult.formatted_outputs;
558
+ result.verification_report = verificationOutputResult.multiModalReport;
559
+ if (verificationOutputResult.validation && !verificationOutputResult.validation.valid) {
560
+ verificationResult.verified = false;
561
+ verificationResult.quality_score = Math.max(0, (verificationResult.quality_score ?? 0) - 0.2);
562
+ verificationResult.findings ??= [];
563
+ verificationResult.findings.push(...verificationOutputResult.validation.issues.map(issue => issue.message));
564
+ }
565
+ verificationResult.verification_details = JSON.stringify({
566
+ compliance_score: verificationOutputResult.parsedResult.compliance_analysis.compliance_score,
567
+ formats_generated: verificationOutputResult.parsedResult.formatted_outputs.map(o => o.format),
568
+ validation_summary: verificationOutputResult.validation?.summary,
569
+ });
570
+ if (this.config.debug) {
571
+ console.log(`[AgentRuntime] Generated ${verificationOutputResult.parsedResult.formatted_outputs.length} verification output formats`);
572
+ }
573
+ }
574
+ catch (error) {
575
+ console.error('[AgentRuntime] Failed to generate verification outputs:', error);
576
+ verificationResult.findings ??= [];
577
+ verificationResult.findings.push('Failed to generate verification output formatting');
578
+ }
579
+ }
580
+ async performVerification(result, contract) {
581
+ // Perform basic verification based on policy
582
+ const verificationResult = {
583
+ verified: result.success,
584
+ verified_at: new Date().toISOString(),
585
+ verified_by: this.config.agent_id,
586
+ verification_method: contract.verification_policy,
587
+ quality_score: result.success ? 0.85 : 0.0,
588
+ findings: result.success
589
+ ? ['output_exists', 'format_valid']
590
+ : ['task_failed'],
591
+ };
592
+ await this.applyVerificationIntegration(result, contract, verificationResult);
593
+ return verificationResult;
594
+ }
595
+ async assessCapability(capability) {
596
+ // Calculate confidence factors from task history
597
+ const recentTasks = this.getRecentTasksForCapability(capability.capability_id);
598
+ const successRate = this.calculateSuccessRate(recentTasks);
599
+ const avgExecutionTime = this.calculateAverageExecutionTime(recentTasks);
600
+ // Adjust confidence based on recent performance
601
+ let adjustedConfidence = capability.confidence_level;
602
+ if (successRate !== null) {
603
+ // Adjust based on success rate
604
+ if (successRate > 0.9) {
605
+ adjustedConfidence = Math.min(1.0, adjustedConfidence + 0.05);
606
+ }
607
+ else if (successRate < 0.7) {
608
+ adjustedConfidence = Math.max(0.1, adjustedConfidence - 0.1);
609
+ }
610
+ }
611
+ const assessment = {
612
+ capability_id: capability.capability_id,
613
+ confidence_level: adjustedConfidence,
614
+ assessed_at: new Date().toISOString(),
615
+ confidence_factors: {
616
+ recent_success_rate: successRate ?? undefined,
617
+ resource_efficiency: (this.calculateResourceEfficiency(recentTasks) ?? undefined),
618
+ },
619
+ reasoning: `Assessment based on ${recentTasks.length} recent tasks`,
620
+ recommendations: {
621
+ confidence_adjustment: adjustedConfidence - capability.confidence_level,
622
+ improvement_areas: successRate && successRate < 0.8 ? ['error_handling', 'edge_cases'] : [],
623
+ },
624
+ };
625
+ return assessment;
626
+ }
627
+ updateCapabilitiesFromExecution(result) {
628
+ // Update capability statistics based on execution result
629
+ if (this.config.capabilities?.capabilities) {
630
+ for (const capability of this.config.capabilities.capabilities) {
631
+ if (this.taskMatchesCapability(result.context.task.description, capability)) {
632
+ capability.successful_completions = (capability.successful_completions || 0) + (result.success ? 1 : 0);
633
+ capability.success_rate = (this.calculateCapabilitySuccessRate(capability.capability_id) ?? null) ?? undefined;
634
+ if (result.metrics.execution_time_ms) {
635
+ capability.completion_time_estimate_ms = this.calculateAverageCompletionTime(capability.capability_id) || 0;
636
+ }
637
+ }
638
+ }
639
+ }
640
+ }
641
+ taskMatchesCapability(taskDescription, capability) {
642
+ // Simple pattern matching (in real implementation, this would be more sophisticated)
643
+ if (capability.supported_patterns) {
644
+ for (const pattern of capability.supported_patterns) {
645
+ if (new RegExp(pattern, 'i').test(taskDescription)) {
646
+ return true;
647
+ }
648
+ }
649
+ }
650
+ return false;
651
+ }
652
+ getRecentTasksForCapability(capabilityId) {
653
+ return this.taskHistory
654
+ .filter(result => this.taskMatchesCapabilityId(result, capabilityId))
655
+ .slice(-10); // Last 10 tasks
656
+ }
657
+ taskMatchesCapabilityId(result, capabilityId) {
658
+ // Match task to capability (simplified)
659
+ const capability = this.config.capabilities?.capabilities.find(c => c.capability_id === capabilityId);
660
+ return capability ? this.taskMatchesCapability(result.context.task.description, capability) : false;
661
+ }
662
+ calculateSuccessRate(tasks) {
663
+ if (tasks.length === 0)
664
+ return null;
665
+ const successCount = tasks.filter(task => task.success).length;
666
+ return successCount / tasks.length;
667
+ }
668
+ calculateAverageExecutionTime(tasks) {
669
+ if (tasks.length === 0)
670
+ return null;
671
+ const totalTime = tasks.reduce((sum, task) => sum + task.metrics.execution_time_ms, 0);
672
+ return totalTime / tasks.length;
673
+ }
674
+ calculateResourceEfficiency(tasks) {
675
+ if (tasks.length === 0)
676
+ return null;
677
+ // Simplified efficiency calculation based on execution time vs estimated time
678
+ return 0.8; // Placeholder
679
+ }
680
+ calculateCurrentReputation() {
681
+ if (this.taskHistory.length === 0)
682
+ return 0.5; // Default
683
+ const recentTasks = this.taskHistory.slice(-20);
684
+ const successRate = this.calculateSuccessRate(recentTasks) || 0.5;
685
+ const avgQuality = this.calculateAverageQuality(recentTasks);
686
+ return (successRate * 0.7) + (avgQuality * 0.3);
687
+ }
688
+ calculateAverageQuality(tasks) {
689
+ const qualityScores = tasks
690
+ .filter(task => task.verification?.quality_score !== undefined)
691
+ .map(task => task.verification.quality_score);
692
+ if (qualityScores.length === 0)
693
+ return 0.5;
694
+ return qualityScores.reduce((sum, score) => sum + score, 0) / qualityScores.length;
695
+ }
696
+ calculateCapabilitySuccessRate(capabilityId) {
697
+ const tasks = this.getRecentTasksForCapability(capabilityId);
698
+ return this.calculateSuccessRate(tasks) || 0.5;
699
+ }
700
+ calculateAverageCompletionTime(capabilityId) {
701
+ const tasks = this.getRecentTasksForCapability(capabilityId);
702
+ return this.calculateAverageExecutionTime(tasks) || 60000; // Default 1 minute
703
+ }
704
+ updateConfidenceHistory(capabilityId, confidence) {
705
+ const history = this.confidenceHistory.get(capabilityId) || [];
706
+ history.push({
707
+ confidence,
708
+ timestamp: new Date().toISOString(),
709
+ });
710
+ // Keep only last 50 entries
711
+ if (history.length > 50) {
712
+ history.shift();
713
+ }
714
+ this.confidenceHistory.set(capabilityId, history);
715
+ }
716
+ checkResourceRequirements(requirements) {
717
+ const limits = this.config.resource_limits;
718
+ if (!limits)
719
+ return { canMeet: true, availability_score: 1 };
720
+ if (requirements.memory_mb && limits.memory_mb && requirements.memory_mb > limits.memory_mb) {
721
+ return { canMeet: false, reason: `Memory requirement ${requirements.memory_mb}MB exceeds limit ${limits.memory_mb}MB` };
722
+ }
723
+ if (requirements.cpu_cores && limits.cpu_percent && (requirements.cpu_cores * 100) > limits.cpu_percent) {
724
+ return { canMeet: false, reason: `CPU requirement ${requirements.cpu_cores * 100}% exceeds limit ${limits.cpu_percent}%` };
725
+ }
726
+ // Calculate availability score based on resource utilization
727
+ let score = 1;
728
+ if (requirements.memory_mb && limits.memory_mb) {
729
+ score *= (1 - requirements.memory_mb / limits.memory_mb);
730
+ }
731
+ if (requirements.cpu_cores && limits.cpu_percent) {
732
+ score *= (1 - (requirements.cpu_cores * 100) / limits.cpu_percent);
733
+ }
734
+ return { canMeet: true, availability_score: Math.max(0, score) };
735
+ }
736
+ checkCapabilityRequirements(requiredCapabilities) {
737
+ const myCapabilities = this.config.capabilities?.capabilities.map(c => c.capability_id) || [];
738
+ const myCapabilityMap = new Map(this.config.capabilities?.capabilities.map(c => [c.capability_id, c]) || []);
739
+ let totalConfidence = 0;
740
+ let matchedCount = 0;
741
+ for (const required of requiredCapabilities) {
742
+ if (!myCapabilities.includes(required)) {
743
+ return { canMeet: false, reason: `Missing required capability: ${required}` };
744
+ }
745
+ const capability = myCapabilityMap.get(required);
746
+ if (capability) {
747
+ totalConfidence += capability.confidence_level;
748
+ matchedCount++;
749
+ }
750
+ }
751
+ const matchScore = matchedCount > 0 ? totalConfidence / matchedCount : 0;
752
+ return { canMeet: true, match_score: matchScore };
753
+ }
754
+ checkSpecializationRequirements(requirements) {
755
+ if (!requirements.required_specializations || !this.config.capabilities) {
756
+ return { meets_requirements: true };
757
+ }
758
+ const mySpecs = this.config.capabilities.specializations || [];
759
+ const missing = requirements.required_specializations.filter(s => !mySpecs.includes(s));
760
+ if (missing.length > 0) {
761
+ return { meets_requirements: false, reason: `Missing required specializations: ${missing.join(', ')}` };
762
+ }
763
+ return { meets_requirements: true };
764
+ }
765
+ checkReputationRequirements(requirements) {
766
+ const currentReputation = this.calculateCurrentReputation();
767
+ const taskHistory = this.getTaskHistory();
768
+ const successfulTasks = taskHistory.filter(task => task.success).length;
769
+ if (requirements.min_security_score && currentReputation < requirements.min_security_score) {
770
+ return {
771
+ meets_requirements: false,
772
+ reason: `Security score ${currentReputation.toFixed(2)} below required ${requirements.min_security_score}`
773
+ };
774
+ }
775
+ if (requirements.min_tasks_completed && successfulTasks < requirements.min_tasks_completed) {
776
+ return {
777
+ meets_requirements: false,
778
+ reason: `Completed tasks ${successfulTasks} below required ${requirements.min_tasks_completed}`
779
+ };
780
+ }
781
+ if (requirements.min_confidence_score && this.config.capabilities) {
782
+ const avgConfidence = this.config.capabilities.overall_confidence;
783
+ if (avgConfidence != null && avgConfidence < requirements.min_confidence_score) {
784
+ return {
785
+ meets_requirements: false,
786
+ reason: `Confidence ${avgConfidence.toFixed(2)} below required ${requirements.min_confidence_score}`
787
+ };
788
+ }
789
+ }
790
+ if (requirements.max_consecutive_failures) {
791
+ const recentFailures = this.calculateConsecutiveFailures();
792
+ if (recentFailures > requirements.max_consecutive_failures) {
793
+ return {
794
+ meets_requirements: false,
795
+ reason: `Consecutive failures ${recentFailures} exceeds limit ${requirements.max_consecutive_failures}`
796
+ };
797
+ }
798
+ }
799
+ return this.checkSpecializationRequirements(requirements);
800
+ }
801
+ validatePermissionToken(token) {
802
+ // Check token expiration
803
+ if (token.expires_at) {
804
+ const expiryTime = new Date(token.expires_at).getTime();
805
+ const currentTime = Date.now();
806
+ if (currentTime > expiryTime) {
807
+ return { valid: false, reason: `Permission token expired at ${token.expires_at}` };
808
+ }
809
+ }
810
+ // Validate required scopes (placeholder - would need agent-specific scope requirements)
811
+ if (token.scopes.length === 0) {
812
+ return { valid: false, reason: 'Permission token has no scopes' };
813
+ }
814
+ // Validate required actions (placeholder)
815
+ if (token.actions.length === 0) {
816
+ return { valid: false, reason: 'Permission token has no allowed actions' };
817
+ }
818
+ // Validate resources (placeholder)
819
+ if (token.resources.length === 0) {
820
+ return { valid: false, reason: 'Permission token has no accessible resources' };
821
+ }
822
+ return { valid: true };
823
+ }
824
+ checkFirebreak(firebreak, contract) {
825
+ switch (firebreak.type) {
826
+ case 'max_depth': {
827
+ const depth = contract.metadata?.delegation_depth || 0;
828
+ if (firebreak.threshold && depth >= firebreak.threshold) {
829
+ return { compliant: false, reason: `Delegation depth ${depth} exceeds firebreak limit ${firebreak.threshold}` };
830
+ }
831
+ return { compliant: true };
832
+ }
833
+ case 'tlp_escalation': {
834
+ const tlp = contract.tlp_classification || 'TLP:CLEAR';
835
+ if (this.isTLPEscalation(tlp, firebreak)) {
836
+ return { compliant: false, reason: `TLP escalation beyond firebreak: ${tlp}` };
837
+ }
838
+ return { compliant: true };
839
+ }
840
+ case 'timeout': {
841
+ const est = this.estimateTaskTime(contract.task_description || '');
842
+ if (firebreak.threshold && est > firebreak.threshold) {
843
+ return { compliant: false, reason: `Estimated time ${est}ms exceeds firebreak limit ${firebreak.threshold}ms` };
844
+ }
845
+ return { compliant: true };
846
+ }
847
+ case 'resource_limit':
848
+ if (contract.resource_requirements) {
849
+ return this.checkFirebreakResourceLimits(contract.resource_requirements, firebreak);
850
+ }
851
+ return { compliant: true };
852
+ case 'human_review':
853
+ if (firebreak.action === 'require_approval') {
854
+ return { compliant: false, reason: 'Human review firebreak requires manual approval' };
855
+ }
856
+ return { compliant: true };
857
+ default:
858
+ return { compliant: true };
859
+ }
860
+ }
861
+ validateFirebreaks(firebreaks, contract) {
862
+ for (const firebreak of firebreaks) {
863
+ const result = this.checkFirebreak(firebreak, contract);
864
+ if (!result.compliant)
865
+ return result;
866
+ }
867
+ return { compliant: true };
868
+ }
869
+ isTLPEscalation(currentTLP, firebreak) {
870
+ const tlpLevels = { 'TLP:CLEAR': 0, 'TLP:GREEN': 1, 'TLP:AMBER': 2, 'TLP:RED': 3 };
871
+ const currentLevel = tlpLevels[currentTLP] || 0;
872
+ const maxLevel = firebreak.threshold || 0;
873
+ return currentLevel > maxLevel;
874
+ }
875
+ checkFirebreakResourceLimits(requirements, firebreak) {
876
+ if (requirements.memory_mb && firebreak.threshold && requirements.memory_mb > firebreak.threshold) {
877
+ return {
878
+ compliant: false,
879
+ reason: `Memory requirement ${requirements.memory_mb}MB exceeds firebreak limit ${firebreak.threshold}MB`
880
+ };
881
+ }
882
+ return { compliant: true };
883
+ }
884
+ calculateAcceptanceConfidence(assessment, contract) {
885
+ // Weight factors based on importance
886
+ const weights = {
887
+ capability_match: 0.3,
888
+ resource_availability: 0.2,
889
+ workload_capacity: 0.2,
890
+ reputation_compliance: 0.15,
891
+ firebreak_compliance: 0.15,
892
+ };
893
+ let confidence = 0;
894
+ confidence += assessment.capability_match * weights.capability_match;
895
+ confidence += assessment.resource_availability * weights.resource_availability;
896
+ confidence += assessment.workload_capacity * weights.workload_capacity;
897
+ confidence += (assessment.reputation_compliance ? 1 : 0) * weights.reputation_compliance;
898
+ confidence += (assessment.firebreak_compliance ? 1 : 0) * weights.firebreak_compliance;
899
+ // Apply penalty for high complexity or tight deadlines
900
+ if (contract.metadata?.estimated_complexity && contract.metadata.estimated_complexity > 7) {
901
+ confidence *= 0.9; // 10% penalty for high complexity
902
+ }
903
+ if (contract.timeout_ms) {
904
+ const estimatedTime = this.estimateTaskTime(contract.task_description || '');
905
+ const timeRatio = estimatedTime / contract.timeout_ms;
906
+ if (timeRatio > 0.8) {
907
+ confidence *= (1 - (timeRatio - 0.8) * 2); // Penalty for tight deadlines
908
+ }
909
+ }
910
+ return Math.max(0, Math.min(1, confidence));
911
+ }
912
+ calculateConsecutiveFailures() {
913
+ const recentTasks = this.getTaskHistory(10); // Last 10 tasks
914
+ let consecutiveFailures = 0;
915
+ // Count failures from the end until we hit a success
916
+ for (let i = recentTasks.length - 1; i >= 0; i--) {
917
+ if (!recentTasks[i].success) {
918
+ consecutiveFailures++;
919
+ }
920
+ else {
921
+ break;
922
+ }
923
+ }
924
+ return consecutiveFailures;
925
+ }
926
+ estimateTaskTime(taskDescription) {
927
+ // Simple estimation based on task description length and complexity
928
+ const baseTime = 5000; // 5 seconds base for reasonable task estimates
929
+ const complexityBonus = Math.min(taskDescription.length * 50, 15000); // Max 15 seconds additional
930
+ // Check for complexity keywords that might indicate longer tasks
931
+ const complexKeywords = ['complex', 'comprehensive', 'detailed', 'enterprise', 'full'];
932
+ const isComplex = complexKeywords.some(keyword => taskDescription.toLowerCase().includes(keyword));
933
+ const complexityMultiplier = isComplex ? 2 : 1;
934
+ return (baseTime + complexityBonus) * complexityMultiplier;
935
+ }
936
+ getCurrentMemoryUsage() {
937
+ // In a real implementation, this would get actual memory usage
938
+ return Math.random() * 100; // Simulated memory usage in MB
939
+ }
940
+ /**
941
+ * Initialize telemetry integration
942
+ */
943
+ initializeTelemetry() {
944
+ if (!this.config.enable_telemetry) {
945
+ if (this.config.debug) {
946
+ console.log('[AgentRuntime] Telemetry disabled');
947
+ }
948
+ return;
949
+ }
950
+ try {
951
+ // Create telemetry integration with default or custom configuration
952
+ if (this.config.telemetry_config) {
953
+ this.telemetryIntegration = new RuntimeTelemetryIntegration({
954
+ telemetry_config: {
955
+ agent_id: this.config.agent_id,
956
+ enabled: true,
957
+ sinks: [], // Will be populated by createDefaultTelemetryIntegration
958
+ ...this.config.telemetry_config.telemetry_config,
959
+ },
960
+ ...this.config.telemetry_config,
961
+ });
962
+ }
963
+ else {
964
+ // Use default telemetry integration
965
+ this.telemetryIntegration = createDefaultTelemetryIntegration(this.config.agent_id, {
966
+ track_task_metrics: true,
967
+ track_delegation_lifecycle: true,
968
+ track_resource_utilization: true,
969
+ track_retry_attempts: true,
970
+ });
971
+ }
972
+ // Attach telemetry to this runtime instance
973
+ this.telemetryIntegration.attach(this);
974
+ if (this.config.debug) {
975
+ console.log('[AgentRuntime] Telemetry integration initialized');
976
+ }
977
+ }
978
+ catch (error) {
979
+ console.error('[AgentRuntime] Failed to initialize telemetry:', error);
980
+ // Continue without telemetry rather than failing completely
981
+ }
982
+ }
983
+ /**
984
+ * Initialize verification integration
985
+ */
986
+ initializeVerificationIntegration() {
987
+ if (!this.config.enable_verification_formatting) {
988
+ if (this.config.debug) {
989
+ console.log('[AgentRuntime] Verification formatting disabled');
990
+ }
991
+ return;
992
+ }
993
+ try {
994
+ this.verificationIntegration = new VerificationIntegration({
995
+ strict_validation: true,
996
+ auto_generate_formats: this.config.verification_auto_formats || ['json', 'markdown'],
997
+ default_formatter_config: {
998
+ default_formats: ['json', 'markdown'],
999
+ include_human_readable: true,
1000
+ include_machine_readable: true,
1001
+ include_content_hash: true,
1002
+ enable_compression: false,
1003
+ strict_compliance_checking: true,
1004
+ max_content_size_bytes: this.config.max_verification_output_bytes || 1024 * 1024,
1005
+ metadata_options: {
1006
+ include_timing_data: true,
1007
+ include_resource_usage: true,
1008
+ include_error_details: true,
1009
+ include_verification_artifacts: true,
1010
+ },
1011
+ },
1012
+ });
1013
+ if (this.config.debug) {
1014
+ console.log('[AgentRuntime] Verification integration initialized');
1015
+ }
1016
+ }
1017
+ catch (error) {
1018
+ console.error('[AgentRuntime] Failed to initialize verification integration:', error);
1019
+ // Continue without verification formatting rather than failing completely
1020
+ }
1021
+ }
1022
+ /**
1023
+ * Get telemetry integration (for external access)
1024
+ */
1025
+ getTelemetryIntegration() {
1026
+ return this.telemetryIntegration;
1027
+ }
1028
+ /**
1029
+ * Query telemetry events
1030
+ */
1031
+ async queryTelemetryEvents(filter) {
1032
+ if (!this.telemetryIntegration) {
1033
+ throw new Error('Telemetry is not enabled');
1034
+ }
1035
+ return this.telemetryIntegration.queryEvents(filter);
1036
+ }
1037
+ /**
1038
+ * Shutdown runtime and cleanup resources
1039
+ */
1040
+ async shutdown() {
1041
+ if (this.config.debug) {
1042
+ console.log('[AgentRuntime] Shutting down...');
1043
+ }
1044
+ // Cancel all running tasks
1045
+ const taskEntries = Array.from(this.currentTasks.entries());
1046
+ for (const [executionId, context] of taskEntries) {
1047
+ context.metadata.status = 'failed';
1048
+ this.emit('task:failed', {
1049
+ context,
1050
+ success: false,
1051
+ output: null,
1052
+ error: {
1053
+ type: 'SHUTDOWN_ERROR',
1054
+ message: 'Runtime shutdown while task was executing',
1055
+ timestamp: new Date().toISOString(),
1056
+ },
1057
+ metrics: {
1058
+ execution_time_ms: Date.now() - new Date(context.metadata.started_at).getTime(),
1059
+ },
1060
+ completed_at: new Date().toISOString(),
1061
+ });
1062
+ }
1063
+ // Clear all tasks
1064
+ this.currentTasks.clear();
1065
+ // Cleanup telemetry integration
1066
+ if (this.telemetryIntegration) {
1067
+ try {
1068
+ await this.telemetryIntegration.detach(this);
1069
+ }
1070
+ catch (error) {
1071
+ console.error('[AgentRuntime] Error during telemetry cleanup:', error);
1072
+ }
1073
+ }
1074
+ // Emit shutdown event before removing listeners
1075
+ this.emit('shutdown');
1076
+ // Remove all event listeners
1077
+ this.removeAllListeners();
1078
+ if (this.config.debug) {
1079
+ console.log('[AgentRuntime] Shutdown complete');
1080
+ }
1081
+ }
1082
+ }
1083
+ export default AgentRuntime;
1084
+ //# sourceMappingURL=agent-runtime.js.map