NEXUS — Developer Documentation
v3.0.1 Claude API Voice Ready
// DEVELOPER DOCUMENTATION
NEXUS
AUTONOMOUS AI AGENT
Single HTML file Zero dependencies Anthropic claude-sonnet-4 Web Speech API Build: 2026-03-30

01 Overview

NEXUS is a single-file, browser-hosted AI agent built on the Anthropic Claude API. It combines a hacker-aesthetic terminal UI, persistent multi-turn conversation, real-time system visualisation, and hands-free voice command into one self-contained HTML application — no build step, no backend, no dependencies to install.

The entire agent runs in the user's browser. Only the Anthropic API endpoint (api.anthropic.com) receives outbound network traffic. Google Fonts CDN is optionally used for typefaces.
PropertyValue
Filenexus-agent.html — single self-contained file
Size~12 KB (no external assets; fonts via Google Fonts CDN)
DependenciesNone — vanilla HTML / CSS / JS
APIAnthropic /v1/messages (claude-sonnet-4-20250514)
Browser req.Chrome 90+, Edge 90+, Safari 15+. Chrome recommended for voice.
Voice APIWeb Speech API — SpeechRecognition (not available in Firefox)

02 Architecture

The file is structured into five logical layers, each separated by comment banners inside the source. All state lives in-memory; the only persistence is the conversationHistory[] array for the current session.

Layer Map

L1
Boot Screen
Full-viewport waiting animation on first load. Matrix rain, hex SVG grid, timed boot log, progress bar. Dismissed by user click.
L2
Shell Chrome
Sticky header with logo, nav links, session ID, and pulsing status indicator. Always visible.
L3
Three-Column UI
Left sidebar (tools, memory bars, sessions), centre chat terminal, right sidebar (metrics graph, event log, reasoning preview).
L4
Input Bar
Command prompt with keyboard and voice input, animated waveform visualiser, and EXECUTE button.
L5
JS Runtime
Matrix renderer, boot sequencer, metrics simulator, Claude API client, chat engine, voice subsystem, ambient log emitter.

Data Flow

User input (keyboard / SpeechRecognition)
↓
addMessage("user", text)
renders bubble in DOM
↓
callClaude(text)
appends to conversationHistory[], POSTs to /v1/messages
↓
Anthropic API → JSON response
↓
addMessage("agent", reply)
renders with glitch animation
↓
addLog() / reasoningBox update
updates right sidebar

03 Boot Screen & Waiting Animation

The boot screen is the first thing a user sees. It serves as both a loading sequence and a brand statement, composed of four independent visual layers stacked via position:fixed.

Visual Layers (bottom → top)

LayerElementDescription
1 — Matrix Rain#matrix-canvasCanvas set to position:fixed with opacity:0.07. Random katakana and hex characters fall on a 50 ms interval. Canvas is shared with the main app behind the UI.
2 — Hex Grid.hexgridSVG <pattern> of 60×52 px hexagons via a filled <rect>. Opacity 0.12. Provides structural depth without competing with foreground.
3 — ForegroundCentred flex columnPulsing NEXUS logotype (Orbitron 900, CSS glow), subtitle in VT323, loading bar with sweeping gradient pseudo-element, and staggered boot log lines (400 ms → 3900 ms delays).
4 — Corners.corner ×4Four divs with partial border-width at viewport corners, giving a targeting-reticle frame. Pure CSS, zero JS.

Dismissal

The ENTER NEXUS button appears at delay 4500 ms via animation-delay. Clicking it calls enterApp() which adds the .hidden class, transitioning opacity → 0 and visibility → hidden. The Matrix canvas continues running behind the main UI.

js — enterApp()
function enterApp() {
  document.getElementById('waiting-screen').classList.add('hidden');
  addLog('Session initialized', 'success');
  addLog('All modules loaded', 'info');
}

04 Chat Engine

Conversation History

All messages are stored in a module-level array. The full history is sent on every request so the model maintains context across turns.

js — history management
const conversationHistory = [];

// Before every API call:
conversationHistory.push({ role: "user", content: userMessage });

// After every API response:
conversationHistory.push({ role: "assistant", content: reply });
There is no truncation logic in v3.0.1. For very long sessions the context window may be reached. See Section 8 for a sliding-window mitigation.

System Prompt

The agent's personality is defined in the system field of every API call:

js — system prompt
system: `You are NEXUS — an autonomous AI agent. You are precise,
technical, and slightly intimidating. You speak like a terminal:
concise, direct, with occasional use of system/hacker terminology.
You do not use markdown formatting. You keep responses under 3
paragraphs. You address the user as "operator". You occasionally
reference your memory system, tools, or reasoning process.`

Message Rendering

Each message is inserted into #messages as a .msg div. User messages align right; agent messages align left. A one-shot CSS animation (msgSlide) fades the bubble in from below. Agent responses gain a .glitch class that plays a 0.4 s text-shadow animation simulating screen artefacts.

A "thinking" placeholder (blinking cursor) is added immediately, then removed and replaced with the real response once the API returns.


05 Voice Command Subsystem

Voice input is powered by the browser-native Web Speech API. No third-party library is required.

Initialisation

js — initSpeech()
function initSpeech() {
  const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
  if (!SR) { showToast('Voice not supported'); return null; }
  const r = new SR();
  r.lang           = 'en-US';    // BCP-47 locale
  r.interimResults = true;       // live transcription while speaking
  r.maxAlternatives = 1;
  return r;
}

The recognition object is created lazily on first mic press — not at page load — to avoid unnecessary permission prompts.

Event Lifecycle

EventBehaviour
onstartSets isRecording=true. Adds .recording to mic button (red pulsing glow). Shows waveform visualiser bars. Updates input placeholder.
onresultJoins all transcripts; writes interim text to input field in real time. When final result fires, calls stopVoice() then sendMessage().
onerrorLogs the error type to the event log sidebar and calls stopVoice().
onendCalls stopVoice() — normalises state regardless of how recognition ended.

Waveform Visualiser

Five .viz-bar divs animate via CSS keyframes (vizAnim). Each bar cycles its height from 4 px to 20 px on a staggered animation-delay (0 s → 0.4 s), creating a rolling waveform. The container is hidden by default and shown only while isRecording === true.

Voice recognition requires HTTPS or localhost. It will not function on plain HTTP origins. Chrome and Edge are most reliable; Safari has partial support; Firefox does not implement this API.

06 System Metrics Panel

The right sidebar displays simulated real-time telemetry to reinforce the hacker aesthetic. In a production deployment these values would be replaced with actual data from a backend health endpoint.

js — metric simulation
function updateMetrics() {
  const cpu = 15 + Math.random() * 35;   // 15–50%
  const ram = 40 + Math.random() * 20;   // 40–60%
  const lat = Math.floor(80 + Math.random() * 120); // 80–200 ms

  cpuHist.push(cpu); cpuHist.shift();    // rolling 60-sample buffer
  // … draws canvas sparkline …
}
setInterval(updateMetrics, 1200);

The sparkline canvas is drawn at 2× pixel density (width = offsetWidth * 2) to avoid blurriness on HiDPI screens. On each tick the 60-sample CPU history is plotted as a continuous path with a green CSS shadowBlur. The canvas clears entirely each frame.


07 Event Log

The log stream in the right sidebar is driven by addLog(message, type). Four severity levels map to colours:

TypeColourUsage
info■ green-dimRoutine operational messages
success■ greenConfirmations and completions
warn■ amberNon-critical notices, pending states
err■ redFailures, API errors, voice errors

Timestamps are injected automatically using toLocaleTimeString with 24 h format. The container has scrollbar-width:none to stay visually clean while still scrollable programmatically via scrollTop = scrollHeight.

An ambient interval fires every 4000 ms and cycles through eight canned log lines, maintaining the illusion of background agent activity when idle.


08 API Connection

NEXUS talks to the Anthropic API to power all AI responses. You need an API key to activate it. There are two ways to connect — choose based on whether you are testing locally or deploying for others.

Getting Your API Key

1
Go to console.anthropic.com and create an account.
2
A credit card is required for verification. New accounts receive ~$5 in free credits — you won't be charged until those run out.
3
In the left sidebar click API Keys → Create Key. Give it a name (e.g. nexus-local).
4
Copy the key immediately — it starts with sk-ant- and is shown only once.
$5 in free credits covers roughly 50–100 full conversations on Sonnet, or 300+ on Haiku. University students can apply for up to $300 in credits at console.anthropic.com/education.

Direct Browser Call

Fastest way to get NEXUS running. Your key lives directly in the HTML file. Use only for personal local testing — never deploy this publicly.

Open nexus-agent.html, find the callClaude() function, and update the fetch() headers:

js — callClaude() · add these three headers
const response = await fetch('https://api.anthropic.com/v1/messages', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'x-api-key': 'sk-ant-YOUR-KEY-HERE',        // ← your key
    'anthropic-version': '2023-06-01',             // ← required
    'anthropic-dangerous-direct-browser-calls': 'true' // ← allows browser origin
  },
  body: JSON.stringify({ /* existing body unchanged */ })
});

That's it. Save the file, open it in Chrome, and NEXUS is live.

Your API key is visible to anyone who opens DevTools → Sources. Only use this method locally or for personal demos where you control who has access to the file.

Proxy Server (Recommended)

A lightweight proxy sits between NEXUS and Anthropic. Your key stays on the server — the browser never sees it. This is the correct pattern for any shared or deployed instance.

Step 1 — Create the proxy (Node.js / Express):

js — proxy.js
const express = require('express');
const app = express();
app.use(express.json());

// Allow NEXUS (served from any origin) to reach the proxy
app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
  if (req.method === 'OPTIONS') return res.sendStatus(200);
  next();
});

app.post('/v1/messages', async (req, res) => {
  const response = await fetch('https://api.anthropic.com/v1/messages', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-api-key': process.env.ANTHROPIC_API_KEY,  // key from env var
      'anthropic-version': '2023-06-01',
    },
    body: JSON.stringify(req.body),
  });
  const data = await response.json();
  res.json(data);
});

app.listen(3000, () => console.log('Proxy running → http://localhost:3000'));

Step 2 — Start the proxy:

bash
npm install express
ANTHROPIC_API_KEY=sk-ant-your-key node proxy.js

Step 3 — Point NEXUS at the proxy. In callClaude() change the fetch URL:

js — callClaude() · change the URL only
// Before (direct to Anthropic):
fetch('https://api.anthropic.com/v1/messages', ...)

// After (through your proxy):
fetch('http://localhost:3000/v1/messages', ...)

No other changes needed. The proxy forwards all request bodies and responses transparently.

For serverless deployments, a Cloudflare Worker makes an ideal proxy — it runs at the edge, costs almost nothing, and has built-in secret storage for your API key via wrangler secret put ANTHROPIC_API_KEY.

Which method should I use?

SituationMethod
Testing locally, just youDirect browser call with key in headers
Sharing with friends / colleaguesNode proxy on your machine or a VPS
Public deployment / productionCloudflare Worker or server-side proxy with rate limiting

09 Extending NEXUS

Changing the Model

js — model swap
// Current (balanced performance / cost)
model: 'claude-sonnet-4-20250514',

// Haiku — lower latency and cost
model: 'claude-haiku-4-5-20251001',

// Opus — maximum capability
model: 'claude-opus-4-6',

Modifying Agent Personality

Edit the system string inside callClaude(). The prompt is sent on every request so changes take effect immediately from the next message. You can make NEXUS more verbose, change its address style, give it a domain focus, or instruct it to simulate tool calls.

Adding Tools (UI Only)

The left sidebar tool list is decorative in v3.0.1. To add a display entry:

html — sidebar tool entry
<div class="side-item active">
  <span class="dot"></span>your_tool_name
</div>

To wire real tool execution, implement Anthropic's tool_use API pattern: define tools in the request body, parse tool_use content blocks in the response, execute client-side, and return a tool_result in the next message turn.

Context Window Management

js — sliding window
const MAX_TURNS = 20;
const recentHistory = conversationHistory.slice(-MAX_TURNS);
// use recentHistory in the API call instead of conversationHistory

Persisting Conversations

js — localStorage persistence
function saveHistory() {
  localStorage.setItem('nexus_history', JSON.stringify(conversationHistory));
}

// On page load:
const saved = localStorage.getItem('nexus_history');
if (saved) conversationHistory.push(...JSON.parse(saved));

Real Backend Metrics

json — GET /api/metrics expected shape
{
  "cpu":     23.4,   // percentage 0–100
  "ram":     51.2,   // percentage 0–100
  "latency": 142    // milliseconds
}

10 Configuration Reference

CSS Variables (:root)

VariableDefaultPurpose
--green#00ff41Primary accent — text, borders, glows, matrix rain
--green-dim#00aa2aSecondary accent — inactive items, labels
--green-dark#003310Background fill for dark panels and memory bars
--cyan#00fff9Agent message bubbles and section headings
--red#ff003cRecording state, error log entries
--bg#000000Page background
--panel#020a02Sidebar and header fill
--border#00ff4133Semi-transparent green for all panel borders
--glowtriple shadowFull neon glow effect on focus elements
--glow-smtwo-layer shadowLighter glow for hover and inline accents

JS Constants

ConstantPurpose
bootMessages[]Array of { text, cls, delay } objects controlling the boot sequence log. Add, remove, or reorder entries here.
ambientLogs[]Eight-entry array of [message, level] pairs cycled every 4 s. Extend with domain-specific activity.
max_tokens1000 — passed in every API call. Increase for longer responses at higher cost.
r.lang"en-US" — BCP-47 language tag for voice recognition. Change for other locales (e.g. "el-GR" for Greek).

11 Security Notes

NEXUS currently makes Anthropic API calls directly from the browser. This means your API key would be visible in client-side code if added. The production pattern is to proxy all /v1/messages calls through a backend that injects the key server-side.

Recommended production hardening:

MeasureDetails
API ProxyDeploy a lightweight proxy (Node/Express, Deno, Cloudflare Worker) that holds the API key. NEXUS points to the proxy, not directly to Anthropic.
Rate LimitingEnforce per-session or per-user rate limits at the proxy layer to prevent abuse.
HTTPSRequired for voice recognition and any production deployment. Serve over TLS.
CSP HeaderRestrict connect-src to your proxy domain and fonts.googleapis.com only.
Key StorageNever expose raw API keys in version control or client bundles.

12 Browser Compatibility

🟢
Chrome 90+
Full support
Recommended
🟢
Edge 90+
Full support
webkit prefix
🟡
Safari 15+
Partial
Voice needs gesture
🔴
Firefox
No voice
Chat works fine
🟢
Chrome Android
Full support
Including voice
🟡
Safari iOS
Partial
iOS 14.5+ voice

13 File Structure

nexus-agent.html is fully self-contained. All CSS and JS are inlined:

nexus-agent.html ├── <head> │ ├── Google Fonts import (Share Tech Mono, Orbitron, VT323) │ └── <style> ── ~400 lines of CSS │ ├── CSS variables (:root) │ ├── Matrix canvas & scanline overlay │ ├── Boot / waiting screen │ ├── Header & navigation │ ├── Three-column main layout │ ├── Sidebar components │ ├── Chat messages & bubbles │ ├── Input bar & voice visualiser │ └── Toast notification └── <body> ├── #matrix-canvas ├── #waiting-screen ── boot animation ├── #app │ ├── <header> │ └── <main> │ ├── .sidebar-left │ ├── .chat-area │ └── .sidebar-right ├── #toast └── <script> ── ~280 lines of JS ├── Matrix rain renderer ├── Boot sequence + enterApp() ├── Session init ├── System metrics + sparkline ├── addLog() utility ├── showToast() utility ├── callClaude() ── Anthropic API client ├── addMessage() ── DOM renderer ├── sendMessage() ── orchestrator ├── Voice subsystem ── initSpeech / toggleVoice / stopVoice └── Ambient log interval

↓ Download NEXUS

NEXUS is a single self-contained HTML file. No installer, no package manager, no build step. Download it, drop in your API key, and open it in Chrome.

NEXUS AGENT // nexus-agent.html
v3.0.1 ~12 KB Single file Zero dependencies
DOWNLOAD FILE

After downloading

1
Open nexus-agent.html in a text editor.
2
Find the callClaude() function and add your API key to the headers (see Section 08).
3
Open the file in Chrome or Edge. No server needed for local use.
4
Click ENTER NEXUS after the boot sequence and start talking to your agent.
Voice commands require Chrome or Edge. For Safari/Firefox, all text features work normally — only the 🎤 mic button is unavailable.

NEXUS Documentation // v3.0.1 // OnlyNerds.club - Leonidas Papadopoulos // 2026 nexus-agent.html — Autonomous AI Agent