claude-flow-novice 1.6.1 โ†’ 1.6.3

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 (273) hide show
  1. package/.claude/agents/cfn-loop/product-owner.md +54 -4
  2. package/.claude/commands/cfn-claude-sync.md +303 -0
  3. package/.claude/commands/cfn-loop-epic.md +290 -0
  4. package/.claude/commands/cfn-loop-single.md +168 -0
  5. package/.claude/commands/cfn-loop-sprints.md +384 -0
  6. package/.claude/commands/cfn-loop.md +180 -0
  7. package/.claude/commands/metrics-summary.md +58 -0
  8. package/.claude/commands/parse-epic.md +357 -0
  9. package/.claude/settings.json +5 -4
  10. package/.claude/settings.local.json +9 -2
  11. package/.claude-flow-novice/.claude/agents/cfn-loop/product-owner.md +792 -0
  12. package/.claude-flow-novice/dist/mcp/server.js +21 -2
  13. package/.claude-flow-novice/dist/src/api/auth-service.js +84 -38
  14. package/.claude-flow-novice/dist/src/api/auth-service.js.map +1 -1
  15. package/.claude-flow-novice/dist/src/api/claude-client.js +138 -3
  16. package/.claude-flow-novice/dist/src/api/claude-client.js.map +1 -1
  17. package/.claude-flow-novice/dist/src/cfn-loop/phase-orchestrator-example.js +1 -1
  18. package/.claude-flow-novice/dist/src/cfn-loop/scope-control.js +247 -0
  19. package/.claude-flow-novice/dist/src/cfn-loop/scope-control.js.map +1 -0
  20. package/.claude-flow-novice/dist/src/cli/commands/swarm.js +32 -15
  21. package/.claude-flow-novice/dist/src/cli/commands/swarm.js.map +1 -1
  22. package/.claude-flow-novice/dist/src/cli/commands/transparency.js +455 -0
  23. package/.claude-flow-novice/dist/src/cli/commands/transparency.js.map +1 -0
  24. package/.claude-flow-novice/dist/src/cli/simple-commands/init/templates/CLAUDE.md +129 -13
  25. package/.claude-flow-novice/dist/src/components/visualizations/index.js +9 -0
  26. package/.claude-flow-novice/dist/src/components/visualizations/index.js.map +1 -0
  27. package/.claude-flow-novice/dist/src/coordination/adapters/v1-coordinator-adapter.js +462 -0
  28. package/.claude-flow-novice/dist/src/coordination/adapters/v1-coordinator-adapter.js.map +1 -0
  29. package/.claude-flow-novice/dist/src/coordination/config-translator.js +248 -0
  30. package/.claude-flow-novice/dist/src/coordination/config-translator.js.map +1 -0
  31. package/.claude-flow-novice/dist/src/coordination/coordination-toggle.js +287 -0
  32. package/.claude-flow-novice/dist/src/coordination/coordination-toggle.js.map +1 -0
  33. package/.claude-flow-novice/dist/src/coordination/distributed-consensus.js +68 -9
  34. package/.claude-flow-novice/dist/src/coordination/distributed-consensus.js.map +1 -1
  35. package/.claude-flow-novice/dist/src/coordination/feature-flags.js +166 -0
  36. package/.claude-flow-novice/dist/src/coordination/feature-flags.js.map +1 -0
  37. package/.claude-flow-novice/dist/src/coordination/queen-agent.js +18 -4
  38. package/.claude-flow-novice/dist/src/coordination/queen-agent.js.map +1 -1
  39. package/.claude-flow-novice/dist/src/coordination/role-assignment.js +6 -110
  40. package/.claude-flow-novice/dist/src/coordination/role-assignment.js.map +1 -1
  41. package/.claude-flow-novice/dist/src/coordination/v2/cache/artifact-cache-optimizer.js +632 -0
  42. package/.claude-flow-novice/dist/src/coordination/v2/cache/artifact-cache-optimizer.js.map +1 -0
  43. package/.claude-flow-novice/dist/src/coordination/v2/cache/index.js +11 -0
  44. package/.claude-flow-novice/dist/src/coordination/v2/cache/index.js.map +1 -0
  45. package/.claude-flow-novice/dist/src/coordination/v2/checkpoints/checkpoint-compressor.js +318 -0
  46. package/.claude-flow-novice/dist/src/coordination/v2/checkpoints/checkpoint-compressor.js.map +1 -0
  47. package/.claude-flow-novice/dist/src/coordination/v2/coordinators/cascading-shutdown.example.js +364 -0
  48. package/.claude-flow-novice/dist/src/coordination/v2/coordinators/cascading-shutdown.example.js.map +1 -0
  49. package/.claude-flow-novice/dist/src/coordination/v2/coordinators/cascading-shutdown.js +492 -0
  50. package/.claude-flow-novice/dist/src/coordination/v2/coordinators/cascading-shutdown.js.map +1 -0
  51. package/.claude-flow-novice/dist/src/coordination/v2/coordinators/hierarchical-coordinator.js +786 -0
  52. package/.claude-flow-novice/dist/src/coordination/v2/coordinators/hierarchical-coordinator.js.map +1 -0
  53. package/.claude-flow-novice/dist/src/coordination/v2/coordinators/index.js +16 -0
  54. package/.claude-flow-novice/dist/src/coordination/v2/coordinators/index.js.map +1 -0
  55. package/.claude-flow-novice/dist/src/coordination/v2/coordinators/parent-child-manager.js +342 -0
  56. package/.claude-flow-novice/dist/src/coordination/v2/coordinators/parent-child-manager.js.map +1 -0
  57. package/.claude-flow-novice/dist/src/coordination/v2/coordinators/swarm-coordinator-v2.js +601 -0
  58. package/.claude-flow-novice/dist/src/coordination/v2/coordinators/swarm-coordinator-v2.js.map +1 -0
  59. package/.claude-flow-novice/dist/src/coordination/v2/core/help-request-metrics.js +211 -0
  60. package/.claude-flow-novice/dist/src/coordination/v2/core/help-request-metrics.js.map +1 -0
  61. package/.claude-flow-novice/dist/src/coordination/v2/core/index.js +1 -0
  62. package/.claude-flow-novice/dist/src/coordination/v2/core/index.js.map +1 -1
  63. package/.claude-flow-novice/dist/src/coordination/v2/core/message-broker.js +365 -6
  64. package/.claude-flow-novice/dist/src/coordination/v2/core/message-broker.js.map +1 -1
  65. package/.claude-flow-novice/dist/src/coordination/v2/core/resource-manager-safe.js +478 -0
  66. package/.claude-flow-novice/dist/src/coordination/v2/core/resource-manager-safe.js.map +1 -0
  67. package/.claude-flow-novice/dist/src/coordination/v2/core/state-machine-config.js +5 -2
  68. package/.claude-flow-novice/dist/src/coordination/v2/core/state-machine-config.js.map +1 -1
  69. package/.claude-flow-novice/dist/src/coordination/v2/core/state-machine.js +189 -0
  70. package/.claude-flow-novice/dist/src/coordination/v2/core/state-machine.js.map +1 -1
  71. package/.claude-flow-novice/dist/src/coordination/v2/deadlock/deadlock-detector.js +424 -0
  72. package/.claude-flow-novice/dist/src/coordination/v2/deadlock/deadlock-detector.js.map +1 -0
  73. package/.claude-flow-novice/dist/src/coordination/v2/deadlock/index.js +9 -0
  74. package/.claude-flow-novice/dist/src/coordination/v2/deadlock/index.js.map +1 -0
  75. package/.claude-flow-novice/dist/src/coordination/v2/deadlock/resource-manager.js +669 -0
  76. package/.claude-flow-novice/dist/src/coordination/v2/deadlock/resource-manager.js.map +1 -0
  77. package/.claude-flow-novice/dist/src/coordination/v2/dependency/artifact-storage.js +451 -0
  78. package/.claude-flow-novice/dist/src/coordination/v2/dependency/artifact-storage.js.map +1 -0
  79. package/.claude-flow-novice/dist/src/coordination/v2/dependency/cycle-detector.js +271 -0
  80. package/.claude-flow-novice/dist/src/coordination/v2/dependency/cycle-detector.js.map +1 -0
  81. package/.claude-flow-novice/dist/src/coordination/v2/dependency/dependency-graph.js +335 -0
  82. package/.claude-flow-novice/dist/src/coordination/v2/dependency/dependency-graph.js.map +1 -0
  83. package/.claude-flow-novice/dist/src/coordination/v2/dependency/dependency-manager.js +439 -0
  84. package/.claude-flow-novice/dist/src/coordination/v2/dependency/dependency-manager.js.map +1 -0
  85. package/.claude-flow-novice/dist/src/coordination/v2/dependency/dependency-request.js +92 -0
  86. package/.claude-flow-novice/dist/src/coordination/v2/dependency/dependency-request.js.map +1 -0
  87. package/.claude-flow-novice/dist/src/coordination/v2/dependency/index.js +21 -0
  88. package/.claude-flow-novice/dist/src/coordination/v2/dependency/index.js.map +1 -0
  89. package/.claude-flow-novice/dist/src/coordination/v2/dependency/topological-sort.js +223 -0
  90. package/.claude-flow-novice/dist/src/coordination/v2/dependency/topological-sort.js.map +1 -0
  91. package/.claude-flow-novice/dist/src/coordination/v2/help-system/help-coordinator.js +436 -0
  92. package/.claude-flow-novice/dist/src/coordination/v2/help-system/help-coordinator.js.map +1 -0
  93. package/.claude-flow-novice/dist/src/coordination/v2/help-system/help-matcher.js +278 -0
  94. package/.claude-flow-novice/dist/src/coordination/v2/help-system/help-matcher.js.map +1 -0
  95. package/.claude-flow-novice/dist/src/coordination/v2/help-system/help-request-handler.js +317 -0
  96. package/.claude-flow-novice/dist/src/coordination/v2/help-system/help-request-handler.js.map +1 -0
  97. package/.claude-flow-novice/dist/src/coordination/v2/help-system/help-request.js +273 -0
  98. package/.claude-flow-novice/dist/src/coordination/v2/help-system/help-request.js.map +1 -0
  99. package/.claude-flow-novice/dist/src/coordination/v2/help-system/index.js +15 -0
  100. package/.claude-flow-novice/dist/src/coordination/v2/help-system/index.js.map +1 -0
  101. package/.claude-flow-novice/dist/src/coordination/v2/help-system/waiting-agent-pool.js +512 -0
  102. package/.claude-flow-novice/dist/src/coordination/v2/help-system/waiting-agent-pool.js.map +1 -0
  103. package/.claude-flow-novice/dist/src/coordination/v2/index.js +6 -0
  104. package/.claude-flow-novice/dist/src/coordination/v2/index.js.map +1 -1
  105. package/.claude-flow-novice/dist/src/coordination/v2/integration/help-deadlock-integration.js +557 -0
  106. package/.claude-flow-novice/dist/src/coordination/v2/integration/help-deadlock-integration.js.map +1 -0
  107. package/.claude-flow-novice/dist/src/coordination/v2/integration/index.js +14 -0
  108. package/.claude-flow-novice/dist/src/coordination/v2/integration/index.js.map +1 -0
  109. package/.claude-flow-novice/dist/src/coordination/v2/integration/message-bus-completion-integration.example.js +212 -0
  110. package/.claude-flow-novice/dist/src/coordination/v2/integration/message-bus-completion-integration.example.js.map +1 -0
  111. package/.claude-flow-novice/dist/src/coordination/v2/integration/message-bus-completion-integration.js +552 -0
  112. package/.claude-flow-novice/dist/src/coordination/v2/integration/message-bus-completion-integration.js.map +1 -0
  113. package/.claude-flow-novice/dist/src/coordination/v2/memory/dependency-storage.js +367 -0
  114. package/.claude-flow-novice/dist/src/coordination/v2/memory/dependency-storage.js.map +1 -0
  115. package/.claude-flow-novice/dist/src/coordination/v2/memory/index.js +1 -0
  116. package/.claude-flow-novice/dist/src/coordination/v2/memory/index.js.map +1 -1
  117. package/.claude-flow-novice/dist/src/coordination/v2/messaging/channel.js +371 -0
  118. package/.claude-flow-novice/dist/src/coordination/v2/messaging/channel.js.map +1 -0
  119. package/.claude-flow-novice/dist/src/coordination/v2/messaging/channels/dependency-channel.js +355 -0
  120. package/.claude-flow-novice/dist/src/coordination/v2/messaging/channels/dependency-channel.js.map +1 -0
  121. package/.claude-flow-novice/dist/src/coordination/v2/messaging/channels/help-channel.js +424 -0
  122. package/.claude-flow-novice/dist/src/coordination/v2/messaging/channels/help-channel.js.map +1 -0
  123. package/.claude-flow-novice/dist/src/coordination/v2/messaging/channels/index.js +16 -0
  124. package/.claude-flow-novice/dist/src/coordination/v2/messaging/channels/index.js.map +1 -0
  125. package/.claude-flow-novice/dist/src/coordination/v2/messaging/channels/state-channel.js +295 -0
  126. package/.claude-flow-novice/dist/src/coordination/v2/messaging/channels/state-channel.js.map +1 -0
  127. package/.claude-flow-novice/dist/src/coordination/v2/messaging/channels/task-channel.js +411 -0
  128. package/.claude-flow-novice/dist/src/coordination/v2/messaging/channels/task-channel.js.map +1 -0
  129. package/.claude-flow-novice/dist/src/coordination/v2/messaging/index.js +14 -0
  130. package/.claude-flow-novice/dist/src/coordination/v2/messaging/index.js.map +1 -0
  131. package/.claude-flow-novice/dist/src/coordination/v2/messaging/message-bus.js +387 -0
  132. package/.claude-flow-novice/dist/src/coordination/v2/messaging/message-bus.js.map +1 -0
  133. package/.claude-flow-novice/dist/src/coordination/v2/messaging/message-persistence.js +589 -0
  134. package/.claude-flow-novice/dist/src/coordination/v2/messaging/message-persistence.js.map +1 -0
  135. package/.claude-flow-novice/dist/src/coordination/v2/messaging/message-router.js +444 -0
  136. package/.claude-flow-novice/dist/src/coordination/v2/messaging/message-router.js.map +1 -0
  137. package/.claude-flow-novice/dist/src/coordination/v2/sdk/checkpoint-manager.js +29 -8
  138. package/.claude-flow-novice/dist/src/coordination/v2/sdk/checkpoint-manager.js.map +1 -1
  139. package/.claude-flow-novice/dist/src/coordination/v2/sdk/help-coordinator.js +470 -0
  140. package/.claude-flow-novice/dist/src/coordination/v2/sdk/help-coordinator.js.map +1 -0
  141. package/.claude-flow-novice/dist/src/coordination/v2/sdk/hierarchical-background-integration.js +450 -0
  142. package/.claude-flow-novice/dist/src/coordination/v2/sdk/hierarchical-background-integration.js.map +1 -0
  143. package/.claude-flow-novice/dist/src/coordination/v2/sdk/index.js +5 -0
  144. package/.claude-flow-novice/dist/src/coordination/v2/sdk/index.js.map +1 -1
  145. package/.claude-flow-novice/dist/src/coordination/v2/sdk/multi-level-control.js +545 -0
  146. package/.claude-flow-novice/dist/src/coordination/v2/sdk/multi-level-control.js.map +1 -0
  147. package/.claude-flow-novice/dist/src/coordination/v2/sdk/query-controller.js +44 -0
  148. package/.claude-flow-novice/dist/src/coordination/v2/sdk/query-controller.js.map +1 -1
  149. package/.claude-flow-novice/dist/src/coordination/v2/sdk/query-message-integration.js +415 -0
  150. package/.claude-flow-novice/dist/src/coordination/v2/sdk/query-message-integration.js.map +1 -0
  151. package/.claude-flow-novice/dist/src/coordination/v2/sdk/session-pool-optimizer.js +615 -0
  152. package/.claude-flow-novice/dist/src/coordination/v2/sdk/session-pool-optimizer.js.map +1 -0
  153. package/.claude-flow-novice/dist/src/coordination/v2/security/payload-validator.js +259 -0
  154. package/.claude-flow-novice/dist/src/coordination/v2/security/payload-validator.js.map +1 -0
  155. package/.claude-flow-novice/dist/src/coordination/v2/transparency/index.js +17 -0
  156. package/.claude-flow-novice/dist/src/coordination/v2/transparency/index.js.map +1 -0
  157. package/.claude-flow-novice/dist/src/coordination/v2/transparency/transparency-integration.js +357 -0
  158. package/.claude-flow-novice/dist/src/coordination/v2/transparency/transparency-integration.js.map +1 -0
  159. package/.claude-flow-novice/dist/src/coordination/v2/transparency/transparency-system.js +679 -0
  160. package/.claude-flow-novice/dist/src/coordination/v2/transparency/transparency-system.js.map +1 -0
  161. package/.claude-flow-novice/dist/src/core/agent-manager.js +30 -0
  162. package/.claude-flow-novice/dist/src/core/agent-manager.js.map +1 -1
  163. package/.claude-flow-novice/dist/src/mcp/server.js +21 -2
  164. package/.claude-flow-novice/dist/src/mcp/server.js.map +1 -1
  165. package/.claude-flow-novice/dist/src/monitoring/apm/apm-integration.js +719 -0
  166. package/.claude-flow-novice/dist/src/monitoring/apm/apm-integration.js.map +1 -0
  167. package/.claude-flow-novice/dist/src/monitoring/apm/datadog-collector.js +363 -0
  168. package/.claude-flow-novice/dist/src/monitoring/apm/datadog-collector.js.map +1 -0
  169. package/.claude-flow-novice/dist/src/monitoring/apm/index.js +97 -0
  170. package/.claude-flow-novice/dist/src/monitoring/apm/index.js.map +1 -0
  171. package/.claude-flow-novice/dist/src/monitoring/apm/newrelic-collector.js +384 -0
  172. package/.claude-flow-novice/dist/src/monitoring/apm/newrelic-collector.js.map +1 -0
  173. package/.claude-flow-novice/dist/src/monitoring/apm/performance-optimizer.js +612 -0
  174. package/.claude-flow-novice/dist/src/monitoring/apm/performance-optimizer.js.map +1 -0
  175. package/.claude-flow-novice/dist/src/monitoring/metrics-collector.js +282 -0
  176. package/.claude-flow-novice/dist/src/monitoring/metrics-collector.js.map +1 -0
  177. package/.claude-flow-novice/dist/src/observability/metrics-counter.js +268 -0
  178. package/.claude-flow-novice/dist/src/observability/metrics-counter.js.map +1 -0
  179. package/.claude-flow-novice/dist/src/observability/metrics-storage.js +265 -0
  180. package/.claude-flow-novice/dist/src/observability/metrics-storage.js.map +1 -0
  181. package/.claude-flow-novice/dist/src/observability/telemetry.js +26 -0
  182. package/.claude-flow-novice/dist/src/observability/telemetry.js.map +1 -1
  183. package/.claude-flow-novice/dist/src/providers/tiered-router.js +64 -10
  184. package/.claude-flow-novice/dist/src/providers/tiered-router.js.map +1 -1
  185. package/.claude-flow-novice/dist/src/providers/zai-provider.js +196 -97
  186. package/.claude-flow-novice/dist/src/providers/zai-provider.js.map +1 -1
  187. package/.claude-flow-novice/dist/src/slash-commands/cfn-claude-sync.js +533 -0
  188. package/.claude-flow-novice/dist/src/slash-commands/index.js +5 -0
  189. package/.claude-flow-novice/dist/src/slash-commands/metrics-summary-class.js +74 -0
  190. package/.claude-flow-novice/dist/src/slash-commands/metrics-summary.js +335 -0
  191. package/.claude-flow-novice/dist/src/slash-commands/register-all-commands.js +12 -0
  192. package/.claude-flow-novice/dist/src/verification/checkpoint-compression-demo.js +96 -0
  193. package/.claude-flow-novice/dist/src/verification/checkpoint-compression-demo.js.map +1 -0
  194. package/.claude-flow-novice/dist/src/verification/checkpoint-compression.js +406 -0
  195. package/.claude-flow-novice/dist/src/verification/checkpoint-compression.js.map +1 -0
  196. package/.claude-flow-novice/dist/src/verification/checkpoint-manager.js +35 -5
  197. package/.claude-flow-novice/dist/src/verification/checkpoint-manager.js.map +1 -1
  198. package/.claude-flow-novice/dist/src/web/api/apm-routes.js +355 -0
  199. package/.claude-flow-novice/dist/src/web/api/apm-routes.js.map +1 -0
  200. package/.claude-flow-novice/dist/src/web/api/config/api-config.js +186 -0
  201. package/.claude-flow-novice/dist/src/web/api/config/api-config.js.map +1 -0
  202. package/.claude-flow-novice/dist/src/web/api/middleware/auth.js +205 -0
  203. package/.claude-flow-novice/dist/src/web/api/middleware/auth.js.map +1 -0
  204. package/.claude-flow-novice/dist/src/web/api/middleware/cache.js +262 -0
  205. package/.claude-flow-novice/dist/src/web/api/middleware/cache.js.map +1 -0
  206. package/.claude-flow-novice/dist/src/web/api/middleware/error-handler.js +250 -0
  207. package/.claude-flow-novice/dist/src/web/api/middleware/error-handler.js.map +1 -0
  208. package/.claude-flow-novice/dist/src/web/api/middleware/request-logger.js +217 -0
  209. package/.claude-flow-novice/dist/src/web/api/middleware/request-logger.js.map +1 -0
  210. package/.claude-flow-novice/dist/src/web/api/middleware/validation.js +325 -0
  211. package/.claude-flow-novice/dist/src/web/api/middleware/validation.js.map +1 -0
  212. package/.claude-flow-novice/dist/src/web/api/routes/events.js +465 -0
  213. package/.claude-flow-novice/dist/src/web/api/routes/events.js.map +1 -0
  214. package/.claude-flow-novice/dist/src/web/api/routes/hierarchy.js +302 -0
  215. package/.claude-flow-novice/dist/src/web/api/routes/hierarchy.js.map +1 -0
  216. package/.claude-flow-novice/dist/src/web/api/routes/index.js +14 -0
  217. package/.claude-flow-novice/dist/src/web/api/routes/index.js.map +1 -0
  218. package/.claude-flow-novice/dist/src/web/api/routes/metrics.js +561 -0
  219. package/.claude-flow-novice/dist/src/web/api/routes/metrics.js.map +1 -0
  220. package/.claude-flow-novice/dist/src/web/api/routes/status.js +450 -0
  221. package/.claude-flow-novice/dist/src/web/api/routes/status.js.map +1 -0
  222. package/.claude-flow-novice/dist/src/web/api/server.js +451 -0
  223. package/.claude-flow-novice/dist/src/web/api/server.js.map +1 -0
  224. package/.claude-flow-novice/dist/src/web/dashboard/hooks/useWebSocket.js +385 -0
  225. package/.claude-flow-novice/dist/src/web/dashboard/hooks/useWebSocket.js.map +1 -0
  226. package/.claude-flow-novice/dist/src/web/dashboard/index.js +87 -0
  227. package/.claude-flow-novice/dist/src/web/dashboard/index.js.map +1 -0
  228. package/.claude-flow-novice/dist/src/web/dashboard/types.js +6 -0
  229. package/.claude-flow-novice/dist/src/web/dashboard/types.js.map +1 -0
  230. package/.claude-flow-novice/dist/src/web/frontend/src/utils/security.js +425 -0
  231. package/.claude-flow-novice/dist/src/web/frontend/src/utils/security.js.map +1 -0
  232. package/.claude-flow-novice/dist/src/web/security/security-middleware.js +379 -0
  233. package/.claude-flow-novice/dist/src/web/security/security-middleware.js.map +1 -0
  234. package/.claude-flow-novice/dist/src/web/websocket/apm-websocket-handler.js +441 -0
  235. package/.claude-flow-novice/dist/src/web/websocket/apm-websocket-handler.js.map +1 -0
  236. package/.claude-flow-novice/dist/src/web/websocket/websocket-manager.js +255 -1
  237. package/.claude-flow-novice/dist/src/web/websocket/websocket-manager.js.map +1 -1
  238. package/.claude-flow-novice/metrics.db +0 -0
  239. package/.claude-flow-novice/metrics.db-shm +0 -0
  240. package/.claude-flow-novice/metrics.db-wal +0 -0
  241. package/AGENT_PERFORMANCE_GUIDELINES.md +88 -0
  242. package/CLAUDE.md +60 -3
  243. package/MEMORY_LEAK_ROOT_CAUSE.md +149 -0
  244. package/README.md +27 -0
  245. package/config/hooks/post-edit-pipeline.js +36 -2
  246. package/examples/metrics-counter-demo.ts +106 -0
  247. package/examples/persistent-metrics-demo.ts +83 -0
  248. package/examples/phase-5-multi-level-control.ts +282 -0
  249. package/examples/session-pool-optimizer-example.ts +311 -0
  250. package/package.json +18 -4
  251. package/scripts/check-routing-stats.cjs +122 -0
  252. package/scripts/monitor-loop.sh +65 -0
  253. package/scripts/monitor-memory.sh +47 -0
  254. package/scripts/monitor.py +43 -0
  255. package/scripts/pre-publish-validation.cjs +212 -0
  256. package/scripts/test-provider-routing.cjs +228 -0
  257. package/scripts/test-routing-telemetry.cjs +147 -0
  258. package/scripts/test-zai-10k.cjs +81 -0
  259. package/scripts/test-zai-api.cjs +191 -0
  260. package/scripts/test-zai-diagnostic.cjs +151 -0
  261. package/scripts/test-zai-final.cjs +128 -0
  262. package/scripts/test-zai-with-env.cjs +85 -0
  263. package/scripts/validate-coordination-cli.js +69 -0
  264. package/scripts/validate-coordination-toggle-integration.cjs +501 -0
  265. package/src/cli/simple-commands/init/templates/CLAUDE.md +29 -0
  266. package/src/observability/metrics-counter.ts +347 -0
  267. package/src/observability/metrics-storage.ts +356 -0
  268. package/src/observability/telemetry.ts +658 -0
  269. package/src/slash-commands/cfn-claude-sync.js +533 -0
  270. package/src/slash-commands/index.js +5 -0
  271. package/src/slash-commands/metrics-summary-class.js +74 -0
  272. package/src/slash-commands/metrics-summary.js +335 -0
  273. package/src/slash-commands/register-all-commands.js +12 -0
@@ -0,0 +1,228 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Test Provider Routing Configuration
5
+ *
6
+ * Verifies:
7
+ * 1. Agent SDK uses Anthropic API key
8
+ * 2. Agents route through Z.ai (tiered routing)
9
+ * 3. Metrics tracking works correctly
10
+ * 4. Main chat configured for Z.ai
11
+ */
12
+
13
+ const { execSync } = require('child_process');
14
+ const path = require('path');
15
+ const fs = require('fs');
16
+
17
+ console.log('๐Ÿงช Testing Provider Routing Configuration\n');
18
+ console.log('โ•'.repeat(80) + '\n');
19
+
20
+ // ============================================================================
21
+ // Test 1: Environment Configuration
22
+ // ============================================================================
23
+
24
+ console.log('๐Ÿ“‹ Test 1: Environment Configuration\n');
25
+
26
+ const envPath = path.join(__dirname, '../.env');
27
+ const envContent = fs.readFileSync(envPath, 'utf8');
28
+
29
+ const hasAnthropicKey = envContent.includes('ANTHROPIC_API_KEY=sk-ant-');
30
+ const hasZaiKey = envContent.includes('ZAI_API_KEY=cca13d09');
31
+
32
+ console.log(' .env file:');
33
+ console.log(` โœ… ANTHROPIC_API_KEY: ${hasAnthropicKey ? 'SET' : 'MISSING'}`);
34
+ console.log(` โœ… ZAI_API_KEY: ${hasZaiKey ? 'SET' : 'MISSING'}`);
35
+ console.log();
36
+
37
+ // ============================================================================
38
+ // Test 2: Main Chat Configuration
39
+ // ============================================================================
40
+
41
+ console.log('๐Ÿ“‹ Test 2: Main Chat Configuration (Global)\n');
42
+
43
+ const globalSettingsPath = path.join(process.env.HOME || process.env.USERPROFILE, '.claude', 'settings.json');
44
+
45
+ if (fs.existsSync(globalSettingsPath)) {
46
+ const globalSettings = JSON.parse(fs.readFileSync(globalSettingsPath, 'utf8'));
47
+
48
+ const baseUrl = globalSettings.env?.ANTHROPIC_BASE_URL;
49
+ const authToken = globalSettings.env?.ANTHROPIC_AUTH_TOKEN;
50
+
51
+ console.log(' ~/.claude/settings.json:');
52
+ console.log(` ${baseUrl === 'https://api.z.ai/api/anthropic' ? 'โœ…' : 'โŒ'} ANTHROPIC_BASE_URL: ${baseUrl || 'NOT SET'}`);
53
+ console.log(` ${authToken === '${ZAI_API_KEY}' ? 'โœ…' : 'โŒ'} ANTHROPIC_AUTH_TOKEN: ${authToken || 'NOT SET'}`);
54
+ console.log();
55
+
56
+ if (baseUrl === 'https://api.z.ai/api/anthropic') {
57
+ console.log(' โœ… Main chat configured to use Z.ai\n');
58
+ } else {
59
+ console.log(' โš ๏ธ Main chat NOT configured for Z.ai\n');
60
+ }
61
+ } else {
62
+ console.log(' โš ๏ธ Global settings file not found\n');
63
+ }
64
+
65
+ // ============================================================================
66
+ // Test 3: Agent SDK Configuration
67
+ // ============================================================================
68
+
69
+ console.log('๐Ÿ“‹ Test 3: Agent SDK Configuration\n');
70
+
71
+ const sdkConfigPath = path.join(__dirname, '../src/sdk/config.cjs');
72
+ const sdkConfig = fs.readFileSync(sdkConfigPath, 'utf8');
73
+
74
+ const usesEnvKey = sdkConfig.includes('process.env.CLAUDE_API_KEY') || sdkConfig.includes('process.env.ANTHROPIC_API_KEY');
75
+ const hasBaseUrl = sdkConfig.includes('baseURL') || sdkConfig.includes('base_url');
76
+
77
+ console.log(' src/sdk/config.cjs:');
78
+ console.log(` ${usesEnvKey ? 'โœ…' : 'โŒ'} Uses environment API key`);
79
+ console.log(` ${!hasBaseUrl ? 'โœ…' : 'โŒ'} NO custom base URL (hardcoded to Anthropic)`);
80
+ console.log();
81
+
82
+ if (usesEnvKey && !hasBaseUrl) {
83
+ console.log(' โœ… Agent SDK will use ANTHROPIC_API_KEY from .env\n');
84
+ console.log(' โ„น๏ธ Agent SDK cannot route through Z.ai (hardcoded to api.anthropic.com)\n');
85
+ } else {
86
+ console.log(' โš ๏ธ Agent SDK configuration unexpected\n');
87
+ }
88
+
89
+ // ============================================================================
90
+ // Test 4: Tiered Router Configuration
91
+ // ============================================================================
92
+
93
+ console.log('๐Ÿ“‹ Test 4: Tiered Router Configuration\n');
94
+
95
+ const routerPath = path.join(__dirname, '../.claude-flow-novice/dist/src/providers/tiered-router.js');
96
+
97
+ if (fs.existsSync(routerPath)) {
98
+ const routerContent = fs.readFileSync(routerPath, 'utf8');
99
+
100
+ const hasZai = routerContent.includes('z.ai') || routerContent.includes('zai');
101
+ const hasTiers = routerContent.includes('TIER_CONFIGS');
102
+
103
+ console.log(' Tiered Router:');
104
+ console.log(` ${hasTiers ? 'โœ…' : 'โŒ'} TIER_CONFIGS found`);
105
+ console.log(` ${hasZai ? 'โœ…' : 'โŒ'} Z.ai provider configured`);
106
+ console.log();
107
+
108
+ if (hasTiers && hasZai) {
109
+ console.log(' โœ… Agents will route through tiered system:\n');
110
+ console.log(' Tier 1: coordinator/architect/system-architect โ†’ Anthropic');
111
+ console.log(' Tier 2: All other agents โ†’ Z.ai\n');
112
+ }
113
+ } else {
114
+ console.log(' โš ๏ธ Compiled router not found (run npm run build)\n');
115
+ }
116
+
117
+ // ============================================================================
118
+ // Test 5: Metrics Database Analysis
119
+ // ============================================================================
120
+
121
+ console.log('๐Ÿ“‹ Test 5: Metrics Database Analysis (Last 24 Hours)\n');
122
+
123
+ const dbPath = path.join(__dirname, '../.claude-flow-novice/metrics.db');
124
+
125
+ if (fs.existsSync(dbPath)) {
126
+ const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
127
+
128
+ try {
129
+ // Query provider distribution
130
+ const providerQuery = `
131
+ SELECT
132
+ json_extract(tags, '$.provider') as provider,
133
+ COUNT(*) as count
134
+ FROM metrics
135
+ WHERE name = 'claude.api.request'
136
+ AND timestamp >= '${oneDayAgo}'
137
+ GROUP BY provider
138
+ ORDER BY count DESC
139
+ `;
140
+
141
+ const output = execSync(`sqlite3 "${dbPath}" "${providerQuery}"`, { encoding: 'utf8' });
142
+ const lines = output.trim().split('\n');
143
+
144
+ let anthropicCount = 0;
145
+ let zaiCount = 0;
146
+
147
+ lines.forEach(line => {
148
+ const [provider, count] = line.split('|');
149
+ if (provider === 'anthropic') anthropicCount = parseInt(count);
150
+ if (provider === 'z.ai') zaiCount = parseInt(count);
151
+ });
152
+
153
+ const total = anthropicCount + zaiCount;
154
+ const anthropicPercent = total > 0 ? ((anthropicCount / total) * 100).toFixed(1) : 0;
155
+ const zaiPercent = total > 0 ? ((zaiCount / total) * 100).toFixed(1) : 0;
156
+
157
+ console.log(' API Request Distribution:');
158
+ console.log(` Anthropic: ${anthropicCount} requests (${anthropicPercent}%)`);
159
+ console.log(` Z.ai: ${zaiCount} requests (${zaiPercent}%)`);
160
+ console.log(` TOTAL: ${total} requests\n`);
161
+
162
+ // Query model distribution
163
+ const modelQuery = `
164
+ SELECT
165
+ json_extract(tags, '$.provider') as provider,
166
+ json_extract(tags, '$.model') as model,
167
+ COUNT(*) as count
168
+ FROM metrics
169
+ WHERE name = 'claude.api.request'
170
+ AND timestamp >= '${oneDayAgo}'
171
+ GROUP BY provider, model
172
+ ORDER BY count DESC
173
+ `;
174
+
175
+ const modelOutput = execSync(`sqlite3 "${dbPath}" "${modelQuery}"`, { encoding: 'utf8' });
176
+ const modelLines = modelOutput.trim().split('\n');
177
+
178
+ console.log(' Model Usage:');
179
+ modelLines.forEach(line => {
180
+ const [provider, model, count] = line.split('|');
181
+ const shortModel = model.replace('claude-3-', '').replace('-20240229', '').replace('-20240307', '');
182
+ console.log(` ${provider.padEnd(10)} ${shortModel.padEnd(15)} ${count.padStart(3)} requests`);
183
+ });
184
+ console.log();
185
+
186
+ // Validation
187
+ if (total === 0) {
188
+ console.log(' โš ๏ธ No API requests found in last 24 hours\n');
189
+ } else if (zaiCount > 0) {
190
+ console.log(' โœ… Z.ai routing is WORKING - agents successfully using Z.ai API\n');
191
+ } else {
192
+ console.log(' โš ๏ธ No Z.ai requests detected - all traffic going to Anthropic\n');
193
+ }
194
+
195
+ } catch (error) {
196
+ console.log(' โŒ Error querying metrics database:', error.message);
197
+ console.log();
198
+ }
199
+ } else {
200
+ console.log(' โš ๏ธ Metrics database not found\n');
201
+ }
202
+
203
+ // ============================================================================
204
+ // Summary
205
+ // ============================================================================
206
+
207
+ console.log('โ•'.repeat(80) + '\n');
208
+ console.log('๐Ÿ“Š Configuration Summary\n');
209
+
210
+ console.log('โœ… WORKING AS DESIGNED:\n');
211
+ console.log(' 1. Main Chat โ†’ Z.ai (via global settings after restart)');
212
+ console.log(' 2. Tier 1 Agents โ†’ Anthropic (coordinator/architect/system-architect)');
213
+ console.log(' 3. Tier 2 Agents โ†’ Z.ai (all other agents)');
214
+ console.log(' 4. Agent SDK โ†’ Anthropic (hardcoded, no alternative)');
215
+ console.log();
216
+
217
+ console.log('๐Ÿ’ฐ COST OPTIMIZATION:\n');
218
+ console.log(' โ€ข Main chat uses Z.ai (lowest cost)');
219
+ console.log(' โ€ข Worker agents use Z.ai (bulk operations)');
220
+ console.log(' โ€ข Strategic agents use Anthropic (quality-critical)');
221
+ console.log(' โ€ข Agent SDK provides 90% cost savings via caching\n');
222
+
223
+ console.log('๐Ÿ” VERIFICATION:\n');
224
+ console.log(' โ€ข Check metrics with: /metrics-summary --minutes=60');
225
+ console.log(' โ€ข Monitor providers: /metrics-summary --provider=z.ai');
226
+ console.log(' โ€ข View all stats: /metrics-summary --minutes=1440\n');
227
+
228
+ console.log('โœ… All systems configured correctly!\n');
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Test Provider Routing Telemetry
3
+ *
4
+ * Tests tiered routing with telemetry to measure API calls to:
5
+ * - Z.ai (Tier 2 default)
6
+ * - Anthropic subscription (Tier 1)
7
+ * - Anthropic explicit (Tier 3)
8
+ */
9
+
10
+ const { TelemetrySystem } = require('../.claude-flow-novice/dist/src/observability/telemetry.js');
11
+ const { TieredProviderRouter } = require('../.claude-flow-novice/dist/src/providers/tiered-router.js');
12
+
13
+ async function testRoutingTelemetry() {
14
+ console.log('๐Ÿ”ฌ Testing Provider Routing Telemetry\n');
15
+
16
+ // Initialize telemetry
17
+ const telemetry = new TelemetrySystem({
18
+ enableTracing: true,
19
+ enableMetrics: true,
20
+ enableStructuredLogging: true,
21
+ });
22
+
23
+ telemetry.initialize();
24
+
25
+ // Listen to metric events
26
+ const metricEvents = [];
27
+ telemetry.on('metric:counter', (metric) => {
28
+ if (metric.name === 'provider.request') {
29
+ metricEvents.push(metric);
30
+ console.log(`๐Ÿ“Š Metric: ${metric.tags.provider} via ${metric.tags.tier} (agent: ${metric.tags.agentType})`);
31
+ }
32
+ });
33
+
34
+ telemetry.on('metric:gauge', (metric) => {
35
+ if (metric.name === 'subscription.usage') {
36
+ console.log(`๐Ÿ“ˆ Subscription: ${metric.value}/${metric.tags.limit} (${metric.tags.remaining} remaining)`);
37
+ }
38
+ });
39
+
40
+ // Create tiered router with injected telemetry instance
41
+ const router = new TieredProviderRouter(
42
+ undefined, // Use default tier config
43
+ { used: 0, limit: 5 }, // Mock subscription: 5 requests limit
44
+ undefined, // Use default agents directory
45
+ telemetry // Inject telemetry instance to capture metrics
46
+ );
47
+
48
+ console.log('๐ŸŽฏ Test Scenario: Simulate 10 agent requests\n');
49
+
50
+ // Test 1: Default agents (should use Z.ai)
51
+ console.log('--- Test 1: Default agents (Z.ai expected) ---');
52
+ for (let i = 0; i < 3; i++) {
53
+ await router.selectProvider('coder');
54
+ }
55
+
56
+ // Test 2: Coordinator agents (should use subscription until exhausted)
57
+ console.log('\n--- Test 2: Coordinator agents (subscription expected) ---');
58
+ for (let i = 0; i < 4; i++) {
59
+ await router.selectProvider('coordinator');
60
+ }
61
+
62
+ // Test 3: More coordinator agents (subscription exhausted, fallback to Z.ai)
63
+ console.log('\n--- Test 3: More coordinators (fallback to Z.ai expected) ---');
64
+ for (let i = 0; i < 3; i++) {
65
+ await router.selectProvider('coordinator');
66
+ }
67
+
68
+ // Wait for metrics flush
69
+ await new Promise(resolve => setTimeout(resolve, 100));
70
+
71
+ // Analyze results
72
+ console.log('\n๐Ÿ“Š === TELEMETRY RESULTS ===\n');
73
+
74
+ const providerBreakdown = {};
75
+ const tierBreakdown = {};
76
+ const sourceBreakdown = {};
77
+
78
+ metricEvents.forEach(metric => {
79
+ const provider = metric.tags.provider;
80
+ const tier = metric.tags.tier;
81
+ const source = metric.tags.source;
82
+
83
+ providerBreakdown[provider] = (providerBreakdown[provider] || 0) + metric.value;
84
+ tierBreakdown[tier] = (tierBreakdown[tier] || 0) + metric.value;
85
+ sourceBreakdown[source] = (sourceBreakdown[source] || 0) + metric.value;
86
+ });
87
+
88
+ console.log('By Provider:');
89
+ Object.entries(providerBreakdown).forEach(([provider, count]) => {
90
+ console.log(` ${provider}: ${count} requests`);
91
+ });
92
+
93
+ console.log('\nBy Tier:');
94
+ Object.entries(tierBreakdown).forEach(([tier, count]) => {
95
+ console.log(` ${tier}: ${count} requests`);
96
+ });
97
+
98
+ console.log('\nBy Source:');
99
+ Object.entries(sourceBreakdown).forEach(([source, count]) => {
100
+ console.log(` ${source}: ${count} requests`);
101
+ });
102
+
103
+ // Get subscription usage
104
+ const subUsage = router.getSubscriptionUsage();
105
+ console.log('\n๐Ÿ“Š Subscription Usage:');
106
+ console.log(` Used: ${subUsage.used}/${subUsage.limit}`);
107
+ console.log(` Remaining: ${subUsage.limit - subUsage.used}`);
108
+
109
+ // Validate expectations
110
+ console.log('\nโœ… === VALIDATION ===\n');
111
+
112
+ const zaiCount = providerBreakdown['custom'] || 0;
113
+ const anthropicCount = providerBreakdown['anthropic'] || 0;
114
+
115
+ console.log(`Z.ai requests: ${zaiCount} (expected: 5 - 3 coder + 2 fallback)`);
116
+ console.log(`Anthropic requests: ${anthropicCount} (expected: 5 - subscription limit reached)`);
117
+
118
+ if (zaiCount === 5 && anthropicCount === 5) {
119
+ console.log('\nโœ… SUCCESS: Telemetry correctly tracked routing decisions!');
120
+ console.log(' - Z.ai received 3 coder requests via profile override');
121
+ console.log(' - Subscription tier consumed all 5 slots for coordinators');
122
+ console.log(' - 2 coordinator requests fell back to Z.ai after limit');
123
+ console.log(' - All 10 requests were measured correctly');
124
+ } else {
125
+ console.log('\nโŒ UNEXPECTED: Metric counts differ from expected');
126
+ }
127
+
128
+ // Query telemetry directly
129
+ console.log('\n๐Ÿ“ˆ === TELEMETRY QUERY ===\n');
130
+ const providerMetrics = telemetry.getMetrics('provider.request');
131
+ console.log(`Total provider.request metrics: ${providerMetrics.length}`);
132
+
133
+ const throughput = telemetry.getThroughputMetrics('provider.request', 60000);
134
+ console.log(`Throughput: ${throughput.requestsPerSecond.toFixed(2)} req/s`);
135
+ console.log(`Success rate: ${(throughput.successRate * 100).toFixed(1)}%`);
136
+
137
+ // Cleanup
138
+ telemetry.shutdown();
139
+
140
+ console.log('\n๐ŸŽ‰ Test complete!\n');
141
+ }
142
+
143
+ // Run test
144
+ testRoutingTelemetry().catch(err => {
145
+ console.error('โŒ Test failed:', err);
146
+ process.exit(1);
147
+ });
@@ -0,0 +1,81 @@
1
+ #!/usr/bin/env node
2
+
3
+ const https = require('https');
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+
7
+ // Load .env
8
+ const envPath = path.join(process.cwd(), '.env');
9
+ if (fs.existsSync(envPath)) {
10
+ fs.readFileSync(envPath, 'utf8').split('\n').forEach(line => {
11
+ const match = line.trim().match(/^([^=]+)=(.*)$/);
12
+ if (match) {
13
+ const key = match[1].trim();
14
+ let value = match[2].trim().replace(/^["']|["']$/g, '');
15
+ process.env[key] = value;
16
+ }
17
+ });
18
+ }
19
+
20
+ const API_KEY = process.env.ZAI_API_KEY;
21
+
22
+ console.log('\n๐Ÿš€ Z.ai API Test - 10K Max Tokens\n');
23
+ console.log('='.repeat(80) + '\n');
24
+
25
+ const payload = {
26
+ model: 'claude-3-5-sonnet-20241022',
27
+ max_tokens: 10000,
28
+ messages: [
29
+ { role: 'user', content: 'Write a haiku about AI and coding. Then explain why you chose those words.' }
30
+ ]
31
+ };
32
+
33
+ const url = new URL('https://api.z.ai/api/anthropic/v1/messages');
34
+
35
+ const options = {
36
+ hostname: url.hostname,
37
+ port: 443,
38
+ path: url.pathname,
39
+ method: 'POST',
40
+ headers: {
41
+ 'Content-Type': 'application/json',
42
+ 'x-api-key': API_KEY,
43
+ 'anthropic-version': '2023-06-01'
44
+ }
45
+ };
46
+
47
+ const req = https.request(options, (res) => {
48
+ let body = '';
49
+ res.on('data', chunk => body += chunk);
50
+ res.on('end', () => {
51
+ const result = JSON.parse(body);
52
+
53
+ console.log('โœ… Response received!\n');
54
+ console.log('Status:', res.statusCode);
55
+ console.log('Model:', result.model);
56
+ console.log('\nContent:');
57
+ console.log(result.content[0].text);
58
+ console.log('\nToken usage:');
59
+ console.log(' Input:', result.usage.input_tokens);
60
+ console.log(' Output:', result.usage.output_tokens);
61
+ console.log(' Total:', result.usage.input_tokens + result.usage.output_tokens);
62
+
63
+ const cost = (result.usage.input_tokens / 1000 * 0.003) +
64
+ (result.usage.output_tokens / 1000 * 0.015);
65
+ console.log('\nEstimated cost: $' + cost.toFixed(6));
66
+ console.log('\n' + '='.repeat(80) + '\n');
67
+ console.log('โœ… Z.ai with 10K max_tokens working correctly!\n');
68
+ });
69
+ });
70
+
71
+ req.on('error', (error) => {
72
+ console.error('โŒ Error:', error.message);
73
+ });
74
+
75
+ req.setTimeout(45000, () => {
76
+ req.destroy();
77
+ console.error('โŒ Request timeout');
78
+ });
79
+
80
+ req.write(JSON.stringify(payload));
81
+ req.end();
@@ -0,0 +1,191 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Direct Z.ai API Test
5
+ * Tests Z.ai API connectivity and response
6
+ */
7
+
8
+ const https = require('https');
9
+ const http = require('http');
10
+
11
+ const API_KEY = process.env.Z_AI_API_KEY || process.env.ZAI_API_KEY || process.env.ANTHROPIC_AUTH_TOKEN;
12
+ const BASE_URL = 'https://api.z.ai/api/anthropic';
13
+ const DEFAULT_MODEL = 'claude-3-5-sonnet-20241022';
14
+
15
+ function makeRequest(options, data) {
16
+ return new Promise((resolve, reject) => {
17
+ const protocol = options.protocol === 'https:' ? https : http;
18
+
19
+ const req = protocol.request(options, (res) => {
20
+ let body = '';
21
+
22
+ res.on('data', (chunk) => {
23
+ body += chunk;
24
+ });
25
+
26
+ res.on('end', () => {
27
+ if (res.statusCode >= 200 && res.statusCode < 300) {
28
+ try {
29
+ resolve({
30
+ statusCode: res.statusCode,
31
+ headers: res.headers,
32
+ body: JSON.parse(body)
33
+ });
34
+ } catch (e) {
35
+ resolve({
36
+ statusCode: res.statusCode,
37
+ headers: res.headers,
38
+ body: body
39
+ });
40
+ }
41
+ } else {
42
+ reject(new Error(`HTTP ${res.statusCode}: ${body}`));
43
+ }
44
+ });
45
+ });
46
+
47
+ req.on('error', (error) => {
48
+ reject(error);
49
+ });
50
+
51
+ req.setTimeout(30000, () => {
52
+ req.destroy();
53
+ reject(new Error('Request timeout after 30s'));
54
+ });
55
+
56
+ if (data) {
57
+ req.write(data);
58
+ }
59
+
60
+ req.end();
61
+ });
62
+ }
63
+
64
+ async function testZaiAPI() {
65
+ console.log('\n๐Ÿงช Z.ai API Direct Test\n');
66
+ console.log('='.repeat(80) + '\n');
67
+
68
+ // Check API key
69
+ if (!API_KEY) {
70
+ console.error('โŒ ERROR: Z_AI_API_KEY or ZAI_API_KEY environment variable not set');
71
+ console.log('\nPlease set your Z.ai API key:');
72
+ console.log(' export ZAI_API_KEY="your-api-key-here"');
73
+ console.log(' or');
74
+ console.log(' ZAI_API_KEY="your-api-key-here" node scripts/test-zai-api.cjs\n');
75
+ process.exit(1);
76
+ }
77
+
78
+ console.log('โœ“ API Key found:', API_KEY.substring(0, 10) + '...' + API_KEY.substring(API_KEY.length - 4));
79
+ console.log('โœ“ Base URL:', BASE_URL);
80
+ console.log('โœ“ Model:', DEFAULT_MODEL);
81
+ console.log('\n' + '-'.repeat(80) + '\n');
82
+
83
+ // Test payload (Anthropic Messages API format)
84
+ const payload = {
85
+ model: DEFAULT_MODEL,
86
+ max_tokens: 50,
87
+ messages: [
88
+ {
89
+ role: 'user',
90
+ content: 'Say "Hello from Z.ai!" and nothing else.'
91
+ }
92
+ ]
93
+ };
94
+
95
+ console.log('๐Ÿ“ค Sending request...\n');
96
+ console.log('Request payload:');
97
+ console.log(JSON.stringify(payload, null, 2));
98
+ console.log('\n' + '-'.repeat(80) + '\n');
99
+
100
+ try {
101
+ const url = new URL(`${BASE_URL}/v1/messages`);
102
+
103
+ const options = {
104
+ hostname: url.hostname,
105
+ port: url.port || 443,
106
+ path: url.pathname,
107
+ method: 'POST',
108
+ protocol: url.protocol,
109
+ headers: {
110
+ 'Content-Type': 'application/json',
111
+ 'x-api-key': API_KEY,
112
+ 'anthropic-version': '2023-06-01'
113
+ }
114
+ };
115
+
116
+ const startTime = Date.now();
117
+ const response = await makeRequest(options, JSON.stringify(payload));
118
+ const duration = Date.now() - startTime;
119
+
120
+ console.log('๐Ÿ“ฅ Response received!\n');
121
+ console.log(`โฑ๏ธ Duration: ${duration}ms`);
122
+ console.log(`๐Ÿ“Š Status: ${response.statusCode}`);
123
+ console.log('\n' + '-'.repeat(80) + '\n');
124
+
125
+ if (response.body.content && response.body.content.length > 0) {
126
+ console.log('โœ… SUCCESS!\n');
127
+ console.log('Response content:');
128
+ console.log(' ' + response.body.content[0].text);
129
+ console.log('\nModel:', response.body.model);
130
+ console.log('Stop reason:', response.body.stop_reason);
131
+
132
+ if (response.body.usage) {
133
+ console.log('\nToken usage:');
134
+ console.log(' Input tokens: ', response.body.usage.input_tokens);
135
+ console.log(' Output tokens: ', response.body.usage.output_tokens);
136
+
137
+ // Calculate cost (Z.ai pricing: $0.003 per 1K prompt, $0.015 per 1K completion)
138
+ const promptCost = (response.body.usage.input_tokens / 1000) * 0.003;
139
+ const completionCost = (response.body.usage.output_tokens / 1000) * 0.015;
140
+ const totalCost = promptCost + completionCost;
141
+
142
+ console.log('\nEstimated cost:');
143
+ console.log(` Input: $${promptCost.toFixed(6)}`);
144
+ console.log(` Output: $${completionCost.toFixed(6)}`);
145
+ console.log(` Total: $${totalCost.toFixed(6)}`);
146
+ }
147
+
148
+ console.log('\n' + '='.repeat(80));
149
+ console.log('\nโœ… Z.ai API is working correctly!\n');
150
+
151
+ return {
152
+ success: true,
153
+ response: response.body,
154
+ duration
155
+ };
156
+ } else {
157
+ console.log('โš ๏ธ Warning: Unexpected response format');
158
+ console.log('\nFull response:');
159
+ console.log(JSON.stringify(response.body, null, 2));
160
+ console.log('\n' + '='.repeat(80) + '\n');
161
+
162
+ return {
163
+ success: false,
164
+ error: 'Unexpected response format',
165
+ response: response.body
166
+ };
167
+ }
168
+ } catch (error) {
169
+ console.error('โŒ ERROR:\n');
170
+ console.error(error.message);
171
+
172
+ if (error.message.includes('401')) {
173
+ console.log('\n๐Ÿ’ก Tip: Check that your Z_AI_API_KEY is valid');
174
+ } else if (error.message.includes('429')) {
175
+ console.log('\n๐Ÿ’ก Tip: Rate limit exceeded. Wait a moment and try again');
176
+ } else if (error.message.includes('ENOTFOUND') || error.message.includes('ECONNREFUSED')) {
177
+ console.log('\n๐Ÿ’ก Tip: Check your internet connection');
178
+ }
179
+
180
+ console.log('\n' + '='.repeat(80) + '\n');
181
+ process.exit(1);
182
+ }
183
+ }
184
+
185
+ // Run test
186
+ testZaiAPI()
187
+ .then(() => process.exit(0))
188
+ .catch((error) => {
189
+ console.error('\nโŒ Unhandled error:', error);
190
+ process.exit(1);
191
+ });