@stkxp/cli 0.1.2

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 (371) hide show
  1. package/README.md +273 -0
  2. package/bin/stkxp.mjs +198 -0
  3. package/package.json +97 -0
  4. package/src/bootstrap.mjs +37 -0
  5. package/src/bootstrap.test.mjs +73 -0
  6. package/src/deploy.mjs +145 -0
  7. package/src/deploy.test.mjs +131 -0
  8. package/src/export.mjs +30 -0
  9. package/src/export.test.mjs +56 -0
  10. package/src/secret-input.mjs +64 -0
  11. package/src/secret-input.test.mjs +58 -0
  12. package/src/serve.mjs +83 -0
  13. package/src/serve.test.mjs +93 -0
  14. package/vendor/dist-server/asyncapi/generator.js +1 -0
  15. package/vendor/dist-server/asyncapi/messages.js +1 -0
  16. package/vendor/dist-server/asyncapi/viewer.html +43 -0
  17. package/vendor/dist-server/core/app-config/branding.js +1 -0
  18. package/vendor/dist-server/core/app-config/mantine-theme.js +1 -0
  19. package/vendor/dist-server/core/app-config/mermaid-theme.js +2 -0
  20. package/vendor/dist-server/core/app-config/prompt-optimization.js +1 -0
  21. package/vendor/dist-server/core/app-config/settings.js +1 -0
  22. package/vendor/dist-server/core/config.js +1 -0
  23. package/vendor/dist-server/core/graph/a2a-agent-executor.js +2 -0
  24. package/vendor/dist-server/core/graph/app.js +120 -0
  25. package/vendor/dist-server/core/graph/delegated-agent-adapter.js +1 -0
  26. package/vendor/dist-server/core/graph/graph-builder.js +3 -0
  27. package/vendor/dist-server/core/graph/kibana-agent-executor.js +1 -0
  28. package/vendor/dist-server/core/graph/nodes/context/assistants-context.js +5 -0
  29. package/vendor/dist-server/core/graph/nodes/context/compare-context.js +10 -0
  30. package/vendor/dist-server/core/graph/nodes/context/enrich-context.js +8 -0
  31. package/vendor/dist-server/core/graph/nodes/context/inventory-context.js +4 -0
  32. package/vendor/dist-server/core/graph/nodes/context/namespace-context.js +2 -0
  33. package/vendor/dist-server/core/graph/nodes/context/node-types-context.js +4 -0
  34. package/vendor/dist-server/core/graph/nodes/context/relevant-assistants-context.js +5 -0
  35. package/vendor/dist-server/core/graph/nodes/context/relevant-skills-context.js +5 -0
  36. package/vendor/dist-server/core/graph/nodes/context/skills-context.js +8 -0
  37. package/vendor/dist-server/core/graph/nodes/context/state-setter.js +1 -0
  38. package/vendor/dist-server/core/graph/nodes/control/check-reset.js +1 -0
  39. package/vendor/dist-server/core/graph/nodes/control/topic-detection.js +1 -0
  40. package/vendor/dist-server/core/graph/nodes/governance/human-approval.js +16 -0
  41. package/vendor/dist-server/core/graph/nodes/index.js +1 -0
  42. package/vendor/dist-server/core/graph/nodes/orchestration/suggestion-generator.js +17 -0
  43. package/vendor/dist-server/core/graph/nodes/orchestration/team-decider.js +1 -0
  44. package/vendor/dist-server/core/graph/nodes/orchestration/team-execution/decider-error.js +4 -0
  45. package/vendor/dist-server/core/graph/nodes/orchestration/team-execution/decider-standalone-runner.js +1 -0
  46. package/vendor/dist-server/core/graph/nodes/orchestration/team-execution/decider-synthesis.js +29 -0
  47. package/vendor/dist-server/core/graph/nodes/orchestration/team-execution/pipeline-memory.js +2 -0
  48. package/vendor/dist-server/core/graph/nodes/orchestration/team-execution/pipeline-runner.js +7 -0
  49. package/vendor/dist-server/core/graph/nodes/orchestration/team-execution/team-assistant-utils.js +1 -0
  50. package/vendor/dist-server/core/graph/nodes/orchestration/team-finder.js +13 -0
  51. package/vendor/dist-server/core/graph/nodes/orchestration/team-invoker.js +3 -0
  52. package/vendor/dist-server/core/graph/nodes/orchestration/team-parallel.js +1 -0
  53. package/vendor/dist-server/core/graph/nodes/orchestration/team-pipeline.js +6 -0
  54. package/vendor/dist-server/core/graph/nodes/orchestration/team-router.js +26 -0
  55. package/vendor/dist-server/core/graph/nodes/reasoning/code-executor/index.js +6 -0
  56. package/vendor/dist-server/core/graph/nodes/reasoning/code-executor/resource-bridge.js +2 -0
  57. package/vendor/dist-server/core/graph/nodes/reasoning/code-executor/sandbox.js +6 -0
  58. package/vendor/dist-server/core/graph/nodes/reasoning/code-executor/tool-bridge.js +1 -0
  59. package/vendor/dist-server/core/graph/nodes/reasoning/local-extractor.js +5 -0
  60. package/vendor/dist-server/core/graph/nodes/reasoning/response-generator.js +47 -0
  61. package/vendor/dist-server/core/graph/nodes/reasoning/static-code-executor/index.js +1 -0
  62. package/vendor/dist-server/core/graph/nodes/reasoning/system.js +54 -0
  63. package/vendor/dist-server/core/graph/nodes/reasoning/tool-executor.js +9 -0
  64. package/vendor/dist-server/core/graph/nodes/tools/raw-output.js +4 -0
  65. package/vendor/dist-server/core/graph/nodes/tools/tool-cleaner.js +7 -0
  66. package/vendor/dist-server/core/graph/nodes/tools/tool-execution/execute-tool-calls.js +3 -0
  67. package/vendor/dist-server/core/graph/nodes/tools/tool-execution/invoke.js +1 -0
  68. package/vendor/dist-server/core/graph/nodes/tools/tool-execution/namespace-guard.js +1 -0
  69. package/vendor/dist-server/core/graph/nodes/tools/tool-execution/result-limits.js +3 -0
  70. package/vendor/dist-server/core/graph/nodes/tools/tool-invoker.js +1 -0
  71. package/vendor/dist-server/core/graph/nodes/tools/tool.js +4 -0
  72. package/vendor/dist-server/core/graph/schemas.js +1 -0
  73. package/vendor/dist-server/core/graph/topic-variants.js +1 -0
  74. package/vendor/dist-server/core/graph/types.js +1 -0
  75. package/vendor/dist-server/core/graph/utils/content-utils.js +17 -0
  76. package/vendor/dist-server/core/graph/utils/edge-jsonata-condition.js +1 -0
  77. package/vendor/dist-server/core/graph/utils/engine-vars.js +1 -0
  78. package/vendor/dist-server/core/graph/utils/logging-utils.js +4 -0
  79. package/vendor/dist-server/core/graph/utils/message-utils.js +5 -0
  80. package/vendor/dist-server/core/graph/utils/node-type-defaults-cache.js +1 -0
  81. package/vendor/dist-server/core/graph/utils/sandbox-catalog.js +1 -0
  82. package/vendor/dist-server/core/graph/utils/schema-utils.js +1 -0
  83. package/vendor/dist-server/core/graph/utils/team-context-policy.js +5 -0
  84. package/vendor/dist-server/core/graph/utils/team-node-resolvers.js +1 -0
  85. package/vendor/dist-server/core/graph/utils/tool-result.js +4 -0
  86. package/vendor/dist-server/core/graph/utils/tool-wrapper.js +14 -0
  87. package/vendor/dist-server/core/llm/init-indices.js +1 -0
  88. package/vendor/dist-server/core/llm/models/index.js +1 -0
  89. package/vendor/dist-server/core/llm/models/model.model.js +1 -0
  90. package/vendor/dist-server/core/llm/models/provider.model.js +1 -0
  91. package/vendor/dist-server/core/llm/models/routing-rule.model.js +1 -0
  92. package/vendor/dist-server/core/llm/providers.js +1 -0
  93. package/vendor/dist-server/core/mcp/client.js +1 -0
  94. package/vendor/dist-server/core/runtime/active-runs-registry.js +1 -0
  95. package/vendor/dist-server/core/runtime/system-prompt-cache.js +1 -0
  96. package/vendor/dist-server/core/runtime/trace-bus.js +1 -0
  97. package/vendor/dist-server/core/schema/cluster_health_report.js +1 -0
  98. package/vendor/dist-server/core/schema/cluster_info.js +1 -0
  99. package/vendor/dist-server/core/schema/cluster_license.js +5 -0
  100. package/vendor/dist-server/core/schema/cluster_stats.js +12 -0
  101. package/vendor/dist-server/core/schema/dashboard.js +1 -0
  102. package/vendor/dist-server/core/schema/indices_settings.js +1 -0
  103. package/vendor/dist-server/core/schema/indices_shards.js +1 -0
  104. package/vendor/dist-server/core/schema/indices_stats.js +1 -0
  105. package/vendor/dist-server/core/schema/nodes_info.js +2 -0
  106. package/vendor/dist-server/core/schema/nodes_stats.js +11 -0
  107. package/vendor/dist-server/core/schema/pricing.js +1 -0
  108. package/vendor/dist-server/core/schema/ui.js +1 -0
  109. package/vendor/dist-server/core/schema/zod_client.js +83 -0
  110. package/vendor/dist-server/core/services/a2a-client.js +2 -0
  111. package/vendor/dist-server/core/services/alerts-service.js +1 -0
  112. package/vendor/dist-server/core/services/api-keys-service.js +1 -0
  113. package/vendor/dist-server/core/services/assistant-resolver.js +1 -0
  114. package/vendor/dist-server/core/services/assistants-index-service.js +1 -0
  115. package/vendor/dist-server/core/services/async-conversations-service.js +22 -0
  116. package/vendor/dist-server/core/services/asyncapi-dispatch.js +1 -0
  117. package/vendor/dist-server/core/services/asyncapi-drivers/driver-manager.js +1 -0
  118. package/vendor/dist-server/core/services/asyncapi-drivers/driver-types.js +0 -0
  119. package/vendor/dist-server/core/services/asyncapi-drivers/http-driver.js +1 -0
  120. package/vendor/dist-server/core/services/asyncapi-drivers/nats-driver.js +1 -0
  121. package/vendor/dist-server/core/services/asyncapi-drivers/websocket-driver.js +1 -0
  122. package/vendor/dist-server/core/services/asyncapi-events-service.js +1 -0
  123. package/vendor/dist-server/core/services/asyncapi-reply-service.js +1 -0
  124. package/vendor/dist-server/core/services/asyncapi-sink.js +1 -0
  125. package/vendor/dist-server/core/services/asyncapi-tools-service.js +1 -0
  126. package/vendor/dist-server/core/services/block-repair-service.js +13 -0
  127. package/vendor/dist-server/core/services/chart-renderer.js +1 -0
  128. package/vendor/dist-server/core/services/chat-llms-service.js +1 -0
  129. package/vendor/dist-server/core/services/chat-runs-service.js +1 -0
  130. package/vendor/dist-server/core/services/chat-tools-service.js +1 -0
  131. package/vendor/dist-server/core/services/chat-traces-service.js +1 -0
  132. package/vendor/dist-server/core/services/chats-service.js +5 -0
  133. package/vendor/dist-server/core/services/comparison-service.js +107 -0
  134. package/vendor/dist-server/core/services/default-model.service.js +1 -0
  135. package/vendor/dist-server/core/services/elastic-stack-sync-service.js +2 -0
  136. package/vendor/dist-server/core/services/elasticsearch-wrapper.js +1 -0
  137. package/vendor/dist-server/core/services/embed-rate-limiter.js +1 -0
  138. package/vendor/dist-server/core/services/error-analytics-service.js +1 -0
  139. package/vendor/dist-server/core/services/es-field-resolver.js +1 -0
  140. package/vendor/dist-server/core/services/gateway-platform-types.js +1 -0
  141. package/vendor/dist-server/core/services/gliner-tagging-service.js +1 -0
  142. package/vendor/dist-server/core/services/golden-questions-scoring.js +1 -0
  143. package/vendor/dist-server/core/services/golden-questions-service.js +1 -0
  144. package/vendor/dist-server/core/services/graph-drilldown-service.js +1 -0
  145. package/vendor/dist-server/core/services/graph-registry-service.js +1 -0
  146. package/vendor/dist-server/core/services/hitl-analytics-service.js +1 -0
  147. package/vendor/dist-server/core/services/ingestion-jobs-service.js +1 -0
  148. package/vendor/dist-server/core/services/ingestion-service.js +5 -0
  149. package/vendor/dist-server/core/services/kibana-client-factory.js +1 -0
  150. package/vendor/dist-server/core/services/kibana-client.js +2 -0
  151. package/vendor/dist-server/core/services/kibana-dashboard-extractor.js +1 -0
  152. package/vendor/dist-server/core/services/kibana-service.js +1 -0
  153. package/vendor/dist-server/core/services/llm-analytics-service.js +1 -0
  154. package/vendor/dist-server/core/services/llm-client-resolver.js +1 -0
  155. package/vendor/dist-server/core/services/llm-models-service.js +1 -0
  156. package/vendor/dist-server/core/services/llm-pricing-pure.js +1 -0
  157. package/vendor/dist-server/core/services/llm-pricing-service.js +1 -0
  158. package/vendor/dist-server/core/services/llm-providers-service.js +1 -0
  159. package/vendor/dist-server/core/services/llm-routing-service.js +1 -0
  160. package/vendor/dist-server/core/services/llm-services.js +1 -0
  161. package/vendor/dist-server/core/services/llm-sync-service.js +1 -0
  162. package/vendor/dist-server/core/services/manifest-loader.js +1 -0
  163. package/vendor/dist-server/core/services/mcp-servers-service.js +1 -0
  164. package/vendor/dist-server/core/services/mcp-sync-service.js +1 -0
  165. package/vendor/dist-server/core/services/mcp-tools-service.js +1 -0
  166. package/vendor/dist-server/core/services/memories-service.js +2 -0
  167. package/vendor/dist-server/core/services/memory-analytics-service.js +1 -0
  168. package/vendor/dist-server/core/services/monitoring-analytics-service.js +1 -0
  169. package/vendor/dist-server/core/services/monitoring-service.js +1 -0
  170. package/vendor/dist-server/core/services/multi-kibana-service.js +1 -0
  171. package/vendor/dist-server/core/services/node-latency-service.js +1 -0
  172. package/vendor/dist-server/core/services/package-policy-service.js +2 -0
  173. package/vendor/dist-server/core/services/pdf-service.js +572 -0
  174. package/vendor/dist-server/core/services/plan-service.js +1 -0
  175. package/vendor/dist-server/core/services/platform-direction.js +1 -0
  176. package/vendor/dist-server/core/services/platform-secrets.js +1 -0
  177. package/vendor/dist-server/core/services/platforms-service.js +1 -0
  178. package/vendor/dist-server/core/services/policy-factory.js +1 -0
  179. package/vendor/dist-server/core/services/prompt-cache-service.js +1 -0
  180. package/vendor/dist-server/core/services/provider-rate-limits.js +1 -0
  181. package/vendor/dist-server/core/services/quota-service.js +1 -0
  182. package/vendor/dist-server/core/services/report-assets-service.js +1 -0
  183. package/vendor/dist-server/core/services/run-analytics-collector.js +1 -0
  184. package/vendor/dist-server/core/services/run-stream-sink.js +1 -0
  185. package/vendor/dist-server/core/services/send_mail.js +460 -0
  186. package/vendor/dist-server/core/services/share-service.js +1 -0
  187. package/vendor/dist-server/core/services/slack-signature.js +1 -0
  188. package/vendor/dist-server/core/services/sources-service.js +6 -0
  189. package/vendor/dist-server/core/services/team-mcp-result.js +4 -0
  190. package/vendor/dist-server/core/services/team-mcp-run-tokens.js +1 -0
  191. package/vendor/dist-server/core/services/team-mcp-runner.js +1 -0
  192. package/vendor/dist-server/core/services/team-mcp-server.js +1 -0
  193. package/vendor/dist-server/core/services/team-mcp-tools.js +1 -0
  194. package/vendor/dist-server/core/services/team-mcp-ui.js +551 -0
  195. package/vendor/dist-server/core/services/team-run-progress.js +1 -0
  196. package/vendor/dist-server/core/services/team-runner-headless.js +7 -0
  197. package/vendor/dist-server/core/services/team-search-service.js +1 -0
  198. package/vendor/dist-server/core/services/teams-service.js +1 -0
  199. package/vendor/dist-server/core/services/token-projection-service.js +1 -0
  200. package/vendor/dist-server/core/services/tool-analytics-service.js +1 -0
  201. package/vendor/dist-server/core/services/tool-history-service.js +1 -0
  202. package/vendor/dist-server/core/services/tool-metrics-service.js +1 -0
  203. package/vendor/dist-server/core/services/tool-scoring.js +1 -0
  204. package/vendor/dist-server/core/services/toolbox-import-mappers.js +1 -0
  205. package/vendor/dist-server/core/services/toolbox-import-service.js +1 -0
  206. package/vendor/dist-server/core/services/trigger-service.js +1 -0
  207. package/vendor/dist-server/core/services/version-snapshot-service.js +1 -0
  208. package/vendor/dist-server/core/services/webhook-calls-service.js +1 -0
  209. package/vendor/dist-server/core/tools/compare-chat.js +46 -0
  210. package/vendor/dist-server/core/tools/enrich-chat.js +50 -0
  211. package/vendor/dist-server/core/tools/variable-encoding.js +1 -0
  212. package/vendor/dist-server/core/types/settings.js +1 -0
  213. package/vendor/dist-server/core/utils/ab-evaluator.js +5 -0
  214. package/vendor/dist-server/core/utils/condition-evaluator.js +1 -0
  215. package/vendor/dist-server/core/utils/http-client.js +1 -0
  216. package/vendor/dist-server/core/utils/json-schema-to-form.js +1 -0
  217. package/vendor/dist-server/core/utils/logger.js +3 -0
  218. package/vendor/dist-server/core/utils/owner-scope.js +1 -0
  219. package/vendor/dist-server/core/utils/ownership.js +1 -0
  220. package/vendor/dist-server/core/utils/parallel-tool-executor.js +1 -0
  221. package/vendor/dist-server/core/utils/performance-tracker.js +3 -0
  222. package/vendor/dist-server/core/utils/prompt-optimizer.js +40 -0
  223. package/vendor/dist-server/core/utils/response-cache.js +1 -0
  224. package/vendor/dist-server/core/utils/schema-validator.js +1 -0
  225. package/vendor/dist-server/core/utils/streaming-optimizer.js +2 -0
  226. package/vendor/dist-server/core/utils/string-helpers.js +1 -0
  227. package/vendor/dist-server/core/utils/test-responses.js +9 -0
  228. package/vendor/dist-server/core/utils/text-utils.js +1 -0
  229. package/vendor/dist-server/core/utils/tool-form-trigger.js +1 -0
  230. package/vendor/dist-server/entrypoints/cli-bootstrap-run.js +1 -0
  231. package/vendor/dist-server/entrypoints/cli-deploy-run.js +1 -0
  232. package/vendor/dist-server/entrypoints/cli-deploy.js +1 -0
  233. package/vendor/dist-server/entrypoints/team-runner.js +1 -0
  234. package/vendor/dist-server/generated/toolbox-catalog.js +1 -0
  235. package/vendor/dist-server/index.js +2 -0
  236. package/vendor/dist-server/middleware/integration-logos.js +1 -0
  237. package/vendor/dist-server/middleware/plan-guard.js +1 -0
  238. package/vendor/dist-server/openapi/generator.js +1 -0
  239. package/vendor/dist-server/openapi/html-tool-spec.js +1 -0
  240. package/vendor/dist-server/routes/a2a-routes.js +1 -0
  241. package/vendor/dist-server/routes/a2a-server-routes.js +5 -0
  242. package/vendor/dist-server/routes/admin.js +1 -0
  243. package/vendor/dist-server/routes/assistants-routes.js +1 -0
  244. package/vendor/dist-server/routes/asyncapi-routes.js +1 -0
  245. package/vendor/dist-server/routes/auth.js +1 -0
  246. package/vendor/dist-server/routes/billing-routes.js +1 -0
  247. package/vendor/dist-server/routes/chat-llms.js +1 -0
  248. package/vendor/dist-server/routes/chat-tools.js +1 -0
  249. package/vendor/dist-server/routes/chat-traces.js +1 -0
  250. package/vendor/dist-server/routes/chats.js +1 -0
  251. package/vendor/dist-server/routes/clusters.js +1 -0
  252. package/vendor/dist-server/routes/compare.js +43 -0
  253. package/vendor/dist-server/routes/connectors-routes.js +1 -0
  254. package/vendor/dist-server/routes/consumptions-routes.js +1 -0
  255. package/vendor/dist-server/routes/data-admin-routes.js +1 -0
  256. package/vendor/dist-server/routes/data-transfer-routes.js +1 -0
  257. package/vendor/dist-server/routes/elastic-tool-execution-routes.js +1 -0
  258. package/vendor/dist-server/routes/geo-proxy-routes.js +1 -0
  259. package/vendor/dist-server/routes/golden-questions-routes.js +1 -0
  260. package/vendor/dist-server/routes/graph-registry.js +1 -0
  261. package/vendor/dist-server/routes/graph-templates-routes.js +1 -0
  262. package/vendor/dist-server/routes/helpdesk-routes.js +35 -0
  263. package/vendor/dist-server/routes/html-routes.js +1 -0
  264. package/vendor/dist-server/routes/index.js +1 -0
  265. package/vendor/dist-server/routes/indices.js +1 -0
  266. package/vendor/dist-server/routes/integrations-routes.js +1 -0
  267. package/vendor/dist-server/routes/langgraph.js +7 -0
  268. package/vendor/dist-server/routes/live-resources-routes.js +1 -0
  269. package/vendor/dist-server/routes/llm-analytics.js +1 -0
  270. package/vendor/dist-server/routes/llm-control-plane.js +1 -0
  271. package/vendor/dist-server/routes/llm.js +1 -0
  272. package/vendor/dist-server/routes/mcp-gateway-routes.js +1 -0
  273. package/vendor/dist-server/routes/mcp-query-routes.js +1 -0
  274. package/vendor/dist-server/routes/mcp-servers-routes.js +1 -0
  275. package/vendor/dist-server/routes/mcp-team-routes.js +1 -0
  276. package/vendor/dist-server/routes/mcp-tools-routes.js +1 -0
  277. package/vendor/dist-server/routes/me-routes.js +63 -0
  278. package/vendor/dist-server/routes/memories-routes.js +1 -0
  279. package/vendor/dist-server/routes/monitoring-analytics.js +12 -0
  280. package/vendor/dist-server/routes/monitoring.js +1 -0
  281. package/vendor/dist-server/routes/node-types-routes.js +171 -0
  282. package/vendor/dist-server/routes/nodes.js +1 -0
  283. package/vendor/dist-server/routes/packages.js +1 -0
  284. package/vendor/dist-server/routes/pdf.js +3 -0
  285. package/vendor/dist-server/routes/plan-routes.js +1 -0
  286. package/vendor/dist-server/routes/platform-requests-routes.js +1 -0
  287. package/vendor/dist-server/routes/platforms-routes.js +1 -0
  288. package/vendor/dist-server/routes/prompts-routes.js +1 -0
  289. package/vendor/dist-server/routes/proxy-logos.js +1 -0
  290. package/vendor/dist-server/routes/quality-routes.js +1 -0
  291. package/vendor/dist-server/routes/resources-ingest-routes.js +1 -0
  292. package/vendor/dist-server/routes/resources-routes.js +1 -0
  293. package/vendor/dist-server/routes/schema-routes.js +1 -0
  294. package/vendor/dist-server/routes/settings-original.js +1 -0
  295. package/vendor/dist-server/routes/settings.js +1 -0
  296. package/vendor/dist-server/routes/share-routes.js +1 -0
  297. package/vendor/dist-server/routes/sources-catalog-routes.js +1 -0
  298. package/vendor/dist-server/routes/sources-routes.js +1 -0
  299. package/vendor/dist-server/routes/team-optimizer-routes.js +1 -0
  300. package/vendor/dist-server/routes/team-schedule-routes.js +1 -0
  301. package/vendor/dist-server/routes/teams-routes.js +1 -0
  302. package/vendor/dist-server/routes/tool-analytics.js +1 -0
  303. package/vendor/dist-server/routes/tool-history-routes.js +1 -0
  304. package/vendor/dist-server/routes/tool-metrics-routes.js +1 -0
  305. package/vendor/dist-server/routes/toolbox-import-routes.js +1 -0
  306. package/vendor/dist-server/routes/tools-routes.js +5 -0
  307. package/vendor/dist-server/routes/transcribe-routes.js +1 -0
  308. package/vendor/dist-server/routes/triggers.js +1 -0
  309. package/vendor/dist-server/routes/versions-routes.js +1 -0
  310. package/vendor/dist-server/routes/webhooks-routes.js +1 -0
  311. package/vendor/dist-server/scripts/add-label-to-tools.js +4 -0
  312. package/vendor/dist-server/scripts/migrate-assistants-to-mcp.js +10 -0
  313. package/vendor/dist-server/scripts/migrate-chat-runs.js +8 -0
  314. package/vendor/dist-server/scripts/migrate-mcp-protocol.js +8 -0
  315. package/vendor/dist-server/scripts/migrate-mcp-to-platforms.js +15 -0
  316. package/vendor/dist-server/services/alert-evaluator.js +3 -0
  317. package/vendor/dist-server/services/auth.js +1 -0
  318. package/vendor/dist-server/services/billing-service.js +1 -0
  319. package/vendor/dist-server/services/chat-title-generator.js +12 -0
  320. package/vendor/dist-server/services/clone/clone-executor.js +1 -0
  321. package/vendor/dist-server/services/clone/closure-resolver.js +3 -0
  322. package/vendor/dist-server/services/clone/entity-graph.js +3 -0
  323. package/vendor/dist-server/services/clone/team-bundle-bootstrap.js +1 -0
  324. package/vendor/dist-server/services/clone/team-bundle-crypto.js +1 -0
  325. package/vendor/dist-server/services/clone/team-bundle-encrypted.js +1 -0
  326. package/vendor/dist-server/services/clone/team-bundle.js +1 -0
  327. package/vendor/dist-server/services/cluster-service.js +1 -0
  328. package/vendor/dist-server/services/connection-adapters.js +1 -0
  329. package/vendor/dist-server/services/connectors-service.js +10 -0
  330. package/vendor/dist-server/services/cost-forecast-service.js +1 -0
  331. package/vendor/dist-server/services/eui-ssr-renderer.js +4 -0
  332. package/vendor/dist-server/services/graph-canvas/full-structure-builder.js +1 -0
  333. package/vendor/dist-server/services/graph-templates-service.js +13 -0
  334. package/vendor/dist-server/services/guest-service.js +1 -0
  335. package/vendor/dist-server/services/html-service.js +1 -0
  336. package/vendor/dist-server/services/langgraph-service.js +2 -0
  337. package/vendor/dist-server/services/leaflet-render-service.js +80 -0
  338. package/vendor/dist-server/services/live-resources-service.js +16 -0
  339. package/vendor/dist-server/services/mcp-app-tester-package.js +1 -0
  340. package/vendor/dist-server/services/mcp-gateway/executors/openapi-executor.js +1 -0
  341. package/vendor/dist-server/services/mcp-gateway/gateway-grant-service.js +2 -0
  342. package/vendor/dist-server/services/team-optimizer-service.js +1 -0
  343. package/vendor/dist-server/services/trace-bus-sink.js +1 -0
  344. package/vendor/dist-server/services/user-provisioning-service.js +3 -0
  345. package/vendor/dist-server/templates/mcp-app-tester/src/mcp-http.js +3 -0
  346. package/vendor/dist-server/templates/mcp-app-tester/src/server.js +1 -0
  347. package/vendor/dist-server/utils.js +1 -0
  348. package/vendor/dist-server/ws/assistant-executor.js +7 -0
  349. package/vendor/dist-server/ws/classify-streamed-json-block.js +1 -0
  350. package/vendor/dist-server/ws/collect-response-generator-node-ids.js +1 -0
  351. package/vendor/dist-server/ws/extractors/blockkit-extractor.js +1 -0
  352. package/vendor/dist-server/ws/extractors/echarts-extractor.js +1 -0
  353. package/vendor/dist-server/ws/extractors/eui-extractor.js +1 -0
  354. package/vendor/dist-server/ws/extractors/form-extractor.js +1 -0
  355. package/vendor/dist-server/ws/extractors/index.js +1 -0
  356. package/vendor/dist-server/ws/extractors/leaflet-extractor.js +1 -0
  357. package/vendor/dist-server/ws/extractors/mantine-extractor.js +1 -0
  358. package/vendor/dist-server/ws/extractors/markdown-extractor.js +7 -0
  359. package/vendor/dist-server/ws/extractors/mermaid-extractor.js +1 -0
  360. package/vendor/dist-server/ws/extractors/recharts-extractor.js +1 -0
  361. package/vendor/dist-server/ws/extractors/remotion-extractor.js +1 -0
  362. package/vendor/dist-server/ws/handler.js +66 -0
  363. package/vendor/dist-server/ws/parsers/anthropic-parser.js +7 -0
  364. package/vendor/dist-server/ws/parsers/base-parser.js +3 -0
  365. package/vendor/dist-server/ws/parsers/gemini-parser.js +8 -0
  366. package/vendor/dist-server/ws/parsers/index.js +1 -0
  367. package/vendor/dist-server/ws/parsers/parse-json-blocks.js +1 -0
  368. package/vendor/dist-server/ws/types.js +0 -0
  369. package/vendor/dist-server/ws/utils.js +1 -0
  370. package/vendor/shared/engine-vars.ts +51 -0
  371. package/vendor/shared/llm-providers-config.ts +69 -0
@@ -0,0 +1 @@
1
+ import{Client as b}from"@elastic/elasticsearch";import{config as S}from"../config";import{wilsonLowerBound as _,bayesianSmooth as T,computeQ as x,classifyQuadrant as E,coerceBool as R,coerceNumber as A,isSuccessfulExecution as M,isEmptyOutput as D,V1_Q_WEIGHTS as O}from"./tool-scoring";const m=new b(S.elasticsearch),k=".stkxp_chat_tools",I=".stkxp_tools",g=".stkxp_tool_metrics",v=["7d","30d","90d"],H=parseFloat(process.env.TOOL_METRICS_Q_THRESHOLD??"0.7"),W=parseInt(process.env.TOOL_METRICS_V_THRESHOLD??"10",10);async function $(){try{if(await m.indices.exists({index:g}))return;await m.indices.create({index:g,body:{settings:{number_of_shards:1,number_of_replicas:1},mappings:{properties:{name:{type:"keyword"},system:{type:"keyword"},owner:{type:"keyword"},window:{type:"keyword"},volume:{type:"integer"},callCount:{type:"integer"},scoreExec:{type:"float"},scoreArgs:{type:"float"},scoreUtil:{type:"float"},Q:{type:"float"},errorRate:{type:"float"},malformedArgRate:{type:"float"},emptyResultRate:{type:"float"},avgDurationMs:{type:"float"},quadrant:{type:"keyword"},hasDef:{type:"boolean"},defMatchCount:{type:"integer"},toolIds:{type:"keyword"},sampleErrors:{type:"object",enabled:!1},updatedAt:{type:"date"}}}}}),console.log(`[tool-metrics] created index ${g}`)}catch(e){throw console.error("[tool-metrics] failed to initialize index:",e),e}}async function L(e){await $();const o=await Q(e);if(o.size===0)return console.log(`[tool-metrics] window=${e}: no tool calls found`),[];const r=await N([...o.keys()]),l=new Date().toISOString(),n=[];for(const t of o.values()){const s=r.get(t.name)??[],f=s[0],u=_(t.successCount,t.callCount),i=t.callCount>0?t.emptyCount/t.callCount:0,a=T(t.callCount-t.emptyCount,t.callCount),c=t.callCount>0?(t.callCount-t.successCount)/t.callCount:0,y=t.durationCount>0?t.durationSum/t.durationCount:null,d=x({scoreExec:u,scoreUtil:a},O),h=E(d,t.callCount,{qThreshold:H,vThreshold:W});n.push({name:t.name,system:f?.system??null,owner:f?.owner??null,window:e,volume:t.callCount,callCount:t.callCount,scoreExec:u,scoreArgs:null,scoreUtil:a,Q:d,errorRate:c,malformedArgRate:null,emptyResultRate:i,avgDurationMs:y,quadrant:h,hasDef:s.length>0,defMatchCount:s.length,toolIds:s.map(C=>C.id),sampleErrors:t.sampleErrors,updatedAt:l})}return await q(n,e),console.log(`[tool-metrics] window=${e}: upserted ${n.length} tool metrics`),n}async function w(){const e={};for(const o of v)try{const r=await L(o);e[o]=r.length}catch(r){console.error(`[tool-metrics] recompute failed for window=${o}:`,r),e[o]=0}return e}async function Q(e){const o=new Map,r=1e3,l={query:{range:{createdAt:{gte:`now-${e}`}}},_source:["tools.name","tools.error","tools.status","tools.empty","tools.output","tools.duration"],size:r,sort:[{createdAt:{order:"asc"}}]};let n;for(;;){const s=(await m.search({index:k,body:n?{...l,search_after:n}:l})).hits?.hits??[];if(s.length===0)break;for(const f of s){const u=f._source?.tools;if(Array.isArray(u))for(const i of u){const a=typeof i?.name=="string"?i.name:null;if(!a)continue;let c=o.get(a);c||(c={name:a,callCount:0,successCount:0,emptyCount:0,durationSum:0,durationCount:0,sampleErrors:[]},o.set(a,c)),c.callCount+=1;const y=M(i);y&&(c.successCount+=1),D(i)&&(c.emptyCount+=1);const d=A(i.duration);if(d!==null&&(c.durationSum+=d,c.durationCount+=1),!y&&c.sampleErrors.length<5){const h=z(i.output)??`status=${i.status} error=${i.error}`;c.sampleErrors.push(h.slice(0,300))}}}if(s.length<r)break;n=s[s.length-1].sort}return o}async function N(e){const o=new Map;if(e.length===0)return o;try{const r=await m.search({index:I,body:{query:{terms:{name:e}},_source:["name","system","owner","enabled"],size:1e4}});for(const l of r.hits?.hits??[]){const n=l._source??{},t=n.name;if(!t)continue;const s=o.get(t)??[];s.push({id:l._id,system:n.system??null,owner:n.owner??null,enabled:R(n.enabled,!0)}),o.set(t,s)}}catch(r){console.warn("[tool-metrics] tool-def join failed (scores computed without enrichment):",r)}return o}async function q(e,o){if(e.length===0)return;const r=[];for(const n of e)r.push({index:{_index:g,_id:`${n.name}::${o}`}}),r.push(n);const l=await m.bulk({operations:r,refresh:!0});if(l.errors){const n=l.items?.find(t=>t.index?.error)?.index?.error;console.error("[tool-metrics] bulk upsert had errors:",n)}}function z(e){if(e==null)return null;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return null}}let p=null;function V(e=360*60*1e3){if(p){console.warn("[tool-metrics] scheduler already running");return}console.log(`[tool-metrics] scheduler started \u2014 tick every ${e/1e3/60}min`),setTimeout(()=>{w().catch(o=>console.error("[tool-metrics] initial recompute failed:",o))},3e4),p=setInterval(()=>{w().catch(o=>console.error("[tool-metrics] tick failed:",o))},e)}function X(){p&&(clearInterval(p),p=null,console.log("[tool-metrics] scheduler stopped"))}export{v as SCORING_WINDOWS,$ as initializeToolMetricsIndex,w as recomputeAllToolMetrics,L as recomputeToolMetrics,V as startToolMetricsScheduler,X as stopToolMetricsScheduler,z as stringifySample};
@@ -0,0 +1 @@
1
+ const a={exec:.5,args:.25,util:.25};function p(e,n,r=1.96){if(n<=0)return 0;const i=Math.max(0,Math.min(e,n))/n,u=r*r,o=1+u/n,m=i+u/(2*n),b=r*Math.sqrt((i*(1-i)+u/(4*n))/n),l=(m-b)/o;return s(l)}function h(e,n,r=.6,t=20){if(n<0||t<=0)return s(r);const u=(Math.max(0,Math.min(e,n))+r*t)/(n+t);return s(u)}function d(e,n=a){const r=[];c(e.scoreExec)&&r.push({value:e.scoreExec,weight:n.exec}),c(e.scoreArgs)&&r.push({value:e.scoreArgs,weight:n.args}),c(e.scoreUtil)&&r.push({value:e.scoreUtil,weight:n.util});const t=r.reduce((u,o)=>u+o.weight,0);if(t<=0)return null;const i=r.reduce((u,o)=>u+o.value*o.weight,0);return s(i/t)}function g(e,n,r){const t=c(e)&&e>=r.qThreshold;return n>=r.vThreshold?t?"boost":"fix":t?"niche":"disable"}function f(e,n=!1){if(typeof e=="boolean")return e;if(typeof e=="number")return e!==0;if(typeof e=="string"){const r=e.trim().toLowerCase();if(r==="true"||r==="1")return!0;if(r==="false"||r==="0"||r==="")return!1}return n}function x(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()!==""){const n=Number(e);if(Number.isFinite(n))return n}return null}function y(e){if(f(e.error))return!1;const n=typeof e.status=="string"?e.status.trim().toLowerCase():"";return!(n==="error"||n==="failed"||n==="failure")}function w(e){if(e.empty!==void 0&&e.empty!==null)return f(e.empty);const n=e.output;if(n==null)return!0;if(typeof n=="string"){const r=n.trim();if(r===""||r==="[]"||r==="{}"||r==="null")return!0;const t=r.toLowerCase();return!!(t.includes("no results")||t.includes("no data"))}return Array.isArray(n)?n.length===0:typeof n=="object"?Object.keys(n).length===0:!1}function s(e){return!Number.isFinite(e)||e<0?0:e>1?1:e}function c(e){return typeof e=="number"&&Number.isFinite(e)}export{a as V1_Q_WEIGHTS,h as bayesianSmooth,g as classifyQuadrant,f as coerceBool,x as coerceNumber,d as computeQ,w as isEmptyOutput,y as isSuccessfulExecution,p as wilsonLowerBound};
@@ -0,0 +1 @@
1
+ function i(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"").slice(0,40)}function p(e){let t=0;for(let n=0;n<e.length;n++)t=Math.imul(31,t)+e.charCodeAt(n)|0;return Math.abs(t).toString(36).slice(0,6).padStart(6,"0")}function l(e){return e.replace(/[-_]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function u(e){if(e.type==="elasticsearch")return{url:e.addresses?.[0]??"",port:"",database:null};const t={url:e.host??"",port:e.port!==void 0?String(e.port):"",database:e.database??null};return e.protocol!==void 0&&(t.protocol=e.protocol),e.secure!==void 0&&(t.secure=e.secure),t}function c(e){return e.endsWith("-esql")?"esql":e}function g(e,t){return t.type==="elasticsearch"?e.statement.match(/FROM\s+([\w.*-]+)/i)?.[1]??"":t.database??""}function m(e){if(!e?.length)return{};const t={},n=[];for(const o of e){const r={type:o.type};o.description&&(r.description=o.description),o.minValue!==void 0&&(r.minimum=o.minValue),o.maxValue!==void 0&&(r.maximum=o.maxValue),t[o.name]=r,n.push(o.name)}return{type:"object",properties:t,required:n,additionalProperties:!1}}function d(e,t){const n=u(e);return{name:e.name,type:e.type,managedType:"self-hosted",enabled:!0,owner:t,config:{endpoints:{[e.type]:n},access:{user:e.user??null,password:e.password??null,apikey:e.apikey??null,certificate:null}}}}function f(e,t,n,o){const r=t.type,a=i(t.name),s=`${i(r)}_${i(e.name)}_${p(`${r}:${e.name}:${o}`)}`;return{name:s,unique_path:s,system:a,description:e.description?.trim()??"",status:"active",category:"custom_query",query:e.statement.trim(),query_language:c(e.type),aggs:"",index_template:"",index_pattern:g(e,t),has_template:!1,platformId:n,namespace:i(t.name),owner:o}}function y(e,t,n,o,r){const a=i(t.name);return{name:e.name,label:l(e.name),description:e.description?.trim()??"",type:"mcp",system:n.system,service:n.unique_path,endpoint:`/api/stack_expert/${n.system}/${a}/${n.unique_path}`,httpMethod:"POST",inputSchema:JSON.stringify(m(e.parameters)),outputSchema:"{}",enabled:!0,apiDocId:n.unique_path,platformId:o,owner:r}}export{g as deriveIndexPattern,p as hash6,l as humanize,c as normalizeQueryLanguage,m as parametersToJsonSchema,i as slugify,d as sourceToPlatform,f as toolToApi,y as toolToTool};
@@ -0,0 +1 @@
1
+ import{Client as k}from"@elastic/elasticsearch";import*as v from"js-yaml";import{z as t,ZodError as P}from"zod";import R from"axios";import O from"https";import{sourceToPlatform as B,toolToApi as C,toolToTool as D,slugify as A}from"./toolbox-import-mappers";const q=process.env.ELASTICSEARCH_HOST||"https://51.159.174.230:9205",$=process.env.ELASTICSEARCH_USER||"elastic",j=process.env.ELASTICSEARCH_PASSWORD||"",S=".stkxp_platforms",_=".stkxp_api",b=".stkxp_tools",h=new k({node:q,auth:{username:$,password:j},tls:{rejectUnauthorized:!1},requestTimeout:6e4,maxRetries:3}),U=new O.Agent({rejectUnauthorized:!1});async function I(){const p=(process.env.MCP_URL||"https://localhost:3001/mcp").replace(/\/mcp$/,"");try{await R.post(`${p}/cache/reload`,{},{httpsAgent:U,timeout:5e3}),console.log("[ToolboxImport] MCP server cache reloaded")}catch(e){console.warn("[ToolboxImport] MCP reload notification failed (non-blocking):",e.message)}}async function E(){const p=process.env.STKXP_API_URL||"http://localhost:4000";try{await R.post(`${p}/api/routes/reload`,{},{timeout:1e4}),console.log("[ToolboxImport] stkxp-api routes reloaded")}catch(e){console.warn("[ToolboxImport] stkxp-api route reload failed (non-blocking):",e.message)}}const L=t.object({kind:t.string().optional(),name:t.string().optional(),type:t.enum(["postgres","clickhouse","elasticsearch","mysql"]),host:t.string().optional(),port:t.union([t.string(),t.number()]).optional(),database:t.string().optional(),user:t.string().optional(),password:t.string().optional(),addresses:t.array(t.string()).optional(),apikey:t.string().optional(),protocol:t.string().optional(),secure:t.boolean().optional()}),M=t.object({name:t.string(),type:t.enum(["string","integer","number","boolean"]),description:t.string().optional(),minValue:t.number().optional(),maxValue:t.number().optional()}),N=t.object({kind:t.string().optional(),name:t.string().optional(),type:t.string(),source:t.string(),statement:t.string(),description:t.string().optional(),parameters:t.array(M).optional()}),z=t.object({sources:t.record(t.string(),L),tools:t.record(t.string(),N)});function F(p){let e;try{e=v.load(p)}catch(l){throw new Error(`YAML parsing failed: ${l.message}`)}const d=z.parse(e),n={};for(const[l,g]of Object.entries(d.sources))n[l]={...g,name:g.name??l};const r={};for(const[l,g]of Object.entries(d.tools))r[l]={...g,name:g.name??l};return{sources:n,tools:r}}async function w(p,e,d){try{const n=await h.search({index:p,size:1,body:{query:{bool:{must:[{bool:{should:[{term:{name:e}},{term:{"name.keyword":e}}],minimum_should_match:1}},{term:{owner:d}}]}}}});if(n.hits.hits.length===0)return null;const r=n.hits.hits[0];return{_id:r._id,_source:r._source}}catch(n){if(n.meta?.statusCode===404)return null;throw n}}function H(){return`platform_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}async function et(p,e,d={}){const n=!!d.dryRun,r={dryRun:n,platforms:[],apis:[],tools:[],errors:[]};let l;try{l=F(p)}catch(o){throw o instanceof P?o:new Error(o.message??String(o))}const g={};for(const[,o]of Object.entries(l.sources))try{const c=B(o,e),i=await w(S,o.name,e),m=new Date().toISOString();if(i){const s=i._source.id??i._id,a={...i._source,...c,id:s,created:i._source.created??m,updated:m};n||await h.index({index:S,id:i._id,body:a,refresh:"wait_for"}),g[o.name]=s,r.platforms.push({action:"update",name:o.name,id:s})}else{const s=H(),a={...c,id:s,created:m,updated:m};n||await h.index({index:S,id:s,body:a,refresh:"wait_for"}),g[o.name]=s,r.platforms.push({action:"create",name:o.name,id:s})}}catch(c){r.errors.push({section:"sources",name:o.name,message:c.message??String(c)})}const x={};for(const o of Object.values(l.sources))x[o.name]=o;for(const[,o]of Object.entries(l.tools))try{const c=x[o.source];if(!c){r.errors.push({section:"tools",name:o.name,message:`Source "${o.source}" not found in YAML sources section`});continue}const i=g[c.name];if(!i){r.errors.push({section:"tools",name:o.name,message:`Platform for source "${c.name}" not available (creation failed above)`});continue}const m=new Date().toISOString(),s=C(o,c,i,e),a=await w(_,s.name,e);if(a){const y={...a._source,...s,createdAt:a._source.createdAt??m,createdBy:a._source.createdBy??e,updatedAt:m,updatedBy:e};n||await h.index({index:_,id:a._id,body:y,refresh:"wait_for"}),r.apis.push({action:"update",name:s.name,unique_path:s.unique_path,platformId:i})}else{const y={...s,createdAt:m,createdBy:e,updatedAt:m,updatedBy:e};n||await h.index({index:_,id:s.unique_path,body:y,refresh:"wait_for"}),r.apis.push({action:"create",name:s.name,unique_path:s.unique_path,platformId:i})}const u=D(o,c,s,i,e),f=await w(b,u.name,e);if(f){const y={...f._source,...u,createdAt:f._source.createdAt??m,createdBy:f._source.createdBy??e,updatedAt:m,updatedBy:e};n||await h.index({index:b,id:f._id,body:y,refresh:"wait_for"}),r.tools.push({action:"update",name:u.name,id:f._id,system:u.system,platformId:i})}else{const y={...u,createdAt:m,createdBy:e,updatedAt:m,updatedBy:e};let T;n||(T=(await h.index({index:b,body:y,refresh:"wait_for"}))._id),r.tools.push({action:"create",name:u.name,id:T,system:u.system,platformId:i})}}catch(c){r.errors.push({section:"tools",name:o.name,message:c.message??String(c)})}return!n&&(r.apis.length>0||r.tools.length>0)&&(I(),E()),r}const Y=new Set(["postgres","clickhouse","elasticsearch","mysql"]);async function ot(p,e){let d;try{const a=await h.get({index:S,id:p});d={_id:a._id,...a._source}}catch(a){throw a.meta?.statusCode===404?new Error(`Platform "${p}" not found`):a}if(d.owner!==e)throw new Error("Platform not owned by user");if(!Y.has(d.type))throw new Error(`Refresh only supported for data-source platforms (postgres, clickhouse, elasticsearch, mysql). This platform has type "${d.type}".`);const n=d.type,r=A(d.name),l=A(d.name),x=d.config?.endpoints?.[n]?.database??"",o=new Date().toISOString(),c=await h.search({index:_,size:1e3,body:{query:{bool:{must:[{term:{platformId:p}},{term:{owner:e}}]}}}}),i=[];for(const a of c.hits.hits){const u=a._source,f={system:r,namespace:l,updatedAt:o,updatedBy:e};if(n==="elasticsearch"){const y=String(u.query??"").match(/FROM\s+([\w.*-]+)/i);f.index_pattern=y?.[1]??u.index_pattern??""}else f.index_pattern=x;i.push({update:{_index:_,_id:a._id}}),i.push({doc:f})}i.length>0&&await h.bulk({refresh:"wait_for",body:i});const m=await h.search({index:b,size:1e3,body:{query:{bool:{must:[{term:{platformId:p}},{term:{owner:e}}]}}}}),s=[];for(const a of m.hits.hits){const u=a._source,f=u.apiDocId??u.service;if(!f)continue;const y={system:r,endpoint:`/api/stack_expert/${r}/${l}/${f}`,updatedAt:o,updatedBy:e};s.push({update:{_index:b,_id:a._id}}),s.push({doc:y})}return s.length>0&&await h.bulk({refresh:"wait_for",body:s}),(i.length>0||s.length>0)&&(I(),E()),{platformId:p,platformName:d.name,platformType:n,apisUpdated:c.hits.hits.length,toolsUpdated:s.length/2}}export{et as importToolboxYaml,F as parseToolboxYaml,ot as refreshToolboxDerived};
@@ -0,0 +1 @@
1
+ import{randomBytes as l}from"crypto";import{makeOwnerScopedClient as d}from"../utils/owner-scope";const p=process.env.ELASTICSEARCH_HOST||"https://51.159.174.230:9205",u=process.env.ELASTICSEARCH_USER||"elastic",y=process.env.ELASTICSEARCH_PASSWORD||"",o=".stkxp_triggers",i=d({node:p,auth:{username:u,password:y},tls:{rejectUnauthorized:!1},requestTimeout:3e4,maxRetries:3});async function T(){try{if(!await i.indices.exists({index:o}))console.log(`[TriggerService] Creating index: ${o}`),await i.indices.create({index:o,body:{mappings:{properties:{id:{type:"keyword"},name:{type:"text"},description:{type:"text"},type:{type:"keyword"},target:{type:"keyword"},targetTeamId:{type:"keyword"},replyChannel:{type:"keyword"},replyHmacSecret:{type:"keyword"},streamingEnabled:{type:"boolean"},streamingBatchMs:{type:"integer"},schedule:{type:"keyword"},webhookSecret:{type:"keyword"},inputTemplate:{type:"object",enabled:!1},enabled:{type:"boolean"},policies:{type:"object",enabled:!1},lastRun:{type:"date"},nextRun:{type:"date"},runCount:{type:"integer"},createdAt:{type:"date"},updatedAt:{type:"date"},owner:{type:"keyword"}}}}}),console.log(`[TriggerService] Index created: ${o}`);else try{await i.indices.putMapping({index:o,body:{properties:{targetTeamId:{type:"keyword"},replyChannel:{type:"keyword"},replyHmacSecret:{type:"keyword"},streamingEnabled:{type:"boolean"},streamingBatchMs:{type:"integer"}}}})}catch(e){String(e?.message||"").match(/illegal_argument|mapper_parsing/)||console.warn("[TriggerService] putMapping(V2.1/V2.2/V2.5 fields) warning:",e?.message)}}catch(r){throw console.error("[TriggerService] Failed to ensure index:",r),r}}async function S(r){try{const e=new Date().toISOString(),t={...r,createdAt:e,updatedAt:e,runCount:0};return await i.index({index:o,id:r.id,document:t,refresh:"wait_for"}),console.log(`[TriggerService] Trigger created: ${r.id}`),r.id}catch(e){throw console.error("[TriggerService] Failed to create trigger:",e),e}}async function g(r){try{return(await i.get({index:o,id:r}))._source}catch(e){if(e.meta?.statusCode===404)return null;throw console.error("[TriggerService] Failed to get trigger:",e),e}}async function h(r){try{const e=[];r?.type&&e.push({term:{type:r.type}}),r?.enabled!==void 0&&e.push({term:{enabled:r.enabled}}),r?.owner&&e.push({term:{owner:r.owner}});const t=e.length>0?{bool:{must:e}}:{match_all:{}};return(await i.search({index:o,body:{query:t,size:1e3,sort:[{createdAt:{order:"desc",unmapped_type:"date"}}]}})).hits.hits.map(a=>a._source)}catch(e){if(e.meta?.statusCode===404)return[];throw console.error("[TriggerService] Failed to list triggers:",e),e}}async function x(r,e){try{return(await i.search({index:o,size:1e3,body:{query:{bool:{must:[{term:{type:"webhook"}},{term:{enabled:!0}},{term:{owner:e}}]}}}})).hits.hits.map(a=>a._source).filter(a=>a.inputTemplate?.asyncapi?.platformId===r)}catch(t){if(t.meta?.statusCode===404)return[];throw t}}async function s(r,e){try{const t=new Date().toISOString(),n={...e,updatedAt:t};await i.update({index:o,id:r,doc:n,refresh:"wait_for"}),console.log(`[TriggerService] Trigger updated: ${r}`)}catch(t){throw console.error("[TriggerService] Failed to update trigger:",t),t}}async function f(r){try{await i.delete({index:o,id:r,refresh:"wait_for"}),console.log(`[TriggerService] Trigger deleted: ${r}`)}catch(e){throw console.error("[TriggerService] Failed to delete trigger:",e),e}}async function b(r,e){try{const t=new Date().toISOString();e===null?await i.update({index:o,id:r,refresh:"wait_for",body:{script:{source:'ctx._source.remove("targetTeamId"); ctx._source.updatedAt = params.now',params:{now:t}}}}):await s(r,{targetTeamId:e}),console.log(`[TriggerService] Trigger target updated: ${r} -> ${e??"(cleared)"}`)}catch(t){throw console.error("[TriggerService] Failed to set trigger target:",t),t}}function c(){return l(16).toString("hex")}async function v(r,e){try{const t=new Date().toISOString();if(e===null)await i.update({index:o,id:r,refresh:"wait_for",body:{script:{source:'ctx._source.remove("replyChannel"); ctx._source.updatedAt = params.now',params:{now:t}}}});else{const n=await g(r),a={replyChannel:e};n?.replyHmacSecret||(a.replyHmacSecret=c()),await s(r,a)}console.log(`[TriggerService] Trigger reply channel updated: ${r} -> ${e??"(cleared)"}`)}catch(t){throw console.error("[TriggerService] Failed to set trigger reply channel:",t),t}}async function C(r){try{const e=c();return await s(r,{replyHmacSecret:e}),console.log(`[TriggerService] Trigger reply HMAC secret rotated: ${r}`),e}catch(e){throw console.error("[TriggerService] Failed to rotate reply HMAC secret:",e),e}}async function _(r,e,t){try{const n={streamingEnabled:e};typeof t=="number"&&Number.isFinite(t)&&t>=0&&(n.streamingBatchMs=Math.min(t,5e3)),await s(r,n),console.log(`[TriggerService] Trigger streaming ${e?"enabled":"disabled"}: ${r}`+(t!==void 0?` (batchMs=${t})`:""))}catch(n){throw console.error("[TriggerService] Failed to set trigger streaming:",n),n}}async function A(r,e){try{await s(r,{enabled:e}),console.log(`[TriggerService] Trigger status updated: ${r} -> ${e?"enabled":"disabled"}`)}catch(t){throw console.error("[TriggerService] Failed to update trigger status:",t),t}}async function E(r){try{const e=await g(r);if(!e)throw new Error(`Trigger not found: ${r}`);const t=new Date().toISOString();await s(r,{lastRun:t,runCount:(e.runCount||0)+1}),console.log(`[TriggerService] Trigger execution recorded: ${r}`)}catch(e){throw console.error("[TriggerService] Failed to record trigger execution:",e),e}}export{S as createTrigger,f as deleteTrigger,T as ensureIndex,c as generateReplySecret,g as getTrigger,x as getTriggersBySubscriberPlatform,h as listTriggers,E as recordTriggerExecution,C as rotateReplyHmacSecret,v as setTriggerReplyChannel,_ as setTriggerStreaming,b as setTriggerTarget,s as updateTrigger,A as updateTriggerStatus};
@@ -0,0 +1 @@
1
+ import{Client as S}from"@elastic/elasticsearch";const g=process.env.ELASTICSEARCH_HOST||"https://51.159.174.230:9205",l=process.env.ELASTICSEARCH_USER||"elastic",m=process.env.ELASTICSEARCH_PASSWORD||"",t=".stkxp_versions",n=new S({node:g,auth:{username:l,password:m},tls:{rejectUnauthorized:!1},requestTimeout:6e4,maxRetries:3});let c=!1;async function d(){if(c)return;await n.indices.exists({index:t})||(console.log(`[VersionSnapshot] Creating index: ${t}`),await n.indices.create({index:t,body:{mappings:{properties:{entityType:{type:"keyword"},entityId:{type:"keyword"},version:{type:"integer"},payload:{type:"object",enabled:!1},changeSource:{type:"keyword"},changeSummary:{type:"text"},owner:{type:"keyword"},created_at:{type:"date"}}}}})),c=!0}async function x(e,r){return await d(),(await n.search({index:t,body:{size:200,query:{bool:{filter:[{term:{entityType:e}},{term:{entityId:r}}]}},sort:[{version:{order:"desc"}}]}})).hits.hits.map(s=>s._source)}async function E(e,r,o,s,p,y){await d();const i=await x(e,r),a=i.length>0?i[0].version+1:1,u={entityType:e,entityId:r,version:a,payload:o,changeSource:s,changeSummary:y,owner:p,created_at:new Date().toISOString()};return await n.index({index:t,body:u,refresh:"wait_for"}),a}export{d as ensureVersionsIndex,x as listVersions,E as snapshotBeforeUpdate};
@@ -0,0 +1 @@
1
+ import{Client as d}from"@elastic/elasticsearch";import{createHash as c}from"crypto";import{config as p}from"../config";const n=new d(p.elasticsearch),o=".stkxp_webhook_calls",y=new Set(["authorization","cookie","set-cookie","x-stkxp-webhook-token","x-api-key","proxy-authorization"]);function b(e){const t={};for(const[r,a]of Object.entries(e)){const s=r.toLowerCase();y.has(s)||a!==void 0&&(t[s]=Array.isArray(a)?a.join(", "):String(a))}return t}function m(e){try{return c("sha256").update(JSON.stringify(e??null)).digest("hex")}catch{return"unknown"}}let i=!1;async function u(){if(!i)try{await n.indices.putMapping({index:o,body:{properties:{replyTargetUrl:{type:"keyword"},replyAttemptedAt:{type:"date"},replyHttpStatus:{type:"short"},replyBodySize:{type:"long"},replyError:{type:"text"}}}}),i=!0}catch(e){e?.meta?.statusCode===400?i=!0:console.warn("[WebhookCalls] putMapping(V2.2 reply fields) warning:",e?.message)}}async function l(){try{if(await n.indices.exists({index:o})){await u();return}await n.indices.create({index:o,body:{settings:{number_of_shards:1,number_of_replicas:1},mappings:{properties:{webhookCallId:{type:"keyword"},receivedAt:{type:"date"},teamId:{type:"keyword"},triggerId:{type:"keyword"},channel:{type:"keyword"},owner:{type:"keyword"},sourceIp:{type:"keyword"},status:{type:"keyword"},rejectionReason:{type:"keyword"},payload:{type:"object",enabled:!1},payloadHash:{type:"keyword"},headers:{type:"object",enabled:!1},runId:{type:"keyword"},chatId:{type:"keyword"},durationMs:{type:"long"},error:{type:"text"},replyTargetUrl:{type:"keyword"},replyAttemptedAt:{type:"date"},replyHttpStatus:{type:"short"},replyBodySize:{type:"long"},replyError:{type:"text"},source:{type:"keyword"}}}}}),console.log(`[WebhookCalls] Created index: ${o}`),i=!0}catch(e){e?.meta?.statusCode!==400&&console.error("[WebhookCalls] Error initializing index:",e?.message)}}async function w(e){try{await l();const{id:t,...r}=e;await n.index({index:o,id:e.webhookCallId,body:r})}catch(t){console.error(`[WebhookCalls] Failed to log webhook call ${e.webhookCallId}:`,t?.message)}}async function f(e,t){try{await n.update({index:o,id:e,body:{doc:t}})}catch(r){r?.meta?.statusCode!==404&&console.error(`[WebhookCalls] Failed to update webhook call ${e}:`,r?.message)}}async function x(e,t=3600*1e3){try{await l();const r=new Date(Date.now()-t).toISOString();return(await n.count({index:o,body:{query:{bool:{must:[{term:{teamId:e}},{terms:{status:["accepted","completed","completed_reply_sent","completed_reply_failed","failed"]}},{range:{receivedAt:{gte:r}}}]}}}}))?.count??0}catch(r){return console.warn(`[WebhookCalls] countTeamWebhookRunsSince(${e}) failed \u2014 returning 0:`,r?.message),0}}async function C(e){try{const t=await n.get({index:o,id:e});return{id:t._id,...t._source}}catch(t){return t?.meta?.statusCode===404||console.error(`[WebhookCalls] Failed to fetch webhook call ${e}:`,t?.message),null}}export{x as countTeamWebhookRunsSince,C as getWebhookCallById,m as hashPayload,w as logWebhookCall,b as sanitiseHeaders,f as updateWebhookCall};
@@ -0,0 +1,46 @@
1
+ import{DynamicStructuredTool as b}from"@langchain/core/tools";import{z as u}from"zod";import{getChatById as D,getUserChats as x}from"../services/chats-service";import{createLLMInstance as M}from"../llm/providers";import{SystemMessage as L,HumanMessage as S}from"@langchain/core/messages";function w(n){const s=[],t=n.filter(r=>r.role==="user"),o=n.filter(r=>r.role==="assistant");if(s.push(`User Messages Count: ${t.length}`),s.push(`Assistant Messages Count: ${o.length}`),t.length>0&&(s.push(`
2
+ First Question: ${t[0].content.substring(0,200)}...`),t.length>1&&s.push(`Last Question: ${t[t.length-1].content.substring(0,200)}...`)),o.length>0){const r=o[o.length-1];let e="";typeof r.content=="string"?e=r.content.substring(0,300):r.content&&typeof r.content=="object"&&(e=JSON.stringify(r.content).substring(0,300)),s.push(`
3
+ Last Response Preview: ${e}...`)}return s.join(`
4
+ `)}function C(n){const s={metrics:[],errors:[],warnings:[],configurations:[],timestamps:[]};return n.forEach(t=>{const o=typeof t.content=="string"?t.content:JSON.stringify(t.content),r=o.match(/(\d+(?:\.\d+)?)\s*(ms|MB|GB|%|requests?|errors?)/gi);if(r&&s.metrics.push(...r),o.toLowerCase().includes("error")){const e=o.split(`
5
+ `).filter(a=>a.toLowerCase().includes("error"));s.errors.push(...e.slice(0,3))}if(o.toLowerCase().includes("warning")){const e=o.split(`
6
+ `).filter(a=>a.toLowerCase().includes("warning"));s.warnings.push(...e.slice(0,3))}t.timestamp&&s.timestamps.push(t.timestamp)}),s}function O(n,s){return new b({name:"compare_with_previous_chat",description:`Compare the current conversation context with a previous chat to identify:
7
+ - Changes in system behavior
8
+ - Differences in metrics or performance
9
+ - Evolution of issues or errors
10
+ - Configuration changes
11
+ - Overall improvements or regressions
12
+
13
+ Use this tool when the user asks to compare with a previous state, reference an old chat,
14
+ or wants to know what changed since a previous analysis.`,schema:u.object({chatId:u.string().describe("ID of the previous chat to compare with. Ask the user for this ID if not provided."),comparisonAspects:u.array(u.enum(["metrics","errors","performance","configuration","overall","recommendations"])).optional().describe("Specific aspects to focus on in the comparison. Default is overall comparison."),includeTimeDelta:u.boolean().optional().describe("Whether to include time difference analysis between the two chats")}),func:async({chatId:t,comparisonAspects:o=["overall"],includeTimeDelta:r=!0})=>{try{console.log(`[CompareTool] Comparing current chat with chat ${t}`);let e=await D(t,n);if(!e){const{chats:h}=await x(n,0,200);e=h.find(m=>m.title?.toLowerCase()===t.toLowerCase())||null}if(!e)return JSON.stringify({error:!0,message:`Chat "${t}" not found. Please use the exact chat ID provided in the compare context.`});const a=w(e.messages),v=w(s),i=C(e.messages),c=C(s);let l="";if(r&&e.updatedAt){const h=new Date(e.updatedAt),g=new Date().getTime()-h.getTime(),f=Math.floor(g/(1e3*60*60*24)),d=Math.floor(g%(1e3*60*60*24)/(1e3*60*60));l=f>0?`${f} days and ${d} hours ago`:`${d} hours ago`}const y=M({provider:"anthropic",model:"claude-sonnet-4-5",temperature:.3,maxTokens:2e3}),p=`You are an expert system analyst comparing two conversation contexts.
15
+
16
+ # Previous Chat Context (${l||"older chat"})
17
+ Title: ${e.title}
18
+ Created: ${e.createdAt}
19
+ ${a}
20
+
21
+ # Previous Chat Structured Data
22
+ Metrics: ${i.metrics.slice(0,10).join(", ")}
23
+ Errors: ${i.errors.slice(0,5).join(", ")}
24
+ Warnings: ${i.warnings.slice(0,5).join(", ")}
25
+
26
+ # Current Chat Context (now)
27
+ ${v}
28
+
29
+ # Current Chat Structured Data
30
+ Metrics: ${c.metrics.slice(0,10).join(", ")}
31
+ Errors: ${c.errors.slice(0,5).join(", ")}
32
+ Warnings: ${c.warnings.slice(0,5).join(", ")}
33
+
34
+ # Comparison Aspects to Focus On
35
+ ${o.join(", ")}
36
+
37
+ # Task
38
+ Provide a structured comparison analysis covering:
39
+ 1. **Key Changes**: What has changed between the two contexts?
40
+ 2. **Improvements**: What has gotten better?
41
+ 3. **Regressions**: What has gotten worse?
42
+ 4. **New Issues**: What new problems appeared?
43
+ 5. **Resolved Issues**: What problems were fixed?
44
+ 6. **Recommendations**: What actions should be taken based on this comparison?
45
+
46
+ Be specific, use numbers and metrics when available, and highlight critical differences.`,$=await y.invoke([new L("You are an expert at analyzing and comparing system states and conversations."),new S(p)]);return console.log("[CompareTool]",p),JSON.stringify({success:!0,previousChatTitle:e.title,previousChatDate:e.updatedAt,timeDelta:l,comparisonAspects:o,analysis:$.content,rawData:{previousMetricsCount:i.metrics.length,currentMetricsCount:c.metrics.length,previousErrorsCount:i.errors.length,currentErrorsCount:c.errors.length}},null,2)}catch(e){return console.error("[CompareTool] Error:",e),JSON.stringify({error:!0,message:`Failed to compare chats: ${e.message}`})}}})}export{O as createCompareChatTool};
@@ -0,0 +1,50 @@
1
+ import{DynamicStructuredTool as S}from"@langchain/core/tools";import{z as g}from"zod";import{getChatById as D,getUserChats as T}from"../services/chats-service";import{createLLMInstance as I}from"../llm/providers";import{SystemMessage as M,HumanMessage as x}from"@langchain/core/messages";function E(a,r){return a.filter(s=>s.role==="assistant"||s.role==="agent").filter(s=>!r||r.size===0?!0:s.assistantId?r.has(s.assistantId):!1).map(s=>({assistantId:s.assistantId,assistantName:s.assistantName,content:typeof s.content=="string"?s.content:JSON.stringify(s.content)}))}function C(a){const r=[],s=a.filter(n=>n.role==="user"),i=a.filter(n=>n.role==="assistant"||n.role==="agent");if(s.length>0){const n=typeof s[0].content=="string"?s[0].content:JSON.stringify(s[0].content);r.push(`First question: ${n.substring(0,300)}`)}for(const n of i){const f=typeof n.content=="string"?n.content:JSON.stringify(n.content),e=n.assistantName?`[${n.assistantName}]`:"[Assistant]";r.push(`${e}: ${f.substring(0,800)}`)}return r.join(`
2
+
3
+ `)}function O(a,r,s,i,n,f,e){const u=e.length>0?e.join(", "):"overall insights";return`You are an expert analyst tasked with enriching a current analysis using perspectives from a different assistant or a prior analysis session.
4
+
5
+ # Reference Analysis (${s})
6
+ **Title:** ${a}
7
+ **Date:** ${r}
8
+ **Enriching perspectives from:** ${i.length>0?i.join(", "):"other assistants"}
9
+
10
+ ${n}
11
+
12
+ ---
13
+
14
+ # Current Analysis Context
15
+ ${f}
16
+
17
+ ---
18
+
19
+ # Enrichment Focus
20
+ ${u}
21
+
22
+ # Your Task
23
+ Based on the **reference analysis** above, enrich the current analysis with the following structure:
24
+
25
+ ## 1. Complementary Insights
26
+ Key findings from the reference analysis that are NOT already covered in the current context
27
+
28
+ ## 2. Additional Perspectives
29
+ Different angles or approaches taken by other assistants that add value
30
+
31
+ ## 3. Corroborating Evidence \u2705
32
+ Points where the reference analysis confirms or supports findings in the current analysis
33
+
34
+ ## 4. Contradictions / Alternative Views \u26A0\uFE0F
35
+ Where the reference analysis suggests a different interpretation or approach
36
+
37
+ ## 5. Gaps Filled
38
+ Information from the reference that fills missing context in the current analysis
39
+
40
+ ## 6. Recommended Actions \u{1F4A1}
41
+ Actionable next steps derived from combining both analyses
42
+
43
+ Be specific, cite data points or metrics when available, and focus on insights that genuinely add value to the current analysis.`}function B(a,r,s=[]){return new S({name:"enrich_from_previous_chat",description:`Enrich the current analysis with insights and perspectives from a previous chat session.
44
+ Use this tool when the user wants to:
45
+ - Incorporate findings from another assistant's analysis
46
+ - Cross-reference results from a different diagnostic session
47
+ - Combine perspectives from multiple analysis approaches
48
+ - Add context from a related previous investigation
49
+
50
+ Use this tool when the user asks to enrich with, reference, or incorporate insights from a previous chat.`,schema:g.object({chatId:g.string().describe("ID of the reference chat to enrich from. Ask the user for this ID if not provided."),enrichmentFocus:g.array(g.enum(["metrics","errors","recommendations","configuration","performance","security","overall"])).optional().describe("Specific aspects to focus on when enriching. Default is overall insights."),includeTimeDelta:g.boolean().optional().describe("Whether to include time difference analysis between the two chats")}),func:async({chatId:i,enrichmentFocus:n=["overall"],includeTimeDelta:f=!0})=>{try{console.log(`[EnrichTool] Enriching from chat ${i} for user ${a}`);let e=await D(i,a);if(!e){const{chats:t}=await T(a,0,200);if(e=t.find(o=>o.title?.toLowerCase()===i.toLowerCase())||null,!e){const o=i.replace(/[-_]/g," ").toLowerCase();e=t.find(c=>(c.title||"").replace(/[-_]/g," ").toLowerCase()===o)||null}if(!e){const o=i.replace(/[-_]/g," ").toLowerCase().split(/\s+/).filter(Boolean);e=t.find(c=>{const h=(c.title||"").toLowerCase();return o.length>=3&&o.every(l=>h.includes(l))})||null}if(!e){const o=t.slice(0,10).map(c=>({id:c.id,title:c.title}));return JSON.stringify({error:!0,message:`Chat "${i}" not found. Use one of the recent chat IDs below.`,recentChats:o})}}const u=new Set(s),y=(e.assistants||[]).filter(t=>t.assistantId&&!u.has(t.assistantId)),d=new Set(y.map(t=>t.assistantId)),p=y.map(t=>t.assistantName||t.assistantId),w=E(e.messages,d.size>0?d:void 0);if(w.length===0)return JSON.stringify({error:!1,warning:!0,message:`No enriching assistant messages found in chat "${e.title}". The reference chat may use the same assistants as the current session.`,referenceTitle:e.title});const A=C(e.messages),$=r.length>0?C(r.map(t=>({role:t.role||(t._getType?t._getType():"user"),content:typeof t.content=="string"?t.content:JSON.stringify(t.content),timestamp:t.timestamp||new Date().toISOString(),id:t.id||""}))):"No current conversation context available.";let m="previous session";if(f&&e.updatedAt){const t=new Date(e.updatedAt),c=new Date().getTime()-t.getTime(),h=Math.floor(c/(1e3*60*60*24)),l=Math.floor(c%(1e3*60*60*24)/(1e3*60*60));m=h>0?`${h} day${h>1?"s":""} and ${l} hour${l!==1?"s":""} ago`:`${l} hour${l!==1?"s":""} ago`}const b=I({provider:"anthropic",model:"claude-sonnet-4-5",temperature:.3,maxTokens:2e3}),v=O(e.title,e.updatedAt||e.createdAt,m,p,A,$,n);console.log("[EnrichTool]",v);const N=await b.invoke([new M("You are an expert analyst skilled at synthesizing insights from multiple diagnostic sessions and assistant perspectives."),new x(v)]);return JSON.stringify({success:!0,referenceChatTitle:e.title,referenceChatDate:e.updatedAt,timeDelta:m,enrichmentFocus:n,enrichingAssistants:p.length>0?p:["All assistants from reference chat"],newAssistantsCount:d.size,analysis:N.content,rawData:{referenceAssistantMessagesCount:w.length,currentThreadMessagesCount:r.length}},null,2)}catch(e){return console.error("[EnrichTool] Error:",e),JSON.stringify({error:!0,message:`Failed to enrich from chat: ${e.message}`})}}})}export{B as createEnrichChatTool};
@@ -0,0 +1 @@
1
+ import{z as p}from"zod";const S=p.object({name:p.string().regex(/^(?!__)[a-zA-Z_][a-zA-Z0-9_]*$/,{message:'"__" prefix is reserved for system variables'}),type:p.enum(["string","number","integer","boolean","array","object"]),description:p.string().optional(),required:p.boolean().optional().default(!1),default:p.any().optional()});function d(n){const i={};for(const[e,r]of Object.entries(n))e.startsWith("__")||(i[e]=r);return i}function E(n){const i=new Set,e=/\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}/g;let r;for(;(r=e.exec(n))!==null;)i.add(r[1]);return Array.from(i)}function b(n,i,e){if(e==null)throw new Error(`Missing value for variable "${n}"`);switch(i){case"string":{const r=typeof e=="string"?e:String(e);return JSON.stringify(r)}case"number":{const r=typeof e=="number"?e:Number(e);if(!Number.isFinite(r))throw new Error(`Variable "${n}" must be a finite number`);return JSON.stringify(r)}case"integer":{const r=typeof e=="number"?e:Number(e);if(!Number.isInteger(r))throw new Error(`Variable "${n}" must be an integer`);return JSON.stringify(r)}case"boolean":{if(typeof e=="boolean")return e?"true":"false";if(e==="true"||e===1)return"true";if(e==="false"||e===0)return"false";throw new Error(`Variable "${n}" must be a boolean`)}case"array":case"object":{if(typeof e=="string")try{const r=JSON.parse(e);return JSON.stringify(r)}catch{throw new Error(`Variable "${n}" must be a valid JSON ${i}`)}return JSON.stringify(e)}}}function a(n,i,e){if(e==null)throw new Error(`Missing value for variable "${n}"`);switch(i){case"string":return`"${(typeof e=="string"?e:String(e)).replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;case"number":{const r=typeof e=="number"?e:Number(e);if(!Number.isFinite(r))throw new Error(`Variable "${n}" must be a finite number`);return String(r)}case"integer":{const r=typeof e=="number"?e:Number(e);if(!Number.isInteger(r))throw new Error(`Variable "${n}" must be an integer`);return String(r)}case"boolean":{if(typeof e=="boolean")return e?"true":"false";if(e==="true"||e===1)return"true";if(e==="false"||e===0)return"false";throw new Error(`Variable "${n}" must be a boolean`)}case"array":case"object":throw new Error(`Variable "${n}": ES|QL inlining only supports scalar types (string/number/integer/boolean)`)}}function $(n,i,e,r){const f=d(e),u=new Map(i.map(g=>[g.name,g]));return n.replace(/\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}/g,(g,s)=>{if(s.startsWith("__")){const c=r?.[s];return c==null?'""':a(s,"string",String(c))}const o=u.get(s);if(!o)throw new Error(`Query references undeclared variable "{{${s}}}"`);const t=f[s]??o.default;if(t==null){if(o.required)throw new Error(`Missing value for required variable "${s}"`);return'""'}return a(s,o.type,t)})}function m(n,i,e){if(e==null)throw new Error(`Missing value for variable "${n}"`);switch(i){case"string":{const r=typeof e=="string"?e:String(e);return encodeURIComponent(r)}case"number":{const r=typeof e=="number"?e:Number(e);if(!Number.isFinite(r))throw new Error(`Variable "${n}" must be a finite number`);return encodeURIComponent(String(r))}case"integer":{const r=typeof e=="number"?e:Number(e);if(!Number.isInteger(r))throw new Error(`Variable "${n}" must be an integer`);return encodeURIComponent(String(r))}case"boolean":{if(typeof e=="boolean")return e?"true":"false";if(e==="true"||e===1)return"true";if(e==="false"||e===0)return"false";throw new Error(`Variable "${n}" must be a boolean`)}case"array":case"object":throw new Error(`Variable "${n}": URL inlining only supports scalar types (string/number/integer/boolean)`)}}function x(n,i,e,r){const f=d(e),u=new Map(i.map(g=>[g.name,g]));return n.replace(/\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}/g,(g,s)=>{if(s.startsWith("__")){const c=r?.[s];return c==null?"":m(s,"string",String(c))}const o=u.get(s);if(!o)throw new Error(`URL references undeclared variable "{{${s}}}"`);const t=f[s]??o.default;if(t==null){if(o.required)throw new Error(`Missing value for required variable "${s}"`);return""}return m(s,o.type,t)})}function h(n,i){const e=/\{\{([#^])\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}([\s\S]*?)\{\{\/\s*\2\s*\}\}/;let r=n,f=0;for(;e.test(r)&&f<100;)r=r.replace(e,(u,g,s,o)=>{const t=i(s);return(g==="#"?t:!t)?o:""}),f+=1;return r}function A(n,i,e,r){const f=d(e),u=new Map(i.map(o=>[o.name,o]));return h(n,o=>{let t;return o.startsWith("__")?t=r?.[o]:t=f[o]??u.get(o)?.default,t==null?!1:typeof t=="string"?t.trim()!=="":Array.isArray(t)?t.length>0:!0}).replace(/\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}/g,(o,t)=>{if(t.startsWith("__")){const l=r?.[t];return l==null?'""':b(t,"string",String(l))}const c=u.get(t);if(!c)throw new Error(`Query references undeclared variable "{{${t}}}"`);const y=f[t]??c.default;if(y==null){if(c.required)throw new Error(`Missing value for required variable "${t}"`);return"null"}return b(t,c.type,y)})}function k(n,i){if(!i||i.length===0)return n;const e={string:"string",number:"number",integer:"integer",boolean:"boolean",array:"array",object:"object"};let r={};if(n&&n.trim())try{r=JSON.parse(n)}catch{r={}}r.type!=="object"&&(r.type="object"),(!r.properties||typeof r.properties!="object")&&(r.properties={});const f=Array.isArray(r.required)?[...r.required]:[];for(const u of i)r.properties[u.name]={type:e[u.type],...u.description?{description:u.description}:{},...u.default!==void 0?{default:u.default}:{}},u.required&&!f.includes(u.name)&&f.push(u.name);return f.length>0&&(r.required=f),JSON.stringify(r,null,2)}export{S as QueryVariableSchema,A as applyDslVariables,$ as applyEsqlVariables,x as applyUrlVariables,E as detectQueryVariables,b as encodeVariableForDsl,a as encodeVariableForEsql,m as encodeVariableForUrl,k as mergeVariablesIntoInputSchema};
@@ -0,0 +1 @@
1
+ import{z as n}from"zod";const e=n.object({api_url:n.string().min(1),api_key:n.string().min(1).optional(),interval:n.string().min(1),ssl:n.string().min(1),username:n.string().optional(),password:n.string().optional()}),i=n.object({packageName:n.string().min(1),packageVersion:n.string().min(1),inputs:n.record(n.object({enabled:n.boolean(),vars:n.record(n.any()).optional()})).optional(),vars:n.record(n.any()).optional(),api_url:n.string().optional(),api_key:n.string().optional(),interval:n.string().optional(),ssl:n.string().optional(),username:n.string().optional(),password:n.string().optional(),oauth_id:n.string().optional(),oauth_secret:n.string().optional(),oauth_token_url:n.string().optional(),oauth_provider:n.string().optional(),oauth_scopes:n.array(n.string()).optional(),oauth_user:n.string().optional(),oauth_password:n.string().optional(),digest_username:n.string().optional(),digest_password:n.string().optional(),digest_no_reuse:n.boolean().optional()}),a=n.object({username:n.string().min(1),password:n.string().min(1),email:n.string().min(1),full_name:n.string().min(1)}),s=n.union([e,i]),o=n.object({username:n.string().min(1),password:n.string().min(1),email:n.string().min(1),full_name:n.string().min(1),metadata:n.object({namespace:n.string().min(1)})}),g=n.object({namespace:n.string().min(1)}),c=n.object({prerelease:n.string().optional().transform(t=>t==="true")}),p=n.object({packageName:n.string().min(1),packageVersion:n.string().min(1)}),l=n.object({packageName:n.string().min(1),packageVersion:n.string().min(1)});export{a as accountSignupSchema,o as accountUpdateSchema,e as connectionSchema,i as dynamicConnectionSchema,l as epmPackageParamsSchema,p as epmPackageQuerySchema,c as epmPackagesQuerySchema,s as flexibleConnectionSchema,g as namespaceSchema};
@@ -0,0 +1,5 @@
1
+ class I{enabled;results=new Map;constructor(t=!1){this.enabled=t,console.log(`[AB-EVAL] A/B Testing ${this.enabled?"ENABLED":"DISABLED"}`)}isEnabled(){return this.enabled}async runTest(t,a,...i){if(!this.enabled){const e=t.variants.find(s=>s.id===t.defaultVariantId);if(!e)throw new Error(`Default variant ${t.defaultVariantId} not found`);return await a(e,...i),{testId:t.testId,baseline:this.createEmptyResult(t.testId,e),variants:[],timestamp:Date.now()}}console.log(`
2
+ ${"=".repeat(80)}`),console.log(`[AB-EVAL] \u{1F9EA} Starting A/B Test: ${t.testId}`),console.log(`${"=".repeat(80)}`);const r=t.iterations||10,d=t.warmupRuns||2,m=[];for(const e of t.variants){if(e.enabled===!1){console.log(`[AB-EVAL] \u23ED\uFE0F Skipping disabled variant: ${e.name}`);continue}console.log(`
3
+ [AB-EVAL] \u{1F52C} Testing variant: ${e.name} (${e.id})`);const s=[],p=[];for(let n=0;n<d;n++)try{await a(e,...i)}catch(o){console.warn(`[AB-EVAL] \u26A0\uFE0F Warmup ${n+1} failed:`,o.message)}for(let n=0;n<r;n++){const o=Date.now();try{await a(e,...i);const v=Date.now()-o;s.push(v),console.log(`[AB-EVAL] Run ${n+1}/${r}: ${v}ms`)}catch(v){const B=Date.now()-o;s.push(B),p.push({iteration:n+1,error:v.message}),console.error(`[AB-EVAL] Run ${n+1}/${r}: ERROR (${B}ms) - ${v.message}`)}}const b=[...s].sort((n,o)=>n-o),$=r-p.length,g={testId:t.testId,variantId:e.id,variantName:e.name,iterations:r,metrics:{avgDuration:s.reduce((n,o)=>n+o,0)/s.length,minDuration:Math.min(...s),maxDuration:Math.max(...s),medianDuration:this.calculatePercentile(b,50),p95Duration:this.calculatePercentile(b,95),p99Duration:this.calculatePercentile(b,99),totalDuration:s.reduce((n,o)=>n+o,0),successRate:$/r*100,errorCount:p.length},rawDurations:s,errors:p,timestamp:Date.now()};m.push(g),console.log("[AB-EVAL] \u{1F4CA} Variant Results:"),console.log(` Avg: ${g.metrics.avgDuration.toFixed(2)}ms`),console.log(` Median: ${g.metrics.medianDuration.toFixed(2)}ms`),console.log(` P95: ${g.metrics.p95Duration.toFixed(2)}ms`),console.log(` Success Rate: ${g.metrics.successRate.toFixed(1)}%`)}this.results.set(t.testId,m);const l=m.find(e=>e.variantId===t.defaultVariantId);if(!l)throw new Error(`Baseline variant ${t.defaultVariantId} not found in results`);const D={testId:t.testId,baseline:l,variants:m.filter(e=>e.variantId!==t.defaultVariantId),timestamp:Date.now()},u=m.reduce((e,s)=>s.metrics.avgDuration<e.metrics.avgDuration?s:e);if(u.variantId!==l.variantId){const e=(l.metrics.avgDuration-u.metrics.avgDuration)/l.metrics.avgDuration*100;D.winner={variantId:u.variantId,improvement:e,metric:"avgDuration"}}return this.printComparison(D),D}async runWithSelection(t,a,...i){const r=t.variants.find(u=>u.id===t.defaultVariantId);if(!r)throw new Error(`Default variant ${t.defaultVariantId} not found`);if(!this.enabled)return{result:await a(r,...i),variantUsed:r.id};const d=await this.runTest(t,a,...i),m=d.winner?.variantId||t.defaultVariantId,l=t.variants.find(u=>u.id===m)||r;return{result:await a(l,...i),variantUsed:l.id,comparison:d}}getResults(t){return this.results.get(t)}getAllResults(){return this.results}clearResults(){this.results.clear()}calculatePercentile(t,a){if(t.length===0)return 0;const i=Math.ceil(a/100*t.length)-1;return t[Math.max(0,i)]}createEmptyResult(t,a){return{testId:t,variantId:a.id,variantName:a.name,iterations:0,metrics:{avgDuration:0,minDuration:0,maxDuration:0,medianDuration:0,p95Duration:0,p99Duration:0,totalDuration:0,successRate:100,errorCount:0},rawDurations:[],errors:[],timestamp:Date.now()}}printComparison(t){console.log(`
4
+ ${"=".repeat(80)}`),console.log(`[AB-EVAL] \u{1F4CA} COMPARISON SUMMARY: ${t.testId}`),console.log(`${"=".repeat(80)}`),console.log(`Baseline: ${t.baseline.variantName} (${t.baseline.variantId})`),console.log(` Avg: ${t.baseline.metrics.avgDuration.toFixed(2)}ms`),console.log(` Median: ${t.baseline.metrics.medianDuration.toFixed(2)}ms`),console.log(` P95: ${t.baseline.metrics.p95Duration.toFixed(2)}ms`),console.log(`${"\u2500".repeat(80)}`),t.variants.forEach(a=>{const i=a.metrics.avgDuration-t.baseline.metrics.avgDuration,r=i/t.baseline.metrics.avgDuration*100,d=i<0?"\u{1F7E2}":i>0?"\u{1F534}":"\u26AA";console.log(`${d} ${a.variantName} (${a.variantId})`),console.log(` Avg: ${a.metrics.avgDuration.toFixed(2)}ms (${r>0?"+":""}${r.toFixed(1)}%)`),console.log(` Median: ${a.metrics.medianDuration.toFixed(2)}ms`),console.log(` P95: ${a.metrics.p95Duration.toFixed(2)}ms`),console.log(` Success Rate: ${a.metrics.successRate.toFixed(1)}%`)}),t.winner&&(console.log(`${"\u2500".repeat(80)}`),console.log(`\u{1F3C6} WINNER: ${t.winner.variantId}`),console.log(` Improvement: ${t.winner.improvement.toFixed(1)}% faster than baseline`)),console.log(`${"=".repeat(80)}
5
+ `)}}let A=null;function h(c){if(!A){const t=c??process.env.AB_TESTING_ENABLED==="true";A=new I(t)}return A}function T(c){A&&(A.enabled=c,console.log(`[AB-EVAL] A/B Testing ${c?"ENABLED":"DISABLED"}`))}export{I as ABEvaluator,h as getABEvaluator,T as setABTestingEnabled};
@@ -0,0 +1 @@
1
+ import i from"jsonata";async function l(r,e){const n=r?.trim();if(!n||n==="*")return!0;if(e.lastResult===void 0||e.lastResult===null)return console.warn(`[ConditionEvaluator] No predecessor result for "${n}" \u2014 running (fail-open)`),!0;let t;try{console.log(`[ConditionEvaluator] Compiling condition "${n}" with context: ${JSON.stringify(e)}`),t=i(n)}catch(o){return console.warn(`[ConditionEvaluator] Compile error for "${n}": ${o?.message} \u2014 running (fail-open)`),!0}try{const o=await t.evaluate(e.lastResult,{topic:e.topic??"",message:e.userMessage??""});return typeof o!="boolean"?(console.warn(`[ConditionEvaluator] Non-boolean result (${JSON.stringify(o)}) for "${n}" \u2014 running (fail-open)`),!0):o}catch(o){return console.warn(`[ConditionEvaluator] Eval error for "${n}": ${o?.message} \u2014 running (fail-open)`),!0}}export{l as evaluateCondition};
@@ -0,0 +1 @@
1
+ import d from"https";import s from"fs";class y{defaultTimeout;rejectUnauthorized;certificatePaths;constructor(c,a,e=!0){this.defaultTimeout=a||5e3,this.certificatePaths=c,this.rejectUnauthorized=e}async request(c,a){const e={timeout:this.defaultTimeout,...c,rejectUnauthorized:this.rejectUnauthorized};return this.certificatePaths?.cert&&s.existsSync(this.certificatePaths.cert)&&(e.cert=s.readFileSync(this.certificatePaths.cert)),this.certificatePaths?.key&&s.existsSync(this.certificatePaths.key)&&(e.key=s.readFileSync(this.certificatePaths.key)),this.certificatePaths?.ca&&s.existsSync(this.certificatePaths.ca)&&(e.ca=s.readFileSync(this.certificatePaths.ca)),new Promise(f=>{const u=e.timeout||this.defaultTimeout;let h=!1;const o=t=>{h||(h=!0,f(t))},r=d.request(e,t=>{let n="";t.on("data",i=>{n+=i}),t.on("end",()=>{try{const i=n?JSON.parse(n):null;t.statusCode===200?o({statusCode:t.statusCode,data:i}):o({statusCode:t.statusCode,error:i||{message:"Unknown error"}})}catch{o({statusCode:t.statusCode,error:{message:"Failed to parse response",data:n}})}})});r.on("socket",t=>{t.setTimeout(u),t.on("timeout",()=>{r.destroy(new Error(`Request timeout after ${u}ms`))}),t.on("error",()=>{})}),r.on("error",t=>{o({error:t})}),a&&r.write(a),r.end()})}}export{y as HttpsClient};
@@ -0,0 +1 @@
1
+ const j=6;function g(t,e={}){const{prefill:p={},hidden:a=[],hints:l={},depth:u=0,parentPath:m=""}=e;if(u>6)return[];if(!t||typeof t!="object")return[];if(t.$ref)return console.warn(`[json-schema-to-form] $ref not resolved: ${t.$ref}`),[];if(t.oneOf||t.anyOf){const s=t.oneOf??t.anyOf,i={type:"object",properties:{},required:[]};for(const d of s)d.properties&&(Object.assign(i.properties,d.properties),i.required.push(...d.required??[]));return g(i,{...e,depth:u})}if(t.type==="object"||t.properties){const s=t.properties??{},i=[...e.required??[],...t.required??[]],d=[];for(const[r,n]of Object.entries(s)){const o=m?`${m}.${r}`:r,f=a.includes(r)||a.includes(o),y=i.includes(r);if(n.type==="object"||n.properties){const c=typeof p[r]=="object"&&p[r]!==null?p[r]:{},b=g(n,{prefill:c,hidden:a,hints:l,required:n.required??[],depth:u+1,parentPath:o});d.push({name:o,type:"object",label:n.title??F(r),description:l[r]??l[o]??n.description,required:y,hidden:f,fields:b});continue}if(n.type==="array"){const c=n.items;if(c?.type==="object"||c?.properties){const b=g(c,{prefill:{},hidden:a,hints:l,required:c.required??[],depth:u+1,parentPath:`${o}[]`});d.push({name:o,type:"array",label:n.title??F(r),description:l[r]??l[o]??n.description,required:y,hidden:f,value:Array.isArray(p[r])?p[r]:[],fields:b})}else{const b=c?.enum??[];d.push({name:o,type:"multiselect",label:n.title??F(r),description:l[r]??l[o]??n.description,required:y,hidden:f,value:Array.isArray(p[r])?p[r]:[],options:b.map(h=>({value:h,label:h}))})}continue}const q=x(r,n,{fullPath:o,required:y,hidden:f,prefill:p[r],hint:l[r]??l[o]});q&&d.push(q)}return d}if(t.type==="array"){const s=t.items;if(s?.type==="object"||s?.properties){const i=g(s,{prefill:{},hidden:a,hints:l,required:s.required??[],depth:u+1,parentPath:"[]"});return[{name:"body",type:"array",label:t.title??"Items",description:t.description,required:!0,value:[],fields:i}]}}return[]}function x(t,e,p){const{fullPath:a,required:l,hidden:u,prefill:m,hint:s}=p;let i="text",d;if(e.enum){i="select";const o=e.enumNames;d=e.enum.map((f,y)=>({value:String(f),label:o?.[y]??String(f)}))}else switch(e.type){case"integer":case"number":i="number";break;case"boolean":i="boolean";break;default:switch(e.format){case"password":i="password";break;case"date":case"date-time":i="date";break;case"binary":case"byte":case"data-url":i="file";break;case"json":i="code";break;default:i=typeof e.maxLength=="number"&&e.maxLength>200?"textarea":"text"}}const r=Array.isArray(e.examples)&&e.examples.length>0?String(e.examples[0]):void 0,n=m!==void 0?m:e.default;return{name:a,type:i,label:e.title??F(t),description:s??e.description,required:l,hidden:u,default:e.default,value:n,placeholder:r,min:e.minimum??e.exclusiveMinimum,max:e.maximum??e.exclusiveMaximum,step:e.multipleOf,minLength:e.minLength,maxLength:e.maxLength,pattern:e.pattern,options:d}}function F(t){return t.replace(/([A-Z])/g," $1").replace(/[_-]/g," ").trimStart().split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}export{g as jsonSchemaToFormFields};
@@ -0,0 +1,3 @@
1
+ import e from"winston";import l from"winston-daily-rotate-file";import n from"path";import Y from"fs";const o=n.join(process.cwd(),"logs");Y.existsSync(o)||Y.mkdirSync(o,{recursive:!0});const r=e.format.combine(e.format.timestamp({format:"YYYY-MM-DD HH:mm:ss"}),e.format.errors({stack:!0}),e.format.printf(({timestamp:t,level:a,message:s,stack:i,...m})=>{let c=`${t} [${a.toUpperCase()}]`;m.service&&(c+=` [${m.service}]`),c+=`: ${s}`,i&&(c+=`
2
+ ${i}`);const d=Object.keys(m).filter(p=>p!=="service");if(d.length>0){const p=Object.fromEntries(d.map(u=>[u,m[u]]));c+=`
3
+ Meta: ${JSON.stringify(p)}`}return c})),x=e.format.combine(e.format.colorize(),e.format.timestamp({format:"HH:mm:ss"}),e.format.printf(({timestamp:t,level:a,message:s,service:i})=>{const m=i?` [${i}]`:"";return`${t}${m} ${a}: ${s}`})),D=new l({filename:n.join(o,"app-%DATE%.log"),datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",format:r,level:"debug"}),f=new l({filename:n.join(o,"error-%DATE%.log"),datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"30d",format:r,level:"error"}),w=new l({filename:n.join(o,"websocket-%DATE%.log"),datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"7d",format:r,level:"debug"}),b=new l({filename:n.join(o,"access-%DATE%.log"),datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"30d",format:e.format.combine(e.format.timestamp(),e.format.json()),level:"info"}),g=e.createLogger({level:process.env.LOG_LEVEL||"info",format:r,transports:[...process.env.NODE_ENV!=="production"||process.env.CONSOLE_LOGS==="true"?[new e.transports.Console({format:x,level:"info"})]:[],D,f],exceptionHandlers:[new e.transports.File({filename:n.join(o,"exceptions.log"),format:r})],rejectionHandlers:[new e.transports.File({filename:n.join(o,"rejections.log"),format:r})]}),L=e.createLogger({level:"debug",format:r,defaultMeta:{service:"websocket"},transports:[w,f]}),v=e.createLogger({level:"info",format:e.format.combine(e.format.timestamp(),e.format.json()),transports:[b]}),M=e.createLogger({level:"debug",format:r,defaultMeta:{service:"mcp"},transports:[new l({filename:n.join(o,"mcp-%DATE%.log"),datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",format:r}),f]}),$={app:g,websocket:L,access:v,mcp:M},z=(t,a,s,i=g)=>{i[t](a,s)},E=(t,a,s)=>{v.info("HTTP Request",{method:t.method,url:t.url,statusCode:a.statusCode,userAgent:t.get("User-Agent"),ip:t.ip||t.connection.remoteAddress,responseTime:s?`${s}ms`:void 0,timestamp:new Date().toISOString()})};var h=g;export{v as accessLogger,h as default,E as logRequest,z as logWithContext,g as logger,$ as loggers,M as mcpLogger,L as wsLogger};
@@ -0,0 +1 @@
1
+ import{AsyncLocalStorage as f}from"async_hooks";import{Client as y}from"@elastic/elasticsearch";import{SYSTEM_OWNERS as S}from"./ownership";import{aggField as d}from"../services/es-field-resolver";const s=new f;function h(n,e){return s.run(n,e)}function k(){return s.getStore()}const p={".stkxp_assistants":{},".stkxp_connectors":{},".stkxp_graphs":{},".stkxp_triggers":{},".stkxp_teams":{},".stkxp_tools":{}},a=process.env.OWNER_SCOPE_DISABLED==="true";function g(n){return typeof n=="string"?n:Array.isArray(n)&&n.length===1&&typeof n[0]=="string"?n[0]:null}function O(n,e){return{bool:{should:[e,...S].map(r=>({term:{[n]:r}})),minimum_should_match:1}}}function l(n,e){return n?{bool:{must:[n],filter:[e]}}:e}async function w(n){try{if(a)return n;const e=s.getStore();if(!e||!e.owner||e.isSuperuser)return n;const t=g(n?.index);if(!t)return n;const r=p[t];if(!r)return n;const u=r.ownerField??await d(t,"owner"),o=O(u,e.owner);return n.body&&typeof n.body=="object"?{...n,body:{...n.body,query:l(n.body.query,o)}}:{...n,query:l(n.query,o)}}catch(e){return console.warn(`[owner-scope] injection skipped (failed open): ${e?.message}`),n}}function m(n){const e=new y(n);return new Proxy(e,{get(t,r,u){if(r==="search")return async(i,c)=>t.search(await w(i),c);if(r==="count")return async(i,c)=>t.count(await w(i),c);const o=Reflect.get(t,r,t);return typeof o=="function"?o.bind(t):o}})}export{k as getOwnerScope,m as makeOwnerScopedClient,h as runWithOwnerScope};
@@ -0,0 +1 @@
1
+ const l=["stkxp","system"];function d(r){return r.auth?.username??null}function f(r){const e=r.auth?.roles;return Array.isArray(e)&&e.includes("superuser")}async function h(r,e,u,a,n,i="owner"){if(f(r))try{return{source:(await u.get({index:a,id:n}))._source??{},docId:n}}catch(s){if(s.meta?.statusCode===404)return e.status(404).json({success:!1,error:"Document not found"}),null;throw s}const c=d(r);if(!c)return e.status(401).json({success:!1,error:"Unauthorized"}),null;let o;try{const s=await u.get({index:a,id:n});if(!s.found)return e.status(404).json({success:!1,error:"Document not found"}),null;o=s._source??{}}catch(s){if(s.meta?.statusCode===404)return e.status(404).json({success:!1,error:"Document not found"}),null;throw s}const t=o[i];return t&&l.includes(t)?(e.status(403).json({success:!1,error:"Forbidden: cannot modify a system-owned resource"}),null):t&&t!==c?(e.status(403).json({success:!1,error:"Forbidden: you do not own this resource"}),null):{source:o,docId:n}}export{l as SYSTEM_OWNERS,h as assertOwner,d as getAuthUsername,f as isSuperuser};
@@ -0,0 +1 @@
1
+ const T={enabled:process.env.PARALLEL_TOOLS_ENABLED!=="false",maxConcurrency:parseInt(process.env.PARALLEL_TOOLS_MAX_CONCURRENCY||"5",10),toolTimeout:parseInt(process.env.PARALLEL_TOOLS_TIMEOUT||"30000",10),verbose:process.env.PARALLEL_TOOLS_VERBOSE==="true"};class f{constructor(e=T){this.config=e}async executeToolCalls(e,l){const r=Date.now();if(!this.config.enabled||e.length<=1)return this.executeSequential(e,l,r);this.config.verbose&&console.log(`[ParallelTools] Executing ${e.length} tools with max concurrency ${this.config.maxConcurrency}`);const o=await this.executeWithConcurrencyLimit(e,l,this.config.maxConcurrency),t=this.calculateStats(o,r);return this.config.verbose&&console.log("[ParallelTools] Stats:",t),{results:o,stats:t}}async executeWithConcurrencyLimit(e,l,r){const o=[],t=[];for(const n of e){const a=this.executeSingleTool(n,l).then(i=>{o.push(i)});if(t.push(a),t.length>=r){await Promise.race(t);const i=t.filter(u=>u!==a||o.length<e.length);t.length=0,t.push(...i)}}return await Promise.all(t),o}async executeSingleTool(e,l){const r=Date.now(),o=e.id||`tool_${Date.now()}`,t=e.name;try{const n=l.get(t);if(!n)throw new Error(`Tool ${t} not found`);const a=await this.executeWithTimeout(()=>n.invoke(e.args),this.config.toolTimeout),i=Date.now();return{toolCallId:o,toolName:t,success:!0,result:a,duration:i-r,startTime:r,endTime:i}}catch(n){const a=Date.now();return this.config.verbose&&console.error(`[ParallelTools] Error executing ${t}:`,n.message),{toolCallId:o,toolName:t,success:!1,error:n,duration:a-r,startTime:r,endTime:a}}}async executeWithTimeout(e,l){return Promise.race([e(),new Promise((r,o)=>setTimeout(()=>o(new Error("Tool execution timeout")),l))])}async executeSequential(e,l,r){const o=[];for(const n of e){const a=await this.executeSingleTool(n,l);o.push(a)}const t=this.calculateStats(o,r);return{results:o,stats:t}}calculateStats(e,l){const r=Date.now()-l,o=e.filter(s=>s.success).length,t=e.length-o,n=e.map(s=>s.duration),a=n.reduce((s,h)=>s+h,0),i=n.length>0?a/n.length:0,u=n.length>0?Math.max(...n):0,g=n.length>0?Math.min(...n):0,m=a,x=m>0?(m-r)/m*100:0;return{totalTools:e.length,successCount:o,errorCount:t,totalDuration:r,averageDuration:i,maxDuration:u,minDuration:g,parallelismGain:parseFloat(x.toFixed(2))}}getConfig(){return{...this.config}}updateConfig(e){this.config={...this.config,...e}}}const C=new f(T);function d(c){return!(c.length<=1)}function S(c){return[c]}export{f as ParallelToolExecutor,S as analyzeToolDependencies,d as canParallelize,T as defaultParallelConfig,C as parallelToolExecutor};
@@ -0,0 +1,3 @@
1
+ class s{metrics=new Map;runId;startTime;constructor(r){this.runId=r,this.startTime=Date.now()}start(r,e){const t={name:r,startTime:Date.now(),metadata:e};this.metrics.set(r,t),console.log(`[PERF][${this.runId}] \u23F1\uFE0F START: ${r}`,e||"")}end(r,e){const t=this.metrics.get(r);return t?(t.endTime=Date.now(),t.duration=t.endTime-t.startTime,e&&(t.metadata={...t.metadata,...e}),console.log(`[PERF][${this.runId}] \u23F9\uFE0F END: ${r} - Duration: ${t.duration}ms`,t.metadata||""),t.duration):(console.warn(`[PERF][${this.runId}] \u26A0\uFE0F Metric not found: ${r}`),0)}instant(r,e){const t={name:r,startTime:Date.now(),endTime:Date.now(),duration:0,metadata:e};this.metrics.set(r,t),console.log(`[PERF][${this.runId}] \u{1F4CC} INSTANT: ${r}`,e||"")}getMetric(r){return this.metrics.get(r)}get(r){return this.metrics.get(r)?.duration||0}getAllMetrics(){return Array.from(this.metrics.values())}getTotalDuration(){return Date.now()-this.startTime}printSummary(){const r=this.getTotalDuration();console.log(`
2
+ ${"=".repeat(80)}`),console.log(`[PERF][${this.runId}] \u{1F4CA} PERFORMANCE SUMMARY`),console.log(`${"=".repeat(80)}`),console.log(`Total Duration: ${r}ms`),console.log(`${"\u2500".repeat(80)}`),this.getAllMetrics().sort((t,n)=>t.startTime-n.startTime).forEach(t=>{const n=t.duration!==void 0?`${t.duration}ms`:"N/A",i=t.duration?`(${(t.duration/r*100).toFixed(1)}%)`:"";console.log(` ${t.name.padEnd(40)} ${n.padStart(10)} ${i.padStart(8)}`),t.metadata&&Object.keys(t.metadata).length>0&&console.log(` \u2514\u2500 Metadata: ${JSON.stringify(t.metadata)}`)}),console.log(`${"=".repeat(80)}
3
+ `)}getSummary(){return{runId:this.runId,totalDuration:this.getTotalDuration(),metrics:this.getAllMetrics()}}}export{s as PerformanceTracker};
@@ -0,0 +1,40 @@
1
+ function l(t){const n={token:t.userToken,cluster:t.cluster};return t.nodes&&(n.nodes=t.nodes),t.roles&&(n.roles=t.roles),t.phases&&(n.phases=t.phases),t.prefix&&(n.prefix=t.prefix),t.suffix&&(n.suffix=t.suffix),t.start&&(n.start=t.start),t.end&&(n.end=t.end),t.interval&&(n.interval=t.interval),t.topic&&(n.topic=t.topic),JSON.stringify(n)}function c(t){const n=t.toolNames?.length?`
2
+ Tools: ${t.toolNames.slice(0,5).join(", ")}${t.toolNames.length>5?"...":""}`:"";return`RULES:
3
+ 1. Use tools for data (never invent)
4
+ 2. Call tools first
5
+ 3. Params: ${t.mandatoryParams}${n}
6
+ 4. **CRITICAL**: If a tool fails OR returns empty data, CONTINUE with remaining tools - DO NOT stop execution
7
+
8
+ \u26A0\uFE0F ERROR HANDLING PROTOCOL (MANDATORY):
9
+ When a tool returns ANY of these:
10
+ - {"status":"error"} or {"status":"no_data"}
11
+ - Empty objects: {"mysql":{}} or {"data":{}} or {}
12
+ - Empty arrays: {"items":[]} or []
13
+ - No useful data
14
+
15
+ You MUST:
16
+ \u2705 CONTINUE calling ALL remaining tools you planned
17
+ \u2705 Try alternative tools that might have data
18
+ \u2705 Work with partial data from successful tools
19
+ \u2705 Generate dashboard with whatever data you found
20
+ \u2705 Mention which tools returned empty data
21
+ \u274C DO NOT stop the entire process
22
+ \u274C DO NOT abort just because 1-2 tools failed or returned empty
23
+ \u274C DO NOT generate dashboard based on assumptions
24
+
25
+ EXAMPLE: If you planned 5 tools and tool #1 returns {"mysql":{}}:
26
+ \u2192 Still call tools #2, #3, #4, #5
27
+ \u2192 If tool #2 and #3 have data, use that
28
+ \u2192 Generate dashboard with data from successful tools
29
+ \u2192 Add note: "Note: mysql_error_logs returned no data, showing data from mysql_slow_queries and mysql_performance"
30
+
31
+ OUTPUT: Compact JSON blocks ONLY (one per line)
32
+ \u26A0\uFE0F CRITICAL: Start response IMMEDIATELY with first JSON block. NO intro text, NO markdown fences.
33
+ FORBIDDEN: "I will...", "Here is...", \`\`\`json
34
+ REQUIRED: {"type":"markdown","title":"...","body":"..."}`}function i(t){return Math.ceil(t.length/4)}function u(t,n=2e3){const o=n*4;if(t.length<=o)return{content:t,truncated:!1};const s=Math.floor(o*.6),e=Math.floor(o*.2),r=t.slice(0,s),a=t.slice(-e);return{content:`${r}
35
+
36
+ [... content truncated for brevity ...]
37
+
38
+ ${a}`,truncated:!0}}function f(t){const{content:n,truncated:o}=u(t.agentPrompt,t.maxAgentPromptTokens||2e3),s=l(t.mandatoryParams),e=c({mandatoryParams:s,toolNames:t.toolNames}),r=`${n}
39
+
40
+ ${e}`;return{prompt:r,stats:{agentPromptTokens:i(n),instructionsTokens:i(e),totalTokens:i(r),agentPromptTruncated:o}}}export{c as buildCompactToolInstructions,f as buildOptimizedSystemPrompt,l as compressMandatoryParams,i as estimateTokens,u as truncateAgentPrompt};
@@ -0,0 +1 @@
1
+ import h from"crypto";const l={maxSize:parseInt(process.env.CACHE_MAX_SIZE||"100",10),ttl:parseInt(process.env.CACHE_TTL||"3600000",10),enableStats:process.env.CACHE_ENABLE_STATS!=="false",compressionThreshold:parseInt(process.env.CACHE_COMPRESSION_THRESHOLD||"1024",10)};class c{constructor(e=l){this.config=e}cache=new Map;stats={hits:0,misses:0,evictions:0,sets:0};generateKey(e){const n={query:e.query.trim().toLowerCase(),topic:e.topic||"default",namespace:e.namespace||"default"},t=JSON.stringify(n);return h.createHash("sha256").update(t).digest("hex")}get(e){const s=this.cache.get(e);return s?Date.now()-s.timestamp>this.config.ttl?(this.cache.delete(e),this.stats.misses++,null):(s.timestamp=Date.now(),s.hits++,this.stats.hits++,this.cache.delete(e),this.cache.set(e,s),s.value):(this.stats.misses++,null)}set(e,s,n){const t=this.estimateSize(s);this.cache.size>=this.config.maxSize&&this.evictOldest();const i={key:e,value:s,timestamp:Date.now(),hits:0,size:t,metadata:n};this.cache.set(e,i),this.stats.sets++}has(e){const s=this.cache.get(e);return s?Date.now()-s.timestamp>this.config.ttl?(this.cache.delete(e),!1):!0:!1}delete(e){return this.cache.delete(e)}clear(){this.cache.clear(),this.resetStats()}evictOldest(){const e=this.cache.keys().next().value;e&&(this.cache.delete(e),this.stats.evictions++)}estimateSize(e){try{return JSON.stringify(e).length}catch{return 0}}getStats(){let e=0;for(const t of this.cache.values())e+=t.size;const s=this.stats.hits+this.stats.misses,n=s>0?this.stats.hits/s:0;return{size:this.cache.size,maxSize:this.config.maxSize,hits:this.stats.hits,misses:this.stats.misses,hitRate:parseFloat((n*100).toFixed(2)),evictions:this.stats.evictions,sets:this.stats.sets,totalBytes:e}}resetStats(){this.stats={hits:0,misses:0,evictions:0,sets:0}}entries(){return Array.from(this.cache.values())}cleanExpired(){let e=0;const s=Date.now();for(const[n,t]of this.cache.entries())s-t.timestamp>this.config.ttl&&(this.cache.delete(n),e++);return e}}class m{calculateSimilarity(e,s){const n=this.normalize(e),t=this.normalize(s);if(n===t)return 1;const i=this.levenshteinDistance(n,t),a=Math.max(n.length,t.length);return 1-i/a}findSimilar(e,s,n=.8){let t=null;for(const i of s){const a=this.calculateSimilarity(e,i);a>=n&&(!t||a>t.similarity)&&(t={query:i,similarity:a})}return t}normalize(e){return e.trim().toLowerCase().replace(/[^\w\s]/g,"").replace(/\s+/g," ")}levenshteinDistance(e,s){const n=[];for(let t=0;t<=e.length;t++)n[t]=[t];for(let t=0;t<=s.length;t++)n[0][t]=t;for(let t=1;t<=e.length;t++)for(let i=1;i<=s.length;i++)e[t-1]===s[i-1]?n[t][i]=n[t-1][i-1]:n[t][i]=Math.min(n[t-1][i-1]+1,n[t][i-1]+1,n[t-1][i]+1);return n[e.length][s.length]}}const u={maxSize:parseInt(process.env.DASHBOARD_CACHE_MAX_SIZE||"100",10),ttl:parseInt(process.env.DASHBOARD_CACHE_TTL||"3600000",10),enableStats:process.env.CACHE_ENABLE_STATS!=="false",compressionThreshold:parseInt(process.env.CACHE_COMPRESSION_THRESHOLD||"1024",10)},p={maxSize:parseInt(process.env.DATA_CACHE_MAX_SIZE||"200",10),ttl:parseInt(process.env.DATA_CACHE_TTL||"300000",10),enableStats:process.env.CACHE_ENABLE_STATS!=="false",compressionThreshold:parseInt(process.env.CACHE_COMPRESSION_THRESHOLD||"1024",10)},o=new c(u),g=new c(p),d=o,f=new m;process.env.CACHE_AUTO_CLEANUP!=="false"&&setInterval(()=>{const r=o.cleanExpired(),e=g.cleanExpired();(r>0||e>0)&&console.log(`[Cache] Cleaned ${r} dashboard + ${e} data expired entries`)},300*1e3);export{c as LRUCache,m as QueryMatcher,u as dashboardCacheConfig,o as dashboardCacheInstance,p as dataCacheConfig,g as dataCacheInstance,l as defaultCacheConfig,f as queryMatcherInstance,d as responseCacheInstance};
@@ -0,0 +1 @@
1
+ import{UiBlockSchema as i,DashboardSchema as u}from"../schema/ui";function l(r){try{const e=i.safeParse(r);return e.success?{success:!0,data:e.data,fallbackApplied:!1}:(console.warn("[Schema] Block validation failed, converting to raw:",e.error.issues),{success:!0,data:{type:"raw",id:r.id||void 0,title:r.title||r.type||"Unknown Block",content:r,error:`Validation failed: ${e.error.issues.map(s=>s.message).join(", ")}`},fallbackApplied:!0})}catch(e){return{success:!1,error:e}}}function f(r){try{const e=u.safeParse(r);if(e.success)return{success:!0,data:e.data,fallbackApplied:!1};if(console.warn("[Schema] Dashboard validation failed, attempting recovery:",e.error.issues),r?.result?.content&&Array.isArray(r.result.content)){const a=[];let s=!1;for(const c of r.result.content){const t=l(c);t.success&&t.data?(a.push(t.data),t.fallbackApplied&&(s=!0)):(s=!0,a.push({type:"raw",content:c,error:"Invalid block structure"}))}return{success:!0,data:{session_id:r.session_id||"unknown",result:{content:a}},fallbackApplied:s}}return{success:!1,error:e.error}}catch(e){return{success:!1,error:e}}}function b(r){try{const e=[];let a=!1;for(const s of r){const o=l(s);o.success&&o.data?(e.push(o.data),o.fallbackApplied&&(a=!0)):(a=!0,console.error("[Schema] Skipping invalid block:",s))}return{success:!0,data:e,fallbackApplied:a}}catch(e){return{success:!1,error:e}}}function n(r){if(r==null)return r;if(Array.isArray(r))return r.map(n).filter(e=>e!==void 0);if(typeof r=="object"){const e={};for(const[a,s]of Object.entries(r))s!==void 0&&(e[a]=n(s));return e}return r}function h(r){const e=n(r);return f(e)}export{n as cleanCachedData,h as safeParseCachedDashboard,l as safeValidateBlock,b as safeValidateBlocks,f as safeValidateDashboard};
@@ -0,0 +1,2 @@
1
+ const n={tokenBatchSize:parseInt(process.env.STREAMING_TOKEN_BATCH_SIZE||"5",10),maxBatchDelay:parseInt(process.env.STREAMING_MAX_BATCH_DELAY||"50",10),adaptiveBatching:process.env.STREAMING_ADAPTIVE_BATCHING!=="false",prioritizeFirstTokens:process.env.STREAMING_PRIORITIZE_FIRST!=="false"};class o{constructor(e,t,i=n){this.ws=e;this.sendFn=t;this.config=i}buffer=[];lastFlush=Date.now();tokenCount=0;firstTokenSent=!1;flushTimer;addToken(e,t){this.buffer.push(e),this.tokenCount++;const i=t?.priority||"normal";if(!this.firstTokenSent&&this.config.prioritizeFirstTokens){this.flush(),this.firstTokenSent=!0;return}if(i==="high"){this.flush();return}this.shouldFlush(e,t?.type)?this.flush():this.scheduleFlush()}shouldFlush(e,t){return!!(e.includes(`
2
+ `)||e.includes("```json")||e.includes("```")||e.match(/[.!?]\s*$/)||this.buffer.length>=this.config.tokenBatchSize||Date.now()-this.lastFlush>=this.config.maxBatchDelay)}scheduleFlush(){if(this.flushTimer)return;const e=this.config.maxBatchDelay-(Date.now()-this.lastFlush);if(e<=0){this.flush();return}this.flushTimer=setTimeout(()=>{this.flush()},e)}flush(){if(this.buffer.length===0)return;this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0);const e=this.buffer.join("");this.buffer=[],this.lastFlush=Date.now(),this.sendFn({text:e,tokenCount:this.tokenCount})}finalize(){this.flush()}getStats(){return{totalTokens:this.tokenCount,bufferSize:this.buffer.length,firstTokenSent:this.firstTokenSent}}}class u{avgChunkSize=0;chunkCount=0;analyzeChunk(e){const t=e.length;return this.avgChunkSize=(this.avgChunkSize*this.chunkCount+t)/(this.chunkCount+1),this.chunkCount++,t<10?{isOptimal:!1,suggestedSize:50,reason:"Chunk too small - high overhead"}:t>200?{isOptimal:!1,suggestedSize:100,reason:"Chunk too large - delayed perception"}:{isOptimal:!0,suggestedSize:t,reason:"Optimal chunk size"}}getAverageChunkSize(){return Math.round(this.avgChunkSize)}}class h{preloadBuffer=[];maxPreloadSize=5;preload(e){this.preloadBuffer.length<this.maxPreloadSize&&this.preloadBuffer.push(e)}getNext(){return this.preloadBuffer.shift()}hasPreloaded(){return this.preloadBuffer.length>0}getSize(){return this.preloadBuffer.length}}class a{startTime=Date.now();firstTokenTime;lastTokenTime;tokenCount=0;bytesSent=0;chunksProcessed=0;recordToken(e){this.firstTokenTime||(this.firstTokenTime=Date.now()),this.lastTokenTime=Date.now(),this.tokenCount++,this.bytesSent+=Buffer.byteLength(e,"utf8")}recordChunk(){this.chunksProcessed++}getSummary(){const e=Date.now(),t=(this.lastTokenTime||e)-this.startTime;return{timeToFirstToken:this.firstTokenTime?this.firstTokenTime-this.startTime:0,totalDuration:t,tokensPerSecond:t>0?this.tokenCount/t*1e3:0,bytesPerSecond:t>0?this.bytesSent/t*1e3:0,averageChunkSize:this.chunksProcessed>0?this.bytesSent/this.chunksProcessed:0,totalTokens:this.tokenCount,totalBytes:this.bytesSent,totalChunks:this.chunksProcessed}}}export{u as ChunkSizeOptimizer,a as StreamingMetrics,o as StreamingOptimizer,h as StreamingPreloader,n as defaultStreamingConfig};
@@ -0,0 +1 @@
1
+ import c from"slugify";import{randomBytes as g}from"crypto";const u={lower:!0,strict:!0};function o(t){return c(t,u).split("-").join("_")}function i(){return Math.random().toString(36).slice(2)}function d(){return g(16).toString("hex")}function p(t,r,e){const n=i();return o(`${t}_${r}_${e}_${n}`)}function m(t,r,e){const n=i(),s=t||`basicauth_${i()}`;return o(`${s}_${r}_${e}_${n}`)}function l(t,r){return"Basic "+Buffer.from(`${t}:${r}`).toString("base64")}function $(t){if(!t||typeof t!="object")return{};const r={};for(const[e,n]of Object.entries(t))typeof e!="string"||!e.trim()||(typeof n=="string"?r[e]=n:(typeof n=="boolean"||typeof n=="number")&&(r[e]=String(n)));return r}export{l as createAuthHeader,m as createNamespace,p as createPolicyId,o as createSlug,i as generateRandomId,d as generateSecureId,$ as normalizeCustomHeaders};
@@ -0,0 +1,9 @@
1
+ import i from"fs";import l from"path";import{fileURLToPath as g}from"url";const d=g(import.meta.url),u=l.dirname(d);function a(s){const n=[],o=/```json\s*\n([\s\S]*?)\n```/g;let t;for(;(t=o.exec(s))!==null;)try{const e=t[1].trim(),r=JSON.parse(e);n.push(r)}catch(e){console.warn("[TestResponses] Failed to parse JSON block:",e)}return n}function p(s){try{const n=l.join(u,"../../../test-responses"),o=l.join(n,s);if(!i.existsSync(o))return console.error(`[TestResponses] File not found: ${o}`),null;const t=i.readFileSync(o,"utf-8"),e=JSON.parse(t);if(e.content&&typeof e.content=="string"){const r=a(e.content),c={id:e.id,query:e.query||"test",response:{blocks:r}};return console.log(`[TestResponses] Loaded: ${c.id} (${r.length} blocks from content)`),c}return e.response?.blocks?(console.log(`[TestResponses] Loaded: ${e.id} (${e.response.blocks.length} blocks)`),e):(console.error(`[TestResponses] Invalid format for ${s}`),null)}catch(n){return console.error(`[TestResponses] Error loading ${s}:`,n),null}}function b(){try{const s=l.join(u,"../../../test-responses");return i.existsSync(s)?i.readdirSync(s).filter(o=>o.endsWith(".json")):[]}catch(s){return console.error("[TestResponses] Error listing files:",s),[]}}function m(s){const n=b();for(const o of n){const t=p(o);if(t&&(t.id===s||t.query.toLowerCase().includes(s.toLowerCase())||s.toLowerCase().includes(t.query.toLowerCase())))return t}return n.length>0?(console.log(`[TestResponses] No match for "${s}", using first available`),p(n[0])):null}function*T(s,n=50){for(const o of s.response.blocks){const e=`\`\`\`json
2
+ ${JSON.stringify(o)}
3
+ \`\`\``,r=50;for(let c=0;c<e.length;c+=r)yield e.slice(c,c+r);yield`
4
+ `}}async function*S(s,n=10){if(s.content){for(let t=0;t<s.content.length;t+=50)yield s.content.slice(t,t+50),n>0&&await new Promise(r=>setTimeout(r,n));return}if(s.response?.blocks)for(const o of s.response.blocks){const e=`\`\`\`json
5
+ ${JSON.stringify(o)}
6
+ \`\`\``,r=50;for(let c=0;c<e.length;c+=r)yield e.slice(c,c+r),n>0&&await new Promise(k=>setTimeout(k,n));yield`
7
+ `}}function _(s,n=0){const o=s.response.blocks[n]||s.response.blocks[0],e=`\`\`\`json
8
+ ${JSON.stringify(o)}
9
+ \`\`\``;return{id:`run-test-${s.id}-${n}`,content:e,additional_kwargs:{},response_metadata:{},tool_calls:[],tool_call_chunks:[],invalid_tool_calls:[],usage_metadata:{input_tokens:100,output_tokens:e.length,total_tokens:100+e.length}}}function w(s){try{const n=l.join(u,"../../../test-responses"),o=l.join(n,s);if(!i.existsSync(o))return null;const t=i.readFileSync(o,"utf-8"),e=JSON.parse(t);if(e.content&&typeof e.content=="string"){const r=a(e.content);return{id:e.id,query:e.query||"test",blockCount:r.length}}return e.response?.blocks?{id:e.id,query:e.query,blockCount:e.response.blocks.length}:null}catch{return null}}export{_ as createMockAIMessageChunk,m as findTestResponse,w as getTestResponseMetadata,b as listTestResponses,p as loadTestResponse,T as streamTestResponse,S as streamTestResponseAsync};
@@ -0,0 +1 @@
1
+ function n(r){return r&&r.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,"")}function F(r,e){if(!r||e<=0||r.length<=e)return r;let t=e;const u=r.charCodeAt(t-1);return u>=55296&&u<=56319&&(t-=1),r.slice(0,t)}export{n as stripLoneSurrogates,F as truncateUtf16Safe};
@@ -0,0 +1 @@
1
+ import{jsonSchemaToFormFields as o}from"./json-schema-to-form";function s(r){return r?.requiresForm===!0}function l(r,e){let i={};try{i=JSON.parse(r.inputSchema??"{}")}catch{console.warn(`[tool-form-trigger] Failed to parse inputSchema for tool "${r.name}"`)}const t=o(i,{prefill:e?.prefill??{},hidden:e?.hidden??[],hints:e?.hints??{}});return{type:"form",tool:r.name,platformId:r.platformId,title:e?.title??r.label??r.name,description:e?.description??r.description,submitLabel:e?.submitLabel,fields:t}}export{l as buildFormBlockFromTool,s as shouldRenderForm};
@@ -0,0 +1 @@
1
+ import{bootstrapTeam as r}from"./cli-deploy";const n="__STKXP_BOOTSTRAP_RESULT__";async function e(t){const o=JSON.parse(t),s=await r(o);return JSON.stringify(s)}async function i(){const t=[];for await(const o of process.stdin)t.push(o);return Buffer.concat(t).toString("utf8")}const a=process.argv[1]&&import.meta.url===`file://${process.argv[1]}`;a&&i().then(e).then(t=>{console.log(n+t),process.exit(0)}).catch(t=>{console.error(`[cli-bootstrap-run] ${t instanceof Error?t.message:String(t)}`),process.exit(1)});export{n as RESULT_SENTINEL,e as handleStdinPayload};
@@ -0,0 +1 @@
1
+ import{runDeploy as s}from"./cli-deploy";const r="__STKXP_DEPLOY_RESULT__";async function e(o){const t=JSON.parse(o),n=await s(t);return JSON.stringify(n)}async function i(){const o=[];for await(const t of process.stdin)o.push(t);return Buffer.concat(o).toString("utf8")}const c=process.argv[1]&&import.meta.url===`file://${process.argv[1]}`;c&&i().then(e).then(o=>{console.log(r+o)}).catch(o=>{console.error(`[cli-deploy-run] ${o instanceof Error?o.message:String(o)}`),process.exit(1)});export{r as RESULT_SENTINEL,e as handleStdinPayload};
@@ -0,0 +1 @@
1
+ import{randomBytes as p}from"crypto";import{readFileSync as h}from"fs";const w="127.0.0.1";function m(e){return e.esInsecure===!0?{rejectUnauthorized:!1}:e.esCaPath?{rejectUnauthorized:!0,ca:h(e.esCaPath,"utf8")}:{rejectUnauthorized:!0}}async function b(e){process.env.ELASTICSEARCH_HOST=e.esUrl,process.env.ELASTICSEARCH_USER=e.esUser,process.env.ELASTICSEARCH_PASSWORD=e.esPassword,e.esCaPath&&(process.env.ELASTICSEARCH_CA_PATH=e.esCaPath),process.env.ELASTICSEARCH_TLS_REJECT_UNAUTHORIZED=e.esInsecure===!0?"false":"true";const{parseAndDecryptTeamBundle:o}=await import("../services/clone/team-bundle-encrypted"),{closure:n,rootName:r}=o(e.bundle,e.secret),t=n.docs.find(i=>i.key==="team");if(!t)throw new Error("Decrypted bundle has no team document \u2014 cannot determine which team to deploy");const{Client:a}=await import("@elastic/elasticsearch"),d=new a({node:e.esUrl,auth:{username:e.esUser,password:e.esPassword},tls:m(e)}),{bootstrapClosureToEs:u}=await import("../services/clone/team-bundle-bootstrap"),s=await u(d,n),c=await d.get({index:t.index,id:t.esId}).then(i=>i?._source??null).catch(()=>null);if(c?.webhookEnabled&&c?.webhookToken)return{rootName:r,teamId:t.esId,teamIndex:t.index,webhookToken:null,alreadyBootstrapped:!0,indicesCreated:s.indicesCreated,docsIndexed:s.docsIndexed};const l=p(32).toString("hex");return await d.update({index:t.index,id:t.esId,body:{doc:{webhookToken:l,webhookEnabled:!0,webhookCreatedAt:new Date().toISOString()}},refresh:"wait_for"}),{rootName:r,teamId:t.esId,teamIndex:t.index,webhookToken:l,alreadyBootstrapped:!1,indicesCreated:s.indicesCreated,docsIndexed:s.docsIndexed}}async function C(e){const o=await b(e),{buildTeamRunnerApp:n}=await import("./team-runner"),r=n(),t=e.webhookHost??w;return await new Promise(a=>{r.listen(e.webhookPort,t,()=>a())}),{rootName:o.rootName,teamId:o.teamId,webhookToken:o.webhookToken??"(unchanged \u2014 target was already bootstrapped, existing token not re-shown)",webhookUrl:`http://localhost:${e.webhookPort}/api/webhooks/team/${o.teamId}`,indicesCreated:o.indicesCreated,docsIndexed:o.docsIndexed}}export{w as DEFAULT_WEBHOOK_HOST,b as bootstrapTeam,m as buildTargetEsTls,C as runDeploy};
@@ -0,0 +1 @@
1
+ import"dotenv/config";import p from"express";import{routes as l}from"../routes/webhooks-routes";process.on("uncaughtException",e=>{console.error("[team-runner] Uncaught Exception:",e),process.exit(1)}),process.on("unhandledRejection",(e,o)=>{console.error("[team-runner] Unhandled Rejection at:",o,"reason:",e)});function i(e,o){const r=e.safeParse(o);return r.success?{success:!0,data:r.data}:{success:!1,error:r.error}}function m(e,o){o.forEach(({method:r,path:t,handler:c,validate:n})=>{console.log(`[team-runner] mounting ${r.toUpperCase()} ${t}`),e[r](t,async(a,u)=>{try{if(n?.params){const s=i(n.params,a.params);if(!s.success)return u.status(400).json({error:"Invalid params",issues:s.error.format()})}if(n?.query){const s=i(n.query,a.query);if(!s.success)return u.status(400).json({error:"Invalid query",issues:s.error.format()})}if(n?.body){const s=i(n.body,a.body);if(!s.success)return u.status(400).json({error:"Invalid body",issues:s.error.format()})}await c(a,u)}catch(s){console.error(`[team-runner] [${r.toUpperCase()}] ${t}`,s),u.status(500).json({error:"Internal Server Error"})}})})}function f(){const e=p();return e.use(p.json({limit:"50mb"})),e.get("/health",(o,r)=>{r.json({status:"ok",service:"team-runner"})}),m(e,l),e}const d=process.argv[1]&&import.meta.url===`file://${process.argv[1]}`;if(d){const e=parseInt(process.env.TEAM_RUNNER_PORT||"4001",10),o=process.env.TEAM_RUNNER_HOST||"127.0.0.1",t=f().listen(e,o,()=>{console.log(`[team-runner] listening on http://${o}:${e}`)}),c=()=>{console.log("[team-runner] graceful shutdown initiated..."),t.close(()=>{console.log("[team-runner] HTTP server closed"),process.exit(0)}),setTimeout(()=>{console.error("[team-runner] force shutdown after timeout"),process.exit(1)},1e4).unref()};process.on("SIGINT",c),process.on("SIGTERM",c)}export{f as buildTeamRunnerApp};