@codemieai/code 0.0.44 → 0.0.46

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 (408) hide show
  1. package/dist/agents/core/BaseAgentAdapter.d.ts +9 -1
  2. package/dist/agents/core/BaseAgentAdapter.d.ts.map +1 -1
  3. package/dist/agents/core/BaseAgentAdapter.js +31 -3
  4. package/dist/agents/core/BaseAgentAdapter.js.map +1 -1
  5. package/dist/agents/core/metrics/types.d.ts +0 -6
  6. package/dist/agents/core/metrics/types.d.ts.map +1 -1
  7. package/dist/agents/core/session/BaseSessionAdapter.d.ts +0 -6
  8. package/dist/agents/core/session/BaseSessionAdapter.d.ts.map +1 -1
  9. package/dist/agents/core/types.d.ts +83 -0
  10. package/dist/agents/core/types.d.ts.map +1 -1
  11. package/dist/agents/plugins/claude/claude.plugin-installer.d.ts +0 -11
  12. package/dist/agents/plugins/claude/claude.plugin-installer.d.ts.map +1 -1
  13. package/dist/agents/plugins/claude/claude.plugin-installer.js +0 -32
  14. package/dist/agents/plugins/claude/claude.plugin-installer.js.map +1 -1
  15. package/dist/agents/plugins/claude/claude.plugin.d.ts.map +1 -1
  16. package/dist/agents/plugins/claude/claude.plugin.js +10 -1
  17. package/dist/agents/plugins/claude/claude.plugin.js.map +1 -1
  18. package/dist/agents/plugins/claude/claude.session.d.ts.map +1 -1
  19. package/dist/agents/plugins/claude/claude.session.js +1 -28
  20. package/dist/agents/plugins/claude/claude.session.js.map +1 -1
  21. package/dist/agents/plugins/claude/plugin/.claude-plugin/plugin.json +1 -1
  22. package/dist/agents/plugins/claude/plugin/README.md +1 -14
  23. package/dist/agents/plugins/claude/plugin/hooks/hooks.json +10 -5
  24. package/dist/agents/plugins/claude/plugin/skills/claude-setup-audit/SKILL.md +206 -0
  25. package/dist/agents/plugins/claude/plugin/skills/claude-setup-audit/examples/bad-agent.md +45 -0
  26. package/dist/agents/plugins/claude/plugin/skills/claude-setup-audit/examples/bad-claude-md-snippet.md +40 -0
  27. package/dist/agents/plugins/claude/plugin/skills/claude-setup-audit/examples/bad-command.md +30 -0
  28. package/dist/agents/plugins/claude/plugin/skills/claude-setup-audit/examples/bad-hooks.json +23 -0
  29. package/dist/agents/plugins/claude/plugin/skills/claude-setup-audit/examples/bad-skill.md +48 -0
  30. package/dist/agents/plugins/claude/plugin/skills/claude-setup-audit/examples/good-agent.md +145 -0
  31. package/dist/agents/plugins/claude/plugin/skills/claude-setup-audit/examples/good-claude-md-snippet.md +126 -0
  32. package/dist/agents/plugins/claude/plugin/skills/claude-setup-audit/examples/good-command.md +170 -0
  33. package/dist/agents/plugins/claude/plugin/skills/claude-setup-audit/examples/good-hooks.json +46 -0
  34. package/dist/agents/plugins/claude/plugin/skills/claude-setup-audit/examples/good-skill.md +144 -0
  35. package/dist/agents/plugins/claude/plugin/skills/claude-setup-audit/examples/sample-report.md +223 -0
  36. package/dist/agents/plugins/claude/plugin/skills/claude-setup-audit/references/best-practices.md +510 -0
  37. package/dist/agents/plugins/claude/plugin/skills/claude-setup-audit/references/component-checklists.md +413 -0
  38. package/dist/agents/plugins/claude/plugin/skills/claude-setup-audit/scripts/scan-repo.sh +162 -0
  39. package/dist/agents/plugins/claude/session/processors/claude.conversations-processor.d.ts.map +1 -1
  40. package/dist/agents/plugins/claude/session/processors/claude.conversations-processor.js +3 -78
  41. package/dist/agents/plugins/claude/session/processors/claude.conversations-processor.js.map +1 -1
  42. package/dist/agents/plugins/claude/session/processors/claude.metrics-processor.d.ts.map +1 -1
  43. package/dist/agents/plugins/claude/session/processors/claude.metrics-processor.js +7 -16
  44. package/dist/agents/plugins/claude/session/processors/claude.metrics-processor.js.map +1 -1
  45. package/dist/agents/plugins/claude/sounds-installer.d.ts +1 -1
  46. package/dist/agents/plugins/claude/sounds-installer.d.ts.map +1 -1
  47. package/dist/agents/plugins/claude/sounds-installer.js +1 -4
  48. package/dist/agents/plugins/claude/sounds-installer.js.map +1 -1
  49. package/dist/agents/plugins/codemie-code.plugin.d.ts +1 -4
  50. package/dist/agents/plugins/codemie-code.plugin.d.ts.map +1 -1
  51. package/dist/agents/plugins/codemie-code.plugin.js +26 -81
  52. package/dist/agents/plugins/codemie-code.plugin.js.map +1 -1
  53. package/dist/agents/plugins/gemini/gemini.plugin.d.ts.map +1 -1
  54. package/dist/agents/plugins/gemini/gemini.plugin.js +10 -0
  55. package/dist/agents/plugins/gemini/gemini.plugin.js.map +1 -1
  56. package/dist/agents/plugins/gemini/gemini.session-adapter.d.ts +1 -8
  57. package/dist/agents/plugins/gemini/gemini.session-adapter.d.ts.map +1 -1
  58. package/dist/agents/plugins/gemini/gemini.session-adapter.js +2 -30
  59. package/dist/agents/plugins/gemini/gemini.session-adapter.js.map +1 -1
  60. package/dist/agents/plugins/gemini/session/processors/gemini.conversations-processor.d.ts.map +1 -1
  61. package/dist/agents/plugins/gemini/session/processors/gemini.conversations-processor.js +2 -8
  62. package/dist/agents/plugins/gemini/session/processors/gemini.conversations-processor.js.map +1 -1
  63. package/dist/agents/plugins/gemini/session/processors/gemini.metrics-processor.d.ts.map +1 -1
  64. package/dist/agents/plugins/gemini/session/processors/gemini.metrics-processor.js +0 -7
  65. package/dist/agents/plugins/gemini/session/processors/gemini.metrics-processor.js.map +1 -1
  66. package/dist/agents/plugins/opencode/index.d.ts +1 -1
  67. package/dist/agents/plugins/opencode/index.d.ts.map +1 -1
  68. package/dist/agents/plugins/opencode/index.js.map +1 -1
  69. package/dist/agents/plugins/opencode/opencode-message-types.d.ts +2 -22
  70. package/dist/agents/plugins/opencode/opencode-message-types.d.ts.map +1 -1
  71. package/dist/agents/plugins/opencode/opencode-message-types.js.map +1 -1
  72. package/dist/agents/plugins/opencode/opencode.session.d.ts.map +1 -1
  73. package/dist/agents/plugins/opencode/opencode.session.js +5 -30
  74. package/dist/agents/plugins/opencode/opencode.session.js.map +1 -1
  75. package/dist/agents/plugins/opencode/opencode.sqlite-reader.d.ts.map +1 -1
  76. package/dist/agents/plugins/opencode/opencode.sqlite-reader.js +0 -2
  77. package/dist/agents/plugins/opencode/opencode.sqlite-reader.js.map +1 -1
  78. package/dist/agents/plugins/opencode/session/processors/opencode.metrics-processor.d.ts +0 -8
  79. package/dist/agents/plugins/opencode/session/processors/opencode.metrics-processor.d.ts.map +1 -1
  80. package/dist/agents/plugins/opencode/session/processors/opencode.metrics-processor.js +8 -97
  81. package/dist/agents/plugins/opencode/session/processors/opencode.metrics-processor.js.map +1 -1
  82. package/dist/cli/commands/analytics/aggregator.d.ts +0 -8
  83. package/dist/cli/commands/analytics/aggregator.d.ts.map +1 -1
  84. package/dist/cli/commands/analytics/aggregator.js +5 -100
  85. package/dist/cli/commands/analytics/aggregator.js.map +1 -1
  86. package/dist/cli/commands/analytics/data-loader.d.ts +0 -7
  87. package/dist/cli/commands/analytics/data-loader.d.ts.map +1 -1
  88. package/dist/cli/commands/analytics/data-loader.js +3 -10
  89. package/dist/cli/commands/analytics/data-loader.js.map +1 -1
  90. package/dist/cli/commands/analytics/exporter.d.ts.map +1 -1
  91. package/dist/cli/commands/analytics/exporter.js +0 -12
  92. package/dist/cli/commands/analytics/exporter.js.map +1 -1
  93. package/dist/cli/commands/analytics/formatter.d.ts.map +1 -1
  94. package/dist/cli/commands/analytics/formatter.js +0 -9
  95. package/dist/cli/commands/analytics/formatter.js.map +1 -1
  96. package/dist/cli/commands/analytics/types.d.ts +0 -17
  97. package/dist/cli/commands/analytics/types.d.ts.map +1 -1
  98. package/dist/cli/commands/assistants/chat/historyLoader.d.ts +22 -0
  99. package/dist/cli/commands/assistants/chat/historyLoader.d.ts.map +1 -0
  100. package/dist/cli/commands/assistants/chat/historyLoader.js +80 -0
  101. package/dist/cli/commands/assistants/chat/historyLoader.js.map +1 -0
  102. package/dist/cli/commands/assistants/{chat.d.ts → chat/index.d.ts} +1 -1
  103. package/dist/cli/commands/assistants/chat/index.d.ts.map +1 -0
  104. package/dist/cli/commands/assistants/{chat.js → chat/index.js} +54 -45
  105. package/dist/cli/commands/assistants/chat/index.js.map +1 -0
  106. package/dist/cli/commands/assistants/chat/types.d.ts +27 -0
  107. package/dist/cli/commands/assistants/chat/types.d.ts.map +1 -0
  108. package/dist/cli/commands/assistants/chat/types.js +5 -0
  109. package/dist/cli/commands/assistants/chat/types.js.map +1 -0
  110. package/dist/cli/commands/assistants/chat/utils.d.ts +12 -0
  111. package/dist/cli/commands/assistants/chat/utils.d.ts.map +1 -0
  112. package/dist/cli/commands/assistants/chat/utils.js +24 -0
  113. package/dist/cli/commands/assistants/chat/utils.js.map +1 -0
  114. package/dist/cli/commands/assistants/constants.d.ts +1 -0
  115. package/dist/cli/commands/assistants/constants.d.ts.map +1 -1
  116. package/dist/cli/commands/assistants/constants.js.map +1 -1
  117. package/dist/cli/commands/assistants/index.js +2 -2
  118. package/dist/cli/commands/assistants/index.js.map +1 -1
  119. package/dist/cli/commands/assistants/setup/generators/claude-agent-generator.js +1 -1
  120. package/dist/cli/commands/assistants/setup/generators/claude-skill-generator.js +1 -1
  121. package/dist/cli/commands/assistants/setup/index.js +4 -4
  122. package/dist/cli/commands/assistants/setup/index.js.map +1 -1
  123. package/dist/cli/commands/assistants/setup/selection/index.d.ts +1 -1
  124. package/dist/cli/commands/assistants/setup/selection/index.d.ts.map +1 -1
  125. package/dist/cli/commands/assistants/setup/selection/index.js +5 -3
  126. package/dist/cli/commands/assistants/setup/selection/index.js.map +1 -1
  127. package/dist/cli/commands/assistants/setup/selection/interactive-prompt.d.ts.map +1 -1
  128. package/dist/cli/commands/assistants/setup/selection/interactive-prompt.js +7 -1
  129. package/dist/cli/commands/assistants/setup/selection/interactive-prompt.js.map +1 -1
  130. package/dist/cli/commands/assistants/setup/selection/types.d.ts +2 -0
  131. package/dist/cli/commands/assistants/setup/selection/types.d.ts.map +1 -1
  132. package/dist/cli/commands/assistants/setup/selection/ui.d.ts.map +1 -1
  133. package/dist/cli/commands/assistants/setup/selection/ui.js +15 -4
  134. package/dist/cli/commands/assistants/setup/selection/ui.js.map +1 -1
  135. package/dist/cli/commands/hook.d.ts.map +1 -1
  136. package/dist/cli/commands/hook.js +22 -6
  137. package/dist/cli/commands/hook.js.map +1 -1
  138. package/dist/cli/commands/plugin.d.ts +16 -0
  139. package/dist/cli/commands/plugin.d.ts.map +1 -0
  140. package/dist/cli/commands/plugin.js +210 -0
  141. package/dist/cli/commands/plugin.js.map +1 -0
  142. package/dist/cli/commands/setup.js +1 -1
  143. package/dist/cli/commands/skill.d.ts.map +1 -1
  144. package/dist/cli/commands/skill.js +3 -1
  145. package/dist/cli/commands/skill.js.map +1 -1
  146. package/dist/cli/commands/sound.d.ts +3 -0
  147. package/dist/cli/commands/sound.d.ts.map +1 -0
  148. package/dist/cli/commands/sound.js +87 -0
  149. package/dist/cli/commands/sound.js.map +1 -0
  150. package/dist/cli/commands/test-metrics.js +3 -5
  151. package/dist/cli/commands/test-metrics.js.map +1 -1
  152. package/dist/cli/index.js +4 -0
  153. package/dist/cli/index.js.map +1 -1
  154. package/dist/env/types.d.ts +8 -0
  155. package/dist/env/types.d.ts.map +1 -1
  156. package/dist/env/types.js.map +1 -1
  157. package/dist/plugins/core/index.d.ts +13 -0
  158. package/dist/plugins/core/index.d.ts.map +1 -0
  159. package/dist/plugins/core/index.js +15 -0
  160. package/dist/plugins/core/index.js.map +1 -0
  161. package/dist/plugins/core/manifest-parser.d.ts +28 -0
  162. package/dist/plugins/core/manifest-parser.d.ts.map +1 -0
  163. package/dist/plugins/core/manifest-parser.js +137 -0
  164. package/dist/plugins/core/manifest-parser.js.map +1 -0
  165. package/dist/plugins/core/plugin-cache.d.ts +65 -0
  166. package/dist/plugins/core/plugin-cache.d.ts.map +1 -0
  167. package/dist/plugins/core/plugin-cache.js +170 -0
  168. package/dist/plugins/core/plugin-cache.js.map +1 -0
  169. package/dist/plugins/core/plugin-loader.d.ts +21 -0
  170. package/dist/plugins/core/plugin-loader.d.ts.map +1 -0
  171. package/dist/plugins/core/plugin-loader.js +55 -0
  172. package/dist/plugins/core/plugin-loader.js.map +1 -0
  173. package/dist/plugins/core/plugin-resolver.d.ts +33 -0
  174. package/dist/plugins/core/plugin-resolver.d.ts.map +1 -0
  175. package/dist/plugins/core/plugin-resolver.js +118 -0
  176. package/dist/plugins/core/plugin-resolver.js.map +1 -0
  177. package/dist/plugins/core/types.d.ts +183 -0
  178. package/dist/plugins/core/types.d.ts.map +1 -0
  179. package/dist/plugins/core/types.js +22 -0
  180. package/dist/plugins/core/types.js.map +1 -0
  181. package/dist/plugins/loaders/agents-loader.d.ts +19 -0
  182. package/dist/plugins/loaders/agents-loader.d.ts.map +1 -0
  183. package/dist/plugins/loaders/agents-loader.js +92 -0
  184. package/dist/plugins/loaders/agents-loader.js.map +1 -0
  185. package/dist/plugins/loaders/hooks-loader.d.ts +27 -0
  186. package/dist/plugins/loaders/hooks-loader.d.ts.map +1 -0
  187. package/dist/plugins/loaders/hooks-loader.js +94 -0
  188. package/dist/plugins/loaders/hooks-loader.js.map +1 -0
  189. package/dist/plugins/loaders/mcp-loader.d.ts +24 -0
  190. package/dist/plugins/loaders/mcp-loader.d.ts.map +1 -0
  191. package/dist/plugins/loaders/mcp-loader.js +86 -0
  192. package/dist/plugins/loaders/mcp-loader.js.map +1 -0
  193. package/dist/plugins/loaders/skills-loader.d.ts +30 -0
  194. package/dist/plugins/loaders/skills-loader.d.ts.map +1 -0
  195. package/dist/plugins/loaders/skills-loader.js +167 -0
  196. package/dist/plugins/loaders/skills-loader.js.map +1 -0
  197. package/dist/providers/plugins/bedrock/bedrock.template.js +1 -1
  198. package/dist/providers/plugins/jwt/jwt.setup-steps.js +1 -1
  199. package/dist/providers/plugins/jwt/jwt.template.js +1 -1
  200. package/dist/providers/plugins/litellm/litellm.template.js +1 -1
  201. package/dist/providers/plugins/sso/proxy/plugins/header-injection.plugin.js +10 -0
  202. package/dist/providers/plugins/sso/proxy/plugins/header-injection.plugin.js.map +1 -1
  203. package/dist/providers/plugins/sso/proxy/proxy-types.d.ts +3 -0
  204. package/dist/providers/plugins/sso/proxy/proxy-types.d.ts.map +1 -1
  205. package/dist/providers/plugins/sso/session/SessionSyncer.d.ts.map +1 -1
  206. package/dist/providers/plugins/sso/session/SessionSyncer.js +2 -3
  207. package/dist/providers/plugins/sso/session/SessionSyncer.js.map +1 -1
  208. package/dist/providers/plugins/sso/session/processors/conversations/apiClient.d.ts +21 -0
  209. package/dist/providers/plugins/sso/session/processors/conversations/apiClient.d.ts.map +1 -0
  210. package/dist/providers/plugins/sso/session/processors/conversations/apiClient.js +159 -0
  211. package/dist/providers/plugins/sso/session/processors/conversations/apiClient.js.map +1 -0
  212. package/dist/providers/plugins/sso/session/processors/conversations/constants.d.ts +24 -0
  213. package/dist/providers/plugins/sso/session/processors/conversations/constants.d.ts.map +1 -0
  214. package/dist/providers/plugins/sso/session/processors/conversations/constants.js +36 -0
  215. package/dist/providers/plugins/sso/session/processors/conversations/constants.js.map +1 -0
  216. package/dist/providers/plugins/sso/session/processors/conversations/syncProcessor.d.ts +19 -0
  217. package/dist/providers/plugins/sso/session/processors/conversations/syncProcessor.d.ts.map +1 -0
  218. package/dist/providers/plugins/sso/session/processors/conversations/{conversation-sync-processor.js → syncProcessor.js} +48 -33
  219. package/dist/providers/plugins/sso/session/processors/conversations/syncProcessor.js.map +1 -0
  220. package/dist/providers/plugins/sso/session/processors/conversations/{conversation-types.d.ts → types.d.ts} +14 -2
  221. package/dist/providers/plugins/sso/session/processors/conversations/types.d.ts.map +1 -0
  222. package/dist/providers/plugins/sso/session/processors/conversations/types.js +14 -0
  223. package/dist/providers/plugins/sso/session/processors/conversations/types.js.map +1 -0
  224. package/dist/providers/plugins/sso/session/processors/metrics/metrics-aggregator.d.ts.map +1 -1
  225. package/dist/providers/plugins/sso/session/processors/metrics/metrics-aggregator.js +16 -17
  226. package/dist/providers/plugins/sso/session/processors/metrics/metrics-aggregator.js.map +1 -1
  227. package/dist/providers/plugins/sso/session/processors/metrics/metrics-api-client.d.ts +6 -5
  228. package/dist/providers/plugins/sso/session/processors/metrics/metrics-api-client.d.ts.map +1 -1
  229. package/dist/providers/plugins/sso/session/processors/metrics/metrics-api-client.js +40 -39
  230. package/dist/providers/plugins/sso/session/processors/metrics/metrics-api-client.js.map +1 -1
  231. package/dist/providers/plugins/sso/session/processors/metrics/metrics-sync-processor.d.ts.map +1 -1
  232. package/dist/providers/plugins/sso/session/processors/metrics/metrics-sync-processor.js +2 -6
  233. package/dist/providers/plugins/sso/session/processors/metrics/metrics-sync-processor.js.map +1 -1
  234. package/dist/providers/plugins/sso/session/processors/metrics/metrics-types.d.ts +74 -31
  235. package/dist/providers/plugins/sso/session/processors/metrics/metrics-types.d.ts.map +1 -1
  236. package/dist/providers/plugins/sso/sso.template.js +1 -1
  237. package/dist/{agents/codemie-code/skills → skills}/core/SkillDiscovery.d.ts +10 -0
  238. package/dist/skills/core/SkillDiscovery.d.ts.map +1 -0
  239. package/dist/{agents/codemie-code/skills → skills}/core/SkillDiscovery.js +64 -7
  240. package/dist/skills/core/SkillDiscovery.js.map +1 -0
  241. package/dist/skills/core/SkillManager.d.ts.map +1 -0
  242. package/dist/{agents/codemie-code/skills → skills}/core/SkillManager.js +15 -10
  243. package/dist/skills/core/SkillManager.js.map +1 -0
  244. package/dist/{agents/codemie-code/skills → skills}/core/types.d.ts +3 -25
  245. package/dist/skills/core/types.d.ts.map +1 -0
  246. package/dist/skills/core/types.js.map +1 -0
  247. package/dist/{agents/codemie-code/skills → skills}/index.d.ts +3 -3
  248. package/dist/skills/index.d.ts.map +1 -0
  249. package/dist/{agents/codemie-code/skills → skills}/index.js +2 -2
  250. package/dist/skills/index.js.map +1 -0
  251. package/dist/skills/sync/SkillSync.d.ts.map +1 -0
  252. package/dist/{agents/codemie-code/skills → skills}/sync/SkillSync.js +5 -3
  253. package/dist/skills/sync/SkillSync.js.map +1 -0
  254. package/dist/{agents/codemie-code/skills → skills}/utils/content-loader.d.ts +2 -12
  255. package/dist/skills/utils/content-loader.d.ts.map +1 -0
  256. package/dist/{agents/codemie-code/skills → skills}/utils/content-loader.js +3 -8
  257. package/dist/skills/utils/content-loader.js.map +1 -0
  258. package/dist/skills/utils/pattern-matcher.d.ts.map +1 -0
  259. package/dist/skills/utils/pattern-matcher.js.map +1 -0
  260. package/dist/utils/extensions-scan.d.ts +27 -0
  261. package/dist/utils/extensions-scan.d.ts.map +1 -0
  262. package/dist/utils/extensions-scan.js +182 -0
  263. package/dist/utils/extensions-scan.js.map +1 -0
  264. package/dist/utils/frontmatter.d.ts.map +1 -0
  265. package/dist/utils/frontmatter.js.map +1 -0
  266. package/package.json +1 -1
  267. package/dist/agents/codemie-code/agent.d.ts +0 -129
  268. package/dist/agents/codemie-code/agent.d.ts.map +0 -1
  269. package/dist/agents/codemie-code/agent.js +0 -1106
  270. package/dist/agents/codemie-code/agent.js.map +0 -1
  271. package/dist/agents/codemie-code/config.d.ts +0 -40
  272. package/dist/agents/codemie-code/config.d.ts.map +0 -1
  273. package/dist/agents/codemie-code/config.js +0 -293
  274. package/dist/agents/codemie-code/config.js.map +0 -1
  275. package/dist/agents/codemie-code/filters.d.ts +0 -91
  276. package/dist/agents/codemie-code/filters.d.ts.map +0 -1
  277. package/dist/agents/codemie-code/filters.js +0 -328
  278. package/dist/agents/codemie-code/filters.js.map +0 -1
  279. package/dist/agents/codemie-code/index.d.ts +0 -93
  280. package/dist/agents/codemie-code/index.d.ts.map +0 -1
  281. package/dist/agents/codemie-code/index.js +0 -359
  282. package/dist/agents/codemie-code/index.js.map +0 -1
  283. package/dist/agents/codemie-code/modes/contextAwarePlanning.d.ts +0 -87
  284. package/dist/agents/codemie-code/modes/contextAwarePlanning.d.ts.map +0 -1
  285. package/dist/agents/codemie-code/modes/contextAwarePlanning.js +0 -957
  286. package/dist/agents/codemie-code/modes/contextAwarePlanning.js.map +0 -1
  287. package/dist/agents/codemie-code/modes/planMode.d.ts +0 -116
  288. package/dist/agents/codemie-code/modes/planMode.d.ts.map +0 -1
  289. package/dist/agents/codemie-code/modes/planMode.js +0 -537
  290. package/dist/agents/codemie-code/modes/planMode.js.map +0 -1
  291. package/dist/agents/codemie-code/prompts.d.ts +0 -47
  292. package/dist/agents/codemie-code/prompts.d.ts.map +0 -1
  293. package/dist/agents/codemie-code/prompts.js +0 -207
  294. package/dist/agents/codemie-code/prompts.js.map +0 -1
  295. package/dist/agents/codemie-code/skills/core/SkillDiscovery.d.ts.map +0 -1
  296. package/dist/agents/codemie-code/skills/core/SkillDiscovery.js.map +0 -1
  297. package/dist/agents/codemie-code/skills/core/SkillManager.d.ts.map +0 -1
  298. package/dist/agents/codemie-code/skills/core/SkillManager.js.map +0 -1
  299. package/dist/agents/codemie-code/skills/core/types.d.ts.map +0 -1
  300. package/dist/agents/codemie-code/skills/core/types.js.map +0 -1
  301. package/dist/agents/codemie-code/skills/index.d.ts.map +0 -1
  302. package/dist/agents/codemie-code/skills/index.js.map +0 -1
  303. package/dist/agents/codemie-code/skills/sync/SkillSync.d.ts.map +0 -1
  304. package/dist/agents/codemie-code/skills/sync/SkillSync.js.map +0 -1
  305. package/dist/agents/codemie-code/skills/utils/content-loader.d.ts.map +0 -1
  306. package/dist/agents/codemie-code/skills/utils/content-loader.js.map +0 -1
  307. package/dist/agents/codemie-code/skills/utils/frontmatter.d.ts.map +0 -1
  308. package/dist/agents/codemie-code/skills/utils/frontmatter.js.map +0 -1
  309. package/dist/agents/codemie-code/skills/utils/pattern-matcher.d.ts.map +0 -1
  310. package/dist/agents/codemie-code/skills/utils/pattern-matcher.js.map +0 -1
  311. package/dist/agents/codemie-code/storage/todoStorage.d.ts +0 -78
  312. package/dist/agents/codemie-code/storage/todoStorage.d.ts.map +0 -1
  313. package/dist/agents/codemie-code/storage/todoStorage.js +0 -225
  314. package/dist/agents/codemie-code/storage/todoStorage.js.map +0 -1
  315. package/dist/agents/codemie-code/tokenUtils.d.ts +0 -108
  316. package/dist/agents/codemie-code/tokenUtils.d.ts.map +0 -1
  317. package/dist/agents/codemie-code/tokenUtils.js +0 -220
  318. package/dist/agents/codemie-code/tokenUtils.js.map +0 -1
  319. package/dist/agents/codemie-code/toolMetadata.d.ts +0 -15
  320. package/dist/agents/codemie-code/toolMetadata.d.ts.map +0 -1
  321. package/dist/agents/codemie-code/toolMetadata.js +0 -316
  322. package/dist/agents/codemie-code/toolMetadata.js.map +0 -1
  323. package/dist/agents/codemie-code/tools/assistant-invocation.d.ts +0 -47
  324. package/dist/agents/codemie-code/tools/assistant-invocation.d.ts.map +0 -1
  325. package/dist/agents/codemie-code/tools/assistant-invocation.js +0 -129
  326. package/dist/agents/codemie-code/tools/assistant-invocation.js.map +0 -1
  327. package/dist/agents/codemie-code/tools/index.d.ts +0 -111
  328. package/dist/agents/codemie-code/tools/index.d.ts.map +0 -1
  329. package/dist/agents/codemie-code/tools/index.js +0 -424
  330. package/dist/agents/codemie-code/tools/index.js.map +0 -1
  331. package/dist/agents/codemie-code/tools/planning.d.ts +0 -54
  332. package/dist/agents/codemie-code/tools/planning.d.ts.map +0 -1
  333. package/dist/agents/codemie-code/tools/planning.js +0 -226
  334. package/dist/agents/codemie-code/tools/planning.js.map +0 -1
  335. package/dist/agents/codemie-code/types.d.ts +0 -459
  336. package/dist/agents/codemie-code/types.d.ts.map +0 -1
  337. package/dist/agents/codemie-code/types.js +0 -59
  338. package/dist/agents/codemie-code/types.js.map +0 -1
  339. package/dist/agents/codemie-code/ui/autocomplete.d.ts +0 -98
  340. package/dist/agents/codemie-code/ui/autocomplete.d.ts.map +0 -1
  341. package/dist/agents/codemie-code/ui/autocomplete.js +0 -145
  342. package/dist/agents/codemie-code/ui/autocomplete.js.map +0 -1
  343. package/dist/agents/codemie-code/ui/keyHandlers.d.ts +0 -112
  344. package/dist/agents/codemie-code/ui/keyHandlers.d.ts.map +0 -1
  345. package/dist/agents/codemie-code/ui/keyHandlers.js +0 -415
  346. package/dist/agents/codemie-code/ui/keyHandlers.js.map +0 -1
  347. package/dist/agents/codemie-code/ui/mentions.d.ts +0 -86
  348. package/dist/agents/codemie-code/ui/mentions.d.ts.map +0 -1
  349. package/dist/agents/codemie-code/ui/mentions.js +0 -122
  350. package/dist/agents/codemie-code/ui/mentions.js.map +0 -1
  351. package/dist/agents/codemie-code/ui/progressTracker.d.ts +0 -125
  352. package/dist/agents/codemie-code/ui/progressTracker.d.ts.map +0 -1
  353. package/dist/agents/codemie-code/ui/progressTracker.js +0 -343
  354. package/dist/agents/codemie-code/ui/progressTracker.js.map +0 -1
  355. package/dist/agents/codemie-code/ui/terminalCodes.d.ts +0 -38
  356. package/dist/agents/codemie-code/ui/terminalCodes.d.ts.map +0 -1
  357. package/dist/agents/codemie-code/ui/terminalCodes.js +0 -42
  358. package/dist/agents/codemie-code/ui/terminalCodes.js.map +0 -1
  359. package/dist/agents/codemie-code/ui/todoPanel.d.ts +0 -112
  360. package/dist/agents/codemie-code/ui/todoPanel.d.ts.map +0 -1
  361. package/dist/agents/codemie-code/ui/todoPanel.js +0 -321
  362. package/dist/agents/codemie-code/ui/todoPanel.js.map +0 -1
  363. package/dist/agents/codemie-code/ui.d.ts +0 -180
  364. package/dist/agents/codemie-code/ui.d.ts.map +0 -1
  365. package/dist/agents/codemie-code/ui.js +0 -1345
  366. package/dist/agents/codemie-code/ui.js.map +0 -1
  367. package/dist/agents/codemie-code/utils/progressionEnforcer.d.ts +0 -87
  368. package/dist/agents/codemie-code/utils/progressionEnforcer.d.ts.map +0 -1
  369. package/dist/agents/codemie-code/utils/progressionEnforcer.js +0 -293
  370. package/dist/agents/codemie-code/utils/progressionEnforcer.js.map +0 -1
  371. package/dist/agents/codemie-code/utils/todoParser.d.ts +0 -41
  372. package/dist/agents/codemie-code/utils/todoParser.d.ts.map +0 -1
  373. package/dist/agents/codemie-code/utils/todoParser.js +0 -305
  374. package/dist/agents/codemie-code/utils/todoParser.js.map +0 -1
  375. package/dist/agents/codemie-code/utils/todoValidator.d.ts +0 -65
  376. package/dist/agents/codemie-code/utils/todoValidator.d.ts.map +0 -1
  377. package/dist/agents/codemie-code/utils/todoValidator.js +0 -249
  378. package/dist/agents/codemie-code/utils/todoValidator.js.map +0 -1
  379. package/dist/agents/codemie-code/validators/planValidator.d.ts +0 -94
  380. package/dist/agents/codemie-code/validators/planValidator.d.ts.map +0 -1
  381. package/dist/agents/codemie-code/validators/planValidator.js +0 -281
  382. package/dist/agents/codemie-code/validators/planValidator.js.map +0 -1
  383. package/dist/agents/plugins/claude/plugin/hooks/hooks.windows.json +0 -98
  384. package/dist/agents/plugins/claude/plugin/sounds/play-random-sound.ps1 +0 -112
  385. package/dist/agents/plugins/claude/plugin/sounds/play-random-sound.sh +0 -58
  386. package/dist/agents/plugins/gemini/session/utils/token-aggregator.d.ts +0 -26
  387. package/dist/agents/plugins/gemini/session/utils/token-aggregator.d.ts.map +0 -1
  388. package/dist/agents/plugins/gemini/session/utils/token-aggregator.js +0 -38
  389. package/dist/agents/plugins/gemini/session/utils/token-aggregator.js.map +0 -1
  390. package/dist/cli/commands/assistants/chat.d.ts.map +0 -1
  391. package/dist/cli/commands/assistants/chat.js.map +0 -1
  392. package/dist/providers/plugins/sso/session/processors/conversations/conversation-api-client.d.ts +0 -26
  393. package/dist/providers/plugins/sso/session/processors/conversations/conversation-api-client.d.ts.map +0 -1
  394. package/dist/providers/plugins/sso/session/processors/conversations/conversation-api-client.js +0 -146
  395. package/dist/providers/plugins/sso/session/processors/conversations/conversation-api-client.js.map +0 -1
  396. package/dist/providers/plugins/sso/session/processors/conversations/conversation-sync-processor.d.ts +0 -22
  397. package/dist/providers/plugins/sso/session/processors/conversations/conversation-sync-processor.d.ts.map +0 -1
  398. package/dist/providers/plugins/sso/session/processors/conversations/conversation-sync-processor.js.map +0 -1
  399. package/dist/providers/plugins/sso/session/processors/conversations/conversation-types.d.ts.map +0 -1
  400. package/dist/providers/plugins/sso/session/processors/conversations/conversation-types.js +0 -7
  401. package/dist/providers/plugins/sso/session/processors/conversations/conversation-types.js.map +0 -1
  402. /package/dist/{agents/codemie-code/skills → skills}/core/SkillManager.d.ts +0 -0
  403. /package/dist/{agents/codemie-code/skills → skills}/core/types.js +0 -0
  404. /package/dist/{agents/codemie-code/skills → skills}/sync/SkillSync.d.ts +0 -0
  405. /package/dist/{agents/codemie-code/skills → skills}/utils/pattern-matcher.d.ts +0 -0
  406. /package/dist/{agents/codemie-code/skills → skills}/utils/pattern-matcher.js +0 -0
  407. /package/dist/{agents/codemie-code/skills/utils → utils}/frontmatter.d.ts +0 -0
  408. /package/dist/{agents/codemie-code/skills/utils → utils}/frontmatter.js +0 -0
@@ -1,1106 +0,0 @@
1
- /**
2
- * CodeMie Native Agent Implementation
3
- *
4
- * Core LangGraph ReAct agent using LangChain v1.0+ with streaming support
5
- */
6
- import { randomUUID } from 'node:crypto';
7
- import { createReactAgent } from '@langchain/langgraph/prebuilt';
8
- import { ChatOpenAI } from '@langchain/openai';
9
- import { HumanMessage, SystemMessage, AIMessage } from '@langchain/core/messages';
10
- import { EVENT_TYPES, CodeMieAgentError } from './types.js';
11
- import { getSystemPrompt } from './prompts.js';
12
- import { extractToolMetadata } from './toolMetadata.js';
13
- import { extractTokenUsageFromStreamChunk, extractTokenUsageFromFinalState } from './tokenUtils.js';
14
- import { setGlobalToolEventCallback } from './tools/index.js';
15
- import { logger } from '../../utils/logger.js';
16
- import { sanitizeCookies, sanitizeAuthToken } from '../../utils/security.js';
17
- import { HookExecutor } from '../../hooks/executor.js';
18
- import { extractSkillPatterns } from './skills/utils/pattern-matcher.js';
19
- import { SkillManager } from './skills/core/SkillManager.js';
20
- import { parseAtMentionCommand } from './ui/mentions.js';
21
- import { loadRegisteredAssistants } from '../../utils/config.js';
22
- export class CodeMieAgent {
23
- agent;
24
- config;
25
- tools;
26
- skills;
27
- conversationHistory = [];
28
- toolCallArgs = new Map(); // Store tool args by tool call ID
29
- currentExecutionSteps = [];
30
- currentStepNumber = 0;
31
- currentLLMTokenUsage = null; // Store token usage for associating with next tool call
32
- isFirstLLMCall = true; // Track if this is the initial user input processing
33
- hookExecutor = null; // Hook executor for lifecycle hooks
34
- hookLoopCounter = 0; // Track Stop hook retry attempts
35
- stats = {
36
- inputTokens: 0,
37
- outputTokens: 0,
38
- cachedTokens: 0,
39
- totalTokens: 0,
40
- estimatedTotalCost: 0,
41
- executionTime: 0,
42
- toolCalls: 0,
43
- successfulTools: 0,
44
- failedTools: 0,
45
- llmCalls: 0,
46
- executionSteps: []
47
- };
48
- constructor(config, tools, skills = []) {
49
- this.config = config;
50
- this.tools = tools;
51
- this.skills = skills;
52
- const sessionId = randomUUID();
53
- logger.setSessionId(sessionId);
54
- // Create the appropriate LLM based on provider
55
- const llm = this.createLLM();
56
- // Create LangGraph ReAct agent with system prompt (including skills if loaded)
57
- this.agent = createReactAgent({
58
- llm,
59
- tools: this.tools,
60
- messageModifier: getSystemPrompt(config.workingDirectory, this.skills)
61
- });
62
- // Initialize hook executor if hooks are configured
63
- if (config.hooks) {
64
- const hookContext = {
65
- sessionId: config.sessionId || 'unknown',
66
- workingDir: config.workingDirectory,
67
- transcriptPath: config.transcriptPath || '',
68
- permissionMode: 'auto', // TODO: Make this configurable
69
- agentName: 'codemie-code',
70
- profileName: config.name || 'default',
71
- };
72
- // Prepare LLM config for prompt hooks (use same config as agent)
73
- const llmConfig = {
74
- apiKey: config.authToken,
75
- baseUrl: config.baseUrl,
76
- model: config.model,
77
- timeout: config.timeout * 1000,
78
- debug: config.debug,
79
- };
80
- this.hookExecutor = new HookExecutor(config.hooks, hookContext, llmConfig);
81
- if (config.debug) {
82
- logger.debug('Hook executor initialized with prompt support');
83
- }
84
- }
85
- if (config.debug) {
86
- logger.debug(`CodeMie Agent initialized with ${tools.length} tools`);
87
- }
88
- }
89
- /**
90
- * Update tools after initialization (needed for tools that require conversation history)
91
- */
92
- async updateTools(tools) {
93
- this.tools = tools;
94
- // Load registered assistants for system prompt
95
- const assistants = await loadRegisteredAssistants();
96
- // Recreate agent with new tools and assistant-aware prompt
97
- const llm = this.createLLM();
98
- this.agent = createReactAgent({
99
- llm,
100
- tools: this.tools,
101
- messageModifier: getSystemPrompt(this.config.workingDirectory, [], assistants)
102
- });
103
- if (this.config.debug) {
104
- logger.debug(`CodeMie Agent tools updated: ${tools.length} tools`);
105
- if (assistants.length > 0) {
106
- logger.debug(`Loaded ${assistants.length} assistants for system prompt:`, assistants.map(a => a.slug));
107
- }
108
- }
109
- }
110
- /**
111
- * Create the appropriate LLM instance based on provider configuration
112
- */
113
- createLLM() {
114
- const commonConfig = {
115
- temperature: 0.7,
116
- maxTokens: 4096,
117
- timeout: this.config.timeout * 1000
118
- };
119
- switch (this.config.provider) {
120
- case 'openai':
121
- return new ChatOpenAI({
122
- model: this.config.model,
123
- apiKey: this.config.authToken,
124
- configuration: {
125
- ...(this.config.baseUrl !== 'https://api.openai.com/v1' && {
126
- baseURL: this.config.baseUrl
127
- }),
128
- // Add client tracking headers to all OpenAI requests
129
- fetch: async (input, init) => {
130
- const cliVersion = process.env.CODEMIE_CLI_VERSION || 'unknown';
131
- const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
132
- if (this.config.debug) {
133
- logger.debug(`OpenAI request to: ${url}`);
134
- }
135
- const updatedInit = {
136
- ...init,
137
- headers: {
138
- ...init?.headers,
139
- 'X-CodeMie-CLI': `codemie-cli/${cliVersion}`,
140
- 'X-CodeMie-Client': 'codemie-code'
141
- }
142
- };
143
- try {
144
- return await fetch(input, updatedInit);
145
- }
146
- catch (error) {
147
- if (this.config.debug) {
148
- logger.debug(`Fetch error for ${url}:`, error);
149
- }
150
- throw error;
151
- }
152
- }
153
- },
154
- ...commonConfig
155
- });
156
- case 'azure':
157
- return new ChatOpenAI({
158
- model: this.config.model,
159
- apiKey: this.config.authToken,
160
- configuration: {
161
- baseURL: this.config.baseUrl,
162
- defaultQuery: { 'api-version': '2024-02-01' },
163
- // Add client tracking header to all Azure requests
164
- fetch: async (input, init) => {
165
- const updatedInit = {
166
- ...init,
167
- headers: {
168
- ...init?.headers,
169
- 'X-CodeMie-Client': 'codemie-code'
170
- }
171
- };
172
- return fetch(input, updatedInit);
173
- }
174
- },
175
- ...commonConfig
176
- });
177
- case 'bedrock':
178
- // For Bedrock, use OpenAI format with AWS Bedrock credentials
179
- // Bedrock uses OpenAI-compatible API with special model IDs
180
- return new ChatOpenAI({
181
- model: this.config.model,
182
- apiKey: this.config.authToken,
183
- configuration: {
184
- baseURL: this.config.baseUrl === 'bedrock' ? undefined : this.config.baseUrl,
185
- // Add client tracking header to all Bedrock requests
186
- fetch: async (input, init) => {
187
- const updatedInit = {
188
- ...init,
189
- headers: {
190
- ...init?.headers,
191
- 'X-CodeMie-Client': 'codemie-code'
192
- }
193
- };
194
- return fetch(input, updatedInit);
195
- }
196
- },
197
- ...commonConfig
198
- });
199
- case 'litellm': {
200
- // LiteLLM proxy - use OpenAI format as it's most compatible
201
- // For SSO, we need to inject cookies into requests
202
- // NOTE: ChatOpenAI appends '/chat/completions' directly, not '/v1/chat/completions'
203
- // So if baseUrl ends with '/v1', use it as is, otherwise append '/v1'
204
- let baseURL = this.config.baseUrl;
205
- if (!baseURL.endsWith('/v1')) {
206
- baseURL = `${baseURL}/v1`;
207
- }
208
- const ssoConfig = {
209
- baseURL
210
- };
211
- // Check if we have SSO cookies to inject (following codemie-ide-plugin pattern)
212
- const ssoCookies = globalThis.codemieSSOCookies;
213
- if (this.config.debug) {
214
- logger.debug(`SSO Cookies available:`, sanitizeCookies(ssoCookies));
215
- logger.debug(`Auth token:`, sanitizeAuthToken(this.config.authToken));
216
- }
217
- if (ssoCookies && this.config.authToken === 'sso-authenticated') {
218
- // Create custom fetch function that includes SSO cookies (matches oauth2Proxy.js line 134)
219
- ssoConfig.fetch = async (input, init) => {
220
- const cookieString = Object.entries(ssoCookies)
221
- .map(([key, value]) => `${key}=${value}`)
222
- .join('; '); // Note: using '; ' separator (semicolon + space) for HTTP standard
223
- const updatedInit = {
224
- ...init,
225
- headers: {
226
- ...init?.headers,
227
- 'cookie': cookieString, // lowercase 'cookie' header like IDE plugin
228
- 'X-CodeMie-Client': 'codemie-code' // Track client type for request metrics
229
- }
230
- };
231
- // Handle SSL verification consistently with CodeMie Proxy (rejectUnauthorized: false)
232
- // CodeMie Proxy and SSO HTTP Client allow self-signed certificates for enterprise environments
233
- process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
234
- // Suppress the NODE_TLS_REJECT_UNAUTHORIZED warning since this is expected behavior
235
- // that matches how codemie-claude works through CodeMie Proxy
236
- process.removeAllListeners('warning');
237
- if (this.config.debug) {
238
- logger.debug('Disabled SSL verification (like CodeMie Proxy and SSO HTTP Client)');
239
- }
240
- if (this.config.debug) {
241
- logger.debug(`SSO request to ${input}`);
242
- logger.debug(`Cookie string length: ${cookieString.length} characters`);
243
- }
244
- try {
245
- const response = await fetch(input, updatedInit);
246
- if (this.config.debug && !response.ok) {
247
- logger.debug(`SSO request failed: ${response.status} ${response.statusText}`);
248
- }
249
- return response;
250
- }
251
- catch (error) {
252
- if (this.config.debug) {
253
- logger.debug(`SSO request error:`, error);
254
- }
255
- throw error;
256
- }
257
- };
258
- }
259
- else {
260
- // Even without SSO cookies, we still want to add the client tracking header
261
- // Explicitly add Authorization header for non-SSO LiteLLM
262
- ssoConfig.fetch = async (input, init) => {
263
- const updatedInit = {
264
- ...init,
265
- headers: {
266
- ...init?.headers,
267
- 'Authorization': `Bearer ${this.config.authToken}`,
268
- 'X-CodeMie-Client': 'codemie-code' // Track client type for request metrics
269
- }
270
- };
271
- if (this.config.debug) {
272
- logger.debug(`Non-SSO LiteLLM request to ${input}`);
273
- logger.debug(`Authorization header set with API key`);
274
- }
275
- return fetch(input, updatedInit);
276
- };
277
- if (this.config.debug) {
278
- logger.debug(`LiteLLM provider configured with API key authentication`);
279
- }
280
- }
281
- return new ChatOpenAI({
282
- model: this.config.model,
283
- apiKey: this.config.authToken,
284
- configuration: ssoConfig,
285
- // Force Completions API for LiteLLM proxy compatibility.
286
- // The Responses API sends a full `reasoning` object (with `summary`) that
287
- // LiteLLM/Azure backends may reject. The Completions API only sends the
288
- // widely-supported `reasoning_effort` scalar.
289
- useResponsesApi: false,
290
- ...commonConfig
291
- });
292
- }
293
- default:
294
- throw new CodeMieAgentError(`Unsupported provider: ${this.config.provider}`, 'INVALID_PROVIDER', { provider: this.config.provider });
295
- }
296
- }
297
- /**
298
- * Create a HumanMessage with optional image support (multiple images)
299
- */
300
- createHumanMessage(text, images = []) {
301
- if (images.length === 0) {
302
- // Text-only message
303
- return new HumanMessage(text);
304
- }
305
- // Multimodal message with images
306
- const content = [
307
- {
308
- type: "text",
309
- text: text
310
- }
311
- ];
312
- // Add all images to the content
313
- for (const image of images) {
314
- content.push({
315
- type: "image_url",
316
- image_url: `data:${image.mimeType};base64,${image.data}`
317
- });
318
- }
319
- return new HumanMessage({
320
- content: content
321
- });
322
- }
323
- /**
324
- * Handle @ mention invocation result by updating history and emitting events
325
- * @param message - Original user message
326
- * @param images - Optional images from user
327
- * @param atMentionResult - Result from preprocessAtMention
328
- * @param onEvent - Event callback
329
- */
330
- handleAtMentionResult(message, images, atMentionResult, onEvent) {
331
- const userMessage = this.createHumanMessage(message, images);
332
- this.conversationHistory.push(userMessage);
333
- const assistantMessage = new AIMessage({
334
- content: atMentionResult.response || 'No response from assistant'
335
- });
336
- this.conversationHistory.push(assistantMessage);
337
- onEvent({ type: EVENT_TYPES.THINKING_END });
338
- onEvent({ type: EVENT_TYPES.CONTENT_CHUNK, content: atMentionResult.response });
339
- onEvent({ type: EVENT_TYPES.COMPLETE });
340
- }
341
- /**
342
- * Preprocess message to detect @ mentions and invoke assistants directly
343
- * Returns { handled: true, response: string, assistantSlug: string } if @ mention was processed,
344
- * or { handled: false } if no @ mention found
345
- */
346
- async preprocessAtMention(message, onEvent) {
347
- // Use shared mention pattern from mentions module
348
- const parsed = parseAtMentionCommand(message);
349
- if (!parsed) {
350
- return { handled: false };
351
- }
352
- const { assistantSlug, message: assistantMessage } = parsed;
353
- try {
354
- // Find the invoke_assistant tool
355
- const invokeTool = this.tools.find(tool => tool.name === 'invoke_assistant');
356
- if (!invokeTool) {
357
- if (this.config.debug) {
358
- logger.debug('@ mention detected but invoke_assistant tool not available');
359
- }
360
- return { handled: false };
361
- }
362
- if (this.config.debug) {
363
- logger.debug(`Preprocessing @ mention: @${assistantSlug} "${assistantMessage.substring(0, 50)}..."`);
364
- }
365
- // Emit thinking_start with assistant info
366
- onEvent({ type: EVENT_TYPES.THINKING_START });
367
- // Invoke the assistant tool directly
368
- const response = await invokeTool.invoke({
369
- assistantSlug,
370
- message: assistantMessage,
371
- includeHistory: false // Default to no history for @ mentions (can be made configurable)
372
- });
373
- return { handled: true, response: String(response), assistantSlug };
374
- }
375
- catch (error) {
376
- if (this.config.debug) {
377
- logger.debug('@ mention preprocessing failed:', error);
378
- }
379
- // Return error as response but mark as handled
380
- return {
381
- handled: true,
382
- response: `Failed to invoke assistant @${assistantSlug}: ${error instanceof Error ? error.message : String(error)}`,
383
- assistantSlug
384
- };
385
- }
386
- }
387
- /**
388
- * Stream a chat interaction with the agent
389
- */
390
- async chatStream(message, onEvent, images = []) {
391
- const startTime = Date.now();
392
- let currentToolCall = null;
393
- let currentStep = null;
394
- let streamAborted = false;
395
- // Reset execution steps for new conversation
396
- this.currentExecutionSteps = [];
397
- this.currentStepNumber = 0;
398
- this.isFirstLLMCall = true;
399
- // Reset hook loop counter only for new user messages (not recursive calls)
400
- if (message.trim() && !message.startsWith('[Hook feedback]')) {
401
- this.hookLoopCounter = 0;
402
- }
403
- // Set up global tool event callback for progress reporting
404
- setGlobalToolEventCallback((event) => {
405
- onEvent({
406
- type: EVENT_TYPES.TOOL_CALL_PROGRESS,
407
- toolName: event.toolName,
408
- toolProgress: event.progress
409
- });
410
- });
411
- // Create an AbortController for proper stream cancellation
412
- const abortController = new AbortController();
413
- // Set up Ctrl+C handler for graceful stream termination
414
- const originalSigintHandler = process.listeners('SIGINT');
415
- const sigintHandler = () => {
416
- if (this.config.debug) {
417
- logger.debug('\nReceived SIGINT - aborting stream...');
418
- }
419
- streamAborted = true;
420
- abortController.abort();
421
- onEvent({ type: EVENT_TYPES.ERROR, error: 'Stream interrupted by user (Ctrl+C)' });
422
- };
423
- process.once('SIGINT', sigintHandler);
424
- if (this.config.debug) {
425
- logger.debug(`Processing message: ${message.substring(0, 100)}...`);
426
- }
427
- // Execute SessionStart hooks (only on first message)
428
- if (this.hookExecutor && this.conversationHistory.length === 0) {
429
- try {
430
- const sessionStartResult = await this.hookExecutor.executeSessionStart();
431
- // Handle blocking decision
432
- if (sessionStartResult.decision === 'block') {
433
- const reason = sessionStartResult.reason || 'Session blocked by SessionStart hook';
434
- const context = sessionStartResult.additionalContext;
435
- // Check if we should retry (exit code 2 behavior)
436
- if (context && this.hookLoopCounter < (this.getMaxHookRetries())) {
437
- this.hookLoopCounter++;
438
- logger.warn(`SessionStart hook blocked (attempt ${this.hookLoopCounter}/${this.getMaxHookRetries()})`);
439
- // Build feedback message
440
- const hookFeedback = [reason, context].filter(Boolean).join('\n\n');
441
- // Clear hook cache for retry
442
- this.hookExecutor.clearCache();
443
- // Retry with feedback
444
- return this.chatStream(`[Hook feedback]: ${hookFeedback}`, onEvent, images);
445
- }
446
- else {
447
- // Max retries reached or no feedback - block session
448
- if (this.hookLoopCounter >= this.getMaxHookRetries()) {
449
- logger.error(`SessionStart hook blocked after ${this.hookLoopCounter} attempts - aborting session`);
450
- onEvent({
451
- type: 'error',
452
- error: `Session blocked after ${this.hookLoopCounter} attempts: ${reason}`
453
- });
454
- }
455
- else {
456
- logger.warn('SessionStart hook blocked session start');
457
- onEvent({
458
- type: 'error',
459
- error: reason
460
- });
461
- }
462
- return; // Exit without starting session
463
- }
464
- }
465
- // Inject hook output as system context
466
- if (sessionStartResult.additionalContext) {
467
- if (this.config.debug) {
468
- logger.debug('SessionStart hook provided context, injecting into conversation');
469
- }
470
- // Add SessionStart output as system message before user message
471
- const systemMessage = new SystemMessage(`[SessionStart Hook Output]:\n${sessionStartResult.additionalContext}`);
472
- this.conversationHistory.push(systemMessage);
473
- }
474
- }
475
- catch (error) {
476
- logger.error(`SessionStart hook failed: ${error}`);
477
- // Continue session start (fail open)
478
- }
479
- }
480
- // Execute UserPromptSubmit hooks
481
- if (this.hookExecutor && message.trim()) {
482
- try {
483
- const hookResult = await this.hookExecutor.executeUserPromptSubmit(message);
484
- // Handle blocking decision
485
- if (hookResult.decision === 'block') {
486
- logger.warn('UserPromptSubmit hook blocked prompt');
487
- onEvent({
488
- type: 'error',
489
- error: hookResult.reason || 'Prompt blocked by hook'
490
- });
491
- return; // Exit without processing
492
- }
493
- // Add context to conversation
494
- if (hookResult.additionalContext) {
495
- if (this.config.debug) {
496
- logger.debug('UserPromptSubmit hook provided context');
497
- }
498
- // Prepend context to the message
499
- message = `${hookResult.additionalContext}\n\n${message}`;
500
- }
501
- }
502
- catch (error) {
503
- logger.error(`UserPromptSubmit hook failed: ${error}`);
504
- // Continue execution
505
- }
506
- }
507
- // Detect skill patterns in message
508
- const patternResult = extractSkillPatterns(message);
509
- if (patternResult.hasPatterns) {
510
- try {
511
- // Load skills with inventory
512
- const skillsWithInventory = await this.loadDetectedSkills(patternResult.patterns);
513
- if (skillsWithInventory.length > 0) {
514
- // Format and inject as system message
515
- const skillContent = this.formatSkillsForInjection(skillsWithInventory);
516
- const skillSystemMessage = new SystemMessage(`[Skill Invocation Detected]\n\n${skillContent}`);
517
- this.conversationHistory.push(skillSystemMessage);
518
- if (this.config.debug) {
519
- logger.debug(`Injected ${skillsWithInventory.length} skills: ${skillsWithInventory.map((s) => s.skill.metadata.name).join(', ')}`);
520
- }
521
- }
522
- }
523
- catch (error) {
524
- // Non-blocking: Log error but continue
525
- logger.warn('Failed to load skills for pattern injection:', error);
526
- }
527
- }
528
- // Preprocess @ mentions before normal agent processing
529
- const atMentionResult = await this.preprocessAtMention(message, onEvent);
530
- if (atMentionResult.handled) {
531
- this.handleAtMentionResult(message, images, atMentionResult, onEvent);
532
- return;
533
- }
534
- // Add user message to conversation history (with optional images)
535
- const userMessage = this.createHumanMessage(message, images);
536
- this.conversationHistory.push(userMessage);
537
- // Notify start of thinking
538
- onEvent({ type: EVENT_TYPES.THINKING_START });
539
- // Start the first LLM call step
540
- currentStep = this.startLLMStep();
541
- // Create the stream with conversation history
542
- const stream = await this.agent.stream({ messages: this.conversationHistory }, {
543
- streamMode: 'updates',
544
- recursionLimit: 50,
545
- signal: abortController.signal // Add abort signal for stream cancellation
546
- });
547
- let hasContent = false;
548
- // Process stream chunks with interruption handling
549
- for await (const chunk of stream) {
550
- // Check if stream was aborted
551
- if (streamAborted || abortController.signal.aborted) {
552
- if (this.config.debug) {
553
- logger.debug('Stream processing aborted');
554
- }
555
- break;
556
- }
557
- // Try to extract token usage from stream chunk
558
- const tokenUsage = extractTokenUsageFromStreamChunk(chunk, this.config.model, this.config.provider);
559
- if (tokenUsage && currentStep?.type === 'llm_call') {
560
- // Update current step with token usage
561
- currentStep.tokenUsage = tokenUsage;
562
- this.updateStatsWithTokenUsage(tokenUsage);
563
- // Store token usage to associate with next tool call
564
- this.currentLLMTokenUsage = tokenUsage;
565
- if (this.config.debug) {
566
- logger.debug(`Token usage: ${tokenUsage.inputTokens} in, ${tokenUsage.outputTokens} out`);
567
- }
568
- }
569
- await this.processStreamChunk(chunk, onEvent, (toolStarted) => {
570
- if (toolStarted) {
571
- // Complete current LLM step if it exists
572
- if (currentStep?.type === 'llm_call') {
573
- this.completeStep(currentStep);
574
- currentStep = null;
575
- }
576
- // Start tool execution step
577
- currentStep = this.startToolStep(toolStarted);
578
- currentToolCall = toolStarted;
579
- this.stats.toolCalls++;
580
- }
581
- else if (currentToolCall && currentStep) {
582
- // Complete tool step
583
- currentStep.toolSuccess = true;
584
- this.completeStep(currentStep);
585
- currentStep = null;
586
- this.stats.successfulTools++;
587
- currentToolCall = null;
588
- // Start new LLM step for next reasoning cycle (processing tool result)
589
- currentStep = this.startLLMStep();
590
- }
591
- });
592
- // Check if we have content
593
- if (chunk.agent?.messages) {
594
- const lastMessage = chunk.agent.messages.at(-1);
595
- if (lastMessage?.content && !hasContent) {
596
- hasContent = true;
597
- }
598
- }
599
- }
600
- // Complete any remaining step
601
- if (currentStep) {
602
- this.completeStep(currentStep);
603
- }
604
- // Update conversation history with final messages and try to extract any missed token usage
605
- try {
606
- const finalState = await this.agent.getState();
607
- if (finalState?.messages) {
608
- this.conversationHistory = finalState.messages;
609
- // Try to extract token usage from final state if we missed it during streaming
610
- const finalTokenUsage = extractTokenUsageFromFinalState(finalState, this.config.model, this.config.provider);
611
- if (finalTokenUsage && this.currentExecutionSteps.length > 0) {
612
- // Find the last LLM step that doesn't have token usage
613
- for (let i = this.currentExecutionSteps.length - 1; i >= 0; i--) {
614
- const step = this.currentExecutionSteps[i];
615
- if (step.type === 'llm_call' && !step.tokenUsage) {
616
- step.tokenUsage = finalTokenUsage;
617
- this.updateStatsWithTokenUsage(finalTokenUsage);
618
- break;
619
- }
620
- }
621
- }
622
- }
623
- }
624
- catch {
625
- // If getState fails, continue without updating history
626
- if (this.config.debug) {
627
- logger.debug('Could not get final state, continuing...');
628
- }
629
- }
630
- // Finalize execution statistics
631
- this.stats.executionTime = Date.now() - startTime;
632
- this.stats.executionSteps = [...this.currentExecutionSteps];
633
- // Execute Stop hooks
634
- try {
635
- if (this.hookExecutor) {
636
- try {
637
- const stopHookResult = await this.hookExecutor.executeStop(this.currentExecutionSteps, {
638
- toolCalls: this.stats.toolCalls,
639
- successfulTools: this.stats.successfulTools,
640
- failedTools: this.stats.failedTools,
641
- });
642
- // Display additional context from hooks if present (even if not blocking)
643
- if (stopHookResult.additionalContext) {
644
- onEvent({
645
- type: 'content_chunk',
646
- content: stopHookResult.additionalContext
647
- });
648
- }
649
- if (stopHookResult.decision === 'block') {
650
- logger.info(`Stop hook blocked completion: ${stopHookResult.reason}`);
651
- // Check if we've reached the retry limit
652
- const maxRetries = this.getMaxHookRetries();
653
- if (this.hookLoopCounter >= maxRetries) {
654
- logger.warn(`Hook retry limit reached (${maxRetries} attempts)`);
655
- // TODO: Ask user for guidance (continue/abort/ignore)
656
- // For now, emit warning and force completion
657
- onEvent({
658
- type: 'content_chunk',
659
- content: `\n\n[Warning: Hook retry limit (${maxRetries}) reached. Completing execution.]\n\n`
660
- });
661
- // Fall through to normal completion
662
- }
663
- else {
664
- // Increment retry counter
665
- this.hookLoopCounter++;
666
- // Construct feedback message from hook output
667
- const hookFeedback = [
668
- stopHookResult.reason || 'Hook requested continuation',
669
- stopHookResult.additionalContext
670
- ]
671
- .filter(Boolean)
672
- .join('\n\n');
673
- // Notify user about hook retry
674
- onEvent({
675
- type: 'content_chunk',
676
- content: `\n\n[Hook retry ${this.hookLoopCounter}/${maxRetries}: ${stopHookResult.reason || 'Continuing execution'}]\n\n`
677
- });
678
- // Reset execution state for continuation
679
- this.currentExecutionSteps = [];
680
- this.currentStepNumber = 0;
681
- // Clear hook cache to allow Stop hooks to run again
682
- if (this.hookExecutor) {
683
- this.hookExecutor.clearCache();
684
- }
685
- // Recurse with hook feedback to guide agent
686
- const feedbackMessage = `[Hook feedback]: ${hookFeedback}`;
687
- return this.chatStream(feedbackMessage, onEvent);
688
- }
689
- }
690
- }
691
- catch (error) {
692
- logger.error(`Stop hook failed: ${error}`);
693
- // Continue with normal completion
694
- }
695
- }
696
- // Notify thinking end and completion
697
- onEvent({ type: EVENT_TYPES.THINKING_END });
698
- onEvent({ type: EVENT_TYPES.COMPLETE });
699
- if (this.config.debug) {
700
- logger.debug(`Agent completed in ${this.stats.executionTime}ms`);
701
- logger.debug(`Total tokens: ${this.stats.totalTokens} (${this.stats.inputTokens} in, ${this.stats.outputTokens} out)`);
702
- logger.debug(`Estimated cost: $${this.stats.estimatedTotalCost.toFixed(4)}`);
703
- }
704
- }
705
- catch (error) {
706
- this.stats.executionTime = Date.now() - startTime;
707
- if (currentToolCall) {
708
- this.stats.failedTools++;
709
- }
710
- const errorMessage = error instanceof Error ? error.message : String(error);
711
- // Handle AbortError from user interruption gracefully
712
- if (error instanceof Error && (error.name === 'AbortError' || streamAborted)) {
713
- if (this.config.debug) {
714
- logger.debug('Stream aborted by user');
715
- }
716
- onEvent({
717
- type: EVENT_TYPES.ERROR,
718
- error: 'Operation interrupted by user'
719
- });
720
- return; // Don't throw error for user interruptions
721
- }
722
- if (this.config.debug) {
723
- logger.debug(`Agent error:`, error);
724
- // Log configuration details for debugging
725
- logger.debug(`Provider: ${this.config.provider}`);
726
- logger.debug(`Base URL: ${this.config.baseUrl}`);
727
- logger.debug(`Model: ${this.config.model}`);
728
- }
729
- onEvent({
730
- type: EVENT_TYPES.ERROR,
731
- error: errorMessage
732
- });
733
- throw new CodeMieAgentError(`Agent execution failed: ${errorMessage}`, 'EXECUTION_ERROR', { originalError: error, stats: this.stats });
734
- }
735
- finally {
736
- // Clean up global tool event callback
737
- setGlobalToolEventCallback(null);
738
- // Always clean up signal handler
739
- process.removeListener('SIGINT', sigintHandler);
740
- // Restore original handlers if they existed
741
- if (originalSigintHandler.length > 0) {
742
- originalSigintHandler.forEach(handler => {
743
- process.on('SIGINT', handler);
744
- });
745
- }
746
- }
747
- }
748
- /**
749
- * Process individual stream chunks from LangGraph
750
- */
751
- async processStreamChunk(chunk, onEvent, onToolEvent) {
752
- try {
753
- // Handle agent node updates (LLM responses)
754
- if (chunk.agent?.messages) {
755
- const messages = chunk.agent.messages;
756
- const lastMessage = messages[messages.length - 1];
757
- // Stream content chunks
758
- if (lastMessage?.content && typeof lastMessage.content === 'string') {
759
- onEvent({
760
- type: EVENT_TYPES.CONTENT_CHUNK,
761
- content: lastMessage.content
762
- });
763
- }
764
- // Handle tool calls
765
- if (lastMessage?.tool_calls && lastMessage.tool_calls.length > 0) {
766
- for (const toolCall of lastMessage.tool_calls) {
767
- // Execute PreToolUse hooks
768
- if (this.hookExecutor) {
769
- try {
770
- const hookResult = await this.hookExecutor.executePreToolUse(toolCall.name, toolCall.args, toolCall.id);
771
- // Handle blocking decision
772
- if (hookResult.decision === 'deny' || hookResult.decision === 'block') {
773
- logger.warn(`PreToolUse hook blocked tool: ${toolCall.name}`);
774
- onEvent({
775
- type: 'error',
776
- error: hookResult.reason || `Tool ${toolCall.name} blocked by hook`
777
- });
778
- continue; // Skip this tool call
779
- }
780
- // Apply input modifications
781
- if (hookResult.updatedInput) {
782
- if (this.config.debug) {
783
- logger.debug(`PreToolUse hook modified input for: ${toolCall.name}`);
784
- }
785
- toolCall.args = { ...toolCall.args, ...hookResult.updatedInput };
786
- }
787
- // Log additional context if provided
788
- if (hookResult.additionalContext && this.config.debug) {
789
- logger.debug(`PreToolUse hook context: ${hookResult.additionalContext}`);
790
- }
791
- }
792
- catch (error) {
793
- logger.error(`PreToolUse hook failed: ${error}`);
794
- // Continue execution (hooks should not break agent)
795
- }
796
- }
797
- // Store tool args for later use in result processing
798
- // Use tool name as key since LangGraph may not preserve IDs consistently
799
- this.toolCallArgs.set(toolCall.name, toolCall.args);
800
- onEvent({
801
- type: EVENT_TYPES.TOOL_CALL_START,
802
- toolName: toolCall.name,
803
- toolArgs: toolCall.args
804
- });
805
- if (onToolEvent) {
806
- onToolEvent(toolCall.name);
807
- }
808
- }
809
- }
810
- }
811
- // Handle tool node updates (tool execution results)
812
- if (chunk.tools?.messages) {
813
- const messages = chunk.tools.messages;
814
- for (const toolMessage of messages) {
815
- const toolName = toolMessage.name || 'unknown';
816
- const result = toolMessage.content || '';
817
- // Get the stored tool args for this tool name
818
- const toolArgs = this.toolCallArgs.get(toolName);
819
- if (toolArgs) {
820
- this.toolCallArgs.delete(toolName); // Clean up after use
821
- }
822
- // Extract enhanced metadata from the tool result
823
- let toolMetadata = extractToolMetadata(toolName, result, toolArgs);
824
- // Associate token usage from the LLM call that triggered this tool
825
- if (toolMetadata && this.currentLLMTokenUsage) {
826
- toolMetadata = {
827
- ...toolMetadata,
828
- tokenUsage: this.currentLLMTokenUsage
829
- };
830
- // Clear the stored token usage after associating it
831
- this.currentLLMTokenUsage = null;
832
- }
833
- // Store metadata in the execution step for this tool
834
- const toolStep = this.currentExecutionSteps
835
- .filter(step => step.type === 'tool_execution' && step.toolName === toolName)
836
- .pop(); // Get the most recent step for this tool
837
- if (toolStep && toolMetadata) {
838
- toolStep.toolMetadata = toolMetadata;
839
- }
840
- // Execute PostToolUse hooks
841
- if (this.hookExecutor) {
842
- try {
843
- const hookResult = await this.hookExecutor.executePostToolUse(toolName, toolArgs || {}, result, toolMetadata);
844
- // Log hook results (PostToolUse is informational, no blocking)
845
- if (hookResult.decision && this.config.debug) {
846
- logger.debug(`PostToolUse hook decision for ${toolName}: ${hookResult.decision}`);
847
- }
848
- // Display additional context from hooks if present
849
- if (hookResult.additionalContext) {
850
- onEvent({
851
- type: 'content_chunk',
852
- content: hookResult.additionalContext
853
- });
854
- }
855
- }
856
- catch (error) {
857
- logger.error(`PostToolUse hook failed: ${error}`);
858
- // Continue execution
859
- }
860
- }
861
- onEvent({
862
- type: EVENT_TYPES.TOOL_CALL_RESULT,
863
- toolName,
864
- result,
865
- toolMetadata
866
- });
867
- if (onToolEvent) {
868
- onToolEvent(); // Signal tool completion
869
- }
870
- }
871
- }
872
- }
873
- catch (error) {
874
- if (this.config.debug) {
875
- logger.debug(`Error processing stream chunk:`, error);
876
- }
877
- // Don't throw here, just log - let the main stream continue
878
- onEvent({
879
- type: EVENT_TYPES.ERROR,
880
- error: `Stream processing error: ${error instanceof Error ? error.message : String(error)}`
881
- });
882
- }
883
- }
884
- /**
885
- * Execute a single message without streaming (for non-interactive use)
886
- */
887
- async executeMessage(message) {
888
- return new Promise((resolve, reject) => {
889
- let response = '';
890
- let hasError = false;
891
- this.chatStream(message, (event) => {
892
- switch (event.type) {
893
- case 'content_chunk':
894
- response += event.content || '';
895
- break;
896
- case 'complete':
897
- if (!hasError) {
898
- resolve(response.trim());
899
- }
900
- break;
901
- case 'error':
902
- hasError = true;
903
- reject(new Error(event.error));
904
- break;
905
- }
906
- }).catch(reject);
907
- });
908
- }
909
- /**
910
- * Clear conversation history
911
- */
912
- clearHistory() {
913
- this.conversationHistory = [];
914
- this.toolCallArgs.clear(); // Clear stored tool args
915
- this.currentExecutionSteps = [];
916
- this.currentStepNumber = 0;
917
- this.currentLLMTokenUsage = null;
918
- this.isFirstLLMCall = true;
919
- // Reset stats
920
- this.stats = {
921
- inputTokens: 0,
922
- outputTokens: 0,
923
- cachedTokens: 0,
924
- totalTokens: 0,
925
- estimatedTotalCost: 0,
926
- executionTime: 0,
927
- toolCalls: 0,
928
- successfulTools: 0,
929
- failedTools: 0,
930
- llmCalls: 0,
931
- executionSteps: []
932
- };
933
- if (this.config.debug) {
934
- logger.debug('Conversation history cleared');
935
- }
936
- }
937
- /**
938
- * Get current conversation history
939
- */
940
- getHistory() {
941
- return [...this.conversationHistory];
942
- }
943
- /**
944
- * Get agent runtime statistics
945
- */
946
- getStats() {
947
- return { ...this.stats };
948
- }
949
- /**
950
- * Get available tools
951
- */
952
- getTools() {
953
- return [...this.tools];
954
- }
955
- /**
956
- * Get agent configuration
957
- */
958
- getConfig() {
959
- // Return sanitized config (without sensitive data)
960
- return {
961
- ...this.config,
962
- authToken: `${this.config.authToken.substring(0, 8)}***`
963
- };
964
- }
965
- /**
966
- * Health check for the agent
967
- */
968
- async healthCheck() {
969
- try {
970
- // Simple test message
971
- await this.executeMessage('Hello, can you confirm you are working?');
972
- return {
973
- status: 'healthy',
974
- provider: this.config.provider,
975
- model: this.config.model,
976
- toolCount: this.tools.length
977
- };
978
- }
979
- catch (error) {
980
- return {
981
- status: 'unhealthy',
982
- provider: this.config.provider,
983
- model: this.config.model,
984
- toolCount: this.tools.length,
985
- error: error instanceof Error ? error.message : String(error)
986
- };
987
- }
988
- }
989
- /**
990
- * Get maximum hook retry attempts from config
991
- */
992
- getMaxHookRetries() {
993
- return this.config.maxHookRetries || 5;
994
- }
995
- /**
996
- * Start a new LLM call step
997
- */
998
- startLLMStep() {
999
- // Determine the context based on whether this is the first call and if we just had a tool execution
1000
- let llmContext;
1001
- if (this.isFirstLLMCall) {
1002
- llmContext = 'initial_input';
1003
- this.isFirstLLMCall = false;
1004
- }
1005
- else {
1006
- // Check if the previous step was a tool execution
1007
- const prevStep = this.currentExecutionSteps.at(-1);
1008
- llmContext = (prevStep?.type === 'tool_execution') ? 'processing_tool_result' : 'final_response';
1009
- }
1010
- const step = {
1011
- stepNumber: ++this.currentStepNumber,
1012
- type: 'llm_call',
1013
- startTime: Date.now(),
1014
- llmContext
1015
- };
1016
- this.currentExecutionSteps.push(step);
1017
- this.stats.llmCalls++;
1018
- if (this.config.debug) {
1019
- logger.debug(`Started LLM step ${step.stepNumber} (${llmContext})`);
1020
- }
1021
- return step;
1022
- }
1023
- /**
1024
- * Start a new tool execution step
1025
- */
1026
- startToolStep(toolName) {
1027
- const step = {
1028
- stepNumber: ++this.currentStepNumber,
1029
- type: 'tool_execution',
1030
- startTime: Date.now(),
1031
- toolName
1032
- };
1033
- this.currentExecutionSteps.push(step);
1034
- if (this.config.debug) {
1035
- // Get the stored tool args for enhanced logging
1036
- const toolArgs = this.toolCallArgs.get(toolName);
1037
- if (toolArgs && Object.keys(toolArgs).length > 0) {
1038
- logger.debug(`Started tool step ${step.stepNumber}: ${toolName} ${JSON.stringify(toolArgs)}`);
1039
- }
1040
- else {
1041
- logger.debug(`Started tool step ${step.stepNumber}: ${toolName}`);
1042
- }
1043
- }
1044
- return step;
1045
- }
1046
- /**
1047
- * Complete an execution step
1048
- */
1049
- completeStep(step) {
1050
- step.endTime = Date.now();
1051
- step.duration = step.endTime - step.startTime;
1052
- if (this.config.debug) {
1053
- const type = step.type === 'llm_call' ? 'LLM' : `Tool (${step.toolName})`;
1054
- logger.debug(`Completed ${type} step ${step.stepNumber} in ${step.duration}ms`);
1055
- }
1056
- }
1057
- /**
1058
- * Update aggregate statistics with token usage
1059
- */
1060
- updateStatsWithTokenUsage(tokenUsage) {
1061
- this.stats.inputTokens += tokenUsage.inputTokens;
1062
- this.stats.outputTokens += tokenUsage.outputTokens;
1063
- if (tokenUsage.cachedTokens) {
1064
- this.stats.cachedTokens += tokenUsage.cachedTokens;
1065
- }
1066
- this.stats.totalTokens = this.stats.inputTokens + this.stats.outputTokens;
1067
- if (tokenUsage.estimatedCost) {
1068
- this.stats.estimatedTotalCost += tokenUsage.estimatedCost;
1069
- }
1070
- }
1071
- /**
1072
- * Load detected skills with file inventory
1073
- *
1074
- * @param patterns - Detected skill patterns
1075
- * @returns Skills with inventory and formatted content
1076
- */
1077
- async loadDetectedSkills(patterns) {
1078
- // Extract unique skill names (preserve order)
1079
- const skillNames = Array.from(new Set(patterns.map((p) => p.name)));
1080
- // Get skills from manager
1081
- const manager = SkillManager.getInstance();
1082
- const skillsWithInventory = await manager.getSkillsByNames(skillNames, {
1083
- cwd: this.config.workingDirectory,
1084
- agentName: 'codemie-code',
1085
- });
1086
- return skillsWithInventory;
1087
- }
1088
- /**
1089
- * Format skills for prompt injection
1090
- *
1091
- * @param skills - Skills with inventory
1092
- * @returns Formatted content for system message
1093
- */
1094
- formatSkillsForInjection(skills) {
1095
- const parts = [
1096
- 'The user has invoked the following skills. Follow their guidance for this request.',
1097
- '',
1098
- ];
1099
- for (const { formattedContent } of skills) {
1100
- parts.push('---', '', formattedContent, '');
1101
- }
1102
- parts.push('---', '', 'IMPORTANT: These skills provide specialized knowledge for this task. Prioritize their guidance over general instructions.');
1103
- return parts.join('\n');
1104
- }
1105
- }
1106
- //# sourceMappingURL=agent.js.map