SOLE Network GodKode kAIxu Engine • Media • Sandbox
kAIxu Logo
kAIxu Engine
Checking status…
kAIxu: Environment initialized on the SOLE Network. Ready to write code and process media. What are we building today?
workspace/main.js
Sandbox Run (Node-style JS)

                
            
Media Jobs (FFmpeg.wasm)
`; frame.setAttribute('sandbox', 'allow-scripts'); frame.srcdoc = html; frame.dataset.initialized = '1'; } function appendSandboxLine(text, kind = 'log') { const out = document.getElementById('sandbox-output'); if (!out) return; const prefix = kind === 'error' ? '[ERR] ' : (kind === 'status' ? '[*] ' : ''); out.textContent += (prefix + text + '\n'); out.scrollTop = out.scrollHeight; } function clearSandboxOutput() { const out = document.getElementById('sandbox-output'); if (out) out.textContent = ''; } function runSandboxJob(code) { if (!featureSandbox) { appendSandboxLine('Sandbox feature disabled by tenant policy', 'status'); broadcastLog('Sandbox run blocked by feature flag', 'sandbox_run'); return; } initSandboxFrame(); const frame = document.getElementById('sandbox-frame'); if (!frame || !frame.contentWindow) { appendSandboxLine('Sandbox frame unavailable', 'error'); return; } appendSandboxLine('--- run_node_script ---', 'status'); broadcastLog('Sandbox run started', 'sandbox_run'); const timeoutMs = 5000; const timeoutId = setTimeout(() => { appendSandboxLine('Sandbox timeout reached (' + timeoutMs + 'ms)', 'error'); broadcastLog('Sandbox run timed out', 'sandbox_run'); }, timeoutMs); try { frame.contentWindow.runUserCode(code); } catch (e) { appendSandboxLine(e && e.message ? e.message : String(e), 'error'); clearTimeout(timeoutId); broadcastLog('Sandbox run error: ' + (e && e.message ? e.message : String(e)), 'sandbox_run'); } } window.addEventListener('message', (event) => { if (!event || !event.data || event.data.source !== 'GodKodeSandbox') return; const { type, msg } = event.data; if (type === 'log') appendSandboxLine(msg, 'log'); else if (type === 'error') { appendSandboxLine(msg, 'error'); broadcastLog('Sandbox script error: ' + msg, 'sandbox_run'); } else if (type === 'status') appendSandboxLine(msg, 'status'); }); async function runSelfCheck() { broadcastLog('Self-check started', 'self_check'); const results = []; results.push(`online=${navigator.onLine}`); const key = localStorage.getItem('KAIXU_VIRTUAL_KEY') || ''; results.push(`key_present=${key ? 'yes' : 'no'}`); try { const r = await fetch('/api/kaixu-key', { signal: AbortSignal.timeout(5000) }); results.push(`server=${r.ok ? 'UP' : 'ERR(' + r.status + ')'}`); } catch (e) { results.push('server=DOWN'); } appendDebugLine('Self-check: ' + results.join(' | '), 'warn'); broadcastLog('Self-check completed: ' + results.join(' | '), 'self_check'); } async function ensureFfmpegLoaded() { if (ffmpegInstance) return ffmpegInstance; if (ffmpegLoading) { // naive wait loop while (ffmpegLoading && !ffmpegInstance) { await new Promise(r => setTimeout(r, 200)); } return ffmpegInstance; } ffmpegLoading = true; try { const FF = window.FFmpeg || {}; const createFFmpeg = FF.createFFmpeg; const fetchFile = FF.fetchFile; if (!createFFmpeg || !fetchFile) { broadcastLog('FFmpeg.wasm not available in this context', 'media_job'); ffmpegLoading = false; return null; } const corePath = 'https://unpkg.com/@ffmpeg/core@0.12.10/dist/ffmpeg-core.js'; const ff = createFFmpeg({ corePath, log: false }); await ff.load(); ffmpegInstance = { ff, fetchFile }; broadcastLog('FFmpeg.wasm loaded', 'media_job'); return ffmpegInstance; } catch (e) { broadcastLog('Failed to load FFmpeg.wasm: ' + (e && e.message ? e.message : String(e)), 'media_job'); ffmpegLoading = false; return null; } finally { ffmpegLoading = false; } } function appendMediaJobLine(text) { const box = document.getElementById('media-jobs'); if (!box) return; const line = document.createElement('div'); line.className = 'text-[11px] text-gray-200'; line.innerHTML = text; box.appendChild(line); box.scrollTop = box.scrollHeight; } async function runFfmpegCommand(inputFile, mode) { const instance = await ensureFfmpegLoaded(); if (!instance) return; const { ff, fetchFile } = instance; try { const data = await fetchFile(inputFile); ff.FS('writeFile', 'input', data); let args; let outputName; if (mode === 'extract_audio') { outputName = 'output.mp3'; args = ['-i', 'input', '-vn', '-acodec', 'copy', outputName]; } else { outputName = 'output.mp4'; args = ['-i', 'input', '-c', 'copy', outputName]; } appendMediaJobLine(`[*] Running FFmpeg (${mode}) on ${inputFile.name}...`); await ff.run(...args); const outData = ff.FS('readFile', outputName); const blob = new Blob([outData.buffer], { type: mode === 'extract_audio' ? 'audio/mpeg' : 'video/mp4' }); const url = URL.createObjectURL(blob); const linkHtml = `Download ${outputName}`; appendMediaJobLine(linkHtml); broadcastLog('Media job completed via FFmpeg.wasm', 'media_job'); } catch (e) { appendMediaJobLine(`[ERR] FFmpeg job failed: ${(e && e.message) ? e.message : String(e)}`); broadcastLog('FFmpeg job failed: ' + (e && e.message ? e.message : String(e)), 'media_job'); } } function enqueueMediaJob(label, file, mode) { appendMediaJobLine(label); broadcastLog('Media job queued: ' + label, 'media_job'); runFfmpegCommand(file, mode); } function extractToolsAndStrip(markdown) { const regex = /```kAIxu-tools\s*([\s\S]*?)```/i; const match = regex.exec(markdown); if (!match) return { text: markdown, calls: [] }; const jsonText = match[1].trim(); let calls = []; try { const parsed = JSON.parse(jsonText); if (Array.isArray(parsed)) calls = parsed; } catch (e) { broadcastLog(`Failed to parse kAIxu-tools JSON: ${e.message}`, 'error'); } const cleaned = markdown.replace(regex, '').trim(); return { text: cleaned, calls }; } function runToolCalls(calls) { if (!Array.isArray(calls) || !calls.length) return; for (const call of calls) { if (!call || typeof call !== 'object') continue; const name = call.tool || call.name; const args = call.args || call.arguments || {}; try { if (name === 'write_to_editor') { if (window.editor && typeof args.code === 'string') { window.editor.setValue(args.code); broadcastLog('Tool write_to_editor applied to Monaco', 'tool_call'); } } else if (name === 'append_to_editor') { if (window.editor && typeof args.code === 'string') { const existing = window.editor.getValue() || ''; window.editor.setValue(existing + '\n' + args.code); broadcastLog('Tool append_to_editor appended to Monaco', 'tool_call'); } } else if (name === 'set_editor_language') { if (window.editor && typeof args.language === 'string' && window.monaco && window.monaco.editor) { const model = window.editor.getModel(); if (model) window.monaco.editor.setModelLanguage(model, args.language); broadcastLog(`Tool set_editor_language → ${args.language}`, 'tool_call'); } } else if (name === 'run_node_script') { const code = typeof args.code === 'string' ? args.code : ''; if (!code) { broadcastLog('run_node_script tool called without code', 'tool_call'); } else { broadcastLog('run_node_script requested (sandbox will handle this)', 'tool_call'); runSandboxJob(code); } } else if (name === 'transform_media_basic') { if (!featureMedia) { broadcastLog('transform_media_basic blocked by feature flag', 'media_job'); } else { const videoAtt = currentAttachments.find(a => a.kind === 'video'); if (!videoAtt) { broadcastLog('transform_media_basic: no video attachment available', 'media_job'); } else { const mode = args.mode || 'extract_audio'; enqueueMediaJob(`Media: ${mode} on ${videoAtt.file.name}`, videoAtt.file, mode); } } } else { broadcastLog(`Unknown kAIxu tool: ${name}`, 'tool_call'); } } catch (e) { broadcastLog(`Error running tool ${name}: ${e.message}`, 'tool_call'); } } } function persistProjectState() { try { if (!window.editor) return; const key = `GODKODE_PROJECT_${currentProjectId}`; const state = { editor: window.editor.getValue(), conversation, }; localStorage.setItem(key, JSON.stringify(state)); } catch (e) { broadcastLog('Failed to persist project state: ' + e.message, 'error'); } } function loadProjectState(projectId) { currentProjectId = projectId || 'default'; localStorage.setItem('GODKODE_PROJECT_ID', currentProjectId); try { const key = `GODKODE_PROJECT_${currentProjectId}`; const raw = localStorage.getItem(key); if (!raw) { conversation = []; if (window.editor) window.editor.setValue('// New GodKode project\n'); return; } const parsed = JSON.parse(raw); conversation = Array.isArray(parsed.conversation) ? parsed.conversation : []; if (window.editor && typeof parsed.editor === 'string') { window.editor.setValue(parsed.editor); } broadcastLog(`Loaded project state for ${currentProjectId}`, 'self_check'); } catch (e) { broadcastLog('Failed to load project state: ' + e.message, 'error'); } } window.switchProject = (projectId) => { loadProjectState(projectId || 'default'); }; async function sendCommand() { const input = document.getElementById('prompt-input'); const chat = document.getElementById('chat-window'); const engineStatus = document.getElementById('engine-status'); const sendBtn = document.getElementById('send-btn'); if (isStreaming) return; const storedKey = localStorage.getItem('KAIXU_VIRTUAL_KEY') || ''; if (!storedKey) { showErrorBanner('No KAIXU_VIRTUAL_KEY configured. Open kAIxu Config (cog) to add your key.'); toggleSettings(); return; } if (!navigator.onLine) { showErrorBanner('You appear to be offline. Reconnect to SOLE Network and try again.'); return; } clearErrorBanner(); const prompt = input.value.trim(); if (!prompt) return; const attachmentContext = await buildAttachmentContext(); // User Message chat.innerHTML += `
You: ${prompt}
`; // Attachment summary message (if any files were attached) if (currentAttachments.length) { const names = currentAttachments.map(a => a.file.name).join(', '); chat.innerHTML += `
System: Context from files used this turn: ${names}
`; broadcastLog(`Using attachment files for this turn: ${names}`, 'info'); } input.value = ''; chat.scrollTop = chat.scrollHeight; // Prepare kAIxu Message const aiMsgDiv = document.createElement('div'); aiMsgDiv.className = "bg-royal bg-opacity-30 p-3 rounded-lg border border-royal text-sm mr-8"; aiMsgDiv.innerHTML = `kAIxu: Thinking...`; chat.appendChild(aiMsgDiv); const contentSpan = aiMsgDiv.querySelector('.ai-content'); engineStatus.classList.remove('hidden'); sendBtn.disabled = true; isStreaming = true; let fullReply = ''; try { const userContent = attachmentContext ? `Attached context from user files (summarized):\n${attachmentContext}\n\nUser request:\n${prompt}` : redactPrompt(prompt); await kaixuStreamChat({ provider: 'gemini', model: 'gemini-2.0-flash', messages: [ { role: 'system', content: 'You are kAIxu, a highly advanced AI engineer operating on the SOLE Network. You help the user build GodKode. When context files are provided, carefully use their content. Output code in markdown blocks if requested. When appropriate, after your natural language answer, emit a fenced code block labeled ```kAIxu-tools containing a JSON array of tool calls for this IDE. Each item should be of the form {"tool": "write_to_editor" | "append_to_editor" | "set_editor_language" | "run_node_script" | "transform_media_basic", "args": { ... }}. Only include this block when a concrete editor or sandbox/media action is helpful.' }, ...conversation, { role: 'user', content: userContent } ], max_tokens: 8192, temperature: 0.7 }, { onDelta: (text) => { fullReply += text; contentSpan.innerHTML = marked.parse(fullReply); chat.scrollTop = chat.scrollHeight; }, onDone: (data) => { const extracted = extractToolsAndStrip(fullReply); const cleanReply = extracted.text; const toolCalls = extracted.calls || []; fullReply = cleanReply; contentSpan.innerHTML = marked.parse(cleanReply); Prism.highlightAllUnder(aiMsgDiv); conversation.push({ role: 'user', content: prompt }); conversation.push({ role: 'assistant', content: cleanReply }); const usage = data.usage || {}; const month = data.month || {}; const inTokens = usage.input_tokens || 0; const outTokens = usage.output_tokens || 0; broadcastLog(`Stream complete. in=${inTokens} out=${outTokens}`, 'success'); if (month.cap_cents != null && month.spent_cents != null) { const remaining = ((month.cap_cents - month.spent_cents) / 100).toFixed(2); broadcastLog(`Budget remaining: $${remaining}`, 'info'); } persistProjectState(); if (toolCalls.length) { broadcastLog(`Executing ${toolCalls.length} kAIxu tool call(s)`, 'info'); runToolCalls(toolCalls); } }, onError: (err) => { showErrorBanner(err.message); } }); } catch (err) { contentSpan.innerHTML = `Error: ${err.message}`; broadcastLog(`Stream error: ${err.message}`, 'error'); } finally { engineStatus.classList.add('hidden'); sendBtn.disabled = false; isStreaming = false; chat.scrollTop = chat.scrollHeight; currentAttachments = []; renderAttachments(); } } // Minting & Export Logic function triggerMint() { const chat = document.getElementById('chat-window'); const soleHub = document.getElementById('sole-hub'); const glowStatus = document.getElementById('glow-status'); // 1. User clicks Mint chat.innerHTML += `
System: [Mint Initiated]
`; // 2. SOLE Hub appears soleHub.classList.remove('hidden'); // 3. kAIxu takes over the export to the Glow Room setTimeout(() => { chat.innerHTML += `
kAIxu: I am routing the export directly to the Glow Room for inspection. Standby.
`; chat.scrollTop = chat.scrollHeight; glowStatus.innerHTML = "kAIxu AI Inspecting code integrity..."; setTimeout(() => { glowStatus.innerHTML = "Inspection Passed. Asset is polished and secure."; broadcastLog('Mint inspection passed', 'success'); }, 2000); }, 1000); } // Handle Enter key document.getElementById('prompt-input').addEventListener('keypress', (e) => { if (e.key === 'Enter') sendCommand(); }); // Handle attachment selection const fileUploadInput = document.getElementById('file-upload'); if (fileUploadInput) { fileUploadInput.addEventListener('change', handleFileSelection); }