feat: Brain Cloud integration with MCP server and CLI commands

- Add brainy connect command for one-click Brain Cloud setup
- Create MCP server for AI memory persistence
- Add cloud management commands (export, status, dashboard)
- Automatic customer ID detection and configuration
- Natural language instructions for AI assistants
- Support for multi-agent coordination
- Complete Brain Cloud integration for solving AI Amnesia
This commit is contained in:
David Snelling 2025-08-09 18:27:21 -07:00
parent 4594b20450
commit 90baeeb4a3
6 changed files with 1065 additions and 5 deletions

View file

@ -14,6 +14,9 @@ import { readFileSync } from 'fs'
import { dirname, join } from 'path'
import { fileURLToPath } from 'url'
// Import fetch for API calls
import fetch from 'node-fetch'
const __dirname = dirname(fileURLToPath(import.meta.url))
const packageJson = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf8'))
@ -177,10 +180,51 @@ program
// BRAIN CLOUD INTEGRATION
// ========================================
program
.command('connect')
.description('🔗 Connect me to your Brain Cloud so I remember everything')
.action(wrapInteractive(async () => {
console.log(chalk.cyan('\n🧠 Setting Up AI Memory...'))
console.log(chalk.gray('━'.repeat(50)))
try {
// Detect customer ID
const customerId = await detectCustomerId()
if (customerId) {
console.log(chalk.green(`✅ Found your Brain Cloud: ${customerId}`))
console.log('\n🔧 I can set up AI memory so I remember our conversations:')
console.log(chalk.yellow(' • Update Claude configuration'))
console.log(chalk.yellow(' • Add memory instructions'))
console.log(chalk.yellow(' • Enable cross-session memory'))
// For now, auto-proceed (in a real CLI environment, user could be prompted)
console.log(chalk.cyan('\n🚀 Setting up AI memory...'))
const proceed = true
if (proceed) {
await setupBrainCloudMemory(customerId)
console.log(chalk.green('\n🎉 AI Memory Connected!'))
console.log(chalk.cyan('Restart Claude Code and I\'ll remember everything!'))
}
} else {
console.log(chalk.yellow('🤔 No Brain Cloud found. Let me help you set one up:'))
console.log('\n1. Visit: ' + chalk.cyan('https://app.soulcraftlabs.com'))
console.log('2. Sign up for Brain Cloud ($19/month)')
console.log('3. Run ' + chalk.green('brainy connect') + ' again')
}
} catch (error) {
console.log(chalk.red('❌ Setup failed:'), error.message)
}
}))
program
.command('cloud [action]')
.description('☁️ Connect to Brain Cloud - AI memory that never forgets')
.option('--connect <id>', 'Connect to existing Brain Cloud instance')
.option('--export <id>', 'Export all data from Brain Cloud instance')
.option('--status <id>', 'Check status of Brain Cloud instance')
.option('--dashboard <id>', 'Open dashboard for Brain Cloud instance')
.option('--migrate', 'Migrate between local and cloud')
.action(wrapInteractive(async (action, options) => {
// For now, show connection instructions
@ -189,8 +233,118 @@ program
if (options.connect) {
console.log(chalk.green(`✅ Connecting to Brain Cloud instance: ${options.connect}`))
console.log(chalk.yellow('\nNote: Full cloud integration coming soon!'))
console.log('\nFor now, visit: ' + chalk.cyan('https://app.soulcraftlabs.com'))
try {
// Test connection to Brain Cloud worker
const healthUrl = `https://brain-cloud.dpsifr.workers.dev/health`
const response = await fetch(healthUrl, {
headers: { 'x-customer-id': options.connect }
})
if (response.ok) {
const data = await response.json()
console.log(chalk.green(`🧠 ${data.status}`))
console.log(chalk.cyan(`💫 Instance: ${data.customerId}`))
console.log(chalk.gray(`⏰ Connected at: ${new Date(data.timestamp).toLocaleString()}`))
// Test memories endpoint
const memoriesResponse = await fetch(`https://brain-cloud.dpsifr.workers.dev/memories`, {
headers: { 'x-customer-id': options.connect }
})
if (memoriesResponse.ok) {
const memoriesData = await memoriesResponse.json()
console.log(chalk.yellow(`\n${memoriesData.message}`))
console.log(chalk.gray('📊 Your atomic memories:'))
memoriesData.memories.forEach(memory => {
const time = new Date(memory.created).toLocaleString()
console.log(chalk.gray(`${memory.content} (${time})`))
})
}
} else {
console.log(chalk.red('❌ Could not connect to Brain Cloud'))
console.log(chalk.yellow('💡 Make sure you have an active instance'))
console.log('\nSign up at: ' + chalk.cyan('https://app.soulcraftlabs.com'))
}
} catch (error) {
console.log(chalk.red('❌ Connection failed:'), error.message)
console.log('\nSign up at: ' + chalk.cyan('https://app.soulcraftlabs.com'))
}
} else if (options.export) {
console.log(chalk.green(`📦 Exporting data from Brain Cloud instance: ${options.export}`))
try {
const response = await fetch(`https://brain-cloud.dpsifr.workers.dev/export`, {
headers: { 'x-customer-id': options.export }
})
if (response.ok) {
const data = await response.json()
const filename = `brainy-export-${options.export}-${Date.now()}.json`
// Write to file
const fs = await import('fs/promises')
await fs.writeFile(filename, JSON.stringify(data, null, 2))
console.log(chalk.green(`✅ Data exported to: ${filename}`))
console.log(chalk.gray(`📊 Exported ${data.memories?.length || 0} memories`))
} else {
console.log(chalk.red('❌ Export failed - instance not found'))
}
} catch (error) {
console.log(chalk.red('❌ Export error:'), error.message)
}
} else if (options.status) {
console.log(chalk.green(`🔍 Checking status of Brain Cloud instance: ${options.status}`))
try {
const response = await fetch(`https://brain-cloud.dpsifr.workers.dev/health`, {
headers: { 'x-customer-id': options.status }
})
if (response.ok) {
const data = await response.json()
console.log(chalk.green(`✅ Instance Status: Active`))
console.log(chalk.cyan(`🧠 ${data.status}`))
console.log(chalk.gray(`⏰ Last check: ${new Date(data.timestamp).toLocaleString()}`))
// Get memory count
const memoriesResponse = await fetch(`https://brain-cloud.dpsifr.workers.dev/memories`, {
headers: { 'x-customer-id': options.status }
})
if (memoriesResponse.ok) {
const memoriesData = await memoriesResponse.json()
console.log(chalk.yellow(`📊 Total memories: ${memoriesData.count}`))
}
} else {
console.log(chalk.red('❌ Instance not found or inactive'))
}
} catch (error) {
console.log(chalk.red('❌ Status check failed:'), error.message)
}
} else if (options.dashboard) {
console.log(chalk.green(`🌐 Opening dashboard for Brain Cloud instance: ${options.dashboard}`))
const dashboardUrl = `https://app.soulcraftlabs.com/dashboard.html?customer_id=${options.dashboard}`
console.log(chalk.cyan(`\n🔗 Dashboard URL: ${dashboardUrl}`))
console.log(chalk.gray('Opening in your default browser...'))
try {
const { exec } = await import('child_process')
const { promisify } = await import('util')
const execAsync = promisify(exec)
// Cross-platform browser opening
const command = process.platform === 'win32' ? 'start' :
process.platform === 'darwin' ? 'open' : 'xdg-open'
await execAsync(`${command} "${dashboardUrl}"`)
console.log(chalk.green('✅ Dashboard opened!'))
} catch (error) {
console.log(chalk.yellow('💡 Copy the URL above to open in your browser'))
}
} else {
console.log(chalk.yellow('📡 Brain Cloud Setup'))
console.log('\n1. Sign up at: ' + chalk.cyan('https://app.soulcraftlabs.com'))
@ -460,4 +614,131 @@ if (!process.argv.slice(2).length) {
console.log(' brainy brain-jar dashboard # View dashboard')
console.log('')
program.outputHelp()
}
// ========================================
// BRAIN CLOUD MEMORY SETUP FUNCTIONS
// ========================================
async function detectCustomerId() {
try {
// Method 1: Check for existing brainy config
const { readFile } = await import('fs/promises')
const { join } = await import('path')
try {
const configPath = join(process.cwd(), 'brainy-config.json')
const config = JSON.parse(await readFile(configPath, 'utf8'))
if (config.brainCloudCustomerId) {
return config.brainCloudCustomerId
}
} catch {}
// Method 2: Check CLAUDE.md for existing customer ID
try {
const claudePath = join(process.cwd(), 'CLAUDE.md')
const claudeContent = await readFile(claudePath, 'utf8')
const match = claudeContent.match(/customer.*?([a-z0-9-]+)/i)
if (match) return match[1]
} catch {}
// Method 3: Test common demo IDs
const testIds = ['demo-test-auto', 'demo-test123']
for (const id of testIds) {
try {
const response = await fetch(`https://brain-cloud.dpsifr.workers.dev/health`, {
headers: { 'x-customer-id': id }
})
if (response.ok) {
return id
}
} catch {}
}
return null
} catch (error) {
return null
}
}
async function setupBrainCloudMemory(customerId) {
const { writeFile, mkdir } = await import('fs/promises')
const { join } = await import('path')
console.log(chalk.gray('📝 Setting up AI memory configuration...'))
// 1. Create/update .claude directory and MCP config
try {
await mkdir('.claude', { recursive: true })
const mcpConfig = {
mcpServers: {
"brain-cloud": {
command: "node",
args: ["brainy-mcp-server.js"],
env: {
CUSTOMER_ID: customerId,
BRAIN_CLOUD_URL: "https://brain-cloud.dpsifr.workers.dev"
}
}
}
}
await writeFile('.claude/mcp_servers.json', JSON.stringify(mcpConfig, null, 2))
console.log(chalk.green('✅ MCP configuration updated'))
} catch (error) {
console.log(chalk.yellow('⚠️ Could not update MCP config:', error.message))
}
// 2. Create/update CLAUDE.md with natural language instructions
const claudeContent = `# 🧠 I Remember Everything Now!
Hi! I'm connected to your Brain Cloud (${customerId}) so I actually remember our conversations across sessions.
## Try Saying:
- "What did we build together?"
- "Remember that React project?"
- "Show me what we worked on yesterday"
- "Find my notes about APIs"
- "Search for that bug we fixed"
## I Can Also:
- Remember context from weeks ago
- Work with other AI assistants who share the same memory
- Keep everything synced across your devices
- Search through all our conversations
## Multi-AI Coordination:
When working with multiple AI assistants, we automatically coordinate:
- **Jarvis** (Backend): APIs, databases, deployment
- **Picasso** (Design): UI, themes, visual elements
- **Claude** (Planning): Coordination, architecture, strategy
**Just talk to me normally - no commands needed!**
---
*Brain Cloud Instance: ${customerId}*
*Last Updated: ${new Date().toLocaleDateString()}*
`
try {
await writeFile('CLAUDE.md', claudeContent)
console.log(chalk.green('✅ CLAUDE.md updated with memory instructions'))
} catch (error) {
console.log(chalk.yellow('⚠️ Could not update CLAUDE.md:', error.message))
}
// 3. Save customer ID to brainy config
try {
const brainyConfig = {
brainCloudCustomerId: customerId,
brainCloudUrl: 'https://brain-cloud.dpsifr.workers.dev',
lastConnected: new Date().toISOString()
}
await writeFile('brainy-config.json', JSON.stringify(brainyConfig, null, 2))
console.log(chalk.green('✅ Brainy configuration saved'))
} catch (error) {
console.log(chalk.yellow('⚠️ Could not save brainy config:', error.message))
}
}