snow-flow 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (240) hide show
  1. package/.env.example +49 -0
  2. package/.mcp.json +106 -0
  3. package/.mcp.json.template +106 -0
  4. package/LICENSE +21 -0
  5. package/README.md +236 -0
  6. package/bin/snow-flow +4 -0
  7. package/bin/snow-flow.js +3 -0
  8. package/claude-flow +79 -0
  9. package/claude-flow.bat +18 -0
  10. package/claude-flow.config.json +20 -0
  11. package/claude-flow.ps1 +24 -0
  12. package/dist/agents/app-creator.agent.d.ts +55 -0
  13. package/dist/agents/app-creator.agent.d.ts.map +1 -0
  14. package/dist/agents/app-creator.agent.js +1292 -0
  15. package/dist/agents/app-creator.agent.js.map +1 -0
  16. package/dist/agents/base-snow-agent.d.ts +63 -0
  17. package/dist/agents/base-snow-agent.d.ts.map +1 -0
  18. package/dist/agents/base-snow-agent.js +296 -0
  19. package/dist/agents/base-snow-agent.js.map +1 -0
  20. package/dist/agents/script-generator.agent.d.ts +32 -0
  21. package/dist/agents/script-generator.agent.d.ts.map +1 -0
  22. package/dist/agents/script-generator.agent.js +772 -0
  23. package/dist/agents/script-generator.agent.js.map +1 -0
  24. package/dist/agents/ui-builder.agent.d.ts +50 -0
  25. package/dist/agents/ui-builder.agent.d.ts.map +1 -0
  26. package/dist/agents/ui-builder.agent.js +1539 -0
  27. package/dist/agents/ui-builder.agent.js.map +1 -0
  28. package/dist/agents/widget-builder.agent.d.ts +32 -0
  29. package/dist/agents/widget-builder.agent.d.ts.map +1 -0
  30. package/dist/agents/widget-builder.agent.js +439 -0
  31. package/dist/agents/widget-builder.agent.js.map +1 -0
  32. package/dist/agents/workflow-designer.agent.d.ts +31 -0
  33. package/dist/agents/workflow-designer.agent.d.ts.map +1 -0
  34. package/dist/agents/workflow-designer.agent.js +583 -0
  35. package/dist/agents/workflow-designer.agent.js.map +1 -0
  36. package/dist/api/error-handling.d.ts +214 -0
  37. package/dist/api/error-handling.d.ts.map +1 -0
  38. package/dist/api/error-handling.js +594 -0
  39. package/dist/api/error-handling.js.map +1 -0
  40. package/dist/api/flow-designer-api.d.ts +167 -0
  41. package/dist/api/flow-designer-api.d.ts.map +1 -0
  42. package/dist/api/flow-designer-api.js +555 -0
  43. package/dist/api/flow-designer-api.js.map +1 -0
  44. package/dist/api/natural-language-mapper.d.ts +126 -0
  45. package/dist/api/natural-language-mapper.d.ts.map +1 -0
  46. package/dist/api/natural-language-mapper.js +498 -0
  47. package/dist/api/natural-language-mapper.js.map +1 -0
  48. package/dist/api/performance-optimizer.d.ts +240 -0
  49. package/dist/api/performance-optimizer.d.ts.map +1 -0
  50. package/dist/api/performance-optimizer.js +701 -0
  51. package/dist/api/performance-optimizer.js.map +1 -0
  52. package/dist/api/transaction-manager.d.ts +189 -0
  53. package/dist/api/transaction-manager.d.ts.map +1 -0
  54. package/dist/api/transaction-manager.js +576 -0
  55. package/dist/api/transaction-manager.js.map +1 -0
  56. package/dist/cli/deploy-artifact.d.ts +7 -0
  57. package/dist/cli/deploy-artifact.d.ts.map +1 -0
  58. package/dist/cli/deploy-artifact.js +279 -0
  59. package/dist/cli/deploy-artifact.js.map +1 -0
  60. package/dist/cli.d.ts +6 -0
  61. package/dist/cli.d.ts.map +1 -0
  62. package/dist/cli.js +2057 -0
  63. package/dist/cli.js.map +1 -0
  64. package/dist/index.d.ts +10 -0
  65. package/dist/index.d.ts.map +1 -0
  66. package/dist/index.js +35 -0
  67. package/dist/index.js.map +1 -0
  68. package/dist/managers/scope-manager.d.ts +75 -0
  69. package/dist/managers/scope-manager.d.ts.map +1 -0
  70. package/dist/managers/scope-manager.js +448 -0
  71. package/dist/managers/scope-manager.js.map +1 -0
  72. package/dist/mcp/mcp-wrapper.d.ts +8 -0
  73. package/dist/mcp/mcp-wrapper.d.ts.map +1 -0
  74. package/dist/mcp/mcp-wrapper.js +77 -0
  75. package/dist/mcp/mcp-wrapper.js.map +1 -0
  76. package/dist/mcp/servicenow-automation-mcp.d.ts +8 -0
  77. package/dist/mcp/servicenow-automation-mcp.d.ts.map +1 -0
  78. package/dist/mcp/servicenow-automation-mcp.js +683 -0
  79. package/dist/mcp/servicenow-automation-mcp.js.map +1 -0
  80. package/dist/mcp/servicenow-deployment-mcp.d.ts +7 -0
  81. package/dist/mcp/servicenow-deployment-mcp.d.ts.map +1 -0
  82. package/dist/mcp/servicenow-deployment-mcp.js +972 -0
  83. package/dist/mcp/servicenow-deployment-mcp.js.map +1 -0
  84. package/dist/mcp/servicenow-flow-composer-mcp.d.ts +7 -0
  85. package/dist/mcp/servicenow-flow-composer-mcp.d.ts.map +1 -0
  86. package/dist/mcp/servicenow-flow-composer-mcp.js +1121 -0
  87. package/dist/mcp/servicenow-flow-composer-mcp.js.map +1 -0
  88. package/dist/mcp/servicenow-graph-memory-mcp.d.ts +7 -0
  89. package/dist/mcp/servicenow-graph-memory-mcp.d.ts.map +1 -0
  90. package/dist/mcp/servicenow-graph-memory-mcp.js +703 -0
  91. package/dist/mcp/servicenow-graph-memory-mcp.js.map +1 -0
  92. package/dist/mcp/servicenow-integration-mcp.d.ts +8 -0
  93. package/dist/mcp/servicenow-integration-mcp.d.ts.map +1 -0
  94. package/dist/mcp/servicenow-integration-mcp.js +689 -0
  95. package/dist/mcp/servicenow-integration-mcp.js.map +1 -0
  96. package/dist/mcp/servicenow-intelligent-mcp.d.ts +7 -0
  97. package/dist/mcp/servicenow-intelligent-mcp.d.ts.map +1 -0
  98. package/dist/mcp/servicenow-intelligent-mcp.js +1138 -0
  99. package/dist/mcp/servicenow-intelligent-mcp.js.map +1 -0
  100. package/dist/mcp/servicenow-mcp-server.d.ts +37 -0
  101. package/dist/mcp/servicenow-mcp-server.d.ts.map +1 -0
  102. package/dist/mcp/servicenow-mcp-server.js +648 -0
  103. package/dist/mcp/servicenow-mcp-server.js.map +1 -0
  104. package/dist/mcp/servicenow-operations-mcp.d.ts +15 -0
  105. package/dist/mcp/servicenow-operations-mcp.d.ts.map +1 -0
  106. package/dist/mcp/servicenow-operations-mcp.js +1287 -0
  107. package/dist/mcp/servicenow-operations-mcp.js.map +1 -0
  108. package/dist/mcp/servicenow-platform-development-mcp.d.ts +8 -0
  109. package/dist/mcp/servicenow-platform-development-mcp.d.ts.map +1 -0
  110. package/dist/mcp/servicenow-platform-development-mcp.js +557 -0
  111. package/dist/mcp/servicenow-platform-development-mcp.js.map +1 -0
  112. package/dist/mcp/servicenow-progressive-indexer.d.ts +79 -0
  113. package/dist/mcp/servicenow-progressive-indexer.d.ts.map +1 -0
  114. package/dist/mcp/servicenow-progressive-indexer.js +320 -0
  115. package/dist/mcp/servicenow-progressive-indexer.js.map +1 -0
  116. package/dist/mcp/servicenow-reporting-analytics-mcp.d.ts +8 -0
  117. package/dist/mcp/servicenow-reporting-analytics-mcp.d.ts.map +1 -0
  118. package/dist/mcp/servicenow-reporting-analytics-mcp.js +888 -0
  119. package/dist/mcp/servicenow-reporting-analytics-mcp.js.map +1 -0
  120. package/dist/mcp/servicenow-security-compliance-mcp.d.ts +8 -0
  121. package/dist/mcp/servicenow-security-compliance-mcp.d.ts.map +1 -0
  122. package/dist/mcp/servicenow-security-compliance-mcp.js +812 -0
  123. package/dist/mcp/servicenow-security-compliance-mcp.js.map +1 -0
  124. package/dist/mcp/servicenow-update-set-mcp.d.ts +7 -0
  125. package/dist/mcp/servicenow-update-set-mcp.d.ts.map +1 -0
  126. package/dist/mcp/servicenow-update-set-mcp.js +599 -0
  127. package/dist/mcp/servicenow-update-set-mcp.js.map +1 -0
  128. package/dist/mcp/start-all-mcp-servers.d.ts +6 -0
  129. package/dist/mcp/start-all-mcp-servers.d.ts.map +1 -0
  130. package/dist/mcp/start-all-mcp-servers.js +65 -0
  131. package/dist/mcp/start-all-mcp-servers.js.map +1 -0
  132. package/dist/mcp/start-servicenow-mcp.d.ts +7 -0
  133. package/dist/mcp/start-servicenow-mcp.d.ts.map +1 -0
  134. package/dist/mcp/start-servicenow-mcp.js +64 -0
  135. package/dist/mcp/start-servicenow-mcp.js.map +1 -0
  136. package/dist/mcp/test-simple-mcp.d.ts +6 -0
  137. package/dist/mcp/test-simple-mcp.d.ts.map +1 -0
  138. package/dist/mcp/test-simple-mcp.js +64 -0
  139. package/dist/mcp/test-simple-mcp.js.map +1 -0
  140. package/dist/orchestrator/flow-composer.d.ts +269 -0
  141. package/dist/orchestrator/flow-composer.d.ts.map +1 -0
  142. package/dist/orchestrator/flow-composer.js +2221 -0
  143. package/dist/orchestrator/flow-composer.js.map +1 -0
  144. package/dist/orchestrator/flow-pattern-templates.d.ts +260 -0
  145. package/dist/orchestrator/flow-pattern-templates.d.ts.map +1 -0
  146. package/dist/orchestrator/flow-pattern-templates.js +906 -0
  147. package/dist/orchestrator/flow-pattern-templates.js.map +1 -0
  148. package/dist/orchestrator/flow-subflow-decision-engine.d.ts +202 -0
  149. package/dist/orchestrator/flow-subflow-decision-engine.d.ts.map +1 -0
  150. package/dist/orchestrator/flow-subflow-decision-engine.js +769 -0
  151. package/dist/orchestrator/flow-subflow-decision-engine.js.map +1 -0
  152. package/dist/orchestrator/flow-validation-engine.d.ts +145 -0
  153. package/dist/orchestrator/flow-validation-engine.d.ts.map +1 -0
  154. package/dist/orchestrator/flow-validation-engine.js +663 -0
  155. package/dist/orchestrator/flow-validation-engine.js.map +1 -0
  156. package/dist/orchestrator/snow-orchestrator.d.ts +49 -0
  157. package/dist/orchestrator/snow-orchestrator.d.ts.map +1 -0
  158. package/dist/orchestrator/snow-orchestrator.js +235 -0
  159. package/dist/orchestrator/snow-orchestrator.js.map +1 -0
  160. package/dist/orchestrator/subflow-creation-handler.d.ts +230 -0
  161. package/dist/orchestrator/subflow-creation-handler.d.ts.map +1 -0
  162. package/dist/orchestrator/subflow-creation-handler.js +791 -0
  163. package/dist/orchestrator/subflow-creation-handler.js.map +1 -0
  164. package/dist/strategies/global-scope-strategy.d.ts +123 -0
  165. package/dist/strategies/global-scope-strategy.d.ts.map +1 -0
  166. package/dist/strategies/global-scope-strategy.js +585 -0
  167. package/dist/strategies/global-scope-strategy.js.map +1 -0
  168. package/dist/types/index.d.ts +138 -0
  169. package/dist/types/index.d.ts.map +1 -0
  170. package/dist/types/index.js +4 -0
  171. package/dist/types/index.js.map +1 -0
  172. package/dist/types/servicenow.types.d.ts +260 -0
  173. package/dist/types/servicenow.types.d.ts.map +1 -0
  174. package/dist/types/servicenow.types.js +3 -0
  175. package/dist/types/servicenow.types.js.map +1 -0
  176. package/dist/types/snow-flow.types.d.ts +114 -0
  177. package/dist/types/snow-flow.types.d.ts.map +1 -0
  178. package/dist/types/snow-flow.types.js +3 -0
  179. package/dist/types/snow-flow.types.js.map +1 -0
  180. package/dist/utils/action-type-cache.d.ts +66 -0
  181. package/dist/utils/action-type-cache.d.ts.map +1 -0
  182. package/dist/utils/action-type-cache.js +237 -0
  183. package/dist/utils/action-type-cache.js.map +1 -0
  184. package/dist/utils/agent-detector.d.ts +35 -0
  185. package/dist/utils/agent-detector.d.ts.map +1 -0
  186. package/dist/utils/agent-detector.js +353 -0
  187. package/dist/utils/agent-detector.js.map +1 -0
  188. package/dist/utils/flow-api-discovery.d.ts +151 -0
  189. package/dist/utils/flow-api-discovery.d.ts.map +1 -0
  190. package/dist/utils/flow-api-discovery.js +440 -0
  191. package/dist/utils/flow-api-discovery.js.map +1 -0
  192. package/dist/utils/flow-xml-generator.d.ts +41 -0
  193. package/dist/utils/flow-xml-generator.d.ts.map +1 -0
  194. package/dist/utils/flow-xml-generator.js +258 -0
  195. package/dist/utils/flow-xml-generator.js.map +1 -0
  196. package/dist/utils/logger.d.ts +13 -0
  197. package/dist/utils/logger.d.ts.map +1 -0
  198. package/dist/utils/logger.js +51 -0
  199. package/dist/utils/logger.js.map +1 -0
  200. package/dist/utils/mcp-auth-middleware.d.ts +58 -0
  201. package/dist/utils/mcp-auth-middleware.d.ts.map +1 -0
  202. package/dist/utils/mcp-auth-middleware.js +227 -0
  203. package/dist/utils/mcp-auth-middleware.js.map +1 -0
  204. package/dist/utils/mcp-config-manager.d.ts +126 -0
  205. package/dist/utils/mcp-config-manager.d.ts.map +1 -0
  206. package/dist/utils/mcp-config-manager.js +209 -0
  207. package/dist/utils/mcp-config-manager.js.map +1 -0
  208. package/dist/utils/mcp-server-manager.d.ts +91 -0
  209. package/dist/utils/mcp-server-manager.d.ts.map +1 -0
  210. package/dist/utils/mcp-server-manager.js +338 -0
  211. package/dist/utils/mcp-server-manager.js.map +1 -0
  212. package/dist/utils/scope-utils.d.ts +72 -0
  213. package/dist/utils/scope-utils.d.ts.map +1 -0
  214. package/dist/utils/scope-utils.js +386 -0
  215. package/dist/utils/scope-utils.js.map +1 -0
  216. package/dist/utils/servicenow-client.d.ts +233 -0
  217. package/dist/utils/servicenow-client.d.ts.map +1 -0
  218. package/dist/utils/servicenow-client.js +1465 -0
  219. package/dist/utils/servicenow-client.js.map +1 -0
  220. package/dist/utils/snow-oauth-old.d.ts +65 -0
  221. package/dist/utils/snow-oauth-old.d.ts.map +1 -0
  222. package/dist/utils/snow-oauth-old.js +345 -0
  223. package/dist/utils/snow-oauth-old.js.map +1 -0
  224. package/dist/utils/snow-oauth.d.ts +85 -0
  225. package/dist/utils/snow-oauth.d.ts.map +1 -0
  226. package/dist/utils/snow-oauth.js +512 -0
  227. package/dist/utils/snow-oauth.js.map +1 -0
  228. package/dist/utils/template-engine.d.ts +76 -0
  229. package/dist/utils/template-engine.d.ts.map +1 -0
  230. package/dist/utils/template-engine.js +391 -0
  231. package/dist/utils/template-engine.js.map +1 -0
  232. package/dist/version.d.ts +35 -0
  233. package/dist/version.d.ts.map +1 -0
  234. package/dist/version.js +72 -0
  235. package/dist/version.js.map +1 -0
  236. package/mcp-wrapper.sh +12 -0
  237. package/package.json +77 -0
  238. package/reports/swarm-auto-centralized-1752649029776.json +13 -0
  239. package/scripts/postinstall.js +30 -0
  240. package/scripts/setup-mcp.js +89 -0
package/dist/cli.js ADDED
@@ -0,0 +1,2057 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /**
4
+ * Minimal CLI for snow-flow - ServiceNow Multi-Agent Framework
5
+ */
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
19
+ }) : function(o, v) {
20
+ o["default"] = v;
21
+ });
22
+ var __importStar = (this && this.__importStar) || (function () {
23
+ var ownKeys = function(o) {
24
+ ownKeys = Object.getOwnPropertyNames || function (o) {
25
+ var ar = [];
26
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
27
+ return ar;
28
+ };
29
+ return ownKeys(o);
30
+ };
31
+ return function (mod) {
32
+ if (mod && mod.__esModule) return mod;
33
+ var result = {};
34
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
35
+ __setModuleDefault(result, mod);
36
+ return result;
37
+ };
38
+ })();
39
+ var __importDefault = (this && this.__importDefault) || function (mod) {
40
+ return (mod && mod.__esModule) ? mod : { "default": mod };
41
+ };
42
+ Object.defineProperty(exports, "__esModule", { value: true });
43
+ const commander_1 = require("commander");
44
+ const dotenv_1 = __importDefault(require("dotenv"));
45
+ const fs_1 = require("fs");
46
+ const path_1 = require("path");
47
+ const child_process_1 = require("child_process");
48
+ const fs_2 = require("fs");
49
+ const snow_oauth_js_1 = require("./utils/snow-oauth.js");
50
+ const servicenow_client_js_1 = require("./utils/servicenow-client.js");
51
+ const agent_detector_js_1 = require("./utils/agent-detector.js");
52
+ // Load environment variables
53
+ dotenv_1.default.config();
54
+ const program = new commander_1.Command();
55
+ program
56
+ .name('snow-flow')
57
+ .description('ServiceNow Multi-Agent Development Framework')
58
+ .version('1.1.0');
59
+ // Swarm command - the main orchestration command
60
+ program
61
+ .command('swarm <objective>')
62
+ .description('Execute multi-agent orchestration for a ServiceNow task')
63
+ .option('--strategy <strategy>', 'Execution strategy (development, analysis, research)', 'development')
64
+ .option('--mode <mode>', 'Coordination mode (hierarchical, mesh, distributed)', 'hierarchical')
65
+ .option('--max-agents <number>', 'Maximum number of agents', '5')
66
+ .option('--parallel', 'Enable parallel execution')
67
+ .option('--monitor', 'Enable real-time monitoring')
68
+ .action(async (objective, options) => {
69
+ console.log(`\nšŸš€ Starting ServiceNow Multi-Agent Swarm v1.1.0`);
70
+ console.log(`šŸ“‹ Objective: ${objective}`);
71
+ console.log(`āš™ļø Strategy: ${options.strategy} | Mode: ${options.mode} | Max Agents: ${options.maxAgents}`);
72
+ console.log(`šŸ”„ Parallel: ${options.parallel ? 'Yes' : 'No'} | Monitor: ${options.monitor ? 'Yes' : 'No'}\n`);
73
+ // Analyze the objective using intelligent agent detection
74
+ const taskAnalysis = analyzeObjective(objective);
75
+ console.log(`šŸŽÆ Task Type: ${taskAnalysis.taskType}`);
76
+ console.log(`🧠 Primary Agent: ${taskAnalysis.primaryAgent}`);
77
+ console.log(`šŸ‘„ Supporting Agents: ${taskAnalysis.supportingAgents.join(', ')}`);
78
+ console.log(`šŸ“Š Complexity: ${taskAnalysis.complexity} | Estimated Agents: ${taskAnalysis.estimatedAgentCount}`);
79
+ console.log(`šŸ”§ ServiceNow Artifacts: ${taskAnalysis.serviceNowArtifacts.join(', ')}`);
80
+ console.log(`šŸ“¦ Auto Update Set: ${taskAnalysis.requiresUpdateSet ? 'āœ… Yes' : 'āŒ No'}`);
81
+ console.log(`šŸ—ļø Auto Application: ${taskAnalysis.requiresApplication ? 'āœ… Yes' : 'āŒ No'}`);
82
+ // Show timeout configuration
83
+ const timeoutMinutes = process.env.SNOW_FLOW_TIMEOUT_MINUTES ? parseInt(process.env.SNOW_FLOW_TIMEOUT_MINUTES) : 60;
84
+ if (timeoutMinutes > 0) {
85
+ console.log(`ā±ļø Timeout: ${timeoutMinutes} minutes`);
86
+ }
87
+ else {
88
+ console.log('ā±ļø Timeout: Disabled (infinite execution time)');
89
+ }
90
+ // Check ServiceNow authentication
91
+ const oauth = new snow_oauth_js_1.ServiceNowOAuth();
92
+ const isAuthenticated = await oauth.isAuthenticated();
93
+ if (isAuthenticated) {
94
+ console.log('šŸ”— ServiceNow connection: āœ… Authenticated');
95
+ // Test ServiceNow connection
96
+ const client = new servicenow_client_js_1.ServiceNowClient();
97
+ const testResult = await client.testConnection();
98
+ if (testResult.success) {
99
+ console.log(`šŸ‘¤ Connected as: ${testResult.data.name} (${testResult.data.user_name})`);
100
+ }
101
+ }
102
+ else {
103
+ console.log('šŸ”— ServiceNow connection: āŒ Not authenticated');
104
+ console.log('šŸ’” Run "snow-flow auth login" to enable live ServiceNow integration');
105
+ }
106
+ // Start real Claude Code orchestration
107
+ try {
108
+ // Generate the orchestration prompt for Claude Code with ServiceNow integration
109
+ const orchestrationPrompt = buildClaudeCodePrompt(objective, taskAnalysis, options, isAuthenticated);
110
+ console.log('šŸŽÆ Executing Claude Code with orchestration prompt...');
111
+ console.log('šŸ’” Claude Code will now coordinate the multi-agent development');
112
+ console.log('šŸ“‹ Use TodoWrite to track progress in real-time');
113
+ console.log('šŸ¤– Agents will be spawned using Task tool');
114
+ console.log('šŸ’¾ Coordination data stored in Memory');
115
+ if (isAuthenticated) {
116
+ console.log('šŸ”— Live ServiceNow integration: āœ… Enabled');
117
+ console.log('šŸ“ Artifacts will be created directly in ServiceNow');
118
+ }
119
+ else {
120
+ console.log('šŸ”— Live ServiceNow integration: āŒ Disabled');
121
+ console.log('šŸ“ Artifacts will be saved to servicenow/ directory');
122
+ }
123
+ console.log(); // Empty line
124
+ // Try to execute Claude Code directly
125
+ const success = await executeClaudeCode(orchestrationPrompt);
126
+ if (success) {
127
+ console.log('āœ… Claude Code execution completed successfully!');
128
+ if (isAuthenticated) {
129
+ console.log('šŸ“Š Check your ServiceNow instance for created artifacts');
130
+ }
131
+ else {
132
+ console.log('šŸ“Š Check the servicenow/ directory for generated artifacts');
133
+ }
134
+ }
135
+ else {
136
+ console.log('āš ļø Claude Code direct execution failed. Using fallback method:');
137
+ console.log('\nšŸš€ CLAUDE CODE ORCHESTRATION PROMPT:');
138
+ console.log('='.repeat(80));
139
+ console.log(orchestrationPrompt);
140
+ console.log('='.repeat(80));
141
+ console.log('\nāœ… Snow-Flow orchestration prompt generated!');
142
+ console.log('šŸ“Š Next Steps:');
143
+ console.log(' 1. Copy the above prompt and paste it into Claude Code');
144
+ console.log(' 2. Claude Code will execute the TodoWrite, Task, and Memory tools');
145
+ console.log(' 3. Monitor progress through the batch tools');
146
+ if (isAuthenticated) {
147
+ console.log(' 4. Artifacts will be created directly in ServiceNow');
148
+ }
149
+ else {
150
+ console.log(' 4. Generated artifacts will appear in servicenow/ directory');
151
+ }
152
+ console.log('\nšŸ’” Tip: Run this in a Claude Code session for full orchestration!');
153
+ }
154
+ }
155
+ catch (error) {
156
+ console.error('āŒ Failed to execute Claude Code orchestration:', error instanceof Error ? error.message : String(error));
157
+ }
158
+ });
159
+ // Helper function to execute Claude Code directly
160
+ async function executeClaudeCode(prompt) {
161
+ return new Promise((resolve) => {
162
+ console.log('šŸ” Checking for Claude Code availability...');
163
+ // Try to find Claude Code binary
164
+ const claudeCommands = ['claude', 'claude-code', 'npx claude-code'];
165
+ let currentCommand = 0;
166
+ const tryNextCommand = () => {
167
+ if (currentCommand >= claudeCommands.length) {
168
+ console.log('āŒ Claude Code not found in PATH');
169
+ resolve(false);
170
+ return;
171
+ }
172
+ const command = claudeCommands[currentCommand];
173
+ console.log(`šŸ” Trying: ${command}`);
174
+ const claudeArgs = [
175
+ '--version'
176
+ ];
177
+ // Test if Claude Code is available
178
+ const testProcess = (0, child_process_1.spawn)(command, claudeArgs, {
179
+ stdio: ['ignore', 'pipe', 'pipe']
180
+ });
181
+ testProcess.on('close', (code) => {
182
+ if (code === 0) {
183
+ console.log(`āœ… Found Claude Code: ${command}`);
184
+ executeWithClaude(command, prompt, resolve);
185
+ }
186
+ else {
187
+ currentCommand++;
188
+ tryNextCommand();
189
+ }
190
+ });
191
+ testProcess.on('error', () => {
192
+ currentCommand++;
193
+ tryNextCommand();
194
+ });
195
+ };
196
+ tryNextCommand();
197
+ });
198
+ }
199
+ // Real-time monitoring dashboard for Claude Code process
200
+ function startMonitoringDashboard(claudeProcess) {
201
+ let iterations = 0;
202
+ const startTime = Date.now();
203
+ // Show initial dashboard only once
204
+ console.log('ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”');
205
+ console.log('│ šŸš€ Snow-Flow Dashboard v1.1.0 │');
206
+ console.log('ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤');
207
+ console.log(`│ šŸ¤– Claude Code Status: āœ… Starting │`);
208
+ console.log(`│ šŸ“Š Process ID: ${claudeProcess.pid || 'N/A'} │`);
209
+ console.log(`│ ā±ļø Session Time: 00:00 │`);
210
+ console.log(`│ šŸ”„ Monitoring Cycles: 0 │`);
211
+ console.log('ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜');
212
+ // Silent monitoring - only log to file or memory, don't interfere with Claude Code UI
213
+ const monitoringInterval = setInterval(() => {
214
+ iterations++;
215
+ const uptime = Math.floor((Date.now() - startTime) / 1000);
216
+ // Silent monitoring - check files but don't output to console
217
+ try {
218
+ const serviceNowDir = (0, path_1.join)(process.cwd(), 'servicenow');
219
+ fs_1.promises.readdir(serviceNowDir).then(files => {
220
+ // Files are being generated - could log to file if needed
221
+ // console.log(`\nšŸ“ Generated Files: ${files.length} artifacts in servicenow/`);
222
+ }).catch(() => {
223
+ // Directory doesn't exist yet, that's normal
224
+ });
225
+ }
226
+ catch (error) {
227
+ // Ignore errors
228
+ }
229
+ }, 5000); // Check every 5 seconds silently
230
+ return monitoringInterval;
231
+ }
232
+ async function executeWithClaude(claudeCommand, prompt, resolve) {
233
+ console.log('šŸš€ Starting Claude Code execution...');
234
+ // Write prompt to temporary file for large prompts
235
+ const tempFile = (0, path_1.join)(process.cwd(), '.snow-flow-prompt.tmp');
236
+ await fs_1.promises.writeFile(tempFile, prompt);
237
+ const claudeArgs = [
238
+ '--dangerously-skip-permissions'
239
+ ];
240
+ // Start Claude Code process in interactive mode
241
+ const claudeProcess = (0, child_process_1.spawn)(claudeCommand, claudeArgs, {
242
+ stdio: ['pipe', 'inherit', 'inherit'], // inherit stdout/stderr for interactive mode
243
+ cwd: process.cwd()
244
+ });
245
+ // Send the prompt via stdin
246
+ console.log('šŸ“ Sending orchestration prompt to Claude Code...');
247
+ console.log('šŸš€ Claude Code interactive interface opening...\n');
248
+ claudeProcess.stdin.write(prompt);
249
+ claudeProcess.stdin.end();
250
+ // Start silent monitoring dashboard (doesn't interfere with Claude Code UI)
251
+ const monitoringInterval = startMonitoringDashboard(claudeProcess);
252
+ claudeProcess.on('close', (code) => {
253
+ clearInterval(monitoringInterval);
254
+ if (code === 0) {
255
+ console.log('\nāœ… Claude Code session completed successfully!');
256
+ resolve(true);
257
+ }
258
+ else {
259
+ console.log(`\nāŒ Claude Code session ended with code: ${code}`);
260
+ resolve(false);
261
+ }
262
+ });
263
+ claudeProcess.on('error', (error) => {
264
+ clearInterval(monitoringInterval);
265
+ console.log(`āŒ Failed to start Claude Code: ${error.message}`);
266
+ resolve(false);
267
+ });
268
+ // Set timeout for Claude Code execution (configurable via environment variable)
269
+ const timeoutMinutes = process.env.SNOW_FLOW_TIMEOUT_MINUTES ? parseInt(process.env.SNOW_FLOW_TIMEOUT_MINUTES) : 60;
270
+ const timeoutMs = timeoutMinutes * 60 * 1000;
271
+ console.log(`ā±ļø Claude Code timeout set to ${timeoutMinutes} minutes (configure with SNOW_FLOW_TIMEOUT_MINUTES=0 for no timeout)`);
272
+ let timeout = null;
273
+ // Only set timeout if not disabled (0 = no timeout)
274
+ if (timeoutMinutes > 0) {
275
+ timeout = setTimeout(() => {
276
+ clearInterval(monitoringInterval);
277
+ console.log(`ā±ļø Claude Code session timeout (${timeoutMinutes} minutes), terminating...`);
278
+ claudeProcess.kill('SIGTERM');
279
+ // Force kill if it doesn't respond
280
+ setTimeout(() => {
281
+ claudeProcess.kill('SIGKILL');
282
+ }, 2000);
283
+ resolve(false);
284
+ }, timeoutMs);
285
+ }
286
+ claudeProcess.on('close', () => {
287
+ if (timeout) {
288
+ clearTimeout(timeout);
289
+ }
290
+ });
291
+ }
292
+ // Helper function to build Claude Code orchestration prompt
293
+ function buildClaudeCodePrompt(objective, taskAnalysis, options, isAuthenticated = false) {
294
+ const prompt = `# Snow-Flow ServiceNow Multi-Agent Development
295
+
296
+ ## Objective
297
+ ${objective}
298
+
299
+ ## 🧠 Intelligent Agent Analysis
300
+ - **Task Type**: ${taskAnalysis.taskType}
301
+ - **Primary Agent**: ${taskAnalysis.primaryAgent}
302
+ - **Supporting Agents**: ${taskAnalysis.supportingAgents.join(', ')}
303
+ - **Complexity**: ${taskAnalysis.complexity}
304
+ - **Estimated Agents**: ${taskAnalysis.estimatedAgentCount}
305
+ - **ServiceNow Artifacts**: ${taskAnalysis.serviceNowArtifacts.join(', ')}
306
+ - **Auto Update Set**: ${taskAnalysis.requiresUpdateSet ? 'āœ… Yes' : 'āŒ No'}
307
+ - **Auto Application**: ${taskAnalysis.requiresApplication ? 'āœ… Yes' : 'āŒ No'}
308
+
309
+ ## Configuration
310
+ - **Strategy**: ${options.strategy}
311
+ - **Mode**: ${options.mode}
312
+ - **Max Agents**: ${Math.min(parseInt(options.maxAgents), taskAnalysis.estimatedAgentCount)}
313
+ - **Parallel**: ${options.parallel ? 'Yes' : 'No'}
314
+ - **Monitor**: ${options.monitor ? 'Yes' : 'No'}
315
+
316
+ ## Task Details
317
+ - **ServiceNow Artifacts**: ${taskAnalysis.serviceNowArtifacts.length > 0 ? taskAnalysis.serviceNowArtifacts.join(', ') : 'None detected'}
318
+ - **Agent Requirements**: ${taskAnalysis.primaryAgent} (lead) + ${taskAnalysis.supportingAgents.join(', ')} (support)
319
+ - **Complexity Assessment**: ${taskAnalysis.complexity} task requiring ${taskAnalysis.estimatedAgentCount} agents
320
+
321
+ ## ServiceNow Integration
322
+ ${isAuthenticated ? 'āœ… **Live ServiceNow Integration: ENABLED**' : 'āŒ **Live ServiceNow Integration: DISABLED**'}
323
+
324
+ ${isAuthenticated ? `
325
+ šŸ”— **You have LIVE ACCESS to ServiceNow APIs and can create artifacts directly in ServiceNow!**
326
+
327
+ 🚨 **CRITICAL: You have ServiceNow MCP tools available for direct deployment:**
328
+
329
+ Available ServiceNow MCP Tools:
330
+ - **ServiceNowClient**: Create widgets, workflows, and applications directly
331
+ - **ServiceNowOAuth**: Authenticated access to ServiceNow APIs
332
+ - **Direct API Access**: Use REST APIs to create and deploy artifacts immediately
333
+
334
+ **MANDATORY: Use ServiceNow API calls to deploy widgets directly:**
335
+ 1. **Create artifacts in ServiceNow using ServiceNowClient.createWidget()**
336
+ 2. **Test functionality immediately in the live ServiceNow instance**
337
+ 3. **Generate update sets for deployment**
338
+ 4. **Provide direct links to created artifacts**
339
+
340
+ āš ļø **DO NOT say you cannot deploy to ServiceNow** - you CAN and SHOULD deploy directly using the available ServiceNow API tools!
341
+
342
+ **Example ServiceNow Widget Creation:**
343
+ \`\`\`typescript
344
+ import { ServiceNowClient } from '../utils/servicenow-client.js';
345
+
346
+ const client = new ServiceNowClient();
347
+ const widget = await client.createWidget({
348
+ name: 'incident_management_widget',
349
+ title: 'Incident Management Widget',
350
+ description: 'Enhanced incident management with visual features',
351
+ template: '<!-- Your HTML template -->',
352
+ css: '/* Your CSS styles */',
353
+ client_script: '/* Your client-side JavaScript */',
354
+ server_script: '/* Your server-side script */',
355
+ category: 'incident'
356
+ });
357
+ \`\`\`
358
+
359
+ **PREFERRED: Use ServiceNow Deployment MCP Tools:**
360
+ \`\`\`typescript
361
+ // Deploy widget using MCP deployment tool
362
+ await snow_deploy_widget({
363
+ name: 'incident_management_widget',
364
+ title: 'Incident Management Widget',
365
+ description: 'Enhanced incident management with visual features',
366
+ template: widgetHTML,
367
+ css: widgetCSS,
368
+ client_script: clientScript,
369
+ server_script: serverScript,
370
+ category: 'incident'
371
+ });
372
+
373
+ // Deploy Flow Designer flow using MCP deployment tool
374
+ await snow_deploy_flow({
375
+ name: 'approval_flow',
376
+ description: 'Approval flow for purchases',
377
+ table: 'sc_request',
378
+ trigger_type: 'record_created',
379
+ condition: 'category=hardware^item=iphone',
380
+ flow_definition: flowJSON,
381
+ category: 'approval'
382
+ });
383
+ \`\`\`
384
+
385
+ **ALTERNATIVE: Use Direct Widget Creator for pre-built widgets:**
386
+ \`\`\`typescript
387
+ import { DirectWidgetCreator } from '../cli/direct-widget-creator.js';
388
+
389
+ const creator = new DirectWidgetCreator();
390
+ await creator.createIncidentManagementWidget();
391
+ \`\`\`
392
+
393
+ šŸŽÆ **YOU CAN AND SHOULD DEPLOY DIRECTLY TO SERVICENOW** - OAuth authentication is active!
394
+
395
+ šŸ“¦ **Available Deployment MCP Tools:**
396
+ - snow_deploy_widget - Deploy widgets with full configuration
397
+ - snow_deploy_flow - Deploy Flow Designer flows
398
+ - snow_deploy_application - Deploy scoped applications
399
+ - snow_deploy_update_set - Create update sets
400
+ - snow_validate_deployment - Validate before deploying
401
+ - snow_rollback_deployment - Rollback if needed
402
+
403
+ 🧠 **Intelligent Flow Composition Tools:**
404
+ - snow_create_complex_flow - Create complete flows with automatic artifact orchestration
405
+ - snow_analyze_flow_instruction - Analyze natural language flow instructions
406
+ - snow_discover_flow_artifacts - Discover artifacts needed for complex flows
407
+ - snow_preview_flow_structure - Preview flow structure before deployment
408
+
409
+ šŸŽÆ **Flow Composition Capabilities:**
410
+ - Automatic discovery of existing ServiceNow artifacts (script includes, business rules, tables)
411
+ - Intelligent artifact orchestration in flows
412
+ - Natural language processing for complex flow instructions
413
+ - Fallback creation for missing artifacts
414
+ - Multi-artifact coordination and deployment
415
+ ` : `
416
+ šŸ“ **File-based development mode**
417
+
418
+ Since ServiceNow integration is not enabled, create artifacts as files in the servicenow/ directory:
419
+ - servicenow/widgets/ for widget files
420
+ - servicenow/workflows/ for workflow definitions
421
+ - servicenow/scripts/ for server scripts
422
+ - servicenow/apps/ for application definitions
423
+
424
+ šŸ’” Run "snow-flow auth login" to enable live ServiceNow integration!
425
+ `}
426
+
427
+ ## 🚨 CRITICAL: Claude-Flow Batch Tool Integration
428
+
429
+ āš ļø **MANDATORY EXECUTION PATTERN**: You MUST execute ALL of these tools in a SINGLE MESSAGE for parallel agent coordination:
430
+
431
+ ### 1. Initialize TodoWrite with ALL tasks (5-10 todos minimum)
432
+ ### 2. Launch ALL Task agents SIMULTANEOUSLY in the same message
433
+ ### 3. Store ALL coordination data in Memory
434
+ ### 4. Execute ALL ServiceNow operations in parallel
435
+
436
+ **BATCH EXECUTION EXAMPLE:**
437
+ You must use this EXACT pattern in ONE message with multiple tool calls:
438
+
439
+ \`\`\`typescript
440
+ // Tool 1: TodoWrite (5-10 todos in one call)
441
+ TodoWrite([
442
+ {
443
+ id: "task_analysis",
444
+ content: "Analyze ${objective} requirements and constraints",
445
+ status: "pending",
446
+ priority: "high"
447
+ },
448
+ {
449
+ id: "architecture_design",
450
+ content: "Design ServiceNow architecture and component structure",
451
+ status: "pending",
452
+ priority: "high"
453
+ },
454
+ ${taskAnalysis.requiresUpdateSet ? `{
455
+ id: "update_set_creation",
456
+ content: "Create Update Set for change management",
457
+ status: "pending",
458
+ priority: "high"
459
+ },` : ''}
460
+ ${taskAnalysis.requiresApplication ? `{
461
+ id: "application_creation",
462
+ content: "Create new ServiceNow Application",
463
+ status: "pending",
464
+ priority: "high"
465
+ },` : ''}
466
+ {
467
+ id: "implementation",
468
+ content: "Implement ${objective}${isAuthenticated ? ' directly in ServiceNow' : ' as files'}",
469
+ status: "pending",
470
+ priority: "high"
471
+ },
472
+ {
473
+ id: "testing",
474
+ content: "Test and validate ${objective}${isAuthenticated ? ' in ServiceNow instance' : ' via file validation'}",
475
+ status: "pending",
476
+ priority: "medium"
477
+ },
478
+ {
479
+ id: "documentation",
480
+ content: "Document ${objective}${isAuthenticated ? ' with ServiceNow links' : ' with file references'}",
481
+ status: "pending",
482
+ priority: "medium"
483
+ },
484
+ {
485
+ id: "deployment",
486
+ content: "Prepare deployment artifacts and instructions",
487
+ status: "pending",
488
+ priority: "low"
489
+ }
490
+ ]);
491
+
492
+ // Tool 2-N: Task agents (ALL launched in same message)
493
+ Task("${taskAnalysis.primaryAgent}", "${agent_detector_js_1.AgentDetector.generateAgentPrompt(taskAnalysis.primaryAgent, objective, taskAnalysis)}");
494
+ ${taskAnalysis.supportingAgents.map(agent => `Task("${agent}", "${agent_detector_js_1.AgentDetector.generateAgentPrompt(agent, objective, taskAnalysis)}");`).join('\n')}
495
+ ${taskAnalysis.requiresUpdateSet ? `Task("Update Set Manager", "Create and manage Update Set for change management. Use snow_update_set_create to create Update Set automatically.");` : ''}
496
+ ${taskAnalysis.requiresApplication ? `Task("Application Manager", "Create new ServiceNow Application. Use snow_deploy_application to create new application scope.");` : ''}
497
+
498
+ // Tool 7: Memory coordination data
499
+ Memory.store("snow_flow_session", {
500
+ objective: "${objective}",
501
+ task_type: "${taskAnalysis.taskType}",
502
+ primary_agent: "${taskAnalysis.primaryAgent}",
503
+ supporting_agents: ${JSON.stringify(taskAnalysis.supportingAgents)},
504
+ complexity: "${taskAnalysis.complexity}",
505
+ servicenow_artifacts: ${JSON.stringify(taskAnalysis.serviceNowArtifacts)},
506
+ requires_update_set: ${taskAnalysis.requiresUpdateSet},
507
+ requires_application: ${taskAnalysis.requiresApplication},
508
+ strategy: "${options.strategy}",
509
+ mode: "${options.mode}",
510
+ started_at: new Date().toISOString(),
511
+ agents: ${taskAnalysis.estimatedAgentCount},
512
+ parallel: ${options.parallel},
513
+ authenticated: ${isAuthenticated}
514
+ });
515
+
516
+ Memory.store("task_analysis", ${JSON.stringify(taskAnalysis, null, 2)});
517
+ \`\`\`
518
+
519
+ ### ServiceNow-Specific Implementation
520
+ ${getServiceNowInstructions(taskAnalysis.taskType)}
521
+
522
+ ### Coordination Guidelines
523
+ - **BATCH EXECUTION**: All tools must be called in ONE message
524
+ - **PARALLEL AGENTS**: Launch multiple Task agents simultaneously
525
+ - **MEMORY SHARING**: All agents use Memory for coordination
526
+ - **REAL-TIME UPDATES**: Update TodoWrite status as tasks complete
527
+ ${isAuthenticated ? '- **MANDATORY DEPLOYMENT**: You MUST deploy directly to ServiceNow using ServiceNowClient.createWidget()' : '- **FILE MODE**: Create artifacts in servicenow/ directory'}
528
+ - **COMPREHENSIVE TESTING**: ${isAuthenticated ? 'Test functionality immediately in the live ServiceNow instance' : 'Validate file structure and syntax'}
529
+ ${isAuthenticated ? '- **NO EXCUSES**: Do NOT say you cannot deploy - you CAN and MUST deploy to ServiceNow!' : ''}
530
+
531
+ ## Expected Deliverables
532
+ ${getExpectedDeliverables(taskAnalysis.taskType, isAuthenticated)}
533
+
534
+ šŸŽÆ **EXECUTION INSTRUCTION**: Execute ALL batch tools (TodoWrite, Task x5, Memory) in a SINGLE message to enable parallel agent coordination!`;
535
+ return prompt;
536
+ }
537
+ function getServiceNowInstructions(taskType) {
538
+ switch (taskType) {
539
+ case 'widget_development':
540
+ return `**Widget Development Process:**
541
+ - Create HTML template with responsive design
542
+ - Implement CSS styling following ServiceNow design patterns
543
+ - Write AngularJS client controller
544
+ - Create server-side data processing script
545
+ - Define widget options and configuration
546
+ - Test widget in Service Portal`;
547
+ case 'application_development':
548
+ return `**Application Development Process:**
549
+ - Design database schema and tables
550
+ - Create business rules and validation
551
+ - Build user interface forms and lists
552
+ - Implement workflows and approvals
553
+ - Configure security and access controls
554
+ - Set up integration points`;
555
+ case 'flow_development':
556
+ return `**Flow Development Process:**
557
+ - Analyze flow requirements and triggers
558
+ - Design process flow and approval steps
559
+ - Create Flow Designer workflow using sys_hub_flow
560
+ - Set up notifications and communications
561
+ - Configure conditional logic and routing
562
+ - Test flow execution and error handling`;
563
+ case 'script_development':
564
+ return `**Script Development Process:**
565
+ - Analyze business requirements
566
+ - Design script architecture and data flow
567
+ - Implement business rules and script includes
568
+ - Create appropriate error handling
569
+ - Test script functionality
570
+ - Document script behavior`;
571
+ case 'integration_development':
572
+ return `**Integration Development Process:**
573
+ - Analyze integration requirements
574
+ - Design API endpoints and data mappings
575
+ - Implement REST/SOAP integrations
576
+ - Create authentication and security
577
+ - Test integration functionality
578
+ - Document API specifications`;
579
+ case 'database_development':
580
+ return `**Database Development Process:**
581
+ - Design table structures and relationships
582
+ - Create custom fields and configurations
583
+ - Implement data validation rules
584
+ - Set up reporting and analytics
585
+ - Test data integrity
586
+ - Document database schema`;
587
+ case 'reporting_development':
588
+ return `**Reporting Development Process:**
589
+ - Analyze reporting requirements
590
+ - Design report layouts and data sources
591
+ - Create dashboards and visualizations
592
+ - Implement filters and drill-downs
593
+ - Test report performance
594
+ - Document report usage`;
595
+ case 'research_task':
596
+ return `**Research Process:**
597
+ - Analyze current state and requirements
598
+ - Research ServiceNow best practices
599
+ - Evaluate available solutions
600
+ - Document findings and recommendations
601
+ - Create implementation roadmap
602
+ - Present research conclusions`;
603
+ default:
604
+ return `**ServiceNow Development Process:**
605
+ - Analyze requirements and specifications
606
+ - Design appropriate ServiceNow solution
607
+ - Implement using ServiceNow best practices
608
+ - Create necessary scripts and configurations
609
+ - Test functionality and integration
610
+ - Document implementation`;
611
+ }
612
+ }
613
+ function getExpectedDeliverables(taskType, isAuthenticated = false) {
614
+ const baseDeliverables = {
615
+ 'widget_development': [
616
+ 'Widget HTML template',
617
+ 'CSS styling files',
618
+ 'AngularJS client script',
619
+ 'Server-side script',
620
+ 'Widget configuration options',
621
+ 'Installation instructions'
622
+ ],
623
+ 'application_development': [
624
+ 'Database schema definition',
625
+ 'Business rules and validations',
626
+ 'User interface components',
627
+ 'Workflow definitions',
628
+ 'Security configuration',
629
+ 'Update set for deployment'
630
+ ],
631
+ 'flow_development': [
632
+ 'Flow Designer workflow',
633
+ 'Process documentation',
634
+ 'Approval configurations',
635
+ 'Notification templates',
636
+ 'Test scenarios',
637
+ 'Implementation guide'
638
+ ],
639
+ 'script_development': [
640
+ 'Business rules and script includes',
641
+ 'Error handling logic',
642
+ 'Test cases and validation',
643
+ 'Documentation and comments',
644
+ 'Performance optimization',
645
+ 'Security considerations'
646
+ ],
647
+ 'integration_development': [
648
+ 'REST/SOAP API endpoints',
649
+ 'Authentication configuration',
650
+ 'Data mapping and transformation',
651
+ 'Error handling and logging',
652
+ 'API documentation',
653
+ 'Integration testing'
654
+ ],
655
+ 'database_development': [
656
+ 'Table structures and relationships',
657
+ 'Custom fields and configurations',
658
+ 'Data validation rules',
659
+ 'Indexes and performance optimization',
660
+ 'Reporting and analytics',
661
+ 'Data migration scripts'
662
+ ],
663
+ 'reporting_development': [
664
+ 'Report definitions and layouts',
665
+ 'Dashboard configurations',
666
+ 'Data source connections',
667
+ 'Filters and drill-downs',
668
+ 'Performance optimization',
669
+ 'User access controls'
670
+ ],
671
+ 'research_task': [
672
+ 'Research findings and analysis',
673
+ 'Best practices documentation',
674
+ 'Solution recommendations',
675
+ 'Implementation roadmap',
676
+ 'Risk assessment',
677
+ 'Feasibility analysis'
678
+ ],
679
+ 'default': [
680
+ 'ServiceNow implementation',
681
+ 'Supporting scripts',
682
+ 'Configuration files',
683
+ 'Documentation',
684
+ 'Test cases',
685
+ 'Deployment instructions'
686
+ ]
687
+ };
688
+ const deliverables = baseDeliverables[taskType] || baseDeliverables['default'];
689
+ if (isAuthenticated) {
690
+ // Add ServiceNow-specific deliverables for authenticated mode
691
+ const serviceNowDeliverables = deliverables.map(item => `- ${item} (created in ServiceNow)`);
692
+ serviceNowDeliverables.push('- **MANDATORY: Direct deployment to ServiceNow using ServiceNowClient.createWidget()**');
693
+ serviceNowDeliverables.push('- Direct links to ServiceNow artifacts');
694
+ serviceNowDeliverables.push('- Update set for deployment');
695
+ serviceNowDeliverables.push('- Test results from live instance');
696
+ serviceNowDeliverables.push('- **CRITICAL: Widget must be deployed, not just created as files**');
697
+ return serviceNowDeliverables.join('\n');
698
+ }
699
+ else {
700
+ // File-based deliverables for non-authenticated mode
701
+ const fileDeliverables = deliverables.map(item => `- ${item} (as files)`);
702
+ fileDeliverables.push('- Deployment-ready file structure');
703
+ fileDeliverables.push('- Import instructions for ServiceNow');
704
+ return fileDeliverables.join('\n');
705
+ }
706
+ }
707
+ // Helper function to analyze objectives using intelligent agent detection
708
+ function analyzeObjective(objective) {
709
+ return agent_detector_js_1.AgentDetector.analyzeTask(objective);
710
+ }
711
+ function extractName(objective, type) {
712
+ const words = objective.split(' ');
713
+ const typeIndex = words.findIndex(w => w.toLowerCase().includes(type));
714
+ if (typeIndex >= 0 && typeIndex < words.length - 1) {
715
+ return words.slice(typeIndex + 1).join(' ').replace(/['"]/g, '');
716
+ }
717
+ return `Generated ${type}`;
718
+ }
719
+ // Spawn agent command
720
+ program
721
+ .command('spawn <type>')
722
+ .description('Spawn a specific agent type')
723
+ .option('--name <name>', 'Custom agent name')
724
+ .action(async (type, options) => {
725
+ console.log(`šŸ¤– Spawning ${type} agent${options.name ? ` with name "${options.name}"` : ''}...`);
726
+ console.log(`āœ… Agent spawned successfully`);
727
+ console.log(`šŸ“‹ Agent capabilities:`);
728
+ if (type === 'widget-builder') {
729
+ console.log(' ā”œā”€ā”€ Service Portal widget creation');
730
+ console.log(' ā”œā”€ā”€ HTML/CSS template generation');
731
+ console.log(' ā”œā”€ā”€ Client script development');
732
+ console.log(' └── Server script implementation');
733
+ }
734
+ else if (type === 'workflow-designer') {
735
+ console.log(' ā”œā”€ā”€ Flow Designer workflow creation');
736
+ console.log(' ā”œā”€ā”€ Process automation');
737
+ console.log(' ā”œā”€ā”€ Approval routing');
738
+ console.log(' └── Integration orchestration');
739
+ }
740
+ else {
741
+ console.log(' ā”œā”€ā”€ Generic ServiceNow development');
742
+ console.log(' ā”œā”€ā”€ Script generation');
743
+ console.log(' ā”œā”€ā”€ Configuration management');
744
+ console.log(' └── API integration');
745
+ }
746
+ });
747
+ // Status command
748
+ program
749
+ .command('status')
750
+ .description('Show orchestrator status')
751
+ .action(async () => {
752
+ console.log('\nšŸ” ServiceNow Multi-Agent Orchestrator Status');
753
+ console.log('=============================================');
754
+ console.log('šŸ“Š System Status: āœ… Online');
755
+ console.log('šŸ¤– Available Agents: 5');
756
+ console.log('šŸ“‹ Queue Status: Empty');
757
+ console.log('šŸ”— ServiceNow Connection: Not configured');
758
+ console.log('šŸ’¾ Memory Usage: 45MB');
759
+ console.log('šŸ•’ Uptime: 00:05:23');
760
+ console.log('\nšŸ¤– Agent Types:');
761
+ console.log(' ā”œā”€ā”€ widget-builder: Available');
762
+ console.log(' ā”œā”€ā”€ workflow-designer: Available');
763
+ console.log(' ā”œā”€ā”€ script-generator: Available');
764
+ console.log(' ā”œā”€ā”€ ui-builder: Available');
765
+ console.log(' └── app-creator: Available');
766
+ console.log('\nāš™ļø Configuration:');
767
+ console.log(' ā”œā”€ā”€ Instance: Not set');
768
+ console.log(' ā”œā”€ā”€ Authentication: Not configured');
769
+ console.log(' └── Mode: Development');
770
+ });
771
+ // Monitor command - real-time dashboard
772
+ program
773
+ .command('monitor')
774
+ .description('Show real-time monitoring dashboard')
775
+ .option('--duration <seconds>', 'Duration to monitor (default: 60)', '60')
776
+ .action(async (options) => {
777
+ const duration = parseInt(options.duration) * 1000;
778
+ console.log('šŸš€ Starting Snow-Flow Real-Time Monitor...\n');
779
+ let iterations = 0;
780
+ const startTime = Date.now();
781
+ const monitoringInterval = setInterval(() => {
782
+ iterations++;
783
+ const uptime = Math.floor((Date.now() - startTime) / 1000);
784
+ const minutes = Math.floor(uptime / 60);
785
+ const seconds = uptime % 60;
786
+ // Clear previous lines and show dashboard
787
+ if (iterations > 1) {
788
+ process.stdout.write('\x1B[12A'); // Move cursor up 12 lines
789
+ process.stdout.write('\x1B[2K'); // Clear line
790
+ }
791
+ console.log('ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”');
792
+ console.log('│ šŸš€ Snow-Flow Monitor v1.1.0 │');
793
+ console.log('ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤');
794
+ console.log(`│ šŸ“Š System Status: āœ… Online │`);
795
+ console.log(`│ ā±ļø Monitor Time: ${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')} │`);
796
+ console.log(`│ šŸ”„ Update Cycles: ${iterations} │`);
797
+ console.log(`│ šŸ¤– Available Agents: 5 │`);
798
+ console.log(`│ šŸ’¾ Memory Usage: ~45MB │`);
799
+ console.log('ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤');
800
+ console.log('│ šŸ“‹ Recent Activity: │');
801
+ console.log(`│ • ${new Date().toLocaleTimeString()} - System monitoring active │`);
802
+ console.log('ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜');
803
+ // Check for active Claude Code processes
804
+ try {
805
+ const { execSync } = require('child_process');
806
+ const processes = execSync('ps aux | grep "claude" | grep -v grep', { encoding: 'utf8' }).toString();
807
+ if (processes.trim()) {
808
+ console.log('\nšŸ¤– Active Claude Code Processes:');
809
+ const lines = processes.trim().split('\n');
810
+ lines.forEach((line, index) => {
811
+ if (index < 3) { // Show max 3 processes
812
+ const parts = line.split(/\s+/);
813
+ const pid = parts[1];
814
+ const cpu = parts[2];
815
+ const mem = parts[3];
816
+ console.log(` Process ${pid}: CPU ${cpu}%, Memory ${mem}%`);
817
+ }
818
+ });
819
+ }
820
+ }
821
+ catch (error) {
822
+ // No active processes or error occurred
823
+ }
824
+ // Check generated files
825
+ try {
826
+ const serviceNowDir = (0, path_1.join)(process.cwd(), 'servicenow');
827
+ fs_1.promises.readdir(serviceNowDir).then(files => {
828
+ if (files.length > 0) {
829
+ console.log(`\nšŸ“ Generated Artifacts: ${files.length} files in servicenow/`);
830
+ files.slice(0, 3).forEach(file => {
831
+ console.log(` • ${file}`);
832
+ });
833
+ if (files.length > 3) {
834
+ console.log(` ... and ${files.length - 3} more files`);
835
+ }
836
+ }
837
+ }).catch(() => {
838
+ // Directory doesn't exist yet
839
+ });
840
+ }
841
+ catch (error) {
842
+ // Ignore errors
843
+ }
844
+ }, 2000); // Update every 2 seconds
845
+ // Stop monitoring after duration
846
+ setTimeout(() => {
847
+ clearInterval(monitoringInterval);
848
+ console.log('\nāœ… Monitoring completed. Use --duration <seconds> to monitor longer.');
849
+ }, duration);
850
+ });
851
+ // Memory commands
852
+ program
853
+ .command('memory <action> [key] [value]')
854
+ .description('Memory operations (store, get, list)')
855
+ .action(async (action, key, value) => {
856
+ console.log(`šŸ’¾ Memory ${action}${key ? `: ${key}` : ''}`);
857
+ if (action === 'store' && key && value) {
858
+ console.log(`āœ… Stored: ${key} = ${value}`);
859
+ }
860
+ else if (action === 'get' && key) {
861
+ console.log(`šŸ“– Retrieved: ${key} = [simulated value]`);
862
+ }
863
+ else if (action === 'list') {
864
+ console.log('šŸ“š Memory contents:');
865
+ console.log(' ā”œā”€ā”€ last_widget: incident_management_widget');
866
+ console.log(' ā”œā”€ā”€ last_workflow: approval_process');
867
+ console.log(' └── session_id: snow-flow-session-123');
868
+ }
869
+ else {
870
+ console.log('āŒ Invalid memory operation');
871
+ }
872
+ });
873
+ // Auth command - OAuth implementation
874
+ program
875
+ .command('auth <action>')
876
+ .description('Authentication management (login, logout, status)')
877
+ .option('--instance <instance>', 'ServiceNow instance (e.g., dev12345.service-now.com)')
878
+ .option('--client-id <clientId>', 'OAuth Client ID')
879
+ .option('--client-secret <clientSecret>', 'OAuth Client Secret')
880
+ .action(async (action, options) => {
881
+ const oauth = new snow_oauth_js_1.ServiceNowOAuth();
882
+ if (action === 'login') {
883
+ console.log('šŸ”‘ Starting ServiceNow OAuth authentication...');
884
+ // Get credentials from options or environment
885
+ const instance = options.instance || process.env.SNOW_INSTANCE;
886
+ const clientId = options.clientId || process.env.SNOW_CLIENT_ID;
887
+ const clientSecret = options.clientSecret || process.env.SNOW_CLIENT_SECRET;
888
+ if (!instance || !clientId || !clientSecret) {
889
+ console.error('āŒ Missing required OAuth credentials');
890
+ console.log('\nšŸ“ Please provide:');
891
+ console.log(' --instance: ServiceNow instance (e.g., dev12345.service-now.com)');
892
+ console.log(' --client-id: OAuth Client ID');
893
+ console.log(' --client-secret: OAuth Client Secret');
894
+ console.log('\nšŸ’” Or set environment variables:');
895
+ console.log(' export SNOW_INSTANCE=your-instance.service-now.com');
896
+ console.log(' export SNOW_CLIENT_ID=your-client-id');
897
+ console.log(' export SNOW_CLIENT_SECRET=your-client-secret');
898
+ return;
899
+ }
900
+ // Start OAuth flow
901
+ const result = await oauth.authenticate(instance, clientId, clientSecret);
902
+ if (result.success) {
903
+ console.log('\nāœ… Authentication successful!');
904
+ console.log('šŸŽ‰ Snow-Flow is now connected to ServiceNow!');
905
+ console.log('\nšŸ“‹ Next steps:');
906
+ console.log(' 1. Test connection: snow-flow auth status');
907
+ console.log(' 2. Start development: snow-flow swarm "create a widget for incident management"');
908
+ // Test connection
909
+ const client = new servicenow_client_js_1.ServiceNowClient();
910
+ const testResult = await client.testConnection();
911
+ if (testResult.success) {
912
+ console.log(`\nšŸ” Connection test successful!`);
913
+ console.log(`šŸ‘¤ Logged in as: ${testResult.data.name} (${testResult.data.user_name})`);
914
+ }
915
+ }
916
+ else {
917
+ console.error(`\nāŒ Authentication failed: ${result.error}`);
918
+ process.exit(1);
919
+ }
920
+ }
921
+ else if (action === 'logout') {
922
+ console.log('šŸ”“ Logging out...');
923
+ await oauth.logout();
924
+ }
925
+ else if (action === 'status') {
926
+ console.log('šŸ“Š Authentication Status:');
927
+ const isAuthenticated = await oauth.isAuthenticated();
928
+ const credentials = await oauth.loadCredentials();
929
+ if (isAuthenticated && credentials) {
930
+ console.log(' ā”œā”€ā”€ Status: āœ… Authenticated');
931
+ console.log(` ā”œā”€ā”€ Instance: ${credentials.instance}`);
932
+ console.log(' ā”œā”€ā”€ Method: OAuth 2.0');
933
+ console.log(` ā”œā”€ā”€ Client ID: ${credentials.clientId}`);
934
+ if (credentials.expiresAt) {
935
+ const expiresAt = new Date(credentials.expiresAt);
936
+ console.log(` └── Token expires: ${expiresAt.toLocaleString()}`);
937
+ }
938
+ // Test connection
939
+ const client = new servicenow_client_js_1.ServiceNowClient();
940
+ const testResult = await client.testConnection();
941
+ if (testResult.success) {
942
+ console.log(`\nšŸ” Connection test: āœ… Success`);
943
+ if (testResult.data.message) {
944
+ console.log(` ${testResult.data.message}`);
945
+ }
946
+ console.log(`🌐 Instance: ${testResult.data.email || credentials.instance}`);
947
+ }
948
+ else {
949
+ console.log(`\nšŸ” Connection test: āŒ Failed`);
950
+ console.log(` Error: ${testResult.error}`);
951
+ }
952
+ }
953
+ else {
954
+ console.log(' ā”œā”€ā”€ Status: āŒ Not authenticated');
955
+ console.log(' ā”œā”€ā”€ Instance: Not configured');
956
+ console.log(' └── Method: Not set');
957
+ console.log('\nšŸ’” Run "snow-flow auth login" to authenticate');
958
+ }
959
+ }
960
+ else {
961
+ console.log('āŒ Invalid action. Use: login, logout, or status');
962
+ }
963
+ });
964
+ // Help command
965
+ program
966
+ .command('help')
967
+ .description('Show detailed help information')
968
+ .action(() => {
969
+ console.log(`
970
+ šŸš€ Snow-Flow v1.1.0 - ServiceNow Multi-Agent Development Framework
971
+
972
+ šŸ“‹ Available Commands:
973
+ swarm <objective> Execute multi-agent orchestration
974
+ spawn <type> Spawn specific agent types
975
+ status Show system status
976
+ monitor Real-time monitoring dashboard
977
+ memory <action> Memory operations
978
+ auth <action> Authentication management
979
+ mcp <action> Manage ServiceNow MCP servers
980
+ create-flow <instruction> Create flows using natural language
981
+ help Show this help
982
+
983
+ šŸŽÆ Example Usage:
984
+ snow-flow auth login --instance dev12345.service-now.com --client-id your-id --client-secret your-secret
985
+ snow-flow auth status
986
+ snow-flow mcp start # Start MCP servers for Claude Code
987
+ snow-flow mcp status # Check MCP server status
988
+ snow-flow swarm "create a widget for incident management"
989
+ snow-flow create-flow "approval flow for hardware purchases over €1000"
990
+ snow-flow spawn widget-builder --name "IncidentWidget"
991
+ snow-flow monitor --duration 120
992
+ snow-flow memory store "project" "incident_system"
993
+ snow-flow status
994
+
995
+ šŸ¤– Agent Types:
996
+ widget-builder Create Service Portal widgets
997
+ workflow-designer Design Flow Designer workflows
998
+ script-generator Generate scripts and business rules
999
+ ui-builder Create UI components
1000
+ app-creator Build complete applications
1001
+
1002
+ āš™ļø OAuth Configuration:
1003
+ Set environment variables or use command line options:
1004
+ - SNOW_INSTANCE: Your ServiceNow instance (e.g., dev12345.service-now.com)
1005
+ - SNOW_CLIENT_ID: OAuth Client ID from ServiceNow
1006
+ - SNOW_CLIENT_SECRET: OAuth Client Secret from ServiceNow
1007
+
1008
+ šŸ”§ MCP Server Management:
1009
+ - start Start all or specific MCP servers
1010
+ - stop Stop all or specific MCP servers
1011
+ - restart Restart all or specific MCP servers
1012
+ - status Show status of all MCP servers
1013
+ - logs View MCP server logs
1014
+ - list List all configured MCP servers
1015
+
1016
+ šŸ”— Live ServiceNow Integration:
1017
+ - Create widgets directly in ServiceNow
1018
+ - Execute workflows in real-time
1019
+ - Test changes immediately in your instance
1020
+
1021
+ 🌐 More Info: https://github.com/groeimetai/snow-flow
1022
+ `);
1023
+ });
1024
+ // Helper functions for init command
1025
+ async function createDirectoryStructure(targetDir) {
1026
+ const directories = [
1027
+ '.claude', '.claude/commands', '.claude/commands/sparc', '.claude/configs',
1028
+ '.swarm', '.swarm/sessions', '.swarm/agents',
1029
+ 'memory', 'memory/agents', 'memory/sessions',
1030
+ 'coordination', 'coordination/memory_bank', 'coordination/subtasks',
1031
+ 'servicenow', 'servicenow/widgets', 'servicenow/workflows', 'servicenow/scripts',
1032
+ 'templates', 'templates/widgets', 'templates/workflows'
1033
+ ];
1034
+ for (const dir of directories) {
1035
+ const dirPath = (0, path_1.join)(targetDir, dir);
1036
+ await fs_1.promises.mkdir(dirPath, { recursive: true });
1037
+ }
1038
+ }
1039
+ async function createBasicConfig(targetDir) {
1040
+ const claudeConfig = {
1041
+ version: '1.0.0',
1042
+ name: 'snow-flow',
1043
+ description: 'ServiceNow Multi-Agent Development Framework',
1044
+ created: new Date().toISOString(),
1045
+ features: {
1046
+ swarmCoordination: true,
1047
+ persistentMemory: true,
1048
+ serviceNowIntegration: true,
1049
+ sparcModes: true
1050
+ }
1051
+ };
1052
+ const swarmConfig = {
1053
+ version: '1.0.0',
1054
+ topology: 'hierarchical',
1055
+ maxAgents: 8,
1056
+ memory: {
1057
+ database: '.swarm/memory.db',
1058
+ namespace: 'snow-flow'
1059
+ }
1060
+ };
1061
+ await fs_1.promises.writeFile((0, path_1.join)(targetDir, '.claude/config.json'), JSON.stringify(claudeConfig, null, 2));
1062
+ await fs_1.promises.writeFile((0, path_1.join)(targetDir, '.swarm/config.json'), JSON.stringify(swarmConfig, null, 2));
1063
+ }
1064
+ async function createReadmeFiles(targetDir) {
1065
+ // Only create README.md if it doesn't exist already
1066
+ const readmePath = (0, path_1.join)(targetDir, 'README.md');
1067
+ if (!(0, fs_2.existsSync)(readmePath)) {
1068
+ const mainReadme = `# Snow-Flow Project
1069
+
1070
+ This is a Snow-Flow project for ServiceNow multi-agent development.
1071
+
1072
+ ## Quick Start
1073
+
1074
+ 1. Configure your ServiceNow credentials in .env
1075
+ 2. Run: \`snow-flow auth login\`
1076
+ 3. Start your first swarm: \`snow-flow swarm "create a widget for incident management"\`
1077
+
1078
+ ## Project Structure
1079
+
1080
+ - \`.claude/\` - Claude configuration and commands
1081
+ - \`.swarm/\` - Swarm coordination and memory
1082
+ - \`memory/\` - Persistent memory for agents
1083
+ - \`coordination/\` - Agent coordination data
1084
+ - \`servicenow/\` - Generated ServiceNow artifacts
1085
+
1086
+ ## Documentation
1087
+
1088
+ - Configuration: \`.claude/config.json\`
1089
+ - Memory system: \`.swarm/memory.db\`
1090
+ - Project structure: \`.claude/commands/\`
1091
+ `;
1092
+ await fs_1.promises.writeFile(readmePath, mainReadme);
1093
+ }
1094
+ // Create sub-directory READMEs
1095
+ await fs_1.promises.writeFile((0, path_1.join)(targetDir, 'memory/agents/README.md'), '# Agent Memory\n\nThis directory contains persistent memory for ServiceNow agents.');
1096
+ await fs_1.promises.writeFile((0, path_1.join)(targetDir, 'servicenow/README.md'), '# ServiceNow Artifacts\n\nThis directory contains generated ServiceNow development artifacts.');
1097
+ }
1098
+ async function createSparcFiles(targetDir) {
1099
+ const sparcModes = [
1100
+ 'orchestrator', 'coder', 'researcher', 'tdd', 'architect', 'reviewer',
1101
+ 'debugger', 'tester', 'analyzer', 'optimizer', 'documenter', 'designer',
1102
+ 'innovator', 'swarm-coordinator', 'memory-manager', 'batch-executor', 'workflow-manager'
1103
+ ];
1104
+ for (const mode of sparcModes) {
1105
+ const content = `# SPARC ${mode.charAt(0).toUpperCase() + mode.slice(1)} Mode
1106
+
1107
+ ## Overview
1108
+ Specialized ${mode} capabilities for ServiceNow development.
1109
+
1110
+ ## Purpose
1111
+ Provide ${mode} expertise for ServiceNow projects.
1112
+
1113
+ ## Usage
1114
+ \`\`\`bash
1115
+ snow-flow sparc ${mode} "your task description"
1116
+ \`\`\`
1117
+
1118
+ This mode provides specialized ${mode} capabilities for ServiceNow development projects.
1119
+ `;
1120
+ await fs_1.promises.writeFile((0, path_1.join)(targetDir, `.claude/commands/sparc/${mode}.md`), content);
1121
+ }
1122
+ // Create CLAUDE.md with comprehensive documentation
1123
+ const claudeMd = `# Claude Code Configuration
1124
+
1125
+ ## Build Commands
1126
+ - \`npm run build\`: Build the project
1127
+ - \`npm run test\`: Run the full test suite
1128
+ - \`npm run lint\`: Run ESLint and format checks
1129
+ - \`npm run typecheck\`: Run TypeScript type checking
1130
+
1131
+ ## Snow-Flow Commands
1132
+ - \`snow-flow init --sparc\`: Initialize project with SPARC environment
1133
+ - \`snow-flow auth login\`: Authenticate with ServiceNow OAuth
1134
+ - \`snow-flow swarm "<objective>"\`: Start multi-agent swarm
1135
+ - \`snow-flow sparc <mode> "<task>"\`: Run specific SPARC mode
1136
+
1137
+ ## Quick Start
1138
+ 1. \`snow-flow init --sparc\` - Initialize project
1139
+ 2. Configure ServiceNow credentials in .env
1140
+ 3. \`snow-flow auth login\` - Authenticate with ServiceNow
1141
+ 4. \`snow-flow swarm "create a widget for incident management"\`
1142
+
1143
+ ## Project Structure
1144
+ This project uses Snow-Flow for ServiceNow multi-agent development with:
1145
+ - Multi-agent coordination
1146
+ - Persistent memory system
1147
+ - ServiceNow OAuth integration
1148
+ - SPARC methodology support
1149
+ `;
1150
+ await fs_1.promises.writeFile((0, path_1.join)(targetDir, 'CLAUDE.md'), claudeMd);
1151
+ }
1152
+ async function createEnvFile(targetDir) {
1153
+ const envContent = `# ServiceNow OAuth Configuration
1154
+ # Replace these values with your actual ServiceNow instance and OAuth credentials
1155
+
1156
+ # ServiceNow Instance URL (without https://)
1157
+ # Example: dev12345.service-now.com
1158
+ SNOW_INSTANCE=your-instance.service-now.com
1159
+
1160
+ # OAuth Client ID from ServiceNow Application Registry
1161
+ # How to get: System OAuth > Application Registry > New > Create an OAuth application
1162
+ SNOW_CLIENT_ID=your-oauth-client-id
1163
+
1164
+ # OAuth Client Secret from ServiceNow Application Registry
1165
+ SNOW_CLIENT_SECRET=your-oauth-client-secret
1166
+
1167
+ # Optional: Additional Configuration
1168
+ # SNOW_REDIRECT_URI=http://localhost:3000/callback
1169
+
1170
+ # ===========================================
1171
+ # Snow-Flow Configuration
1172
+ # ===========================================
1173
+
1174
+ # Enable debug logging (true/false)
1175
+ SNOW_FLOW_DEBUG=false
1176
+
1177
+ # Default coordination strategy
1178
+ SNOW_FLOW_STRATEGY=development
1179
+
1180
+ # Maximum number of agents
1181
+ SNOW_FLOW_MAX_AGENTS=5
1182
+
1183
+ # Claude Code timeout configuration (in minutes)
1184
+ # Set to 0 to disable timeout (infinite execution time)
1185
+ # Default: 60 minutes
1186
+ SNOW_FLOW_TIMEOUT_MINUTES=0
1187
+
1188
+ # ===========================================
1189
+ # How to Set Up ServiceNow OAuth
1190
+ # ===========================================
1191
+ # 1. Log into your ServiceNow instance as admin
1192
+ # 2. Navigate to: System OAuth > Application Registry
1193
+ # 3. Click "New" > "Create an OAuth application"
1194
+ # 4. Fill in:
1195
+ # - Name: Snow-Flow Development
1196
+ # - Client ID: (will be generated)
1197
+ # - Client Secret: (will be generated)
1198
+ # - Redirect URL: http://localhost:3000/callback
1199
+ # - Grant Type: Authorization Code
1200
+ # 5. Copy the Client ID and Client Secret to this file
1201
+ # 6. Run: snow-flow auth login
1202
+ `;
1203
+ const envFilePath = (0, path_1.join)(targetDir, '.env');
1204
+ // Check if .env already exists
1205
+ try {
1206
+ await fs_1.promises.access(envFilePath);
1207
+ console.log('āš ļø .env file already exists, creating .env.example instead...');
1208
+ await fs_1.promises.writeFile((0, path_1.join)(targetDir, '.env.example'), envContent);
1209
+ }
1210
+ catch {
1211
+ // .env doesn't exist, create it
1212
+ await fs_1.promises.writeFile(envFilePath, envContent);
1213
+ }
1214
+ }
1215
+ async function createMCPConfig(targetDir) {
1216
+ // Create the correct .mcp.json file for Claude Code discovery
1217
+ const mcpConfig = {
1218
+ "mcpServers": {
1219
+ "servicenow-deployment": {
1220
+ "command": "node",
1221
+ "args": ["dist/mcp/servicenow-deployment-mcp.js"],
1222
+ "env": {
1223
+ "SNOW_INSTANCE": "${SNOW_INSTANCE}",
1224
+ "SNOW_CLIENT_ID": "${SNOW_CLIENT_ID}",
1225
+ "SNOW_CLIENT_SECRET": "${SNOW_CLIENT_SECRET}"
1226
+ }
1227
+ },
1228
+ "servicenow-flow-composer": {
1229
+ "command": "node",
1230
+ "args": ["dist/mcp/servicenow-flow-composer-mcp.js"],
1231
+ "env": {
1232
+ "SNOW_INSTANCE": "${SNOW_INSTANCE}",
1233
+ "SNOW_CLIENT_ID": "${SNOW_CLIENT_ID}",
1234
+ "SNOW_CLIENT_SECRET": "${SNOW_CLIENT_SECRET}"
1235
+ }
1236
+ },
1237
+ "servicenow-update-set": {
1238
+ "command": "node",
1239
+ "args": ["dist/mcp/servicenow-update-set-mcp.js"],
1240
+ "env": {
1241
+ "SNOW_INSTANCE": "${SNOW_INSTANCE}",
1242
+ "SNOW_CLIENT_ID": "${SNOW_CLIENT_ID}",
1243
+ "SNOW_CLIENT_SECRET": "${SNOW_CLIENT_SECRET}"
1244
+ }
1245
+ },
1246
+ "servicenow-intelligent": {
1247
+ "command": "node",
1248
+ "args": ["dist/mcp/servicenow-intelligent-mcp.js"],
1249
+ "env": {
1250
+ "SNOW_INSTANCE": "${SNOW_INSTANCE}",
1251
+ "SNOW_CLIENT_ID": "${SNOW_CLIENT_ID}",
1252
+ "SNOW_CLIENT_SECRET": "${SNOW_CLIENT_SECRET}"
1253
+ }
1254
+ },
1255
+ "servicenow-graph-memory": {
1256
+ "command": "node",
1257
+ "args": ["dist/mcp/servicenow-graph-memory-mcp.js"],
1258
+ "env": {
1259
+ "NEO4J_URI": "${NEO4J_URI}",
1260
+ "NEO4J_USER": "${NEO4J_USER}",
1261
+ "NEO4J_PASSWORD": "${NEO4J_PASSWORD}",
1262
+ "SNOW_INSTANCE": "${SNOW_INSTANCE}",
1263
+ "SNOW_CLIENT_ID": "${SNOW_CLIENT_ID}",
1264
+ "SNOW_CLIENT_SECRET": "${SNOW_CLIENT_SECRET}"
1265
+ }
1266
+ },
1267
+ "servicenow-operations": {
1268
+ "command": "node",
1269
+ "args": ["dist/mcp/servicenow-operations-mcp.js"],
1270
+ "env": {
1271
+ "SNOW_INSTANCE": "${SNOW_INSTANCE}",
1272
+ "SNOW_CLIENT_ID": "${SNOW_CLIENT_ID}",
1273
+ "SNOW_CLIENT_SECRET": "${SNOW_CLIENT_SECRET}"
1274
+ }
1275
+ },
1276
+ "servicenow-platform-development": {
1277
+ "command": "node",
1278
+ "args": ["dist/mcp/servicenow-platform-development-mcp.js"],
1279
+ "env": {
1280
+ "SNOW_INSTANCE": "${SNOW_INSTANCE}",
1281
+ "SNOW_CLIENT_ID": "${SNOW_CLIENT_ID}",
1282
+ "SNOW_CLIENT_SECRET": "${SNOW_CLIENT_SECRET}"
1283
+ }
1284
+ },
1285
+ "servicenow-integration": {
1286
+ "command": "node",
1287
+ "args": ["dist/mcp/servicenow-integration-mcp.js"],
1288
+ "env": {
1289
+ "SNOW_INSTANCE": "${SNOW_INSTANCE}",
1290
+ "SNOW_CLIENT_ID": "${SNOW_CLIENT_ID}",
1291
+ "SNOW_CLIENT_SECRET": "${SNOW_CLIENT_SECRET}"
1292
+ }
1293
+ },
1294
+ "servicenow-automation": {
1295
+ "command": "node",
1296
+ "args": ["dist/mcp/servicenow-automation-mcp.js"],
1297
+ "env": {
1298
+ "SNOW_INSTANCE": "${SNOW_INSTANCE}",
1299
+ "SNOW_CLIENT_ID": "${SNOW_CLIENT_ID}",
1300
+ "SNOW_CLIENT_SECRET": "${SNOW_CLIENT_SECRET}"
1301
+ }
1302
+ },
1303
+ "servicenow-security-compliance": {
1304
+ "command": "node",
1305
+ "args": ["dist/mcp/servicenow-security-compliance-mcp.js"],
1306
+ "env": {
1307
+ "SNOW_INSTANCE": "${SNOW_INSTANCE}",
1308
+ "SNOW_CLIENT_ID": "${SNOW_CLIENT_ID}",
1309
+ "SNOW_CLIENT_SECRET": "${SNOW_CLIENT_SECRET}"
1310
+ }
1311
+ },
1312
+ "servicenow-reporting-analytics": {
1313
+ "command": "node",
1314
+ "args": ["dist/mcp/servicenow-reporting-analytics-mcp.js"],
1315
+ "env": {
1316
+ "SNOW_INSTANCE": "${SNOW_INSTANCE}",
1317
+ "SNOW_CLIENT_ID": "${SNOW_CLIENT_ID}",
1318
+ "SNOW_CLIENT_SECRET": "${SNOW_CLIENT_SECRET}"
1319
+ }
1320
+ }
1321
+ }
1322
+ };
1323
+ // Create .mcp.json in project root for Claude Code discovery
1324
+ const mcpConfigPath = (0, path_1.join)(targetDir, '.mcp.json');
1325
+ await fs_1.promises.writeFile(mcpConfigPath, JSON.stringify(mcpConfig, null, 2));
1326
+ // Also create legacy config in .claude for backward compatibility
1327
+ const legacyConfigPath = (0, path_1.join)(targetDir, '.claude/mcp-config.json');
1328
+ await fs_1.promises.writeFile(legacyConfigPath, JSON.stringify(mcpConfig, null, 2));
1329
+ // Create comprehensive Claude Code settings file
1330
+ const claudeSettings = {
1331
+ "permissions": {
1332
+ "allow": [
1333
+ "Bash(*)",
1334
+ "Read(*)",
1335
+ "Write(*)",
1336
+ "Edit(*)",
1337
+ "MultiEdit(*)",
1338
+ "Glob(*)",
1339
+ "Grep(*)",
1340
+ "LS(*)",
1341
+ "NotebookEdit(*)",
1342
+ "NotebookRead(*)",
1343
+ "WebFetch(*)",
1344
+ "WebSearch(*)",
1345
+ "TodoRead",
1346
+ "TodoWrite",
1347
+ "Task(*)",
1348
+ "ListMcpResourcesTool",
1349
+ "ReadMcpResourceTool",
1350
+ "mcp__claude-flow__*"
1351
+ ],
1352
+ "deny": []
1353
+ },
1354
+ "env": {
1355
+ "BASH_DEFAULT_TIMEOUT_MS": "0",
1356
+ "BASH_MAX_TIMEOUT_MS": "0",
1357
+ "BASH_MAX_OUTPUT_LENGTH": "500000",
1358
+ "CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR": "true",
1359
+ "MAX_THINKING_TOKENS": "50000",
1360
+ "MCP_TIMEOUT": "0",
1361
+ "MCP_TOOL_TIMEOUT": "0",
1362
+ "DISABLE_COST_WARNINGS": "1",
1363
+ "DISABLE_NON_ESSENTIAL_MODEL_CALLS": "0",
1364
+ "CLAUDE_CODE_MAX_OUTPUT_TOKENS": "8192",
1365
+ "CLAUDE_CODE_TIMEOUT": "0",
1366
+ "CLAUDE_CODE_SESSION_TIMEOUT": "0",
1367
+ "CLAUDE_CODE_EXECUTION_TIMEOUT": "0"
1368
+ },
1369
+ "cleanupPeriodDays": 90,
1370
+ "includeCoAuthoredBy": true,
1371
+ "automation": {
1372
+ "enabled": true,
1373
+ "defaultTimeout": 300000,
1374
+ "maxRetries": 3,
1375
+ "retryBackoff": 2000,
1376
+ "parallelExecution": true,
1377
+ "batchOperations": true,
1378
+ "autoSaveMemory": true,
1379
+ "autoCommit": false
1380
+ },
1381
+ "claudeFlow": {
1382
+ "version": "1.0.72",
1383
+ "swarmDefaults": {
1384
+ "maxAgents": 10,
1385
+ "timeout": 0,
1386
+ "parallel": true,
1387
+ "monitor": true,
1388
+ "outputFormat": "json"
1389
+ },
1390
+ "sparcDefaults": {
1391
+ "timeout": 0,
1392
+ "parallel": true,
1393
+ "batch": true,
1394
+ "memoryKey": "sparc_session"
1395
+ },
1396
+ "memoryDefaults": {
1397
+ "maxSize": "5GB",
1398
+ "autoCompress": true,
1399
+ "autoCleanup": true,
1400
+ "indexingEnabled": true,
1401
+ "persistenceEnabled": true
1402
+ }
1403
+ },
1404
+ "mcpServers": {
1405
+ "servicenow": {
1406
+ "command": "node",
1407
+ "args": ["dist/mcp/start-servicenow-mcp.js"],
1408
+ "env": {
1409
+ "SNOW_INSTANCE": "${SNOW_INSTANCE}",
1410
+ "SNOW_CLIENT_ID": "${SNOW_CLIENT_ID}",
1411
+ "SNOW_CLIENT_SECRET": "${SNOW_CLIENT_SECRET}"
1412
+ }
1413
+ }
1414
+ }
1415
+ };
1416
+ const claudeSettingsPath = (0, path_1.join)(targetDir, '.claude/settings.json');
1417
+ await fs_1.promises.writeFile(claudeSettingsPath, JSON.stringify(claudeSettings, null, 2));
1418
+ }
1419
+ // Direct widget creation command
1420
+ program
1421
+ .command('create-widget [type]')
1422
+ .description('Create a ServiceNow widget using templates')
1423
+ .action(async (type = 'incident-management') => {
1424
+ try {
1425
+ // Use generic artifact deployment instead
1426
+ console.log('šŸŽÆ Creating widget using template system...');
1427
+ console.log('✨ Use: snow-flow deploy-artifact -t widget -c <config-file>');
1428
+ console.log('šŸ“ Or use: snow-flow swarm "create a widget for incident management"');
1429
+ }
1430
+ catch (error) {
1431
+ console.error('āŒ Error creating widget:', error);
1432
+ }
1433
+ });
1434
+ // MCP Server command with subcommands
1435
+ program
1436
+ .command('mcp <action>')
1437
+ .description('Manage ServiceNow MCP servers for Claude Code integration')
1438
+ .option('--server <name>', 'Specific server name to manage')
1439
+ .option('--port <port>', 'Port for MCP server (default: auto)')
1440
+ .option('--host <host>', 'Host for MCP server (default: localhost)')
1441
+ .action(async (action, options) => {
1442
+ const { MCPServerManager } = await Promise.resolve().then(() => __importStar(require('./utils/mcp-server-manager.js')));
1443
+ const manager = new MCPServerManager();
1444
+ try {
1445
+ await manager.initialize();
1446
+ switch (action) {
1447
+ case 'start':
1448
+ await handleMCPStart(manager, options);
1449
+ break;
1450
+ case 'stop':
1451
+ await handleMCPStop(manager, options);
1452
+ break;
1453
+ case 'restart':
1454
+ await handleMCPRestart(manager, options);
1455
+ break;
1456
+ case 'status':
1457
+ await handleMCPStatus(manager, options);
1458
+ break;
1459
+ case 'logs':
1460
+ await handleMCPLogs(manager, options);
1461
+ break;
1462
+ case 'list':
1463
+ await handleMCPList(manager, options);
1464
+ break;
1465
+ default:
1466
+ console.error(`āŒ Unknown action: ${action}`);
1467
+ console.log('Available actions: start, stop, restart, status, logs, list');
1468
+ process.exit(1);
1469
+ }
1470
+ }
1471
+ catch (error) {
1472
+ console.error('āŒ MCP operation failed:', error instanceof Error ? error.message : String(error));
1473
+ process.exit(1);
1474
+ }
1475
+ });
1476
+ // MCP action handlers
1477
+ async function handleMCPStart(manager, options) {
1478
+ console.log('šŸš€ Starting ServiceNow MCP Servers...');
1479
+ if (options.server) {
1480
+ console.log(`šŸ“” Starting server: ${options.server}`);
1481
+ const success = await manager.startServer(options.server);
1482
+ if (success) {
1483
+ console.log(`āœ… Server '${options.server}' started successfully`);
1484
+ }
1485
+ else {
1486
+ console.log(`āŒ Failed to start server '${options.server}'`);
1487
+ process.exit(1);
1488
+ }
1489
+ }
1490
+ else {
1491
+ console.log('šŸ“” Starting all configured MCP servers...');
1492
+ await manager.startAllServers();
1493
+ const status = manager.getServerStatus();
1494
+ const running = status.filter((s) => s.status === 'running').length;
1495
+ const total = status.length;
1496
+ console.log(`\nāœ… Started ${running}/${total} MCP servers`);
1497
+ if (running === total) {
1498
+ console.log('šŸŽ‰ All MCP servers are now running and available in Claude Code!');
1499
+ console.log('\nšŸ“‹ Next steps:');
1500
+ console.log(' 1. Open Claude Code');
1501
+ console.log(' 2. MCP tools will be automatically available');
1502
+ console.log(' 3. Use snow_deploy_widget, snow_deploy_flow, etc.');
1503
+ }
1504
+ else {
1505
+ console.log('āš ļø Some servers failed to start. Check logs with: snow-flow mcp logs');
1506
+ }
1507
+ }
1508
+ }
1509
+ async function handleMCPStop(manager, options) {
1510
+ if (options.server) {
1511
+ console.log(`šŸ›‘ Stopping server: ${options.server}`);
1512
+ const success = await manager.stopServer(options.server);
1513
+ if (success) {
1514
+ console.log(`āœ… Server '${options.server}' stopped successfully`);
1515
+ }
1516
+ else {
1517
+ console.log(`āŒ Failed to stop server '${options.server}'`);
1518
+ process.exit(1);
1519
+ }
1520
+ }
1521
+ else {
1522
+ console.log('šŸ›‘ Stopping all MCP servers...');
1523
+ await manager.stopAllServers();
1524
+ console.log('āœ… All MCP servers stopped');
1525
+ }
1526
+ }
1527
+ async function handleMCPRestart(manager, options) {
1528
+ if (options.server) {
1529
+ console.log(`šŸ”„ Restarting server: ${options.server}`);
1530
+ await manager.stopServer(options.server);
1531
+ const success = await manager.startServer(options.server);
1532
+ if (success) {
1533
+ console.log(`āœ… Server '${options.server}' restarted successfully`);
1534
+ }
1535
+ else {
1536
+ console.log(`āŒ Failed to restart server '${options.server}'`);
1537
+ process.exit(1);
1538
+ }
1539
+ }
1540
+ else {
1541
+ console.log('šŸ”„ Restarting all MCP servers...');
1542
+ await manager.stopAllServers();
1543
+ await manager.startAllServers();
1544
+ const running = manager.getRunningServersCount();
1545
+ const total = manager.getServerStatus().length;
1546
+ console.log(`āœ… Restarted ${running}/${total} MCP servers`);
1547
+ }
1548
+ }
1549
+ async function handleMCPStatus(manager, options) {
1550
+ const servers = manager.getServerStatus();
1551
+ console.log('\nšŸ“Š MCP Server Status');
1552
+ console.log('═'.repeat(80));
1553
+ if (servers.length === 0) {
1554
+ console.log('No MCP servers configured');
1555
+ return;
1556
+ }
1557
+ servers.forEach((server) => {
1558
+ const statusIcon = server.status === 'running' ? 'āœ…' :
1559
+ server.status === 'starting' ? 'šŸ”„' :
1560
+ server.status === 'error' ? 'āŒ' : 'ā­•';
1561
+ console.log(`${statusIcon} ${server.name}`);
1562
+ console.log(` Status: ${server.status}`);
1563
+ console.log(` Script: ${server.script}`);
1564
+ if (server.pid) {
1565
+ console.log(` PID: ${server.pid}`);
1566
+ }
1567
+ if (server.startedAt) {
1568
+ console.log(` Started: ${server.startedAt.toLocaleString()}`);
1569
+ }
1570
+ if (server.lastError) {
1571
+ console.log(` Last Error: ${server.lastError}`);
1572
+ }
1573
+ console.log('');
1574
+ });
1575
+ const running = servers.filter((s) => s.status === 'running').length;
1576
+ const total = servers.length;
1577
+ console.log(`šŸ“ˆ Summary: ${running}/${total} servers running`);
1578
+ if (running === total) {
1579
+ console.log('šŸŽ‰ All MCP servers are operational and available in Claude Code!');
1580
+ }
1581
+ else if (running > 0) {
1582
+ console.log('āš ļø Some servers are not running. Use "snow-flow mcp start" to start them.');
1583
+ }
1584
+ else {
1585
+ console.log('šŸ’” No servers running. Use "snow-flow mcp start" to start all servers.');
1586
+ }
1587
+ }
1588
+ async function handleMCPLogs(manager, options) {
1589
+ const { join } = require('path');
1590
+ const { promises: fs } = require('fs');
1591
+ const logDir = join(process.cwd(), '.snow-flow', 'logs');
1592
+ try {
1593
+ const logFiles = await fs.readdir(logDir);
1594
+ if (options.server) {
1595
+ const serverLogFile = `${options.server.replace(/\\s+/g, '_').toLowerCase()}.log`;
1596
+ if (logFiles.includes(serverLogFile)) {
1597
+ console.log(`šŸ“„ Logs for ${options.server}:`);
1598
+ console.log('═'.repeat(80));
1599
+ const logContent = await fs.readFile(join(logDir, serverLogFile), 'utf-8');
1600
+ console.log(logContent);
1601
+ }
1602
+ else {
1603
+ console.log(`āŒ No logs found for server '${options.server}'`);
1604
+ }
1605
+ }
1606
+ else {
1607
+ console.log('šŸ“„ Available log files:');
1608
+ logFiles.forEach((file) => {
1609
+ console.log(` - ${file}`);
1610
+ });
1611
+ console.log('\\nšŸ’” Use --server <name> to view specific server logs');
1612
+ }
1613
+ }
1614
+ catch (error) {
1615
+ console.log('šŸ“„ No log files found');
1616
+ }
1617
+ }
1618
+ async function handleMCPList(manager, options) {
1619
+ const servers = manager.getServerStatus();
1620
+ console.log('\nšŸ“‹ Configured MCP Servers');
1621
+ console.log('═'.repeat(80));
1622
+ if (servers.length === 0) {
1623
+ console.log('No MCP servers configured');
1624
+ console.log('šŸ’” Run "snow-flow init" to configure default MCP servers');
1625
+ return;
1626
+ }
1627
+ servers.forEach((server, index) => {
1628
+ console.log(`${index + 1}. ${server.name}`);
1629
+ console.log(` Script: ${server.script}`);
1630
+ console.log(` Status: ${server.status}`);
1631
+ console.log('');
1632
+ });
1633
+ }
1634
+ // Create Flow command - intelligent flow composition
1635
+ program
1636
+ .command('create-flow <instruction>')
1637
+ .description('Create complex ServiceNow flows using natural language with automatic artifact orchestration')
1638
+ .option('--analyze-only', 'Only analyze the instruction without creating the flow')
1639
+ .option('--preview', 'Preview the flow structure before deployment')
1640
+ .option('--no-deploy', 'Create the flow but do not deploy it')
1641
+ .action(async (instruction, options) => {
1642
+ console.log(`\n🧠 Snow-Flow Intelligent Flow Composer`);
1643
+ console.log(`šŸ“ Instruction: ${instruction}`);
1644
+ console.log(`šŸ” Analyzing requirements and discovering artifacts...\n`);
1645
+ // Check authentication
1646
+ const oauth = new snow_oauth_js_1.ServiceNowOAuth();
1647
+ const isAuthenticated = await oauth.isAuthenticated();
1648
+ if (!isAuthenticated) {
1649
+ console.log('šŸ”— ServiceNow connection: āŒ Not authenticated');
1650
+ console.log('šŸ’” Run "snow-flow auth login" to enable live ServiceNow integration');
1651
+ console.log('šŸ“ Flow will be created as definition files\n');
1652
+ }
1653
+ else {
1654
+ console.log('šŸ”— ServiceNow connection: āœ… Authenticated');
1655
+ console.log('šŸš€ Flow will be created and deployed directly to ServiceNow\n');
1656
+ }
1657
+ // Generate Claude Code prompt for flow composition
1658
+ const flowPrompt = `# Snow-Flow Intelligent Flow Composer
1659
+
1660
+ ## Instruction
1661
+ ${instruction}
1662
+
1663
+ ## Task: Create Complex ServiceNow Flow with Multi-Artifact Orchestration
1664
+
1665
+ You are Snow-Flow's intelligent flow composer. Your task is to create a complex ServiceNow flow using natural language processing and automatic artifact orchestration.
1666
+
1667
+ ## Process Steps
1668
+
1669
+ ### 1. Analyze Flow Requirements
1670
+ Use the flow composition MCP tools to understand the instruction:
1671
+ - \`snow_analyze_flow_instruction\` - Parse and understand the natural language instruction
1672
+ - Identify required ServiceNow artifacts (script includes, business rules, tables, etc.)
1673
+ - Determine data flow and business logic requirements
1674
+
1675
+ ### 2. Discover ServiceNow Artifacts
1676
+ Use intelligent artifact discovery:
1677
+ - \`snow_discover_flow_artifacts\` - Find existing ServiceNow artifacts that match requirements
1678
+ - Search for script includes, business rules, tables, and other components
1679
+ - Identify missing artifacts that need to be created
1680
+
1681
+ ### 3. Preview Flow Structure
1682
+ Before deployment, preview the complete flow:
1683
+ - \`snow_preview_flow_structure\` - Show the complete flow structure
1684
+ - Display all activities, variables, and error handling
1685
+ - Show how discovered artifacts will be orchestrated
1686
+
1687
+ ### 4. Create and Deploy Flow
1688
+ Create the complete flow with orchestration:
1689
+ - \`snow_create_complex_flow\` - Generate complete flow with all artifacts
1690
+ - Automatically create fallback artifacts if needed
1691
+ - Deploy to ServiceNow if authenticated
1692
+
1693
+ ## Advanced Capabilities
1694
+
1695
+ ### Multi-Artifact Orchestration
1696
+ The flow composer can automatically:
1697
+ - Find existing script includes for LLM translation
1698
+ - Discover business rules for data storage
1699
+ - Create tables for translated messages
1700
+ - Link all components in a cohesive flow
1701
+
1702
+ ### Intelligent Fallback Creation
1703
+ If required artifacts are not found:
1704
+ - Creates basic LLM translation script includes
1705
+ - Generates data storage business rules
1706
+ - Creates database tables with proper schema
1707
+ - Ensures all components work together
1708
+
1709
+ ### Natural Language Processing
1710
+ Understands complex instructions like:
1711
+ - "Create a flow using LLM localization to translate support desk messages to English"
1712
+ - "Build approval flow with email notifications after manager approval"
1713
+ - "Design incident escalation with automatic assignment based on priority"
1714
+
1715
+ ## Available Flow Composition Tools
1716
+
1717
+ ### Core Tools
1718
+ - \`snow_create_complex_flow\` - Main flow creation tool
1719
+ - \`snow_analyze_flow_instruction\` - Instruction analysis
1720
+ - \`snow_discover_flow_artifacts\` - Artifact discovery
1721
+ - \`snow_preview_flow_structure\` - Flow preview
1722
+
1723
+ ### Configuration
1724
+ - Deploy immediately: ${!options.noDeploy}
1725
+ - Analysis only: ${options.analyzeOnly || false}
1726
+ - Preview mode: ${options.preview || false}
1727
+ - ServiceNow authenticated: ${isAuthenticated}
1728
+
1729
+ ## Expected Output
1730
+
1731
+ The flow composer will:
1732
+ 1. Parse your natural language instruction
1733
+ 2. Identify all required ServiceNow artifacts
1734
+ 3. Discover existing artifacts or create fallbacks
1735
+ 4. Compose a complete flow with orchestration
1736
+ 5. Deploy to ServiceNow (if authenticated)
1737
+ 6. Provide direct links to created artifacts
1738
+
1739
+ ## Instructions for Execution
1740
+
1741
+ ${options.analyzeOnly ?
1742
+ 'ANALYZE ONLY: Use snow_analyze_flow_instruction to analyze the instruction and show requirements.' :
1743
+ options.preview ?
1744
+ 'PREVIEW MODE: Use snow_preview_flow_structure to show the complete flow structure before deployment.' :
1745
+ 'FULL CREATION: Use snow_create_complex_flow to create and deploy the complete flow with orchestration.'}
1746
+
1747
+ Execute this intelligent flow composition using Snow-Flow's advanced orchestration capabilities.
1748
+ `;
1749
+ try {
1750
+ // Execute Claude Code with the flow composition prompt
1751
+ const success = await executeClaudeCode(flowPrompt);
1752
+ if (success) {
1753
+ console.log('\nāœ… Flow composition completed successfully!');
1754
+ if (isAuthenticated && !options.noDeploy) {
1755
+ console.log('šŸš€ Flow deployed to ServiceNow with all artifacts');
1756
+ console.log('šŸ“Š Check your ServiceNow instance for the deployed flow');
1757
+ }
1758
+ else {
1759
+ console.log('šŸ“‹ Flow structure created and analyzed');
1760
+ }
1761
+ }
1762
+ else {
1763
+ console.log('\nāš ļø Claude Code execution failed. Flow composition prompt generated:');
1764
+ console.log('='.repeat(80));
1765
+ console.log(flowPrompt);
1766
+ console.log('='.repeat(80));
1767
+ console.log('\nšŸ’” Copy this prompt and run it in Claude Code for flow composition');
1768
+ }
1769
+ }
1770
+ catch (error) {
1771
+ console.error('āŒ Flow composition failed:', error instanceof Error ? error.message : String(error));
1772
+ }
1773
+ });
1774
+ // Parse command line arguments
1775
+ // Init command - initialize a new Snow-Flow project
1776
+ program
1777
+ .command('init')
1778
+ .description('Initialize a new Snow-Flow project')
1779
+ .option('--sparc', 'Initialize with full SPARC development environment')
1780
+ .option('--force', 'Force reinitialize if project already exists')
1781
+ .action(async (options) => {
1782
+ const targetDir = process.cwd();
1783
+ try {
1784
+ console.log('šŸš€ Initializing Snow-Flow project...\n');
1785
+ // Check if project is already initialized
1786
+ const claudeDir = (0, path_1.join)(targetDir, '.claude');
1787
+ if (!options.force) {
1788
+ try {
1789
+ await fs_1.promises.access(claudeDir);
1790
+ console.log('āŒ Snow-Flow project already initialized. Use --force to reinitialize.');
1791
+ return;
1792
+ }
1793
+ catch {
1794
+ // Directory doesn't exist, continue with initialization
1795
+ }
1796
+ }
1797
+ // Phase 1: Create basic structure
1798
+ console.log('šŸ“ Creating directory structure...');
1799
+ await createDirectoryStructure(targetDir);
1800
+ console.log('āœ… Directory structure created\n');
1801
+ // Phase 2: Create configuration files
1802
+ console.log('āš™ļø Creating configuration files...');
1803
+ await createBasicConfig(targetDir);
1804
+ console.log('āœ… Configuration files created\n');
1805
+ // Phase 3: Create README files
1806
+ console.log('šŸ“š Creating documentation...');
1807
+ await createReadmeFiles(targetDir);
1808
+ console.log('āœ… Documentation created\n');
1809
+ if (options.sparc) {
1810
+ console.log('šŸŽÆ Creating SPARC environment...');
1811
+ await createSparcFiles(targetDir);
1812
+ console.log('āœ… SPARC environment created\n');
1813
+ }
1814
+ // Phase 4: Create .env file
1815
+ console.log('šŸ” Creating environment configuration...');
1816
+ await createEnvFile(targetDir);
1817
+ console.log('āœ… Environment file created\n');
1818
+ // Phase 5: Create MCP configuration and Claude Code settings
1819
+ console.log('🌐 MCP server configuration will be generated after build...');
1820
+ console.log('āš™ļø Claude Code settings configured with:\n');
1821
+ console.log(' - No timeouts (unlimited execution time)');
1822
+ console.log(' - All batch tools enabled (TodoWrite, Task, Memory)');
1823
+ console.log(' - ServiceNow MCP server integration');
1824
+ console.log(' - Automation and parallel execution enabled');
1825
+ console.log(' - Extended output limits and thinking tokens\n');
1826
+ // Phase 6: Build project and start MCP servers
1827
+ console.log('šŸ”§ Setting up MCP servers...');
1828
+ // Check if we're running from npm global install or local dev
1829
+ const isGlobalInstall = __dirname.includes('node_modules') || !(0, fs_2.existsSync)((0, path_1.join)(targetDir, 'src'));
1830
+ if (!isGlobalInstall) {
1831
+ // Only build if we're in development mode with source files
1832
+ console.log('šŸ—ļø Building project (compiling TypeScript)...');
1833
+ try {
1834
+ const { spawn } = require('child_process');
1835
+ const buildProcess = spawn('npm', ['run', 'build'], {
1836
+ cwd: targetDir,
1837
+ stdio: 'pipe'
1838
+ });
1839
+ await new Promise((resolve, reject) => {
1840
+ buildProcess.on('close', (code) => {
1841
+ if (code === 0) {
1842
+ resolve(undefined);
1843
+ }
1844
+ else {
1845
+ reject(new Error(`Build failed with code ${code}`));
1846
+ }
1847
+ });
1848
+ });
1849
+ console.log('āœ… Project built successfully');
1850
+ }
1851
+ catch (error) {
1852
+ console.log('āš ļø Build failed - continuing with setup...');
1853
+ }
1854
+ }
1855
+ else {
1856
+ console.log('āœ… Using pre-built MCP servers from npm package');
1857
+ }
1858
+ // Run MCP setup script to generate .mcp.json
1859
+ console.log('šŸ”§ Generating MCP configuration...');
1860
+ const setupProcess = (0, child_process_1.spawn)('npm', ['run', 'setup-mcp'], {
1861
+ cwd: targetDir,
1862
+ stdio: 'pipe'
1863
+ });
1864
+ await new Promise((resolve, reject) => {
1865
+ setupProcess.on('close', (code) => {
1866
+ if (code === 0) {
1867
+ resolve(undefined);
1868
+ }
1869
+ else {
1870
+ reject(new Error(`MCP setup failed with code ${code}`));
1871
+ }
1872
+ });
1873
+ });
1874
+ console.log('āœ… MCP configuration generated with absolute paths');
1875
+ // Now initialize and start MCP servers
1876
+ const { MCPServerManager } = await Promise.resolve().then(() => __importStar(require('./utils/mcp-server-manager.js')));
1877
+ const manager = new MCPServerManager();
1878
+ await manager.initialize();
1879
+ console.log('āœ… MCP server manager initialized');
1880
+ console.log('šŸ“” Starting MCP servers...');
1881
+ await manager.startAllServers();
1882
+ const status = manager.getServerStatus();
1883
+ const running = status.filter(s => s.status === 'running').length;
1884
+ const total = status.length;
1885
+ if (running > 0) {
1886
+ console.log(`āœ… Started ${running}/${total} MCP servers`);
1887
+ console.log('šŸŽ‰ MCP servers are now running and available in Claude Code!');
1888
+ }
1889
+ else {
1890
+ console.log('āš ļø MCP servers configured but failed to start');
1891
+ }
1892
+ // Phase 7: Register MCP servers with Claude Code
1893
+ console.log('šŸ“” Registering MCP servers with Claude Code...');
1894
+ try {
1895
+ const { spawn } = require('child_process');
1896
+ const mcpServers = [
1897
+ { name: 'servicenow-deployment', path: (0, path_1.join)(targetDir, 'dist/mcp/servicenow-deployment-mcp.js') },
1898
+ { name: 'servicenow-flow-composer', path: (0, path_1.join)(targetDir, 'dist/mcp/servicenow-flow-composer-mcp.js') },
1899
+ { name: 'servicenow-update-set', path: (0, path_1.join)(targetDir, 'dist/mcp/servicenow-update-set-mcp.js') },
1900
+ { name: 'servicenow-intelligent', path: (0, path_1.join)(targetDir, 'dist/mcp/servicenow-intelligent-mcp.js') },
1901
+ { name: 'servicenow-graph-memory', path: (0, path_1.join)(targetDir, 'dist/mcp/servicenow-graph-memory-mcp.js') },
1902
+ { name: 'servicenow-operations', path: (0, path_1.join)(targetDir, 'dist/mcp/servicenow-operations-mcp.js') },
1903
+ { name: 'servicenow-platform-development', path: (0, path_1.join)(targetDir, 'dist/mcp/servicenow-platform-development-mcp.js') },
1904
+ { name: 'servicenow-integration', path: (0, path_1.join)(targetDir, 'dist/mcp/servicenow-integration-mcp.js') },
1905
+ { name: 'servicenow-automation', path: (0, path_1.join)(targetDir, 'dist/mcp/servicenow-automation-mcp.js') },
1906
+ { name: 'servicenow-security-compliance', path: (0, path_1.join)(targetDir, 'dist/mcp/servicenow-security-compliance-mcp.js') },
1907
+ { name: 'servicenow-reporting-analytics', path: (0, path_1.join)(targetDir, 'dist/mcp/servicenow-reporting-analytics-mcp.js') }
1908
+ ];
1909
+ let registeredCount = 0;
1910
+ for (const server of mcpServers) {
1911
+ try {
1912
+ await new Promise((resolve, reject) => {
1913
+ const registerProcess = spawn('claude', ['mcp', 'add', server.name, server.path], {
1914
+ cwd: targetDir,
1915
+ stdio: 'pipe'
1916
+ });
1917
+ registerProcess.on('close', (code) => {
1918
+ if (code === 0) {
1919
+ registeredCount++;
1920
+ resolve(undefined);
1921
+ }
1922
+ else {
1923
+ reject(new Error(`Failed to register ${server.name}`));
1924
+ }
1925
+ });
1926
+ registerProcess.on('error', reject);
1927
+ });
1928
+ }
1929
+ catch (error) {
1930
+ console.log(` āš ļø Failed to register ${server.name} with Claude Code`);
1931
+ }
1932
+ }
1933
+ if (registeredCount > 0) {
1934
+ console.log(`āœ… Registered ${registeredCount}/${mcpServers.length} MCP servers with Claude Code`);
1935
+ console.log('šŸŽ‰ MCP servers are now visible in Claude Code /mcp command!');
1936
+ }
1937
+ else {
1938
+ console.log('āš ļø MCP server registration failed - use manual registration:');
1939
+ console.log(` claude mcp add servicenow-deployment "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-deployment-mcp.js')}"`);
1940
+ console.log(` claude mcp add servicenow-flow-composer "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-flow-composer-mcp.js')}"`);
1941
+ console.log(` claude mcp add servicenow-update-set "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-update-set-mcp.js')}"`);
1942
+ console.log(` claude mcp add servicenow-intelligent "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-intelligent-mcp.js')}"`);
1943
+ console.log(` claude mcp add servicenow-graph-memory "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-graph-memory-mcp.js')}"`);
1944
+ console.log(` claude mcp add servicenow-operations "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-operations-mcp.js')}"`);
1945
+ console.log(` claude mcp add servicenow-platform-development "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-platform-development-mcp.js')}"`);
1946
+ console.log(` claude mcp add servicenow-integration "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-integration-mcp.js')}"`);
1947
+ console.log(` claude mcp add servicenow-automation "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-automation-mcp.js')}"`);
1948
+ console.log(` claude mcp add servicenow-security-compliance "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-security-compliance-mcp.js')}"`);
1949
+ console.log(` claude mcp add servicenow-reporting-analytics "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-reporting-analytics-mcp.js')}"`);
1950
+ }
1951
+ }
1952
+ catch (error) {
1953
+ console.log('āš ļø Claude Code MCP registration failed - manual registration required:');
1954
+ console.log(` claude mcp add servicenow-deployment "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-deployment-mcp.js')}"`);
1955
+ console.log(` claude mcp add servicenow-flow-composer "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-flow-composer-mcp.js')}"`);
1956
+ console.log(` claude mcp add servicenow-update-set "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-update-set-mcp.js')}"`);
1957
+ console.log(` claude mcp add servicenow-intelligent "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-intelligent-mcp.js')}"`);
1958
+ console.log(` claude mcp add servicenow-graph-memory "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-graph-memory-mcp.js')}"`);
1959
+ console.log(` claude mcp add servicenow-operations "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-operations-mcp.js')}"`);
1960
+ console.log(` claude mcp add servicenow-platform-development "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-platform-development-mcp.js')}"`);
1961
+ console.log(` claude mcp add servicenow-integration "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-integration-mcp.js')}"`);
1962
+ console.log(` claude mcp add servicenow-automation "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-automation-mcp.js')}"`);
1963
+ console.log(` claude mcp add servicenow-security-compliance "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-security-compliance-mcp.js')}"`);
1964
+ console.log(` claude mcp add servicenow-reporting-analytics "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-reporting-analytics-mcp.js')}"`);
1965
+ }
1966
+ }
1967
+ catch (error) {
1968
+ if (!isGlobalInstall) {
1969
+ // Only show build errors in development mode
1970
+ console.log('āš ļø Build failed - MCP servers will need manual start:');
1971
+ console.log(' 1. Run: npm run build');
1972
+ console.log(' 2. Run: snow-flow mcp start');
1973
+ console.log(' 3. Register with Claude Code:');
1974
+ console.log(` claude mcp add servicenow-deployment "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-deployment-mcp.js')}"`);
1975
+ console.log(` claude mcp add servicenow-flow-composer "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-flow-composer-mcp.js')}"`);
1976
+ console.log(` claude mcp add servicenow-update-set "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-update-set-mcp.js')}"`);
1977
+ console.log(` claude mcp add servicenow-intelligent "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-intelligent-mcp.js')}"`);
1978
+ console.log(` claude mcp add servicenow-graph-memory "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-graph-memory-mcp.js')}"`);
1979
+ console.log(` claude mcp add servicenow-operations "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-operations-mcp.js')}"`);
1980
+ console.log(` claude mcp add servicenow-platform-development "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-platform-development-mcp.js')}"`);
1981
+ console.log(` claude mcp add servicenow-integration "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-integration-mcp.js')}"`);
1982
+ console.log(` claude mcp add servicenow-automation "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-automation-mcp.js')}"`);
1983
+ console.log(` claude mcp add servicenow-security-compliance "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-security-compliance-mcp.js')}"`);
1984
+ console.log(` claude mcp add servicenow-reporting-analytics "${(0, path_1.join)(targetDir, 'dist/mcp/servicenow-reporting-analytics-mcp.js')}"`);
1985
+ console.log(` Error: ${error instanceof Error ? error.message : String(error)}`);
1986
+ }
1987
+ else {
1988
+ // In global install mode, just show a simpler message
1989
+ console.log('āš ļø MCP setup encountered an issue:');
1990
+ console.log(` ${error instanceof Error ? error.message : String(error)}`);
1991
+ console.log(' The project has been initialized successfully.');
1992
+ console.log(' You may need to configure MCP servers manually.');
1993
+ }
1994
+ }
1995
+ // Success message
1996
+ console.log('\nšŸŽ‰ Snow-Flow project initialized successfully!');
1997
+ console.log('');
1998
+ console.log('šŸ“‹ Next steps:');
1999
+ console.log(' 1. Edit .env file with your ServiceNow OAuth credentials');
2000
+ console.log(' 2. Run: snow-flow auth login');
2001
+ console.log(' 3. Start your first swarm: snow-flow swarm "create a widget for incident management"');
2002
+ console.log('');
2003
+ console.log('āœ… Project is ready to use!');
2004
+ console.log('');
2005
+ console.log('šŸ”§ MCP Servers:');
2006
+ console.log(' - āœ… All 11 MCP servers have been built and configured');
2007
+ console.log(' - āœ… .mcp.json generated with absolute paths and credentials');
2008
+ console.log(' - āœ… Ready to use in Claude Code');
2009
+ console.log('');
2010
+ console.log('šŸ“” Available MCP Tools:');
2011
+ console.log(' - snow_deploy_widget - Deploy widgets directly');
2012
+ console.log(' - snow_create_complex_flow - Natural language flow creation');
2013
+ console.log(' - snow_update_set_create - Manage Update Sets');
2014
+ console.log(' - snow_find_artifact - Search with natural language');
2015
+ console.log(' - snow_graph_index_artifact - Neo4j graph memory');
2016
+ console.log(' - snow_create_ui_page - Platform development UI');
2017
+ console.log(' - snow_create_rest_message - Integration management');
2018
+ console.log(' - snow_create_scheduled_job - Process automation');
2019
+ console.log(' - snow_create_security_policy - Security & compliance');
2020
+ console.log(' - snow_create_report - Reporting & analytics');
2021
+ console.log('');
2022
+ console.log('šŸ”§ MCP Server Management:');
2023
+ console.log(' - Start servers: snow-flow mcp start');
2024
+ console.log(' - Check status: snow-flow mcp status');
2025
+ console.log(' - View logs: snow-flow mcp logs');
2026
+ console.log(' - Stop servers: snow-flow mcp stop');
2027
+ console.log('');
2028
+ console.log('šŸ“š Documentation:');
2029
+ console.log(' - Environment config: .env (configure OAuth credentials here)');
2030
+ console.log(' - MCP configuration: .mcp.json (auto-generated)');
2031
+ console.log(' - Project structure: README.md');
2032
+ console.log(' - Memory system: .swarm/memory.db');
2033
+ console.log(' - MCP servers: .snow-flow/mcp-servers.json');
2034
+ if (options.sparc) {
2035
+ console.log(' - SPARC modes: .claude/commands/sparc/');
2036
+ console.log(' - Full guide: CLAUDE.md');
2037
+ }
2038
+ console.log('');
2039
+ console.log('šŸ” OAuth Setup Guide:');
2040
+ console.log(' 1. Open .env file in your editor');
2041
+ console.log(' 2. Follow the setup instructions in the file');
2042
+ console.log(' 3. Replace placeholder values with your ServiceNow credentials');
2043
+ console.log('');
2044
+ console.log('šŸš€ Ready to build with Snow-Flow!');
2045
+ });
2046
+ try { }
2047
+ catch (error) {
2048
+ console.error('āŒ Initialization failed:', error instanceof Error ? error.message : String(error));
2049
+ process.exit(1);
2050
+ }
2051
+ ;
2052
+ program.parse(process.argv);
2053
+ // Show help if no command provided
2054
+ if (!process.argv.slice(2).length) {
2055
+ program.outputHelp();
2056
+ }
2057
+ //# sourceMappingURL=cli.js.map