@mcp-abap-adt/llm-agent-server 12.0.2 → 12.0.4

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 (555) hide show
  1. package/dist/agent.d.ts +1 -1
  2. package/dist/agent.d.ts.map +1 -1
  3. package/dist/agent.js +1 -1
  4. package/dist/agent.js.map +1 -1
  5. package/dist/generated/version.d.ts +1 -1
  6. package/dist/generated/version.js +1 -1
  7. package/dist/index.d.ts +1 -64
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +1 -61
  10. package/dist/index.js.map +1 -1
  11. package/dist/smart-agent/cli.js +1 -2
  12. package/dist/smart-agent/cli.js.map +1 -1
  13. package/dist/smart-agent/pipeline.d.ts +1 -1
  14. package/dist/smart-agent/pipeline.d.ts.map +1 -1
  15. package/dist/smart-agent/server.d.ts +1 -1
  16. package/dist/smart-agent/server.d.ts.map +1 -1
  17. package/dist/smart-agent/smart-server.d.ts +2 -3
  18. package/dist/smart-agent/smart-server.d.ts.map +1 -1
  19. package/dist/smart-agent/smart-server.js +11 -18
  20. package/dist/smart-agent/smart-server.js.map +1 -1
  21. package/dist/smoke-adapters.js +2 -4
  22. package/dist/smoke-adapters.js.map +1 -1
  23. package/package.json +15 -15
  24. package/dist/agents/anthropic-agent.d.ts +0 -33
  25. package/dist/agents/anthropic-agent.d.ts.map +0 -1
  26. package/dist/agents/anthropic-agent.js +0 -138
  27. package/dist/agents/anthropic-agent.js.map +0 -1
  28. package/dist/agents/base.d.ts +0 -90
  29. package/dist/agents/base.d.ts.map +0 -1
  30. package/dist/agents/base.js +0 -107
  31. package/dist/agents/base.js.map +0 -1
  32. package/dist/agents/deepseek-agent.d.ts +0 -31
  33. package/dist/agents/deepseek-agent.d.ts.map +0 -1
  34. package/dist/agents/deepseek-agent.js +0 -121
  35. package/dist/agents/deepseek-agent.js.map +0 -1
  36. package/dist/agents/index.d.ts +0 -10
  37. package/dist/agents/index.d.ts.map +0 -1
  38. package/dist/agents/index.js +0 -10
  39. package/dist/agents/index.js.map +0 -1
  40. package/dist/agents/openai-agent.d.ts +0 -32
  41. package/dist/agents/openai-agent.d.ts.map +0 -1
  42. package/dist/agents/openai-agent.js +0 -122
  43. package/dist/agents/openai-agent.js.map +0 -1
  44. package/dist/agents/prompt-based-agent.d.ts +0 -28
  45. package/dist/agents/prompt-based-agent.d.ts.map +0 -1
  46. package/dist/agents/prompt-based-agent.js +0 -67
  47. package/dist/agents/prompt-based-agent.js.map +0 -1
  48. package/dist/agents/sap-core-ai-agent.d.ts +0 -41
  49. package/dist/agents/sap-core-ai-agent.d.ts.map +0 -1
  50. package/dist/agents/sap-core-ai-agent.js +0 -151
  51. package/dist/agents/sap-core-ai-agent.js.map +0 -1
  52. package/dist/cli.d.ts +0 -53
  53. package/dist/cli.d.ts.map +0 -1
  54. package/dist/cli.js +0 -338
  55. package/dist/cli.js.map +0 -1
  56. package/dist/llm-providers/anthropic.d.ts +0 -25
  57. package/dist/llm-providers/anthropic.d.ts.map +0 -1
  58. package/dist/llm-providers/anthropic.js +0 -202
  59. package/dist/llm-providers/anthropic.js.map +0 -1
  60. package/dist/llm-providers/base.d.ts +0 -33
  61. package/dist/llm-providers/base.d.ts.map +0 -1
  62. package/dist/llm-providers/base.js +0 -18
  63. package/dist/llm-providers/base.js.map +0 -1
  64. package/dist/llm-providers/deepseek.d.ts +0 -24
  65. package/dist/llm-providers/deepseek.d.ts.map +0 -1
  66. package/dist/llm-providers/deepseek.js +0 -60
  67. package/dist/llm-providers/deepseek.js.map +0 -1
  68. package/dist/llm-providers/index.d.ts +0 -13
  69. package/dist/llm-providers/index.d.ts.map +0 -1
  70. package/dist/llm-providers/index.js +0 -15
  71. package/dist/llm-providers/index.js.map +0 -1
  72. package/dist/llm-providers/openai.d.ts +0 -34
  73. package/dist/llm-providers/openai.d.ts.map +0 -1
  74. package/dist/llm-providers/openai.js +0 -193
  75. package/dist/llm-providers/openai.js.map +0 -1
  76. package/dist/llm-providers/sap-core-ai.d.ts +0 -90
  77. package/dist/llm-providers/sap-core-ai.d.ts.map +0 -1
  78. package/dist/llm-providers/sap-core-ai.js +0 -394
  79. package/dist/llm-providers/sap-core-ai.js.map +0 -1
  80. package/dist/mcp/client.d.ts +0 -133
  81. package/dist/mcp/client.d.ts.map +0 -1
  82. package/dist/mcp/client.js +0 -314
  83. package/dist/mcp/client.js.map +0 -1
  84. package/dist/smart-agent/adapters/cline-client-adapter.d.ts +0 -18
  85. package/dist/smart-agent/adapters/cline-client-adapter.d.ts.map +0 -1
  86. package/dist/smart-agent/adapters/cline-client-adapter.js +0 -21
  87. package/dist/smart-agent/adapters/cline-client-adapter.js.map +0 -1
  88. package/dist/smart-agent/adapters/index.d.ts +0 -4
  89. package/dist/smart-agent/adapters/index.d.ts.map +0 -1
  90. package/dist/smart-agent/adapters/index.js +0 -4
  91. package/dist/smart-agent/adapters/index.js.map +0 -1
  92. package/dist/smart-agent/adapters/llm-adapter.d.ts +0 -39
  93. package/dist/smart-agent/adapters/llm-adapter.d.ts.map +0 -1
  94. package/dist/smart-agent/adapters/llm-adapter.js +0 -345
  95. package/dist/smart-agent/adapters/llm-adapter.js.map +0 -1
  96. package/dist/smart-agent/adapters/llm-provider-bridge.d.ts +0 -31
  97. package/dist/smart-agent/adapters/llm-provider-bridge.d.ts.map +0 -1
  98. package/dist/smart-agent/adapters/llm-provider-bridge.js +0 -122
  99. package/dist/smart-agent/adapters/llm-provider-bridge.js.map +0 -1
  100. package/dist/smart-agent/adapters/mcp-client-adapter.d.ts +0 -16
  101. package/dist/smart-agent/adapters/mcp-client-adapter.d.ts.map +0 -1
  102. package/dist/smart-agent/adapters/mcp-client-adapter.js +0 -95
  103. package/dist/smart-agent/adapters/mcp-client-adapter.js.map +0 -1
  104. package/dist/smart-agent/adapters/non-streaming-llm.d.ts +0 -18
  105. package/dist/smart-agent/adapters/non-streaming-llm.d.ts.map +0 -1
  106. package/dist/smart-agent/adapters/non-streaming-llm.js +0 -44
  107. package/dist/smart-agent/adapters/non-streaming-llm.js.map +0 -1
  108. package/dist/smart-agent/agent.d.ts +0 -227
  109. package/dist/smart-agent/agent.d.ts.map +0 -1
  110. package/dist/smart-agent/agent.js +0 -1534
  111. package/dist/smart-agent/agent.js.map +0 -1
  112. package/dist/smart-agent/api-adapters/anthropic-adapter.d.ts +0 -10
  113. package/dist/smart-agent/api-adapters/anthropic-adapter.d.ts.map +0 -1
  114. package/dist/smart-agent/api-adapters/anthropic-adapter.js +0 -356
  115. package/dist/smart-agent/api-adapters/anthropic-adapter.js.map +0 -1
  116. package/dist/smart-agent/api-adapters/index.d.ts +0 -3
  117. package/dist/smart-agent/api-adapters/index.d.ts.map +0 -1
  118. package/dist/smart-agent/api-adapters/index.js +0 -3
  119. package/dist/smart-agent/api-adapters/index.js.map +0 -1
  120. package/dist/smart-agent/api-adapters/openai-adapter.d.ts +0 -10
  121. package/dist/smart-agent/api-adapters/openai-adapter.d.ts.map +0 -1
  122. package/dist/smart-agent/api-adapters/openai-adapter.js +0 -277
  123. package/dist/smart-agent/api-adapters/openai-adapter.js.map +0 -1
  124. package/dist/smart-agent/builder.d.ts +0 -276
  125. package/dist/smart-agent/builder.d.ts.map +0 -1
  126. package/dist/smart-agent/builder.js +0 -950
  127. package/dist/smart-agent/builder.js.map +0 -1
  128. package/dist/smart-agent/cache/index.d.ts +0 -4
  129. package/dist/smart-agent/cache/index.d.ts.map +0 -1
  130. package/dist/smart-agent/cache/index.js +0 -3
  131. package/dist/smart-agent/cache/index.js.map +0 -1
  132. package/dist/smart-agent/cache/noop-tool-cache.d.ts +0 -7
  133. package/dist/smart-agent/cache/noop-tool-cache.d.ts.map +0 -1
  134. package/dist/smart-agent/cache/noop-tool-cache.js +0 -8
  135. package/dist/smart-agent/cache/noop-tool-cache.js.map +0 -1
  136. package/dist/smart-agent/cache/tool-cache.d.ts +0 -14
  137. package/dist/smart-agent/cache/tool-cache.d.ts.map +0 -1
  138. package/dist/smart-agent/cache/tool-cache.js +0 -32
  139. package/dist/smart-agent/cache/tool-cache.js.map +0 -1
  140. package/dist/smart-agent/cache/types.d.ts +0 -7
  141. package/dist/smart-agent/cache/types.d.ts.map +0 -1
  142. package/dist/smart-agent/cache/types.js +0 -2
  143. package/dist/smart-agent/cache/types.js.map +0 -1
  144. package/dist/smart-agent/classifier/index.d.ts +0 -3
  145. package/dist/smart-agent/classifier/index.d.ts.map +0 -1
  146. package/dist/smart-agent/classifier/index.js +0 -2
  147. package/dist/smart-agent/classifier/index.js.map +0 -1
  148. package/dist/smart-agent/classifier/llm-classifier.d.ts +0 -20
  149. package/dist/smart-agent/classifier/llm-classifier.d.ts.map +0 -1
  150. package/dist/smart-agent/classifier/llm-classifier.js +0 -128
  151. package/dist/smart-agent/classifier/llm-classifier.js.map +0 -1
  152. package/dist/smart-agent/config/config-watcher.d.ts +0 -54
  153. package/dist/smart-agent/config/config-watcher.d.ts.map +0 -1
  154. package/dist/smart-agent/config/config-watcher.js +0 -107
  155. package/dist/smart-agent/config/config-watcher.js.map +0 -1
  156. package/dist/smart-agent/config/index.d.ts +0 -2
  157. package/dist/smart-agent/config/index.d.ts.map +0 -1
  158. package/dist/smart-agent/config/index.js +0 -2
  159. package/dist/smart-agent/config/index.js.map +0 -1
  160. package/dist/smart-agent/context/context-assembler.d.ts +0 -49
  161. package/dist/smart-agent/context/context-assembler.d.ts.map +0 -1
  162. package/dist/smart-agent/context/context-assembler.js +0 -184
  163. package/dist/smart-agent/context/context-assembler.js.map +0 -1
  164. package/dist/smart-agent/context/index.d.ts +0 -3
  165. package/dist/smart-agent/context/index.d.ts.map +0 -1
  166. package/dist/smart-agent/context/index.js +0 -2
  167. package/dist/smart-agent/context/index.js.map +0 -1
  168. package/dist/smart-agent/embedder-factories.d.ts +0 -14
  169. package/dist/smart-agent/embedder-factories.d.ts.map +0 -1
  170. package/dist/smart-agent/embedder-factories.js +0 -61
  171. package/dist/smart-agent/embedder-factories.js.map +0 -1
  172. package/dist/smart-agent/health/health-checker.d.ts +0 -21
  173. package/dist/smart-agent/health/health-checker.d.ts.map +0 -1
  174. package/dist/smart-agent/health/health-checker.js +0 -52
  175. package/dist/smart-agent/health/health-checker.js.map +0 -1
  176. package/dist/smart-agent/health/index.d.ts +0 -3
  177. package/dist/smart-agent/health/index.d.ts.map +0 -1
  178. package/dist/smart-agent/health/index.js +0 -2
  179. package/dist/smart-agent/health/index.js.map +0 -1
  180. package/dist/smart-agent/health/types.d.ts +0 -25
  181. package/dist/smart-agent/health/types.d.ts.map +0 -1
  182. package/dist/smart-agent/health/types.js +0 -2
  183. package/dist/smart-agent/health/types.js.map +0 -1
  184. package/dist/smart-agent/history/history-memory.d.ts +0 -12
  185. package/dist/smart-agent/history/history-memory.d.ts.map +0 -1
  186. package/dist/smart-agent/history/history-memory.js +0 -26
  187. package/dist/smart-agent/history/history-memory.js.map +0 -1
  188. package/dist/smart-agent/history/history-summarizer.d.ts +0 -10
  189. package/dist/smart-agent/history/history-summarizer.d.ts.map +0 -1
  190. package/dist/smart-agent/history/history-summarizer.js +0 -27
  191. package/dist/smart-agent/history/history-summarizer.js.map +0 -1
  192. package/dist/smart-agent/history/index.d.ts +0 -3
  193. package/dist/smart-agent/history/index.d.ts.map +0 -1
  194. package/dist/smart-agent/history/index.js +0 -3
  195. package/dist/smart-agent/history/index.js.map +0 -1
  196. package/dist/smart-agent/interfaces/api-adapter.d.ts +0 -36
  197. package/dist/smart-agent/interfaces/api-adapter.d.ts.map +0 -1
  198. package/dist/smart-agent/interfaces/api-adapter.js +0 -9
  199. package/dist/smart-agent/interfaces/api-adapter.js.map +0 -1
  200. package/dist/smart-agent/interfaces/client-adapter.d.ts +0 -23
  201. package/dist/smart-agent/interfaces/client-adapter.d.ts.map +0 -1
  202. package/dist/smart-agent/interfaces/client-adapter.js +0 -10
  203. package/dist/smart-agent/interfaces/client-adapter.js.map +0 -1
  204. package/dist/smart-agent/interfaces/mcp-connection-strategy.d.ts +0 -26
  205. package/dist/smart-agent/interfaces/mcp-connection-strategy.d.ts.map +0 -1
  206. package/dist/smart-agent/interfaces/mcp-connection-strategy.js +0 -2
  207. package/dist/smart-agent/interfaces/mcp-connection-strategy.js.map +0 -1
  208. package/dist/smart-agent/interfaces/model-resolver.d.ts +0 -9
  209. package/dist/smart-agent/interfaces/model-resolver.d.ts.map +0 -1
  210. package/dist/smart-agent/interfaces/model-resolver.js +0 -2
  211. package/dist/smart-agent/interfaces/model-resolver.js.map +0 -1
  212. package/dist/smart-agent/interfaces/pipeline.d.ts +0 -123
  213. package/dist/smart-agent/interfaces/pipeline.d.ts.map +0 -1
  214. package/dist/smart-agent/interfaces/pipeline.js +0 -13
  215. package/dist/smart-agent/interfaces/pipeline.js.map +0 -1
  216. package/dist/smart-agent/logger/console-logger.d.ts +0 -7
  217. package/dist/smart-agent/logger/console-logger.d.ts.map +0 -1
  218. package/dist/smart-agent/logger/console-logger.js +0 -12
  219. package/dist/smart-agent/logger/console-logger.js.map +0 -1
  220. package/dist/smart-agent/logger/default-request-logger.d.ts +0 -17
  221. package/dist/smart-agent/logger/default-request-logger.d.ts.map +0 -1
  222. package/dist/smart-agent/logger/default-request-logger.js +0 -86
  223. package/dist/smart-agent/logger/default-request-logger.js.map +0 -1
  224. package/dist/smart-agent/logger/index.d.ts +0 -3
  225. package/dist/smart-agent/logger/index.d.ts.map +0 -1
  226. package/dist/smart-agent/logger/index.js +0 -2
  227. package/dist/smart-agent/logger/index.js.map +0 -1
  228. package/dist/smart-agent/logger/noop-request-logger.d.ts +0 -11
  229. package/dist/smart-agent/logger/noop-request-logger.d.ts.map +0 -1
  230. package/dist/smart-agent/logger/noop-request-logger.js +0 -20
  231. package/dist/smart-agent/logger/noop-request-logger.js.map +0 -1
  232. package/dist/smart-agent/logger/session-logger.d.ts +0 -10
  233. package/dist/smart-agent/logger/session-logger.d.ts.map +0 -1
  234. package/dist/smart-agent/logger/session-logger.js +0 -40
  235. package/dist/smart-agent/logger/session-logger.js.map +0 -1
  236. package/dist/smart-agent/logger/types.d.ts +0 -63
  237. package/dist/smart-agent/logger/types.d.ts.map +0 -1
  238. package/dist/smart-agent/logger/types.js +0 -2
  239. package/dist/smart-agent/logger/types.js.map +0 -1
  240. package/dist/smart-agent/mcp-client-factory.d.ts +0 -3
  241. package/dist/smart-agent/mcp-client-factory.d.ts.map +0 -1
  242. package/dist/smart-agent/mcp-client-factory.js +0 -21
  243. package/dist/smart-agent/mcp-client-factory.js.map +0 -1
  244. package/dist/smart-agent/metrics/in-memory-metrics.d.ts +0 -58
  245. package/dist/smart-agent/metrics/in-memory-metrics.d.ts.map +0 -1
  246. package/dist/smart-agent/metrics/in-memory-metrics.js +0 -78
  247. package/dist/smart-agent/metrics/in-memory-metrics.js.map +0 -1
  248. package/dist/smart-agent/metrics/index.d.ts +0 -4
  249. package/dist/smart-agent/metrics/index.d.ts.map +0 -1
  250. package/dist/smart-agent/metrics/index.js +0 -3
  251. package/dist/smart-agent/metrics/index.js.map +0 -1
  252. package/dist/smart-agent/metrics/noop-metrics.d.ts +0 -17
  253. package/dist/smart-agent/metrics/noop-metrics.d.ts.map +0 -1
  254. package/dist/smart-agent/metrics/noop-metrics.js +0 -22
  255. package/dist/smart-agent/metrics/noop-metrics.js.map +0 -1
  256. package/dist/smart-agent/metrics/types.d.ts +0 -36
  257. package/dist/smart-agent/metrics/types.d.ts.map +0 -1
  258. package/dist/smart-agent/metrics/types.js +0 -9
  259. package/dist/smart-agent/metrics/types.js.map +0 -1
  260. package/dist/smart-agent/otel/index.d.ts +0 -2
  261. package/dist/smart-agent/otel/index.d.ts.map +0 -1
  262. package/dist/smart-agent/otel/index.js +0 -2
  263. package/dist/smart-agent/otel/index.js.map +0 -1
  264. package/dist/smart-agent/otel/otel-tracer-adapter.d.ts +0 -15
  265. package/dist/smart-agent/otel/otel-tracer-adapter.d.ts.map +0 -1
  266. package/dist/smart-agent/otel/otel-tracer-adapter.js +0 -62
  267. package/dist/smart-agent/otel/otel-tracer-adapter.js.map +0 -1
  268. package/dist/smart-agent/pipeline/condition-evaluator.d.ts +0 -35
  269. package/dist/smart-agent/pipeline/condition-evaluator.d.ts.map +0 -1
  270. package/dist/smart-agent/pipeline/condition-evaluator.js +0 -143
  271. package/dist/smart-agent/pipeline/condition-evaluator.js.map +0 -1
  272. package/dist/smart-agent/pipeline/context.d.ts +0 -119
  273. package/dist/smart-agent/pipeline/context.d.ts.map +0 -1
  274. package/dist/smart-agent/pipeline/context.js +0 -19
  275. package/dist/smart-agent/pipeline/context.js.map +0 -1
  276. package/dist/smart-agent/pipeline/default-pipeline.d.ts +0 -69
  277. package/dist/smart-agent/pipeline/default-pipeline.d.ts.map +0 -1
  278. package/dist/smart-agent/pipeline/default-pipeline.js +0 -276
  279. package/dist/smart-agent/pipeline/default-pipeline.js.map +0 -1
  280. package/dist/smart-agent/pipeline/executor.d.ts +0 -54
  281. package/dist/smart-agent/pipeline/executor.d.ts.map +0 -1
  282. package/dist/smart-agent/pipeline/executor.js +0 -133
  283. package/dist/smart-agent/pipeline/executor.js.map +0 -1
  284. package/dist/smart-agent/pipeline/handlers/assemble.d.ts +0 -16
  285. package/dist/smart-agent/pipeline/handlers/assemble.d.ts.map +0 -1
  286. package/dist/smart-agent/pipeline/handlers/assemble.js +0 -72
  287. package/dist/smart-agent/pipeline/handlers/assemble.js.map +0 -1
  288. package/dist/smart-agent/pipeline/handlers/build-tool-query.d.ts +0 -30
  289. package/dist/smart-agent/pipeline/handlers/build-tool-query.d.ts.map +0 -1
  290. package/dist/smart-agent/pipeline/handlers/build-tool-query.js +0 -80
  291. package/dist/smart-agent/pipeline/handlers/build-tool-query.js.map +0 -1
  292. package/dist/smart-agent/pipeline/handlers/classify.d.ts +0 -21
  293. package/dist/smart-agent/pipeline/handlers/classify.d.ts.map +0 -1
  294. package/dist/smart-agent/pipeline/handlers/classify.js +0 -60
  295. package/dist/smart-agent/pipeline/handlers/classify.js.map +0 -1
  296. package/dist/smart-agent/pipeline/handlers/expand.d.ts +0 -16
  297. package/dist/smart-agent/pipeline/handlers/expand.d.ts.map +0 -1
  298. package/dist/smart-agent/pipeline/handlers/expand.js +0 -24
  299. package/dist/smart-agent/pipeline/handlers/expand.js.map +0 -1
  300. package/dist/smart-agent/pipeline/handlers/history-upsert.d.ts +0 -29
  301. package/dist/smart-agent/pipeline/handlers/history-upsert.d.ts.map +0 -1
  302. package/dist/smart-agent/pipeline/handlers/history-upsert.js +0 -75
  303. package/dist/smart-agent/pipeline/handlers/history-upsert.js.map +0 -1
  304. package/dist/smart-agent/pipeline/handlers/index.d.ts +0 -31
  305. package/dist/smart-agent/pipeline/handlers/index.d.ts.map +0 -1
  306. package/dist/smart-agent/pipeline/handlers/index.js +0 -44
  307. package/dist/smart-agent/pipeline/handlers/index.js.map +0 -1
  308. package/dist/smart-agent/pipeline/handlers/rag-query.d.ts +0 -27
  309. package/dist/smart-agent/pipeline/handlers/rag-query.d.ts.map +0 -1
  310. package/dist/smart-agent/pipeline/handlers/rag-query.js +0 -117
  311. package/dist/smart-agent/pipeline/handlers/rag-query.js.map +0 -1
  312. package/dist/smart-agent/pipeline/handlers/rerank.d.ts +0 -16
  313. package/dist/smart-agent/pipeline/handlers/rerank.d.ts.map +0 -1
  314. package/dist/smart-agent/pipeline/handlers/rerank.js +0 -27
  315. package/dist/smart-agent/pipeline/handlers/rerank.js.map +0 -1
  316. package/dist/smart-agent/pipeline/handlers/skill-select.d.ts +0 -18
  317. package/dist/smart-agent/pipeline/handlers/skill-select.d.ts.map +0 -1
  318. package/dist/smart-agent/pipeline/handlers/skill-select.js +0 -88
  319. package/dist/smart-agent/pipeline/handlers/skill-select.js.map +0 -1
  320. package/dist/smart-agent/pipeline/handlers/summarize.d.ts +0 -17
  321. package/dist/smart-agent/pipeline/handlers/summarize.d.ts.map +0 -1
  322. package/dist/smart-agent/pipeline/handlers/summarize.js +0 -56
  323. package/dist/smart-agent/pipeline/handlers/summarize.js.map +0 -1
  324. package/dist/smart-agent/pipeline/handlers/tool-loop.d.ts +0 -32
  325. package/dist/smart-agent/pipeline/handlers/tool-loop.d.ts.map +0 -1
  326. package/dist/smart-agent/pipeline/handlers/tool-loop.js +0 -734
  327. package/dist/smart-agent/pipeline/handlers/tool-loop.js.map +0 -1
  328. package/dist/smart-agent/pipeline/handlers/tool-select.d.ts +0 -21
  329. package/dist/smart-agent/pipeline/handlers/tool-select.d.ts.map +0 -1
  330. package/dist/smart-agent/pipeline/handlers/tool-select.js +0 -109
  331. package/dist/smart-agent/pipeline/handlers/tool-select.js.map +0 -1
  332. package/dist/smart-agent/pipeline/handlers/translate.d.ts +0 -17
  333. package/dist/smart-agent/pipeline/handlers/translate.d.ts.map +0 -1
  334. package/dist/smart-agent/pipeline/handlers/translate.js +0 -42
  335. package/dist/smart-agent/pipeline/handlers/translate.js.map +0 -1
  336. package/dist/smart-agent/pipeline/index.d.ts +0 -14
  337. package/dist/smart-agent/pipeline/index.d.ts.map +0 -1
  338. package/dist/smart-agent/pipeline/index.js +0 -16
  339. package/dist/smart-agent/pipeline/index.js.map +0 -1
  340. package/dist/smart-agent/pipeline/stage-handler.d.ts +0 -36
  341. package/dist/smart-agent/pipeline/stage-handler.d.ts.map +0 -1
  342. package/dist/smart-agent/pipeline/stage-handler.js +0 -24
  343. package/dist/smart-agent/pipeline/stage-handler.js.map +0 -1
  344. package/dist/smart-agent/pipeline/types.d.ts +0 -116
  345. package/dist/smart-agent/pipeline/types.d.ts.map +0 -1
  346. package/dist/smart-agent/pipeline/types.js +0 -54
  347. package/dist/smart-agent/pipeline/types.js.map +0 -1
  348. package/dist/smart-agent/plugins/index.d.ts +0 -4
  349. package/dist/smart-agent/plugins/index.d.ts.map +0 -1
  350. package/dist/smart-agent/plugins/index.js +0 -3
  351. package/dist/smart-agent/plugins/index.js.map +0 -1
  352. package/dist/smart-agent/plugins/loader.d.ts +0 -67
  353. package/dist/smart-agent/plugins/loader.d.ts.map +0 -1
  354. package/dist/smart-agent/plugins/loader.js +0 -114
  355. package/dist/smart-agent/plugins/loader.js.map +0 -1
  356. package/dist/smart-agent/plugins/types.d.ts +0 -162
  357. package/dist/smart-agent/plugins/types.d.ts.map +0 -1
  358. package/dist/smart-agent/plugins/types.js +0 -136
  359. package/dist/smart-agent/plugins/types.js.map +0 -1
  360. package/dist/smart-agent/policy/fallback-llm-call-strategy.d.ts +0 -16
  361. package/dist/smart-agent/policy/fallback-llm-call-strategy.d.ts.map +0 -1
  362. package/dist/smart-agent/policy/fallback-llm-call-strategy.js +0 -66
  363. package/dist/smart-agent/policy/fallback-llm-call-strategy.js.map +0 -1
  364. package/dist/smart-agent/policy/heuristic-injection-detector.d.ts +0 -5
  365. package/dist/smart-agent/policy/heuristic-injection-detector.d.ts.map +0 -1
  366. package/dist/smart-agent/policy/heuristic-injection-detector.js +0 -36
  367. package/dist/smart-agent/policy/heuristic-injection-detector.js.map +0 -1
  368. package/dist/smart-agent/policy/index.d.ts +0 -6
  369. package/dist/smart-agent/policy/index.d.ts.map +0 -1
  370. package/dist/smart-agent/policy/index.js +0 -5
  371. package/dist/smart-agent/policy/index.js.map +0 -1
  372. package/dist/smart-agent/policy/mixed-tool-call-handler.d.ts +0 -15
  373. package/dist/smart-agent/policy/mixed-tool-call-handler.d.ts.map +0 -1
  374. package/dist/smart-agent/policy/mixed-tool-call-handler.js +0 -49
  375. package/dist/smart-agent/policy/mixed-tool-call-handler.js.map +0 -1
  376. package/dist/smart-agent/policy/non-streaming-llm-call-strategy.d.ts +0 -6
  377. package/dist/smart-agent/policy/non-streaming-llm-call-strategy.d.ts.map +0 -1
  378. package/dist/smart-agent/policy/non-streaming-llm-call-strategy.js +0 -21
  379. package/dist/smart-agent/policy/non-streaming-llm-call-strategy.js.map +0 -1
  380. package/dist/smart-agent/policy/pending-tool-results-registry.d.ts +0 -25
  381. package/dist/smart-agent/policy/pending-tool-results-registry.d.ts.map +0 -1
  382. package/dist/smart-agent/policy/pending-tool-results-registry.js +0 -50
  383. package/dist/smart-agent/policy/pending-tool-results-registry.js.map +0 -1
  384. package/dist/smart-agent/policy/streaming-llm-call-strategy.d.ts +0 -6
  385. package/dist/smart-agent/policy/streaming-llm-call-strategy.d.ts.map +0 -1
  386. package/dist/smart-agent/policy/streaming-llm-call-strategy.js +0 -7
  387. package/dist/smart-agent/policy/streaming-llm-call-strategy.js.map +0 -1
  388. package/dist/smart-agent/policy/tool-availability-registry.d.ts +0 -21
  389. package/dist/smart-agent/policy/tool-availability-registry.d.ts.map +0 -1
  390. package/dist/smart-agent/policy/tool-availability-registry.js +0 -77
  391. package/dist/smart-agent/policy/tool-availability-registry.js.map +0 -1
  392. package/dist/smart-agent/policy/tool-policy-guard.d.ts +0 -8
  393. package/dist/smart-agent/policy/tool-policy-guard.d.ts.map +0 -1
  394. package/dist/smart-agent/policy/tool-policy-guard.js +0 -40
  395. package/dist/smart-agent/policy/tool-policy-guard.js.map +0 -1
  396. package/dist/smart-agent/policy/types.d.ts +0 -51
  397. package/dist/smart-agent/policy/types.d.ts.map +0 -1
  398. package/dist/smart-agent/policy/types.js +0 -17
  399. package/dist/smart-agent/policy/types.js.map +0 -1
  400. package/dist/smart-agent/providers.d.ts +0 -124
  401. package/dist/smart-agent/providers.d.ts.map +0 -1
  402. package/dist/smart-agent/providers.js +0 -276
  403. package/dist/smart-agent/providers.js.map +0 -1
  404. package/dist/smart-agent/rag-factories.d.ts +0 -31
  405. package/dist/smart-agent/rag-factories.d.ts.map +0 -1
  406. package/dist/smart-agent/rag-factories.js +0 -53
  407. package/dist/smart-agent/rag-factories.js.map +0 -1
  408. package/dist/smart-agent/reranker/index.d.ts +0 -4
  409. package/dist/smart-agent/reranker/index.d.ts.map +0 -1
  410. package/dist/smart-agent/reranker/index.js +0 -3
  411. package/dist/smart-agent/reranker/index.js.map +0 -1
  412. package/dist/smart-agent/reranker/llm-reranker.d.ts +0 -10
  413. package/dist/smart-agent/reranker/llm-reranker.d.ts.map +0 -1
  414. package/dist/smart-agent/reranker/llm-reranker.js +0 -55
  415. package/dist/smart-agent/reranker/llm-reranker.js.map +0 -1
  416. package/dist/smart-agent/reranker/noop-reranker.d.ts +0 -6
  417. package/dist/smart-agent/reranker/noop-reranker.d.ts.map +0 -1
  418. package/dist/smart-agent/reranker/noop-reranker.js +0 -6
  419. package/dist/smart-agent/reranker/noop-reranker.js.map +0 -1
  420. package/dist/smart-agent/reranker/types.d.ts +0 -5
  421. package/dist/smart-agent/reranker/types.d.ts.map +0 -1
  422. package/dist/smart-agent/reranker/types.js +0 -2
  423. package/dist/smart-agent/reranker/types.js.map +0 -1
  424. package/dist/smart-agent/resilience/circuit-breaker-embedder.d.ts +0 -16
  425. package/dist/smart-agent/resilience/circuit-breaker-embedder.d.ts.map +0 -1
  426. package/dist/smart-agent/resilience/circuit-breaker-embedder.js +0 -47
  427. package/dist/smart-agent/resilience/circuit-breaker-embedder.js.map +0 -1
  428. package/dist/smart-agent/resilience/circuit-breaker-llm.d.ts +0 -19
  429. package/dist/smart-agent/resilience/circuit-breaker-llm.d.ts.map +0 -1
  430. package/dist/smart-agent/resilience/circuit-breaker-llm.js +0 -72
  431. package/dist/smart-agent/resilience/circuit-breaker-llm.js.map +0 -1
  432. package/dist/smart-agent/resilience/circuit-breaker.d.ts +0 -36
  433. package/dist/smart-agent/resilience/circuit-breaker.d.ts.map +0 -1
  434. package/dist/smart-agent/resilience/circuit-breaker.js +0 -60
  435. package/dist/smart-agent/resilience/circuit-breaker.js.map +0 -1
  436. package/dist/smart-agent/resilience/fallback-rag.d.ts +0 -21
  437. package/dist/smart-agent/resilience/fallback-rag.d.ts.map +0 -1
  438. package/dist/smart-agent/resilience/fallback-rag.js +0 -80
  439. package/dist/smart-agent/resilience/fallback-rag.js.map +0 -1
  440. package/dist/smart-agent/resilience/index.d.ts +0 -5
  441. package/dist/smart-agent/resilience/index.d.ts.map +0 -1
  442. package/dist/smart-agent/resilience/index.js +0 -5
  443. package/dist/smart-agent/resilience/index.js.map +0 -1
  444. package/dist/smart-agent/resilience/rate-limiter-llm.d.ts +0 -17
  445. package/dist/smart-agent/resilience/rate-limiter-llm.d.ts.map +0 -1
  446. package/dist/smart-agent/resilience/rate-limiter-llm.js +0 -30
  447. package/dist/smart-agent/resilience/rate-limiter-llm.js.map +0 -1
  448. package/dist/smart-agent/resilience/retry-llm.d.ts +0 -32
  449. package/dist/smart-agent/resilience/retry-llm.d.ts.map +0 -1
  450. package/dist/smart-agent/resilience/retry-llm.js +0 -103
  451. package/dist/smart-agent/resilience/retry-llm.js.map +0 -1
  452. package/dist/smart-agent/resilience/token-bucket-rate-limiter.d.ts +0 -21
  453. package/dist/smart-agent/resilience/token-bucket-rate-limiter.d.ts.map +0 -1
  454. package/dist/smart-agent/resilience/token-bucket-rate-limiter.js +0 -32
  455. package/dist/smart-agent/resilience/token-bucket-rate-limiter.js.map +0 -1
  456. package/dist/smart-agent/session/index.d.ts +0 -4
  457. package/dist/smart-agent/session/index.d.ts.map +0 -1
  458. package/dist/smart-agent/session/index.js +0 -3
  459. package/dist/smart-agent/session/index.js.map +0 -1
  460. package/dist/smart-agent/session/noop-session-manager.d.ts +0 -8
  461. package/dist/smart-agent/session/noop-session-manager.d.ts.map +0 -1
  462. package/dist/smart-agent/session/noop-session-manager.js +0 -11
  463. package/dist/smart-agent/session/noop-session-manager.js.map +0 -1
  464. package/dist/smart-agent/session/session-manager.d.ts +0 -13
  465. package/dist/smart-agent/session/session-manager.d.ts.map +0 -1
  466. package/dist/smart-agent/session/session-manager.js +0 -20
  467. package/dist/smart-agent/session/session-manager.js.map +0 -1
  468. package/dist/smart-agent/session/types.d.ts +0 -7
  469. package/dist/smart-agent/session/types.d.ts.map +0 -1
  470. package/dist/smart-agent/session/types.js +0 -2
  471. package/dist/smart-agent/session/types.js.map +0 -1
  472. package/dist/smart-agent/skills/claude-skill-manager.d.ts +0 -24
  473. package/dist/smart-agent/skills/claude-skill-manager.d.ts.map +0 -1
  474. package/dist/smart-agent/skills/claude-skill-manager.js +0 -81
  475. package/dist/smart-agent/skills/claude-skill-manager.js.map +0 -1
  476. package/dist/smart-agent/skills/codex-skill-manager.d.ts +0 -20
  477. package/dist/smart-agent/skills/codex-skill-manager.d.ts.map +0 -1
  478. package/dist/smart-agent/skills/codex-skill-manager.js +0 -75
  479. package/dist/smart-agent/skills/codex-skill-manager.js.map +0 -1
  480. package/dist/smart-agent/skills/filesystem-skill-manager.d.ts +0 -17
  481. package/dist/smart-agent/skills/filesystem-skill-manager.d.ts.map +0 -1
  482. package/dist/smart-agent/skills/filesystem-skill-manager.js +0 -48
  483. package/dist/smart-agent/skills/filesystem-skill-manager.js.map +0 -1
  484. package/dist/smart-agent/skills/filesystem-skill.d.ts +0 -25
  485. package/dist/smart-agent/skills/filesystem-skill.d.ts.map +0 -1
  486. package/dist/smart-agent/skills/filesystem-skill.js +0 -110
  487. package/dist/smart-agent/skills/filesystem-skill.js.map +0 -1
  488. package/dist/smart-agent/skills/index.d.ts +0 -9
  489. package/dist/smart-agent/skills/index.d.ts.map +0 -1
  490. package/dist/smart-agent/skills/index.js +0 -9
  491. package/dist/smart-agent/skills/index.js.map +0 -1
  492. package/dist/smart-agent/skills/skill-utils.d.ts +0 -15
  493. package/dist/smart-agent/skills/skill-utils.d.ts.map +0 -1
  494. package/dist/smart-agent/skills/skill-utils.js +0 -46
  495. package/dist/smart-agent/skills/skill-utils.js.map +0 -1
  496. package/dist/smart-agent/strategies/index.d.ts +0 -4
  497. package/dist/smart-agent/strategies/index.d.ts.map +0 -1
  498. package/dist/smart-agent/strategies/index.js +0 -4
  499. package/dist/smart-agent/strategies/index.js.map +0 -1
  500. package/dist/smart-agent/strategies/lazy-connection-strategy.d.ts +0 -15
  501. package/dist/smart-agent/strategies/lazy-connection-strategy.d.ts.map +0 -1
  502. package/dist/smart-agent/strategies/lazy-connection-strategy.js +0 -82
  503. package/dist/smart-agent/strategies/lazy-connection-strategy.js.map +0 -1
  504. package/dist/smart-agent/strategies/noop-connection-strategy.d.ts +0 -6
  505. package/dist/smart-agent/strategies/noop-connection-strategy.d.ts.map +0 -1
  506. package/dist/smart-agent/strategies/noop-connection-strategy.js +0 -6
  507. package/dist/smart-agent/strategies/noop-connection-strategy.js.map +0 -1
  508. package/dist/smart-agent/strategies/periodic-connection-strategy.d.ts +0 -13
  509. package/dist/smart-agent/strategies/periodic-connection-strategy.d.ts.map +0 -1
  510. package/dist/smart-agent/strategies/periodic-connection-strategy.js +0 -40
  511. package/dist/smart-agent/strategies/periodic-connection-strategy.js.map +0 -1
  512. package/dist/smart-agent/testing/index.d.ts +0 -118
  513. package/dist/smart-agent/testing/index.d.ts.map +0 -1
  514. package/dist/smart-agent/testing/index.js +0 -351
  515. package/dist/smart-agent/testing/index.js.map +0 -1
  516. package/dist/smart-agent/tracer/index.d.ts +0 -3
  517. package/dist/smart-agent/tracer/index.d.ts.map +0 -1
  518. package/dist/smart-agent/tracer/index.js +0 -2
  519. package/dist/smart-agent/tracer/index.js.map +0 -1
  520. package/dist/smart-agent/tracer/noop-tracer.d.ts +0 -5
  521. package/dist/smart-agent/tracer/noop-tracer.d.ts.map +0 -1
  522. package/dist/smart-agent/tracer/noop-tracer.js +0 -16
  523. package/dist/smart-agent/tracer/noop-tracer.js.map +0 -1
  524. package/dist/smart-agent/tracer/types.d.ts +0 -17
  525. package/dist/smart-agent/tracer/types.d.ts.map +0 -1
  526. package/dist/smart-agent/tracer/types.js +0 -2
  527. package/dist/smart-agent/tracer/types.js.map +0 -1
  528. package/dist/smart-agent/utils/external-tools-normalizer.d.ts +0 -15
  529. package/dist/smart-agent/utils/external-tools-normalizer.d.ts.map +0 -1
  530. package/dist/smart-agent/utils/external-tools-normalizer.js +0 -146
  531. package/dist/smart-agent/utils/external-tools-normalizer.js.map +0 -1
  532. package/dist/smart-agent/utils/lazy.d.ts +0 -51
  533. package/dist/smart-agent/utils/lazy.d.ts.map +0 -1
  534. package/dist/smart-agent/utils/lazy.js +0 -127
  535. package/dist/smart-agent/utils/lazy.js.map +0 -1
  536. package/dist/smart-agent/utils/parse-frontmatter.d.ts +0 -15
  537. package/dist/smart-agent/utils/parse-frontmatter.d.ts.map +0 -1
  538. package/dist/smart-agent/utils/parse-frontmatter.js +0 -22
  539. package/dist/smart-agent/utils/parse-frontmatter.js.map +0 -1
  540. package/dist/smart-agent/utils/tool-call-deltas.d.ts +0 -4
  541. package/dist/smart-agent/utils/tool-call-deltas.d.ts.map +0 -1
  542. package/dist/smart-agent/utils/tool-call-deltas.js +0 -25
  543. package/dist/smart-agent/utils/tool-call-deltas.js.map +0 -1
  544. package/dist/smart-agent/validator/index.d.ts +0 -3
  545. package/dist/smart-agent/validator/index.d.ts.map +0 -1
  546. package/dist/smart-agent/validator/index.js +0 -2
  547. package/dist/smart-agent/validator/index.js.map +0 -1
  548. package/dist/smart-agent/validator/noop-validator.d.ts +0 -6
  549. package/dist/smart-agent/validator/noop-validator.d.ts.map +0 -1
  550. package/dist/smart-agent/validator/noop-validator.js +0 -6
  551. package/dist/smart-agent/validator/noop-validator.js.map +0 -1
  552. package/dist/smart-agent/validator/types.d.ts +0 -17
  553. package/dist/smart-agent/validator/types.d.ts.map +0 -1
  554. package/dist/smart-agent/validator/types.js +0 -8
  555. package/dist/smart-agent/validator/types.js.map +0 -1
@@ -1,1534 +0,0 @@
1
- import { randomUUID } from 'node:crypto';
2
- import { getStreamToolCallName, NoopQueryExpander, NoopToolCache, normalizeExternalTools, OrchestratorError, QueryEmbedding, StreamingLlmCallStrategy, TextOnlyEmbedding, toToolCallDelta, } from '@mcp-abap-adt/llm-agent';
3
- import { LlmClassifier } from './classifier/llm-classifier.js';
4
- export { OrchestratorError, } from '@mcp-abap-adt/llm-agent';
5
- import { NoopRequestLogger } from './logger/noop-request-logger.js';
6
- import { NoopMetrics } from './metrics/noop-metrics.js';
7
- import { fireInternalToolsAsync } from './policy/mixed-tool-call-handler.js';
8
- import { PendingToolResultsRegistry } from './policy/pending-tool-results-registry.js';
9
- import { isToolContextUnavailableError, ToolAvailabilityRegistry, } from './policy/tool-availability-registry.js';
10
- import { NoopReranker } from './reranker/noop-reranker.js';
11
- import { NoopSessionManager } from './session/noop-session-manager.js';
12
- import { NoopTracer } from './tracer/noop-tracer.js';
13
- import { NoopValidator } from './validator/noop-validator.js';
14
- function mergeSignals(...signals) {
15
- const ctrl = new AbortController();
16
- for (const s of signals) {
17
- if (!s)
18
- continue;
19
- if (s.aborted) {
20
- ctrl.abort(s.reason);
21
- return ctrl;
22
- }
23
- s.addEventListener('abort', () => ctrl.abort(s.reason), { once: true });
24
- }
25
- return ctrl;
26
- }
27
- function createTimeoutSignal(ms) {
28
- const ctrl = new AbortController();
29
- const id = setTimeout(() => ctrl.abort(new Error('Timeout')), ms);
30
- return { signal: ctrl.signal, clear: () => clearTimeout(id) };
31
- }
32
- export class SmartAgent {
33
- deps;
34
- config;
35
- toolAvailabilityRegistry;
36
- tracer;
37
- metrics;
38
- reranker;
39
- queryExpander;
40
- toolCache;
41
- outputValidator;
42
- sessionManager;
43
- pendingToolResults;
44
- requestLogger;
45
- defaultLlmCallStrategy;
46
- _activeClients;
47
- _mainLlm;
48
- _classifierLlm;
49
- _helperLlm;
50
- _classifier;
51
- constructor(deps, config) {
52
- this.deps = deps;
53
- this.config = config;
54
- this.toolAvailabilityRegistry = new ToolAvailabilityRegistry(this.config.toolUnavailableTtlMs);
55
- this.tracer = deps.tracer ?? new NoopTracer();
56
- this.metrics = deps.metrics ?? new NoopMetrics();
57
- this.reranker = deps.reranker ?? new NoopReranker();
58
- this.queryExpander = deps.queryExpander ?? new NoopQueryExpander();
59
- this.toolCache = deps.toolCache ?? new NoopToolCache();
60
- this.outputValidator = deps.outputValidator ?? new NoopValidator();
61
- this.sessionManager = deps.sessionManager ?? new NoopSessionManager();
62
- this.pendingToolResults = new PendingToolResultsRegistry();
63
- this.requestLogger = deps.requestLogger ?? new NoopRequestLogger();
64
- this.defaultLlmCallStrategy =
65
- deps.llmCallStrategy ?? new StreamingLlmCallStrategy();
66
- this._activeClients = [...deps.mcpClients];
67
- this._mainLlm = deps.mainLlm;
68
- this._helperLlm = deps.helperLlm;
69
- this._classifier = deps.classifier;
70
- this._classifierLlm = deps.classifierLlm;
71
- }
72
- /** Current main LLM instance. Use this for direct LLM calls that should respect hot-swap. */
73
- get currentMainLlm() {
74
- return this._mainLlm;
75
- }
76
- async _resolveActiveClients(opts) {
77
- if (!this.deps.connectionStrategy)
78
- return;
79
- const result = await this.deps.connectionStrategy.resolve(this._activeClients, opts);
80
- this._activeClients = result.clients;
81
- if (result.toolsChanged) {
82
- await this._revectorizeTools(result.clients, opts);
83
- }
84
- }
85
- async _revectorizeTools(clients, opts) {
86
- const toolsRag = this.deps.ragStores.tools ?? Object.values(this.deps.ragStores)[0];
87
- if (!toolsRag)
88
- return;
89
- for (const client of clients) {
90
- const result = await client.listTools(opts);
91
- if (!result.ok)
92
- continue;
93
- for (const tool of result.value) {
94
- const text = `Tool: ${tool.name} — ${tool.description}`;
95
- await toolsRag.writer?.()?.upsertRaw(`tool:${tool.name}`, text, {});
96
- }
97
- }
98
- }
99
- /** Apply a partial config update at runtime (hot-reload). */
100
- applyConfigUpdate(update) {
101
- this.config = { ...this.config, ...update };
102
- }
103
- /**
104
- * Replace active LLM instances at runtime.
105
- * Changes apply to new requests only — in-flight requests continue
106
- * using the dependency snapshot captured at request start.
107
- * Reconfigured LLMs do not inherit builder-time wrappers (retry, circuit breaker, rate limiter).
108
- *
109
- * **Important:** This is the only supported way to hot-swap LLMs.
110
- * Direct mutation of `deps` fields has no effect — SmartAgent copies
111
- * deps into private fields at construction time.
112
- *
113
- * @example
114
- * ```typescript
115
- * const newLlm = makeLlm({ provider: 'openai', model: 'gpt-5.4-pro', ... });
116
- * handle.agent.reconfigure({ mainLlm: newLlm });
117
- * // handle.chat() and handle.streamChat() now use the new LLM
118
- * ```
119
- */
120
- reconfigure(update) {
121
- if (update.mainLlm) {
122
- this._mainLlm = update.mainLlm;
123
- }
124
- if (update.helperLlm) {
125
- this._helperLlm = update.helperLlm;
126
- }
127
- if (update.classifierLlm) {
128
- this._classifierLlm = update.classifierLlm;
129
- this._classifier = new LlmClassifier(update.classifierLlm, this.deps.classifierConfig, this.requestLogger);
130
- }
131
- }
132
- /**
133
- * Add a custom RAG store at runtime. Takes effect on the next request.
134
- * Built-in store names ('tools', 'history') cannot be overwritten.
135
- *
136
- * @param options.translateQuery — when true, the pipeline translates the
137
- * query to English before searching this store (useful for stores with
138
- * English-only content like MCP tool descriptions).
139
- */
140
- addRagStore(name, store, options) {
141
- if (name === 'tools' || name === 'history') {
142
- throw new Error(`Cannot overwrite built-in RAG store "${name}" via addRagStore()`);
143
- }
144
- if (this.deps.ragRegistry) {
145
- // Route through registry so the ragStores projection (and any listeners)
146
- // see the change.
147
- if (this.deps.ragRegistry.get(name)) {
148
- this.deps.ragRegistry.unregister(name);
149
- }
150
- this.deps.ragRegistry.register(name, store, undefined, {
151
- displayName: name,
152
- scope: 'global',
153
- });
154
- }
155
- else {
156
- // Fallback for consumers that built SmartAgentDeps without a registry.
157
- this.deps.ragStores[name] = store;
158
- }
159
- if (options?.translateQuery) {
160
- if (!this.deps.translateQueryStores) {
161
- this.deps.translateQueryStores = new Set();
162
- }
163
- this.deps.translateQueryStores.add(name);
164
- }
165
- this.deps.pipeline?.rebuildStages?.();
166
- }
167
- /**
168
- * Remove a custom RAG store at runtime. Takes effect on the next request.
169
- * Built-in store names ('tools', 'history') cannot be removed.
170
- */
171
- removeRagStore(name) {
172
- if (name === 'tools' || name === 'history') {
173
- throw new Error(`Cannot remove built-in RAG store "${name}" via removeRagStore()`);
174
- }
175
- if (this.deps.ragRegistry) {
176
- this.deps.ragRegistry.unregister(name);
177
- }
178
- else {
179
- delete this.deps.ragStores[name];
180
- }
181
- this.deps.translateQueryStores?.delete(name);
182
- this.deps.pipeline?.rebuildStages?.();
183
- }
184
- /**
185
- * Close a session: remove session-scoped RAG collections for the given
186
- * sessionId and flush session-scoped history memory.
187
- * Errors from registry cleanup are logged but not thrown — best-effort.
188
- */
189
- async closeSession(sessionId) {
190
- if (this.deps.ragRegistry) {
191
- const res = await this.deps.ragRegistry.closeSession(sessionId);
192
- if (!res.ok) {
193
- this.deps.logger?.log({
194
- type: 'warning',
195
- traceId: 'close_session',
196
- message: `closeSession(${sessionId}) failed: ${res.error.message}`,
197
- });
198
- }
199
- }
200
- this.deps.historyMemory?.clear(sessionId);
201
- }
202
- /** Returns the model identifiers of the currently active LLM instances. */
203
- getActiveConfig() {
204
- return {
205
- mainModel: this._mainLlm.model,
206
- classifierModel: this._classifierLlm?.model,
207
- helperModel: this._helperLlm?.model,
208
- };
209
- }
210
- /** Returns whitelisted runtime-safe agent config fields (for HTTP DTO). */
211
- getAgentConfig() {
212
- return {
213
- maxIterations: this.config.maxIterations,
214
- maxToolCalls: this.config.maxToolCalls,
215
- ragQueryK: this.config.ragQueryK,
216
- toolUnavailableTtlMs: this.config.toolUnavailableTtlMs,
217
- showReasoning: this.config.showReasoning,
218
- historyAutoSummarizeLimit: this.config.historyAutoSummarizeLimit,
219
- classificationEnabled: this.config.classificationEnabled,
220
- };
221
- }
222
- async healthCheck(options) {
223
- const HEALTH_TIMEOUT_MS = this.config.healthTimeoutMs ?? 5_000;
224
- const { signal: timeoutSignal, clear: clearTimeout_ } = createTimeoutSignal(HEALTH_TIMEOUT_MS);
225
- const merged = mergeSignals(timeoutSignal, options?.signal);
226
- const healthOptions = {
227
- ...options,
228
- signal: merged.signal,
229
- maxTokens: 1,
230
- };
231
- const results = {
232
- llm: false,
233
- rag: false,
234
- mcp: [],
235
- };
236
- try {
237
- if (this._mainLlm.healthCheck) {
238
- const hc = await this._mainLlm.healthCheck(healthOptions);
239
- results.llm = hc.ok && hc.value;
240
- }
241
- else {
242
- // Fallback for ILlm implementations without healthCheck
243
- const llmRes = await this._mainLlm.chat([{ role: 'user', content: 'ping' }], [], healthOptions);
244
- results.llm = llmRes.ok;
245
- }
246
- }
247
- catch {
248
- results.llm = false;
249
- }
250
- try {
251
- const firstStore = Object.values(this.deps.ragStores)[0];
252
- const ragRes = firstStore
253
- ? await firstStore.healthCheck(healthOptions)
254
- : { ok: true, value: undefined };
255
- results.rag = ragRes.ok;
256
- }
257
- catch {
258
- results.rag = false;
259
- }
260
- try {
261
- const mcpChecks = await Promise.all(this._activeClients.map(async (client) => {
262
- try {
263
- if (client.healthCheck) {
264
- const hc = await client.healthCheck(healthOptions);
265
- return {
266
- name: 'mcp-client',
267
- ok: hc.ok,
268
- error: hc.ok || !hc.error
269
- ? undefined
270
- : hc.error instanceof Error
271
- ? hc.error.message
272
- : String(hc.error),
273
- };
274
- }
275
- // Fallback for IMcpClient implementations without healthCheck
276
- const tools = await client.listTools(healthOptions);
277
- return {
278
- name: 'mcp-client',
279
- ok: tools.ok,
280
- error: tools.ok || !tools.error
281
- ? undefined
282
- : tools.error instanceof Error
283
- ? tools.error.message
284
- : String(tools.error),
285
- };
286
- }
287
- catch (err) {
288
- return {
289
- name: 'mcp-client',
290
- ok: false,
291
- error: err instanceof Error ? err.message : String(err),
292
- };
293
- }
294
- }));
295
- results.mcp = mcpChecks;
296
- }
297
- catch {
298
- // AbortSignal timeout — leave mcp as empty
299
- }
300
- clearTimeout_();
301
- return { ok: true, value: results };
302
- }
303
- async process(textOrMessages, options) {
304
- let content = '';
305
- const totalUsage = { promptTokens: 0, completionTokens: 0, totalTokens: 0 };
306
- let stopReason = 'stop';
307
- const collectedToolCalls = [];
308
- // Map streaming index → position in collectedToolCalls for delta correlation
309
- const indexToPosition = new Map();
310
- for await (const chunk of this.streamProcess(textOrMessages, options)) {
311
- if (!chunk.ok)
312
- return chunk;
313
- if (chunk.value.content)
314
- content += chunk.value.content;
315
- if (chunk.value.toolCalls) {
316
- for (const tc of chunk.value.toolCalls) {
317
- const delta = toToolCallDelta(tc, collectedToolCalls.length);
318
- // Try to find existing entry by index first (streaming deltas),
319
- // then by id (non-streaming / first delta with id).
320
- const posByIndex = indexToPosition.get(delta.index);
321
- const existing = posByIndex !== undefined
322
- ? collectedToolCalls[posByIndex]
323
- : delta.id
324
- ? collectedToolCalls.find((c) => c.id === delta.id)
325
- : undefined;
326
- if (existing) {
327
- if (delta.arguments)
328
- existing.function.arguments += delta.arguments;
329
- }
330
- else if (delta.name) {
331
- const pos = collectedToolCalls.length;
332
- collectedToolCalls.push({
333
- id: delta.id || '',
334
- type: 'function',
335
- function: {
336
- name: delta.name,
337
- arguments: delta.arguments || '',
338
- },
339
- });
340
- indexToPosition.set(delta.index, pos);
341
- }
342
- }
343
- }
344
- if (chunk.value.finishReason === 'tool_calls') {
345
- stopReason = 'tool_calls';
346
- }
347
- if (chunk.value.usage) {
348
- totalUsage.promptTokens += chunk.value.usage.promptTokens;
349
- totalUsage.completionTokens += chunk.value.usage.completionTokens;
350
- totalUsage.totalTokens += chunk.value.usage.totalTokens;
351
- if (chunk.value.usage.models) {
352
- totalUsage.models = chunk.value.usage.models;
353
- }
354
- }
355
- }
356
- return {
357
- ok: true,
358
- value: {
359
- content,
360
- iterations: 1,
361
- toolCallCount: collectedToolCalls.length,
362
- stopReason,
363
- ...(collectedToolCalls.length > 0
364
- ? { toolCalls: collectedToolCalls }
365
- : {}),
366
- usage: totalUsage,
367
- },
368
- };
369
- }
370
- async *streamProcess(textOrMessages, options) {
371
- if (this.config.smartAgentEnabled === false) {
372
- yield {
373
- ok: false,
374
- error: new OrchestratorError('SmartAgent is disabled', 'DISABLED'),
375
- };
376
- return;
377
- }
378
- this.metrics.requestCount.add();
379
- const requestStart = Date.now();
380
- const traceId = options?.trace?.traceId ?? randomUUID();
381
- const rootSpan = this.tracer.startSpan('smart_agent.process', {
382
- traceId,
383
- attributes: { 'smart_agent.mode': this.config.mode || 'smart' },
384
- });
385
- let timeoutCleanup;
386
- let opts = options;
387
- if (this.config.timeoutMs) {
388
- const { signal, clear } = createTimeoutSignal(this.config.timeoutMs);
389
- timeoutCleanup = clear;
390
- const merged = mergeSignals(options?.signal, signal);
391
- opts = { ...options, signal: merged.signal };
392
- }
393
- const mode = this.config.mode || 'smart';
394
- // Per-request client adapter detection from system prompt
395
- let detectedAdapter;
396
- const messages = typeof textOrMessages === 'string' ? undefined : textOrMessages;
397
- if (messages && this.deps.clientAdapters?.length) {
398
- const systemMsg = messages.find((m) => m.role === 'system');
399
- if (systemMsg?.content) {
400
- detectedAdapter = this.deps.clientAdapters.find((a) => a.detect(typeof systemMsg.content === 'string' ? systemMsg.content : ''));
401
- }
402
- }
403
- const sessionId = options?.sessionId ?? 'default';
404
- const externalTools = normalizeExternalTools(options?.externalTools);
405
- opts?.sessionLogger?.logStep('external_tools_normalized', {
406
- rawCount: options?.externalTools?.length ?? 0,
407
- normalizedCount: externalTools.length,
408
- normalizedNames: externalTools.map((t) => t.name),
409
- });
410
- opts?.sessionLogger?.logStep('pipeline_start', { mode, textOrMessages });
411
- this.requestLogger.startRequest();
412
- try {
413
- if (mode === 'pass') {
414
- const messages = typeof textOrMessages === 'string'
415
- ? [{ role: 'user', content: textOrMessages }]
416
- : textOrMessages;
417
- opts?.sessionLogger?.logStep('client_request', { textOrMessages });
418
- const stream = this._mainLlm.streamChat(messages, externalTools, opts);
419
- let passContent = '';
420
- const passToolCalls = [];
421
- for await (const chunk of stream) {
422
- if (chunk.ok) {
423
- if (chunk.value.reset) {
424
- passContent = '';
425
- passToolCalls.length = 0;
426
- continue;
427
- }
428
- if (chunk.value.content)
429
- passContent += chunk.value.content;
430
- if (chunk.value.toolCalls)
431
- passToolCalls.push(...chunk.value.toolCalls);
432
- }
433
- yield chunk;
434
- }
435
- opts?.sessionLogger?.logStep('llm_response_pass', {
436
- content: passContent,
437
- toolCalls: passToolCalls.length > 0 ? passToolCalls : undefined,
438
- });
439
- rootSpan.setStatus('ok');
440
- rootSpan.end();
441
- return;
442
- }
443
- // Pipeline path (when configured via Builder)
444
- if (this.deps.pipeline) {
445
- const stream = this._runStructuredPipeline(textOrMessages, externalTools, opts, rootSpan, sessionId);
446
- for await (const chunk of stream)
447
- yield chunk;
448
- rootSpan.setStatus('ok');
449
- rootSpan.end();
450
- return;
451
- }
452
- // 1. Unified Preparation (default hardcoded flow)
453
- const initResult = await this._preparePipeline(textOrMessages, opts, rootSpan);
454
- if (!initResult.ok) {
455
- rootSpan.setStatus('error', initResult.error.message);
456
- rootSpan.end();
457
- yield initResult;
458
- return;
459
- }
460
- let { processedHistory } = initResult.value;
461
- const { subprompts, toolClientMap } = initResult.value;
462
- // Token budget check — summarize if over budget
463
- if (this.sessionManager.isOverBudget()) {
464
- const sumResult = await this._summarizeHistory(processedHistory, opts);
465
- if (sumResult.ok)
466
- processedHistory = sumResult.value;
467
- this.sessionManager.reset();
468
- }
469
- // 2. Decide context and tools for the WHOLE request
470
- await this._resolveActiveClients(opts);
471
- const actions = subprompts.filter((sp) => sp.type === 'action');
472
- const hasActions = actions.length > 0;
473
- const hasMcpClients = this._activeClients.length > 0;
474
- const hasRagStores = Object.keys(this.deps.ragStores).length > 0;
475
- const shouldRetrieve = mode === 'hard' || (hasActions && (hasMcpClients || hasRagStores));
476
- let finalTools = [];
477
- let retrieved = {
478
- ragResults: {},
479
- tools: [],
480
- };
481
- let skillContent = '';
482
- if (shouldRetrieve) {
483
- // Collect all action texts for RAG
484
- const combinedActionText = actions.map((a) => a.text).join(' ');
485
- // Translate + expand once (only used for stores in translateQueryStores)
486
- const translateStores = this.deps.translateQueryStores;
487
- let translatedText;
488
- if (translateStores && translateStores.size > 0) {
489
- translatedText = await this._toEnglishForRag(combinedActionText, opts);
490
- if (this.config.queryExpansionEnabled) {
491
- const expandResult = await this.queryExpander.expand(translatedText, opts);
492
- if (expandResult.ok)
493
- translatedText = expandResult.value;
494
- }
495
- }
496
- const k = this.config.ragQueryK ?? 10;
497
- const ragSpan = this.tracer.startSpan('smart_agent.rag_query', {
498
- parent: rootSpan,
499
- attributes: { 'rag.k': k },
500
- });
501
- const storeEntries = Object.entries(this.deps.ragStores);
502
- // Build per-store embedding: translated for translateQuery stores, original for others
503
- const mkEmbed = (text) => this.deps.embedder
504
- ? new QueryEmbedding(text, this.deps.embedder, opts)
505
- : new TextOnlyEmbedding(text);
506
- // Cache embeddings to avoid duplicate embed calls
507
- const originalEmbedding = mkEmbed(combinedActionText);
508
- const translatedEmbedding = translatedText && translatedText !== combinedActionText
509
- ? mkEmbed(translatedText)
510
- : originalEmbedding;
511
- const ragQueryResults = await Promise.all(storeEntries.map(([name, store]) => {
512
- const emb = translateStores?.has(name) && translatedText
513
- ? translatedEmbedding
514
- : originalEmbedding;
515
- return store.query(emb, k, opts).then((r) => ({ name, result: r }));
516
- }));
517
- ragSpan.end();
518
- const ragResultsMap = {};
519
- for (const { name, result: r } of ragQueryResults) {
520
- ragResultsMap[name] = r.ok ? r.value : [];
521
- this.metrics.ragQueryCount.add(1, {
522
- store: name,
523
- hit: String(r.ok && r.value.length > 0),
524
- });
525
- }
526
- // Rerank results
527
- // Rerank all stores in parallel, using matching query text per store
528
- const rerankedEntries = await Promise.all(Object.entries(ragResultsMap).map(async ([name, results]) => {
529
- if (results.length > 0) {
530
- const rerankText = translateStores?.has(name) && translatedText
531
- ? translatedText
532
- : combinedActionText;
533
- const rr = await this.reranker.rerank(rerankText, results, opts);
534
- return { name, results: rr.ok ? rr.value : results };
535
- }
536
- return { name, results };
537
- }));
538
- const rerankedMap = {};
539
- for (const { name, results } of rerankedEntries) {
540
- rerankedMap[name] = results;
541
- }
542
- const { tools: mcpTools } = await this._listAllTools(opts);
543
- // Collect all RAG results for tool discovery
544
- const allRagResults = Object.values(rerankedMap).flat();
545
- // Log RAG results with scores for diagnostics
546
- for (const [storeName, results] of Object.entries(rerankedMap)) {
547
- const logQuery = translateStores?.has(storeName) && translatedText
548
- ? translatedText
549
- : combinedActionText;
550
- opts?.sessionLogger?.logStep(`rag_query_${storeName}`, {
551
- query: logQuery.slice(0, 200),
552
- k,
553
- resultCount: results.length,
554
- results: results.map((r) => ({
555
- id: r.metadata.id,
556
- score: r.score,
557
- text: r.text.slice(0, 120),
558
- })),
559
- });
560
- }
561
- const ragToolNames = new Set(allRagResults
562
- .map((r) => r.metadata.id)
563
- .filter((id) => id?.startsWith('tool:'))
564
- .map((id) => id.slice(5).replace(/:.*$/, '')));
565
- const selectedMcpTools = ragToolNames.size > 0
566
- ? mcpTools.filter((t) => ragToolNames.has(t.name))
567
- : mode === 'hard'
568
- ? mcpTools
569
- : [];
570
- // Log tool selection diagnostics
571
- opts?.sessionLogger?.logStep('tools_selected', {
572
- totalMcp: mcpTools.length,
573
- ragMatchedTools: [...ragToolNames],
574
- selectedCount: selectedMcpTools.length + externalTools.length,
575
- selectedNames: [
576
- ...selectedMcpTools.map((t) => t.name),
577
- ...externalTools.map((t) => t.name),
578
- ],
579
- });
580
- retrieved = {
581
- ragResults: rerankedMap,
582
- tools: selectedMcpTools,
583
- };
584
- finalTools =
585
- mode === 'hard'
586
- ? selectedMcpTools
587
- : [...selectedMcpTools, ...externalTools];
588
- opts?.sessionLogger?.logStep('external_tools_merge', {
589
- mode,
590
- mcpCount: selectedMcpTools.length,
591
- externalCount: externalTools.length,
592
- externalNames: externalTools.map((t) => t.name),
593
- finalCount: finalTools.length,
594
- });
595
- // Skill injection (when enabled and skillManager configured)
596
- if (this.config.skillInjectionEnabled !== false &&
597
- this.deps.skillManager) {
598
- const ragSkillNames = new Set(allRagResults
599
- .map((r) => r.metadata.id)
600
- .filter((id) => id?.startsWith('skill:'))
601
- .map((id) => id.slice(6)));
602
- // Fallback: dedicated RAG query when no skill:* in existing results
603
- if (ragSkillNames.size === 0) {
604
- const k = this.config.ragQueryK ?? 15;
605
- const storeEntries = Object.entries(this.deps.ragStores);
606
- const fallbackResults = await Promise.all(storeEntries.map(([name, store]) => {
607
- const text = translateStores?.has(name) && translatedText
608
- ? translatedText
609
- : combinedActionText;
610
- const emb = this.deps.embedder
611
- ? new QueryEmbedding(text, this.deps.embedder, opts)
612
- : new TextOnlyEmbedding(text);
613
- return store.query(emb, k, opts);
614
- }));
615
- for (const result of fallbackResults) {
616
- if (result.ok) {
617
- for (const r of result.value) {
618
- const id = r.metadata.id;
619
- if (id?.startsWith('skill:')) {
620
- ragSkillNames.add(id.slice(6));
621
- }
622
- }
623
- }
624
- }
625
- if (ragSkillNames.size > 0) {
626
- opts?.sessionLogger?.logStep('skill_select_rag_fallback', {
627
- query: combinedActionText.slice(0, 200),
628
- k,
629
- matchedSkills: [...ragSkillNames],
630
- });
631
- }
632
- }
633
- const allSkillsResult = await this.deps.skillManager.listSkills(opts);
634
- if (allSkillsResult.ok) {
635
- const allSkills = allSkillsResult.value;
636
- const matched = ragSkillNames.size > 0
637
- ? allSkills.filter((s) => ragSkillNames.has(s.name))
638
- : mode === 'hard'
639
- ? allSkills
640
- : [];
641
- const contentParts = [];
642
- for (const skill of matched) {
643
- const contentResult = await skill.getContent(undefined, opts);
644
- if (contentResult.ok && contentResult.value) {
645
- contentParts.push(`### Skill: ${skill.name}\n${contentResult.value}`);
646
- }
647
- }
648
- skillContent = contentParts.join('\n\n');
649
- opts?.sessionLogger?.logStep('skills_selected', {
650
- totalSkills: allSkills.length,
651
- ragMatchedSkills: [...ragSkillNames],
652
- selectedCount: matched.length,
653
- selectedNames: matched.map((s) => s.name),
654
- });
655
- }
656
- }
657
- }
658
- else {
659
- // If we're here, mode is definitely 'smart' (not 'hard' or 'pass')
660
- finalTools = externalTools;
661
- }
662
- const filteredTools = this.toolAvailabilityRegistry.filterTools(sessionId, finalTools);
663
- finalTools = filteredTools.allowed;
664
- if (filteredTools.blocked.length > 0) {
665
- opts?.sessionLogger?.logStep('active_tools_filtered_by_registry', {
666
- blocked: filteredTools.blocked,
667
- });
668
- }
669
- // 3. Assemble Context once
670
- const mainAction = actions.length > 1
671
- ? {
672
- type: 'action',
673
- text: actions.map((a) => a.text).join('\n'),
674
- context: actions.find((a) => a.context)?.context,
675
- dependency: 'independent',
676
- }
677
- : actions.length === 1
678
- ? actions[0]
679
- : subprompts.find((sp) => sp.type === 'chat') || subprompts[0];
680
- if (actions.length > 1) {
681
- opts?.sessionLogger?.logStep('actions_merged', {
682
- count: actions.length,
683
- actions: actions.map((a) => ({
684
- text: a.text,
685
- dependency: a.dependency,
686
- })),
687
- });
688
- }
689
- const assembleSpan = this.tracer.startSpan('smart_agent.assemble', {
690
- parent: rootSpan,
691
- });
692
- const assembleResult = await this.deps.assembler.assemble(mainAction, retrieved, processedHistory, opts);
693
- if (!assembleResult.ok) {
694
- assembleSpan.setStatus('error', assembleResult.error.message);
695
- assembleSpan.end();
696
- rootSpan.setStatus('error', assembleResult.error.message);
697
- rootSpan.end();
698
- yield {
699
- ok: false,
700
- error: new OrchestratorError(assembleResult.error.message, 'ASSEMBLER_ERROR'),
701
- };
702
- return;
703
- }
704
- assembleSpan.setStatus('ok');
705
- assembleSpan.end();
706
- // Inject skill content into system message (post-assembly)
707
- if (skillContent) {
708
- const sysMsg = assembleResult.value.find((m) => m.role === 'system');
709
- if (sysMsg) {
710
- sysMsg.content += `\n\n## Active Skills\n${skillContent}`;
711
- }
712
- else {
713
- assembleResult.value.unshift({
714
- role: 'system',
715
- content: `## Active Skills\n${skillContent}`,
716
- });
717
- }
718
- }
719
- opts?.sessionLogger?.logStep(`final_context_assembled`, {
720
- messages: assembleResult.value,
721
- tools: finalTools.map((t) => t.name),
722
- });
723
- // 4. Single Streaming Loop
724
- const stream = this._runStreamingToolLoop(mainAction, retrieved, assembleResult.value, toolClientMap, opts, rootSpan, sessionId, mode === 'hard' ? [] : externalTools, finalTools, detectedAdapter);
725
- for await (const chunk of stream)
726
- yield chunk;
727
- rootSpan.setStatus('ok');
728
- }
729
- finally {
730
- this.requestLogger.endRequest();
731
- rootSpan.end();
732
- timeoutCleanup?.();
733
- this.metrics.requestLatency.record(Date.now() - requestStart);
734
- }
735
- }
736
- async _preparePipeline(textOrMessages, opts, parentSpan) {
737
- opts?.sessionLogger?.logStep('client_request', { textOrMessages });
738
- const text = typeof textOrMessages === 'string'
739
- ? textOrMessages
740
- : (textOrMessages.filter((m) => m.role === 'user').slice(-1)[0]
741
- ?.content ?? '');
742
- const history = typeof textOrMessages === 'string' ? [] : textOrMessages;
743
- let processedHistory = history;
744
- const summarizeLimit = this.config.historyAutoSummarizeLimit ?? 10;
745
- if (this._helperLlm && history.length > summarizeLimit) {
746
- const res = await this._summarizeHistory(history, opts);
747
- if (res.ok)
748
- processedHistory = res.value;
749
- }
750
- let subprompts;
751
- if (this.config.classificationEnabled === false) {
752
- // Skip classification — treat entire input as a single action
753
- subprompts = [
754
- { type: 'action', text, dependency: 'independent' },
755
- ];
756
- opts?.sessionLogger?.logStep('classification_skipped', { text });
757
- }
758
- else {
759
- const classifySpan = this.tracer.startSpan('smart_agent.classify', {
760
- parent: parentSpan,
761
- });
762
- const classifyResult = await this._classifier.classify(text, opts);
763
- if (!classifyResult.ok) {
764
- classifySpan.setStatus('error', classifyResult.error.message);
765
- classifySpan.end();
766
- return {
767
- ok: false,
768
- error: new OrchestratorError(classifyResult.error.message, 'CLASSIFIER_ERROR'),
769
- };
770
- }
771
- classifySpan.setStatus('ok');
772
- classifySpan.end();
773
- opts?.sessionLogger?.logStep('classifier_response', {
774
- subprompts: classifyResult.value,
775
- });
776
- subprompts = classifyResult.value;
777
- }
778
- for (const sp of subprompts) {
779
- this.metrics.classifierIntentCount.add(1, { intent: sp.type });
780
- }
781
- const { toolClientMap } = await this._listAllTools(opts);
782
- return { ok: true, value: { subprompts, processedHistory, toolClientMap } };
783
- }
784
- async *_runStreamingToolLoop(_action, _retrieved, initialMessages, toolClientMap, opts, parentSpan, sessionId, externalTools, activeTools, clientAdapter) {
785
- const toolLoopSpan = this.tracer.startSpan('smart_agent.tool_loop', {
786
- parent: parentSpan,
787
- });
788
- let toolCallCount = 0;
789
- let messages = initialMessages;
790
- const usage = { promptTokens: 0, completionTokens: 0, totalTokens: 0 };
791
- const externalToolNames = new Set(externalTools.map((t) => t.name));
792
- const timingLog = [];
793
- const loopStart = Date.now();
794
- let currentTools = activeTools;
795
- // Inject tool priority instruction when external tools are present
796
- if (externalTools.length > 0) {
797
- const systemIdx = messages.findIndex((m) => m.role === 'system');
798
- if (systemIdx >= 0) {
799
- const sys = messages[systemIdx];
800
- messages = [...messages];
801
- messages[systemIdx] = {
802
- ...sys,
803
- content: `${sys.content}\n\nIMPORTANT: You have internal tools and client-provided tools (marked [client-provided] in their description). Always prefer internal tools when they can accomplish the task. Use client-provided tools only when no internal tool can do the job.`,
804
- };
805
- }
806
- }
807
- // Inject pending internal tool results from previous mixed-call request
808
- if (this.pendingToolResults.has(sessionId)) {
809
- const pending = await this.pendingToolResults.consume(sessionId);
810
- if (pending) {
811
- messages = [
812
- ...messages,
813
- pending.assistantMessage,
814
- ...pending.results.map((r) => ({
815
- role: 'tool',
816
- content: r.text,
817
- tool_call_id: r.toolCallId,
818
- })),
819
- ];
820
- opts?.sessionLogger?.logStep('pending_tool_results_injected', {
821
- toolNames: pending.results.map((r) => r.toolName),
822
- });
823
- }
824
- }
825
- for (let iteration = 0;; iteration++) {
826
- let iterationBuffer = '';
827
- if (opts?.signal?.aborted) {
828
- toolLoopSpan.setStatus('error', 'Aborted');
829
- toolLoopSpan.end();
830
- yield { ok: false, error: new OrchestratorError('Aborted', 'ABORTED') };
831
- return;
832
- }
833
- if (iteration >= this.config.maxIterations) {
834
- timingLog.push({ phase: 'total', duration: Date.now() - loopStart });
835
- toolLoopSpan.addEvent('iteration_limit_reached');
836
- toolLoopSpan.end();
837
- yield {
838
- ok: true,
839
- value: {
840
- content: '',
841
- finishReason: 'length',
842
- usage: {
843
- ...usage,
844
- models: this.requestLogger.getSummary().byModel,
845
- },
846
- timing: timingLog,
847
- },
848
- };
849
- return;
850
- }
851
- // Refresh MCP tools on each iteration (when enabled)
852
- if (iteration > 0 && this.config.refreshToolsPerIteration !== false) {
853
- const refreshSpan = this.tracer.startSpan('smart_agent.refresh_tools', {
854
- parent: toolLoopSpan,
855
- attributes: { 'llm.iteration': iteration + 1 },
856
- });
857
- const refreshed = await this._listAllTools(opts);
858
- const prevNames = [...toolClientMap.keys()];
859
- toolClientMap.clear();
860
- for (const [name, client] of refreshed.toolClientMap) {
861
- toolClientMap.set(name, client);
862
- }
863
- currentTools = [...refreshed.tools, ...externalTools];
864
- opts?.sessionLogger?.logStep('tools_refreshed', {
865
- iteration: iteration + 1,
866
- previous: prevNames,
867
- current: currentTools.map((t) => t.name),
868
- });
869
- refreshSpan.end();
870
- }
871
- // Per-iteration RAG tool re-selection (when enabled)
872
- if (iteration > 0 &&
873
- this.config.toolReselectPerIteration &&
874
- this.deps.ragStores?.tools) {
875
- const reselectSpan = this.tracer.startSpan('smart_agent.tool_reselect', {
876
- parent: toolLoopSpan,
877
- attributes: { 'llm.iteration': iteration + 1 },
878
- });
879
- try {
880
- // Extract last tool calls
881
- const lastAssistant = [...messages]
882
- .reverse()
883
- .find((m) => m.role === 'assistant');
884
- const toolCallNames = [];
885
- if (lastAssistant && 'tool_calls' in lastAssistant) {
886
- const tcs = lastAssistant.tool_calls;
887
- if (Array.isArray(tcs)) {
888
- for (const tc of tcs) {
889
- const name = tc?.function?.name || '';
890
- if (name)
891
- toolCallNames.push(name);
892
- }
893
- }
894
- }
895
- // Skip for read-only tools — they rarely need different tools on retry
896
- const readOnlyPrefixes = [
897
- 'Search',
898
- 'Read',
899
- 'Get',
900
- 'List',
901
- 'Describe',
902
- ];
903
- const allReadOnly = toolCallNames.length > 0 &&
904
- toolCallNames.every((n) => readOnlyPrefixes.some((p) => n.startsWith(p)));
905
- if (!allReadOnly) {
906
- // Build context-aware query from error/result context
907
- const lastToolMsg = [...messages]
908
- .reverse()
909
- .find((m) => m.role === 'tool');
910
- const toolResult = typeof lastToolMsg?.content === 'string'
911
- ? lastToolMsg.content.slice(0, 200)
912
- : '';
913
- const isError = toolResult.toLowerCase().includes('error') ||
914
- toolResult.toLowerCase().includes('already exist') ||
915
- toolResult.toLowerCase().includes('failed');
916
- const inputText = _action.text;
917
- let reSelectQuery;
918
- if (toolCallNames.length > 0 && isError) {
919
- const updateHints = toolCallNames
920
- .filter((n) => n.startsWith('Create'))
921
- .map((n) => n.replace(/^Create/, 'Update'))
922
- .join(', ');
923
- const hints = updateHints ? ` Need ${updateHints}.` : '';
924
- reSelectQuery = `${toolCallNames.join(', ')} failed: ${toolResult.slice(0, 150)}.${hints} ${inputText.slice(0, 200)}`;
925
- }
926
- else if (toolCallNames.length > 0) {
927
- reSelectQuery = `After ${toolCallNames.join(', ')}: ${toolResult}\n${inputText.slice(0, 200)}`;
928
- }
929
- else {
930
- reSelectQuery = inputText;
931
- }
932
- // Query tools RAG
933
- const embedding = this.deps.embedder
934
- ? new QueryEmbedding(reSelectQuery, this.deps.embedder, opts)
935
- : new TextOnlyEmbedding(reSelectQuery);
936
- const ragK = this.config.ragQueryK ?? 20;
937
- const ragResult = await this.deps.ragStores.tools.query(embedding, ragK, opts);
938
- if (ragResult.ok && ragResult.value.length > 0) {
939
- const newToolNames = new Set(ragResult.value
940
- .map((r) => r.metadata?.id || '')
941
- .filter((id) => id.startsWith('tool:'))
942
- .map((id) => id.slice(5).replace(/:.*$/, '')));
943
- if (newToolNames.size > 0) {
944
- const refreshed = await this._listAllTools(opts);
945
- const newMcpTools = refreshed.tools.filter((t) => newToolNames.has(t.name));
946
- currentTools = [
947
- ...newMcpTools,
948
- ...externalTools,
949
- ];
950
- opts?.sessionLogger?.logStep('tools_reselected', {
951
- iteration: iteration + 1,
952
- query: reSelectQuery.slice(0, 100),
953
- previousTools: toolCallNames,
954
- newTools: [...newToolNames],
955
- });
956
- }
957
- }
958
- }
959
- else {
960
- opts?.sessionLogger?.logStep('tools_reselect_skipped', {
961
- iteration: iteration + 1,
962
- reason: 'read-only tools only',
963
- tools: toolCallNames,
964
- });
965
- }
966
- }
967
- finally {
968
- reselectSpan.end();
969
- }
970
- }
971
- const filteredForIteration = this.toolAvailabilityRegistry.filterTools(sessionId, currentTools);
972
- currentTools = filteredForIteration.allowed;
973
- if (filteredForIteration.blocked.length > 0) {
974
- opts?.sessionLogger?.logStep('active_tools_filtered_in_iteration', {
975
- iteration: iteration + 1,
976
- blocked: filteredForIteration.blocked,
977
- });
978
- }
979
- opts?.sessionLogger?.logStep(`llm_request_iter_${iteration + 1}`, {
980
- messages,
981
- tools: currentTools,
982
- });
983
- const llmSpan = this.tracer.startSpan('smart_agent.llm_call', {
984
- parent: toolLoopSpan,
985
- attributes: { 'llm.iteration': iteration + 1 },
986
- });
987
- this.metrics.llmCallCount.add();
988
- const llmCallStart = Date.now();
989
- const stream = this.defaultLlmCallStrategy.call(this._mainLlm, messages, currentTools, opts);
990
- let content = '';
991
- let finishReason;
992
- const toolCallsMap = new Map();
993
- // Track which streaming indices belong to external tools so that
994
- // argument-only continuation deltas (no name field) are forwarded too.
995
- const externalToolIndices = new Set();
996
- for await (const chunkResult of stream) {
997
- if (!chunkResult.ok) {
998
- llmSpan.setStatus('error', chunkResult.error.message);
999
- llmSpan.end();
1000
- toolLoopSpan.setStatus('error', chunkResult.error.message);
1001
- toolLoopSpan.end();
1002
- yield {
1003
- ok: false,
1004
- error: new OrchestratorError(chunkResult.error.message, 'LLM_ERROR'),
1005
- };
1006
- return;
1007
- }
1008
- const chunk = chunkResult.value;
1009
- // Mid-stream retry: discard accumulated state and restart accumulation
1010
- if (chunk.reset) {
1011
- content = '';
1012
- iterationBuffer = '';
1013
- toolCallsMap.clear();
1014
- externalToolIndices.clear();
1015
- finishReason = undefined;
1016
- continue;
1017
- }
1018
- if (chunk.content) {
1019
- content += chunk.content;
1020
- // When a client adapter is detected, buffer content — it will be wrapped after the stream completes
1021
- if (!clientAdapter) {
1022
- if (this.config.streamMode === 'final') {
1023
- iterationBuffer += chunk.content;
1024
- }
1025
- else {
1026
- yield { ok: true, value: { content: chunk.content } };
1027
- }
1028
- }
1029
- }
1030
- if (chunk.toolCalls) {
1031
- // Register newly seen external tool indices
1032
- for (const tc of chunk.toolCalls) {
1033
- const name = getStreamToolCallName(tc);
1034
- if (name && externalToolNames.has(name)) {
1035
- const delta = toToolCallDelta(tc, 0);
1036
- externalToolIndices.add(delta.index);
1037
- }
1038
- }
1039
- const externalDeltas = chunk.toolCalls.filter((tc) => {
1040
- const delta = toToolCallDelta(tc, 0);
1041
- return externalToolIndices.has(delta.index);
1042
- });
1043
- if (externalDeltas.length > 0) {
1044
- yield {
1045
- ok: true,
1046
- value: { content: '', toolCalls: externalDeltas },
1047
- };
1048
- }
1049
- for (const [fallbackIndex, rawToolCall,] of chunk.toolCalls.entries()) {
1050
- const tc = toToolCallDelta(rawToolCall, fallbackIndex);
1051
- if (!toolCallsMap.has(tc.index)) {
1052
- toolCallsMap.set(tc.index, {
1053
- id: tc.id || '',
1054
- name: tc.name || '',
1055
- arguments: tc.arguments || '',
1056
- });
1057
- }
1058
- else {
1059
- const ex = toolCallsMap.get(tc.index);
1060
- if (ex) {
1061
- if (tc.id)
1062
- ex.id = tc.id;
1063
- if (tc.name)
1064
- ex.name = tc.name;
1065
- if (tc.arguments)
1066
- ex.arguments += tc.arguments;
1067
- }
1068
- }
1069
- }
1070
- }
1071
- if (chunk.finishReason)
1072
- finishReason = chunk.finishReason;
1073
- if (chunk.usage) {
1074
- usage.promptTokens += chunk.usage.promptTokens;
1075
- usage.completionTokens += chunk.usage.completionTokens;
1076
- usage.totalTokens += chunk.usage.totalTokens;
1077
- this.sessionManager.addTokens(chunk.usage.totalTokens);
1078
- }
1079
- }
1080
- llmSpan.setStatus('ok');
1081
- llmSpan.end();
1082
- const llmCallDuration = Date.now() - llmCallStart;
1083
- this.metrics.llmCallLatency.record(llmCallDuration);
1084
- timingLog.push({
1085
- phase: `llm_call_${iteration + 1}`,
1086
- duration: llmCallDuration,
1087
- });
1088
- // In 'final' mode: yield buffered content only if this is the last iteration
1089
- if (this.config.streamMode === 'final' && iterationBuffer) {
1090
- if (finishReason !== 'tool_calls') {
1091
- // Final iteration — stream the buffered content
1092
- yield { ok: true, value: { content: iterationBuffer } };
1093
- }
1094
- iterationBuffer = '';
1095
- }
1096
- const toolCalls = Array.from(toolCallsMap.values()).map((tc) => {
1097
- let args = {};
1098
- try {
1099
- args = JSON.parse(tc.arguments);
1100
- }
1101
- catch {
1102
- args = {};
1103
- }
1104
- return { id: tc.id, name: tc.name, arguments: args };
1105
- });
1106
- opts?.sessionLogger?.logStep(`llm_response_iter_${iteration + 1}`, {
1107
- content,
1108
- toolCalls,
1109
- finishReason,
1110
- });
1111
- if (finishReason !== 'tool_calls' || toolCalls.length === 0) {
1112
- // Output validation
1113
- const valResult = await this.outputValidator.validate(content, { messages, tools: currentTools }, opts);
1114
- if (valResult.ok && !valResult.value.valid) {
1115
- const correction = valResult.value.correctedContent ?? valResult.value.reason;
1116
- messages = [
1117
- ...messages,
1118
- { role: 'assistant', content },
1119
- {
1120
- role: 'user',
1121
- content: `Your previous response was rejected by validation: ${correction}. Please try again.`,
1122
- },
1123
- ];
1124
- continue;
1125
- }
1126
- opts?.sessionLogger?.logStep('final_response', { content, usage });
1127
- // onBeforeStream hook — consumer transforms content before streaming
1128
- if (this.config.onBeforeStream) {
1129
- const hookCtx = { messages };
1130
- for await (const chunk of this.config.onBeforeStream(content, hookCtx)) {
1131
- if (clientAdapter) {
1132
- yield {
1133
- ok: true,
1134
- value: { content: clientAdapter.wrapResponse(chunk) },
1135
- };
1136
- }
1137
- else {
1138
- yield { ok: true, value: { content: chunk } };
1139
- }
1140
- }
1141
- }
1142
- else if (clientAdapter && content) {
1143
- yield {
1144
- ok: true,
1145
- value: { content: clientAdapter.wrapResponse(content) },
1146
- };
1147
- }
1148
- timingLog.push({ phase: 'total', duration: Date.now() - loopStart });
1149
- toolLoopSpan.setStatus('ok');
1150
- toolLoopSpan.end();
1151
- const summary = this.requestLogger.getSummary();
1152
- yield {
1153
- ok: true,
1154
- value: {
1155
- content: '',
1156
- finishReason: finishReason || 'stop',
1157
- usage: {
1158
- ...usage,
1159
- models: summary.byModel,
1160
- },
1161
- timing: timingLog,
1162
- },
1163
- };
1164
- return;
1165
- }
1166
- const internalCalls = toolCalls.filter((tc) => toolClientMap.has(tc.name));
1167
- const validExternalCalls = toolCalls.filter((tc) => externalToolNames.has(tc.name));
1168
- const blockedToolNames = this.toolAvailabilityRegistry.getBlockedToolNames(sessionId);
1169
- const blockedCalls = toolCalls.filter((tc) => blockedToolNames.has(tc.name));
1170
- const hallucinations = toolCalls.filter((tc) => !blockedToolNames.has(tc.name) &&
1171
- !toolClientMap.has(tc.name) &&
1172
- !externalToolNames.has(tc.name));
1173
- if (blockedCalls.length > 0) {
1174
- messages = [
1175
- ...messages,
1176
- {
1177
- role: 'assistant',
1178
- content: content || null,
1179
- tool_calls: blockedCalls.map((tc) => ({
1180
- id: tc.id,
1181
- type: 'function',
1182
- function: {
1183
- name: tc.name,
1184
- arguments: JSON.stringify(tc.arguments),
1185
- },
1186
- })),
1187
- },
1188
- ];
1189
- for (const blocked of blockedCalls) {
1190
- messages = [
1191
- ...messages,
1192
- {
1193
- role: 'tool',
1194
- content: `Error: Tool "${blocked.name}" is temporarily unavailable in this session.`,
1195
- tool_call_id: blocked.id,
1196
- },
1197
- ];
1198
- }
1199
- opts?.sessionLogger?.logStep('blocked_tool_calls_intercepted', {
1200
- toolNames: blockedCalls.map((tc) => tc.name),
1201
- });
1202
- continue;
1203
- }
1204
- if (hallucinations.length > 0) {
1205
- messages = [
1206
- ...messages,
1207
- {
1208
- role: 'assistant',
1209
- content: content || null,
1210
- tool_calls: toolCalls.map((tc) => ({
1211
- id: tc.id,
1212
- type: 'function',
1213
- function: {
1214
- name: tc.name,
1215
- arguments: JSON.stringify(tc.arguments),
1216
- },
1217
- })),
1218
- },
1219
- ];
1220
- for (const h of hallucinations) {
1221
- messages = [
1222
- ...messages,
1223
- {
1224
- role: 'tool',
1225
- content: `Error: Tool "${h.name}" not found.`,
1226
- tool_call_id: h.id,
1227
- },
1228
- ];
1229
- }
1230
- continue;
1231
- }
1232
- if (validExternalCalls.length > 0) {
1233
- // Mixed calls: fire internal tools async, store pending results
1234
- if (internalCalls.length > 0) {
1235
- fireInternalToolsAsync(content, internalCalls, this.pendingToolResults, sessionId, {
1236
- toolClientMap,
1237
- toolCache: this.toolCache,
1238
- metrics: this.metrics,
1239
- options: opts,
1240
- });
1241
- opts?.sessionLogger?.logStep('mixed_tool_calls', {
1242
- internal: internalCalls.map((tc) => tc.name),
1243
- external: validExternalCalls.map((tc) => tc.name),
1244
- });
1245
- }
1246
- timingLog.push({ phase: 'total', duration: Date.now() - loopStart });
1247
- toolLoopSpan.setStatus('ok');
1248
- toolLoopSpan.end();
1249
- yield {
1250
- ok: true,
1251
- value: {
1252
- content: '',
1253
- finishReason: 'tool_calls',
1254
- usage: {
1255
- ...usage,
1256
- models: this.requestLogger.getSummary().byModel,
1257
- },
1258
- timing: timingLog,
1259
- },
1260
- };
1261
- return;
1262
- }
1263
- if (content || internalCalls.length > 0)
1264
- messages = [
1265
- ...messages,
1266
- {
1267
- role: 'assistant',
1268
- content: content || null,
1269
- tool_calls: internalCalls.map((tc) => ({
1270
- id: tc.id,
1271
- type: 'function',
1272
- function: {
1273
- name: tc.name,
1274
- arguments: JSON.stringify(tc.arguments),
1275
- },
1276
- })),
1277
- },
1278
- ];
1279
- // Truncate batch to remaining budget
1280
- const remaining = this.config.maxToolCalls !== undefined
1281
- ? this.config.maxToolCalls - toolCallCount
1282
- : internalCalls.length;
1283
- if (remaining <= 0) {
1284
- timingLog.push({ phase: 'total', duration: Date.now() - loopStart });
1285
- toolLoopSpan.addEvent('tool_call_limit_reached');
1286
- toolLoopSpan.end();
1287
- yield {
1288
- ok: true,
1289
- value: {
1290
- content: '',
1291
- finishReason: 'length',
1292
- usage: {
1293
- ...usage,
1294
- models: this.requestLogger.getSummary().byModel,
1295
- },
1296
- timing: timingLog,
1297
- },
1298
- };
1299
- return;
1300
- }
1301
- const batch = internalCalls.slice(0, remaining);
1302
- const heartbeatMs = this.config.heartbeatIntervalMs ?? 5000;
1303
- // Yield all progress messages before execution
1304
- for (const tc of batch) {
1305
- yield {
1306
- ok: true,
1307
- value: { content: `\n\n[SmartAgent: Executing ${tc.name}...]\n` },
1308
- };
1309
- }
1310
- const toolExecPromises = batch.map(async (tc) => {
1311
- const toolStart = Date.now();
1312
- opts?.sessionLogger?.logStep(`mcp_call_${tc.name}`, {
1313
- arguments: tc.arguments,
1314
- });
1315
- const client = toolClientMap.get(tc.name);
1316
- if (!client)
1317
- return { tc, text: '', res: null, duration: 0 };
1318
- const toolSpan = this.tracer.startSpan('smart_agent.tool_call', {
1319
- parent: toolLoopSpan,
1320
- attributes: { 'tool.name': tc.name },
1321
- });
1322
- const cached = this.toolCache.get(tc.name, tc.arguments);
1323
- const res = cached
1324
- ? (() => {
1325
- this.metrics.toolCacheHitCount.add();
1326
- toolSpan.setAttribute('cache', 'hit');
1327
- return { ok: true, value: cached };
1328
- })()
1329
- : await (async () => {
1330
- const r = await client.callTool(tc.name, tc.arguments, opts);
1331
- if (r.ok)
1332
- this.toolCache.set(tc.name, tc.arguments, r.value);
1333
- return r;
1334
- })();
1335
- const text = !res.ok
1336
- ? res.error.message
1337
- : typeof res.value.content === 'string'
1338
- ? res.value.content
1339
- : JSON.stringify(res.value.content);
1340
- toolSpan.setStatus(res.ok ? 'ok' : 'error', res.ok ? undefined : text);
1341
- toolSpan.end();
1342
- return { tc, text, res, duration: Date.now() - toolStart };
1343
- });
1344
- // Race: tool execution vs periodic heartbeat
1345
- const allDone = Promise.all(toolExecPromises);
1346
- const pendingTools = new Set(batch.map((tc) => tc.name));
1347
- const toolStartTime = Date.now();
1348
- let results = [];
1349
- let settled = false;
1350
- // Mark individual tools as done when they resolve
1351
- for (const [i, p] of toolExecPromises.entries()) {
1352
- p.then(() => pendingTools.delete(batch[i].name));
1353
- }
1354
- while (!settled) {
1355
- const winner = await Promise.race([
1356
- allDone.then((r) => ({ tag: 'done', results: r })),
1357
- new Promise((resolve) => setTimeout(() => resolve({ tag: 'tick' }), heartbeatMs)),
1358
- ]);
1359
- if (winner.tag === 'done') {
1360
- results = winner.results;
1361
- settled = true;
1362
- }
1363
- else {
1364
- // Yield heartbeat for each still-pending tool
1365
- for (const tool of pendingTools) {
1366
- yield {
1367
- ok: true,
1368
- value: {
1369
- content: '',
1370
- heartbeat: {
1371
- tool,
1372
- elapsed: Date.now() - toolStartTime,
1373
- },
1374
- },
1375
- };
1376
- }
1377
- }
1378
- }
1379
- // Collect per-tool timing into the shared timing log
1380
- for (const r of results) {
1381
- timingLog.push({
1382
- phase: `tool_${r.tc.name}`,
1383
- duration: r.duration,
1384
- });
1385
- }
1386
- // Process results: update availability, metrics, messages
1387
- const toolMessages = [];
1388
- for (const { tc, text, res } of results) {
1389
- if (!res)
1390
- continue;
1391
- if (!res.ok &&
1392
- isToolContextUnavailableError(text) &&
1393
- !externalToolNames.has(tc.name)) {
1394
- const entry = this.toolAvailabilityRegistry.block(sessionId, tc.name, text);
1395
- currentTools = currentTools.filter((t) => t.name !== tc.name);
1396
- opts?.sessionLogger?.logStep(`tool_blacklisted_${tc.name}`, {
1397
- reason: text,
1398
- blockedUntil: entry.blockedUntil,
1399
- });
1400
- }
1401
- opts?.sessionLogger?.logStep(`mcp_result_${tc.name}`, {
1402
- result: text,
1403
- });
1404
- toolCallCount++;
1405
- this.metrics.toolCallCount.add();
1406
- toolMessages.push({
1407
- role: 'tool',
1408
- content: text,
1409
- tool_call_id: tc.id,
1410
- });
1411
- }
1412
- messages = [...messages, ...toolMessages];
1413
- }
1414
- }
1415
- async _listAllTools(opts) {
1416
- await this._resolveActiveClients(opts);
1417
- const tools = [];
1418
- const toolClientMap = new Map();
1419
- const settled = await Promise.allSettled(this._activeClients.map(async (client) => ({
1420
- client,
1421
- result: await client.listTools(opts),
1422
- })));
1423
- for (const e of settled) {
1424
- if (e.status === 'fulfilled' && e.value.result.ok) {
1425
- for (const t of e.value.result.value) {
1426
- if (!toolClientMap.has(t.name)) {
1427
- tools.push(t);
1428
- toolClientMap.set(t.name, e.value.client);
1429
- }
1430
- }
1431
- }
1432
- }
1433
- return { tools, toolClientMap };
1434
- }
1435
- async _toEnglishForRag(text, opts) {
1436
- if (/^[\p{ASCII}]+$/u.test(text) || text.length < 15)
1437
- return text;
1438
- const dp = 'Translate the user request to English for search purposes. Preserve technical terms if present. Reply with only the expanded English terms, no explanation.';
1439
- const llm = this._helperLlm || this._mainLlm;
1440
- const res = await llm.chat([
1441
- {
1442
- role: 'system',
1443
- content: this.config.ragTranslatePrompt || dp,
1444
- },
1445
- { role: 'user', content: text },
1446
- ], [], opts);
1447
- return res.ok && res.value.content.trim() ? res.value.content.trim() : text;
1448
- }
1449
- async _summarizeHistory(h, opts) {
1450
- if (!this._helperLlm)
1451
- return { ok: true, value: h };
1452
- const toS = h.slice(0, -5);
1453
- const rec = h.slice(-5);
1454
- if (toS.length === 0)
1455
- return { ok: true, value: h };
1456
- const dp = 'Summarize the conversation so far in 2-3 sentences. Focus on the user goals and the current status of the task. Keep technical SAP terms as is.';
1457
- const summarizeStart = Date.now();
1458
- const res = await this._helperLlm.chat([
1459
- ...toS,
1460
- {
1461
- role: 'system',
1462
- content: this.config.historySummaryPrompt || dp,
1463
- },
1464
- ], [], opts);
1465
- this.requestLogger.logLlmCall({
1466
- component: 'helper',
1467
- model: this._helperLlm.model ?? 'unknown',
1468
- promptTokens: res.ok ? (res.value.usage?.promptTokens ?? 0) : 0,
1469
- completionTokens: res.ok ? (res.value.usage?.completionTokens ?? 0) : 0,
1470
- totalTokens: res.ok ? (res.value.usage?.totalTokens ?? 0) : 0,
1471
- durationMs: Date.now() - summarizeStart,
1472
- });
1473
- if (!res.ok)
1474
- return { ok: true, value: h };
1475
- return {
1476
- ok: true,
1477
- value: [
1478
- {
1479
- role: 'system',
1480
- content: `Summary of previous conversation: ${res.value.content}`,
1481
- },
1482
- ...rec,
1483
- ],
1484
- };
1485
- }
1486
- async *_runStructuredPipeline(textOrMessages, externalTools, opts, _parentSpan, _sessionId) {
1487
- if (!this.deps.pipeline)
1488
- return;
1489
- const history = typeof textOrMessages === 'string' ? [] : textOrMessages;
1490
- const chunkQueue = [];
1491
- let resolveWait = null;
1492
- let done = false;
1493
- const executorPromise = this.deps.pipeline
1494
- .execute(textOrMessages, history, opts, (chunk) => {
1495
- chunkQueue.push(chunk);
1496
- if (resolveWait) {
1497
- resolveWait();
1498
- resolveWait = null;
1499
- }
1500
- }, externalTools)
1501
- .then(() => {
1502
- done = true;
1503
- if (resolveWait) {
1504
- resolveWait();
1505
- resolveWait = null;
1506
- }
1507
- })
1508
- .catch((err) => {
1509
- chunkQueue.push({
1510
- ok: false,
1511
- error: new OrchestratorError(String(err), 'PIPELINE_ERROR'),
1512
- });
1513
- done = true;
1514
- if (resolveWait) {
1515
- resolveWait();
1516
- resolveWait = null;
1517
- }
1518
- });
1519
- while (!done || chunkQueue.length > 0) {
1520
- if (chunkQueue.length > 0) {
1521
- const chunk = chunkQueue.shift();
1522
- if (chunk !== undefined)
1523
- yield chunk;
1524
- }
1525
- else if (!done) {
1526
- await new Promise((r) => {
1527
- resolveWait = r;
1528
- });
1529
- }
1530
- }
1531
- await executorPromise;
1532
- }
1533
- }
1534
- //# sourceMappingURL=agent.js.map