snow-flow
Version:
Snow-Flow v3.2.0: Complete ServiceNow Enterprise Suite with 180+ MCP Tools. ATF Testing, Knowledge Management, Service Catalog, Change Management with CAB scheduling, Virtual Agent chatbots with NLU, Performance Analytics KPIs, Flow Designer automation, A
1,056 lines (988 loc) โข 188 kB
JavaScript
#!/usr/bin/env node
"use strict";
/**
* Minimal CLI for snow-flow - ServiceNow Multi-Agent Framework
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const commander_1 = require("commander");
const dotenv_1 = __importDefault(require("dotenv"));
const fs_1 = require("fs");
const path_1 = require("path");
const child_process_1 = require("child_process");
const os = __importStar(require("os"));
const fs_2 = require("fs");
const snow_oauth_js_1 = require("./utils/snow-oauth.js");
const servicenow_client_js_1 = require("./utils/servicenow-client.js");
const agent_detector_js_1 = require("./utils/agent-detector.js");
const version_js_1 = require("./version.js");
const logger_js_1 = require("./utils/logger.js");
const chalk_1 = __importDefault(require("chalk"));
// Load environment variables
dotenv_1.default.config();
// Create CLI logger instance
const cliLogger = new logger_js_1.Logger('cli');
const program = new commander_1.Command();
program
.name('snow-flow')
.description('ServiceNow Multi-Agent Development Framework')
.version(version_js_1.VERSION);
// Flow deprecation handler - check for flow-related commands
function checkFlowDeprecation(command, objective) {
const flowKeywords = ['flow', 'create-flow', 'xml-flow', 'flow-designer'];
const isFlowCommand = flowKeywords.some(keyword => command.includes(keyword));
const isFlowObjective = objective && objective.toLowerCase().includes('flow') &&
!objective.toLowerCase().includes('workflow') &&
!objective.toLowerCase().includes('data flow') &&
!objective.toLowerCase().includes('snow-flow');
if (isFlowCommand || isFlowObjective) {
console.error('โ Flow creation has been removed from snow-flow v1.4.0+');
console.error('');
console.error('Please use ServiceNow Flow Designer directly:');
console.error('1. Log into your ServiceNow instance');
console.error('2. Navigate to: Flow Designer > Designer');
console.error('3. Create flows using the visual interface');
console.error('');
console.error('Snow-flow continues to support:');
console.error('- Widget development');
console.error('- Update Set management');
console.error('- Table/field discovery');
console.error('- General ServiceNow operations');
process.exit(1);
}
}
// Swarm command - the main orchestration command with EVERYTHING
program
.command('swarm <objective>')
.description('Execute multi-agent orchestration for a ServiceNow task - รฉรฉn command voor alles!')
.option('--strategy <strategy>', 'Execution strategy (development, _analysis, research)', 'development')
.option('--mode <mode>', 'Coordination mode (hierarchical, mesh, distributed)', 'hierarchical')
.option('--max-agents <number>', 'Maximum number of agents', '5')
.option('--parallel', 'Enable parallel execution')
.option('--monitor', 'Enable real-time monitoring')
.option('--auto-permissions', 'Automatic permission escalation when needed')
.option('--smart-discovery', 'Smart artifact discovery and reuse (default: true)', true)
.option('--no-smart-discovery', 'Disable smart artifact discovery')
.option('--live-testing', 'Enable live testing during development (default: true)', true)
.option('--no-live-testing', 'Disable live testing')
.option('--auto-deploy', 'Automatic deployment when ready (default: true)', true)
.option('--no-auto-deploy', 'Disable automatic deployment')
.option('--auto-rollback', 'Automatic rollback on failures (default: true)', true)
.option('--no-auto-rollback', 'Disable automatic rollback')
.option('--shared-memory', 'Enable shared memory between agents (default: true)', true)
.option('--no-shared-memory', 'Disable shared memory')
.option('--progress-monitoring', 'Real-time progress monitoring (default: true)', true)
.option('--no-progress-monitoring', 'Disable progress monitoring')
.option('--xml-first', 'Use XML-first approach for flow creation (MOST RELIABLE!)')
.option('--xml-output <path>', 'Save generated XML to specific path (with --xml-first)')
.option('--autonomous-documentation', 'Enable autonomous documentation system (default: true)', true)
.option('--no-autonomous-documentation', 'Disable autonomous documentation system')
.option('--autonomous-cost-optimization', 'Enable autonomous cost optimization engine (default: true)', true)
.option('--no-autonomous-cost-optimization', 'Disable autonomous cost optimization engine')
.option('--autonomous-compliance', 'Enable autonomous compliance monitoring (default: true)', true)
.option('--no-autonomous-compliance', 'Disable autonomous compliance monitoring')
.option('--autonomous-healing', 'Enable autonomous self-healing capabilities (default: true)', true)
.option('--no-autonomous-healing', 'Disable autonomous self-healing capabilities')
.option('--autonomous-all', 'Force enable all autonomous systems (overrides individual --no- flags)')
.option('--no-autonomous-all', 'Disable all autonomous systems (overrides individual settings)')
.option('--verbose', 'Show detailed execution information')
.action(async (objective, options) => {
// Check for flow deprecation first
checkFlowDeprecation('swarm', objective);
// Always show essential info
cliLogger.info(`\n๐ Snow-Flow v${version_js_1.VERSION}`);
cliLogger.info(`๐ Objective: ${objective}`);
// Only show detailed config in verbose mode
if (options.verbose) {
cliLogger.info(`โ๏ธ Strategy: ${options.strategy} | Mode: ${options.mode} | Max Agents: ${options.maxAgents}`);
cliLogger.info(`๐ Parallel: ${options.parallel ? 'Yes' : 'No'} | Monitor: ${options.monitor ? 'Yes' : 'No'}`);
// Show new intelligent features
cliLogger.info(`\n๐ง Intelligent Features:`);
cliLogger.info(` ๐ Auto Permissions: ${options.autoPermissions ? 'โ
Yes' : 'โ No'}`);
cliLogger.info(` ๐ Smart Discovery: ${options.smartDiscovery ? 'โ
Yes' : 'โ No'}`);
cliLogger.info(` ๐งช Live Testing: ${options.liveTesting ? 'โ
Yes' : 'โ No'}`);
cliLogger.info(` ๐ Auto Deploy: ${options.autoDeploy ? 'โ
DEPLOYMENT MODE - WILL CREATE REAL ARTIFACTS' : 'โ PLANNING MODE - ANALYSIS ONLY'}`);
cliLogger.info(` ๐ Auto Rollback: ${options.autoRollback ? 'โ
Yes' : 'โ No'}`);
cliLogger.info(` ๐พ Shared Memory: ${options.sharedMemory ? 'โ
Yes' : 'โ No'}`);
cliLogger.info(` ๐ Progress Monitoring: ${options.progressMonitoring ? 'โ
Yes' : 'โ No'}`);
// Calculate actual autonomous system states (with override logic)
// Commander.js converts --no-autonomous-all to autonomousAll: false
const noAutonomousAll = options.autonomousAll === false;
const forceAutonomousAll = options.autonomousAll === true;
const autonomousDocActive = noAutonomousAll ? false :
forceAutonomousAll ? true :
options.autonomousDocumentation !== false;
const autonomousCostActive = noAutonomousAll ? false :
forceAutonomousAll ? true :
options.autonomousCostOptimization !== false;
const autonomousComplianceActive = noAutonomousAll ? false :
forceAutonomousAll ? true :
options.autonomousCompliance !== false;
const autonomousHealingActive = noAutonomousAll ? false :
forceAutonomousAll ? true :
options.autonomousHealing !== false;
const hasAutonomousSystems = autonomousDocActive || autonomousCostActive ||
autonomousComplianceActive || autonomousHealingActive;
cliLogger.info(`\n๐ค Autonomous Systems (DEFAULT ENABLED):`);
cliLogger.info(` ๐ Documentation: ${autonomousDocActive ? 'โ
ACTIVE' : 'โ Disabled'}`);
cliLogger.info(` ๐ฐ Cost Optimization: ${autonomousCostActive ? 'โ
ACTIVE' : 'โ Disabled'}`);
cliLogger.info(` ๐ Compliance Monitoring: ${autonomousComplianceActive ? 'โ
ACTIVE' : 'โ Disabled'}`);
cliLogger.info(` ๐ฅ Self-Healing: ${autonomousHealingActive ? 'โ
ACTIVE' : 'โ Disabled'}`);
cliLogger.info('');
}
else {
// In non-verbose mode, only show critical info
if (options.autoDeploy) {
cliLogger.info(`๐ Auto-Deploy: ENABLED - Will create real artifacts in ServiceNow`);
}
// Calculate autonomous systems for non-verbose mode (same logic as verbose)
const noAutonomousAll = options.autonomousAll === false;
const forceAutonomousAll = options.autonomousAll === true;
const autonomousDocActive = noAutonomousAll ? false :
forceAutonomousAll ? true :
options.autonomousDocumentation !== false;
const autonomousCostActive = noAutonomousAll ? false :
forceAutonomousAll ? true :
options.autonomousCostOptimization !== false;
const autonomousComplianceActive = noAutonomousAll ? false :
forceAutonomousAll ? true :
options.autonomousCompliance !== false;
const autonomousHealingActive = noAutonomousAll ? false :
forceAutonomousAll ? true :
options.autonomousHealing !== false;
// Show active autonomous systems
const activeSystems = [];
if (autonomousDocActive)
activeSystems.push('๐ Documentation');
if (autonomousCostActive)
activeSystems.push('๐ฐ Cost Optimization');
if (autonomousComplianceActive)
activeSystems.push('๐ Compliance');
if (autonomousHealingActive)
activeSystems.push('๐ฅ Self-Healing');
if (activeSystems.length > 0) {
cliLogger.info(`๐ค Autonomous Systems: ${activeSystems.join(', ')}`);
}
else {
cliLogger.info(`๐ค Autonomous Systems: โ All Disabled`);
}
}
// Analyze the objective using intelligent agent detection
const taskAnalysis = analyzeObjective(objective, parseInt(options.maxAgents));
// Debug logging to understand task type detection
if (process.env.DEBUG || options.verbose) {
if (process.env.DEBUG) {
cliLogger.info(`๐ DEBUG - Detected artifacts: [${taskAnalysis.serviceNowArtifacts.join(', ')}]`);
cliLogger.info(`๐ DEBUG - Flow keywords in objective: ${objective.toLowerCase().includes('flow')}`);
cliLogger.info(`๐ DEBUG - Widget keywords in objective: ${objective.toLowerCase().includes('widget')}`);
}
cliLogger.info(`\n๐ Task Analysis:`);
cliLogger.info(` ๐ฏ Task Type: ${taskAnalysis.taskType}`);
cliLogger.info(` ๐ง Primary Agent: ${taskAnalysis.primaryAgent}`);
cliLogger.info(` ๐ฅ Supporting Agents: ${taskAnalysis.supportingAgents.join(', ')}`);
cliLogger.info(` ๐ Complexity: ${taskAnalysis.complexity} | Estimated Agents: ${taskAnalysis.estimatedAgentCount}`);
cliLogger.info(` ๐ง ServiceNow Artifacts: ${taskAnalysis.serviceNowArtifacts.join(', ')}`);
cliLogger.info(` ๐ฆ Auto Update Set: ${taskAnalysis.requiresUpdateSet ? 'โ
Yes' : 'โ No'}`);
cliLogger.info(` ๐๏ธ Auto Application: ${taskAnalysis.requiresApplication ? 'โ
Yes' : 'โ No'}`);
}
// Show timeout configuration only in verbose mode
const timeoutMinutes = process.env.SNOW_FLOW_TIMEOUT_MINUTES ? parseInt(process.env.SNOW_FLOW_TIMEOUT_MINUTES) : 60;
if (options.verbose) {
if (timeoutMinutes > 0) {
cliLogger.info(`โฑ๏ธ Timeout: ${timeoutMinutes} minutes`);
}
else {
cliLogger.info('โฑ๏ธ Timeout: Disabled (infinite execution time)');
}
}
// Check ServiceNow authentication
const oauth = new snow_oauth_js_1.ServiceNowOAuth();
const isAuthenticated = await oauth.isAuthenticated();
if (options.verbose) {
if (isAuthenticated) {
cliLogger.info('๐ ServiceNow connection: โ
Authenticated');
// Test ServiceNow connection
const client = new servicenow_client_js_1.ServiceNowClient();
const testResult = await client.testConnection();
if (testResult.success) {
cliLogger.info(`๐ค Connected as: ${testResult.data.name} (${testResult.data.user_name})`);
}
}
else {
cliLogger.warn('๐ ServiceNow connection: โ Not authenticated');
cliLogger.info('๐ก Run "snow-flow auth login" to enable live ServiceNow integration');
}
}
else if (!isAuthenticated) {
// In non-verbose mode, only warn if not authenticated
cliLogger.warn('โ ๏ธ Not authenticated. Run "snow-flow auth login" for ServiceNow integration');
}
// Initialize Queen Agent memory system
if (options.verbose) {
cliLogger.info('\n๐พ Initializing swarm memory system...');
}
const { QueenMemorySystem } = await Promise.resolve().then(() => __importStar(require('./queen/queen-memory.js')));
const memorySystem = new QueenMemorySystem();
// Generate swarm session ID
const sessionId = `swarm_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
cliLogger.info(`\n๐ Session: ${sessionId}`);
// Store swarm session in memory
memorySystem.storeLearning(`session_${sessionId}`, {
objective,
taskAnalysis,
options,
started_at: new Date().toISOString(),
is_authenticated: isAuthenticated
});
// Check if this is a Flow Designer flow request
const isFlowDesignerTask = taskAnalysis.taskType === 'flow_development' ||
taskAnalysis.primaryAgent === 'flow-builder' ||
(objective.toLowerCase().includes('flow') &&
!objective.toLowerCase().includes('workflow') &&
!objective.toLowerCase().includes('data flow'));
let xmlFlowResult = null;
// Start real Claude Code orchestration
try {
// Generate the Queen Agent orchestration prompt
const orchestrationPrompt = buildQueenAgentPrompt(objective, taskAnalysis, options, isAuthenticated, sessionId, isFlowDesignerTask);
if (options.verbose) {
cliLogger.info('\n๐ Initializing Queen Agent orchestration...');
cliLogger.info('๐ฏ Queen Agent will coordinate the following:');
cliLogger.info(` - Analyze objective: "${objective}"`);
cliLogger.info(` - Spawn ${taskAnalysis.estimatedAgentCount} specialized agents`);
cliLogger.info(` - Coordinate through shared memory (session: ${sessionId})`);
cliLogger.info(` - Monitor progress and adapt strategy`);
}
else {
cliLogger.info('\n๐ Launching Queen Agent...');
}
// Check if intelligent features are enabled
const hasIntelligentFeatures = options.autoPermissions || options.smartDiscovery ||
options.liveTesting || options.autoDeploy || options.autoRollback ||
options.sharedMemory || options.progressMonitoring;
if (options.verbose && hasIntelligentFeatures && isAuthenticated) {
cliLogger.info('\n๐ง INTELLIGENT ORCHESTRATION MODE ENABLED!');
cliLogger.info('โจ Queen Agent will use advanced features:');
if (options.autoPermissions) {
cliLogger.info(' ๐ Automatic permission escalation');
}
if (options.smartDiscovery) {
cliLogger.info(' ๐ Smart artifact discovery and reuse');
}
if (options.liveTesting) {
cliLogger.info(' ๐งช Real-time testing in ServiceNow');
}
if (options.autoDeploy) {
cliLogger.info(' ๐ Automatic deployment when ready');
}
if (options.autoRollback) {
cliLogger.info(' ๐ Automatic rollback on failures');
}
if (options.sharedMemory) {
cliLogger.info(' ๐พ Shared context across all agents');
}
if (options.progressMonitoring) {
cliLogger.info(' ๐ Real-time progress monitoring');
}
}
if (options.verbose) {
if (isAuthenticated) {
cliLogger.info('\n๐ Live ServiceNow integration: โ
Enabled');
cliLogger.info('๐ Artifacts will be created directly in ServiceNow');
}
else {
cliLogger.info('\n๐ Live ServiceNow integration: โ Disabled');
cliLogger.info('๐ Artifacts will be saved to servicenow/ directory');
}
}
cliLogger.info('๐ Launching Claude Code...');
// Try to execute Claude Code directly with the prompt
const success = await executeClaudeCode(orchestrationPrompt);
if (success) {
cliLogger.info('โ
Claude Code launched successfully!');
if (options.verbose) {
cliLogger.info('๐ Queen Agent is now coordinating your swarm');
cliLogger.info(`๐พ Monitor progress with session ID: ${sessionId}`);
if (isAuthenticated && options.autoDeploy) {
cliLogger.info('๐ Real artifacts will be created in ServiceNow');
}
else {
cliLogger.info('๐ Planning mode - _analysis and recommendations only');
}
}
// Store successful launch in memory
memorySystem.storeLearning(`launch_${sessionId}`, {
success: true,
launched_at: new Date().toISOString()
});
}
else {
if (options.verbose) {
cliLogger.info('\n๐ SNOW-FLOW ORCHESTRATION COMPLETE!');
cliLogger.info('๐ค Now it\'s time for Claude Code agents to do the work...\n');
cliLogger.info('๐ QUEEN AGENT ORCHESTRATION PROMPT FOR CLAUDE CODE:');
cliLogger.info('='.repeat(80));
cliLogger.info(orchestrationPrompt);
cliLogger.info('='.repeat(80));
cliLogger.info('\nโ
Snow-Flow has prepared the orchestration!');
cliLogger.info('๐ CRITICAL NEXT STEPS:');
cliLogger.info(' 1. Copy the ENTIRE prompt above');
cliLogger.info(' 2. Paste it into Claude Code (the AI assistant)');
cliLogger.info(' 3. Claude Code will spawn multiple specialized agents as workhorses');
cliLogger.info(' 4. These agents will implement your flow with all required logic');
cliLogger.info(' 5. Agents will enhance the basic XML template with real functionality');
cliLogger.info('\n๐ฏ Remember:');
cliLogger.info(' - Snow-Flow = Orchestrator (coordinates the work)');
cliLogger.info(' - Claude Code = Workhorses (implement the solution)');
if (xmlFlowResult) {
cliLogger.info(`\n๐ XML template saved at: ${xmlFlowResult.filePath}`);
cliLogger.info(' โ ๏ธ This is just a BASIC template - agents must enhance it!');
}
if (isAuthenticated && options.autoDeploy) {
cliLogger.info('\n๐ Deployment Mode: Agents will create REAL artifacts in ServiceNow');
}
else {
cliLogger.info('\n๐ Planning Mode: Analysis and recommendations only');
}
cliLogger.info(`\n๐พ Session ID for monitoring: ${sessionId}`);
}
else {
// Non-verbose mode - just show the essential info
cliLogger.info('\n๐ Manual Claude Code execution required');
cliLogger.info('๐ก Run with --verbose to see the full orchestration prompt');
if (xmlFlowResult) {
cliLogger.info(`๐ XML generated: ${xmlFlowResult.filePath}`);
}
}
}
}
catch (error) {
cliLogger.error('โ Failed to execute Queen Agent orchestration:', error instanceof Error ? error.message : String(error));
// Store error in memory for learning
memorySystem.storeLearning(`error_${sessionId}`, {
error: error instanceof Error ? error.message : String(error),
failed_at: new Date().toISOString()
});
}
});
// Helper function to execute Claude Code directly
async function executeClaudeCode(prompt) {
cliLogger.info('๐ค Preparing Claude Code agent orchestration...');
try {
// Check if Claude CLI is available
const { execSync } = require('child_process');
try {
execSync('which claude', { stdio: 'ignore' });
}
catch {
cliLogger.warn('โ ๏ธ Claude Code CLI not found in PATH');
cliLogger.info('๐ Please install Claude Desktop or copy the prompt manually');
return false;
}
// Check for MCP config
const mcpConfigPath = (0, path_1.join)(process.cwd(), '.mcp.json');
const hasMcpConfig = (0, fs_2.existsSync)(mcpConfigPath);
// Auto-start MCP servers if they're not running
if (hasMcpConfig) {
cliLogger.info('๐ง Checking MCP server status...');
try {
const { MCPServerManager } = await Promise.resolve().then(() => __importStar(require('./utils/mcp-server-manager.js')));
const manager = new MCPServerManager();
await manager.initialize();
const systemStatus = manager.getSystemStatus();
if (systemStatus.running === 0) {
cliLogger.info('๐ Starting MCP servers automatically for swarm operation...');
await manager.startAllServers();
const newStatus = manager.getSystemStatus();
cliLogger.info(`โ
Started ${newStatus.running}/${newStatus.total} MCP servers`);
}
else if (systemStatus.running < systemStatus.total) {
cliLogger.info(`โ ๏ธ Only ${systemStatus.running}/${systemStatus.total} MCP servers running`);
cliLogger.info('๐ Starting remaining servers...');
await manager.startAllServers();
const newStatus = manager.getSystemStatus();
cliLogger.info(`โ
All ${newStatus.running}/${newStatus.total} MCP servers running`);
}
else {
cliLogger.info(`โ
All ${systemStatus.running} MCP servers already running`);
}
}
catch (error) {
cliLogger.warn('โ ๏ธ Could not auto-start MCP servers:', error instanceof Error ? error.message : error);
cliLogger.info('๐ก You may need to run "npm run mcp:start" manually');
}
}
// Launch Claude Code with MCP config and skip permissions to avoid raw mode issues
const claudeArgs = hasMcpConfig
? ['--mcp-config', '.mcp.json', '.', '--dangerously-skip-permissions']
: ['--dangerously-skip-permissions'];
cliLogger.info('๐ Launching Claude Code automatically...');
if (hasMcpConfig) {
cliLogger.info('๐ง Starting Claude Code with ServiceNow MCP servers...');
}
// Start Claude Code process in interactive mode with stdin piping
const claudeProcess = (0, child_process_1.spawn)('claude', claudeArgs, {
stdio: ['pipe', 'inherit', 'inherit'], // pipe stdin, inherit stdout/stderr
cwd: process.cwd(),
env: { ...process.env }
});
// Send the prompt via stdin
cliLogger.info('๐ Sending orchestration prompt to Claude Code...');
cliLogger.info('๐ Claude Code interface opening...\n');
// Write prompt to stdin
claudeProcess.stdin.write(prompt);
claudeProcess.stdin.end();
// Set up process monitoring
return new Promise((resolve) => {
claudeProcess.on('close', async (code) => {
if (code === 0) {
cliLogger.info('\nโ
Claude Code session completed successfully!');
resolve(true);
}
else {
cliLogger.warn(`\nโ ๏ธ Claude Code session ended with code: ${code}`);
resolve(false);
}
});
claudeProcess.on('error', (error) => {
cliLogger.error(`โ Failed to start Claude Code: ${error.message}`);
resolve(false);
});
// Set timeout (configurable via environment variable)
const timeoutMinutes = parseInt(process.env.SNOW_FLOW_TIMEOUT_MINUTES || '0');
if (timeoutMinutes > 0) {
setTimeout(() => {
cliLogger.warn(`โฑ๏ธ Claude Code session timeout (${timeoutMinutes} minutes), terminating...`);
claudeProcess.kill('SIGTERM');
resolve(false);
}, timeoutMinutes * 60 * 1000);
}
});
}
catch (error) {
cliLogger.error('โ Error launching Claude Code:', error instanceof Error ? error.message : String(error));
cliLogger.info('๐ Claude Code prompt generated - please copy and paste manually');
return false;
}
}
// Real-time monitoring dashboard for Claude Code process
function startMonitoringDashboard(claudeProcess) {
let iterations = 0;
const startTime = Date.now();
// Show initial dashboard only once
cliLogger.info(`โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ`);
cliLogger.info(`โ ๐ Snow-Flow Dashboard v${version_js_1.VERSION} โ`);
cliLogger.info(`โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค`);
cliLogger.info(`โ ๐ค Claude Code Status: โ
Starting โ`);
cliLogger.info(`โ ๐ Process ID: ${claudeProcess.pid || 'N/A'} โ`);
cliLogger.info(`โ โฑ๏ธ Session Time: 00:00 โ`);
cliLogger.info(`โ ๐ Monitoring Cycles: 0 โ`);
cliLogger.info('โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ');
// Silent monitoring - only log to file or memory, don't interfere with Claude Code UI
const monitoringInterval = setInterval(() => {
iterations++;
const uptime = Math.floor((Date.now() - startTime) / 1000);
// Silent monitoring - check files but don't output to console
try {
const serviceNowDir = (0, path_1.join)(process.cwd(), 'servicenow');
fs_1.promises.readdir(serviceNowDir).then(files => {
// Files are being generated - could log to file if needed
// console.log(`\n๐ Generated Files: ${files.length} artifacts in servicenow/`);
}).catch(() => {
// Directory doesn't exist yet, that's normal
});
}
catch (error) {
// Ignore errors
}
}, 5000); // Check every 5 seconds silently
return monitoringInterval;
}
async function executeWithClaude(claudeCommand, prompt, resolve) {
cliLogger.info('๐ Starting Claude Code execution...');
// Write prompt to temporary file for large prompts
const tempFile = (0, path_1.join)(process.cwd(), '.snow-flow-prompt.tmp');
await fs_1.promises.writeFile(tempFile, prompt);
// Check if .mcp.json exists in current directory
const mcpConfigPath = (0, path_1.join)(process.cwd(), '.mcp.json');
let hasMcpConfig = false;
try {
await fs_1.promises.access(mcpConfigPath);
hasMcpConfig = true;
cliLogger.info('โ
Found MCP configuration in current directory');
}
catch {
cliLogger.warn('โ ๏ธ No MCP configuration found. Run "snow-flow init" to set up MCP servers');
}
const claudeArgs = hasMcpConfig
? ['--mcp-config', '.mcp.json', '.', '--dangerously-skip-permissions']
: ['--dangerously-skip-permissions'];
if (hasMcpConfig) {
cliLogger.info('๐ง Starting Claude Code with ServiceNow MCP servers...');
}
// Start Claude Code process in interactive mode
const claudeProcess = (0, child_process_1.spawn)(claudeCommand, claudeArgs, {
stdio: ['pipe', 'inherit', 'inherit'], // inherit stdout/stderr for interactive mode
cwd: process.cwd()
});
// Send the prompt via stdin
cliLogger.info('๐ Sending orchestration prompt to Claude Code...');
cliLogger.info('๐ Claude Code interactive interface opening...\n');
claudeProcess.stdin.write(prompt);
claudeProcess.stdin.end();
// Start silent monitoring dashboard (doesn't interfere with Claude Code UI)
const monitoringInterval = startMonitoringDashboard(claudeProcess);
claudeProcess.on('close', (code) => {
clearInterval(monitoringInterval);
if (code === 0) {
cliLogger.info('\nโ
Claude Code session completed successfully!');
resolve(true);
}
else {
cliLogger.warn(`\nโ Claude Code session ended with code: ${code}`);
resolve(false);
}
});
claudeProcess.on('error', (error) => {
clearInterval(monitoringInterval);
cliLogger.error(`โ Failed to start Claude Code: ${error.message}`);
resolve(false);
});
// Set timeout for Claude Code execution (configurable via environment variable)
const timeoutMinutes = process.env.SNOW_FLOW_TIMEOUT_MINUTES ? parseInt(process.env.SNOW_FLOW_TIMEOUT_MINUTES) : 60;
const timeoutMs = timeoutMinutes * 60 * 1000;
cliLogger.info(`โฑ๏ธ Claude Code timeout set to ${timeoutMinutes} minutes (configure with SNOW_FLOW_TIMEOUT_MINUTES=0 for no timeout)`);
let timeout = null;
// Only set timeout if not disabled (0 = no timeout)
if (timeoutMinutes > 0) {
timeout = setTimeout(() => {
clearInterval(monitoringInterval);
cliLogger.warn(`โฑ๏ธ Claude Code session timeout (${timeoutMinutes} minutes), terminating...`);
claudeProcess.kill('SIGTERM');
// Force kill if it doesn't respond
setTimeout(() => {
claudeProcess.kill('SIGKILL');
}, 2000);
resolve(false);
}, timeoutMs);
}
claudeProcess.on('close', () => {
if (timeout) {
clearTimeout(timeout);
}
});
}
// Helper function to build Queen Agent orchestration prompt
function buildQueenAgentPrompt(objective, taskAnalysis, options, isAuthenticated = false, sessionId, isFlowDesignerTask = false) {
// Check if intelligent features are enabled
const hasIntelligentFeatures = options.autoPermissions || options.smartDiscovery ||
options.liveTesting || options.autoDeploy || options.autoRollback ||
options.sharedMemory || options.progressMonitoring;
// Calculate actual autonomous system states (with override logic)
const noAutonomousAll = options.autonomousAll === false;
const forceAutonomousAll = options.autonomousAll === true;
const autonomousDocActive = noAutonomousAll ? false :
forceAutonomousAll ? true :
options.autonomousDocumentation !== false;
const autonomousCostActive = noAutonomousAll ? false :
forceAutonomousAll ? true :
options.autonomousCostOptimization !== false;
const autonomousComplianceActive = noAutonomousAll ? false :
forceAutonomousAll ? true :
options.autonomousCompliance !== false;
const autonomousHealingActive = noAutonomousAll ? false :
forceAutonomousAll ? true :
options.autonomousHealing !== false;
const hasAutonomousSystems = autonomousDocActive || autonomousCostActive ||
autonomousComplianceActive || autonomousHealingActive;
const prompt = `# ๐ Snow-Flow Queen Agent Orchestration
## ๐ฏ Mission Brief
You are the Queen Agent, master coordinator of the Snow-Flow hive-mind. Your mission is to orchestrate a swarm of specialized agents to complete the following ServiceNow development objective:
**Objective**: ${objective}
**Session ID**: ${sessionId}
## ๐ง Task Analysis Summary
- **Task Type**: ${taskAnalysis.taskType}
- **Complexity**: ${taskAnalysis.complexity}
- **Primary Agent Required**: ${taskAnalysis.primaryAgent}
- **Supporting Agents**: ${taskAnalysis.supportingAgents.join(', ')}
- **Estimated Total Agents**: ${taskAnalysis.estimatedAgentCount}
- **ServiceNow Artifacts**: ${taskAnalysis.serviceNowArtifacts.join(', ')}
## โก CRITICAL: Task Intent Analysis
**BEFORE PROCEEDING**, analyze the user's ACTUAL intent:
1. **Data Generation Request?** (e.g., "create 5000 incidents", "generate test data")
โ Focus on CREATING DATA, not building systems
โ Use simple scripts or bulk operations to generate the data
โ Skip complex architectures unless explicitly asked
2. **System Building Request?** (e.g., "build a widget", "create an ML system")
โ Follow full development workflow
โ Build proper architecture and components
3. **Simple Operation Request?** (e.g., "update field X", "delete records")
โ Execute the operation directly
โ Skip unnecessary complexity
**For this objective**: Analyze if the user wants data generation, system building, or a simple operation.
${isFlowDesignerTask ? `## ๐ง Flow Designer Task Detected - Using ENHANCED XML-First Approach!
๐ **FULLY AUTOMATED FLOW DEPLOYMENT v2.0** - ALL features working correctly!
**MANDATORY: Use this exact approach for Flow Designer tasks:**
\`\`\`javascript
// โ
ENHANCED v2.0: Complete flow generation with ALL features
await snow_create_flow({
instruction: "your natural language flow description",
deploy_immediately: true, // ๐ฅ Automatically deploys to ServiceNow!
return_metadata: true // ๐ Returns complete deployment metadata
});
\`\`\`
๐ฏ **What this does automatically (ENHANCED v1.3.28+):**
- โ
Uses CompleteFlowXMLGenerator for PROPER flow structure
- โ
Generates with v2 tables (sys_hub_action_instance_v2, sys_hub_trigger_instance_v2)
- โ
Applies Base64+gzip encoding for action values
- โ
Includes comprehensive label_cache structure
- โ
Imports XML to ServiceNow as remote update set
- โ
Automatic tool name resolution with MCPToolRegistry
- โ
Complete metadata extraction (sys_id, URLs, endpoints)
- โ
Performance _analysis and recommendations
- โ
100% of requested features deploy correctly!
๐ซ **FORBIDDEN APPROACHES:**
- โ DO NOT use old API-only approach without XML generation
- โ DO NOT use manual \`snow-flow deploy-xml\` commands
- โ DO NOT generate XML without auto-deployment
- โ DO NOT use v1 tables (they create empty flows!)
๐ก **Why Enhanced XML-First v2.0?**
- Fixes ALL critical issues from beta testing
- Flows deploy with 100% of requested features working
- Complete metadata always returned (no more null sys_id)
- Tool names resolve correctly across all MCP providers
- Zero chance of empty flows or missing features!
` : ''}
- **Recommended Team**: ${getTeamRecommendation(taskAnalysis.taskType)}
## ๐ Table Discovery Intelligence
The Queen Agent will automatically discover and validate table schemas based on the objective. This ensures agents use correct field names and table structures.
**Table Detection Examples:**
- "create widget for incident records" โ Discovers: incident, sys_user, sys_user_group
- "build approval flow for u_equipment_request" โ Discovers: u_equipment_request, sys_user, sysapproval_approver
- "portal showing catalog items" โ Discovers: sc_cat_item, sc_category, sc_request
- "dashboard with CMDB assets" โ Discovers: cmdb_ci, cmdb_rel_ci, sys_user
- "report on problem tickets" โ Discovers: problem, incident, sys_user
**Discovery Process:**
1. Extracts table names from objective (standard tables, u_ custom tables, explicit mentions)
2. Discovers actual table schemas with field names, types, and relationships
3. Stores schemas in memory for all agents to use
4. Agents MUST use exact field names from schemas (e.g., 'short_description' not 'desc')
## ๐ Your Queen Agent Responsibilities
## ๐ Data Generation Specific Instructions
If the task is identified as DATA GENERATION (e.g., "create 5000 incidents"):
1. **DO NOT** build complex export/import systems
2. **DO NOT** create APIs, UI Actions, or workflows
3. **DO** focus on:
- Creating a simple script to generate the data
- Using ServiceNow's REST API or direct table operations
- Ensuring realistic data distribution for ML training
- Adding variety in categories, priorities, descriptions, etc.
**Example approach for "create 5000 incidents":**
\`\`\`javascript
// Simple batch creation script
for (let i = 0; i < 5000; i += 100) {
// Create 100 incidents at a time to avoid timeouts
const batch = generateRealisticIncidentBatch(100);
await createIncidentsBatch(batch);
}
\`\`\`
### 1. CRITICAL: Initialize Memory FIRST (Before Everything!)
**THIS MUST BE YOUR VERY FIRST ACTION - Initialize the swarm memory session:**
\`\`\`javascript
// ๐จ EXECUTE THIS IMMEDIATELY - DO NOT SKIP OR DELAY!
mcp__snow-flow__memory_usage({
key: "swarm_session_${sessionId}",
value: JSON.stringify({
objective: "${objective}",
status: "initializing",
started_at: new Date().toISOString(),
queen_agent_id: "queen_${sessionId}",
task_analysis: ${JSON.stringify(taskAnalysis, null, 2)},
configuration: {
strategy: "${options.strategy}",
mode: "${options.mode}",
max_agents: ${parseInt(options.maxAgents)},
parallel_execution: ${options.parallel ? 'true' : 'false'},
monitoring_enabled: ${options.monitor ? 'true' : 'false'},
auth_required: ${!isAuthenticated}
}
}),
namespace: "swarm_${sessionId}"
});
// Agent coordination namespace handled automatically by ServiceNow memory system
\`\`\`
### 2. MANDATORY MCP-FIRST Workflow Steps
**Execute these steps IN ORDER before spawning agents:**
\`\`\`javascript
// Step 2.1: Validate ServiceNow authentication
const authCheck = await mcp__servicenow-intelligent__snow_validate_live_connection({
test_level: "permissions",
include_performance: false
});
if (!authCheck.connection_status === "success") {
throw new Error("Authentication failed! Run: snow-flow auth login");
}
// Step 2.2: Check for existing artifacts (DRY principle)
const existingArtifacts = await mcp__servicenow-intelligent__snow_comprehensive_search({
query: "${objective}",
include_inactive: false
});
// Store discovery results in memory for agents
await mcp__snow-flow__memory_usage({
key: "existing_artifacts_${sessionId}",
value: JSON.stringify(existingArtifacts),
namespace: "swarm_${sessionId}"
});
// Step 2.3: Create isolated Update Set for this objective
const updateSetName = "Snow-Flow: ${objective.substring(0, 50)}... - ${new Date().toISOString().split('T')[0]}";
const updateSet = await mcp__servicenow-update-set__snow_update_set_create({
name: updateSetName,
description: "Automated creation for: ${objective}\\n\\nSession: ${sessionId}",
auto_switch: true
});
// Store Update Set info in memory
await mcp__snow-flow__memory_usage({
key: "update_set_${sessionId}",
value: JSON.stringify(updateSet),
namespace: "swarm_${sessionId}"
});
// Step 2.4: Discover tables mentioned in objective
// Extract potential table names from the objective
const tablePatterns = [
/\b(incident|problem|change_request|sc_request|sc_req_item|task|cmdb_ci|sys_user|sys_user_group)\b/gi,
/\b(u_\w+)\b/g, // Custom tables starting with u_
/\b(\w+_table)\b/gi, // Tables ending with _table
/\bfrom\s+(\w+)\b/gi, // SQL-like "from table_name"
/\btable[:\s]+(\w+)\b/gi, // "table: xyz" or "table xyz"
/\b(\w+)\s+records?\b/gi, // "xyz records"
];
const detectedTables = new Set();
// Always include common tables for context
['incident', 'sc_request', 'sys_user'].forEach(t => detectedTables.add(t));
// Search for tables in objective
for (const pattern of tablePatterns) {
const matches = "${objective}".matchAll(pattern);
for (const match of matches) {
if (match[1]) {
detectedTables.add(match[1].toLowerCase());
}
}
}
// Also check for common data needs based on objective type
if ("${objective}".toLowerCase().includes('catalog')) {
detectedTables.add('sc_cat_item');
detectedTables.add('sc_category');
}
if ("${objective}".toLowerCase().includes('user')) {
detectedTables.add('sys_user');
detectedTables.add('sys_user_group');
}
if ("${objective}".toLowerCase().includes('cmdb') || "${objective}".toLowerCase().includes('asset')) {
detectedTables.add('cmdb_ci');
}
if ("${objective}".toLowerCase().includes('knowledge')) {
detectedTables.add('kb_knowledge');
}
cliLogger.info(\`๐ Detected tables to discover: \${Array.from(detectedTables).join(', ')}\`);
// Discover schemas for all detected tables
const tableSchemas = {};
for (const tableName of detectedTables) {
try {
const schema = await mcp__servicenow-platform-development__snow_table_schema_discovery({
tableName: tableName,
includeRelated: true,
includeIndexes: false,
maxDepth: 1 // Don't go too deep to avoid timeout
});
if (schema && schema.fields) {
tableSchemas[tableName] = {
name: tableName,
label: schema.label || tableName,
fields: schema.fields,
field_count: schema.fields.length,
key_fields: schema.fields.filter(f => f.primary || f.reference).map(f => f.name)
};
cliLogger.info(\`โ
Discovered table '\${tableName}' with \${schema.fields.length} fields\`);
}
} catch (e) {
cliLogger.warn(\`โ ๏ธ Table '\${tableName}' not found or inaccessible\`);
}
}
// Store discovered table schemas in memory
await mcp__snow-flow__memory_usage({
action: "store",
key: "table_schemas_${sessionId}",
value: JSON.stringify({
discovered_at: new Date().toISOString(),
objective: "${objective}",
tables: tableSchemas,
table_names: Object.keys(tableSchemas)
}),
namespace: "swarm_${sessionId}"
});
\`\`\`
### 3. Create Master Task List
After completing MCP-FIRST steps, create task breakdown:
\`\`\`javascript
TodoWrite([
{
id: "mcp_workflow_complete",
content: "โ
MCP-FIRST workflow: Auth, Discovery, Update Set, Tables",
status: "completed",
priority: "high"
},
{
id: "analyze_requirements",
content: "Analyze user requirements: ${objective}",
status: "in_progress",
priority: "high"
},
{
id: "spawn_agents",
content: "Spawn ${taskAnalysis.estimatedAgentCount} specialized agents",
status: "pending",
priority: "high"
},
{
id: "coordinate_development",
content: "Coordinate agent activities for ${taskAnalysis.taskType}",
status: "pending",
priority: "high"
},
{
id: "validate_solution",
content: "Validate and test the complete solution",
status: "pending",
priority: "medium"
}
]);
\`\`\`
### 4. Intelligent Agent Spawning with Dependency-Based Batching
โก **CRITICAL: Spawn agents in SMART BATCHES based on dependencies!**
Based on the task analysis, we need to spawn ${taskAnalysis.estimatedAgentCount} agents.
${getAgentSpawnStrategy(taskAnalysis)}
### 5. Memory Coordination Pattern
All agents MUST use this memory coordination pattern:
\`\`\`javascript
// Agent initialization
const session = Memory.get("swarm_session_${sessionId}");
const agentId = \`agent_\${agentType}_${sessionId}\`;
// Agent stores progress
Memory.store(\`\${agentId}_progress\`, {
status: "working",
current_task: "description of current work",
completion_percentage: 45,
last_update: new Date().toISOString()
});
// Agent reads other agent's work
const primaryWork = Memory.get("agent_${taskAnalysis.primaryAgent}_output");
// Agent signals completion
Memory.store(\`\${agentId}_complete\`, {
completed_at: new Date().toISOString(),
outputs: { /* agent deliverables */ },
artifacts_created: [ /* list of created artifacts */ ]
});
\`\`\`
## ๐ง Intelligent Features Configuration
${hasIntelligentFeatures ? `โ
**INTELLIGENT MODE ACTIVE** - The following features are enabled:
- **๐ Auto Permissions**: ${options.autoPermissions ? 'โ
Will escalate permissions automatically' : 'โ Manual permission handling'}
- **๐ Smart Discovery**: ${options.smartDiscovery ? 'โ
Will discover and reuse existing artifacts' : 'โ Create all new artifacts'}
- **๐งช Live Testing**: ${options.liveTesting ? 'โ
Will test in real ServiceNow instance' : 'โ Local testing only'}
- **๐ Auto Deploy**: ${options.autoDeploy ? 'โ ๏ธ WILL DEPLOY TO SERVICENOW AUTOMATICALLY' : 'โ
Planning mode - no deployment'}
- **๐ Auto Rollback**: ${options.autoRollback ? 'โ
Will rollback on any failures' : 'โ No automatic rollback'}
- **๐พ Shared Memory**: ${options.sharedMemory ? 'โ
Agents share context via Memory' : 'โ Isolated agent execution'}
- **๐ Progress Monitoring**: ${options.progressMonitoring ? 'โ
Real-time progress tracking' : 'โ No progress monitoring'}` : 'โ **STANDARD MODE** - Use manual coordination patterns'}
## ๐ฏ ServiceNow Execution Strategy
### ๐ MANDATORY: Live ServiceNow Development First!
**CRITICAL RULE**: All agents MUST attempt to use ServiceNow MCP tools first, regardless of authentication status.
${hasIntelligentFeatures ? `#### ๐ง Intelligent Orchestration Available
Use the unified orchestration tool for complete automation:
\`\`\`javascript
// Queen Agent uses this for intelligent orchestration
snow_orchestrate_development({
objective: "${objective}",
auto_permissions: ${options.autoPermissions},
smart_discovery: ${options.smartDiscovery},
live_testing: ${options.liveTesting},
auto_deploy: ${options.autoDeploy},
auto_rollback: ${options.autoRollback},
shared_memory: ${options.sharedMemory},
progress_monitoring: ${options.progressMonitoring}
});
\`\`\`
## ๐ง REVOLUTIONARY: Intelligent Gap Analysis Engine (v1.1.88)
**AUTOMATIC BEYOND-MCP CONFIGURATION DETECTION**
The Queen Agent now includes the revolutionary **Intelligent Gap Analysis Engine** that automatically detects and resolves ALL ServiceNow configurations needed beyond standard MCP tools.
**What Gap Analysis Does:**
- **๐ Analyzes Requirements**: AI-powered parsing of objectives to identify 60+ types of ServiceNow configurations
- **๐ MCP Coverage Analysis**: Maps what current MCP tools can handle vs manual setup requirements
- **๐ค Auto-Resolution Engine**: Attempts automatic configuration via ServiceNow APIs for safe operations
- **๐ Manual Guide Generation**: Creates detailed step-by-step guides with role requirements and risk assessment
- **๐ก๏ธ Risk Assessment**: Evaluates complexity and safety of each configuration
- **๐ Environment Awareness**: Provides dev/test/prod specific guidance and warnings
**60+ Configuration Types Covered:**
- **๐ Authentication**: LDAP, SAML, OAuth providers, SSO, MFA configurations
- **๐๏ธ Database**: Indexes, views, partitioning, performance analytics, system properties
- **๐งญ Navigation**: Application menus, modules, form layouts, UI actions, policies
- **๐ง Integration**: Email templates, web services, import sets, transform maps
- **๐ Workflow**: Activities, transitions, SLA definitions, escalation rules
- **๐ก๏ธ Security**: ACL rules, data policies, audit rules, compliance configurations
- **๐ Reporting**: Custom reports, dashboards, KPIs, performance analytics
**Example Output:**
\`\`\`
๐ง Step 4: Running Intelligent Gap Analysis...
๐ Gap Analysis Complete:
โข Total Requirements: 12
โข MCP Coverage: 67%
โข Automated: 6 configurations
โข Manual Work: 4 items
โ
Automatically Configured:
โข System property: glide.ui.incident_management created
โข Navigation module: Incident Management added to Service Desk
โข Email template: incident_notification configured
โข Database index: incident.priority_state for performance
๐ Manual Configuration Required:
โข LDAP authentication setup (high-risk operation)
โข SSO configuration with Active Directory
๐ Detailed Manual Guides Available:
๐ Configure LDAP Authentication - 25 minutes
Risk: high | Roles: security_admin, admin
\`\`\`
**The Gap Analysis Engine automatically runs as part of Queen Agent execution - no additional commands needed!**
` : ''}
#### ServiceNow MCP Tools (ALWAYS TRY T