Pastebin
API
tools
faq
paste
Login
Sign up
Please fix the following errors:
New Paste
Syntax Highlighting
(function() { 'use strict'; // ============ NAMESPACE & CONFIGURATION ============ const ns = { sf: {}, config: { LOG_MAX_LINES: 200, DEFAULT_DELAY: 1000, MAX_CONCURRENT: 3, RETRY_ATTEMPTS: 3, OLLAMA_PORT: 11434, DEFAULT_MODEL: 'Zircuitry/Zircuitry:latest' }, // CONNECTIVITY: Central event system events: { listeners: {}, on(event, callback) { if (!this.listeners[event]) this.listeners[event] = []; this.listeners[event].push(callback); }, emit(event, data) { if (!this.listeners[event]) return; this.listeners[event].forEach(callback => callback(data)); }, off(event, callback) { if (!this.listeners[event]) return; if (callback) { this.listeners[event] = this.listeners[event].filter(cb => cb !== callback); } else { this.listeners[event] = []; } }, once(event, callback) { const wrapper = (data) => { callback(data); this.off(event, wrapper); }; this.on(event, wrapper); }, listListeners() { return Object.keys(this.listeners).map(event => ({ event, count: this.listeners[event].length })); } } }; window.its = ns; window.fs = {}; // ============ EVENT HANDLER CLASS ============ class EventHandler { constructor() { this.handlers = new Map(); this.middlewares = []; this.eventHistory = []; this.maxHistorySize = 100; } // Register an event handler register(eventName, handler, options = {}) { if (!this.handlers.has(eventName)) { this.handlers.set(eventName, []); } const handlerObj = { fn: handler, priority: options.priority || 0, once: options.once || false, id: options.id || `handler_${Date.now()}_${Math.random()}`, enabled: true }; this.handlers.get(eventName).push(handlerObj); // Sort by priority (higher priority first) this.handlers.get(eventName).sort((a, b) => b.priority - a.priority); return handlerObj.id; } // Unregister an event handler unregister(eventName, handlerId) { if (!this.handlers.has(eventName)) return false; const handlers = this.handlers.get(eventName); const index = handlers.findIndex(h => h.id === handlerId); if (index !== -1) { handlers.splice(index, 1); return true; } return false; } // Add middleware (runs before all handlers) use(middleware) { this.middlewares.push(middleware); } // Emit an event async emit(eventName, data) { const eventData = { name: eventName, data, timestamp: Date.now(), preventDefault: false, stopPropagation: false }; // Add to history this.eventHistory.push({ event: eventName, timestamp: eventData.timestamp, data: JSON.stringify(data).substring(0, 100) }); if (this.eventHistory.length > this.maxHistorySize) { this.eventHistory.shift(); } // Run middlewares for (const middleware of this.middlewares) { try { await middleware(eventData); if (eventData.preventDefault) return; } catch (error) { console.error(`Middleware error:`, error); } } // Run handlers if (!this.handlers.has(eventName)) return; const handlers = this.handlers.get(eventName).filter(h => h.enabled); for (const handler of handlers) { if (eventData.stopPropagation) break; try { await handler.fn(eventData.data, eventData); // Remove if it's a one-time handler if (handler.once) { this.unregister(eventName, handler.id); } } catch (error) { console.error(`Handler error for ${eventName}:`, error); } } } // Enable/disable handler toggleHandler(eventName, handlerId, enabled) { if (!this.handlers.has(eventName)) return false; const handler = this.handlers.get(eventName).find(h => h.id === handlerId); if (handler) { handler.enabled = enabled; return true; } return false; } // Get event statistics getStats() { const stats = { totalHandlers: 0, eventTypes: this.handlers.size, events: [] }; for (const [event, handlers] of this.handlers.entries()) { stats.totalHandlers += handlers.length; stats.events.push({ event, handlers: handlers.length, enabled: handlers.filter(h => h.enabled).length }); } return stats; } // Get event history getHistory(limit = 50) { return this.eventHistory.slice(-limit); } // Clear all handlers for an event clear(eventName) { if (eventName) { this.handlers.delete(eventName); } else { this.handlers.clear(); } } } // ============ STYLES ============ const createStyles = () => { const style = document.createElement('style'); style.textContent = ` .ai-terminal-container * { margin: 0; padding: 0; box-sizing: border-box; } .ai-terminal-container { font-family: 'Consolas', 'Monaco', monospace; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: linear-gradient(135deg, #0a0a0a 0%, #1a1a2e 100%); color: #00ff00; padding: 20px; overflow-y: auto; z-index: 999999; } .ai-terminal-inner { max-width: 1400px; margin: 0 auto; } .ai-terminal-container h1 { text-align: center; color: #00ffff; text-shadow: 0 0 10px #00ffff; margin-bottom: 30px; font-size: 2.5em; } .ai-terminal-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px; } @media (max-width: 768px) { .ai-terminal-grid { grid-template-columns: 1fr; } } .ai-terminal-panel { background: rgba(0, 255, 255, 0.05); border: 2px solid #00ffff; border-radius: 10px; padding: 20px; box-shadow: 0 0 20px rgba(0, 255, 255, 0.3); } .ai-terminal-panel h2 { color: #00ffff; margin-bottom: 15px; font-size: 1.3em; border-bottom: 1px solid #00ffff; padding-bottom: 10px; } .ai-terminal-input-group { margin-bottom: 15px; } .ai-terminal-container label { display: block; color: #00ff00; margin-bottom: 5px; font-size: 0.9em; } .ai-terminal-container input, .ai-terminal-container select, .ai-terminal-container textarea { width: 100%; background: rgba(0, 0, 0, 0.5); border: 1px solid #00ff00; color: #00ff00; padding: 10px; border-radius: 5px; font-family: inherit; font-size: 0.9em; } .ai-terminal-container textarea { resize: vertical; min-height: 100px; } .ai-terminal-container button { background: linear-gradient(135deg, #00ff00 0%, #00ffff 100%); border: none; color: #000; padding: 12px 24px; border-radius: 5px; cursor: pointer; font-weight: bold; font-size: 1em; transition: all 0.3s; margin-right: 10px; margin-bottom: 10px; } .ai-terminal-container button:hover { transform: scale(1.05); box-shadow: 0 0 20px rgba(0, 255, 255, 0.6); } .ai-terminal-container button:active { transform: scale(0.95); } .ai-terminal-container button:disabled { opacity: 0.5; cursor: not-allowed; transform: none; } .ai-terminal-container button.zircuitry-btn { background: linear-gradient(135deg, #ff00ff 0%, #00ffff 100%); animation: zircuitryPulse 2s infinite; } @keyframes zircuitryPulse { 0%, 100% { box-shadow: 0 0 10px rgba(255, 0, 255, 0.5); } 50% { box-shadow: 0 0 20px rgba(255, 0, 255, 0.8); } } .ai-terminal-output { background: rgba(0, 0, 0, 0.8); border: 2px solid #00ff00; border-radius: 10px; padding: 15px; height: 400px; overflow-y: auto; font-size: 0.85em; line-height: 1.4; } .ai-terminal-line { margin-bottom: 5px; animation: terminalFadeIn 0.3s; } @keyframes terminalFadeIn { from { opacity: 0; } to { opacity: 1; } } .ai-terminal-line.success { color: #00ff00; } .ai-terminal-line.error { color: #ff0000; } .ai-terminal-line.info { color: #00ffff; } .ai-terminal-line.warning { color: #ffff00; } .ai-terminal-line.zircuitry { color: #ff00ff; font-weight: bold; } .ai-terminal-line.probe { color: #ffa500; font-weight: bold; } .ai-terminal-line.event { color: #ff69b4; font-weight: bold; } .ai-terminal-line.download { color: #00ffff; font-weight: bold; } .ai-terminal-line.serve { color: #ffff00; font-weight: bold; } .ai-queue-item { background: rgba(0, 255, 0, 0.1); border-left: 3px solid #00ff00; padding: 10px; margin-bottom: 10px; border-radius: 5px; font-size: 0.85em; } .ai-queue-item.processing { border-left-color: #ffff00; background: rgba(255, 255, 0, 0.1); } .ai-queue-item.completed { border-left-color: #00ffff; background: rgba(0, 255, 255, 0.1); } .ai-queue-item.failed { border-left-color: #ff0000; background: rgba(255, 0, 0, 0.1); } .ai-status-indicator { display: inline-block; width: 10px; height: 10px; border-radius: 50%; margin-right: 8px; animation: statusPulse 2s infinite; } .ai-status-indicator.connected { background: #00ff00; } .ai-status-indicator.disconnected { background: #ff0000; } .ai-status-indicator.processing { background: #ffff00; } .ai-status-indicator.downloading { background: #ff00ff; } .ai-status-indicator.serving { background: #00ffff; } @keyframes statusPulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } } .ai-terminal-stats { display: flex; justify-content: space-between; margin-top: 15px; padding: 10px; background: rgba(0, 0, 0, 0.3); border-radius: 5px; } .ai-stat-item { text-align: center; } .ai-stat-value { font-size: 1.5em; color: #00ffff; font-weight: bold; } .ai-stat-label { font-size: 0.8em; color: #00ff00; } .ai-response-box { background: rgba(0, 0, 0, 0.6); border: 1px solid #00ffff; border-radius: 5px; padding: 10px; margin-top: 10px; max-height: 200px; overflow-y: auto; color: #00ffff; font-size: 0.85em; white-space: pre-wrap; word-wrap: break-word; } .ai-close-btn { position: fixed; top: 20px; right: 20px; background: #ff0000 !important; z-index: 1000000; } .ai-event-item { background: rgba(255, 105, 180, 0.1); border-left: 3px solid #ff69b4; padding: 8px; margin-bottom: 8px; border-radius: 3px; font-size: 0.85em; } .ai-event-name { color: #ff69b4; font-weight: bold; } .ai-event-time { color: #888; font-size: 0.8em; } .ai-download-progress { background: rgba(0, 0, 0, 0.5); border: 1px solid #ff00ff; border-radius: 5px; padding: 10px; margin-top: 10px; } .ai-progress-bar { width: 100%; height: 20px; background: rgba(0, 0, 0, 0.7); border-radius: 10px; overflow: hidden; margin-top: 5px; } .ai-progress-fill { height: 100%; background: linear-gradient(135deg, #ff00ff 0%, #00ffff 100%); transition: width 0.3s; display: flex; align-items: center; justify-content: center; color: #000; font-weight: bold; font-size: 0.8em; } .ai-serve-instructions { background: rgba(255, 255, 0, 0.1); border: 1px solid #ffff00; border-radius: 5px; padding: 10px; margin-top: 10px; font-size: 0.85em; color: #ffff00; } .ai-serve-instructions code { background: rgba(0, 0, 0, 0.5); padding: 2px 6px; border-radius: 3px; color: #00ff00; } `; return style; }; // ============ LOGGER ============ class Logger { constructor(elementId, maxLines = ns.config.LOG_MAX_LINES) { this.element = document.getElementById(elementId); this.maxLines = maxLines; } log(message, type = 'info') { if (!this.element) return; const line = document.createElement('div'); line.className = `ai-terminal-line ${type}`; const timestamp = new Date().toLocaleTimeString(); line.textContent = `[${timestamp}] ${message}`; this.element.appendChild(line); this.element.scrollTop = this.element.scrollHeight; if (this.element.children.length > this.maxLines) { this.element.removeChild(this.element.firstChild); } ns.events.emit('log', { message, type, timestamp }); } clear() { if (this.element) this.element.innerHTML = ''; ns.events.emit('log:cleared', {}); } } let logger; let eventHandler; // ============ PROBE SYSTEM ============ class ProbeSystem { static probeBrowser() { const browserData = { userAgent: navigator.userAgent, platform: navigator.platform, language: navigator.language, cookieEnabled: navigator.cookieEnabled, onLine: navigator.onLine }; logger.log(`Browser: ${this.detectBrowser()}`, 'success'); logger.log(`Platform: ${browserData.platform}`, 'success'); ns.events.emit('probe:browser', browserData); eventHandler.emit('probe:browser', browserData); return browserData; } static detectBrowser() { const ua = navigator.userAgent; const browsers = { Firefox: /Firefox/, Chrome: /Chrome(?!.*Edg)/, Safari: /Safari(?!.*Chrome)/, Edge: /Edg/, Opera: /Opera|OPR/ }; for (const [name, regex] of Object.entries(browsers)) { if (regex.test(ua)) return name; } return 'Unknown'; } static async probeSystem() { logger.log('═══════════════════════════════════════', 'probe'); logger.log('FULL SYSTEM PROBE INITIATED', 'probe'); logger.log('═══════════════════════════════════════', 'probe'); const systemData = { timestamp: new Date().toISOString(), browser: this.probeBrowser() }; logger.log('═══════════════════════════════════════', 'probe'); logger.log('SYSTEM PROBE COMPLETE', 'probe'); logger.log('═══════════════════════════════════════', 'probe'); ns.events.emit('probe:system', systemData); eventHandler.emit('probe:system', systemData); return systemData; } } // ============ DELAYED CALL QUEUE ============ class DelayedCallQueue { constructor(options = {}) { this.queue = []; this.processing = []; this.completed = []; this.defaultDelay = options.defaultDelay || ns.config.DEFAULT_DELAY; this.maxConcurrent = options.maxConcurrent || ns.config.MAX_CONCURRENT; this.retryFailed = options.retryFailed !== false; this.isProcessing = false; this.isPaused = false; } add(fn, delay = null, metadata = {}) { const item = { id: Date.now() + Math.random(), fn, delay: delay !== null ? delay : this.defaultDelay, metadata, status: 'queued', addedAt: new Date(), attempts: 0 }; this.queue.push(item); logger.log(`Queued: ${metadata.name || 'Task ' + item.id.toString().slice(-4)}`, 'info'); ns.events.emit('queue:add', item); eventHandler.emit('queue:add', item); this.process(); updateQueueDisplay(); return item.id; } async process() { if (this.isProcessing || this.isPaused) return; this.isProcessing = true; ns.events.emit('queue:process:start', {}); eventHandler.emit('queue:process:start', {}); while ((this.queue.length > 0 || this.processing.length > 0) && !this.isPaused) { while (this.processing.length < this.maxConcurrent && this.queue.length > 0 && !this.isPaused) { const item = this.queue.shift(); this.processing.push(item); updateQueueDisplay(); this.executeItem(item); } await new Promise(resolve => setTimeout(resolve, 100)); } this.isProcessing = false; ns.events.emit('queue:process:end', {}); eventHandler.emit('queue:process:end', {}); updateQueueDisplay(); } async executeItem(item) { try { item.status = 'processing'; item.startedAt = new Date(); updateQueueDisplay(); ns.events.emit('queue:item:start', item); eventHandler.emit('queue:item:start', item); logger.log(`Processing: ${item.metadata.name || 'Task'}`, 'warning'); if (item.delay > 0) { await new Promise(resolve => setTimeout(resolve, item.delay)); } const result = await item.fn(); item.status = 'completed'; item.completedAt = new Date(); item.result = result; this.processing = this.processing.filter(i => i.id !== item.id); this.completed.push(item); logger.log(`Completed: ${item.metadata.name || 'Task'}`, 'success'); ns.events.emit('queue:item:complete', item); eventHandler.emit('queue:item:complete', item); } catch (error) { item.attempts++; logger.log(`Error in ${item.metadata.name || 'Task'}: ${error.message}`, 'error'); if (this.retryFailed && item.attempts < ns.config.RETRY_ATTEMPTS) { logger.log(`Retry ${item.metadata.name || 'Task'} (attempt ${item.attempts + 1})`, 'warning'); this.processing = this.processing.filter(i => i.id !== item.id); item.status = 'queued'; this.queue.push(item); ns.events.emit('queue:item:retry', item); eventHandler.emit('queue:item:retry', item); } else { item.status = 'failed'; item.error = error.message; this.processing = this.processing.filter(i => i.id !== item.id); this.completed.push(item); ns.events.emit('queue:item:failed', item); eventHandler.emit('queue:item:failed', item); } } updateQueueDisplay(); } clear() { this.queue = []; logger.log('Queue cleared', 'warning'); ns.events.emit('queue:cleared', {}); eventHandler.emit('queue:cleared', {}); updateQueueDisplay(); } getStats() { return { queued: this.queue.length, processing: this.processing.length, completed: this.completed.length }; } getAllItems() { return { queue: this.queue, processing: this.processing, completed: this.completed }; } } // ============ OLLAMA CLIENT WITH SERVE & AUTO-DOWNLOAD ============ class OllamaClient { constructor(url, model) { this.url = url; this.model = model; this.connected = false; this.isDownloading = false; this.downloadProgress = 0; this.isServing = false; } async testConnection() { logger.log(`Testing connection to ${this.url}...`, 'info'); ns.events.emit('ollama:test:start', { url: this.url }); eventHandler.emit('ollama:test:start', { url: this.url }); try { const response = await fetch(`${this.url}/api/tags`); if (response.ok) { this.connected = true; logger.log('Connection successful!', 'success'); updateStatus(true); hideServeInstructions(); ns.events.emit('ollama:connected', { url: this.url, model: this.model }); eventHandler.emit('ollama:connected', { url: this.url, model: this.model }); return true; } else { logger.log('Connection failed', 'error'); showServeInstructions(); ns.events.emit('ollama:connection:failed', { url: this.url, status: response.status }); eventHandler.emit('ollama:connection:failed', { url: this.url, status: response.status }); return false; } } catch (error) { logger.log(`Connection error: ${error.message}`, 'error'); logger.log('Make sure Ollama is running: ollama serve', 'warning'); showServeInstructions(); ns.events.emit('ollama:connection:error', { url: this.url, error: error.message }); eventHandler.emit('ollama:connection:error', { url: this.url, error: error.message }); return false; } } async checkModelExists() { try { const response = await fetch(`${this.url}/api/tags`); if (!response.ok) return false; const data = await response.json(); const modelExists = data.models && data.models.some(m => m.name === this.model); return modelExists; } catch (error) { logger.log(`Error checking models: ${error.message}`, 'error'); return false; } } async downloadModel() { if (this.isDownloading) { logger.log('Download already in progress', 'warning'); return false; } this.isDownloading = true; this.downloadProgress = 0; logger.log('═══════════════════════════════════════', 'download'); logger.log(`DOWNLOADING MODEL: ${this.model}`, 'download'); logger.log('═══════════════════════════════════════', 'download'); updateStatus('downloading'); showDownloadProgress(); ns.events.emit('model:download:start', { model: this.model }); eventHandler.emit('model:download:start', { model: this.model }); try { const response = await fetch(`${this.url}/api/pull`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: this.model, stream: true }) }); if (!response.ok) { throw new Error(`HTTP ${response.status}`); } const reader = response.body.getReader(); const decoder = new TextDecoder(); while (true) { const { done, value } = await reader.read(); if (done) break; const text = decoder.decode(value); const lines = text.split('\n').filter(l => l.trim()); for (const line of lines) { try { const data = JSON.parse(line); if (data.status) { logger.log(`Download: ${data.status}`, 'download'); if (data.completed && data.total) { this.downloadProgress = Math.round((data.completed / data.total) * 100); updateDownloadProgress(this.downloadProgress, data.status); ns.events.emit('model:download:progress', { model: this.model, progress: this.downloadProgress, status: data.status }); eventHandler.emit('model:download:progress', { model: this.model, progress: this.downloadProgress, status: data.status }); } } if (data.status === 'success') { logger.log('═══════════════════════════════════════', 'download'); logger.log('MODEL DOWNLOAD COMPLETE!', 'success'); logger.log('═══════════════════════════════════════', 'download'); this.isDownloading = false; updateStatus(true); hideDownloadProgress(); ns.events.emit('model:download:complete', { model: this.model }); eventHandler.emit('model:download:complete', { model: this.model }); return true; } } catch (e) { // Skip invalid JSON lines } } } this.isDownloading = false; updateStatus(true); hideDownloadProgress(); return true; } catch (error) { logger.log(`Download error: ${error.message}`, 'error'); this.isDownloading = false; updateStatus(false); hideDownloadProgress(); ns.events.emit('model:download:error', { model: this.model, error: error.message }); eventHandler.emit('model:download:error', { model: this.model, error: error.message }); throw error; } } async ensureModelReady() { const exists = await this.checkModelExists(); if (!exists) { logger.log(`Model ${this.model} not found. Starting download...`, 'warning'); await this.downloadModel(); } else { logger.log(`Model ${this.model} is ready!`, 'success'); ns.events.emit('model:ready', { model: this.model }); eventHandler.emit('model:ready', { model: this.model }); } } async runModel() { logger.log('═══════════════════════════════════════', 'serve'); logger.log('RUNNING MODEL', 'serve'); logger.log('═══════════════════════════════════════', 'serve'); this.isServing = true; updateStatus('serving'); ns.events.emit('model:run:start', { model: this.model }); eventHandler.emit('model:run:start', { model: this.model }); try { await this.ensureModelReady(); // Load model into memory const response = await fetch(`${this.url}/api/generate`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ model: this.model, prompt: '', keep_alive: -1 }) }); if (!response.ok) { throw new Error(`HTTP ${response.status}`); } logger.log(`Model ${this.model} is now loaded and ready!`, 'success'); logger.log('═══════════════════════════════════════', 'serve'); this.isServing = true; updateStatus(true); ns.events.emit('model:run:complete', { model: this.model }); eventHandler.emit('model:run:complete', { model: this.model }); return true; } catch (error) { logger.log(`Error running model: ${error.message}`, 'error'); this.isServing = false; updateStatus(false); ns.events.emit('model:run:error', { model: this.model, error: error.message }); eventHandler.emit('model:run:error', { model: this.model, error: error.message }); throw error; } } async generate(prompt) { if (!this.connected) { logger.log('Not connected to Ollama server', 'error'); throw new Error('Not connected'); } // Ensure model is ready before generating await this.ensureModelReady(); logger.log(`Generating: "${prompt.substring(0, 50)}..."`, 'info'); ns.events.emit('ollama:generate:start', { prompt: prompt.substring(0, 100), model: this.model }); eventHandler.emit('ollama:generate:start', { prompt: prompt.substring(0, 100), model: this.model }); try { const response = await fetch(`${this.url}/api/generate`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ model: this.model, prompt: prompt, stream: false }) }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const data = await response.json(); logger.log('Response received', 'success'); ns.events.emit('ollama:generate:success', { prompt: prompt.substring(0, 100), response: data.response?.substring(0, 100), model: this.model }); eventHandler.emit('ollama:generate:success', { prompt: prompt.substring(0, 100), response: data.response?.substring(0, 100), model: this.model }); return data.response || ''; } catch (error) { logger.log(`Generation error: ${error.message}`, 'error'); ns.events.emit('ollama:generate:error', { error: error.message, model: this.model }); eventHandler.emit('ollama:generate:error', { error: error.message, model: this.model }); throw error; } } } // ============ UI HELPERS ============ function updateStatus(status) { const indicator = document.getElementById('aiStatusIndicator'); const text = document.getElementById('aiStatusText'); if (status === true) { indicator.className = 'ai-status-indicator connected'; text.textContent = 'Connected'; } else if (status === 'downloading') { indicator.className = 'ai-status-indicator downloading'; text.textContent = 'Downloading Model'; } else if (status === 'serving') { indicator.className = 'ai-status-indicator serving'; text.textContent = 'Running Model'; } else { indicator.className = 'ai-status-indicator disconnected'; text.textContent = 'Disconnected'; } ns.events.emit('ui:status:changed', { status }); eventHandler.emit('ui:status:changed', { status }); } function showDownloadProgress() { let progressDiv = document.getElementById('aiDownloadProgress'); if (!progressDiv) { progressDiv = document.createElement('div'); progressDiv.id = 'aiDownloadProgress'; progressDiv.className = 'ai-download-progress'; progressDiv.innerHTML = ` <div style="color: #ff00ff; font-weight: bold; margin-bottom: 5px;" id="aiDownloadStatus">Initializing download...</div> <div class="ai-progress-bar"> <div class="ai-progress-fill" id="aiProgressFill" style="width: 0%">0%</div> </div> `; const connectionPanel = document.querySelectorAll('.ai-terminal-panel')[1]; connectionPanel.appendChild(progressDiv); } } function updateDownloadProgress(percent, status) { const progressFill = document.getElementById('aiProgressFill'); const statusText = document.getElementById('aiDownloadStatus'); if (progressFill) { progressFill.style.width = `${percent}%`; progressFill.textContent = `${percent}%`; } if (statusText) { statusText.textContent = status || `Downloading: ${percent}%`; } } function hideDownloadProgress() { const progressDiv = document.getElementById('aiDownloadProgress'); if (progressDiv) { setTimeout(() => progressDiv.remove(), 2000); } } function showServeInstructions() { let instructDiv = document.getElementById('aiServeInstructions'); if (!instructDiv) { instructDiv = document.createElement('div'); instructDiv.id = 'aiServeInstructions'; instructDiv.className = 'ai-serve-instructions'; instructDiv.innerHTML = ` <strong>⚠️ Ollama Not Running</strong><br> To use this terminal, start Ollama first:<br> 1. Open terminal/command prompt<br> 2. Run: <code>ollama serve</code><br> 3. Then click "Test Connection" above `; const connectionPanel = document.querySelectorAll('.ai-terminal-panel')[1]; connectionPanel.appendChild(instructDiv); } } function hideServeInstructions() { const instructDiv = document.getElementById('aiServeInstructions'); if (instructDiv) { instructDiv.remove(); } } function updateQueueDisplay() { const stats = queueInstance.getStats(); const items = queueInstance.getAllItems(); document.getElementById('aiQueuedCount').textContent = stats.queued; document.getElementById('aiProcessingCount').textContent = stats.processing; document.getElementById('aiCompletedCount').textContent = stats.completed; ns.events.emit('ui:queue:stats', stats); const display = document.getElementById('aiQueueDisplay'); if (stats.queued === 0 && stats.processing === 0) { display.innerHTML = '<div style="color: #666; text-align: center; padding: 20px;">Queue is empty</div>'; return; } display.innerHTML = ''; items.processing.forEach(item => { const div = document.createElement('div'); div.className = 'ai-queue-item processing'; div.innerHTML = `⚡ ${item.metadata.name || 'Task'} <span style="color: #ffff00;">(Processing)</span>`; display.appendChild(div); }); items.queue.forEach(item => { const div = document.createElement('div'); div.className = 'ai-queue-item'; div.innerHTML = `⏳ ${item.metadata.name || 'Task'} <span style="color: #888;">(${item.delay}ms)</span>`; display.appendChild(div); }); } function updateEventDisplay() { const display = document.getElementById('aiEventDisplay'); const stats = eventHandler.getStats(); const history = eventHandler.getHistory(10); document.getElementById('aiEventHandlerCount').textContent = stats.totalHandlers; document.getElementById('aiEventTypeCount').textContent = stats.eventTypes; document.getElementById('aiEventHistoryCount').textContent = history.length; display.innerHTML = ''; history.reverse().forEach(event => { const div = document.createElement('div'); div.className = 'ai-event-item'; const time = new Date(event.timestamp).toLocaleTimeString(); div.innerHTML = `<span class="ai-event-name">${event.event}</span> <span class="ai-event-time">[${time}]</span><br><small>${event.data}</small>`; display.appendChild(div); }); } // ============ EVENT LISTENERS ============ function setupEventListeners() { // Log all events to terminal eventHandler.use(async (eventData) => { logger.log(`EVENT: ${eventData.name}`, 'event'); updateEventDisplay(); }); // Register default handlers eventHandler.register('ollama:connected', (data) => { logger.log(`✓ Connected to Ollama: ${data.url}`, 'zircuitry'); }, { priority: 10 }); eventHandler.register('ollama:connection:error', (data) => { logger.log(`✗ Make sure to run: ollama serve`, 'warning'); }, { priority: 10 }); eventHandler.register('queue:add', (data) => { logger.log(`✓ Task added to queue: ${data.metadata.name}`, 'info'); }); eventHandler.register('queue:item:complete', (data) => { logger.log(`✓ Task completed: ${data.metadata.name}`, 'success'); }); eventHandler.register('probe:system', (data) => { logger.log(`✓ System probe complete at ${data.timestamp}`, 'probe'); }); // Model download handlers eventHandler.register('model:download:start', (data) => { logger.log(`✓ Starting download: ${data.model}`, 'zircuitry'); }, { priority: 10 }); eventHandler.register('model:download:complete', (data) => { logger.log(`✓ Download complete: ${data.model}`, 'zircuitry'); }, { priority: 10 }); eventHandler.register('model:download:error', (data) => { logger.log(`✗ Download failed: ${data.error}`, 'error'); }, { priority: 10 }); eventHandler.register('model:ready', (data) => { logger.log(`✓ Model ready: ${data.model}`, 'success'); }); // Model run handlers eventHandler.register('model:run:start', (data) => { logger.log(`✓ Loading model: ${data.model}`, 'serve'); }, { priority: 10 }); eventHandler.register('model:run:complete', (data) => { logger.log(`✓ Model running: ${data.model}`, 'serve'); }, { priority: 10 }); eventHandler.register('model:run:error', (data) => { logger.log(`✗ Model run failed: ${data.error}`, 'error'); }, { priority: 10 }); } // ============ INITIALIZATION ============ let queueInstance; let ollamaClient; let lastAIResponse = ''; document.head.appendChild(createStyles()); const container = document.createElement('div'); container.className = 'ai-terminal-container'; container.innerHTML = ` <button class="ai-close-btn" onclick="window.terminal.destroy()">✕ Close Terminal</button> <div class="ai-terminal-inner"> <h1>⚡ AI CONTROL TERMINAL ⚡</h1> <div class="ai-terminal-panel" style="margin-bottom: 20px;"> <h2>Event Handler System</h2> <div class="ai-terminal-stats"> <div class="ai-stat-item"> <div class="ai-stat-value" id="aiEventHandlerCount">0</div> <div class="ai-stat-label">Handlers</div> </div> <div class="ai-stat-item"> <div class="ai-stat-value" id="aiEventTypeCount">0</div> <div class="ai-stat-label">Event Types</div> </div> <div class="ai-stat-item"> <div class="ai-stat-value" id="aiEventHistoryCount">0</div> <div class="ai-stat-label">History</div> </div> </div> <div style="margin-top: 15px;"> <button onclick="window.aiTerminal.showEventStats()">Show Stats</button> <button onclick="window.aiTerminal.clearEventHistory()">Clear History</button> <button onclick="window.aiTerminal.testEventHandler()">Test Events</button> </div> <div id="aiEventDisplay" style="max-height: 200px; overflow-y: auto; margin-top: 15px; background: rgba(0,0,0,0.5); padding: 10px; border-radius: 5px;"> <div style="color: #666; text-align: center;">No events yet</div> </div> </div> <div class="ai-terminal-grid"> <div class="ai-terminal-panel"> <h2>Ollama Connection</h2> <div class="ai-terminal-input-group"> <label>Server URL:</label> <input type="text" id="aiOllamaUrl" value="http://localhost:11434"> </div> <div class="ai-terminal-input-group"> <label>Model Name:</label> <input type="text" id="aiModelName" value="Zircuitry/Zircuitry:latest"> </div> <div class="ai-terminal-input-group"> <label>Status: <span class="ai-status-indicator disconnected" id="aiStatusIndicator"></span><span id="aiStatusText">Disconnected</span></label> </div> <button onclick="window.aiTerminal.testConnection()">Test Connection</button> <button onclick="window.aiTerminal.connect()" class="zircuitry-btn">Connect & Setup</button> <button onclick="window.aiTerminal.downloadModel()" class="zircuitry-btn">Download Model</button> <button onclick="window.aiTerminal.runModel()" class="zircuitry-btn">Run Model</button> </div> <div class="ai-terminal-panel"> <h2>Queue Settings</h2> <div class="ai-terminal-input-group"> <label>Default Delay (ms):</label> <input type="number" id="aiDefaultDelay" value="1000" min="0"> </div> <div class="ai-terminal-input-group"> <label>Max Concurrent:</label> <input type="number" id="aiMaxConcurrent" value="3" min="1" max="10"> </div> <button onclick="window.aiTerminal.updateSettings()">Update Settings</button> <button onclick="window.aiTerminal.clearQueue()">Clear Queue</button> </div> </div> <div class="ai-terminal-grid"> <div class="ai-terminal-panel"> <h2>Queue Status</h2> <div id="aiQueueDisplay" style="max-height: 250px; overflow-y: auto;"> <div style="color: #666; text-align: center; padding: 20px;">Queue is empty</div> </div> <div class="ai-terminal-stats"> <div class="ai-stat-item"> <div class="ai-stat-value" id="aiQueuedCount">0</div> <div class="ai-stat-label">Queued</div> </div> <div class="ai-stat-item"> <div class="ai-stat-value" id="aiProcessingCount">0</div> <div class="ai-stat-label">Processing</div> </div> <div class="ai-stat-item"> <div class="ai-stat-value" id="aiCompletedCount">0</div> <div class="ai-stat-label">Completed</div> </div> </div> </div> <div class="ai-terminal-panel"> <h2>Send Prompt</h2> <div class="ai-terminal-input-group"> <label>Prompt:</label> <textarea id="aiUserPrompt">Hello! Tell me a short joke.</textarea> </div> <div class="ai-terminal-input-group"> <label>Delay (ms):</label> <input type="number" id="aiPromptDelay" value="0" min="0"> </div> <button onclick="window.aiTerminal.send()">Send Now</button> <button onclick="window.aiTerminal.queue()">Add to Queue</button> <div id="aiResponseContainer"></div> </div> </div> <div class="ai-terminal-panel" style="grid-column: 1 / -1;"> <h2>System Diagnostics</h2> <button onclick="window.aiTerminal.probeSystem()">Full System Probe</button> <button onclick="window.aiTerminal.probeBrowser()">Browser Info</button> <button onclick="window.aiTerminal.checkOllamaServe()">Check Ollama Status</button> </div> <div class="ai-terminal-panel" style="grid-column: 1 / -1;"> <h2>Terminal Output</h2> <div class="ai-terminal-output" id="aiTerminalOutput"></div> <button onclick="window.aiTerminal.clearTerminal()">Clear</button> </div> </div> `; document.body.appendChild(container); // Initialize logger logger = new Logger('aiTerminalOutput'); // Initialize event handler eventHandler = new EventHandler(); // Initialize queue queueInstance = new DelayedCallQueue(); ns.sf.DelayedCallQueue = queueInstance; // Setup event listeners setupEventListeners(); // Main AI Terminal API window.aiTerminal = { testConnection: async function() { const url = document.getElementById('aiOllamaUrl').value; const model = document.getElementById('aiModelName').value; ollamaClient = new OllamaClient(url, model); await ollamaClient.testConnection(); }, connect: async function() { const url = document.getElementById('aiOllamaUrl').value; const model = document.getElementById('aiModelName').value; ollamaClient = new OllamaClient(url, model); const connected = await ollamaClient.testConnection(); if (connected) { logger.log(`Connected to ${url} with model: ${model}`, 'success'); await ollamaClient.ensureModelReady(); await ollamaClient.runModel(); } }, downloadModel: async function() { if (!ollamaClient) { const url = document.getElementById('aiOllamaUrl').value; const model = document.getElementById('aiModelName').value; ollamaClient = new OllamaClient(url, model); const connected = await ollamaClient.testConnection(); if (!connected) { logger.log('Cannot download: Ollama not running', 'error'); return; } } await ollamaClient.downloadModel(); }, runModel: async function() { if (!ollamaClient) { logger.log('Please connect first', 'error'); return; } await ollamaClient.runModel(); }, checkOllamaServe: async function() { logger.log('═══════════════════════════════════════', 'serve'); logger.log('CHECKING OLLAMA SERVER', 'serve'); logger.log('═══════════════════════════════════════', 'serve'); const url = document.getElementById('aiOllamaUrl').value; try { const response = await fetch(`${url}/api/tags`, { method: 'GET' }); if (response.ok) { const data = await response.json(); logger.log('✓ Ollama server is running!', 'success'); logger.log(`✓ Available models: ${data.models?.length || 0}`, 'info'); if (data.models && data.models.length > 0) { data.models.forEach(m => { logger.log(` - ${m.name}`, 'info'); }); } ns.events.emit('ollama:serve:running', { models: data.models }); eventHandler.emit('ollama:serve:running', { models: data.models }); } else { throw new Error('Server error'); } } catch (error) { logger.log('✗ Ollama server is NOT running', 'error'); logger.log('Start it with: ollama serve', 'warning'); ns.events.emit('ollama:serve:not_running', {}); eventHandler.emit('ollama:serve:not_running', {}); } logger.log('═══════════════════════════════════════', 'serve'); }, updateSettings: function() { const delay = parseInt(document.getElementById('aiDefaultDelay').value); const concurrent = parseInt(document.getElementById('aiMaxConcurrent').value); queueInstance = new DelayedCallQueue({ defaultDelay: delay, maxConcurrent: concurrent, retryFailed: true }); ns.sf.DelayedCallQueue = queueInstance; logger.log(`Settings updated: ${delay}ms delay, ${concurrent} concurrent`, 'success'); ns.events.emit('queue:settings:updated', { delay, concurrent }); eventHandler.emit('queue:settings:updated', { delay, concurrent }); }, clearQueue: () => queueInstance.clear(), probeBrowser: () => ProbeSystem.probeBrowser(), probeSystem: async function() { await ProbeSystem.probeSystem(); }, send: async function() { const prompt = document.getElementById('aiUserPrompt').value; const delay = parseInt(document.getElementById('aiPromptDelay').value); if (!prompt) { logger.log('Please enter a prompt', 'warning'); return; } if (!ollamaClient?.connected) { logger.log('Not connected to Ollama server', 'error'); return; } if (delay > 0) { logger.log(`Waiting ${delay}ms before sending...`, 'info'); await new Promise(resolve => setTimeout(resolve, delay)); } try { const response = await ollamaClient.generate(prompt); lastAIResponse = response; const container = document.getElementById('aiResponseContainer'); container.innerHTML = `<div class="ai-response-box">${response}</div>`; ns.events.emit('ai:response:received', { prompt, response: response.substring(0, 100) }); eventHandler.emit('ai:response:received', { prompt, response: response.substring(0, 100) }); } catch (error) { logger.log(`Error: ${error.message}`, 'error'); } }, queue: function() { const prompt = document.getElementById('aiUserPrompt').value; const delay = parseInt(document.getElementById('aiPromptDelay').value); if (!prompt) { logger.log('Please enter a prompt', 'warning'); return; } queueInstance.add( () => this.send(), delay, { name: `Prompt: ${prompt.substring(0, 20)}...` } ); }, clearTerminal: () => logger.clear(), // Event Handler methods showEventStats: function() { const stats = eventHandler.getStats(); logger.log('═══════════════════════════════════════', 'event'); logger.log('EVENT HANDLER STATISTICS', 'event'); logger.log('═══════════════════════════════════════', 'event'); logger.log(`Total Handlers: ${stats.totalHandlers}`, 'info'); logger.log(`Event Types: ${stats.eventTypes}`, 'info'); stats.events.forEach(e => { logger.log(` ${e.event}: ${e.handlers} handlers (${e.enabled} enabled)`, 'info'); }); logger.log('═══════════════════════════════════════', 'event'); }, clearEventHistory: function() { eventHandler.eventHistory = []; logger.log('Event history cleared', 'warning'); updateEventDisplay(); }, testEventHandler: async function() { logger.log('Testing event handler system...', 'event'); await eventHandler.emit('test:basic', { message: 'Basic test' }); eventHandler.register('test:priority', (data) => { logger.log(`Priority handler: ${data.message}`, 'success'); }, { priority: 100 }); await eventHandler.emit('test:priority', { message: 'High priority test' }); eventHandler.register('test:once', (data) => { logger.log(`Once handler: ${data.message}`, 'success'); }, { once: true }); await eventHandler.emit('test:once', { message: 'First call' }); await eventHandler.emit('test:once', { message: 'Second call (should not trigger)' }); logger.log('Event handler tests complete', 'event'); }, // Expose event handler API on: (event, handler, options) => eventHandler.register(event, handler, options), off: (event, handlerId) => eventHandler.unregister(event, handlerId), emit: (event, data) => eventHandler.emit(event, data), destroy: function() { ns.events.emit('terminal:destroyed', {}); eventHandler.emit('terminal:destroyed', {}); container.remove(); window.aiTerminal = null; }, getState: function() { return { connected: ollamaClient?.connected || false, queueStats: queueInstance.getStats(), eventStats: eventHandler.getStats(), lastResponse: lastAIResponse, ollamaUrl: document.getElementById('aiOllamaUrl').value, modelName: document.getElementById('aiModelName').value, isDownloading: ollamaClient?.isDownloading || false, isServing: ollamaClient?.isServing || false }; } }; window.terminal = { destroy: () => window.aiTerminal.destroy() }; // Expose event handler globally window.eventHandler = eventHandler; logger.log('═══════════════════════════════════════', 'zircuitry'); logger.log('AI CONTROL TERMINAL INITIALIZED', 'zircuitry'); logger.log('═══════════════════════════════════════', 'zircuitry'); logger.log('✓ Event handler system active', 'success'); logger.log('✓ Queue system ready', 'success'); logger.log('✓ Probe systems integrated', 'success'); logger.log('✓ Ollama client configured', 'success'); logger.log('✓ Auto-download system ready', 'success'); logger.log('✓ Model run system ready', 'success'); logger.log(`✓ Default model: ${ns.config.DEFAULT_MODEL}`, 'zircuitry'); logger.log('═══════════════════════════════════════', 'zircuitry'); logger.log('QUICK START GUIDE:', 'warning'); logger.log('1. Run in terminal: ollama serve', 'info'); logger.log('2. Click "Test Connection"', 'info'); logger.log('3. Click "Connect & Setup" (auto-downloads Zircuitry)', 'info'); logger.log('4. Send prompts and enjoy!', 'info'); logger.log('═══════════════════════════════════════', 'zircuitry'); logger.log('All systems operational', 'zircuitry'); ns.events.emit('terminal:initialized', { timestamp: new Date().toISOString(), version: '2.3.0-complete' }); eventHandler.emit('terminal:initialized', { timestamp: new Date().toISOString(), version: '2.3.0-complete' }); updateEventDisplay(); })();
Optional Paste Settings
Category:
None
Cryptocurrency
Cybersecurity
Fixit
Food
Gaming
Haiku
Help
History
Housing
Jokes
Legal
Money
Movies
Music
Pets
Photo
Science
Software
Source Code
Spirit
Sports
Travel
TV
Writing
Tags:
Syntax Highlighting:
None
Bash
C
C#
C++
CSS
HTML
JSON
Java
JavaScript
Lua
Markdown (PRO members only)
Objective C
PHP
Perl
Python
Ruby
Swift
4CS
6502 ACME Cross Assembler
6502 Kick Assembler
6502 TASM/64TASS
ABAP
AIMMS
ALGOL 68
APT Sources
ARM
ASM (NASM)
ASP
ActionScript
ActionScript 3
Ada
Apache Log
AppleScript
Arduino
Asymptote
AutoIt
Autohotkey
Avisynth
Awk
BASCOM AVR
BNF
BOO
Bash
Basic4GL
Batch
BibTeX
Blitz Basic
Blitz3D
BlitzMax
BrainFuck
C
C (WinAPI)
C Intermediate Language
C for Macs
C#
C++
C++ (WinAPI)
C++ (with Qt extensions)
C: Loadrunner
CAD DCL
CAD Lisp
CFDG
CMake
COBOL
CSS
Ceylon
ChaiScript
Chapel
Clojure
Clone C
Clone C++
CoffeeScript
ColdFusion
Cuesheet
D
DCL
DCPU-16
DCS
DIV
DOT
Dart
Delphi
Delphi Prism (Oxygene)
Diff
E
ECMAScript
EPC
Easytrieve
Eiffel
Email
Erlang
Euphoria
F#
FO Language
Falcon
Filemaker
Formula One
Fortran
FreeBasic
FreeSWITCH
GAMBAS
GDB
GDScript
Game Maker
Genero
Genie
GetText
Go
Godot GLSL
Groovy
GwBasic
HQ9 Plus
HTML
HTML 5
Haskell
Haxe
HicEst
IDL
INI file
INTERCAL
IO
ISPF Panel Definition
Icon
Inno Script
J
JCL
JSON
Java
Java 5
JavaScript
Julia
KSP (Kontakt Script)
KiXtart
Kotlin
LDIF
LLVM
LOL Code
LScript
Latex
Liberty BASIC
Linden Scripting
Lisp
Loco Basic
Logtalk
Lotus Formulas
Lotus Script
Lua
M68000 Assembler
MIX Assembler
MK-61/52
MPASM
MXML
MagikSF
Make
MapBasic
Markdown (PRO members only)
MatLab
Mercury
MetaPost
Modula 2
Modula 3
Motorola 68000 HiSoft Dev
MySQL
Nagios
NetRexx
Nginx
Nim
NullSoft Installer
OCaml
OCaml Brief
Oberon 2
Objeck Programming Langua
Objective C
Octave
Open Object Rexx
OpenBSD PACKET FILTER
OpenGL Shading
Openoffice BASIC
Oracle 11
Oracle 8
Oz
PARI/GP
PCRE
PHP
PHP Brief
PL/I
PL/SQL
POV-Ray
ParaSail
Pascal
Pawn
Per
Perl
Perl 6
Phix
Pic 16
Pike
Pixel Bender
PostScript
PostgreSQL
PowerBuilder
PowerShell
ProFTPd
Progress
Prolog
Properties
ProvideX
Puppet
PureBasic
PyCon
Python
Python for S60
QBasic
QML
R
RBScript
REBOL
REG
RPM Spec
Racket
Rails
Rexx
Robots
Roff Manpage
Ruby
Ruby Gnuplot
Rust
SAS
SCL
SPARK
SPARQL
SQF
SQL
SSH Config
Scala
Scheme
Scilab
SdlBasic
Smalltalk
Smarty
StandardML
StoneScript
SuperCollider
Swift
SystemVerilog
T-SQL
TCL
TeXgraph
Tera Term
TypeScript
TypoScript
UPC
Unicon
UnrealScript
Urbi
VB.NET
VBScript
VHDL
VIM
Vala
Vedit
VeriLog
Visual Pro Log
VisualBasic
VisualFoxPro
WHOIS
WhiteSpace
Winbatch
XBasic
XML
XPP
Xojo
Xorg Config
YAML
YARA
Z80 Assembler
ZXBasic
autoconf
jQuery
mIRC
newLISP
q/kdb+
thinBasic
Paste Expiration:
Never
Burn after read
10 Minutes
1 Hour
1 Day
1 Week
2 Weeks
1 Month
6 Months
1 Year
Paste Exposure:
Public
Unlisted
Private
Folder:
(members only)
Password
NEW
Enabled
Disabled
Burn after read
NEW
Paste Name / Title:
Create New Paste
Hello
Guest
Sign Up
or
Login
Sign in with Facebook
Sign in with Twitter
Sign in with Google
You are currently not logged in, this means you can not edit or delete anything you paste.
Sign Up
or
Login
Public Pastes
API-Flaw Profit Guide
CSS | 15 min ago | 0.99 KB
This month smells like profit
CSS | 21 min ago | 0.99 KB
Schrödinger's Crit
1 day ago | 15.37 KB
PRCE internal cursor
2 days ago | 0.73 KB
AI Interaction Method
2 days ago | 1.60 KB
awkwrapper.c
C | 2 days ago | 2.35 KB
z66is_archive.zip.txt
2 days ago | 39.19 KB
Clients: Setting up 2FA
3 days ago | 1.44 KB
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the
Cookies Policy
.
OK, I Understand
Not a member of Pastebin yet?
Sign Up
, it unlocks many cool features!