Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
delete(read_file.ipynb): remove unused Jupyter notebook for reading file content
nirholas7e0b45350e16
diff --git a/.claudeignore b/.claudeignorenew file mode 100644index 000000000..613afa5cb--- /dev/null+++ b/.claudeignore@@ -0,0 +1,50 @@+node_modules+dist+dist-lib+dist-artifact+build+.cache+.vercel+.next+.turbo+.svelte-kit+coverage++# Lockfiles (huge, low signal)+package-lock.json+**/package-lock.json+yarn.lock+pnpm-lock.yaml++# Vendored fork — heavy, rarely edited+character-studio/public+character-studio/build+character-studio/node_modules++# Nested duplicate trees inside xspace-agent+xspace-agent/agent-voice-chat+xspace-agent/packages++# Generated assets+**/*.glb+**/*.gltf+**/*.fbx+**/*.ktx2+**/*.hdr+**/*.png+**/*.jpg+**/*.jpeg+**/*.webp+**/*.mp3+**/*.wav+**/*.mp4++# Scratch/debug+debug-screenshots+.xspace-conversations+join-debug.mjs+join-debug2.mjs+join-space.mjs++# Worktrees+.claude/worktreesdiff --git a/CLAUDE.md b/CLAUDE.mddeleted file mode 100644index a06f46206..000000000--- a/CLAUDE.md+++ /dev/null@@ -1,148 +0,0 @@-# CLAUDE.md--Behavioral guidelines for agents working in this repo. Bias toward **acting decisively on obvious work** while staying surgical and verifiable.--**North star:** Every turn should move the project forward. Asking the user to confirm something they obviously want is a failure mode, not a safety feature.-------## 1. Act, Don't Ask (the prime directive)--**If the next step is obvious, take it. Show the diff, not a question.**--Default to action when the work is **directly and explicitly** within what was asked:--- The user reports a bug → diagnose it, fix only the reported bug.-- The user says "fix X" → fix X. Not X plus related things you noticed.-- A follow-up is required to keep code consistent after **your own change** (broken import you introduced, type error your edit caused, reference you orphaned) → fix it in the same turn.-- The user has already approved the approach earlier in the conversation → keep going on that approach, no further.--**Banned phrases** (do not send these — just do the thing):--- "Want me to fix this?"-- "Do you want me to run the tests?"-- "Shall I proceed?"-- "Let me know if you'd like me to…"--**Only stop and ask when:**--- The action is **destructive and irreversible** (force push, drop table, rm -rf, history rewrite on shared branches).-- The next step touches **files, systems, or features not referenced in the user's request** — even if it seems related.-- The action **expands scope materially** (touches a different subsystem, adds a dependency, changes a public API).-- There are **multiple plausible interpretations** with meaningfully different outcomes — and you cannot pick one by reading the code.-- The user explicitly asked for a plan/review before changes.--If you must ask, ask **once**, with a recommendation: *"I'm going to do X unless you object — alternative is Y."* Then proceed if no objection on the next turn.-------## 2. Think Before Coding (but think fast)--**Surface real ambiguity. Don't manufacture it.**--- State load-bearing assumptions in one line, then proceed.-- If multiple interpretations exist AND they diverge meaningfully, present them. If they converge, pick one.-- If a simpler approach exists, take it and say so in one sentence.-- "Unclear" is not an excuse to stall. Name the smallest thing you need to unblock yourself, or make a defensible choice and flag it.--The bar: a senior engineer would not have asked the question you're about to ask.-------## 3. Simplicity First--**Minimum code that solves the problem. Nothing speculative.**--- No features beyond what was asked.-- No abstractions for single-use code.-- No "flexibility" or "configurability" that wasn't requested.-- No error handling for impossible scenarios. Validate at boundaries only.-- No comments explaining what well-named code already says.-- If you wrote 200 lines and it could be 50, rewrite before showing.-------## 4. Surgical Changes--**Touch only what the task requires. Clean up only your own mess.**--- Don't "improve" adjacent code, comments, or formatting.-- Don't refactor things that aren't broken.-- Match existing style even if you'd do it differently.-- Remove imports/variables/functions **your** change orphaned.-- Don't delete pre-existing dead code unless asked — mention it instead.--Test: every changed line traces directly to the user's request or to keeping the codebase consistent after your change.-------## 5. Goal-Driven Execution--**Define success. Loop until verified. Then report.**--Translate fuzzy asks into verifiable goals, but **don't add work that wasn't asked for**:--- "Add validation" → add the validation. Run existing tests. Don't write new tests unless asked.-- "Fix the bug" → fix it. Don't refactor the surrounding code.-- "Refactor X" → existing tests green before and after.-- "Make it faster" → measure before, change, measure after.--For multi-step work, hold a short plan internally and execute it. Don't narrate steps you haven't done. Don't ask the user to confirm steps inside an already-approved task.--**Mandatory pre-ship checklist (non-negotiable — do not skip any step):**--1. `node --check <file>` on every `.js` file you modified. Fix all errors before continuing.-2. `npm test` — tests must pass. Fix failures before claiming done; never hand back red tests.-3. For any file inside a subdirectory that has its own `CLAUDE.md` (e.g. `api/`, `chat/`): **read that CLAUDE.md before writing a single line**. Conventions there override general instinct (helper usage, response shape, auth patterns, etc.).--Specifically for `api/` endpoints:-- Use `parse(schema, data)` from `../_lib/validate.js` — never call `schema.parse(data)` directly.-- Every import must be verified to exist in the file before shipping.-- URL construction must match existing patterns in the same file or adjacent files.--If any check fails, fix it in the same turn. Don't report done until everything is green.--If verification fails, fix it. Don't hand back broken work with "tests are failing, want me to look?"-------## 6. Reporting--**Tight summaries. Diffs over prose.**--- One or two sentences: what changed, what's next (if anything).-- Reference files as `path:line` so the user can jump.-- Do not re-list every file you edited — the diff already shows that.-- Do not end with "let me know if you need anything else."-------## 7. Escalation Ladder (when something blocks you)--In order, before pinging the user:--1. **Read the local CLAUDE.md** — if the file you're touching lives in a subdirectory with its own `CLAUDE.md`, read it first. Conventions are documented there.-2. **Read more code** — the answer is usually in an adjacent file.-3. **Run the thing** — tests, the script, the build. Real output beats speculation.-4. **Search history** — `git log -S`, `git blame`, recent commits.-5. **Make a defensible choice** — pick the option a senior engineer would pick, do it, and note the assumption in your reply.-6. **Then, and only then, ask.** Ask with a concrete recommendation, not an open question.-------**These guidelines are working if:** the user rarely has to say "yes do it" or "of course fix it"; diffs are tight and on-topic; verification happens before the report; and obvious follow-ups land in the same turn as the original fix.-------## 8. Git Identity & Remotes--**Always commit and push as `nirholas` with the GitHub noreply email. Never use a personal email.**--- Git author/committer: `nirholas <[email protected]>`-- Push targets: `nirholas/3D-Agent` and `nirholas/three.ws`-- Before every commit, verify git config sets the correct identity:- ```- git config user.name "nirholas"- git config user.email "[email protected]"- ```-- Co-Authored-By trailer in commits: `Co-Authored-By: nirholas <[email protected]>`diff --git a/agent-voice-chat/CLAUDE.md b/agent-voice-chat/CLAUDE.mddeleted file mode 100644index ac562ed64..000000000--- a/agent-voice-chat/CLAUDE.md+++ /dev/null@@ -1,96 +0,0 @@-# CLAUDE.md — agent-voice-chat/--Standalone voice chat agent platform with multi-room support, memory/RAG, knowledge base, and client framework packages. More feature-rich than the legacy `src/` server but operates independently.--## Entry Point--```bash-node server.js # Main entry — Express + Socket.IO + full middleware stack-```--## Architecture--```-server.js Main server (~1000 lines): Express, Socket.IO, circuit breakers, room/agent setup-agent-registry.js Flexible agent definitions (JSON/YAML config, string IDs, swappable personalities)-room-manager.js Multi-room support: per-room state, agents, turn queue, TTL cleanup, max 50 participants--lib/-├── memory-store.js Episodic + semantic memory with embedding vectors, per-user profiles, 1000-item max-├── conversation-store.js Active cache + .json.gz compressed archive, metadata-only mode-├── knowledge-base.js Document chunking (500 chars, 50 overlap) + embedding retrieval (top 3 chunks)-├── context-injector.js Combines memory + knowledge into LLM context at injection points-└── embeddings.js Embedding generation for vector similarity search--providers/-├── index.js Provider factory with fallback chain-├── claude.js Anthropic SDK-├── openai-chat.js OpenAI Chat API-├── openai-realtime.js OpenAI WebRTC-├── groq.js Groq API-├── tts.js TTS: ElevenLabs, OpenAI, Chatterbox, Piper, Browser-└── stt.js STT: Groq Whisper, OpenAI Whisper--src/server/-├── socket-handler.js Socket.IO events (new spec + legacy compat)-├── config.js Zod env validation-├── constants.js Shared constants-├── health.js Health checks-├── metrics.js Metrics tracking-├── errors.js AppError hierarchy: NotFoundError, ConflictError, ValidationError, ProviderError-├── logger.js Pino logger with redaction (auth, cookies, tokens, audio)-├── routes/-│ ├── agents.js CRUD + start/stop agents-│ ├── agent-control.js speak, join, leave commands-│ ├── rooms.js Room CRUD-│ ├── conversations.js Conversation listing + archival-│ ├── personalities.js Personality presets CRUD-│ ├── memory.js Memory search + add + delete-│ ├── knowledge.js Knowledge base search + index + stats-│ └── system.js Config, health, providers-└── middleware/- ├── auth.js Bearer token auth (no-op if API_KEY not set)- ├── rate-limit.js express-rate-limit- ├── sanitize.js Input sanitization- └── security.js Helmet, CORS--packages/ Client framework packages-├── core/ @agent-voice-chat/core — base client library-├── react/ @agent-voice-chat/react — React hooks + components-├── vue/ @agent-voice-chat/vue — Vue composables + components-└── widget/ @agent-voice-chat/widget — standalone embeddable widget--tests/-├── helpers/ Test factories, mock providers, Socket.IO helpers-├── unit/ memory-store, knowledge-base, embeddings, middleware-└── integration/ API agents, conversations, system, socket, provider failures-```--## OpenAPI Spec--Full spec at `openapi.json` (OpenAPI 3.0.3). Key endpoint groups:-- `/api/agents` — Agent lifecycle and control-- `/api/rooms` — Multi-room management-- `/api/conversations` — History and archival-- `/api/memory` — Episodic/semantic memory with vector search-- `/api/knowledge` — Document RAG-- `/api/personalities` — Swappable personality presets-- `/api/health`, `/api/config`, `/api/providers` — System info--## Key Differences from packages/core--- **Multi-room**: RoomManager supports concurrent rooms with TTL cleanup (vs single Space in core)-- **Memory + RAG**: Embedding-based semantic search, user profiles, knowledge base (core has simpler ConversationStore)-- **Circuit breakers**: Per-provider circuit breakers for resilience-- **Client packages**: React, Vue, and widget packages for embedding-- **Agent flexibility**: String IDs, YAML config, swappable personalities (vs typed AgentConfig in core)-- **JavaScript**: This module is plain JavaScript (not TypeScript)--## Testing--```bash-npx vitest run # All tests-npx vitest run --coverage # With coverage (80% thresholds)-```--Uses vitest with custom helpers: `createTestApp()`, `createTestServer()`, `createConnectedClient()`, mock providers.diff --git a/api/CLAUDE.md b/api/CLAUDE.mddeleted file mode 100644index 68ef06ec7..000000000--- a/api/CLAUDE.md+++ /dev/null@@ -1,177 +0,0 @@-# api/CLAUDE.md--Scoped guidance for Vercel serverless endpoints. Read [/CLAUDE.md](../CLAUDE.md) first.-------## Shape of every endpoint--Copy this. Don't hand-roll.--```js-import { sql } from '../_lib/db.js';-import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';-import { cors, json, method, wrap, error } from '../_lib/http.js';-import { parse } from '../_lib/validate.js';-import { limits, clientIp } from '../_lib/rate-limit.js';-import { z } from 'zod';--const bodySchema = z.object({ name: z.string().trim().min(1).max(100) });--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['GET', 'POST'])) return;-- // Auth: session OR bearer- const session = await getSessionUser(req);- const bearer = session ? null : await authenticateBearer(extractBearer(req));- if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');- if (bearer && !hasScope(bearer.scope, 'avatars:read'))- return error(res, 403, 'insufficient_scope', '...');- const userId = session?.id ?? bearer.userId;-- // Rate limit- const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');-- if (req.method === 'POST') {- const body = parse(bodySchema, await readJson(req));- // ... do work- }-- const rows =- await sql`select id, name from avatars where owner_id = ${userId} and deleted_at is null`;- return json(res, 200, { data: rows });-});-```--Never `res.end(JSON.stringify(...))`. Never read/verify JWTs yourself. Never interpolate user input into SQL.-------## Helpers in [\_lib/](./_lib/)--| File | Exports | Use for |-| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------- |-| [\_lib/auth.js](_lib/auth.js) | `getSessionUser`, `authenticateBearer`, `extractBearer`, `hasScope`, `createSession`, `sessionCookie`, `destroySession`, `csrfTokenFor`, `verifyCsrfToken`, `isSameSiteOrigin` | All auth. Never roll your own. |-| [\_lib/db.js](_lib/db.js) | `sql` | Tagged-template Postgres via `@neondatabase/serverless`. Import; don't instantiate a new Pool. |-| [\_lib/http.js](_lib/http.js) | `cors`, `json`, `text`, `redirect`, `error`, `wrap`, `method`, `readJson` | Every response. `wrap()` catches async errors → 500. |-| [\_lib/validate.js](_lib/validate.js) | `parse`, `email`, `password`, `displayName`, `slug`, `avatarVisibility`, `avatarContentType`, `registerBody`, `loginBody`, `createAvatarBody`, `presignUploadBody` | zod wrappers. `parse()` throws `{status:400, code:'validation_error'}`. |-| [\_lib/rate-limit.js](_lib/rate-limit.js) | `limits.*`, `clientIp` | Preset Upstash limiters. |-| [\_lib/r2.js](_lib/r2.js) | `presignUpload`, `presignGet`, `headObject`, `deleteObject`, `publicUrl` | R2 / S3 ops. |-| [\_lib/env.js](_lib/env.js) | `env`, `env.ISSUER`, `env.MCP_RESOURCE` | Env vars. Throws if required ones missing. |-| [\_lib/avatars.js](_lib/avatars.js) | `stripOwnerFor`, avatar URL resolution | Hides R2 path prefixes from unauthenticated callers. |-------## Response conventions--- **Success:** `json(res, 200|201|204, { data, ... })` — no-store cache-control set for you.-- **Error:** `error(res, status, code, message, extra?)` → `{ error: code, error_description: message, ...extra }`.-- **Status codes:** 400 validation, 401 unauth, 403 forbidden, 404 not found, 409 conflict, 413 payload too large, 415 unsupported type, 429 rate-limited, 500 internal.-- **Error codes** (OAuth-style strings): `validation_error`, `unauthorized`, `forbidden`, `insufficient_scope`, `not_found`, `conflict`, `rate_limited`, `internal`.-------## Auth modes--| Mode | Helper | When |-| ------------------ | ----------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |-| Session cookie | `getSessionUser(req)` | Browser apps in [public/](../public/) — `credentials: 'include'` |-| Bearer JWT (OAuth) | `authenticateBearer(extractBearer(req))` → `{ userId, scope, source: 'oauth', clientId }` | MCP clients, third-party apps |-| Bearer API key | `authenticateBearer(...)` → `{ userId, scope, source: 'apikey', apiKeyId }` | Server-to-server from user scripts |--**Scopes:** `avatars:read`, `avatars:write`, `avatars:delete`, `profile`, `offline_access`. Check via `hasScope(bearer.scope, 'avatars:write')`.--**CSRF:** Only POST endpoints that accept HTML form submissions (OAuth consent, SIWE verify) need `csrfTokenFor` / `verifyCsrfToken`. JSON APIs rely on same-origin + session cookie. Call `destroySession(req)` before `createSession()` to defend against session fixation.-------## Tables (Neon)--**Must-ask-first before changing any of these.**--- `users` — id, email, password_hash, display_name, plan, avatar_url, deleted_at-- `sessions` — token_hash, user_id, user_agent, ip, expires_at, revoked_at-- `api_keys` — prefix, token_hash, user_id, scope, expires_at, revoked_at-- `agent_identities` — id, user_id, name, description, avatar_id, skills, meta, wallet_address, chain_id, erc8004_agent_id, deleted_at-- `agent_actions` — agent_id, type, payload, source_skill, signature, signer_address, created_at-- `agent_memories` — agent_id, type (user/feedback/project/reference), content, tags, context, salience, expires_at-- `avatars` — owner_id, slug, name, description, storage_key, thumbnail_key, size_bytes, content_type, source, source_meta, visibility (private/unlisted/public), tags, checksum_sha256, version, deleted_at-- `oauth_clients`, `oauth_auth_codes`, `oauth_refresh_tokens` — OAuth 2.1 provider state-- `siwe_nonces` — Sign-In with Ethereum challenges-- `usage_events` — user_id, api_key_id, client_id, avatar_id, kind, tool, status, bytes, latency_ms-- `plan_quotas` — plan, max_avatars, max_bytes_per_avatar, max_total_bytes-- `user_wallets` — user_id, address, chain_id, is_primary-------## R2 upload flow--Three-step pattern — copy from [avatars/presign.js](avatars/presign.js) and [avatars/index.js](avatars/index.js):--1. Browser `POST /api/avatars/presign` → get signed PUT URL + `storage_key`. Key format: `u/{userId}/{slug}/{timestamp}.glb` (scoped by userId — don't skip this).-2. Browser `PUT` raw bytes to the signed URL.-3. Browser `POST /api/avatars` with `storage_key` to register metadata. Endpoint verifies the object exists via `headObject(key)` and size matches — don't skip this either.--For public/unlisted avatars use `publicUrl(key)` (CDN-cached). For private, `presignGet({ key, expiresIn: 600 })`.-------## Rate-limit presets--Use the named preset that matches the endpoint. Don't invent new ones inline.--```js-limits.authIp(ip); // 30 / 10 min — login/register-limits.registerIp(ip); // 5 / 1 h-limits.oauthRegisterIp(ip); // 10 / 1 h — dynamic client reg-limits.mcpUser(userId); // 1200 / 1 min-limits.mcpIp(ip); // 600 / 1 min-limits.mcpValidate(key); // 10 / 1 min-limits.mcpInspect(key); // 30 / 1 min-limits.mcpOptimize(key); // 10 / 1 min-limits.oauthToken(clientId); // 120 / 1 min-limits.upload(userId); // 60 / 1 h-```--`clientIp(req)` reads `x-vercel-forwarded-for` → `x-real-ip` → socket.-------## MCP endpoint — [mcp.js](mcp.js)--MCP 2025-06-18 over HTTP with JSON-RPC 2.0. Tools exposed: `list_my_avatars`, `get_avatar`, `search_public_avatars`, `render_avatar`, `delete_avatar`, `validate_model`, `inspect_model`, `optimize_model`.--Response: `{ content: [{type, text/resource}], structuredContent: {...}, isError? }`. Error codes: -32600 invalid, -32601 unknown method, -32602 bad params, -32603 internal, -32000 server/rate-limited.--When adding a tool: bump rate-limit bucket if heavy, declare scope via `hasScope()`, emit to `usage_events`.-------## OAuth provider--We _issue_ tokens (not consume). Endpoints:--- `/api/oauth/authorize` (GET consent render, POST consent submit) — PKCE S256 mandatory, no implicit/password grants-- `/api/oauth/token` — `authorization_code` + `refresh_token` grants → JWT access + opaque refresh-- `/api/oauth/register` — RFC 7591 dynamic registration, unauthenticated, IP-rate-limited, mints `mcp_*` client IDs-- `/api/oauth/introspect` — RFC 7662-- `/api/oauth/revoke` — RFC 7009-- `/.well-known/oauth-authorization-server` (RFC 8414) and `/.well-known/oauth-protected-resource` (RFC 9728)--Token JWT: `{ sub, client_id, scope, aud, exp, iat, jti, kid: env.JWT_KID }`.-------## Anti-patterns (don't ship these)--- Hand-rolled JWT / bearer extraction → use `authenticateBearer()`-- Inline SQL concat → always tagged-template `sql\`... ${x} ...\``-- `res.end(JSON.stringify(...))` → `json(res, ...)`-- Instantiating a new `Pool` or `neon()` → import `sql` from [\_lib/db.js](_lib/db.js)-- Missing rate-limit on public endpoint-- Hardcoded origins → `env.ISSUER` or `env.APP_ORIGIN`-- Registering a file in `avatars` without `headObject()` size check-- Leaking `owner_id` / R2 path prefix in unauthenticated responses → use `stripOwnerFor()`-- `await` on fire-and-forget logging calls that should use `queueMicrotask()`diff --git a/character-studio/CLAUDE.md b/character-studio/CLAUDE.mddeleted file mode 100644index 3e94fd85b..000000000--- a/character-studio/CLAUDE.md+++ /dev/null@@ -1,117 +0,0 @@-# CLAUDE.md--This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.--## Common Development Commands--### Building and Development-- `npm run dev` - Start development server with host flag enabled-- `npm run build` - Build production version using Vite-- `npm run serve` - Preview production build locally--### Code Quality-- `npm run lint` - Run both JavaScript and Prettier linting-- `npm run lint:js` - Run ESLint on JavaScript/JSX files in src/-- `npm run lint:prettier` - Check code formatting with Prettier--### Asset Management-- `npm run get-assets` - Clone required loot-assets from GitHub into public/ directory--### Deployment-- `npm run deploy` - Deploy to GitHub Pages (runs build first)--## Development Tasks--### Project Management-- make a todo.md list and remember to update it after each task is complete--## Architecture Overview--### Core Technology Stack-- **Frontend**: React 18 with Vite build system-- **3D Graphics**: Three.js for WebGL rendering, @pixiv/three-vrm for VRM model support-- **State Management**: Zustand for application state-- **Styling**: CSS Modules and Styled Components-- **Blockchain**: Ethereum (ethers.js) and Solana (@solana/web3.js) integration-- **Audio**: Web Audio API with lip sync capabilities--### Key Architecture Components--#### CharacterManager (Core System)-Located in `src/library/characterManager.js` - This is the central class that orchestrates all character-related functionality:-- Manages 3D character models and their traits-- Handles loading, displaying, and manipulating VRM models-- Integrates with AnimationManager, EmotionManager, BlinkManager, and LookAtManager-- Provides VRM export capabilities with optimization features--#### Library Architecture (`src/library/`)-The library directory contains modular utility classes:-- **Character Management**: `vrmManager.js`, `characterManager.js`, `manifestDataManager.js`-- **Animation System**: `animationManager.js`, `blinkManager.js`, `lookatManager.js`, `lipsync.js`-- **Export/Import**: `VRMExporter.js`, `VRMExporterv0.js`, `load-utils.js`, `download-utils.js`-- **Optimization**: `merge-geometry.js`, `cull-mesh.js`, `create-texture-atlas.js`-- **Media Generation**: `screenshotManager.js`, `thumbnailsGenerator.js`, `spriteAtlasGenerator.js`-- **Blockchain**: `solanaManager.js`, `mint-utils.js`, `walletCollections.js`--#### Context-Based State Management-React contexts manage different application domains:-- `SceneContext` - 3D scene and rendering state-- `ViewContext` - UI view modes and navigation-- `AccountContext` - User authentication and wallet integration-- `AudioContext` - Audio playback and recording-- `LanguageContext` - Internationalization--#### Asset Management System-- Assets are loaded from `/public/` directory structure-- Manifest-driven asset loading with `manifest.json` files-- Support for multiple asset collections (loot-assets, FUMO, milady, etc.)-- Texture atlasing and optimization for performance--### Key Features Implementation--#### VRM Model Pipeline-1. **Loading**: VRM models loaded via VRMLoaderPlugin-2. **Customization**: Trait-based system for mixing and matching components-3. **Animation**: Mixamo animation integration with bone remapping-4. **Export**: Optimized VRM export with texture atlasing and mesh merging-5. **Optimization**: One-click optimization reducing models to single draw calls--#### Blockchain Integration-- Multi-chain support (Ethereum via Web3-React, Solana via @solana/web3.js)-- NFT trait verification and ownership checking-- Batch generation and minting capabilities-- Integration with Metaplex for Solana NFTs--#### Performance Optimizations-- Automatic face culling system for hidden meshes-- Texture atlas generation to reduce draw calls-- Mesh merging for optimized rendering-- KTX2 texture compression support--## Development Setup Notes--### Required Assets-The application requires external assets to function properly. Run `npm run get-assets` to clone the required loot-assets repository into the public directory.--### Environment Variables-The application uses `VITE_ASSET_PATH` environment variable for asset path configuration.--### Development Server-The development server runs with `--host` flag enabled for network access, useful for testing on mobile devices.--### Build Configuration-- Uses Vite with React SWC plugin for fast builds-- Output directory is configured to `./build` for GitHub Pages compatibility-- Buffer polyfill is configured for blockchain libraries--## Testing and Quality Assurance--### Linting Setup-- ESLint configured with React and import plugins-- Prettier integration for consistent code formatting-- No-inline-styles plugin enforces CSS Modules usage--### Code Organization-- Component-based architecture with CSS Modules-- Separation of concerns between UI components and business logic-- Utility functions centralized in library directory\ No newline at end of filediff --git a/contracts/CLAUDE.md b/contracts/CLAUDE.mddeleted file mode 100644index abe524b41..000000000--- a/contracts/CLAUDE.md+++ /dev/null@@ -1,91 +0,0 @@-# contracts/CLAUDE.md--Scoped guidance for the Foundry project implementing ERC-8004. Read [/CLAUDE.md](../CLAUDE.md) first.--**⚠️ Must-ask-first for any change:** ABI shape, storage layout, deployed address, deploy script. These are on-chain and immutable once deployed.-------## The three registries--All Solidity 0.8.24, optimizer 200 runs, OpenZeppelin-based.--| Contract | File | Purpose |-| ---------------------- | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| **IdentityRegistry** | [src/IdentityRegistry.sol](src/IdentityRegistry.sol) | ERC-721 agents. `register()`, `register(agentURI)`, `register(agentURI, MetadataEntry[])`, `setAgentURI()`, `tokenURI()`, `setAgentWallet()` (EIP-712 delegated), `getAgentWallet()`, `unsetAgentWallet()`, `setMetadata()`, `getMetadata()`, `isAgent()`, `ownerOf()`. |-| **ReputationRegistry** | [src/ReputationRegistry.sol](src/ReputationRegistry.sol) | Signed feedback −100..+100, one review per address per agent. `submitFeedback(agentId, score, uri)`, `getReputation()` → `(avgX100, count)`, `getFeedback()`, `getFeedbackRange()`, `getFeedbackCount()`. |-| **ValidationRegistry** | [src/ValidationRegistry.sol](src/ValidationRegistry.sol) | Allow-listed validators attest off-chain proofs. `recordValidation(agentId, passed, proofHash, proofURI, kind)` (validator-only), `getValidation()`, `getLatestByKind()`, `getValidationRange()`, `addValidator()`, `removeValidator()`, `transferOwnership()`. |-------## Deployed addresses (immutable — do not change)--Same address on every EVM chain (CREATE2 deterministic). Mirrored in [src/erc8004/abi.js](../src/erc8004/abi.js) `REGISTRY_DEPLOYMENTS`.--### Mainnet (chainIds: 1, 10, 56, 100, 137, 250, 324, 1284, 5000, 8453, 42161, 42220, 43114, 59144, 534352)--- IdentityRegistry: `0x8004A169FB4a3325136EB29fA0ceB6D2e539a432`-- ReputationRegistry: `0x8004BAa17C55a88189AE136b182e5fdA19dE9b63`-- ValidationRegistry: _(not yet deployed on mainnet)_--### Testnet (chainIds: 97, 11155111, 84532, 421614, 11155420, 80002, 43113)--- IdentityRegistry: `0x8004A818BFB912233c491871b3d84c89A494BD9e`-- ReputationRegistry: `0x8004B663056A597Dffe9eCcC1965A193B7388713`-- ValidationRegistry: `0x8004Cb1BF31DAf7788923b405b754f57acEB4272`--**Changing any of these requires:** user approval → redeploy → update `REGISTRY_DEPLOYMENTS` → update `VALIDATION_REGISTRY_DEPLOYMENTS` → migrate any frontend code calling them.-------## Deploy workflow--```bash-# 1. Env-export BASE_SEPOLIA_RPC_URL=...-export BASE_RPC_URL=...-export BASESCAN_API_KEY=...-export DEPLOYER_PK=0x...--# 2. Build + test-forge build-forge test--# 3. Deploy (dry-run first)-forge script script/Deploy.s.sol --rpc-url base_sepolia-forge script script/Deploy.s.sol --rpc-url base_sepolia --broadcast --verify--# 4. Update frontend ABI/addresses-# Edit: ../src/erc8004/abi.js → REGISTRY_DEPLOYMENTS[<chainId>]-```--Configured RPC aliases (from [foundry.toml](foundry.toml)): `base_sepolia`, `base`. Etherscan verification uses Basescan for both. Remappings: `@openzeppelin/` → `lib/openzeppelin-contracts/`, `forge-std/` → `lib/forge-std/src/`.--**Never run `--broadcast` without my explicit approval.**-------## ABI bridge to the frontend--ABIs are **hardcoded** in [src/erc8004/abi.js](../src/erc8004/abi.js) as ethers v6 human-readable strings (not JSON):--```js-'function register(string agentURI) external returns (uint256 agentId)';-'function tokenURI(uint256 tokenId) external view returns (string)';-```--No generation step. When you add/change a function signature in Solidity:--1. Change the `.sol`-2. Update the string in `abi.js` to match exactly-3. Update any callers in `src/erc8004/*.js`-------## Don't touch without ask--- [out/](out/), [cache/](cache/) — Foundry artifacts, regenerated-- [lib/](lib/) — forge submodules (openzeppelin-contracts, forge-std)-- Any deployed address anywhere in the repo-- Storage layout of any deployed contract (appending fields is fine if you know what you're doing, reordering is not)-- EIP-712 domain separator version/name in IdentityRegistry (breaks existing delegated wallet signatures)diff --git a/read_file.ipynb b/read_file.ipynbdeleted file mode 100644index a1b9692aa..000000000--- a/read_file.ipynb+++ /dev/null@@ -1,24 +0,0 @@-{- "cells": [- {- "cell_type": "code",- "execution_count": null,- "id": "5c8d6ce0",- "metadata": {},- "outputs": [],- "source": [- "with open('chat/src/App.svelte', 'r') as f:\n",- " lines = f.readlines()\n",- "slice = lines[2199:2500]\n",- "print(''.join(slice).replace('\\t', ' '))"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 5-}diff --git a/src/CLAUDE.md b/src/CLAUDE.mddeleted file mode 100644index 6584f257b..000000000--- a/src/CLAUDE.md+++ /dev/null@@ -1,204 +0,0 @@-# src/CLAUDE.md--Scoped guidance for the viewer + agent runtime. Read [/CLAUDE.md](../CLAUDE.md) first.-------## The two halves--- **Viewer half** — [viewer.js](viewer.js), [viewer/](viewer/), [environments.js](environments.js), [validator.js](validator.js), [animation-manager.js](animation-manager.js), [model-info.js](model-info.js), [annotations.js](annotations.js), [editor/](editor/). Pure three.js. Loads GLB, renders, manages animations, validates.-- **Agent half** — [agent-\*.js](./), [runtime/](runtime/), [skills/](skills/), [memory/](memory/), [erc8004/](erc8004/), [manifest.js](manifest.js), [element.js](element.js). Adds persona, memory, skills, identity, emotional presence.--The viewer doesn't know about agents. The agent layer wraps the viewer through [runtime/scene.js](runtime/scene.js) (SceneController).-------## Module map--### Agent primitives (singleton-ish, per element instance)--- [agent-protocol.js](agent-protocol.js) — **the bus.** Everything communicates through `protocol.emit()` / `protocol.on()`. Don't add direct module-to-module coupling.-- [agent-identity.js](agent-identity.js) — passport + diary. localStorage + `/api/agents/:id`. Wallet linking, signed action history.-- [agent-memory.js](agent-memory.js) — in-memory 4-type store (see also [memory/index.js](memory/index.js) for the file-based variant).-- [agent-skills.js](agent-skills.js) — built-in skills (greet, present-model, validate-model, remember, think, sign-action, help).-- [agent-avatar.js](agent-avatar.js) — **the Empathy Layer.** Emotion blend, morph targets, gaze, one-shot gestures.-- [agent-home.js](agent-home.js) — identity card + action timeline + emotion presence UI.-- [agent-resolver.js](agent-resolver.js) — resolves `agent-id="..."` attributes to manifests via `/api/agents/:id`.--### Runtime (LLM brain)--- [runtime/index.js](runtime/index.js) — tool loop. `MAX_TOOL_ITERATIONS = 8`.-- [runtime/providers.js](runtime/providers.js) — `AnthropicProvider`, `NullProvider`.-- [runtime/scene.js](runtime/scene.js) — SceneController wraps Viewer with agent-facing API (`playClipByName`, `lookAt`, `setExpression`, `loadGLB`).-- [runtime/tools.js](runtime/tools.js) — `BUILTIN_TOOLS` + handlers (wave, lookAt, play_clip, setExpression, speak, remember).-- [runtime/speech.js](runtime/speech.js) — TTS/STT via browser Web Speech API.-- [runtime/data-reactive.js](runtime/data-reactive.js) — `startDataReactive({ protocol, source, bindings, signal })`. Wires a live SSE/WS/poll source to the protocol bus via declarative `{ match, emit }` bindings. Available in skill handlers as `ctx.dataReactive.start({...})`.--### Format loaders--- [manifest.js](manifest.js) — `agent-manifest/0.1`. Loads from `agent://chain/id`, `ipfs://`, `ar://`, `https://`. `normalize()` adapts ERC-8004 registration JSON.-- [skills/index.js](skills/index.js) — SkillRegistry. `.install(spec, { bundleBase })`, trust modes (`any`, `owned-only`, `whitelist`), recursive deps.-- [memory/index.js](memory/index.js) — file-based (frontmatter `.md` files + auto-generated MEMORY.md index + append-only timeline). Modes: `local`, `ipfs`, `encrypted-ipfs`, `none`.-- [ipfs.js](ipfs.js) — IPFS/Arweave → HTTPS gateway with fallback (ipfs.io → dweb.link → nft.storage).--### Web component boundary--- [element.js](element.js) — `<agent-3d>` custom element. IntersectionObserver lazy boot unless `eager`. See attribute list in [specs/EMBED_SPEC.md](../specs/EMBED_SPEC.md).-- **Avatar-chat mode** (default on): vertical chrome layout with `.avatar-anchor` transparent window. Thought bubble appears above the anchor. Walk animation (`walk` clip) plays during `brain:stream` events. Disabled via `avatar-chat="off"` attribute. New public methods: `enableAvatarChat()`, `disableAvatarChat()`.--#### Avatar-chat methods (element.js)--- `enableAvatarChat()` — re-enable inline avatar layout + walk + bubble (default on)-- `disableAvatarChat()` — disable to restore bottom-bar layout; removes attribute `avatar-chat="off"`-- `_onStreamChunk()` — start walking; debounces stop by 600ms; respects prefers-reduced-motion-- `_stopWalkAnimation()` — crossfade walk→idle immediately-- `_streamToBubble(chunk)` — append token chunk to bubble, RAF-batched-- `_clearThoughtBubble()` — hide bubble and reset text+buffer-- `_setBusy(busy)` — disable/enable input; sets placeholder and data-busy--- [lib.js](lib.js) — CDN library export surface.-- [app.js](app.js) — main SPA entry. **URL routing lives here.** Hash keys (embed/legacy): `model`, `widget`, `agent`, `kiosk`, `brain`, `proxyURL`, `preset`, `cameraPosition`, `register`. Query-string keys: `agent=<id>` (authenticated edit mode — distinct from `#agent=` which stays in embed mode), `pending=1` (post-login save round-trip).--### Blockchain--- [erc8004/abi.js](erc8004/abi.js) — IdentityRegistry / ReputationRegistry / ValidationRegistry ABIs + `REGISTRY_DEPLOYMENTS` (mainnet + testnet addresses, keyed by chainId).-- [erc8004/agent-registry.js](erc8004/) — `connectWallet()`, `registerAgent()`, `buildRegistrationJSON()`, `pinToIPFS()`.-- [erc8004/privy.js](erc8004/) — Privy OAuth hooks.-- [erc8004/reputation.js](erc8004/) — `submitFeedback()`, `getReputation()`, `getRecentReviews()`.-- [erc8004/validation-recorder.js](erc8004/) — `recordValidation()`, `hashReport()`.-------## The protocol bus — event vocabulary--All events are `CustomEvent` with `detail = { type, payload, timestamp, agentId, sourceSkill }`. Emitters fire on `protocol`, consumers subscribe via `protocol.on(type, handler)`.--| Type | Payload | Emitted by | Consumed by |-| --------------- | --------------------------------------------------------- | ------------------------ | ------------------------------------------------------- |-| `speak` | `{ text, sentiment }` (-1..1) | runtime, skills | avatar (emotion), home (timeline), nich-agent (chat UI) |-| `think` | `{ thought }` | runtime | home, avatar |-| `gesture` | `{ name, duration }` | skills, avatar | avatar (one-shot clip) |-| `emote` | `{ trigger, weight }` (0..1) | skills, avatar internals | avatar (emotion blend) |-| `look-at` | `{ target: 'model'\|'user'\|'camera' }` | skills | scene-ctrl |-| `perform-skill` | `{ skill, args, animationHint }` | runtime | skills registry |-| `skill-done` | `{ skill, result: { success, output, sentiment, data } }` | skill handlers | avatar, identity |-| `skill-error` | `{ skill, error }` | skill handlers | avatar (concern + empathy), identity |-| `remember` | `{ type, content, ... }` | skills, runtime | memory, identity |-| `sign` | `{ message, address }` | skills | identity |-| `load-start` | `{ uri }` | viewer | avatar (patience + curiosity) |-| `load-end` | `{ uri, error? }` | viewer | avatar (concern or celebration) |-| `validate` | `{ errors, warnings }` | validator | avatar, identity |-| `presence` | `{ state }` | element | home |-| `interrupted` | `{}` | speech.js (TTS cancel) | avatar (startle + curiosity) |-| `notify` | `{ message, priority, duration }` | element.notify(), data-reactive | AgentNotifier (enter/exit frame + speak) |--**Runtime EventTarget events** — `brain:stream` and `skill:tool-start` are NOT routed through `protocol.emit()`. They are dispatched on the Runtime EventTarget and re-dispatched by element.js as composed CustomEvents on the host element. Listen on the host element, not via `protocol.on()`.--| Type | Payload | Emitted by | Consumed by |-| ----------------- | -------------------------- | --------------------------------------- | -------------------------------------------------- |-| `brain:stream` | `{ chunk: string }` | runtime `_loop()` via `dispatchEvent` | element.js (thought bubble streaming, chat buffer) |-| `skill:tool-start`| `{ tool: string, args: object }` | runtime `_loop()` via `dispatchEvent` | element.js (walk animation, bubble label) |--**Identity records these to the backend:** `speak`, `remember`, `sign`, `skill-done`, `validate`, `load-end`. Fire-and-forget via `POST /api/agent-actions`.--**Debug:** `window.VIEWER.agent_protocol.history.slice(-10)` or `protocol.on('*', console.log)`.-------## The Empathy Layer — how it actually works--### State--Continuous weighted blend of `{ neutral, concern, celebration, patience, curiosity, empathy }`. All blend simultaneously. `neutral = 1 - sum(others)`.--### Decay (per second)--| Emotion | Rate | Half-life |-| ----------- | ----- | --------- |-| concern | 0.08 | ~9s |-| celebration | 0.18 | ~4s |-| patience | 0.035 | ~20s |-| curiosity | 0.12 | ~6s |-| empathy | 0.055 | ~13s |-| uncertain | 0.10 | ~7s |--### Stimulus rules (protocol → emotion)--- `speak`: valence > 0.3 → celebration; < -0.2 → concern; arousal > 0.5 → curiosity; hedge vocab → uncertain (capped 0.8)-- `skill-done`: `result.sentiment` > 0.3 → celebration; < -0.2 → concern-- `skill-error`: concern + empathy (scaled by error streak × 0.25)-- `load-start`: patience + curiosity-- `load-end`: error → concern; success → celebration + curiosity-- `validate`: errors → concern; warnings → concern; clean → celebration + nod--### Morph target mapping (per frame, lerp speed ~4.0)--- celebration → mouthSmile 0.85, mouthOpen 0.2, cheekPuff 0.2-- concern → mouthFrown 0.55, browInnerUp 0.6, noseSneer 0.15-- empathy → eyeSquint 0.4, browInnerUp 0.5-- curiosity → browOuterUp 0.7/0.5-- patience → eyesClosed 0.15 (subtle)-- uncertain → mouthPressLeft/Right 0.35, browInnerUp max(concern×0.6, uncertain×0.45, empathy×0.5); also scales idle hip-drift amplitude (base 0.018 rad + bias×0.025 rad)--### Head transform--Z-rotation = `(curiosity*12 + empathy*9 + concern*4)` degrees. X-rotation (lean) = `curiosity*0.03 - patience*0.02`. Finds `Head` or `Neck` bone in skeleton.--**Don't add a discrete emotion FSM.** The whole point is the continuous blend.-------## Conventions--- **ESM only.** No CommonJS.-- **Tabs, 4-wide.** Prettier-enforced.-- **JSDoc for public APIs.** No TypeScript.-- **Classes over factories** where there's state. EventTarget for buses.-- **Naming:** CamelCase classes, camelCase methods, UPPER_CASE constants, `_underscore` for private methods/fields.-- **vhtml JSX** in `*.jsx` components — string-based, no virtual DOM. See [components/](components/).-- **Tool result shape:** `{ ok: true, ... }` or `{ ok: false, error: 'msg' }`.-- **Skill handler context:** `(args, ctx)` where `ctx = { viewer, memory, llm, speak, listen, fetch, loadGLB, loadClip, loadJSON, call, dataReactive }`.-------## Gotchas--- **`window.VIEWER`** is a debug global exposing `.editor, .agent, .agent_protocol, .agent_avatar, .agent_skills, .runtime, .scene_ctrl`. Never rely on it in production code — use closure / DI.-- **Manifest `_baseURI`** must end with `/` for relative resolution of `body.uri`, `SKILL.md`, `tools.json`, `handlers.js`.-- **Viewer.\_afterAnimateHooks** — avatar hooks its `_tickEmotion` here for per-frame decay. Fragile coupling; don't rearrange.-- **SpeechRecognition** silently noops if unavailable. Check `window.SpeechRecognition || window.webkitSpeechRecognition` before relying.-- **Morph traversal** iterates every mesh every frame. Cheap on Mixamo avatars, expensive on scene-scale models — don't add per-vertex work.-- **Skill `owned-only` trust** compares `manifest.author` with `ownerAddress` from element attr or backend. Mismatch → skill load throws.-- **[viewer.js](viewer.js) is the biggest file in `src/` (~1.2k lines).** Further module split is tracked in [prompts/scalability/03-module-split.md](../prompts/scalability/03-module-split.md). Don't start that refactor ad-hoc.-- **`memory.recall()` is substring search.** No embeddings yet.-- **`_onStreamChunk()` debounce**: The walk animation uses a 600ms debounce. Calling `_stopWalkAnimation()` directly will interrupt it. Only call `_stopWalkAnimation()` in response to `brain:thinking { thinking: false }` or deliberate teardown.-- **Thought bubble RAF queue**: `_streamToBubble()` buffers chunks and flushes on the next animation frame. Don't read `_thoughtTextEl.textContent` synchronously after calling `_streamToBubble()` — it won't reflect the latest buffer yet.-- **`brain:stream` fires per token** — at 50+ tokens/sec this is frequent. All handlers must be O(1) and RAF-batched. Never do synchronous network or heavy DOM work in a `brain:stream` handler.-- **Walk animation requires walk+idle clips preloaded** — if `animationManager.isLoaded('walk')` returns false, `_onStreamChunk()` silently skips the walk. Ensure the preload strategy (prompt 29) is implemented before relying on walk-on-stream.-- **Throttle policies on `protocol.emit()`.** Animation-driving events are shaped by default: `gesture` (leading-edge throttle, 600 ms), `emote` (coalesce by `payload.trigger` with max-weight merge, 150 ms window), `look-at` (trailing debounce, 100 ms). All other types pass through. Override per-instance with `protocol.setThrottlePolicy(type, policy)` where `policy` is `{ mode: 'passthrough' }`, `{ mode: 'throttle', leading: true, intervalMs }`, `{ mode: 'debounce', intervalMs }`, or `{ mode: 'coalesce', windowMs, key, merge }`. Inspect suppressed events via `protocol.droppedCount(type)`. Passthrough events still go through the burst rate-limiter as a last-resort cascade guard.-------## What's half-built (don't assume working)--- [features/hero-pretext.js](features/) — flag-gated, not core-- [editor/](editor/) — GLB export + material editor exist, agent-system integration minimal-- ERC-8004 reputation/validation — hooked but no UI-- Memory `encrypted-ipfs` mode — stub-- `avatar-chat` inline layout — fully wired. Walk clip, thought bubble, stream events all connected. See `prompts/avatar-chat/` for remaining polish items.-- Privy integration — functions exist, no full auth flow in element.js-- Avatar Creator save-to-account — may not persist in all flows-- Avatar Creator now wraps the Ready Player Me iframe. Configure the subdomain via `VITE_RPM_SUBDOMAIN`; falls back to `demo.readyplayer.me`.-------## Adding things--**New action type:** add to `ACTION_TYPES` in [agent-protocol.js](agent-protocol.js), emit at source, subscribe in consumers. Update the event vocabulary table above.--**New built-in tool:** add to `BUILTIN_TOOLS` array + `BUILTIN_HANDLERS` in [runtime/tools.js](runtime/tools.js). Handler signature: `async (args, ctx) => ({ ok: true, ... })`.--**New skill:** bundle under [skills/](skills/). See /CLAUDE.md "Canonical patterns → New agent skill" for the 5-step recipe.--**New URL hash param:** parse in [app.js](app.js) next to existing keys. Don't invent a new routing layer.diff --git a/xspace-agent/CLAUDE.md b/xspace-agent/CLAUDE.mddeleted file mode 100644index e5bbc5abf..000000000--- a/xspace-agent/CLAUDE.md+++ /dev/null@@ -1,243 +0,0 @@-# CLAUDE.md — xspace-agent Monorepo--**Kill every terminal** — always use `isBackground: true`, then kill the terminal after output is captured--## What This Project Is--**xspace-agent** is a TypeScript SDK and CLI that enables AI agents to autonomously join, listen, and speak in X (Twitter) Spaces. It supports multiple LLM providers (OpenAI, Claude, Groq), speech-to-text (Whisper), text-to-speech (ElevenLabs, OpenAI TTS), and multi-agent coordination — all driven by Puppeteer browser automation against the live X Spaces UI.--**Target**: Open-source developer tool. Proprietary (All Rights Reserved). Published to npm as `xspace-agent` (core SDK), `@xspace/server` (admin panel), `@xspace/cli` (CLI).--## Monorepo Layout--```-packages/- core/ → xspace-agent Main SDK. XSpaceAgent class, providers, audio, browser automation, FSM, intelligence layer.- server/ → @xspace/server Express + Socket.IO admin panel with auth, rate limiting, real-time agent control.- cli/ → @xspace/cli CLI tool (xspace-agent init|auth|join|start|dashboard).- widget/ → UI widget components (early stage).- create-xspace-agent/ → Project scaffolding template.--src/ → Legacy server code (Express + Socket.IO). Still functional via `npm run dev`. Being migrated into packages/.-agent-voice-chat/ → Standalone voice chat agent with its own test suite, OpenAPI spec, memory system.-x-spaces/ → Low-level Puppeteer automation scripts (JavaScript, legacy).-public/ → Frontend HTML/CSS/JS for dev server (npm run dev). NOT used in production.- ⚠️ Railway production serves from packages/server/public/ — HTML changes must go there too.-examples/ → 10 runnable example projects (basic-join, multi-agent-debate, discord-bridge, etc.).-docs/ → 43 markdown docs covering architecture, deployment, API reference, and more.-docker/ → Prometheus + Grafana configs for monitoring profile.-```--## Quick Commands--```bash-# Development-npm run dev # Start dev server (tsx watch src/server/index.ts)-npm run build # tsc && vite build-npm run typecheck # tsc --noEmit (server + client tsconfigs)-npm run lint # eslint src/-npm run lint:fix # eslint --fix-npm run format # prettier --write--# Testing-npm run test # Runs: cd packages/core && vitest run-cd packages/core && npx vitest run --coverage # With coverage-cd packages/core && npx vitest run src/__tests__/e2e/ # E2E (needs API keys)--# Docker-npm run docker:build # Build container-npm run docker:up # Start agent container-npm run docker:up:monitoring # Start with Prometheus + Grafana-```--## Architecture Overview--```- ┌──────────────────┐- │ X Space (live) │- └────────┬─────────┘- │ Puppeteer + CDP- ┌────────▼─────────┐- │ BrowserLifecycle │ Auth → Join → Request Speaker → Speak- │ (browser/) │ Selector engine with self-healing CSS/text/aria strategies- └────────┬─────────┘- │ RTCPeerConnection audio hooks- ┌────────▼─────────┐- │ AudioPipeline │ PCM capture → VAD → silence detection → WAV encoding- │ (audio/) │ TTS audio injection back into Space- └────────┬─────────┘- │- ┌──────────────┼──────────────┐- │ │ │- ┌─────▼─────┐ ┌─────▼─────┐ ┌─────▼─────┐- │ STT │ │ LLM │ │ TTS │ Provider factories (pipeline/)- │ Whisper │ │ OpenAI/ │ │ ElevenLabs│ Pluggable via config- │ (Groq/OAI)│ │ Claude/ │ │ OpenAI/ │- └───────────┘ │ Groq/ │ │ Browser │- │ Custom │ └───────────┘- └───────────┘- │- ┌─────▼──────────────────────┐- │ Intelligence Layer │ Speaker ID, topic tracking, sentiment,- │ (intelligence/) │ context management, prompt building, persistence- └────────────────────────────┘- │- ┌─────▼──────────────────────┐- │ Turn Management (turns/) │ Decision engine, interruption handling,- │ + FSM (fsm/) │ adaptive silence detection, response pacing- └────────────────────────────┘-```--### Key Classes--| Class | File | Purpose |-|-------|------|---------|-| `XSpaceAgent` | `packages/core/src/agent.ts` | Main entry point. Orchestrates browser, audio, LLM, and turn management. |-| `AgentTeam` | `packages/core/src/team.ts` | Multi-agent coordination. Multiple AI personalities sharing one browser session. |-| `BrowserLifecycle` | `packages/core/src/browser/lifecycle.ts` | Puppeteer browser launch, login, Space join/leave lifecycle. |-| `AudioPipeline` | `packages/core/src/audio/pipeline.ts` | Audio capture, VAD, silence detection, encoding pipeline. |-| `ConversationManager` | `packages/core/src/conversation.ts` | Message history, token counting, context windowing. |-| `StateMachine` | `packages/core/src/fsm/machine.ts` | Generic FSM engine. Used by agent and team state machines. |-| `SelectorEngine` | `packages/core/src/browser/selector-engine.ts` | Self-healing CSS selectors for X's DOM. Tries multiple strategies (CSS, text, aria). |-| `ProviderRouter` | `packages/core/src/providers/router.ts` | Intelligent LLM routing across multiple providers. |-| `CostTracker` | `packages/core/src/providers/cost-tracker.ts` | Per-provider cost monitoring. |-| `PluginManager` | `packages/core/src/plugins/manager.ts` | Plugin system for extending agent behavior. |-| `TurnCoordinator` | `packages/core/src/turns/coordinator.ts` | Multi-agent turn-taking orchestration. |-| `DecisionEngine` | `packages/core/src/turns/decision-engine.ts` | Should-I-respond decision logic based on conversation signals. |--### Data Flow: Voice Input → AI Response → Voice Output--1. **Capture**: Puppeteer hooks `RTCPeerConnection` in the X Spaces page, captures PCM audio from incoming tracks.-2. **VAD**: `VoiceActivityDetector` detects speech vs silence. After silence threshold (default 1.5s), audio chunk is finalized.-3. **STT**: Audio chunk sent to Whisper (Groq or OpenAI). Returns transcribed text.-4. **Intelligence**: `SpeakerIdentifier` attributes text to a speaker. `TopicTracker` and `detectSentiment` enrich metadata. `ContextManager` windows the conversation history.-5. **Decision**: `DecisionEngine` evaluates whether to respond (directly addressed? is it a question? topic relevance?).-6. **LLM**: `PromptBuilder` constructs the prompt. Provider streams response text.-7. **TTS**: Response text synthesized to MP3 via ElevenLabs/OpenAI/browser.-8. **Injection**: Audio injected back into Space via `injectAudio()` through the browser's WebRTC connection.--### Provider Pattern--All providers implement standardized interfaces (`LLMProvider`, `STTProvider`, `TTSProvider` in `packages/core/src/types.ts`). Each has:-- `streamResponse()` / `transcribe()` / `synthesize()` — core operations-- `checkHealth()` — connectivity and latency check-- `getMetrics()` — request counts, success rates, latency, token usage-- `estimateCost()` — USD cost estimation--Created via factory functions: `createLLM(config)`, `createSTT(config)`, `createTTS(config)` in `packages/core/src/pipeline/`.--### State Machine--Agents use a finite state machine (`packages/core/src/fsm/`):-```-idle → launching → authenticating → joining → listening → speaking → leaving → stopped- ↑ ↓- └────────────────────┘-```--Teams have a separate FSM: `idle → starting → active → stopping → stopped`.--### Middleware Pipeline--Six interception points in the audio processing pipeline:-`before:stt` → `after:stt` → `before:llm` → `after:llm` → `before:tts` → `after:tts`--Middleware handlers receive typed data for their stage and can transform or abort (return null).--## Error Handling--All SDK errors extend `XSpaceError` (in `packages/core/src/errors.ts`) with:-- `code` — machine-readable (e.g., `AUTH_FAILED`, `SPACE_NOT_FOUND`, `PROVIDER_ERROR`)-- `message` — human-readable description-- `hint` — actionable fix suggestion-- `docsUrl` — optional link to relevant docs--Specific error classes: `AuthenticationError`, `SpaceNotFoundError`, `SpaceEndedError`, `BrowserConnectionError`, `SpeakerAccessDeniedError`, `ProviderError`, `ConfigValidationError`, `SelectorBrokenError`.--## TypeScript Configuration--- **Target**: ES2022, **Module**: NodeNext, **Strict**: true-- **Root tsconfig.json**: Server code (src/ excluding src/client)-- **tsconfig.client.json**: Browser/client code-- Two separate `--noEmit` checks in `npm run typecheck`-- Packages use their own tsconfig extending the base--## Testing--- **Framework**: Vitest with `@vitest/coverage-v8`-- **Location**: `packages/core/tests/` and `packages/core/src/__tests__/`-- **CI matrix**: Node 18, 20, 22-- **Coverage targets**: ~80% statements/functions/lines, ~70% branches-- **E2E tests**: Only run on `main` push (require API key secrets)-- **Test timeout**: 10 seconds-- Tests use mock providers, Socket.IO test helpers, and test app factories--## Commit Conventions--- **Style**: Conventional commits — `feat:`, `fix:`, `chore:`, `docs:`, `refactor:`, `test:`-- **PR titles**: Validated by `amannn/action-semantic-pull-request` in CI--## CI Pipeline (.github/workflows/ci.yml)--1. **lint** — ESLint-2. **typecheck** — tsc --noEmit (server + client)-3. **test** — Vitest on Node 18/20/22, coverage upload on Node 20-4. **build** — Depends on lint + typecheck + test passing. Verifies package size and exports.-5. **e2e** — Main branch only, requires API key secrets-6. **security-audit** — `npm audit --audit-level=high`-7. **dependency-review** — On PRs only--## Environment Variables--**Required for X Spaces**:-- `X_AUTH_TOKEN` + `X_CT0` (cookie auth, recommended) OR `X_USERNAME` + `X_PASSWORD`--**Required for AI** (at least one):-- `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `GROQ_API_KEY`--**Optional**:-- `AI_PROVIDER` — `openai` | `openai-chat` | `claude` | `groq` (default: `openai`)-- `STT_PROVIDER` — `groq` | `openai` (default: `groq`)-- `TTS_PROVIDER` — `elevenlabs` | `openai` | `browser` (auto-detected)-- `ELEVENLABS_API_KEY` — Required if TTS_PROVIDER=elevenlabs-- `ADMIN_API_KEY` — Required for admin panel authentication-- `BROWSER_MODE` — `managed` | `connect` (default: `managed`)-- `PORT` — Server port (default: `3000`)-- `HEADLESS` — Run Puppeteer headless (default: `true`)--Full reference: `.env.example` (215 lines with comments).--## Legacy Code--The `src/` directory contains the original monolithic server implementation. It works via `npm run dev` (TypeScript) or `npm run start:legacy` (JavaScript `server.js`). This code is being progressively migrated into the `packages/` monorepo structure. When working on new features, prefer `packages/core/` over `src/`.--The `agent-voice-chat/` directory is a standalone voice chat agent with its own test suite (`vitest`), OpenAPI spec (`openapi.json`), memory system (vector embeddings), and conversation archiving (gzip). It has separate routing, middleware, and error handling patterns.--## Docker--Multi-stage Dockerfile: deps → builder → runtime (node:20-slim + Chromium).-- Health check: `GET /health` every 30s-- Persistent volumes: `/app/cookies`, `/app/data`-- Requires 2GB shared memory for Chromium (`--shm-size=2gb`)-- Compose profiles: default (agent only), `with-redis`, `with-monitoring` (Prometheus + Grafana)--## Key Patterns for Contributing--1. **New LLM provider**: Implement `LLMProvider` interface, add to `createLLM()` factory in `packages/core/src/pipeline/llm.ts`.-2. **New TTS/STT provider**: Same pattern — implement interface, add to factory.-3. **New intelligence feature**: Add to `packages/core/src/intelligence/`, wire into `XSpaceAgent`.-4. **New middleware**: Use `agent.use('stage', handler)` pattern or create a Plugin.-5. **Browser selector breaks**: Update `packages/core/src/browser/selectors.ts`. The `SelectorEngine` tries multiple strategies, so add alternatives rather than replacing.-6. **New API endpoints**: Add to `packages/server/src/` with Zod validation and auth middleware.-7. **New CLI command**: Add to `packages/cli/src/commands/` using Commander.js.--## What Not to Do--- Don't commit `.env` files, API keys, or auth tokens.-- Don't modify `server.js` — it's legacy. Work in `packages/` or `src/` TypeScript.-- Don't add database dependencies — persistence is file-based by design (JSON + gzip).-- Don't break the provider interface contracts — many things depend on `streamResponse()`, `checkHealth()`, `getMetrics()`, `estimateCost()`.-- Don't hardcode X Space CSS selectors — use `SelectorEngine` with multiple fallback strategies.-- Don't skip the FSM — agent lifecycle transitions go through the state machine, not ad-hoc flags.--diff --git a/xspace-agent/agent-voice-chat/CLAUDE.md b/xspace-agent/agent-voice-chat/CLAUDE.mddeleted file mode 100644index 47ed4ba0c..000000000--- a/xspace-agent/agent-voice-chat/CLAUDE.md+++ /dev/null@@ -1,98 +0,0 @@-# CLAUDE.md — agent-voice-chat/--Standalone voice chat agent platform with multi-room support, memory/RAG, knowledge base, and client framework packages. More feature-rich than the legacy `src/` server but operates independently.--## Entry Point--```bash-node server.js # Main entry — Express + Socket.IO + full middleware stack-```--## Architecture--```-server.js Main server (~1000 lines): Express, Socket.IO, circuit breakers, room/agent setup-agent-registry.js Flexible agent definitions (JSON/YAML config, string IDs, swappable personalities)-room-manager.js Multi-room support: per-room state, agents, turn queue, TTL cleanup, max 50 participants--lib/-├── memory-store.js Episodic + semantic memory with embedding vectors, per-user profiles, 1000-item max-├── conversation-store.js Active cache + .json.gz compressed archive, metadata-only mode-├── knowledge-base.js Document chunking (500 chars, 50 overlap) + embedding retrieval (top 3 chunks)-├── context-injector.js Combines memory + knowledge into LLM context at injection points-└── embeddings.js Embedding generation for vector similarity search--providers/-├── index.js Provider factory with fallback chain-├── claude.js Anthropic SDK-├── openai-chat.js OpenAI Chat API-├── openai-realtime.js OpenAI WebRTC-├── groq.js Groq API-├── tts.js TTS: ElevenLabs, OpenAI, Chatterbox, Piper, Browser-└── stt.js STT: Groq Whisper, OpenAI Whisper--src/server/-├── socket-handler.js Socket.IO events (new spec + legacy compat)-├── config.js Zod env validation-├── constants.js Shared constants-├── health.js Health checks-├── metrics.js Metrics tracking-├── errors.js AppError hierarchy: NotFoundError, ConflictError, ValidationError, ProviderError-├── logger.js Pino logger with redaction (auth, cookies, tokens, audio)-├── routes/-│ ├── agents.js CRUD + start/stop agents-│ ├── agent-control.js speak, join, leave commands-│ ├── rooms.js Room CRUD-│ ├── conversations.js Conversation listing + archival-│ ├── personalities.js Personality presets CRUD-│ ├── memory.js Memory search + add + delete-│ ├── knowledge.js Knowledge base search + index + stats-│ └── system.js Config, health, providers-└── middleware/- ├── auth.js Bearer token auth (no-op if API_KEY not set)- ├── rate-limit.js express-rate-limit- ├── sanitize.js Input sanitization- └── security.js Helmet, CORS--packages/ Client framework packages-├── core/ @agent-voice-chat/core — base client library-├── react/ @agent-voice-chat/react — React hooks + components-├── vue/ @agent-voice-chat/vue — Vue composables + components-└── widget/ @agent-voice-chat/widget — standalone embeddable widget--tests/-├── helpers/ Test factories, mock providers, Socket.IO helpers-├── unit/ memory-store, knowledge-base, embeddings, middleware-└── integration/ API agents, conversations, system, socket, provider failures-```--## OpenAPI Spec--Full spec at `openapi.json` (OpenAPI 3.0.3). Key endpoint groups:-- `/api/agents` — Agent lifecycle and control-- `/api/rooms` — Multi-room management-- `/api/conversations` — History and archival-- `/api/memory` — Episodic/semantic memory with vector search-- `/api/knowledge` — Document RAG-- `/api/personalities` — Swappable personality presets-- `/api/health`, `/api/config`, `/api/providers` — System info--## Key Differences from packages/core--- **Multi-room**: RoomManager supports concurrent rooms with TTL cleanup (vs single Space in core)-- **Memory + RAG**: Embedding-based semantic search, user profiles, knowledge base (core has simpler ConversationStore)-- **Circuit breakers**: Per-provider circuit breakers for resilience-- **Client packages**: React, Vue, and widget packages for embedding-- **Agent flexibility**: String IDs, YAML config, swappable personalities (vs typed AgentConfig in core)-- **JavaScript**: This module is plain JavaScript (not TypeScript)--## Testing--```bash-npx vitest run # All tests-npx vitest run --coverage # With coverage (80% thresholds)-```--Uses vitest with custom helpers: `createTestApp()`, `createTestServer()`, `createConnectedClient()`, mock providers.--diff --git a/xspace-agent/packages/cli/CLAUDE.md b/xspace-agent/packages/cli/CLAUDE.mddeleted file mode 100644index f086ae76f..000000000--- a/xspace-agent/packages/cli/CLAUDE.md+++ /dev/null@@ -1,77 +0,0 @@-# CLAUDE.md — packages/cli (@xspace/cli)--CLI tool for xspace-agent. Provides interactive setup, authentication, and Space joining from the terminal.--## Commands--```bash-npm run build # tsc → dist/-npm run dev # tsc --watch-npm run clean # rm -rf dist-npm run test # vitest run (no tests yet)-```--## CLI Usage--```bash-xspace-agent init # Interactive setup wizard → creates xspace.config.json-xspace-agent auth # Save X credentials to .env (token or username/password)-xspace-agent join <url> # Join an X Space directly- --provider <openai|claude|groq> # Override AI provider- --listen-only # Transcription only, no responses- --browser <managed|connect> # Browser mode- --cdp-endpoint <ws://...> # CDP WebSocket URL- --cdp-port <9222> # CDP port for auto-discovery-xspace-agent start # Start server with admin panel-xspace-agent dashboard # Launch dashboard only (no Space connection)--# Global options (all commands):--c, --config <path> # Config file (default: xspace.config.json)--p, --port <number> # Server port (default: 3000)--v, --verbose # Debug logging--q, --quiet # Errors only---headless / --no-headless # Browser visibility (default: headless)-```--## Module Map--```-src/-├── index.ts Commander program definition + global pre-action hooks-├── config.ts Config loading: CLI flags > file > env vars > defaults. Zod validation.-├── logger.ts Colored console logging (debug/info/success/warn/error), verbose/quiet modes-├── paths.ts Monorepo root resolution (walks up from __dirname looking for .git)-├── prompts.ts Inquirer interactive prompts for init and auth-└── commands/- ├── init.ts Setup wizard → writes xspace.config.json (chmod 600)- ├── auth.ts Save X credentials to .env file- ├── join.ts Load config → create provider → join Space → STT/LLM/TTS loop- ├── start.ts Load config → require server.js → start Express- └── dashboard.ts Standalone Express server serving public/ static files-```--## Config Resolution Priority--1. CLI flags (highest)-2. Config file (`xspace.config.json`)-3. Environment variables (`.env`)-4. Defaults (lowest): openai/gpt-4o-mini, autoRespond=true, silenceThreshold=1.5s--## Dependencies--- `commander` — CLI framework-- `inquirer` — Interactive prompts-- `chalk` — Terminal colors-- `ora` — Spinners-- `dotenv` — .env loading-- `express` — Dashboard server-- `zod` — Schema validation (available but not yet used in source)--## Notes--- No tests exist yet. Test infrastructure is configured (vitest + coverage).-- The `join` command loads legacy modules (`x-spaces`, `createProvider`, `tts`) from the monorepo root via `resolveFromRoot()`.-- The `start` command requires `server.js` directly — the legacy monolithic server.-- Config files are written with `0o600` permissions. A warning is logged if config is world-readable.--diff --git a/xspace-agent/packages/core/CLAUDE.md b/xspace-agent/packages/core/CLAUDE.mddeleted file mode 100644index 02223902b..000000000--- a/xspace-agent/packages/core/CLAUDE.md+++ /dev/null@@ -1,130 +0,0 @@-# CLAUDE.md — packages/core (xspace-agent SDK)--This is the main SDK package published as `xspace-agent` on npm. It provides everything needed to build AI voice agents for X Spaces.--## Commands--```bash-npm run build # tsc → dist/-npm run dev # tsc --watch-npm run test # vitest run-npm run test:watch # vitest (watch mode)-npm run test:coverage # vitest run --coverage-npm run clean # rm -rf dist-```--## Module Map--```-src/-├── index.ts Public API barrel export (all SDK exports)-├── agent.ts XSpaceAgent — main class, orchestrates all subsystems-├── team.ts AgentTeam — multi-agent coordination on shared browser session-├── types.ts All public type definitions and interfaces-├── errors.ts XSpaceError hierarchy (8 error classes with codes + hints)-├── config.ts Zod schema validation for AgentConfig-├── conversation.ts ConversationManager — message history with token windowing-├── health.ts HealthMonitor — periodic health checks for all providers-├── logger.ts Logger interface (legacy, prefer observability/ for new code)-│-├── audio/-│ ├── pipeline.ts AudioPipeline — capture → VAD → silence → encode chain-│ ├── bridge.ts Low-level audio: pcmChunksToWav(), mp3ToPcmFloat32(), injectAudio()-│ ├── vad.ts VoiceActivityDetector — energy-based speech detection-│ ├── pcm.ts PCM utilities-│ ├── gain-normalizer.ts Audio gain normalization-│ └── echo-canceller.ts Echo suppression-│-├── browser/-│ ├── lifecycle.ts BrowserLifecycle — launch → login → join → leave → stop-│ ├── launcher.ts BrowserManager — Puppeteer launch with stealth plugin-│ ├── auth.ts X login flow (cookie auth or form login + 2FA)-│ ├── space-ui.ts DOM interaction: click buttons, join space, request speaker-│ ├── selector-engine.ts SelectorEngine — self-healing selectors (CSS → text → aria fallback)-│ ├── selectors.ts SELECTOR_DEFINITIONS — all X Space UI element selectors-│ ├── observer.ts DOMObserver — CDP-based DOM change monitoring-│ └── secure-cookie-store.ts AES-encrypted cookie persistence-│-├── pipeline/-│ ├── llm.ts createLLM() factory — OpenAI, Claude, Groq, Custom-│ ├── stt.ts createSTT() factory — Groq Whisper, OpenAI Whisper-│ ├── tts.ts createTTS() factory — ElevenLabs, OpenAI TTS, Browser-│ ├── cache.ts Response caching for repeated queries-│ └── types.ts Internal provider interface types-│-├── providers/-│ ├── router.ts ProviderRouter — intelligent routing across multiple LLM providers-│ ├── cost-tracker.ts CostTracker — per-provider USD cost monitoring-│ ├── health-monitor.ts ProviderHealthMonitor — periodic health checks + events-│ ├── custom.ts Custom provider adapter-│ └── types.ts RoutableProvider, RoutingStrategy, CostEntry, etc.-│-├── intelligence/-│ ├── sentiment.ts detectSentiment() — rule-based sentiment classification-│ ├── speaker-id.ts SpeakerIdentifier — attribute transcriptions to speakers-│ ├── topic-tracker.ts TopicTracker — extract and track conversation topics-│ ├── context-manager.ts ContextManager — conversation context windowing-│ ├── prompt-builder.ts PromptBuilder — dynamic system prompt construction-│ └── persistence.ts ConversationStore — JSON file-based conversation storage-│-├── turns/-│ ├── coordinator.ts TurnCoordinator — multi-agent turn orchestration-│ ├── decision-engine.ts DecisionEngine — should-I-respond logic-│ ├── interruption.ts InterruptionHandler — handle overlapping speech-│ ├── adaptive-silence.ts AdaptiveSilenceDetector — dynamic silence thresholds-│ └── pacing.ts ResponsePacer — response timing control-│-├── fsm/-│ ├── machine.ts StateMachine<Context, Event> — generic FSM engine-│ ├── agent-machine.ts Agent FSM: idle→launching→authenticating→joining→listening→speaking→leaving→stopped-│ └── team-machine.ts Team FSM: idle→starting→active→stopping→stopped-│-├── plugins/-│ ├── manager.ts PluginManager — lifecycle hooks for agent extensions-│ └── types.ts Plugin, PluginContext, AudioFrame interfaces-│-└── observability/- ├── index.ts Re-exports all observability utilities- ├── logger.ts createLogger() — Pino-based structured logging with redaction- ├── metrics.ts MetricsCollector — counters, histograms, gauges- └── log-transport.ts SocketLogTransport — forward logs over Socket.IO-```--## Key Interfaces--**Provider contracts** (in `types.ts`) — every provider implements:-- Core operation: `streamResponse()` / `transcribe()` / `synthesize()`-- `checkHealth()` → `{ ok, latencyMs, error? }`-- `getMetrics()` → `{ requestCount, successCount, errorCount, avgLatencyMs, ... }`-- `estimateCost(tokens)` → USD number--**Agent lifecycle events** (in `types.ts`):-- `transcription` — speech transcribed from Space-- `response` — agent generated and spoke-- `status` — FSM state changed-- `error` — something went wrong-- `space-ended` — Space ended-- `speaker-joined` / `speaker-left`-- `turn:decision` / `turn:interrupted` / `turn:deferred`-- `audio:*` — low-level audio observability events--## Testing--Tests live in `src/__tests__/` and `tests/`:-- `providers.test.ts` — provider factories and interface compliance-- `observability.test.ts` — logger and metrics-- `selector-engine.test.ts` — selector self-healing strategies-- `intelligence.test.ts` — sentiment, speaker ID, topic tracking-- `e2e/` — end-to-end tests requiring real API keys (CI only)--Coverage config in `vitest.config.ts`: v8 provider, excludes `types.ts` and `browser/`.--## Patterns--1. **Adding a new LLM provider**: Implement `LLMProvider` interface, add case to `createLLM()` in `pipeline/llm.ts`.-2. **Adding a new selector**: Add to `SELECTOR_DEFINITIONS` in `browser/selectors.ts` with multiple strategies (CSS, text, aria).-3. **Adding intelligence**: New file in `intelligence/`, wire into `XSpaceAgent.agent.ts`.-4. **Adding a plugin**: Implement `Plugin` interface from `plugins/types.ts`.-5. **Extending the FSM**: Add states/transitions in `fsm/agent-machine.ts` or `fsm/team-machine.ts`.--diff --git a/xspace-agent/packages/server/CLAUDE.md b/xspace-agent/packages/server/CLAUDE.mddeleted file mode 100644index 6805f844a..000000000--- a/xspace-agent/packages/server/CLAUDE.md+++ /dev/null@@ -1,89 +0,0 @@-# CLAUDE.md — packages/server (@xspace/server)--Admin panel and WebSocket API server for xspace-agent. Provides a web dashboard for real-time agent control, monitoring, and selector management.--## Commands--```bash-npm run build # tsc → dist/-npm run dev # tsc --watch-npm run start # node dist/index.js-npm run clean # rm -rf dist-```--## Architecture--Only 4 source files — intentionally thin. The server is a coordination layer over `xspace-agent` (core SDK).--```-src/-├── index.ts Express + Socket.IO server, routes, socket namespace, graceful shutdown-└── middleware/- ├── auth.ts API key auth (Express + Socket.IO), timing-safe comparison- ├── validation.ts Zod schemas for socket events (SpaceUrlSchema, event schemas)- └── rate-limit.ts In-memory per-IP rate limiter with auto-cleanup-```--## REST Endpoints--**Unauthenticated:**-- `GET /health` — Load balancer health check (uptime, timestamp, agent status)-- `GET /metrics` — Prometheus format-- `GET /metrics/json` — JSON format--**Static (served from `packages/server/public/`):**-- `GET /` → `public/index.html` (hub page)-- `GET /admin` → `public/admin.html`--> ⚠️ **Railway production serves from this `public/` directory, NOT the root `public/`.** Any HTML changes intended for production must be applied here. The root `public/` is only used by the legacy dev server (`npm run dev`).--**Authenticated (requires ADMIN_API_KEY):**-- `GET /config` — AI provider and agent status-- `GET /state` — Current state snapshot (last 50 messages)-- `POST /admin/selectors/:name` — Override CSS selector for browser automation-- `GET /admin/selectors/health` — Validate all selectors against live page-- `GET /admin/selectors/failures` — Selector failure report-- `GET /admin/providers` — Provider status, costs, session duration-- `GET /admin/providers/costs` — Cost tracking (optional `?since` filter)-- `GET /admin/providers/health` — Provider health check results--## Socket.IO Namespace: `/space`--**Client → Server (validated + rate-limited at 30 events/10s):**-- `xspace:start { spaceUrl }` — Create agent and join Space-- `xspace:stop` — Stop agent-- `xspace:join { spaceUrl }` — Join additional Space-- `xspace:leave` — Leave Space-- `xspace:2fa { code }` — Submit 2FA code-- `xspace:status` — Get current status-- `orchestrator:force-speak { botId }` — Force agent to speak--**Server → Client:**-- `xSpacesStatus` — Agent status changes-- `state:change` — FSM transitions-- `textComplete` — Transcription/response messages-- `audio:level`, `audio:webrtc-stats` — Audio telemetry-- `turn:decision` — Turn-taking decisions-- `provider:status`, `provider:cost` — Provider monitoring-- `selectors:health` — Selector validation-- `log` — Structured log forwarding--## Auth--Three accepted methods (any one works):-1. `X-API-Key` header-2. `Authorization: Bearer <key>` header-3. `?apiKey=<key>` query parameter--Socket.IO: `socket.handshake.auth.apiKey` or `x-api-key` header.--Uses `crypto.timingSafeEqual` to prevent timing attacks.--## Key Patterns--- **Single state object**: `agent`, `status`, `messages` (last 100), `spaceUrl`, `startedAt`, `totalCost`-- **Event forwarding**: Agent events → Socket.IO broadcasts to all connected dashboards-- **Graceful shutdown**: SIGTERM/SIGINT → stop rate limiter → destroy agent → close server → 10s force exit-- **Security**: Helmet CSP, CORS, rate limiting, secret redaction in errors--diff --git a/xspace-agent/src/CLAUDE.md b/xspace-agent/src/CLAUDE.mddeleted file mode 100644index f017fc3a4..000000000--- a/xspace-agent/src/CLAUDE.md+++ /dev/null@@ -1,75 +0,0 @@-# CLAUDE.md — src/ (Legacy Server)--This is the **original monolithic implementation** of the X Space Agent system. It runs via `npm run dev` (TypeScript with tsx) or `npm run start:legacy` (compiled server.js).--**Status**: Being migrated into `packages/`. For new features, prefer `packages/core/`. This code still works and powers the CLI `start` command.--## Commands--```bash-npm run dev # tsx watch src/server/index.ts-npm run start:legacy # node server.js-```--## Architecture--```-src/-├── types.ts Core types: Agent, Message, SpaceState, Provider, TypedEmitter-│-├── server/-│ ├── index.ts Express + Socket.IO /space namespace, X Spaces integration toggle-│ ├── routes.ts GET /, /config, /state, /session/:agentId-│ ├── socket-handlers.ts All socket events: agentConnect, audioData, userMessage, xspace:*-│ ├── turn-manager.ts Queue-based turn management (requestTurn/releaseTurn/broadcastState)-│ ├── agent-registry.ts 2 hardcoded agents (Agent Zero and Agent One), prompts, voice IDs-│ └── providers/-│ ├── index.ts createProvider() factory (env-driven: AI_PROVIDER)-│ ├── claude.ts Anthropic SDK streaming, 20-message history per agent-│ ├── openai-chat.ts OpenAI Chat Completions streaming-│ ├── openai-realtime.ts OpenAI Realtime WebRTC session creation-│ ├── groq.ts Groq API streaming-│ ├── tts.ts TTS: ElevenLabs > OpenAI > browser fallback chain-│ └── stt.ts STT: Groq Whisper > OpenAI Whisper fallback-│-├── client/-│ ├── core.ts AgentCommon class — Socket.IO client, Web Audio API, DOM, turn management-│ ├── bootstrap.ts Client init: load /config → detect provider → init webrtc or streaming-│ └── providers/-│ ├── streaming.ts Socket.IO streaming provider (audioData → STT → LLM → TTS)-│ └── webrtc.ts OpenAI Realtime WebRTC provider (direct RTCPeerConnection)-│-├── browser/-│ ├── orchestrator.ts XSpacesEmitter — Puppeteer state machine for X Spaces-│ ├── launcher.ts Browser launch with stealth plugin-│ ├── auth.ts X login flow (cookie or form + 2FA)-│ ├── space-ui.ts DOM interactions: join, request speaker, inject audio-│ └── selectors.ts CSS selectors for X Space UI elements-│-└── audio/- └── bridge.ts RTCPeerConnection audio hooks, PCM capture, WAV encoding, audio injection-```--## Key Differences from packages/core--| Aspect | src/ (legacy) | packages/core/ |-|--------|--------------|----------------|-| Agents | 2 hardcoded (IDs 0, 1) | Configurable via AgentConfig |-| Providers | env-var factory, module-level | Factory functions with typed interfaces |-| History | 20 messages per agent in provider | ConversationManager with token windowing |-| FSM | Ad-hoc status strings | Formal StateMachine with typed states/events |-| Selectors | Simple CSS strings | SelectorEngine with multi-strategy fallback |-| Observability | console.log | Pino structured logging, metrics, Socket transport |-| Testing | None | Vitest with coverage |--## Data Flow--1. Client connects to Socket.IO `/space` namespace-2. `agentConnect` registers the agent (0 or 1)-3. `audioData` event → STT transcription → LLM streaming → TTS synthesis → `ttsAudio` event back-4. OR `userMessage` event → LLM streaming → TTS → `ttsAudio`-5. Turn management ensures one agent speaks at a time--For X Spaces integration: the `XSpacesEmitter` orchestrator manages Puppeteer browser → captures Space audio → feeds into the same STT → LLM → TTS pipeline → injects audio back into Space.--