AI-Syed Jalal — Professional AI Workspace

Explore AI chat, multi-model workflows, deep research, coding, data analysis, documents, image and voice tools, AI agents, provider integrations and secure operations in one workspace.

`);w.document.close();w.focus();setTimeout(()=>w.print(),500)}; async $('#aiRefreshBtn')?.addEventListener('click',renderAICommand); $('#runSupervisorBtn')?.addEventListener('click',async()=>{if(!remoteMode()){toast('Connect the API to run Supervisor.');return}const goal=$('#supervisorGoal').value.trim();if(goal.length<2){$('#supervisorOutput').textContent='Enter a goal first.';return}const b=$('#runSupervisorBtn');b.disabled=true;$('#supervisorOutput').textContent='Running bounded specialist tasks…';try{const x=await api('/api/ai/supervisor',{method:'POST',body:JSON.stringify({goal,provider:$('#aiProviderSelect').value,maxTasks:3})});$('#supervisorOutput').textContent=JSON.stringify({status:x.status,summary:x.summary,tasks:x.results?.map(t=>({agentId:t.agentId,status:t.status,output:t.output,error:t.error}))},null,2)}catch(e){$('#supervisorOutput').textContent=e.message;toast(e.message)}finally{b.disabled=false}}); $('#runAutoGPTBtn')?.addEventListener('click',async()=>{if(!remoteMode()){toast('Connect the API to run bounded AutoGPT.');return}const goal=$('#autogptGoal').value.trim();if(goal.length<2){$('#autogptOutput').textContent='Enter a goal first.';return}const b=$('#runAutoGPTBtn');b.disabled=true;$('#autogptOutput').textContent='Running bounded task loop…';try{const x=await api('/api/ai/autogpt',{method:'POST',body:JSON.stringify({goal,agentId:$('#aiAgentSelect').value,provider:$('#aiProviderSelect').value,maxIterations:3})});$('#autogptOutput').textContent=JSON.stringify({status:x.status,iterations:x.iteration,steps:x.steps?.map(s=>({iteration:s.iteration,status:s.status,output:s.output,error:s.error}))},null,2)}catch(e){$('#autogptOutput').textContent=e.message;toast(e.message)}finally{b.disabled=false}}); $('#aiRunBtn')?.addEventListener('click',async()=>{if(!remoteMode()){toast('Connect the current API before running a real agent.');return} const btn=$('#aiRunBtn');btn.disabled=true;$('#aiRunMessage').textContent='Executing…';try{const x=await api('/api/ai/run',{method:'POST',body:JSON.stringify({agentId:$('#aiAgentSelect').value,provider:$('#aiProviderSelect').value,model:$('#aiModelInput').value.trim()||undefined,thinking:$('#aiThinking').checked,prompt:$('#aiPrompt').value.trim()})});$('#aiTraceTag').textContent=x.traceId||'COMPLETED';$('#aiOutput').textContent=x.output||'';$('#aiRunMessage').textContent=`Completed via ${x.provider||'provider'} · trace ${x.traceId||'n/a'}`;await renderAICommand()}catch(e){$('#aiRunMessage').textContent=e.message;toast(e.message)}finally{btn.disabled=false}}); async async async function renderAICommand(){ if(!remoteMode()){ $('#aiRuntimeStatus').textContent='LOCAL / DEMO'; $('#aiAgentCount').textContent='—'; $('#aiProviderCount').textContent='—'; $('#aiCapabilityCount').textContent='—'; $('#aiInventory').textContent='Local demo mode. Connect the current API for real agent inventory, provider health, execution traces and run history.'; $('#aiProviderHealth').textContent='No central API connected.'; $('#aiRecentRuns').textContent='No server-side run history in local demo mode.'; return; } try{ const [cap,ov,ph,runs]=await Promise.all([api('/api/ai/capabilities'),api('/api/admin/ai/overview'),api('/api/admin/ai/provider-health'),api('/api/ai/runs?limit=8')]); $('#aiRuntimeStatus').textContent='LIVE / VERIFIED'; $('#aiAgentCount').textContent=cap.executableAgentProfiles??cap.agents?.length??'—'; $('#aiProviderCount').textContent=(cap.providers||[]).length; $('#aiCapabilityCount').textContent=cap.skills?.length??cap.skillPacks?.length??'—'; $('#aiAgentSelect').innerHTML=(cap.agents||[]).map(a=>``).join(''); const s=ov.summary||{}; $('#ai24Runs').textContent=s.runs??0; $('#ai24Completed').textContent=`${s.completed??0} completed · ${s.non_completed??0} non-completed`; $('#ai24Tokens').textContent=Number(s.tokens||0).toLocaleString(); const configured=(ph.providers||[]).filter(x=>x.configured).length; $('#aiConfiguredProviders').textContent=`${configured}/${(ph.providers||[]).length}`; const blocked=(cap.runtime?.providers?Object.values(cap.runtime.providers).filter(x=>(x.blockedUntil||0)>Date.now()).length:0); $('#aiCircuitState').textContent=blocked?'OPEN':'READY'; $('#aiInventory').innerHTML=`
${escape(String($('#aiAgentCount').textContent))} executable profiles
${configured} providers configured
${escape(String(cap.skillPacks?.length??cap.skills?.length??0))} skill packs/capability groups
Profiles are configurations, not independent model instances.
`; $('#aiProviderHealth').innerHTML=(ph.providers||[]).map(x=>`
${escape(x.label||x.id)} · ${escape(x.status)}
${escape(x.model||'default model')} · ${escape(x.baseUrl||'provider default')}
`).join('')||'No providers returned.'; $('#aiRecentRuns').innerHTML=(runs.runs||[]).map(r=>`
${escape(r.agentId)} · ${escape(r.provider)} · ${escape(r.status)}
${new Date(r.createdAt).toLocaleString()} · ${escape(r.id)}
`).join('')||'No AI runs yet.'; }catch(e){ $('#aiRuntimeStatus').textContent='UNAVAILABLE'; $('#aiInventory').textContent='AI runtime unavailable: '+e.message; toast(e.message); } } $('#newMissionBtn').onclick=()=>{const n=prompt('Mission name:','New Mission');if(n){toast('Mission “'+n+'” created in this demo workspace')}}; const DEMO_APPROVALS_KEY='aj-v76-approvals'; function demoApprovals(){try{const x=JSON.parse(localStorage.getItem(DEMO_APPROVALS_KEY)||'null');if(Array.isArray(x))return x}catch{}const x=[{id:'demo-1',action:'Regional Data Review',description:'Validate the next regional record batch.',status:'pending',requestedBy:'demo-workspace',createdAt:new Date().toISOString()},{id:'demo-2',action:'Verification Pack',description:'Release the prepared A4 verification document.',status:'pending',requestedBy:'demo-workspace',createdAt:new Date().toISOString()},{id:'demo-3',action:'AI Mission Handoff',description:'Allow the selected AI workflow to proceed to the next stage.',status:'pending',requestedBy:'demo-workspace',createdAt:new Date().toISOString()}];localStorage.setItem(DEMO_APPROVALS_KEY,JSON.stringify(x));return x} function saveDemoApprovals(x){localStorage.setItem(DEMO_APPROVALS_KEY,JSON.stringify(x))} function approvalModal(){let m=$('#approvalModal');if(m)return m;m=document.createElement('div');m.id='approvalModal';m.className='modal hidden';m.innerHTML='';document.body.appendChild(m);$('#closeApprovalModal').onclick=()=>m.classList.add('hidden');return m} async function renderApprovals(){const m=approvalModal(),list=$('#approvalList');let rows=[];if(remoteMode()){try{rows=(await api('/api/approvals')).approvals||[]}catch(e){list.textContent='Approval service unavailable: '+e.message;$('#approvalCount').textContent='—';return}}else rows=demoApprovals().filter(x=>x.status==='pending');$('#approvalCount').textContent=String(rows.length);if($('#controlApprovalCount'))$('#controlApprovalCount').textContent=String(rows.length);list.innerHTML=rows.length?rows.map(x=>`
${escape(x.action)}PENDING

${escape(x.description)}

`).join(''):'

No pending approvals.

';m.classList.remove('hidden')} document.addEventListener('click',async e=>{const open=e.target.closest('[data-approval="open"]');if(open){e.preventDefault();await renderApprovals();return}const b=e.target.closest('[data-approval-action]');if(!b)return;const status=b.dataset.approvalAction,id=b.dataset.approvalId;try{if(remoteMode()){await api('/api/approvals/'+encodeURIComponent(id),{method:'PATCH',body:JSON.stringify({status})})}else{const rows=demoApprovals().map(x=>x.id===id?{...x,status,resolvedAt:new Date().toISOString(),resolvedBy:state.user||'Operator'}:x);saveDemoApprovals(rows)}toast(status==='approved'?'Approval recorded':'Approval rejected');await renderApprovals()}catch(err){toast(err.message||'Approval update failed')}}); renderApprovals().catch(()=>{}); function loadConnection(){$('#apiUrl').value=state.apiUrl;$('#tenantId').value=state.tenantId;$('#roleSelect').value=state.role;$('#apiStatus').textContent=state.apiUrl?'CONFIGURED':'NOT CONNECTED';$('#connectionMessage').textContent=state.apiUrl?'Endpoint configured. Test it, then use Live Sign In from the login screen.':'Saved locally only. A real API must implement authentication, authorization and data validation.'} $('#saveConnection').onclick=()=>{state.apiUrl=$('#apiUrl').value.trim();state.tenantId=$('#tenantId').value.trim()||'alsyed-jalal';state.role=$('#roleSelect').value;localStorage.setItem('aj-v31-api',state.apiUrl);localStorage.setItem('aj-v31-tenant',state.tenantId);localStorage.setItem('aj-v31-role',state.role);$('#apiStatus').textContent=state.apiUrl?'CONFIGURED':'NOT CONNECTED';$('#roleValue').textContent=state.role;$('#connectionMessage').textContent='Connection settings saved locally. No secret or password is stored here.';toast('Production connection settings saved')} $('#testConnection').onclick=async()=>{if(!state.apiUrl){toast('Enter an API base URL first');return}$('#connectionMessage').textContent='Testing endpoint…';try{const r=await fetch(state.apiUrl.replace(/\/$/,'')+'/api/health',{method:'GET',mode:'cors'});const x=await r.json();$('#connectionMessage').textContent='API healthy: '+x.service+' · '+x.version;toast('Backend reachable')}catch(e){$('#connectionMessage').textContent='Endpoint could not be reached from this browser. Check HTTPS, CORS and the API URL.';toast('Connection test failed')}} $('#loginApiUrl').value=state.apiUrl; $('#revokeSessionsBtn')?.addEventListener('click',async()=>{try{await api('/api/auth/sessions',{method:'DELETE'});$('#securityMessage').textContent='Other sessions revoked.';toast('Other sessions revoked')}catch(e){$('#securityMessage').textContent=e.message}}); $('#changePasswordBtn')?.addEventListener('click',async()=>{const current=prompt('Current password:');if(current===null)return;const next=prompt('New password (minimum 10 characters):');if(next===null)return;try{await api('/api/auth/change-password',{method:'POST',body:JSON.stringify({currentPassword:current,newPassword:next})});state.token='';state.user='';toast('Password changed. Please sign in again.');setTimeout(()=>location.reload(),500)}catch(e){$('#securityMessage').textContent=e.message}}); /* Current interaction layer: lightweight pointer parallax, 3D cards, safe reduced-motion support. Legacy motion contract: initV52Motion. */ (function initMotionV76(){ const reduce=window.matchMedia&&window.matchMedia('(prefers-reduced-motion: reduce)').matches; if(reduce)return; const fine=window.matchMedia&&window.matchMedia('(pointer:fine)').matches; if(!fine)return; const tilt=(el,max=5)=>{ if(!el||el.dataset.v51Tilt)return; el.dataset.v51Tilt='1'; let raf=0; el.addEventListener('pointermove',e=>{ const r=el.getBoundingClientRect(),x=(e.clientX-r.left)/r.width-.5,y=(e.clientY-r.top)/r.height-.5; cancelAnimationFrame(raf);raf=requestAnimationFrame(()=>el.style.transform=`perspective(1200px) rotateX(${-y*max}deg) rotateY(${x*max}deg) translateZ(2px)`) }); el.addEventListener('pointerleave',()=>{cancelAnimationFrame(raf);el.style.transform=''}) }; const bind=()=>{ tilt(document.querySelector('.login-shell'),2.8); tilt(document.querySelector('.home-hero'),2.2); document.querySelectorAll('.home-feature,.premium-stat,.premium-card,.login-feature,.provider-strip').forEach(x=>tilt(x,2.8)); }; bind(); const observer=new MutationObserver(()=>bind()); observer.observe(document.body,{childList:true,subtree:true}); window.addEventListener('beforeunload',()=>observer.disconnect(),{once:true}); })(); if('serviceWorker' in navigator){navigator.serviceWorker.register('./sw.js').catch(()=>{})} async function renderUsers(){if(!remoteMode()){$('#usersBody').innerHTML='Connect the central API and sign in to manage users.';return}try{const x=await api('/api/admin/users');$('#usersBody').innerHTML=x.users.map(u=>`${escape(u.username)}${escape(u.role)}${u.active?'Active':'Inactive'}${new Date(u.createdAt).toLocaleDateString()}`).join('')||'No users.'}catch(e){toast(e.message)}} async function renderOperations(){if(!remoteMode()){$('#opsApi').textContent='LOCAL';$('#opsDb').textContent='—';$('#opsRecords').textContent='—';$('#opsUsers').textContent='—';$('#opsSnapshot').textContent='Connect the central current API for live system telemetry.';$('#opsDistribution').textContent='Live distribution requires the central API.';return}try{const base=state.apiUrl.replace(/\/$/,'');const [h,ready,st,us,sec,met,perm,snap]=await Promise.all([fetch(base+'/api/health').then(r=>r.json()),fetch(base+'/api/ready').then(r=>r.json()),api('/api/stats'),api('/api/admin/users'),api('/api/security/events'),api('/api/admin/metrics'),api('/api/admin/permissions'),api('/api/admin/system-snapshot')]);$('#opsApi').textContent=h.ok?'ONLINE':'ERROR';$('#opsDb').textContent=ready.ready?'READY':'ERROR';$('#opsRecords').textContent=st.total;$('#opsUsers').textContent=us.users.filter(x=>x.active).length;$('#opsTelemetry').innerHTML=`
Uptime: ${Math.floor(met.process.uptimeSeconds/3600)}h ${Math.floor(met.process.uptimeSeconds/60)%60}m
Requests: ${met.requests.requests} · Errors: ${met.requests.errors} · Rate limited: ${met.requests.rateLimited}
DB connections: ${met.db.connections} / ${met.db.max_connections}
AI runtime: ${snap.ai.active}/${snap.ai.maxConcurrent} active · Queue: ${snap.ai.queued??0}
`;$('#opsPermissions').innerHTML=Object.entries(perm.permissions).map(([role,items])=>`
${escape(role)}
${items.map(escape).join(' · ')}
`).join('');$('#opsSecurityList').innerHTML=sec.events.slice(0,8).map(e=>`
${escape(e.action)} · ${escape(e.user||'system')}
${escape(e.detail)} · ${new Date(e.time).toLocaleString()}
`).join('')||'No security events.';$('#opsSnapshot').innerHTML=`
Active records: ${snap.records.active} · Deleted: ${snap.records.deleted}
Active sessions: ${snap.sessions.active} · Audit events (24h): ${snap.audit24h.total}
Pool: ${snap.pool.total} total / ${snap.pool.idle} idle / ${snap.pool.waiting} waiting
Uptime: ${Math.floor(snap.process.uptimeSeconds/3600)}h ${Math.floor(snap.process.uptimeSeconds/60)%60}m
`;const regionHtml=snap.regions.slice(0,8).map(x=>`${escape(x.region||'(blank)')}: ${x.count}`).join(' · ')||'No regions';const sectorHtml=snap.sectors.slice(0,8).map(x=>`${escape(x.sector||'(blank)')}: ${x.count}`).join(' · ')||'No sectors';$('#opsDistribution').innerHTML=`
Regions: ${regionHtml}
Sectors: ${sectorHtml}
`}catch(e){$('#opsMessage').textContent=e.message;toast(e.message)}} $('#opsIntegrityBtn')?.addEventListener('click',async()=>{if(!remoteMode()){toast('Connect the central current API first.');return}$('#opsDiagnostics').textContent='Checking data integrity…';try{const x=await api('/api/admin/data-integrity');const c=x.checks;$('#opsDiagnostics').innerHTML=''+escape(x.status)+' · Missing names '+c.recordsMissingName+' · Orphan history '+c.orphanHistory+' · Orphan documents '+c.orphanDocuments+' · Duplicate usernames '+c.duplicateUsernames;toast(x.ok?'Data integrity clean':'Data integrity issues found')}catch(e){$('#opsDiagnostics').textContent='Integrity check failed: '+e.message;toast('Integrity check failed')}}); $('#opsDiagnosticsBtn')?.addEventListener('click',async()=>{if(!remoteMode()){toast('Connect the central current API first.');return}$('#opsDiagnostics').textContent='Running diagnostics…';try{const x=await api('/api/admin/diagnostics');$('#opsDiagnostics').innerHTML=''+escape(x.status)+' · DB '+(x.checks.database?'OK':'FAIL')+' · Schema '+(x.checks.schema?'OK':'FAIL')+' · AI '+(x.checks.aiRuntime?'OK':'FAIL')+'
Tables '+x.schemaTables+' · Pool '+x.pool.total+' total / '+x.pool.waiting+' waiting · AI active '+x.ai.active+'/'+x.ai.maxConcurrent+'';toast('Diagnostics complete')}catch(e){$('#opsDiagnostics').textContent='Diagnostics failed: '+e.message;toast('Diagnostics failed')}}); $('#opsRefreshBtn')?.addEventListener('click',renderOperations);$('#refreshUsersBtn')?.addEventListener('click',renderUsers); $('#addUserBtn')?.addEventListener('click',()=>$('#userModal').classList.remove('hidden'));$('#closeUserModal')?.addEventListener('click',()=>$('#userModal').classList.add('hidden')); $('#userForm')?.addEventListener('submit',async e=>{e.preventDefault();try{const x=await api('/api/admin/users',{method:'POST',body:JSON.stringify({username:$('#uUsername').value.trim(),role:$('#uRole').value,password:$('#uPassword').value})});$('#userMessage').textContent='Created '+x.user.username+'. Temporary password was accepted by the server; distribute it securely.';toast('User created');await renderUsers()}catch(err){$('#userMessage').textContent=err.message}}); $('#usersBody')?.addEventListener('click',async e=>{const b=e.target.closest('[data-user-action]');if(!b)return;try{await api('/api/admin/users/'+encodeURIComponent(b.dataset.userId),{method:'PATCH',body:JSON.stringify({active:b.dataset.active!=='true'})});toast('User status updated');renderUsers()}catch(err){toast(err.message)}}); $('#opsBackupBtn')?.addEventListener('click',async()=>{try{const x=await api('/api/backup');const raw=JSON.stringify(x,null,2);const digest=await crypto.subtle.digest('SHA-256',new TextEncoder().encode(raw));const sha=Array.from(new Uint8Array(digest)).map(b=>b.toString(16).padStart(2,'0')).join('');const serverSha=x.integritySha256||'not-provided';download('al-syed-jalal-enterprise-backup.json',raw);download('al-syed-jalal-enterprise-backup.sha256',sha+' al-syed-jalal-enterprise-backup.json\n');$('#opsIntegrity').innerHTML='SHA-256
'+escape(sha)+'
Records: '+(x.records?.length||0)+' · Exported: '+new Date(x.exportedAt).toLocaleString()+'';$('#opsMessage').textContent='Backup + SHA-256 manifest downloaded.'}catch(e){$('#opsMessage').textContent=e.message}}); $('#opsRestoreBtn')?.addEventListener('click',()=>$('#opsRestoreFile').click());$('#opsRestoreFile')?.addEventListener('change',async e=>{const f=e.target.files[0];if(!f)return;try{const x=JSON.parse(await f.text());const r=await api('/api/restore',{method:'POST',body:JSON.stringify(x)});$('#opsMessage').textContent=`Restore complete: ${r.restoredRecords} records.`;toast('Restore completed');renderOperations()}catch(err){$('#opsMessage').textContent=err.message}e.target.value='' }); openDB().then(async()=>{if(!(await all(STORE)).length){const seed=[['AJ-001','North Intake Review','North','Operations','Active'],['AJ-002','Central Verification','Central','Verification','Pending'],['AJ-003','South Data Check','South','Data','Verified']];for(const [id,name,region,sector,status] of seed)await put(STORE,{id,name,region,sector,status,notes:'Seed record',updatedAt:new Date().toISOString()})}if(state.apiUrl){try{const x=await api('/api/me');state.user=x.user.username;state.role=x.user.role;showApp()}catch{state.user='';state.role='Admin'}}else if(localStorage.getItem('aj-v31-demo')==='1'){state.user='Operator';state.role='Admin';showApp()}}).catch(e=>toast('Local database unavailable'));