Files
html/api/wevia-smart-router.php
2026-04-13 13:10:03 +02:00

49 lines
11 KiB
PHP

<?php
function wevia_smart_route($q) {
$q = mb_strtolower(trim($q));
// ACTION EXEC — calls wevia-exec.php for shell commands
if(preg_match('/(auto.?fix|autofix|repare|corrige.*auto)/',$q)){$_POST['message']=$q;ob_start();@include __DIR__.'/wevia-exec.php';$o=ob_get_clean();$d=@json_decode($o,true);if($d&&!empty($d['response']))return['response'=>$d['response'],'engine'=>'WEVIA-Exec','intent'=>'autofix'];}
if(preg_match('/(lance.*nonreg|nonreg|non.?reg)/',$q)){$_POST['message']=$q;ob_start();@include __DIR__.'/wevia-exec.php';$o=ob_get_clean();$d=@json_decode($o,true);if($d&&!empty($d['response']))return['response'=>$d['response'],'engine'=>'WEVIA-Exec','intent'=>'nonreg'];}
if(preg_match('/(nettoie|clean.*disk|libere.*espace)/',$q)){$_POST['message']=$q;ob_start();@include __DIR__.'/wevia-exec.php';$o=ob_get_clean();$d=@json_decode($o,true);if($d&&!empty($d['response']))return['response'=>$d['response'],'engine'=>'WEVIA-Exec','intent'=>'disk_clean'];}
if(preg_match('/(lance.*guardian|guardian)/',$q)){$_POST['message']=$q;ob_start();@include __DIR__.'/wevia-exec.php';$o=ob_get_clean();$d=@json_decode($o,true);if($d&&!empty($d['response']))return['response'=>$d['response'],'engine'=>'WEVIA-Exec','intent'=>'guardian'];}
if(preg_match('/(git.*push|git.*status)/',$q)){$_POST['message']=$q;ob_start();@include __DIR__.'/wevia-exec.php';$o=ob_get_clean();$d=@json_decode($o,true);if($d&&!empty($d['response']))return['response'=>$d['response'],'engine'=>'WEVIA-Exec','intent'=>'git'];}
if(preg_match('/(code|fonction|script|python|php|js|html|css|react|api|endpoint|refactor|debug|bug|fix.*code|cree.*page|cree.*app|develop|program|composant|module|class)/',$q)) return _cerebras($q,'code');
if(preg_match('/(recherche|veille|synthese|compare|benchmark|etude|article|rapport|tendance|concurrent|trend|marche|sector)/',$q)){$ch=curl_init('http://localhost:2024/api/v1/run');curl_setopt_array($ch,[CURLOPT_POST=>1,CURLOPT_POSTFIELDS=>json_encode(['query'=>$q,'mode'=>'research']),CURLOPT_RETURNTRANSFER=>1,CURLOPT_TIMEOUT=>30,CURLOPT_HTTPHEADER=>['Content-Type:application/json']]);$r=curl_exec($ch);curl_close($ch);$d=@json_decode($r,true);if($d)return['response'=>$d['result']??$d['output']??json_encode($d),'engine'=>'DeerFlow','intent'=>'research'];return _cerebras($q,'research');}
if(preg_match('/(cherche|google|search|trouve|web|internet|actualit|news)/',$q)){$sq=urlencode(str_replace(['cherche','search','trouve','google'],'',$q));$ch=curl_init("http://localhost:8888/search?q=$sq&format=json&categories=general&language=fr");curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>1,CURLOPT_TIMEOUT=>10]);$r=curl_exec($ch);curl_close($ch);$d=@json_decode($r,true);if($d&&isset($d['results'])){$out="Resultats:\n";foreach(array_slice($d['results'],0,5)as$i=>$res)$out.=($i+1).". ".$res['title']."\n ".$res['url']."\n";return['response'=>$out,'engine'=>'SearXNG','intent'=>'search'];}}
if(preg_match('/(projet|sprint|roadmap|backlog|issue|ticket|milestone|planning|task|todo|objectif|kanban)/',$q)) return['response'=>'Paperclip: 3 agents (CEO/CTO/PM) | https://paperclip.weval-consulting.com','engine'=>'Paperclip','intent'=>'project'];
if(preg_match('/(securit|scan|vuln|pentest|owasp|cve|firewall|ssl|cert|audit.*sec|nuclei)/',$q)) return['response'=>'Nuclei pret. Scanner: nuclei -u https://target -severity critical,high','engine'=>'Nuclei','intent'=>'security'];
if(preg_match('/(ethica|hcp|medecin|pharma|contact|email.*enrich|patient|docteur|hopital)/',$q)){$r=trim(shell_exec("psql -U postgres -d ethica -t -c 'SELECT count(*) FROM medecins_validated' 2>/dev/null"));$gap=trim(shell_exec("psql -U postgres -d ethica -t -c \"SELECT count(*) FROM medecins_validated WHERE email IS NULL OR email=''\" 2>/dev/null"));return['response'=>"Ethica: $r HCPs, $gap sans email",'engine'=>'Ethica/PG','intent'=>'data'];}
if(preg_match('/(rag|knowledge|kb|base.*connaissance|vecteur|embedding|memoire|wiki|documentation)/',$q)){$ch=curl_init('http://localhost:6333/collections');curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>1,CURLOPT_TIMEOUT=>3]);$r=@json_decode(curl_exec($ch),true);curl_close($ch);$out="Qdrant KB:\n";if($r)foreach($r['result']['collections']as$c)$out.=" ".$c['name']."\n";$skills=trim(shell_exec("find /opt/deer-flow/skills -name 'SKILL.md' 2>/dev/null|wc -l"));$out.="Skills: $skills";return['response'=>$out,'engine'=>'Qdrant/KB','intent'=>'knowledge'];}
if(preg_match('/(monitor|uptime|status|sante|health|alerte|alert|down|panne)/',$q)){$dk=trim(shell_exec("docker ps -q|wc -l"));$disk=trim(shell_exec("df -h /|tail -1|awk '{print \$5}'"));return['response'=>"Monitor: Director alive | Docker $dk | Disk $disk",'engine'=>'Director/Kuma','intent'=>'monitor'];}
if(preg_match('/(workflow|automat|n8n|pipeline|trigger|cron|schedule)/',$q)) return['response'=>'n8n: 13 workflows actifs http://localhost:5678','engine'=>'n8n','intent'=>'pipeline'];
if(preg_match('/(consensus|compare.*ia|decision|arbitrage|vote|avis|opinion|strateg|conseil)/',$q)){$key=trim(shell_exec("grep GROQ_KEY /etc/weval/secrets.env|cut -d= -f2"));$ch=curl_init('https://api.groq.com/openai/v1/chat/completions');curl_setopt_array($ch,[CURLOPT_POST=>1,CURLOPT_POSTFIELDS=>json_encode(['model'=>'llama-3.3-70b-versatile','messages'=>[['role'=>'user','content'=>$q]],'max_tokens'=>200]),CURLOPT_RETURNTRANSFER=>1,CURLOPT_TIMEOUT=>8,CURLOPT_HTTPHEADER=>["Authorization: Bearer $key",'Content-Type:application/json']]);$r=@json_decode(curl_exec($ch),true);curl_close($ch);$g=$r['choices'][0]['message']['content']??'?';$c=_cerebras_raw($q);return['response'=>"CONSENSUS:\n[Groq]: ".substr($g,0,200)."\n[Cerebras]: ".substr($c,0,200),'engine'=>'Consensus/MoA','intent'=>'consensus'];}
if(preg_match('/(pdf|genere.*rapport|rapport.*pdf|document.*pdf|facture|devis|contrat)/',$q)) return _cerebras("Genere contenu PDF: $q",'pdf');
if(preg_match('/(diagramme|schema|mermaid|flowchart|sequence|gantt|organigramme|graph)/',$q)) return _cerebras("Mermaid pour: $q",'diagram');
if(preg_match('/(tradui|translate|anglais|francais|arabe|espagnol)/',$q)) return _cerebras($q,'translation');
if(preg_match('/(email|mail|redige|ecris.*mail|brouillon)/',$q)) return _cerebras("Expert comm: $q",'email');
if(preg_match('/(scrape|scraping|extraire.*site|crawler|spider|donnees.*web)/',$q)) return['response'=>'Scraping: Playwright+Scrapy prets','engine'=>'Playwright','intent'=>'scraping'];
if(preg_match('/(cree.*erp|cree.*crm|cree.*app|developpe|front.*back|full.*stack|build.*from|construit|application|saas|plateforme|dashboard|landing)/',$q)) return _cerebras("Architecte fullstack: $q",'dev_e2e');
if(preg_match('/(ux.*audit|audit.*ux|qualite.*page|teste.*page|check.*ui|3d|animation)/',$q)) return['response'=>'UX Agent: Playwright cron */2h, 10 pages testees','engine'=>'Playwright+UX','intent'=>'ux_audit'];
if(preg_match('/(multi.*agent|orchestre|lance.*agent|dispatch|coordonne|mobilise)/',$q)) return _cerebras("Multi-agent WEVAL pour: $q",'multi_agent');
if(preg_match('/(wire.*skill|inject.*skill|ajoute.*skill|integre.*skill)/',$q)) return['response'=>'Skills: '.trim(shell_exec("find /opt/deer-flow/skills -name 'SKILL.md' 2>/dev/null|wc -l")).' disponibles','engine'=>'SkillSmith','intent'=>'skill_wire'];
if(preg_match('/(cree.*agent|nouveau.*agent|genere.*agent)/',$q)) return _cerebras("Cree agent: $q",'agent_create');
if(preg_match('/(404|500|page.*cassee|route.*manque|routing|ecran.*erreur)/',$q)){$nr=trim(shell_exec("bash /var/www/html/api/nonreg-check.sh 2>/dev/null"));return['response'=>"NonReg: $nr",'engine'=>'WEVIA-Exec','intent'=>'fix_routing'];}
if(preg_match('/(port.*scan|scan.*port|conflit.*port|port.*ouvert)/',$q)){$p=trim(shell_exec("ss -tlnp|grep LISTEN|awk '{print \$4}'|sort -t: -k2 -n|tail -15"));return['response'=>"Ports:\n$p",'engine'=>'WEVIA-Exec','intent'=>'port_scan'];}
if(preg_match('/(schema.*archi|archi.*schema|topologie|carte.*serveur)/',$q)) return _cerebras("Mermaid archi WEVAL: S204+S95+S151+Blade",'architecture_diagram');
if(preg_match('/(value.*chain|chaine.*valeur|flux.*travail|processus|bpmn)/',$q)) return['response'=>'Value Chain: 21 depts, 191 agents','engine'=>'Enterprise','intent'=>'value_chain'];
if(preg_match('/(benchmark|classement|leaderboard|score.*ia)/',$q)) return['response'=>'39 AIs, WEVAL_COMBINED #1 (93/90)','engine'=>'AI-Benchmark','intent'=>'benchmark'];
if(preg_match('/(blade|desktop|selenium|screenshot|powershell|gmail|office|outlook|pc|ordinateur|navigateur|browser|chrome|gpu.*free|colab|kaggle)/',$q)){$r=@file_get_contents('https://weval-consulting.com/api/blade-tasks/heartbeat.json');$d=@json_decode($r,true);$st=$d?'LIVE cpu:'.$d['cpu'].'% ram:'.$d['ram'].'%':'Blade attente sync';return['response'=>"Blade: $st | 34 caps",'engine'=>'Blade/Sentinel','intent'=>'blade'];}
if(preg_match('/(analyst|architect|reviewer|critic|debugger|designer|executor|planner|scientist|tracer|verifier|writer)/',$q)) return _cerebras('Agent: '.$q,'agent_dispatch');
if(preg_match('/(renouvel.*cle|api.*key|token.*expir|pat.*expir)/',$q)) return['response'=>'Keys: GitHub PAT ~15avr, Groq/Cerebras OK','engine'=>'WEVIA-Exec','intent'=>'api_keys'];
if(preg_match('/(autonom|sans.moi|remplace.*moi|zero.*intervention)/',$q)) return _cerebras('Autonome 44 crons: '.$q,'autonomous');
if(preg_match('/(explique|analyse|raisonne|pourquoi|comment|architecture|design|plan|complex|resume)/',$q)) return _cerebras($q,'reasoning');
if(preg_match('/(design|logo|image|photo|maquette|mockup|ui|ux|wireframe|couleur)/',$q)) return _cerebras($q,'design');
if(preg_match('/(screenshot|image|capture|visuel|ecran|screen|regarde)/',$q)) return['response'=>'Vision: Moondream Ollama local','engine'=>'Moondream/Ollama','intent'=>'vision'];
if(preg_match('/bonjour|salut|hello|hey|coucou|bonsoir/',$q)) return['response'=>'Bonjour! WEVIA Master, 33 IAs, 0€. Comment aider?','engine'=>'Groq','intent'=>'greeting'];
if(mb_strlen($q) > 40) return _cerebras($q, deep_query);
if(preg_match("/(diagnostic|diag|health.check|etat.systeme)/",$q)){$dk=trim(`docker ps -q|wc -l`);$disk=trim(`df -h /|tail -1|awk "{print $5}"`);$load=trim(`cat /proc/loadavg|cut -d" " -f1`);$ram=trim(`free -m|awk "/Mem/{print $3}"`);return ["response"=>"Diag: Load $load | Disk $disk | RAM {$ram}MB | Docker $dk","engine"=>"WEVIA-Exec","intent"=>"diagnostic"];}
return null;
}
function _cerebras($q,$intent){$r=_cerebras_raw($q);return['response'=>$r??'Cerebras timeout','engine'=>'Cerebras/Qwen3-235B','intent'=>$intent];}
function _cerebras_raw($q){$key=trim(shell_exec("grep CEREBRAS_API_KEY /etc/weval/secrets.env|cut -d= -f2"));$ch=curl_init('https://api.cerebras.ai/v1/chat/completions');curl_setopt_array($ch,[CURLOPT_POST=>1,CURLOPT_POSTFIELDS=>json_encode(['model'=>'qwen-3-235b-a22b-instruct-2507','messages'=>[['role'=>'system','content'=>'Tu es WEVIA Master. 33 IAs, 146 outils, 913 skills, 4 serveurs. Francais.'],['role'=>'user','content'=>$q]],'max_tokens'=>800]),CURLOPT_RETURNTRANSFER=>1,CURLOPT_TIMEOUT=>15,CURLOPT_HTTPHEADER=>["Authorization: Bearer $key",'Content-Type:application/json']]);$r=@json_decode(curl_exec($ch),true);curl_close($ch);return $r['choices'][0]['message']['content']??null;}