+++ index.html (修改后) ابرهوش کوکب // ==================== AGENT 1: UI/UX Architect ==================== const UIAgent={particles:[],canvas:null,ctx:null,init(){this.initParticles();this.animateParticles();this.loadSettings();this.renderTools();},initParticles(){this.canvas=document.getElementById('particle-canvas');this.ctx=this.canvas.getContext('2d');this.resizeCanvas();window.addEventListener('resize',()=>this.resizeCanvas());for(let i=0;i<100;i++){this.particles.push({x:Math.random()*this.canvas.width,y:Math.random()*this.canvas.height,vx:(Math.random()-0.5)*0.5,vy:(Math.random()-0.5)*0.5,size:Math.random()*3+1,opacity:Math.random()*0.5+0.2});}},resizeCanvas(){this.canvas.width=window.innerWidth;this.canvas.height=window.innerHeight;},animateParticles(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);this.particles.forEach((p,i)=>{p.x+=p.vx;p.y+=p.vy;if(p.x<0||p.x>this.canvas.width)p.vx*=-1;if(p.y<0||p.y>this.canvas.height)p.vy*=-1;this.ctx.beginPath();this.ctx.arc(p.x,p.y,p.size,0,Math.PI*2);this.ctx.fillStyle=`rgba(59,130,246,${p.opacity})`;this.ctx.fill();for(let j=i+1;jthis.animateParticles());},toggleSidebar(){document.getElementById('sidebar').classList.toggle('sidebar-hidden');},renderTools(){const tools=[{icon:'fa-image',name:'تصویر',action:'image'},{icon:'fa-microphone',name:'صدا',action:'voice'},{icon:'fa-video',name:'ویدیو',action:'video'},{icon:'fa-language',name:'ترجمه',action:'translate'},{icon:'fa-code',name:'کد',action:'code'},{icon:'fa-search',name:'جستجو',action:'search'},{icon:'fa-calculator',name:'محاسبه',action:'calculate'},{icon:'fa-file-alt',name:'مستندات',action:'docs'}];document.getElementById('tools-grid').innerHTML=tools.map(t=>``).join('');},setTheme(theme){if(theme==='light'){document.body.style.background='linear-gradient(135deg,#f0f4f8 0%,#e2e8f0 50%,#f0f4f8 100%)';document.body.style.color='#1e293b';}else{document.body.style.background='linear-gradient(135deg,#0f172a 0%,#1e293b 50%,#0f172a 100%)';document.body.style.color='#e2e8f0';}},loadSettings(){const s=JSON.parse(localStorage.getItem('kokab-settings')||'{}');if(s.theme)this.setTheme(s.theme);if(s.openrouterKey)document.getElementById('openrouter-key').value=s.openrouterKey;if(s.hfKey)document.getElementById('hf-key').value=s.hfKey;if(s.ttsEnabled!==undefined)document.getElementById('tts-enabled').checked=s.ttsEnabled;},scrollToBottom(){const c=document.getElementById('chat-container');c.scrollTop=c.scrollHeight;},showToast(msg,type='info'){const toast=document.getElementById('toast'),icons={success:'fa-check-circle text-green-500',error:'fa-exclamation-circle text-red-500',info:'fa-info-circle text-blue-500'};document.getElementById('toast-message').textContent=msg;document.getElementById('toast-icon').className=`fas ${icons[type]}`;toast.classList.remove('hidden');setTimeout(()=>toast.classList.add('hidden'),3000);}}; // ==================== AGENT 2: API Connection Engineer ==================== const APIAgent={async callLLM(prompt,model='mock'){try{if(model==='hf-free')return await this.callHF(prompt);if(model==='hf-openrouter')return await this.callOpenRouter(prompt);return await this.mock(prompt);}catch(e){throw new Error(`خطا API: ${e.message}`);}},async callHF(prompt){const key=localStorage.getItem('kokab-hf-key')||'';const res=await fetch('https://corsproxy.io/?'+encodeURIComponent('https://api-inference.huggingface.co/models/gpt2'),{method:'POST',headers:{'Content-Type':'application/json',...(key?{Authorization:`Bearer ${key}`}:{})},body:JSON.stringify({inputs:prompt,parameters:{max_new_tokens:500,temperature:0.7}})});if(!res.ok)throw new Error(`HTTP ${res.status}`);const data=await res.json();return data[0]?.generated_text||'پاسخی دریافت نشد';},async callOpenRouter(prompt){const key=localStorage.getItem('kokab-openrouter-key');if(!key)throw new Error('کلید OpenRouter تنظیم نشده');const res=await fetch('https://corsproxy.io/?'+encodeURIComponent('https://openrouter.ai/api/v1/chat/completions'),{method:'POST',headers:{'Content-Type':'application/json',Authorization:`Bearer ${key}`,'HTTP-Referer':location.href,'X-Title':'Kokab'},body:JSON.stringify({model:'google/gemma-2-9b-it:free',messages:[{role:'system',content:'You are Kokab, respond in Persian.'},{role:'user',content:prompt}],max_tokens:1000})});if(!res.ok)throw new Error(`HTTP ${res.status}`);const data=await res.json();return data.choices?.[0]?.message?.content||'پاسخی دریافت نشد';},async mock(prompt){await new Promise(r=>setTimeout(r,800));return`پاسخ آزمایشی به: "${prompt.substring(0,30)}..."\n\nبرای پاسخ واقعی، کلید API تنظیم کنید.`;}}; // ==================== AGENT 3: Tools Specialist ==================== const ToolsAgent={attachedFiles:[],tools:{image:async(p)=>{const f=p.file||ToolsAgent.attachedFiles[0];if(!f)return'تصویری آپلود نشده';return new Promise(r=>{const reader=new FileReader();reader.onload=e=>r(`تصویر: ${f.name}\n\n![img](${e.target.result})`);reader.readAsDataURL(f);});},voice:async()=> 'ضبط صدا فعال شد...',video:async()=> 'پردازش ویدیو نیاز به backend دارد.',translate:async(p)=>{const t=p.text||'متن وارد کنید';return`ترجمه: ${t}`;},code:async(p)=>{return`\`\`\`javascript\n// ${p.desc||'کد نمونه'}\nfunction hello(){console.log("Kokab");}\n\`\`\``;},search:async(p)=>`جستجو برای: ${p.query||''}`,calculate:async(p)=>{try{const r=Function('"use strict";return('+p.exp+')')();return`نتیجه: ${p.exp}=${r}`;}catch{return'خطای محاسبه';}},docs:async()=>'📚 مستندات ابرهوش کوکب'},async executeTool(name,params={}){return this.tools[name]?await this.tools[name](params):`ابزار "${name}" یافت نشد`;},handleFileSelect(e){this.attachedFiles.push(...Array.from(e.target.files));this.renderPreview();},renderPreview(){document.getElementById('files-preview').innerHTML=this.attachedFiles.map((f,i)=>`
${f.name}
`).join('');},removeFile(i){this.attachedFiles.splice(i,1);this.renderPreview();},clearFiles(){this.attachedFiles=[];this.renderPreview();document.getElementById('file-input').value='';}}; // ==================== AGENT 4: Agent Core ==================== const AgentCore={history:[],async processMessage(msg){this.history.push({role:'user',content:msg,ts:Date.now()});const intent=this.analyzeIntent(msg);if(intent.tool){app.ui.showToast(`فراخوانی: ${intent.tool}`,'info');const result=await ToolsAgent.executeTool(intent.tool,intent.params);const enhanced=`${msg}\n\n[نتیجه ابزار]: ${result}`;const resp=await APIAgent.callLLM(enhanced,document.getElementById('model-select').value);this.history.push({role:'assistant',content:resp,ts:Date.now()});return resp;}const ctx=this.buildContext(msg);const resp=await APIAgent.callLLM(ctx,document.getElementById('model-select').value);this.history.push({role:'assistant',content:resp,ts:Date.now()});return resp;},analyzeIntent(msg){const l=msg.toLowerCase();if(l.includes('عکس')||l.includes('تصویر'))return ToolsAgent.attachedFiles.some(f=>f.type.startsWith('image/'))?{tool:'image',params:{}}:{};if(l.includes('ترجمه'))return{tool:'translate',params:{text:msg}};if(l.includes('کد'))return{tool:'code',params:{desc:msg}};if(l.match(/[\d+\-*/.=]+/)){const m=l.match(/([\d+\-*/(). ]+)/);if(m)return{tool:'calculate',params:{exp:m[1]}};}return{tool:null,params:{}};},buildContext(msg){const recent=this.history.slice(-10);return`شما کوکب هستید، دستیار فارسی.\n\n${recent.map(m=>`${m.role==='user'?'کاربر':'کوکب'}: ${m.content}`).join('\n')}\nکاربر: ${msg}\nکوکب:`;},quickAction(a){const p={'تحلیل تصویر':'این تصویر را تحلیل کن','ترجمه':'ترجمه کن: ','خلاصه':'خلاصه کن: ','کدنویسی':'کد بنویس برای: ','محاسبه':'محاسبه کن: '};const i=document.getElementById('user-input');i.value=p[a]||a;i.focus();}}; // ==================== AGENT 5: Voice Specialist ==================== const VoiceAgent={recorder:null,chunks:[],recording:false,async initRecognition(){if('webkitSpeechRecognition'in window||'SpeechRecognition'in window){const SR=window.SpeechRecognition||window.webkitSpeechRecognition;const rec=new SR();rec.lang='fa-IR';rec.continuous=false;rec.onresult=e=>{document.getElementById('user-input').value+=e.results[0][0].transcript;app.ui.showToast('صدا به متن تبدیل شد','success');};rec.onerror=()=>app.ui.showToast('خطای تشخیص صدا','error');return rec;}return null;},toggleRecording(){this.recording?this.stop():this.start();},async start(){try{const stream=await navigator.mediaDevices.getUserMedia({audio:true});this.recorder=new MediaRecorder(stream);this.chunks=[];this.recorder.ondataavailable=e=>this.chunks.push(e.data);this.recorder.onstop=()=>{new Blob(this.chunks,{type:'audio/wav'});app.ui.showToast('ضبط 완료','success');};this.recorder.start();this.recording=true;app.ui.showToast('در حال ضبط...','info');}catch(e){app.ui.showToast('دسترسی میکروفون نیاز است','error');}},stop(){if(this.recorder&&this.recording){this.recorder.stop();this.recording=false;}},speak(text){if(!document.getElementById('tts-enabled')?.checked)return;if('speechSynthesis'in window){const u=new SpeechSynthesisUtterance(text);u.lang='fa-IR';u.rate=0.9;speechSynthesis.speak(u);}}}; // ==================== AGENT 6: Data Engineer ==================== const DataAgent={saveChat(){localStorage.setItem('kokab-chat-history',JSON.stringify(AgentCore.history));},loadChat(){const s=localStorage.getItem('kokab-chat-history');if(s)AgentCore.history=JSON.parse(s);},exportChat(){const c=AgentCore.history.map(m=>`[${new Date(m.ts).toLocaleString('fa-IR')}] ${m.role==='user'?'کاربر':'کوکب'}: ${m.content}`).join('\n\n');const blob=new Blob([c],{type:'text/plain;charset=utf-8'}),url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download=`kokab-${Date.now()}.txt`;a.click();URL.revokeObjectURL(url);app.ui.showToast('خروجی گرفته شد','success');},clearChat(){AgentCore.history=[];localStorage.removeItem('kokab-chat-history');document.getElementById('chat-container').innerHTML='';app.ui.showToast('پاک شد','success');},saveSettings(){const s={openrouterKey:document.getElementById('openrouter-key').value,hfKey:document.getElementById('hf-key').value,ttsEnabled:document.getElementById('tts-enabled').checked,theme:'dark'};localStorage.setItem('kokab-settings',JSON.stringify(s));if(s.openrouterKey)localStorage.setItem('kokab-openrouter-key',s.openrouterKey);if(s.hfKey)localStorage.setItem('kokab-hf-key',s.hfKey);}}; // ==================== AGENT 7: Quality Manager ==================== const QualityAgent={runTests(){console.log('Tests: OK');},validateInput(i){if(!i||!i.trim()){app.ui.showToast('پیام خالی است','error');return false;}if(i.length>10000){app.ui.showToast('پیام طولانی است','error');return false;}return true;},handleError(e,c){console.error(`Error ${c}:`,e);app.ui.showToast(`خطا: ${e.message}`,'error');}}; // ==================== Main App ==================== const app={ui:UIAgent,api:APIAgent,tools:ToolsAgent,agent:AgentCore,voice:VoiceAgent,DataAgent,qa:QualityAgent,init(){this.ui.init();this.data.loadChat();this.qa.runTests();const rec=this.voice.initRecognition();if(rec)document.querySelector('.fa-microphone').parentElement.onclick=()=>{rec.start();app.ui.showToast('گوش می‌دهم...','info');};console.log('🌟 Kokab initialized');},chat:{async send(){const input=document.getElementById('user-input'),msg=input.value.trim();if(!app.qa.validateInput(msg))return;input.value='';input.style.height='auto';app.tools.clearFiles();this.addMessage('user',msg);const tid=this.showTyping();try{const resp=await app.agent.processMessage(msg);this.removeTyping(tid);this.addMessage('assistant',resp);app.data.saveChat();app.voice.speak(resp);}catch(e){this.removeTyping(tid);this.addMessage('error',`خطا: ${e.message}`);app.qa.handleError(e,'send');}},addMessage(role,content){const c=document.getElementById('chat-container'),isUser=role==='user',isError=role==='error';c.insertAdjacentHTML('beforeend',`
${isError?`${content}`:marked.parse(content)}
${new Date().toLocaleTimeString('fa-IR')}
`);app.ui.scrollToBottom();},showTyping(){const id='typing-'+Date.now(),c=document.getElementById('chat-container');c.insertAdjacentHTML('beforeend',`
`);app.ui.scrollToBottom();return id;},removeTyping(id){const e=document.getElementById(id);if(e)e.remove();},handleKeyDown(e){if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();app.chat.send();}},clearHistory(){if(confirm('آیا مطمئن هستید؟')){app.data.clearChat();location.reload();}}},settings:{open(){document.getElementById('settings-modal').classList.remove('hidden');},close(){document.getElementById('settings-modal').classList.add('hidden');},save(){app.data.saveSettings();this.close();app.ui.showToast('ذخیره شد','success');}}}; document.addEventListener('DOMContentLoaded',()=>app.init());