/* global React, Glyph */ /* ============================================================ AETHERCORE AGENT — Claude-powered assistant Answers questions, explains science, and can take actions (navigate views / scroll sections / open a disease). ============================================================ */ const { useState:useAgS, useEffect:useAgE, useRef:useAgR } = React; const AG_KEY='aether_agent_v1'; function agentOpen(prefill){ window.dispatchEvent(new CustomEvent('aether-agent',{detail:{prefill}})); } function mdLite(txt){ const esc=s=>s.replace(/&/g,'&').replace(/esc(s).replace(/\*\*(.+?)\*\*/g,'$1').replace(/`([^`]+)`/g,'$1'); const out=[]; let list=null; txt.split('\n').forEach(l=>{ const m=l.match(/^\s*[-*•]\s+(.*)/); if(m){ if(!list){list=[];} list.push('
  • '+inline(m[1])+'
  • '); return; } if(list){ out.push(''); list=null; } if(l.trim()) out.push('

    '+inline(l)+'

    '); }); if(list) out.push(''); return out.join(''); } function AetherAgent({ mode='dash', views=[], current, onAction, suggestions }){ const [open,setOpen]=useAgS(false); const [msgs,setMsgs]=useAgS(()=>{ try{ const saved=JSON.parse(sessionStorage.getItem(AG_KEY)); return Array.isArray(saved)?saved.filter(m=>['user','assistant'].includes(m.role)&&typeof m.content==='string').slice(-30):[]; }catch(e){ return []; } }); const [input,setInput]=useAgS(''); const [busy,setBusy]=useAgS(false); const body=useAgR(null), inp=useAgR(null), drawer=useAgR(null), sending=useAgR(false); useAgE(()=>{ if(!open) return; const previous=document.activeElement; inp.current&&inp.current.focus(); const trap=e=>{ if(e.key!=='Tab'||!drawer.current) return; const nodes=[...drawer.current.querySelectorAll('button:not(:disabled),textarea')]; if(!nodes.length) return; if(e.shiftKey&&document.activeElement===nodes[0]){e.preventDefault();nodes[nodes.length-1].focus();} else if(!e.shiftKey&&document.activeElement===nodes[nodes.length-1]){e.preventDefault();nodes[0].focus();} }; document.addEventListener('keydown',trap); return ()=>{document.removeEventListener('keydown',trap); previous&&previous.isConnected&&previous.focus();}; },[open]); useAgE(()=>{ try{ sessionStorage.setItem(AG_KEY,JSON.stringify(msgs.slice(-30))); }catch(e){} if(body.current) body.current.scrollTop=body.current.scrollHeight; },[msgs,busy]); useAgE(()=>{ const h=(e)=>{ setOpen(true); const p=e.detail&&e.detail.prefill; if(p) setTimeout(()=>send(p),120); else setTimeout(()=>inp.current&&inp.current.focus(),300); }; const k=(e)=>{ if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()==='j'){ e.preventDefault(); setOpen(o=>!o); setTimeout(()=>inp.current&&inp.current.focus(),300); } if(e.key==='Escape') setOpen(false); }; window.addEventListener('aether-agent',h); window.addEventListener('keydown',k); return ()=>{ window.removeEventListener('aether-agent',h); window.removeEventListener('keydown',k); }; },[msgs,busy]); const send=async(text)=>{ const q=(text||input).trim(); if(!q||sending.current||q.length>4000) return; sending.current=true; setInput(''); const next=[...msgs,{role:'user',content:q}]; setMsgs(next); setBusy(true); try{ const convo=next.slice(-10).map(m=>({role:m.role,content:m.content.slice(0,4000)})); while(convo.length>1&&convo.reduce((n,m)=>n+m.content.length,0)>16000) convo.shift(); const response=await fetch(new URL('api/anthropic/agent',new URL('./',window.location.href)),{ method:'POST',headers:{'Content-Type':'application/json'}, body:JSON.stringify({mode,current:current||'',messages:convo}) }); const result=await response.json(); if(!response.ok) throw new Error(result.error||'The assistant is unavailable.'); const {reply,action}=result; setMsgs(m=>[...m,{role:'assistant',content:reply,action}]); }catch(e){ setMsgs(m=>[...m,{role:'assistant',content:e.message||'The assistant is unavailable. Please try again.'}]); } sending.current=false; setBusy(false); }; const sugs=suggestions||(mode==='dash' ? ['What should I study first?','Explain how CRISPR works','Quiz me on the scientific method','Take me to the marketplace'] : ['What does AetherCore build?','What is MOIRA?','Who leads the company?','How do I join the Academy?']); const caps=mode==='dash' ? [['dna2','Explain any disease'],['target','Plan your learning'],['cpu','Teach AI building'],['orbit','Navigate for you']] : [['orbit','Tour the platform'],['brain','Explain the science'],['building','Partnerships'],['arrow','Join the Academy']]; return ReactDOM.createPortal(React.createElement(React.Fragment,null, React.createElement('div',{className:`agent-scrim ${open?'open':''}`,onClick:()=>setOpen(false)}), React.createElement('aside',{ref:drawer,className:`agent ${open?'open':''}`,inert:open?undefined:'','aria-hidden':!open,'aria-label':'AetherCore Agent',role:'dialog','aria-modal':open?'true':undefined}, React.createElement('div',{className:'agent-head'}, React.createElement('span',{className:`agent-orb ${busy?'busy':''}`}), React.createElement('div',{className:'agent-title'},React.createElement('b',null,'AETHERCORE AGENT'), React.createElement('span',null,busy?'Thinking…':'Assistant · Ctrl/⌘J')), msgs.length>0&&React.createElement('button',{className:'agent-clear',disabled:busy,onClick:()=>setMsgs([])},'CLEAR'), React.createElement('button',{className:'agent-x',onClick:()=>setOpen(false),'aria-label':'Close'},'×')), React.createElement('div',{className:'agent-body',ref:body,'aria-live':'polite'}, msgs.length===0&&React.createElement('div',{className:'agent-hello'}, React.createElement('h4',null,'HOW CAN I HELP?'), React.createElement('p',null,mode==='dash'?'Ask me anything about biology, disease, or building with AI. I can also take you anywhere in the Academy.':'Ask me about our platforms, the science, or the team. I can guide you anywhere on the site.'), React.createElement('div',{className:'agent-caps'},caps.map(c=>React.createElement('div',{key:c[1],className:'agent-cap'}, React.createElement(Glyph,{name:c[0],width:15,height:15}),c[1])))), msgs.map((m,i)=>React.createElement('div',{key:i,className:`msg ${m.role==='user'?'user':'bot'}`}, m.role==='user'?m.content:React.createElement(React.Fragment,null, React.createElement('div',{dangerouslySetInnerHTML:{__html:mdLite(m.content)}}), m.action&&React.createElement('button',{className:'msg-act',onClick:()=>{ onAction&&onAction(m.action); if(mode==='landing'||m.action.type!=='view') setOpen(false); }}, (m.action.label||'GO').toUpperCase(),' →')))), busy&&React.createElement('div',{className:'msg bot typing'},React.createElement('i'),React.createElement('i'),React.createElement('i'))), msgs.length<2&&React.createElement('div',{className:'agent-sugs'}, sugs.map(s=>React.createElement('button',{key:s,className:'agent-sug',disabled:busy,onClick:()=>send(s)},s))), React.createElement('form',{className:'agent-form',onSubmit:e=>{e.preventDefault();send();}}, React.createElement('textarea',{ref:inp,className:'agent-in',rows:1,maxLength:4000,'aria-label':'Your question',placeholder:'Ask the agent…',value:input, onChange:e=>setInput(e.target.value),onKeyDown:e=>{ if(e.key==='Enter'&&!e.shiftKey){ e.preventDefault(); send(); } }}), React.createElement('button',{className:'agent-send',type:'submit',disabled:!input.trim()||busy,'aria-label':'Send'}, React.createElement('svg',{width:18,height:18,viewBox:'0 0 24 24',fill:'none',stroke:'currentColor',strokeWidth:1.8,strokeLinecap:'round',strokeLinejoin:'round'}, React.createElement('path',{d:'M5 12h14M13 6l6 6-6 6'})))), React.createElement('div',{className:'agent-foot'},'AI ASSISTANT · RESPONSES MAY CONTAIN ERRORS')) ),document.body); } Object.assign(window,{ AetherAgent, agentOpen });