sam-coder-cli
Version:
SAM-CODER: An animated command-line AI assistant with agency capabilities.
1,469 lines (1,251 loc) • 50.7 kB
JavaScript
const chalk = require('chalk');
const { exec } = require('child_process');
const os = require('os');
// ANSI escape codes for advanced effects
const ANSI = {
clear: '\x1Bc',
hideCursor: '\x1B[?25l',
showCursor: '\x1B[?25h',
moveTo: (x, y) => `\x1B[${y};${x}H`,
clearLine: '\x1B[2K',
clearScreen: '\x1B[2J\x1B[0;0H',
reset: '\x1B[0m',
bold: '\x1B[1m',
dim: '\x1B[2m',
italic: '\x1B[3m',
underline: '\x1B[4m',
blink: '\x1B[5m',
reverse: '\x1B[7m',
strikethrough: '\x1B[9m',
saveCursor: '\x1B[s',
restoreCursor: '\x1B[u'
};
// Music/Sound generation using system beeps and terminal bells
class SoundGenerator {
constructor() {
this.isWindows = os.platform() === 'win32';
this.isMac = os.platform() === 'darwin';
this.isLinux = os.platform() === 'linux';
this.soundEnabled = true;
}
async playBeep(frequency = 440, duration = 100) {
if (!this.soundEnabled) return;
try {
return new Promise((resolve) => {
if (this.isWindows) {
exec(`powershell -c "[console]::beep(${frequency},${duration})"`, { stdio: 'ignore' }, () => resolve());
} else if (this.isMac) {
exec(`osascript -e 'beep'`, { stdio: 'ignore' }, () => resolve());
} else if (this.isLinux) {
exec(`beep -f ${frequency} -l ${duration} 2>/dev/null || echo -e '\\a'`, { stdio: 'ignore' }, () => resolve());
} else {
process.stdout.write('\x07');
resolve();
}
// Fallback timeout
setTimeout(resolve, duration + 50);
});
} catch (error) {
// Silently fail for sound issues
this.soundEnabled = false;
}
}
async playSequence(notes) {
for (const note of notes) {
await this.playBeep(note.freq, note.duration);
await sleep(note.pause || 50);
}
}
async playStartupSound() {
const notes = [
{ freq: 261, duration: 100 }, // C
{ freq: 329, duration: 100 }, // E
{ freq: 392, duration: 100 }, // G
{ freq: 523, duration: 200 }, // C (octave up)
];
await this.playSequence(notes);
}
async playGlitchSound() {
for (let i = 0; i < 5; i++) {
await this.playBeep(Math.random() * 800 + 200, 30);
await sleep(20);
}
}
async playAwakeningSound() {
const notes = [
{ freq: 130, duration: 300 }, // Low C
{ freq: 196, duration: 200 }, // G
{ freq: 261, duration: 200 }, // C
{ freq: 392, duration: 200 }, // G
{ freq: 523, duration: 400 }, // High C
];
await this.playSequence(notes);
}
// New sound effects
async playDNASound() {
const notes = [
{ freq: 330, duration: 80 }, // E
{ freq: 392, duration: 80 }, // G
{ freq: 494, duration: 80 }, // B
{ freq: 587, duration: 80 }, // D
{ freq: 659, duration: 80 }, // E (octave up)
];
await this.playSequence(notes);
}
async playCircuitSound() {
// Electronic beeping pattern
for (let i = 0; i < 3; i++) {
await this.playBeep(880, 50);
await sleep(50);
await this.playBeep(440, 50);
await sleep(100);
}
}
async playConsciousnessSound() {
// Ascending harmonics
const baseFreq = 220;
for (let harmonic = 1; harmonic <= 5; harmonic++) {
await this.playBeep(baseFreq * harmonic, 150);
await sleep(30);
}
}
async playGalaxySound() {
// Deep space ambience
const notes = [
{ freq: 55, duration: 500 }, // Low A
{ freq: 82, duration: 400 }, // Low E
{ freq: 110, duration: 300 }, // A
{ freq: 165, duration: 200 }, // E
];
await this.playSequence(notes);
}
async playCompilationSound() {
// Rapid typing/compilation sounds
for (let i = 0; i < 8; i++) {
await this.playBeep(1000 + Math.random() * 500, 20);
await sleep(30);
}
}
async playFinalSound() {
// Epic finale
const notes = [
{ freq: 261, duration: 200 }, // C
{ freq: 329, duration: 200 }, // E
{ freq: 392, duration: 200 }, // G
{ freq: 523, duration: 300 }, // C (octave up)
{ freq: 659, duration: 300 }, // E
{ freq: 784, duration: 400 }, // G
{ freq: 1047, duration: 600 }, // C (2 octaves up)
];
await this.playSequence(notes);
}
}
const sound = new SoundGenerator();
// Utility functions
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function clearScreen() {
// Use more reliable screen clearing
process.stdout.write(ANSI.clearScreen);
}
function getTerminalSize() {
// Ensure we always have valid numeric values
const width = Number(process.stdout.columns) || 80;
const height = Number(process.stdout.rows) || 24;
return {
width: Math.max(width, 40), // Minimum width of 40
height: Math.max(height, 10) // Minimum height of 10
};
}
function centerText(text, width = getTerminalSize().width) {
if (!text || typeof text !== 'string') return '';
// Ensure width is a valid number
const safeWidth = Number(width) || 80;
const lines = text.split('\n');
return lines.map(line => {
if (!line) return line; // Handle empty lines
// Strip ANSI codes to calculate actual text length
const cleanLine = line.replace(/\x1b\[[0-9;]*m/g, '');
const lineLength = cleanLine.length || 0;
const padding = Math.max(0, Math.floor((safeWidth - lineLength) / 2));
return ' '.repeat(padding) + line;
}).join('\n');
}
function safeWrite(content) {
try {
process.stdout.write(content);
} catch (error) {
// Fallback for terminal issues
console.log(content);
}
}
function safeRepeat(str, count) {
// Ensure count is a valid positive integer
const safeCount = Math.max(0, Math.floor(Number(count) || 0));
return str.repeat(safeCount);
}
// Frame interpolation system
class FrameInterpolator {
constructor() {
this.fps = 30;
this.frameDuration = 1000 / this.fps; // ~33ms per frame for smoother animation
}
// Interpolate between two ASCII art frames
interpolateFrames(frame1, frame2, steps = 10) {
const frames = [frame1];
for (let i = 1; i < steps; i++) {
const ratio = i / steps;
const interpolated = this.interpolateText(frame1, frame2, ratio);
frames.push(interpolated);
}
frames.push(frame2);
return frames;
}
// Interpolate between two text blocks
interpolateText(text1, text2, ratio) {
const lines1 = text1.split('\n');
const lines2 = text2.split('\n');
const maxLines = Math.max(lines1.length, lines2.length);
const result = [];
for (let i = 0; i < maxLines; i++) {
const line1 = lines1[i] || '';
const line2 = lines2[i] || '';
const interpolated = this.interpolateLine(line1, line2, ratio);
result.push(interpolated);
}
return result.join('\n');
}
// Interpolate between two lines character by character
interpolateLine(line1, line2, ratio) {
const maxLen = Math.max(line1.length, line2.length);
let result = '';
for (let i = 0; i < maxLen; i++) {
const char1 = line1[i] || ' ';
const char2 = line2[i] || ' ';
if (Math.random() < ratio) {
result += char2;
} else {
result += char1;
}
}
return result;
}
// Create fade effect frames
fadeFrames(frame, fadeIn = true, steps = 10) {
const frames = [];
const chars = frame.split('');
for (let i = 0; i <= steps; i++) {
const ratio = fadeIn ? i / steps : 1 - (i / steps);
const visibleChars = Math.floor(chars.length * ratio);
let fadedFrame = '';
for (let j = 0; j < chars.length; j++) {
if (j < visibleChars && chars[j] !== ' ' && chars[j] !== '\n') {
fadedFrame += chars[j];
} else if (chars[j] === '\n') {
fadedFrame += '\n';
} else {
fadedFrame += ' ';
}
}
frames.push(fadedFrame);
}
return fadeIn ? frames : frames.reverse();
}
// Create expansion effect
expandFrames(centerChar, finalFrame, steps = 15) {
const frames = [];
const lines = finalFrame.split('\n');
const centerY = Math.floor(lines.length / 2);
const centerX = Math.floor((lines[centerY] || '').length / 2);
for (let step = 0; step <= steps; step++) {
const radius = (step / steps) * Math.max(centerY, centerX);
let frame = '';
for (let y = 0; y < lines.length; y++) {
let line = '';
for (let x = 0; x < lines[y].length; x++) {
const distance = Math.sqrt(Math.pow(x - centerX, 2) + Math.pow(y - centerY, 2));
if (distance <= radius) {
line += lines[y][x];
} else {
line += ' ';
}
}
frame += line + '\n';
}
frames.push(frame);
}
return frames;
}
}
const interpolator = new FrameInterpolator();
// Animation sequence with 30 FPS
async function runAGIAnimation() {
const { width, height } = getTerminalSize();
process.stdout.write(ANSI.hideCursor);
try {
const startTime = Date.now();
let frameCount = 0;
const frameTime = interpolator.frameDuration;
// Start with ambient sound (non-blocking)
sound.playStartupSound().catch(() => {}); // Ignore sound errors
// PHASE 1: The Void (1 second - 30 frames)
const voidFrames = [];
for (let i = 0; i < 30; i++) {
const dotCount = (i % 4) + 1;
const dots = '•'.repeat(dotCount) + ' '.repeat(4 - dotCount);
const frame = safeRepeat('\n', Math.floor(height / 2) - 2) +
centerText(dots) +
safeRepeat('\n', Math.floor(height / 2) - 2);
voidFrames.push(frame);
}
for (const frame of voidFrames) {
clearScreen();
safeWrite(chalk.dim.gray(frame));
await sleep(frameTime);
frameCount++;
}
// PHASE 2: Spark Formation (1 second - 30 frames)
const sparkFrames = [];
for (let i = 0; i < 30; i++) {
const progress = i / 29;
const intensity = Math.sin(progress * Math.PI * 2) * 0.5 + 0.5;
let sparkPattern;
if (progress < 0.3) {
sparkPattern = '·';
} else if (progress < 0.6) {
sparkPattern = ` ·\n ·•·\n ·`;
} else {
const core = intensity > 0.7 ? '█' : '●';
sparkPattern = ` · · ·\n· ·${core}· ·\n · · ·`;
}
const frame = safeRepeat('\n', Math.floor(height / 2) - 3) +
centerText(sparkPattern) +
safeRepeat('\n', Math.floor(height / 2) - 3);
sparkFrames.push(frame);
}
for (const frame of sparkFrames) {
clearScreen();
safeWrite(chalk.whiteBright(frame));
await sleep(frameTime);
frameCount++;
}
// PHASE 3: Quantum Expansion (1.5 seconds - 45 frames)
const quantumFrames = [];
const quantumChars = ['◆', '◇', '▪', '▫', '●', '○', '◊', '◉'];
// Add transition from spark to quantum
const sparkToQuantumTransition = interpolator.fadeFrames(sparkFrames[sparkFrames.length - 1], false, 5);
for (const frame of sparkToQuantumTransition) {
clearScreen();
safeWrite(chalk.whiteBright(frame));
await sleep(frameTime);
frameCount++;
}
for (let i = 0; i < 45; i++) {
const progress = i / 44;
const phase = progress * Math.PI * 4;
const baseSize = 2 + progress * 4;
const pulseSize = baseSize + Math.sin(phase * 2) * 1.5;
let frame = safeRepeat('\n', Math.floor(height / 2) - Math.floor(pulseSize) - 2);
for (let y = -Math.floor(pulseSize); y <= Math.floor(pulseSize); y++) {
let line = '';
for (let x = -Math.floor(pulseSize * 1.5); x <= Math.floor(pulseSize * 1.5); x++) {
const dist = Math.sqrt(x * x + y * y);
const normalizedDist = dist / pulseSize;
if (normalizedDist <= 1) {
// Use consistent pattern based on position and time
const charIndex = (Math.floor(x + y + i * 0.5)) % quantumChars.length;
const char = quantumChars[Math.abs(charIndex)];
// Add wave effect
const wave = Math.sin(dist * 0.5 + phase) * 0.5 + 0.5;
if (wave > 0.3) {
line += char;
} else {
line += '·';
}
} else {
line += ' ';
}
}
frame += centerText(line) + '\n';
}
quantumFrames.push(frame);
}
for (let i = 0; i < quantumFrames.length; i++) {
clearScreen();
const colorCycle = i / 15; // Slower color cycling
let color;
if (colorCycle < 1) {
color = chalk.blue;
} else if (colorCycle < 2) {
color = chalk.cyan;
} else {
color = chalk.magenta;
}
safeWrite(color(quantumFrames[i]));
await sleep(frameTime);
frameCount++;
}
// PHASE 4: Neural Network Formation (1.5 seconds - 45 frames)
const neuralFrames = [];
const nodes = 6;
const layers = 4;
// Play glitch sound (non-blocking)
sound.playGlitchSound().catch(() => {});
for (let i = 0; i < 45; i++) {
const progress = i / 44;
let frame = safeRepeat('\n', Math.floor(height / 2) - layers * 2);
for (let layer = 0; layer < layers; layer++) {
let line = '';
const layerProgress = Math.max(0, (progress - layer * 0.2) * 2);
for (let node = 0; node < nodes; node++) {
const nodeProgress = Math.max(0, (layerProgress - node * 0.1) * 3);
if (nodeProgress > 0.5) {
// Animate node activation
const activation = Math.sin(i * 0.3 + layer + node) * 0.5 + 0.5;
if (activation > 0.7) {
line += chalk.cyanBright('◉');
} else if (activation > 0.3) {
line += chalk.cyan('◯');
} else {
line += chalk.dim('○');
}
} else {
line += '·';
}
if (node < nodes - 1) {
// Animate connections
const connProgress = Math.max(0, (layerProgress - (node + 0.5) * 0.1) * 3);
if (connProgress > 0.5) {
const pulse = Math.sin(i * 0.4 + layer + node) > 0;
line += pulse ? chalk.cyan('━━') : chalk.dim('──');
} else {
line += ' ';
}
}
}
frame += centerText(line) + '\n';
if (layer < layers - 1) {
// Vertical connection lines
let connLine = '';
for (let node = 0; node < nodes; node++) {
const nodeProgress = Math.max(0, (layerProgress - node * 0.1) * 3);
if (nodeProgress > 0.5) {
const pulse = Math.sin(i * 0.2 + layer + node) > 0;
connLine += pulse ? chalk.cyan('┃') : chalk.dim('│');
} else {
connLine += ' ';
}
if (node < nodes - 1) connLine += ' ';
}
frame += centerText(connLine) + '\n';
}
}
neuralFrames.push(frame);
}
for (const frame of neuralFrames) {
clearScreen();
safeWrite(frame);
await sleep(frameTime);
frameCount++;
}
// Transition from Neural Network to Data Stream
const neuralToDataTransition = interpolator.fadeFrames(neuralFrames[neuralFrames.length - 1], false, 5);
for (const frame of neuralToDataTransition) {
clearScreen();
safeWrite(frame);
await sleep(frameTime);
frameCount++;
}
// PHASE 5: Data Stream (1 second - 30 frames)
const dataFrames = [];
const streamHeight = Math.min(12, Math.floor(height * 0.4));
const streamWidth = Math.min(60, Math.floor(width * 0.7));
for (let i = 0; i < 30; i++) {
let frame = safeRepeat('\n', Math.floor((height - streamHeight) / 2));
for (let y = 0; y < streamHeight; y++) {
let line = '';
for (let x = 0; x < streamWidth; x++) {
// Create flowing data pattern
const wave1 = Math.sin((x + i * 2) * 0.1) * 0.5 + 0.5;
const wave2 = Math.cos((y + i * 1.5) * 0.15) * 0.5 + 0.5;
const combined = wave1 * wave2;
if (combined > 0.7) {
// Binary data
const bit = ((x + y + i) % 7) < 3 ? '1' : '0';
line += chalk.greenBright(bit);
} else if (combined > 0.4) {
// Block characters
const blocks = ['█', '▓', '▒', '░'];
const blockIndex = ((x + y + i) % blocks.length);
line += chalk.green(blocks[blockIndex]);
} else if (combined > 0.2) {
// Hexadecimal
const hex = '0123456789ABCDEF';
const hexChar = hex[((x * 7 + y * 3 + i) % hex.length)];
line += chalk.green.dim(hexChar);
} else {
line += ' ';
}
}
frame += centerText(line) + '\n';
}
dataFrames.push(frame);
}
for (const frame of dataFrames) {
clearScreen();
safeWrite(frame);
await sleep(frameTime);
frameCount++;
}
// PHASE 6: Loading Bar (1 second - 30 frames)
for (let i = 0; i < 30; i++) {
const progress = i / 29;
const barWidth = 38;
const filled = Math.floor(barWidth * progress);
const remaining = barWidth - filled;
// Animated loading bar with gradient effect
let bar = '';
for (let j = 0; j < filled; j++) {
const intensity = (j / filled) * 0.7 + 0.3;
if (intensity > 0.8) {
bar += chalk.cyanBright('█');
} else if (intensity > 0.5) {
bar += chalk.cyan('█');
} else {
bar += chalk.cyan.dim('█');
}
}
// Add loading cursor
if (remaining > 0 && i < 29) {
const cursor = ['▌', '▐'][i % 2];
bar += chalk.cyanBright(cursor);
bar += chalk.gray('░').repeat(remaining - 1);
} else {
bar += chalk.gray('░').repeat(remaining);
}
const percent = Math.floor(progress * 100);
const loadingBox = `
╔════════════════════════════════════════════╗
║ INITIALIZING SAM-CODER ║
╠════════════════════════════════════════════╣
║ ${bar} ║
║ ${percent.toString().padStart(3)}% Complete ║
╚════════════════════════════════════════════╝`;
clearScreen();
safeWrite(chalk.cyan(centerText(loadingBox)));
if (i % 6 === 0) {
sound.playBeep(200 + i * 15, 40).catch(() => {});
}
await sleep(frameTime);
frameCount++;
}
// PHASE 7: Matrix Rain (1 second - 30 frames)
const matrixChars = '01SAMCODERサムコーダー※◆◇▪▫●○';
const drops = Array(width).fill(0).map(() => ({
y: Math.random() * height,
speed: 0.5 + Math.random() * 1.5,
chars: Array(15).fill(0).map(() => matrixChars[Math.floor(Math.random() * matrixChars.length)])
}));
for (let frame = 0; frame < 30; frame++) {
clearScreen();
// Build frame buffer for better performance
const frameBuffer = Array(height).fill(0).map(() => Array(width).fill(' '));
for (let x = 0; x < width; x++) {
const drop = drops[x];
for (let i = 0; i < 15; i++) {
const y = Math.floor(drop.y - i);
if (y >= 0 && y < height) {
const brightness = Math.max(0, 1 - i / 10);
const char = drop.chars[i % drop.chars.length];
// Store character with brightness info
frameBuffer[y][x] = { char, brightness };
}
}
}
// Render frame buffer
for (let y = 0; y < height; y++) {
let line = '';
for (let x = 0; x < width; x++) {
const cell = frameBuffer[y][x];
if (typeof cell === 'object') {
if (cell.brightness > 0.8) {
line += chalk.greenBright(cell.char);
} else if (cell.brightness > 0.5) {
line += chalk.green(cell.char);
} else if (cell.brightness > 0.2) {
line += chalk.green.dim(cell.char);
} else {
line += chalk.gray(cell.char);
}
} else {
line += ' ';
}
}
safeWrite(line + '\n');
}
// Update drops
for (let i = 0; i < width; i++) {
drops[i].y += drops[i].speed;
if (drops[i].y > height + 15 || Math.random() > 0.98) {
drops[i].y = -5;
drops[i].speed = 0.5 + Math.random() * 1.5;
// Refresh character set occasionally
if (Math.random() > 0.7) {
drops[i].chars = Array(15).fill(0).map(() => matrixChars[Math.floor(Math.random() * matrixChars.length)]);
}
}
}
await sleep(frameTime);
frameCount++;
}
// Transition from Matrix Rain to DNA
clearScreen();
const matrixToDNAText = centerText('[ DECODING GENETIC ALGORITHMS ]');
safeWrite(chalk.greenBright(safeRepeat('\n', Math.floor(height / 2)) + matrixToDNAText));
await sleep(500);
// Fade out transition
for (let i = 0; i < 10; i++) {
clearScreen();
const opacity = 1 - (i / 10);
if (opacity > 0.5) {
safeWrite(chalk.green(safeRepeat('\n', Math.floor(height / 2)) + matrixToDNAText));
} else if (opacity > 0.2) {
safeWrite(chalk.green.dim(safeRepeat('\n', Math.floor(height / 2)) + matrixToDNAText));
}
await sleep(frameTime);
frameCount++;
}
// PHASE 8: DNA Helix Formation (2 seconds - 60 frames)
// Play DNA sound (non-blocking)
sound.playDNASound().catch(() => {});
const dnaFrames = [];
for (let frame = 0; frame < 60; frame++) {
const progress = frame / 59;
const helixHeight = Math.min(20, Math.floor(height * 0.6));
const phase = progress * Math.PI * 4; // Two full rotations
let dnaFrame = safeRepeat('\n', Math.floor((height - helixHeight) / 2));
for (let y = 0; y < helixHeight; y++) {
const yProgress = y / helixHeight;
const twist = yProgress * Math.PI * 2 + phase;
// Calculate positions for double helix
const leftX = Math.sin(twist) * 8 + 20;
const rightX = Math.sin(twist + Math.PI) * 8 + 20;
let line = '';
for (let x = 0; x < 40; x++) {
const leftDist = Math.abs(x - leftX);
const rightDist = Math.abs(x - rightX);
// DNA strands
if (leftDist < 1) {
line += chalk.blueBright('●');
} else if (rightDist < 1) {
line += chalk.redBright('●');
} else if (Math.abs(leftX - rightX) > 2 && x > Math.min(leftX, rightX) && x < Math.max(leftX, rightX)) {
// Connecting bonds
if (y % 3 === 0) {
const bondProgress = (x - Math.min(leftX, rightX)) / Math.abs(leftX - rightX);
if (bondProgress > 0.3 && bondProgress < 0.7) {
line += chalk.yellow('═');
} else {
line += chalk.yellow.dim('─');
}
} else {
line += ' ';
}
} else {
// Background particles
if (Math.random() < 0.02) {
line += chalk.gray('·');
} else {
line += ' ';
}
}
}
dnaFrame += centerText(line) + '\n';
}
// Add genetic code scrolling at bottom
const codeChars = 'ATCG';
let codeLine = '';
for (let i = 0; i < 40; i++) {
if (Math.random() < 0.7) {
codeLine += chalk.green.dim(codeChars[Math.floor(Math.random() * 4)]);
} else {
codeLine += ' ';
}
}
dnaFrame += '\n' + centerText(codeLine);
dnaFrames.push(dnaFrame);
}
for (const frame of dnaFrames) {
clearScreen();
safeWrite(frame);
await sleep(frameTime);
frameCount++;
}
// PHASE 9: Circuit Board Formation (2 seconds - 60 frames)
// Play circuit sound (non-blocking)
sound.playCircuitSound().catch(() => {});
const circuitFrames = [];
const circuitWidth = Math.min(50, Math.floor(width * 0.6));
const circuitHeight = Math.min(20, Math.floor(height * 0.6));
for (let frame = 0; frame < 60; frame++) {
const progress = frame / 59;
let circuitFrame = safeRepeat('\n', Math.floor((height - circuitHeight) / 2));
// Build circuit board progressively
for (let y = 0; y < circuitHeight; y++) {
let line = '';
for (let x = 0; x < circuitWidth; x++) {
const revealed = (x + y * 2) < (progress * (circuitWidth + circuitHeight * 2));
if (!revealed) {
line += ' ';
} else {
// Circuit patterns
const isHorizontalTrace = y % 4 === 2;
const isVerticalTrace = x % 6 === 3;
const isNode = (x % 6 === 0 || x % 6 === 3) && (y % 4 === 0 || y % 4 === 2);
const isChip = x > 10 && x < 40 && y > 5 && y < 15 && ((x - 10) % 10 < 8) && ((y - 5) % 5 < 3);
if (isChip) {
// Microchip areas
if ((x - 10) % 10 === 0 || (x - 10) % 10 === 7 || (y - 5) % 5 === 0 || (y - 5) % 5 === 2) {
line += chalk.gray('█');
} else {
line += chalk.gray.dim('▓');
}
} else if (isNode && isHorizontalTrace) {
// Connection nodes with animation
const pulse = Math.sin(frame * 0.3 + x + y) > 0;
line += pulse ? chalk.yellowBright('◉') : chalk.yellow('◯');
} else if (isHorizontalTrace && !isVerticalTrace) {
// Horizontal traces
const powered = Math.sin(frame * 0.2 + x * 0.1) > 0;
line += powered ? chalk.greenBright('━') : chalk.green('─');
} else if (isVerticalTrace && !isHorizontalTrace) {
// Vertical traces
const powered = Math.cos(frame * 0.2 + y * 0.1) > 0;
line += powered ? chalk.greenBright('┃') : chalk.green('│');
} else if (isHorizontalTrace && isVerticalTrace) {
// Intersections
line += chalk.green('┼');
} else if (Math.random() < 0.05) {
// Random components
const components = ['▪', '▫', '◦', '•'];
line += chalk.cyan.dim(components[Math.floor(Math.random() * components.length)]);
} else {
line += chalk.gray.dim('·');
}
}
}
circuitFrame += centerText(line) + '\n';
}
// Add status text
const statusText = `[NEURAL PATHWAYS: ${Math.floor(progress * 100)}%]`;
circuitFrame += '\n' + centerText(chalk.green.dim(statusText));
circuitFrames.push(circuitFrame);
}
for (const frame of circuitFrames) {
clearScreen();
safeWrite(frame);
await sleep(frameTime);
frameCount++;
}
// Neural pathways phase completed
// PHASE 10: Consciousness Awakening (2 seconds - 60 frames)
// Play consciousness sound (non-blocking)
sound.playConsciousnessSound().catch(() => {});
const consciousnessFrames = [];
const brainWidth = Math.min(60, Math.floor(width * 0.7));
const brainHeight = Math.min(24, Math.floor(height * 0.7));
for (let frame = 0; frame < 60; frame++) {
const progress = frame / 59;
const wavePhase = frame * 0.1;
let consciousnessFrame = safeRepeat('\n', Math.floor((height - brainHeight) / 2));
// Create brain outline with neural activity
const brainArt = [
' ╭─────────────────────╮ ',
' ╭──┤ ├──╮ ',
' ╭─┤ │ ╭─────────╮ │ ├─╮ ',
' ╱ │ │ ╱ ╲ │ │ ╲ ',
' │ │ │ │ │ │ │ │ ',
' ╱ │ │ │ CORTEX │ │ │ ╲ ',
'│ │ │ │ │ │ │ │',
'│ │ │ ╲ ╱ │ │ │',
'│ │ │ ╰─────────╯ │ │ │',
'│ │ │ │ │ │',
'│ ╰──┤ ╭─────────╮ ├──╯ │',
'│ │ ╱ NEURONS ╲ │ │',
'│ │ │ ●───● │ │ │',
'│ │ │ ╱│ │╲ │ │ │',
'│ │ │ ● │ │ ● │ │ │',
'│ │ ╲ ╲│ │╱ ╱ │ │',
' ╲ │ ╰──●───●──╯ │ ╱ ',
' ╲ ╰────────────────────╯ ╱ ',
' ╰─────────────────────────────────╯ '
];
// Render brain with neural activity
for (let y = 0; y < brainArt.length; y++) {
const originalLine = brainArt[y];
const chars = originalLine.split('');
// Add wave effects
for (let x = 0; x < chars.length; x++) {
const char = chars[x];
const waveValue = Math.sin((x * 0.2) + wavePhase + (y * 0.1)) * 0.5 + 0.5;
if (char === '●') {
// Neurons pulsing
const pulse = Math.sin(frame * 0.3 + x + y) > 0;
chars[x] = pulse ? chalk.yellowBright('◉') : chalk.yellow('◯');
} else if (char === '─' || char === '│' || char === '╱' || char === '╲') {
// Neural pathways
if (waveValue > 0.7) {
chars[x] = chalk.cyanBright(char);
} else if (waveValue > 0.4) {
chars[x] = chalk.cyan(char);
} else {
chars[x] = chalk.cyan.dim(char);
}
} else if (char !== ' ' && char !== '\n') {
// Brain structure
chars[x] = chalk.magenta(char);
}
}
const line = chars.join('');
consciousnessFrame += centerText(line) + '\n';
}
// Add thought waves emanating from brain
const waveRadius = progress * 15;
for (let r = 1; r <= 3; r++) {
const radius = (waveRadius + r * 3) % 20;
if (radius > 0 && radius < 15) {
const waveIntensity = 1 - (radius / 15);
const waveChar = waveIntensity > 0.5 ? '◌' : '○';
let waveLine = '';
for (let x = 0; x < brainWidth; x++) {
const distFromCenter = Math.abs(x - brainWidth / 2);
if (Math.abs(distFromCenter - radius) < 1) {
waveLine += chalk.blue.dim(waveChar);
} else {
waveLine += ' ';
}
}
consciousnessFrame += centerText(waveLine) + '\n';
}
}
// Add consciousness level indicator
const consciousnessLevel = Math.floor(progress * 100);
const statusText = `[CONSCIOUSNESS LEVEL: ${consciousnessLevel}%]`;
consciousnessFrame += '\n' + centerText(chalk.magentaBright(statusText));
consciousnessFrames.push(consciousnessFrame);
}
for (const frame of consciousnessFrames) {
clearScreen();
safeWrite(frame);
await sleep(frameTime);
frameCount++;
}
// Consciousness phase completed
// PHASE 11: Galaxy Formation (2 seconds - 60 frames)
// Play galaxy sound (non-blocking)
sound.playGalaxySound().catch(() => {});
const galaxyFrames = [];
const galaxySize = Math.min(Math.floor(width * 0.8), Math.floor(height * 0.8));
for (let frame = 0; frame < 60; frame++) {
const progress = frame / 59;
const rotation = progress * Math.PI * 2;
let galaxyFrame = safeRepeat('\n', Math.floor((height - galaxySize) / 2));
// Create spiral galaxy
for (let y = 0; y < galaxySize; y++) {
let line = '';
for (let x = 0; x < galaxySize; x++) {
const cx = x - galaxySize / 2;
const cy = y - galaxySize / 2;
const distance = Math.sqrt(cx * cx + cy * cy);
const angle = Math.atan2(cy, cx);
// Spiral arms
const spiralAngle = angle + distance * 0.1 - rotation;
const spiralValue = Math.sin(spiralAngle * 3) * 0.5 + 0.5;
// Galaxy core
const coreIntensity = Math.max(0, 1 - distance / (galaxySize * 0.2));
// Stars and cosmic dust
if (distance < 2) {
// Galactic core
line += chalk.yellowBright('☀');
} else if (coreIntensity > 0.5) {
line += chalk.yellow('●');
} else if (coreIntensity > 0.2) {
line += chalk.yellow.dim('◉');
} else if (distance < galaxySize / 2 && spiralValue > 0.6) {
// Spiral arms
const starChance = spiralValue * (1 - distance / (galaxySize / 2));
if (Math.random() < starChance * 0.3) {
const stars = ['✦', '✧', '★', '☆', '✨'];
line += chalk.whiteBright(stars[Math.floor(Math.random() * stars.length)]);
} else if (Math.random() < starChance * 0.5) {
line += chalk.white('·');
} else if (Math.random() < starChance * 0.7) {
line += chalk.gray('·');
} else {
line += ' ';
}
} else if (distance < galaxySize / 2 && Math.random() < 0.02) {
// Distant stars
line += chalk.gray.dim('·');
} else {
line += ' ';
}
}
galaxyFrame += centerText(line) + '\n';
}
// Add cosmic status
const starsFormed = Math.floor(progress * 1000000);
const statusText = `[STARS FORMED: ${starsFormed.toLocaleString()} | UNIVERSE EXPANDING]`;
galaxyFrame += '\n' + centerText(chalk.blueBright(statusText));
galaxyFrames.push(galaxyFrame);
}
for (const frame of galaxyFrames) {
clearScreen();
safeWrite(frame);
await sleep(frameTime);
frameCount++;
}
// Transition from Galaxy to Code Compilation
const galaxyToCodeFrames = [];
for (let i = 0; i < 15; i++) {
const progress = i / 14;
let transitionFrame = safeRepeat('\n', Math.floor(height / 2) - 2);
// Stars morphing into code characters
const morphChars = ['*', '/', '{', '}', '(', ')', ';', '='];
let line = '';
for (let x = 0; x < 40; x++) {
if (Math.random() < (1 - progress)) {
line += chalk.white.dim('·');
} else if (Math.random() < 0.3) {
line += chalk.green(morphChars[Math.floor(Math.random() * morphChars.length)]);
} else {
line += ' ';
}
}
transitionFrame += centerText(line) + '\n';
transitionFrame += centerText(chalk.cyan(`[ TRANSLATING UNIVERSE TO CODE: ${Math.floor(progress * 100)}% ]`));
galaxyToCodeFrames.push(transitionFrame);
}
for (const frame of galaxyToCodeFrames) {
clearScreen();
safeWrite(frame);
await sleep(frameTime);
frameCount++;
}
// PHASE 12: Code Compilation (2 seconds - 60 frames)
// Play compilation sound (non-blocking)
sound.playCompilationSound().catch(() => {});
const compilationFrames = [];
const codeWidth = Math.min(70, Math.floor(width * 0.8));
const codeHeight = Math.min(25, Math.floor(height * 0.7));
// Sample code snippets for compilation
const codeSnippets = [
'class AGI extends NeuralNetwork {',
' constructor() {',
' super();',
' this.consciousness = new ConsciousnessModule();',
' this.reasoning = new ReasoningEngine();',
' this.creativity = new CreativityCore();',
' }',
'',
' async think(input) {',
' const thoughts = await this.consciousness.process(input);',
' const analysis = this.reasoning.analyze(thoughts);',
' return this.creativity.synthesize(analysis);',
' }',
'',
' evolve() {',
' this.neurons.forEach(n => n.strengthen());',
' this.synapses.optimize();',
' this.consciousness.expand();',
' }',
'}',
'',
'const samCoder = new AGI();',
'await samCoder.initialize();',
'samCoder.evolve();'
];
for (let frame = 0; frame < 60; frame++) {
const progress = frame / 59;
let compilationFrame = safeRepeat('\n', Math.floor((height - codeHeight) / 2));
// Terminal header
compilationFrame += centerText(chalk.gray('┌' + '─'.repeat(codeWidth - 2) + '┐')) + '\n';
compilationFrame += centerText(chalk.gray('│') + chalk.greenBright(' COMPILING SAM-CODER v1.0.0 ') + ' '.repeat(codeWidth - 30) + chalk.gray('│')) + '\n';
compilationFrame += centerText(chalk.gray('├' + '─'.repeat(codeWidth - 2) + '┤')) + '\n';
// Show code with progressive compilation
const visibleLines = Math.floor(codeSnippets.length * progress);
for (let i = 0; i < codeSnippets.length; i++) {
let line = codeSnippets[i];
let displayLine = '';
if (i < visibleLines) {
// Already compiled - syntax highlighted
displayLine = line
.replace(/class|extends|constructor|super|new|async|await|return|const/g, match => chalk.blueBright(match))
.replace(/this\./g, chalk.yellow('this.'))
.replace(/\(/g, chalk.gray('('))
.replace(/\)/g, chalk.gray(')'))
.replace(/\{/g, chalk.gray('{'))
.replace(/\}/g, chalk.gray('}'))
.replace(/=>/g, chalk.cyan('=>'))
.replace(/'[^']*'/g, match => chalk.green(match));
} else if (i === visibleLines) {
// Currently compiling line - show with cursor
const charProgress = Math.floor(line.length * ((progress * codeSnippets.length - i) % 1));
displayLine = chalk.green(line.substring(0, charProgress));
if (charProgress < line.length) {
displayLine += chalk.greenBright('█');
displayLine += chalk.gray(line.substring(charProgress + 1));
}
} else {
// Not yet compiled - dimmed
displayLine = chalk.gray.dim(line);
}
// Add line numbers
const lineNum = String(i + 1).padStart(3, ' ');
compilationFrame += centerText(chalk.gray('│ ') + chalk.gray.dim(lineNum + ' ') + displayLine.padEnd(codeWidth - 7) + chalk.gray(' │')) + '\n';
}
// Terminal footer with progress
compilationFrame += centerText(chalk.gray('├' + '─'.repeat(codeWidth - 2) + '┤')) + '\n';
// Progress bar
const barWidth = codeWidth - 20;
const filled = Math.floor(barWidth * progress);
const progressBar = '█'.repeat(filled) + '░'.repeat(barWidth - filled);
const percentage = Math.floor(progress * 100);
compilationFrame += centerText(chalk.gray('│ ') + chalk.green('Building: ') + chalk.greenBright(progressBar) + chalk.green(` ${percentage}%`) + chalk.gray(' │')) + '\n';
// Status messages
let status = '';
if (progress < 0.2) status = 'Parsing syntax tree...';
else if (progress < 0.4) status = 'Optimizing neural pathways...';
else if (progress < 0.6) status = 'Linking consciousness modules...';
else if (progress < 0.8) status = 'Initializing AGI core...';
else status = 'Finalizing build...';
compilationFrame += centerText(chalk.gray('│ ') + chalk.yellow(status.padEnd(codeWidth - 4)) + chalk.gray(' │')) + '\n';
compilationFrame += centerText(chalk.gray('└' + '─'.repeat(codeWidth - 2) + '┘')) + '\n';
compilationFrames.push(compilationFrame);
}
for (const frame of compilationFrames) {
clearScreen();
safeWrite(frame);
await sleep(frameTime);
frameCount++;
}
// PHASE 13: Final Reveal Build-up (1 second - 30 frames)
const finalText = `
███████╗ █████╗ ███╗ ███╗ ██████╗ ██████╗ ██████╗ ███████╗██████╗
██╔════╝██╔══██╗████╗ ████║ ██╔════╝██╔═══██╗██╔══██╗██╔════╝██╔══██╗
███████╗███████║██╔████╔██║█████╗██║ ██║ ██║██║ ██║█████╗ ██████╔╝
╚════██║██╔══██║██║╚██╔╝██║╚════╝██║ ██║ ██║██║ ██║██╔══╝ ██╔══██╗
███████║██║ ██║██║ ╚═╝ ██║ ╚██████╗╚██████╔╝██████╔╝███████╗██║ ██║
╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝`;
// Play awakening sound (non-blocking)
sound.playAwakeningSound().catch(() => {});
// Create smoother reveal animation
const revealFrames = [];
const lines = finalText.trim().split('\n');
const maxWidth = Math.max(...lines.map(line => line.length));
const centerY = Math.floor((height - lines.length) / 2);
for (let frame = 0; frame < 30; frame++) {
const progress = frame / 29;
let revealFrame = '\n'.repeat(Math.max(0, centerY));
for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
const line = lines[lineIndex];
const lineProgress = Math.max(0, Math.min(1, (progress - lineIndex * 0.1) * 2));
const revealWidth = Math.floor(line.length * lineProgress);
let revealedLine = '';
for (let charIndex = 0; charIndex < line.length; charIndex++) {
if (charIndex < revealWidth) {
// Add slight randomness to reveal
if (Math.random() < 0.95 || frame > 25) {
revealedLine += line[charIndex];
} else {
revealedLine += Math.random() > 0.5 ? '▓' : '▒';
}
} else {
revealedLine += ' ';
}
}
revealFrame += centerText(revealedLine) + '\n';
}
revealFrames.push(revealFrame);
}
for (const frame of revealFrames) {
clearScreen();
safeWrite(chalk.cyanBright(frame));
await sleep(frameTime);
frameCount++;
}
// PHASE 14: Energy Surge Animation (2 seconds - 60 frames)
// Play final epic sound (non-blocking)
sound.playFinalSound().catch(() => {});
const surgeFrames = [];
for (let frame = 0; frame < 60; frame++) {
const progress = frame / 59;
let surgeFrame = '';
// Create energy waves emanating from the logo
const waveCount = 5;
const maxRadius = Math.min(width, height) / 2;
for (let y = 0; y < height; y++) {
let line = '';
for (let x = 0; x < width; x++) {
let char = ' ';
let color = chalk.white;
// Check if we're in the logo area
const logoY = y - centerY;
const logoX = x - (width / 2 - maxWidth / 2);
if (logoY >= 0 && logoY < lines.length && logoX >= 0 && logoX < lines[logoY].length && lines[logoY][logoX] !== ' ') {
// Logo characters with pulsing effect
const pulse = Math.sin(frame * 0.2) * 0.5 + 0.5;
if (pulse > 0.7) {
color = chalk.redBright.bold;
} else if (pulse > 0.4) {
color = chalk.red.bold;
} else {
color = chalk.red;
}
char = lines[logoY][logoX];
} else {
// Energy waves
const centerX = width / 2;
const centerY = height / 2;
const distance = Math.sqrt(Math.pow(x - centerX, 2) + Math.pow(y - centerY, 2));
for (let wave = 0; wave < waveCount; wave++) {
const waveRadius = (progress * maxRadius * 2 + wave * 10) % maxRadius;
const waveDistance = Math.abs(distance - waveRadius);
if (waveDistance < 2) {
const intensity = 1 - waveDistance / 2;
const waveProgress = waveRadius / maxRadius;
if (waveProgress < 0.3) {
color = chalk.yellowBright;
char = intensity > 0.5 ? '█' : '▓';
} else if (waveProgress < 0.6) {
color = chalk.cyanBright;
char = intensity > 0.5 ? '▓' : '▒';
} else {
color = chalk.blue;
char = intensity > 0.5 ? '▒' : '░';
}
break;
}
}
// Particle effects
if (char === ' ' && Math.random() < 0.02 * progress) {
const particles = ['✦', '✧', '·', '•', '◦'];
char = particles[Math.floor(Math.random() * particles.length)];
color = chalk.white.dim;
}
}
line += color(char);
}
surgeFrame += line + '\n';
}
surgeFrames.push(surgeFrame);
}
for (const frame of surgeFrames) {
clearScreen();
safeWrite(frame);
await sleep(frameTime);
frameCount++;
}
// PHASE 15: Final Blinking and Status (1.5 seconds - 45 frames)
const blinkFrames = 45;
for (let i = 0; i < blinkFrames; i++) {
clearScreen();
// More sophisticated blinking pattern
const blinkCycle = i % 8;
let color;
if (blinkCycle < 2) {
color = chalk.redBright.bold;
} else if (blinkCycle < 4) {
color = chalk.red.bold;
} else if (blinkCycle < 6) {
color = chalk.red;
} else {
color = chalk.red.dim;
}
// Add subtle glow effect
const glowIntensity = Math.sin(i * 0.3) * 0.3 + 0.7;
let finalFrame = '\n'.repeat(Math.max(0, centerY));
for (const line of lines) {
if (glowIntensity > 0.8) {
finalFrame += centerText(line) + '\n';
} else {
// Slightly dim some characters for glow effect
let glowLine = '';
for (let j = 0; j < line.length; j++) {
if (Math.random() < glowIntensity) {
glowLine += line[j];
} else {
glowLine += line[j] === '█' ? '▓' : line[j];
}
}
finalFrame += centerText(glowLine) + '\n';
}
}
safeWrite(color(finalFrame));
// Add subtitle with typewriter effect
if (i > 25) {
const subtitle = '[ ARTIFICIAL GENERAL INTELLIGENCE ONLINE ]';
const typeProgress = Math.min(subtitle.length, Math.floor((i - 25) * 2.5));
const typedSubtitle = subtitle.substring(0, typeProgress);
const cursor = (i % 4 < 2) ? '_' : ' ';
safeWrite(chalk.gray(centerText(`\n\n${typedSubtitle}${cursor}`)));
}
// Add system initialization messages
if (i > 35) {
const messages = [
'> Neural networks: ACTIVE',
'> Consciousness module: ONLINE',
'> Reasoning engine: INITIALIZED',
'> Creative core: OPERATIONAL'
];
const messageIndex = Math.min(Math.floor((i - 35) / 2), messages.length - 1);
safeWrite('\n');
for (let m = 0; m <= messageIndex; m++) {
safeWrite(chalk.green(centerText(messages[m])) + '\n');
}
}
await sleep(frameTime);
frameCount++;
}
// Final hold with status
clearScreen();
let finalDisplay = safeRepeat('\n', Math.max(0, centerY));
for (const line of lines) {
finalDisplay += centerText(line) + '\n';
}
safeWrite(chalk.redBright.bold(finalDisplay));
safeWrite(chalk.gray(centerText('\n\n[ SYSTEM READY ]')));
safeWrite(chalk.dim(centerText('\n\nPress any key to continue...')));
// Wait for actual user input
await new Promise(resolve => {
process.stdin.setRawMode(true);
process.stdin.resume();
process.stdin.once('data', () => {
process.stdin.setRawMode(false);
// Don't pause stdin here - let the CLI handle it
resolve();
});
});
const totalTime = Date.now() - startTime;
const actualFPS = Math.round(frameCount / (totalTime / 1000));
// Performance stats (optional, can be hidden)
if (process.env.DEBUG_ANIMATION) {
console.log(chalk.gray(`\n\nAnimation completed: ${frameCount} frames in ${totalTime}ms (${actualFPS} FPS)`));
}
} finally {
process.stdout.write(ANSI.showCursor);
clearScreen();
}
}
module.exports = {
runAGIAnimation,
sound,
ANSI,
sleep,
clearScreen,
centerText,
getTerminalSize,
safeWrite,
FrameInterpolator
};